Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(competitors): compute head-to-head from every answer through the daily rollups (#1152)
Gökhan Geyikf3a50f2b3da4
diff --git a/supabase/migrations/00169_head_to_head_daily.sql b/supabase/migrations/00169_head_to_head_daily.sqlnew file mode 100644index 000000000..3c05b61f9--- /dev/null+++ b/supabase/migrations/00169_head_to_head_daily.sql@@ -0,0 +1,132 @@+-- Head-to-head on the Competitors page, from the daily rollups (#923).+--+-- getHeadToHeadComparison read the brand's raw prompt_results in one+-- request, which PostgREST caps at 1,000 rows, and summed them in the app:+-- a brand past 1,000 answers was compared on its newest 1,000 only, with no+-- sign of it. The largest brand has ~220k answers.+--+-- Every number the page shows is a sum the rollups already keep (00164):+-- * groups, one per (prompt, platform, model, region): runs and the+-- brand's visibility from insights_prompt_daily; the competitor's from+-- its sightings in insights_competitor_prompt_daily. An answer that is+-- not a sighting has the competitor at 0, which is what the page counted+-- for a group's runs without it.+-- * the averages per engine and overall: the brand's over every answer+-- (insights_brand_daily, answers with no prompt included), the+-- competitor's over the answers that list it (insights_competitor_daily+-- has one row per answer listing the competitor). The app folds engines+-- into display providers.+-- All time, as the page always read. The prompts' text comes along, once per+-- prompt, so the app needn't send hundreds of prompt ids back in a query+-- string. On the largest brand: 5,724 groups over 720 prompts, 1.1 s as a+-- member, every answer counted.+--+-- plpgsql with force_custom_plan, security definer with the organization+-- check made explicit, as the other Insights reads (00147): a caller+-- outside the brand's organization gets null.++create or replace function public.head_to_head_daily(+ p_brand_id uuid,+ p_competitor_id text+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ with brand_groups as (+ select d.prompt_id, d.platform, d.model_used, d.region,+ sum(d.answer_count) as runs,+ sum(d.sum_visibility) as brand_total,+ max(d.max_created_at) as latest_at+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ group by d.prompt_id, d.platform, d.model_used, d.region+ ),+ comp_groups as (+ select cd.prompt_id, cd.platform, cd.model_used, cd.region,+ sum(cd.sum_visibility) as comp_total+ from public.insights_competitor_prompt_daily cd+ where cd.brand_id = p_brand_id+ and cd.competitor_id = p_competitor_id+ group by cd.prompt_id, cd.platform, cd.model_used, cd.region+ ),+ brand_engines as (+ select d.platform, d.model_used,+ sum(d.answer_count) as brand_count,+ sum(d.sum_visibility) as brand_total+ from public.insights_brand_daily d+ where d.brand_id = p_brand_id+ group by d.platform, d.model_used+ ),+ comp_engines as (+ select cd.platform, cd.model_used,+ sum(cd.answer_count) as comp_count,+ sum(cd.sum_visibility) as comp_total+ from public.insights_competitor_daily cd+ where cd.brand_id = p_brand_id+ and cd.competitor_id = p_competitor_id+ group by cd.platform, cd.model_used+ )+ select jsonb_build_object(+ 'groups', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'prompt_id', g.prompt_id,+ 'platform', g.platform,+ 'model_used', g.model_used,+ 'region', g.region,+ 'runs', g.runs,+ 'brand_total', coalesce(g.brand_total, 0),+ 'comp_total', coalesce(c.comp_total, 0),+ 'latest_at', g.latest_at))+ from brand_groups g+ left join comp_groups c+ on c.prompt_id = g.prompt_id+ and c.platform is not distinct from g.platform+ and c.model_used is not distinct from g.model_used+ and c.region is not distinct from g.region+ ), '[]'::jsonb),+ -- Each prompt's text once, rather than on each of its groups.+ 'prompts', coalesce((+ select jsonb_agg(jsonb_build_object('id', p.id, 'text', p.text, 'category', p.category))+ from public.prompts p+ where p.id in (select g.prompt_id from brand_groups g)+ ), '[]'::jsonb),+ 'engines', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'platform', e.platform,+ 'model_used', e.model_used,+ 'brand_count', e.brand_count,+ 'brand_total', coalesce(e.brand_total, 0),+ 'comp_count', coalesce(c.comp_count, 0),+ 'comp_total', coalesce(c.comp_total, 0)))+ from brand_engines e+ left join comp_engines c+ on c.platform is not distinct from e.platform+ and c.model_used is not distinct from e.model_used+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke execute on function public.head_to_head_daily(uuid, text) from public, anon;+grant execute on function public.head_to_head_daily(uuid, text) to authenticated, service_role;++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex e74f1c199..0c4bc9776 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -22634,3 +22634,139 @@ revoke all on function public.sync_opportunity_status() from public, anon, authenotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00169_head_to_head_daily.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Head-to-head on the Competitors page, from the daily rollups (#923).+--+-- getHeadToHeadComparison read the brand's raw prompt_results in one+-- request, which PostgREST caps at 1,000 rows, and summed them in the app:+-- a brand past 1,000 answers was compared on its newest 1,000 only, with no+-- sign of it. The largest brand has ~220k answers.+--+-- Every number the page shows is a sum the rollups already keep (00164):+-- * groups, one per (prompt, platform, model, region): runs and the+-- brand's visibility from insights_prompt_daily; the competitor's from+-- its sightings in insights_competitor_prompt_daily. An answer that is+-- not a sighting has the competitor at 0, which is what the page counted+-- for a group's runs without it.+-- * the averages per engine and overall: the brand's over every answer+-- (insights_brand_daily, answers with no prompt included), the+-- competitor's over the answers that list it (insights_competitor_daily+-- has one row per answer listing the competitor). The app folds engines+-- into display providers.+-- All time, as the page always read. The prompts' text comes along, once per+-- prompt, so the app needn't send hundreds of prompt ids back in a query+-- string. On the largest brand: 5,724 groups over 720 prompts, 1.1 s as a+-- member, every answer counted.+--+-- plpgsql with force_custom_plan, security definer with the organization+-- check made explicit, as the other Insights reads (00147): a caller+-- outside the brand's organization gets null.++create or replace function public.head_to_head_daily(+ p_brand_id uuid,+ p_competitor_id text+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ with brand_groups as (+ select d.prompt_id, d.platform, d.model_used, d.region,+ sum(d.answer_count) as runs,+ sum(d.sum_visibility) as brand_total,+ max(d.max_created_at) as latest_at+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ group by d.prompt_id, d.platform, d.model_used, d.region+ ),+ comp_groups as (+ select cd.prompt_id, cd.platform, cd.model_used, cd.region,+ sum(cd.sum_visibility) as comp_total+ from public.insights_competitor_prompt_daily cd+ where cd.brand_id = p_brand_id+ and cd.competitor_id = p_competitor_id+ group by cd.prompt_id, cd.platform, cd.model_used, cd.region+ ),+ brand_engines as (+ select d.platform, d.model_used,+ sum(d.answer_count) as brand_count,+ sum(d.sum_visibility) as brand_total+ from public.insights_brand_daily d+ where d.brand_id = p_brand_id+ group by d.platform, d.model_used+ ),+ comp_engines as (+ select cd.platform, cd.model_used,+ sum(cd.answer_count) as comp_count,+ sum(cd.sum_visibility) as comp_total+ from public.insights_competitor_daily cd+ where cd.brand_id = p_brand_id+ and cd.competitor_id = p_competitor_id+ group by cd.platform, cd.model_used+ )+ select jsonb_build_object(+ 'groups', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'prompt_id', g.prompt_id,+ 'platform', g.platform,+ 'model_used', g.model_used,+ 'region', g.region,+ 'runs', g.runs,+ 'brand_total', coalesce(g.brand_total, 0),+ 'comp_total', coalesce(c.comp_total, 0),+ 'latest_at', g.latest_at))+ from brand_groups g+ left join comp_groups c+ on c.prompt_id = g.prompt_id+ and c.platform is not distinct from g.platform+ and c.model_used is not distinct from g.model_used+ and c.region is not distinct from g.region+ ), '[]'::jsonb),+ -- Each prompt's text once, rather than on each of its groups.+ 'prompts', coalesce((+ select jsonb_agg(jsonb_build_object('id', p.id, 'text', p.text, 'category', p.category))+ from public.prompts p+ where p.id in (select g.prompt_id from brand_groups g)+ ), '[]'::jsonb),+ 'engines', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'platform', e.platform,+ 'model_used', e.model_used,+ 'brand_count', e.brand_count,+ 'brand_total', coalesce(e.brand_total, 0),+ 'comp_count', coalesce(c.comp_count, 0),+ 'comp_total', coalesce(c.comp_total, 0)))+ from brand_engines e+ left join comp_engines c+ on c.platform is not distinct from e.platform+ and c.model_used is not distinct from e.model_used+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke execute on function public.head_to_head_daily(uuid, text) from public, anon;+grant execute on function public.head_to_head_daily(uuid, text) to authenticated, service_role;++notify pgrst, 'reload schema';+diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 3a6432cab..a33ce52fc 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -79,11 +79,11 @@ import {} from '@/lib/insights-breakdown';import { PLATFORM_LABELS } from '@/config/platform-labels';import {- aggregateHeadToHead,competitorScoreIn,emptyHeadToHead,+ headToHeadFromRollups,type HeadToHeadData,- type HeadToHeadResultRow,+ type HeadToHeadRollups,type HeadToHeadRun,} from '@/lib/head-to-head';@@ -3333,38 +3333,18 @@ export async function getHeadToHeadComparison(): Promise<HeadToHeadData> {const supabase = await dbClient();- // #155 — head-to-head comparisons are a Competitors-tab feature, which- // also lives under Insights — same isolation rule applies here.- // Still a single page of raw results (PostgREST caps it at 1,000), so- // large brands are summarised from their newest answers only; #923 moves- // this onto the daily rollups.- const { data: results, error } = await supabase- .from('prompt_results')- .select(- 'prompt_id, platform, model_used, region, visibility_score, competitor_mentions, created_at',- )- .eq('brand_id', brandId)- .neq('platform', 'chatgpt-shopping')- .order('created_at', { ascending: false })- .order('id', { ascending: false });-+ // Every answer, from the daily rollups (00169, #923): a read of the raw+ // answers stopped at PostgREST's 1,000-row page. The rollups leave out+ // chatgpt-shopping (#155), as the Competitors tab always did.+ const { data, error } = await supabase.rpc('head_to_head_daily', {+ p_brand_id: brandId,+ p_competitor_id: competitorId,+ });if (error) throw new Error(error.message);- const rows = (results ?? []) as HeadToHeadResultRow[];- if (rows.length === 0) return emptyHeadToHead();-- const promptIds = [...new Set(rows.map((r) => r.prompt_id).filter((id): id is string => !!id))];- const { data: promptData } =- promptIds.length > 0- ? await supabase.from('prompts').select('id, text, category').in('id', promptIds)- : { data: [] };- const prompts = new Map(- (promptData ?? []).map((p) => [- p.id as string,- { text: p.text as string, category: (p.category as string | null) ?? undefined },- ]),- );+ const rollups = data as unknown as HeadToHeadRollups | null;+ if (!rollups || rollups.groups.length === 0) return emptyHeadToHead();- return aggregateHeadToHead(rows, competitorId, prompts, resolveProvider);+ return headToHeadFromRollups(rollups, resolveProvider);}/**diff --git a/web/src/lib/head-to-head.test.ts b/web/src/lib/head-to-head.test.tsindex dcb9b324a..6635edb2d 100644--- a/web/src/lib/head-to-head.test.ts+++ b/web/src/lib/head-to-head.test.ts@@ -1,28 +1,54 @@import { describe, expect, it } from 'vitest';-import { aggregateHeadToHead, competitorScoreIn, type HeadToHeadResultRow } from './head-to-head';+import {+ competitorScoreIn,+ headToHeadFromRollups,+ type HeadToHeadRollupEngine,+ type HeadToHeadRollupGroup,+ type HeadToHeadRollups,+} from './head-to-head';const COMP = 'comp-1';-const prompts = new Map([- ['p1', { text: 'best crm for startups', category: 'comparison' }],- ['p2', { text: 'how to pick a crm' }],-]);+const prompts: HeadToHeadRollups['prompts'] = [+ { id: 'p1', text: 'best crm for startups', category: 'comparison' },+ { id: 'p2', text: 'how to pick a crm', category: null },+];const provider = (model: string | null, platform: string | null) =>platform === 'chatgpt' ? 'ChatGPT' : (model ?? 'Unknown');-function row(overrides: Partial<HeadToHeadResultRow>): HeadToHeadResultRow {+function group(overrides: Partial<HeadToHeadRollupGroup>): HeadToHeadRollupGroup {return {prompt_id: 'p1',platform: 'chatgpt',model_used: null,region: 'US',- visibility_score: 0,- competitor_mentions: [],- created_at: '2026-10-01T00:00:00Z',+ runs: 1,+ brand_total: 0,+ comp_total: 0,+ latest_at: '2026-10-01T00:00:00+00:00',...overrides,};}+function engine(overrides: Partial<HeadToHeadRollupEngine>): HeadToHeadRollupEngine {+ return {+ platform: 'chatgpt',+ model_used: null,+ brand_count: 1,+ brand_total: 0,+ comp_count: 0,+ comp_total: 0,+ ...overrides,+ };+}++const rollups = (r: Partial<HeadToHeadRollups>): HeadToHeadRollups => ({+ groups: [],+ engines: [],+ prompts,+ ...r,+});+const mention = (score: number, id = COMP) => [{ competitor_id: id, visibility_score: score }];describe('competitorScoreIn', () => {@@ -37,26 +63,25 @@ describe('competitorScoreIn', () => {});});-describe('aggregateHeadToHead', () => {- it('returns one group per prompt, engine, model and region, averaged over its runs', () => {- const data = aggregateHeadToHead(- [- row({ visibility_score: 60, competitor_mentions: mention(20) }),- row({- visibility_score: 40,- competitor_mentions: mention(40),- created_at: '2026-10-02T00:00:00Z',- }),- row({ region: 'GB', visibility_score: 10, competitor_mentions: mention(50) }),- ],- COMP,- prompts,+describe('headToHeadFromRollups', () => {+ it('averages each prompt, engine, model and region group over its runs', () => {+ const data = headToHeadFromRollups(+ rollups({+ groups: [+ group({+ runs: 2,+ brand_total: 100,+ comp_total: 60,+ latest_at: '2026-10-02T00:00:00+00:00',+ }),+ group({ region: 'GB', brand_total: 10, comp_total: 50 }),+ ],+ }),provider,);expect(data.groups).toHaveLength(2);- const us = data.groups.find((g) => g.region === 'US')!;- expect(us).toMatchObject({+ expect(data.groups.find((g) => g.region === 'US')).toMatchObject({promptId: 'p1',promptText: 'best crm for startups',promptCategory: 'comparison',@@ -67,24 +92,30 @@ describe('aggregateHeadToHead', () => {brandScore: 50,competitorScore: 30,diff: 20,- latestAt: '2026-10-02T00:00:00Z',+ latestAt: '2026-10-02T00:00:00+00:00',});});- it('carries no answer text or citations', () => {- const data = aggregateHeadToHead([row({ visibility_score: 10 })], COMP, prompts, provider);- expect(Object.keys(data.groups[0])).not.toContain('response');- expect(Object.keys(data.groups[0])).not.toContain('citations');+ it('lists the most recently run groups first', () => {+ const data = headToHeadFromRollups(+ rollups({+ groups: [+ group({ prompt_id: 'p1', latest_at: '2026-10-01T00:00:00+00:00' }),+ group({ prompt_id: 'p2', latest_at: '2026-10-05T00:00:00+00:00' }),+ ],+ }),+ provider,+ );+ expect(data.groups.map((g) => g.promptId)).toEqual(['p2', 'p1']);});- it('counts a missing competitor as 0 in groups but leaves it out of the overall average', () => {- const data = aggregateHeadToHead(- [- row({ visibility_score: 50, competitor_mentions: mention(30) }),- row({ visibility_score: 50, competitor_mentions: [] }),- ],- COMP,- prompts,+ it('averages the competitor over the answers that list it, the brand over every answer', () => {+ // Two answers: the competitor is listed (30) in one, missing in the other.+ const data = headToHeadFromRollups(+ rollups({+ groups: [group({ runs: 2, brand_total: 100, comp_total: 30 })],+ engines: [engine({ brand_count: 2, brand_total: 100, comp_count: 1, comp_total: 30 })],+ }),provider,);expect(data.groups[0].competitorScore).toBe(15);@@ -92,19 +123,21 @@ describe('aggregateHeadToHead', () => {expect(data.brandAvg).toBe(50);});- it('breaks results down by display provider', () => {- const data = aggregateHeadToHead(- [- row({ platform: 'chatgpt', visibility_score: 80, competitor_mentions: mention(20) }),- row({- platform: null,- model_used: 'Gemini',- visibility_score: 20,- competitor_mentions: mention(60),- }),- ],- COMP,- prompts,+ it('breaks the averages down by display provider', () => {+ const data = headToHeadFromRollups(+ rollups({+ groups: [group({ brand_total: 80, comp_total: 20 })],+ engines: [+ engine({ brand_total: 80, comp_count: 1, comp_total: 20 }),+ engine({+ platform: null,+ model_used: 'Gemini',+ brand_total: 20,+ comp_count: 1,+ comp_total: 60,+ }),+ ],+ }),provider,);expect(data.platformRows).toEqual([@@ -114,25 +147,15 @@ describe('aggregateHeadToHead', () => {});it('ranks gaps and strengths by group average, worst and best first', () => {- const data = aggregateHeadToHead(- [- row({ prompt_id: 'p1', visibility_score: 10, competitor_mentions: mention(60) }),- row({ prompt_id: 'p2', visibility_score: 30, competitor_mentions: mention(40) }),- row({- prompt_id: 'p2',- region: 'GB',- visibility_score: 90,- competitor_mentions: mention(10),- }),- row({- prompt_id: 'p1',- region: 'GB',- visibility_score: 20,- competitor_mentions: mention(20),- }),- ],- COMP,- prompts,+ const data = headToHeadFromRollups(+ rollups({+ groups: [+ group({ prompt_id: 'p1', brand_total: 10, comp_total: 60 }),+ group({ prompt_id: 'p2', brand_total: 30, comp_total: 40 }),+ group({ prompt_id: 'p2', region: 'GB', brand_total: 90, comp_total: 10 }),+ group({ prompt_id: 'p1', region: 'GB', brand_total: 20, comp_total: 20 }),+ ],+ }),provider,);expect(data.gaps.map((g) => [g.promptId, g.diff])).toEqual([@@ -142,14 +165,30 @@ describe('aggregateHeadToHead', () => {expect(data.strengths.map((g) => [g.promptId, g.diff])).toEqual([['p2', 80]]);});- it('counts results without a prompt in the averages but not as a group', () => {- const data = aggregateHeadToHead(- [row({ prompt_id: null, visibility_score: 90 }), row({ visibility_score: 10 })],- COMP,- prompts,+ it('counts answers without a prompt in the averages, which only the engines carry', () => {+ // An answer without a prompt (90) and one with (10): one group, both averaged.+ const data = headToHeadFromRollups(+ rollups({+ groups: [group({ brand_total: 10 })],+ engines: [engine({ brand_count: 2, brand_total: 100 })],+ }),provider,);expect(data.groups).toHaveLength(1);expect(data.brandAvg).toBe(50);});++ it('reads numbers sent as strings, as Postgres numerics arrive', () => {+ const data = headToHeadFromRollups(+ rollups({+ groups: [+ group({ runs: '2' as never, brand_total: '50.5' as never, comp_total: '0' as never }),+ ],+ engines: [engine({ brand_count: '2' as never, brand_total: '101' as never })],+ }),+ provider,+ );+ expect(data.groups[0].brandScore).toBeCloseTo(25.25);+ expect(data.brandAvg).toBe(51);+ });});diff --git a/web/src/lib/head-to-head.ts b/web/src/lib/head-to-head.tsindex 6bd8fa659..0eb59eb45 100644--- a/web/src/lib/head-to-head.ts+++ b/web/src/lib/head-to-head.ts@@ -9,6 +9,10 @@* hundreds of thousands of rows. It now receives one summary per (prompt,* engine, model, region) and loads a group's individual runs only when the* user opens it.+ *+ * The summaries come from the daily rollups (head_to_head_daily, 00169), so+ * every answer counts: a read of the raw answers stopped at PostgREST's+ * 1,000-row page and compared large brands on their newest answers only.*/import type { Sentiment } from '@/types';@@ -57,15 +61,37 @@ export interface HeadToHeadData {strengths: HeadToHeadGroup[];}-/** The `prompt_results` columns the aggregation reads. */-export interface HeadToHeadResultRow {- prompt_id: string | null;+/** One (prompt, engine, model, region) as head_to_head_daily sums it. */+export interface HeadToHeadRollupGroup {+ prompt_id: string;platform: string | null;model_used: string | null;region: string | null;- visibility_score: number | null;- competitor_mentions: unknown;- created_at: string;+ runs: number;+ /** The brand's visibility summed over the group's answers. */+ brand_total: number;+ /** The competitor's, an answer that doesn't list it counting 0. */+ comp_total: number;+ latest_at: string;+}++/** One (platform, model) over every answer, for the averages. */+export interface HeadToHeadRollupEngine {+ platform: string | null;+ model_used: string | null;+ /** Answers, those without a prompt included. */+ brand_count: number;+ brand_total: number;+ /** Answers that list the competitor, and its visibility over them. */+ comp_count: number;+ comp_total: number;+}++/** head_to_head_daily's payload (00169). */+export interface HeadToHeadRollups {+ groups: HeadToHeadRollupGroup[];+ engines: HeadToHeadRollupEngine[];+ prompts: { id: string; text: string | null; category: string | null }[];}interface CompetitorMention {@@ -86,75 +112,62 @@ export function competitorScoreIn(mentions: unknown, competitorId: string): numbreturn hit ? (hit.visibility_score ?? 0) : null;}-export function aggregateHeadToHead(- rows: HeadToHeadResultRow[],- competitorId: string,- prompts: Map<string, { text: string; category?: string }>,+/**+ * The page's summaries from head_to_head_daily (00169). Each group is+ * averaged over its runs, a missing competitor counting 0, as the page always+ * did. The averages per display provider and overall are over every answer+ * for the brand (those without a prompt included) and over the answers that+ * list the competitor for it: an answer from before the competitor was added+ * says nothing about it. Groups come most recently run first, the order the+ * page lists prompts in.+ */+export function headToHeadFromRollups(+ rollups: HeadToHeadRollups,resolveProvider: (modelUsed: string | null, platform: string | null) => string,): HeadToHeadData {- type GroupAcc = Omit<HeadToHeadGroup, 'brandScore' | 'competitorScore' | 'diff'> & {- brandTotal: number;- compTotal: number;- };type Totals = { brandTotal: number; brandCount: number; compTotal: number; compCount: number };const newTotals = (): Totals => ({ brandTotal: 0, brandCount: 0, compTotal: 0, compCount: 0 });- const groups = new Map<string, GroupAcc>();+ const prompts = new Map(rollups.prompts.map((p) => [p.id, p]));const byProvider = new Map<string, Totals>();const overall = newTotals();- for (const row of rows) {- const brandScore = row.visibility_score ?? 0;- const compScore = competitorScoreIn(row.competitor_mentions, competitorId);- const provider = resolveProvider(row.model_used, row.platform);-- // Averages over answers that list the competitor, as before: an answer- // from before the competitor was added says nothing about it.+ for (const engine of rollups.engines) {+ const provider = resolveProvider(engine.model_used, engine.platform);const providerTotals = byProvider.get(provider) ?? newTotals();byProvider.set(provider, providerTotals);for (const totals of [overall, providerTotals]) {- totals.brandTotal += brandScore;- totals.brandCount += 1;- if (compScore !== null) {- totals.compTotal += compScore;- totals.compCount += 1;- }+ totals.brandTotal += Number(engine.brand_total);+ totals.brandCount += Number(engine.brand_count);+ totals.compTotal += Number(engine.comp_total);+ totals.compCount += Number(engine.comp_count);}-- // Results without a prompt still count towards the averages above.- if (!row.prompt_id) continue;- const key = [row.prompt_id, row.platform ?? '', row.model_used ?? '', row.region ?? ''].join(- '\u0000',- );- const group = groups.get(key) ?? {- promptId: row.prompt_id,- promptText: prompts.get(row.prompt_id)?.text ?? '',- promptCategory: prompts.get(row.prompt_id)?.category,- platform: provider,- rawPlatform: row.platform,- modelUsed: row.model_used ?? '',- rawModelUsed: row.model_used,- region: row.region ?? undefined,- runs: 0,- latestAt: row.created_at,- brandTotal: 0,- compTotal: 0,- };- // Group averages count a missing competitor as 0, as the page always did.- group.runs += 1;- group.brandTotal += brandScore;- group.compTotal += compScore ?? 0;- if (row.created_at > group.latestAt) group.latestAt = row.created_at;- groups.set(key, group);}- const groupList: HeadToHeadGroup[] = [...groups.values()].map(- ({ brandTotal, compTotal, ...g }) => {- const brandScore = brandTotal / g.runs;- const competitorScore = compTotal / g.runs;- return { ...g, brandScore, competitorScore, diff: brandScore - competitorScore };- },- );+ const groupList: HeadToHeadGroup[] = rollups.groups+ .filter((g) => Number(g.runs) > 0)+ .map((g) => {+ const runs = Number(g.runs);+ const brandScore = Number(g.brand_total) / runs;+ const competitorScore = Number(g.comp_total) / runs;+ const prompt = prompts.get(g.prompt_id);+ return {+ promptId: g.prompt_id,+ promptText: prompt?.text ?? '',+ promptCategory: prompt?.category ?? undefined,+ platform: resolveProvider(g.model_used, g.platform),+ rawPlatform: g.platform,+ modelUsed: g.model_used ?? '',+ rawModelUsed: g.model_used,+ region: g.region ?? undefined,+ runs,+ brandScore,+ competitorScore,+ diff: brandScore - competitorScore,+ latestAt: g.latest_at,+ };+ })+ .sort((a, b) => (a.latestAt < b.latestAt ? 1 : a.latestAt > b.latestAt ? -1 : 0));const avg = (total: number, count: number) => (count > 0 ? Math.round(total / count) : 0);const platformRows = [...byProvider.entries()]diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex f2bfd0507..575d1ad34 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3170,6 +3170,10 @@ export type Database = {query: string}[]}+ head_to_head_daily: {+ Args: { p_brand_id: string; p_competitor_id: string }+ Returns: Json+ }insights_aggregates: {Args: {p_brand_id: string