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): serve the dashboard from daily rollups instead of rescanning history (#773)

Gökhan Geyik91146ce3e34e
diff --git a/server/src/lib/insights-rollups.js b/server/src/lib/insights-rollups.js
new file mode 100644
index 000000000..5ff2a8065
--- /dev/null
+++ b/server/src/lib/insights-rollups.js
@@ -0,0 +1,89 @@
+/**
+ * Insights daily-rollup maintenance (00066).
+ *
+ * The Insights page reads pre-aggregated daily rows instead of recomputing a
+ * brand's whole history per load; this module is the only thing that writes
+ * them, by calling the `refresh_insights_daily` SQL function. Two callers:
+ *
+ * - tracking-worker, the moment a run's ledger row is stamped — so a day
+ * enters the rollups only once its run completed, never mid-stream
+ * - the daily sweep, which re-refreshes the trailing days for every brand
+ * as a backstop: runs that never stamped (partial, crashed, ghost tasks)
+ * and out-of-run writes (a prompt analyzed the moment it was added, #754)
+ * all get their day picked up the next morning
+ *
+ * Every entry point is best-effort. The rollups are derived state, always
+ * recomputable from prompt_results; a refresh failure costs freshness until
+ * the next sweep, so it must never take a tracking run down with it.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+
+/** How many trailing days the daily sweep recomputes, today included. */
+export const SWEEP_DAYS = 3;
+
+/** UTC calendar day of an ISO timestamp (or of now), as 'YYYY-MM-DD'. */
+export function utcDay(iso = undefined) {
+ return (iso ? new Date(iso) : new Date()).toISOString().slice(0, 10);
+}
+
+/**
+ * Recompute one brand's rollup rows for an inclusive UTC day range.
+ * Resolves to true when the refresh succeeded, false otherwise — callers
+ * branch on it for logging only, never for control flow.
+ */
+export async function refreshInsightsDaily(brandId, dayFrom, dayTo) {
+ const { error } = await supabaseAdmin.rpc('refresh_insights_daily', {
+ p_brand_id: brandId,
+ p_day_from: dayFrom,
+ p_day_to: dayTo,
+ });
+ if (error) {
+ logger.error({ err: error, brandId, dayFrom, dayTo }, '[insights-rollups] refresh failed');
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Refresh the days a completed tracking run touched: from the run's start
+ * day through today (a run crossing UTC midnight lands rows on two days).
+ */
+export async function refreshForCompletedRun(brandId, runStartedAtIso) {
+ return refreshInsightsDaily(brandId, utcDay(runStartedAtIso), utcDay());
+}
+
+/**
+ * Daily backstop: refresh the trailing SWEEP_DAYS for every brand.
+ *
+ * Deliberately every brand rather than "brands with recent results" — a
+ * refresh over days with no rows deletes nothing and inserts nothing, so the
+ * empty case costs one cheap call, and no discovery query can miss anyone.
+ * Sequential on purpose: this shares the instance with live dashboards, and
+ * finishing in half a minute instead of five seconds is the right trade.
+ */
+export async function sweepInsightsRollups({ days = SWEEP_DAYS } = {}) {
+ const { data: brands, error } = await supabaseAdmin.from('brands').select('id');
+ if (error) {
+ logger.error({ err: error }, '[insights-rollups] sweep could not list brands');
+ return { refreshed: 0, failed: 0 };
+ }
+
+ const to = new Date();
+ const from = new Date(to);
+ from.setUTCDate(from.getUTCDate() - (days - 1));
+ const dayFrom = utcDay(from.toISOString());
+ const dayTo = utcDay(to.toISOString());
+
+ let refreshed = 0;
+ let failed = 0;
+ for (const brand of brands ?? []) {
+ const ok = await refreshInsightsDaily(brand.id, dayFrom, dayTo);
+ if (ok) refreshed++;
+ else failed++;
+ }
+
+ logger.info({ refreshed, failed, dayFrom, dayTo }, '[insights-rollups] sweep complete');
+ return { refreshed, failed };
+}
diff --git a/server/src/lib/insights-rollups.test.js b/server/src/lib/insights-rollups.test.js
new file mode 100644
index 000000000..1d8b981df
--- /dev/null
+++ b/server/src/lib/insights-rollups.test.js
@@ -0,0 +1,132 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// The module reaches the supabase admin client at import time, whose config
+// hard-exits when SUPABASE_* env is absent (as in CI).
+const rpc = vi.fn();
+const from = vi.fn();
+vi.mock('../config/supabase.js', () => ({
+ default: { rpc: (...a) => rpc(...a), from: (...a) => from(...a) },
+}));
+
+import {
+ refreshInsightsDaily,
+ refreshForCompletedRun,
+ sweepInsightsRollups,
+ utcDay,
+ SWEEP_DAYS,
+} from './insights-rollups.js';
+
+beforeEach(() => {
+ rpc.mockReset();
+ from.mockReset();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-21T05:30:00Z'));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('utcDay', () => {
+ it('returns the UTC calendar day of an ISO timestamp', () => {
+ expect(utcDay('2026-08-20T23:59:59Z')).toBe('2026-08-20');
+ expect(utcDay('2026-08-21T00:00:01Z')).toBe('2026-08-21');
+ });
+
+ // A timestamp carrying a positive offset belongs to the previous UTC day —
+ // days in the rollup tables are UTC, whatever wrote the string.
+ it('normalizes offsets to UTC', () => {
+ expect(utcDay('2026-08-21T01:30:00+03:00')).toBe('2026-08-20');
+ });
+
+ it('defaults to today (UTC)', () => {
+ expect(utcDay()).toBe('2026-08-21');
+ });
+});
+
+describe('refreshInsightsDaily', () => {
+ it('calls the refresh function with the brand and inclusive day range', async () => {
+ rpc.mockResolvedValue({ error: null });
+ const ok = await refreshInsightsDaily('brand-1', '2026-08-19', '2026-08-21');
+ expect(ok).toBe(true);
+ expect(rpc).toHaveBeenCalledWith('refresh_insights_daily', {
+ p_brand_id: 'brand-1',
+ p_day_from: '2026-08-19',
+ p_day_to: '2026-08-21',
+ });
+ });
+
+ // The rollups are derived state: a failed refresh costs freshness until the
+ // next sweep, and must never throw into a tracking run's finalize path.
+ it('reports failure without throwing', async () => {
+ rpc.mockResolvedValue({ error: { message: 'boom' } });
+ await expect(refreshInsightsDaily('brand-1', '2026-08-21', '2026-08-21')).resolves.toBe(false);
+ });
+});
+
+describe('refreshForCompletedRun', () => {
+ it('spans from the run start day through today', async () => {
+ rpc.mockResolvedValue({ error: null });
+ await refreshForCompletedRun('brand-1', '2026-08-21T03:10:00Z');
+ expect(rpc).toHaveBeenCalledWith('refresh_insights_daily', {
+ p_brand_id: 'brand-1',
+ p_day_from: '2026-08-21',
+ p_day_to: '2026-08-21',
+ });
+ });
+
+ // A run that started before UTC midnight lands rows on two calendar days;
+ // refreshing only "today" would leave yesterday's tail stale until the
+ // sweep.
+ it('covers both days of a run that crossed midnight', async () => {
+ rpc.mockResolvedValue({ error: null });
+ await refreshForCompletedRun('brand-1', '2026-08-20T23:45:00Z');
+ expect(rpc).toHaveBeenCalledWith('refresh_insights_daily', {
+ p_brand_id: 'brand-1',
+ p_day_from: '2026-08-20',
+ p_day_to: '2026-08-21',
+ });
+ });
+});
+
+describe('sweepInsightsRollups', () => {
+ function brandsList(rows, error = null) {
+ from.mockReturnValue({ select: () => Promise.resolve({ data: rows, error }) });
+ }
+
+ it('refreshes the trailing window for every brand, today included', async () => {
+ brandsList([{ id: 'a' }, { id: 'b' }]);
+ rpc.mockResolvedValue({ error: null });
+
+ const res = await sweepInsightsRollups();
+
+ expect(res).toEqual({ refreshed: 2, failed: 0 });
+ expect(rpc).toHaveBeenCalledTimes(2);
+ // SWEEP_DAYS trailing days ending today: 3 days → today-2 .. today.
+ expect(rpc).toHaveBeenCalledWith('refresh_insights_daily', {
+ p_brand_id: 'a',
+ p_day_from: '2026-08-19',
+ p_day_to: '2026-08-21',
+ });
+ expect(SWEEP_DAYS).toBe(3);
+ });
+
+ // One brand's failure must not stop the sweep — the whole point of the
+ // backstop is that no brand silently stays stale.
+ it('keeps sweeping past a failing brand and counts it', async () => {
+ brandsList([{ id: 'a' }, { id: 'b' }, { id: 'c' }]);
+ rpc.mockResolvedValueOnce({ error: { message: 'boom' } }).mockResolvedValue({ error: null });
+
+ const res = await sweepInsightsRollups();
+
+ expect(res).toEqual({ refreshed: 2, failed: 1 });
+ expect(rpc).toHaveBeenCalledTimes(3);
+ });
+
+ it('gives up quietly when the brand list cannot be read', async () => {
+ brandsList(null, { message: 'boom' });
+ const res = await sweepInsightsRollups();
+ expect(res).toEqual({ refreshed: 0, failed: 0 });
+ expect(rpc).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/scripts/backfill-insights-daily.js b/server/src/scripts/backfill-insights-daily.js
new file mode 100644
index 000000000..aee9ba355
--- /dev/null
+++ b/server/src/scripts/backfill-insights-daily.js
@@ -0,0 +1,96 @@
+/**
+ * Backfill the Insights daily rollups (00066) from historical prompt_results.
+ *
+ * Run: `node src/scripts/backfill-insights-daily.js`
+ *
+ * Options via env:
+ * - INSIGHTS_BACKFILL_CHUNK_DAYS days recomputed per refresh call
+ * (default 31)
+ * - INSIGHTS_BACKFILL_PAUSE milliseconds between refresh calls
+ * (default 250)
+ * - INSIGHTS_BACKFILL_BRAND limit the run to one brand id
+ *
+ * Covers every brand with results — including cancelled orgs, deliberately:
+ * the read path switches for everyone at once, and a reactivated account
+ * whose history was skipped would open an empty dashboard.
+ *
+ * Idempotent and restartable. `refresh_insights_daily` is delete + insert
+ * per day range, so an interrupted run can simply be started again; at worst
+ * it redoes chunks it already wrote. Chunked by calendar month so no single
+ * call parses more than ~31 days of competitor jsonb, with a pause between
+ * calls because this shares the instance with live dashboards.
+ */
+
+import 'dotenv/config';
+import supabaseAdmin from '../config/supabase.js';
+import { refreshInsightsDaily, utcDay } from '../lib/insights-rollups.js';
+
+const CHUNK_DAYS = Number.parseInt(process.env.INSIGHTS_BACKFILL_CHUNK_DAYS ?? '31', 10);
+const PAUSE_MS = Number.parseInt(process.env.INSIGHTS_BACKFILL_PAUSE ?? '250', 10);
+const ONLY_BRAND = process.env.INSIGHTS_BACKFILL_BRAND ?? null;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** UTC day of a brand's first/last result, or null when it has none. */
+async function resultDayBound(brandId, ascending) {
+ const { data, error } = await supabaseAdmin
+ .from('prompt_results')
+ .select('created_at')
+ .eq('brand_id', brandId)
+ .order('created_at', { ascending })
+ .limit(1);
+ if (error) throw new Error(error.message);
+ return data?.[0]?.created_at ? utcDay(data[0].created_at) : null;
+}
+
+function addDays(day, n) {
+ const d = new Date(`${day}T00:00:00Z`);
+ d.setUTCDate(d.getUTCDate() + n);
+ return utcDay(d.toISOString());
+}
+
+async function backfillBrand(brandId) {
+ const firstDay = await resultDayBound(brandId, true);
+ if (!firstDay) return { chunks: 0, skipped: true };
+ const lastDay = await resultDayBound(brandId, false);
+
+ let chunks = 0;
+ for (let from = firstDay; from <= lastDay; from = addDays(from, CHUNK_DAYS)) {
+ const to = addDays(from, CHUNK_DAYS - 1) < lastDay ? addDays(from, CHUNK_DAYS - 1) : lastDay;
+ const ok = await refreshInsightsDaily(brandId, from, to);
+ if (!ok) throw new Error(`refresh failed for ${brandId} ${from}..${to}`);
+ chunks++;
+ await sleep(PAUSE_MS);
+ }
+ return { chunks, skipped: false, firstDay, lastDay };
+}
+
+async function main() {
+ const query = supabaseAdmin.from('brands').select('id, name');
+ const { data: brands, error } = ONLY_BRAND ? await query.eq('id', ONLY_BRAND) : await query;
+ if (error) throw new Error(error.message);
+
+ let done = 0;
+ let failed = 0;
+ for (const brand of brands ?? []) {
+ try {
+ const res = await backfillBrand(brand.id);
+ done++;
+ console.log(
+ res.skipped
+ ? `[${done}/${brands.length}] ${brand.id} — no results, skipped`
+ : `[${done}/${brands.length}] ${brand.id} — ${res.firstDay}..${res.lastDay} in ${res.chunks} chunk(s)`,
+ );
+ } catch (err) {
+ failed++;
+ console.error(`FAILED ${brand.id}: ${err.message}`);
+ }
+ }
+ console.log(`Backfill complete: ${done} brand(s), ${failed} failure(s).`);
+ if (failed > 0) process.exitCode = 1;
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/server/src/server.js b/server/src/server.js
index 1ab0cfb78..2db238dee 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -20,6 +20,7 @@ import {
cleanupStalePendingTasks,
} from './lib/job-manager.js';
import { runTrackingJob } from './lib/job-runner.js';
+import { sweepInsightsRollups } from './lib/insights-rollups.js';
import { parseScraperResponse } from './lib/cloro-scraper.js';
import { handleScraperResult } from './lib/cloro-result-handler.js';
import { verifyCloroWebhook } from './lib/cloro-webhook-verify.js';
@@ -122,6 +123,15 @@ async function runDailyTracking() {
logger.error({ err }, '[pulse] catch-up sweep crashed');
});
+ // Insights rollup backstop (00066). Re-refreshes the trailing days for
+ // every brand, so days whose run never stamped (partial, crashed) and
+ // out-of-run writes (a prompt analyzed right after being added) appear the
+ // next morning. Fire-and-forget: idempotent against the per-run refresh
+ // that today's runs will do when they stamp, and never blocks tracking.
+ sweepInsightsRollups().catch((err) => {
+ logger.error({ err }, '[insights-rollups] daily sweep crashed');
+ });
+
// Skip paused brands (is_active = false): the user has explicitly suspended
// tracking for them, so they should not spend Cloro / LLM credits daily.
const { data: brands, error } = await supabaseAdmin
diff --git a/server/src/workers/tracking-worker.js b/server/src/workers/tracking-worker.js
index 7cee89735..69653f464 100644
--- a/server/src/workers/tracking-worker.js
+++ b/server/src/workers/tracking-worker.js
@@ -12,6 +12,7 @@ import { applyPlanOverrides } from '../lib/plan-guard.js';
import { generateContentOpportunities } from '../lib/opportunity-generator.js';
import { updateTargetUrlStats } from '../lib/target-url-stats.js';
import { persistCitationRows } from '../lib/citation-rows.js';
+import { refreshForCompletedRun } from '../lib/insights-rollups.js';
import logger from '../lib/logger.js';
function resolveModelPlatform(model) {
@@ -872,6 +873,13 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,
} else {
runStamped = true;
logger.info({ brandId, trackingRunId, runResultCount }, 'tracking run stamped');
+
+ // Fold the run's days into the Insights rollups (00066). Anchored to
+ // the stamp on purpose: a day enters the wide-window aggregates only
+ // once its run completed, so mid-run partial counts never show. Runs
+ // that never reach this point are picked up by the daily sweep.
+ // Best-effort inside — a refresh failure never unstamps the run.
+ await refreshForCompletedRun(brandId, trackingRunStartedAt);
}
} else if ((runResultCount ?? 0) > 0) {
logger.warn(
diff --git a/supabase/migrations/00066_insights_daily_rollups.sql b/supabase/migrations/00066_insights_daily_rollups.sql
new file mode 100644
index 000000000..b8af3a2ad
--- /dev/null
+++ b/supabase/migrations/00066_insights_daily_rollups.sql
@@ -0,0 +1,863 @@
+-- Insights stops recomputing history on every page load.
+--
+-- The Insights aggregate RPCs scan every prompt_results row a brand has ever
+-- produced and explode competitor_mentions jsonb on the fly — 566,908 array
+-- elements for the largest brand. Under the authenticated role's 8s
+-- statement_timeout, competitor_aggregates takes 9.7s on that brand's
+-- all-time window, so 30d/90d/all render as an opaque server error. The cost
+-- grows with accumulated history: rewriting the query buys weeks, not a fix.
+--
+-- These tables invert the work. Each brand-day is aggregated ONCE — when the
+-- brand's tracking run completes (the same drain point Daily Pulse waits on),
+-- with a daily catch-up sweep as backstop — and the page reads the daily
+-- rows. Read cost then scales with days in the window, never with results.
+--
+-- Grain: (day, model_used, platform, region), because those are exactly the
+-- page's filter dimensions. Two extra tables carry the prompt dimension: the
+-- leaderboard's rate is COUNT(DISTINCT prompt_id) over the window, which
+-- cannot be summed across days. insights_prompt_daily mirrors one row per
+-- answered (prompt, engine, day); insights_competitor_prompt_daily keeps only
+-- VISIBLE competitor sightings — 9.4% of elements on the largest brand
+-- (53,331 of 566,908) — so the distinct-count input stays small.
+--
+-- Two deliberate semantic carriers, verified against the live definitions:
+-- * share_of_voice_aggregates counts competitor mentions WITHOUT a join to
+-- competitors (deleted competitors included); competitor_aggregates and
+-- ai_visibility_aggregates filter to live competitors. The rollups store
+-- every competitor_id seen in the jsonb, and the liveness join is applied
+-- by the read functions that had it — parity for both, and a competitor
+-- deleted tomorrow disappears from reads without touching stored rows.
+-- * Topic- and prompt-filtered calls stay on the raw RPCs: topic is a live
+-- prompt attribute (reassignment must move history with it), and both
+-- filters cut the scanned set far below the danger line.
+--
+-- The old RPCs are left untouched — MCP, reports and pulse call them under
+-- the service role, which has no statement timeout. Only day-window reads
+-- move here.
+
+-- ─── Tables ─────────────────────────────────────────────────────────────────
+
+-- Brand-side additive measures. One row per (day, engine, region).
+create table if not exists public.insights_brand_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ model_used text,
+ platform text,
+ region text,
+ answer_count integer not null,
+ mention_answers integer not null,
+ citation_answers integer not null,
+ -- mention OR citation — not derivable from the two columns above.
+ mentioning_answers integer not null,
+ sum_visibility numeric not null,
+ -- SUM(visibility_score) over mentioning answers only (visible_prompt_stats).
+ sum_visibility_visible numeric not null,
+ total_mentions bigint not null,
+ total_citations bigint not null,
+ positive_count integer not null,
+ -- AVG(1.0/mention_position) folds as sum/count across any window.
+ sum_inv_position numeric,
+ position_count integer not null,
+ max_created_at timestamptz not null
+);
+
+create index if not exists idx_insights_brand_daily_brand_day
+ on public.insights_brand_daily (brand_id, day);
+
+-- Per-competitor additive measures. Dense: every competitor_id present in an
+-- answer's jsonb gets a row, zeros included, because the comparison table
+-- shows a row (and an answer count) even for a competitor never mentioned.
+create table if not exists public.insights_competitor_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ -- Text, not uuid: it mirrors the jsonb payload verbatim, and the read
+ -- functions echo it back as the old RPCs did.
+ competitor_id text not null,
+ model_used text,
+ platform text,
+ region text,
+ answer_count integer not null,
+ sum_visibility numeric,
+ total_mentions bigint not null,
+ total_citations bigint not null,
+ mention_answers integer not null,
+ citation_answers integer not null,
+ sum_inv_position numeric,
+ position_count integer not null
+);
+
+create index if not exists idx_insights_competitor_daily_brand_day
+ on public.insights_competitor_daily (brand_id, day);
+
+-- One row per answered (prompt, engine, region, day) — the input for every
+-- COUNT(DISTINCT prompt_id) the page shows. The widest of the four tables,
+-- but each row is a few booleans; the largest brand adds ~1,800/day.
+create table if not exists public.insights_prompt_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ prompt_id uuid not null,
+ model_used text,
+ platform text,
+ region text,
+ answer_count integer not null,
+ has_mention boolean not null,
+ has_citation boolean not null
+);
+
+create index if not exists idx_insights_prompt_daily_brand_day
+ on public.insights_prompt_daily (brand_id, day);
+
+-- Visible competitor sightings only: (competitor, prompt, engine, day) rows
+-- where the competitor was actually mentioned, cited or scored. Existence is
+-- the datum — the per-competitor visible-prompt distinct counts read this.
+create table if not exists public.insights_competitor_prompt_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ competitor_id text not null,
+ prompt_id uuid not null,
+ model_used text,
+ platform text,
+ region text
+);
+
+create index if not exists idx_insights_competitor_prompt_daily_brand_day
+ on public.insights_competitor_prompt_daily (brand_id, day);
+
+-- ─── RLS — same shape as prompt_results ─────────────────────────────────────
+
+alter table public.insights_brand_daily enable row level security;
+alter table public.insights_competitor_daily enable row level security;
+alter table public.insights_prompt_daily enable row level security;
+alter table public.insights_competitor_prompt_daily enable row level security;
+
+create policy "Users can read own org insights rollups"
+ on public.insights_brand_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org competitor rollups"
+ on public.insights_competitor_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org prompt rollups"
+ on public.insights_prompt_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org competitor prompt rollups"
+ on public.insights_competitor_prompt_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+-- ─── Refresh ────────────────────────────────────────────────────────────────
+
+-- Recomputes a brand's rollup rows for a day range from prompt_results.
+-- Delete + insert in one transaction: idempotent by construction (no upsert
+-- arbiter needed, so NULL dimension values need no synthetic encoding), and
+-- readers never see a half-refreshed day. Day-scoped, so the jsonb explode
+-- that makes the read path unaffordable stays cheap here: one day of the
+-- largest brand is ~1,800 answers.
+--
+-- Service-role only. The web tier must never trigger writes; execute is
+-- revoked from anon/authenticated below.
+create or replace function public.refresh_insights_daily(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+begin
+ delete from public.insights_brand_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.insights_competitor_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.insights_prompt_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.insights_competitor_prompt_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+
+ insert into public.insights_brand_daily (
+ brand_id, day, model_used, platform, region,
+ answer_count, mention_answers, citation_answers, mentioning_answers,
+ sum_visibility, sum_visibility_visible, total_mentions, total_citations,
+ positive_count, sum_inv_position, position_count, max_created_at)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.model_used, pr.platform, pr.region,
+ count(*),
+ count(*) filter (where pr.mention_count > 0),
+ count(*) filter (where pr.citation_count > 0),
+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),
+ coalesce(sum(pr.visibility_score), 0),
+ coalesce(sum(pr.visibility_score)
+ filter (where pr.mention_count > 0 or pr.citation_count > 0), 0),
+ coalesce(sum(pr.mention_count), 0),
+ coalesce(sum(pr.citation_count), 0),
+ count(*) filter (where pr.sentiment = 'positive'),
+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),
+ count(*) filter (where pr.mention_position is not null),
+ max(pr.created_at)
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ group by 2, pr.model_used, pr.platform, pr.region;
+
+ insert into public.insights_prompt_daily (
+ brand_id, day, prompt_id, model_used, platform, region,
+ answer_count, has_mention, has_citation)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id, pr.model_used, pr.platform, pr.region,
+ count(*),
+ bool_or(pr.mention_count > 0),
+ bool_or(pr.citation_count > 0)
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ group by 2, pr.prompt_id, pr.model_used, pr.platform, pr.region;
+
+ insert into public.insights_competitor_daily (
+ brand_id, day, competitor_id, model_used, platform, region,
+ answer_count, sum_visibility, total_mentions, total_citations,
+ mention_answers, citation_answers, sum_inv_position, position_count)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ cm.value->>'competitor_id',
+ pr.model_used, pr.platform, pr.region,
+ count(*),
+ sum((cm.value->>'visibility_score')::numeric),
+ coalesce(sum(coalesce((cm.value->>'mention_count')::int, 0)), 0),
+ coalesce(sum(coalesce((cm.value->>'citation_count')::int, 0)), 0),
+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),
+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),
+ sum(1.0 / (cm.value->>'mention_position')::numeric)
+ filter (where (cm.value->>'mention_position') is not null),
+ count(*) filter (where (cm.value->>'mention_position') is not null)
+ from public.prompt_results pr,
+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ and cm.value ? 'competitor_id'
+ group by 2, cm.value->>'competitor_id', pr.model_used, pr.platform, pr.region;
+
+ insert into public.insights_competitor_prompt_daily (
+ brand_id, day, competitor_id, prompt_id, model_used, platform, region)
+ select distinct
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ cm.value->>'competitor_id',
+ pr.prompt_id, pr.model_used, pr.platform, pr.region
+ from public.prompt_results pr,
+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ and cm.value ? 'competitor_id'
+ and (coalesce((cm.value->>'mention_count')::int, 0) > 0
+ or coalesce((cm.value->>'citation_count')::int, 0) > 0
+ or coalesce((cm.value->>'visibility_score')::numeric, 0) > 0);
+end;
+$$;
+
+revoke execute on function public.refresh_insights_daily(uuid, date, date)
+ from public, anon, authenticated;
+
+-- ─── Read functions ─────────────────────────────────────────────────────────
+--
+-- Each mirrors its raw counterpart's payload byte for byte — same keys, same
+-- ordering clauses — so the web mapping code cannot tell which one answered,
+-- and the cutover can be shadow-verified by diffing the two outputs. All are
+-- SECURITY INVOKER: the caller's RLS on the rollup tables scopes the read,
+-- exactly as the raw RPCs lean on prompt_results RLS.
+--
+-- Windows are whole days (p_day_from .. p_day_to inclusive, UTC), which is
+-- what makes the rollup readable at all. The one caller-visible consequence —
+-- a preset window covers calendar days instead of sliding with the clock —
+-- is deliberate: numbers move once per completed run instead of drifting
+-- within the day.
+
+-- insights_aggregates over rollups.
+create or replace function public.insights_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with filtered as (
+ select * from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ totals as (
+ select
+ coalesce(sum(answer_count), 0) as total_results,
+ coalesce(sum(sum_visibility), 0) as sum_visibility,
+ coalesce(sum(total_mentions), 0) as total_mentions,
+ coalesce(sum(total_citations), 0) as total_citations,
+ coalesce(sum(positive_count), 0) as positive_count,
+ coalesce(sum(mentioning_answers), 0) as mentioning_results,
+ max(max_created_at) as last_checked_at
+ from filtered
+ ),
+ by_model as (
+ select
+ coalesce(model_used, 'unknown') as model_used,
+ sum(sum_visibility) as sum_visibility,
+ sum(answer_count) as result_count
+ from filtered
+ group by coalesce(model_used, 'unknown')
+ )
+ select jsonb_build_object(
+ 'total_results', t.total_results,
+ 'sum_visibility', t.sum_visibility,
+ 'total_mentions', t.total_mentions,
+ 'total_citations', t.total_citations,
+ 'positive_count', t.positive_count,
+ 'mentioning_results', t.mentioning_results,
+ 'last_checked_at', t.last_checked_at,
+ 'by_model', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bm.model_used,
+ 'sum_visibility', bm.sum_visibility,
+ 'result_count', bm.result_count)
+ order by bm.result_count desc, bm.model_used)
+ from by_model bm),
+ '[]'::jsonb)
+ )
+ from totals t;
+$$;
+
+-- visible_prompt_stats over rollups.
+create or replace function public.visible_prompt_stats_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ select jsonb_build_object(
+ 'visible_prompts',
+ (select count(distinct pd.prompt_id)
+ from public.insights_prompt_daily pd
+ where pd.brand_id = p_brand_id
+ and (pd.has_mention or pd.has_citation)
+ and (p_platform is null or pd.platform = p_platform)
+ and (p_models is null or pd.model_used = any (p_models))
+ and (p_region is null or pd.region = p_region)
+ and (p_day_from is null or pd.day >= p_day_from)
+ and (p_day_to is null or pd.day <= p_day_to)),
+ 'visible_results',
+ coalesce((select sum(bd.mentioning_answers)
+ from public.insights_brand_daily bd
+ where bd.brand_id = p_brand_id
+ and (p_platform is null or bd.platform = p_platform)
+ and (p_models is null or bd.model_used = any (p_models))
+ and (p_region is null or bd.region = p_region)
+ and (p_day_from is null or bd.day >= p_day_from)
+ and (p_day_to is null or bd.day <= p_day_to)), 0),
+ 'sum_visibility_visible',
+ coalesce((select sum(bd.sum_visibility_visible)
+ from public.insights_brand_daily bd
+ where bd.brand_id = p_brand_id
+ and (p_platform is null or bd.platform = p_platform)
+ and (p_models is null or bd.model_used = any (p_models))
+ and (p_region is null or bd.region = p_region)
+ and (p_day_from is null or bd.day >= p_day_from)
+ and (p_day_to is null or bd.day <= p_day_to)), 0)
+ );
+$$;
+
+-- tracked_prompt_count over rollups.
+create or replace function public.tracked_prompt_count_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns integer
+language sql
+stable
+set search_path to 'public'
+as $$
+ select count(distinct pd.prompt_id)::integer
+ from public.insights_prompt_daily pd
+ where pd.brand_id = p_brand_id
+ and (p_platform is null or pd.platform = p_platform)
+ and (p_models is null or pd.model_used = any (p_models))
+ and (p_region is null or pd.region = p_region)
+ and (p_day_from is null or pd.day >= p_day_from)
+ and (p_day_to is null or pd.day <= p_day_to)
+$$;
+
+-- ai_visibility_aggregates over rollups. Liveness join preserved: only
+-- competitors that still exist appear, exactly like the raw RPC's EXISTS.
+-- Names come from competitors.name (live) rather than the jsonb snapshot the
+-- raw RPC MAX()es over — a renamed competitor shows its current name.
+create or replace function public.ai_visibility_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_agg as (
+ select
+ coalesce(sum(answer_count), 0) as answers,
+ coalesce(sum(mention_answers), 0) as mention_answers,
+ coalesce(sum(citation_answers), 0) as citation_answers,
+ sum(sum_inv_position) / nullif(sum(position_count), 0) as position_factor
+ from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ comp_agg as (
+ select
+ cd.competitor_id,
+ max(c.name) as name,
+ sum(cd.mention_answers) as mention_answers,
+ sum(cd.citation_answers) as citation_answers,
+ sum(cd.sum_inv_position) / nullif(sum(cd.position_count), 0) as position_factor
+ from public.insights_competitor_daily cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ where cd.brand_id = p_brand_id
+ and (p_platform is null or cd.platform = p_platform)
+ and (p_models is null or cd.model_used = any (p_models))
+ and (p_region is null or cd.region = p_region)
+ and (p_day_from is null or cd.day >= p_day_from)
+ and (p_day_to is null or cd.day <= p_day_to)
+ group by cd.competitor_id
+ )
+ select jsonb_build_object(
+ 'answers', b.answers,
+ 'mention_answers', b.mention_answers,
+ 'citation_answers', b.citation_answers,
+ 'position_factor', b.position_factor,
+ 'by_competitor', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'competitor_id', ca.competitor_id,
+ 'name', ca.name,
+ 'mention_answers', ca.mention_answers,
+ 'citation_answers', ca.citation_answers,
+ 'position_factor', ca.position_factor)
+ order by ca.mention_answers desc, ca.competitor_id)
+ from comp_agg ca),
+ '[]'::jsonb)
+ )
+ from brand_agg b;
+$$;
+
+-- competitor_aggregates over rollups. The distinct-prompt counts read the two
+-- prompt-grain tables; everything additive reads the day-grain ones. Engine
+-- keys join with IS NOT DISTINCT FROM because model_used can be null.
+create or replace function public.competitor_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_days as (
+ select * from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ prompt_days as (
+ select * from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ comp_days as (
+ select cd.* from public.insights_competitor_daily cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ where cd.brand_id = p_brand_id
+ and (p_platform is null or cd.platform = p_platform)
+ and (p_models is null or cd.model_used = any (p_models))
+ and (p_region is null or cd.region = p_region)
+ and (p_day_from is null or cd.day >= p_day_from)
+ and (p_day_to is null or cd.day <= p_day_to)
+ ),
+ comp_prompt_days as (
+ select cpd.* from public.insights_competitor_prompt_daily cpd
+ 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_platform is null or cpd.platform = p_platform)
+ and (p_models is null or cpd.model_used = any (p_models))
+ and (p_region is null or cpd.region = p_region)
+ and (p_day_from is null or cpd.day >= p_day_from)
+ and (p_day_to is null or cpd.day <= p_day_to)
+ ),
+ brand_totals as (
+ select
+ coalesce((select sum(answer_count) from brand_days), 0) as row_count,
+ coalesce((select sum(sum_visibility) from brand_days), 0) as sum_visibility,
+ coalesce((select sum(total_mentions) from brand_days), 0) as total_mentions,
+ coalesce((select sum(total_citations) from brand_days), 0) as total_citations,
+ (select count(distinct prompt_id) from prompt_days) as prompt_count,
+ (select count(distinct prompt_id) from prompt_days
+ where has_mention or has_citation) as visible_prompts
+ ),
+ by_brand_provider as (
+ select b.model_used, b.platform, b.sum_visibility, b.row_count,
+ p.prompt_count, p.visible_prompts
+ from (
+ select model_used, platform,
+ sum(sum_visibility) as sum_visibility,
+ sum(answer_count) as row_count
+ from brand_days group by model_used, platform
+ ) b
+ join (
+ select model_used, platform,
+ count(distinct prompt_id) as prompt_count,
+ count(distinct prompt_id)
+ filter (where has_mention or has_citation) as visible_prompts
+ from prompt_days group by model_used, platform
+ ) p on p.model_used is not distinct from b.model_used
+ and p.platform is not distinct from b.platform
+ ),
+ -- Grouped once each, then joined — a correlated subselect here rescans
+ -- comp_prompt_days per output group (13 + ~119 of them), which measured
+ -- 1.6s on the largest brand's all-time window against ~100ms this way.
+ visible_by_comp as (
+ select competitor_id, count(distinct prompt_id) as visible_prompts
+ from comp_prompt_days group by competitor_id
+ ),
+ visible_by_comp_engine as (
+ select competitor_id, model_used, platform,
+ count(distinct prompt_id) as visible_prompts
+ from comp_prompt_days group by competitor_id, model_used, platform
+ ),
+ by_competitor as (
+ select
+ cd.competitor_id,
+ max(c.name) as name,
+ sum(cd.sum_visibility) as sum_visibility,
+ sum(cd.answer_count) as row_count,
+ coalesce(sum(cd.total_mentions), 0)::bigint as total_mentions,
+ coalesce(sum(cd.total_citations), 0)::bigint as total_citations,
+ coalesce(max(v.visible_prompts), 0) as visible_prompts
+ from comp_days cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ left join visible_by_comp v on v.competitor_id = cd.competitor_id
+ group by cd.competitor_id
+ ),
+ by_competitor_provider as (
+ select
+ cd.model_used, cd.platform, cd.competitor_id,
+ max(c.name) as competitor_name,
+ sum(cd.sum_visibility) as sum_visibility,
+ sum(cd.answer_count) as row_count,
+ coalesce(max(v.visible_prompts), 0) as visible_prompts
+ from comp_days cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ left join visible_by_comp_engine v
+ on v.competitor_id = cd.competitor_id
+ and v.model_used is not distinct from cd.model_used
+ and v.platform is not distinct from cd.platform
+ group by cd.model_used, cd.platform, cd.competitor_id
+ )
+ select jsonb_build_object(
+ 'brand_row_count', b.row_count,
+ 'brand_sum_visibility', b.sum_visibility,
+ 'brand_total_mentions', b.total_mentions,
+ 'brand_total_citations', b.total_citations,
+ 'brand_prompt_count', b.prompt_count,
+ 'brand_visible_prompts', b.visible_prompts,
+ 'by_competitor', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'competitor_id', bc.competitor_id,
+ 'name', bc.name,
+ 'sum_visibility', bc.sum_visibility,
+ 'row_count', bc.row_count,
+ 'total_mentions', bc.total_mentions,
+ 'total_citations', bc.total_citations,
+ 'visible_prompts', bc.visible_prompts)
+ order by bc.row_count desc, bc.competitor_id)
+ from by_competitor bc),
+ '[]'::jsonb),
+ 'by_brand_provider', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bbp.model_used,
+ 'platform', bbp.platform,
+ 'sum_visibility', bbp.sum_visibility,
+ 'row_count', bbp.row_count,
+ 'prompt_count', bbp.prompt_count,
+ 'visible_prompts', bbp.visible_prompts)
+ order by bbp.platform nulls last, bbp.model_used nulls last)
+ from by_brand_provider bbp),
+ '[]'::jsonb),
+ 'by_competitor_provider', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bcp.model_used,
+ 'platform', bcp.platform,
+ 'competitor_id', bcp.competitor_id,
+ 'competitor_name', bcp.competitor_name,
+ 'sum_visibility', bcp.sum_visibility,
+ 'row_count', bcp.row_count,
+ 'visible_prompts', bcp.visible_prompts)
+ order by bcp.platform nulls last, bcp.model_used nulls last, bcp.competitor_id)
+ from by_competitor_provider bcp),
+ '[]'::jsonb)
+ )
+ from brand_totals b;
+$$;
+
+-- share_of_voice_aggregates over rollups. No competitors join anywhere — the
+-- raw RPC sums every jsonb element regardless of liveness, and SoV parity
+-- means keeping that.
+create or replace function public.share_of_voice_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_days as (
+ select * from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ comp_days as (
+ select * from public.insights_competitor_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ totals as (
+ select
+ coalesce((select sum(total_mentions) from brand_days), 0)::bigint as total_brand_mentions,
+ coalesce((select sum(total_mentions) from comp_days), 0)::bigint as total_competitor_mentions
+ ),
+ by_platform as (
+ select b.model_used, b.platform,
+ b.brand_mentions,
+ coalesce(c.competitor_mentions, 0) as competitor_mentions
+ from (
+ select model_used, platform,
+ coalesce(sum(total_mentions), 0)::bigint as brand_mentions
+ from brand_days group by model_used, platform
+ ) b
+ left join (
+ select model_used, platform,
+ coalesce(sum(total_mentions), 0)::bigint as competitor_mentions
+ from comp_days group by model_used, platform
+ ) c on c.model_used is not distinct from b.model_used
+ and c.platform is not distinct from b.platform
+ ),
+ by_day as (
+ select b.day,
+ b.brand_mentions,
+ coalesce(c.competitor_mentions, 0) as competitor_mentions
+ from (
+ select to_char(day, 'YYYY-MM-DD') as day,
+ coalesce(sum(total_mentions), 0)::bigint as brand_mentions
+ from brand_days group by day
+ ) b
+ left join (
+ select to_char(day, 'YYYY-MM-DD') as day,
+ coalesce(sum(total_mentions), 0)::bigint as competitor_mentions
+ from comp_days group by day
+ ) c on c.day = b.day
+ )
+ select jsonb_build_object(
+ 'total_brand_mentions', t.total_brand_mentions,
+ 'total_competitor_mentions', t.total_competitor_mentions,
+ 'by_platform', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bp.model_used,
+ 'platform', bp.platform,
+ 'brand_mentions', bp.brand_mentions,
+ 'competitor_mentions', bp.competitor_mentions)
+ order by bp.platform nulls last, bp.model_used nulls last)
+ from by_platform bp),
+ '[]'::jsonb),
+ 'by_day', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'day', bd.day,
+ 'brand_mentions', bd.brand_mentions,
+ 'competitor_mentions', bd.competitor_mentions)
+ order by bd.day)
+ from by_day bd),
+ '[]'::jsonb)
+ )
+ from totals t;
+$$;
+
+-- visibility_rate_trend over rollups. Brand rows fold the day-grain and
+-- prompt-grain tables; competitor rows are the dense per-day counts left-
+-- joined with the visible-sighting distincts (liveness join preserved).
+create or replace function public.visibility_rate_trend_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_daily as (
+ select d.day,
+ sum(d.answer_count) as answers,
+ sum(d.mention_answers) as mention_answers,
+ sum(d.citation_answers) as citation_answers,
+ sum(d.sum_inv_position) / nullif(sum(d.position_count), 0) as position_factor,
+ sum(d.position_count) as position_n
+ from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ group by d.day
+ ),
+ prompt_daily as (
+ select d.day,
+ count(distinct d.prompt_id) as prompt_count,
+ count(distinct d.prompt_id)
+ filter (where d.has_mention or d.has_citation) as visible_prompts
+ from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ group by d.day
+ ),
+ comp_daily as (
+ select cd.day, cd.competitor_id,
+ sum(cd.mention_answers) as mention_answers,
+ sum(cd.citation_answers) as citation_answers,
+ sum(cd.sum_inv_position) / nullif(sum(cd.position_count), 0) as position_factor,
+ sum(cd.position_count) as position_n
+ from public.insights_competitor_daily cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ where cd.brand_id = p_brand_id
+ and (p_platform is null or cd.platform = p_platform)
+ and (p_models is null or cd.model_used = any (p_models))
+ and (p_region is null or cd.region = p_region)
+ and (p_day_from is null or cd.day >= p_day_from)
+ and (p_day_to is null or cd.day <= p_day_to)
+ group by cd.day, cd.competitor_id
+ ),
+ comp_visible as (
+ select cpd.day, cpd.competitor_id,
+ count(distinct cpd.prompt_id) as visible_prompts
+ from public.insights_competitor_prompt_daily cpd
+ 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_platform is null or cpd.platform = p_platform)
+ and (p_models is null or cpd.model_used = any (p_models))
+ and (p_region is null or cpd.region = p_region)
+ and (p_day_from is null or cpd.day >= p_day_from)
+ and (p_day_to is null or cpd.day <= p_day_to)
+ group by cpd.day, cpd.competitor_id
+ )
+ select coalesce(
+ jsonb_agg(jsonb_build_object(
+ 'day', bd.day,
+ 'prompt_count', coalesce(pd.prompt_count, 0),
+ 'visible_prompts', coalesce(pd.visible_prompts, 0),
+ 'answers', bd.answers,
+ 'mention_answers', bd.mention_answers,
+ 'citation_answers', bd.citation_answers,
+ 'position_factor', bd.position_factor,
+ 'position_n', bd.position_n,
+ 'competitors', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'competitor_id', cd.competitor_id,
+ 'visible_prompts', coalesce(cv.visible_prompts, 0),
+ 'mention_answers', cd.mention_answers,
+ 'citation_answers', cd.citation_answers,
+ 'position_factor', cd.position_factor,
+ 'position_n', cd.position_n)
+ order by cd.competitor_id)
+ from comp_daily cd
+ left join comp_visible cv
+ on cv.day = cd.day and cv.competitor_id = cd.competitor_id
+ where cd.day = bd.day),
+ '[]'::jsonb)
+ ) order by bd.day),
+ '[]'::jsonb)
+ from brand_daily bd
+ left join prompt_daily pd on pd.day = bd.day;
+$$;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index befa6afb7..e0393993a 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -6693,3 +6693,870 @@ $$;
GRANT EXECUTE ON FUNCTION "public"."report_query_fanout_engines"(uuid, timestamptz, timestamptz) TO "authenticated";
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00066_insights_daily_rollups.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Insights stops recomputing history on every page load.
+--
+-- The Insights aggregate RPCs scan every prompt_results row a brand has ever
+-- produced and explode competitor_mentions jsonb on the fly — 566,908 array
+-- elements for the largest brand. Under the authenticated role's 8s
+-- statement_timeout, competitor_aggregates takes 9.7s on that brand's
+-- all-time window, so 30d/90d/all render as an opaque server error. The cost
+-- grows with accumulated history: rewriting the query buys weeks, not a fix.
+--
+-- These tables invert the work. Each brand-day is aggregated ONCE — when the
+-- brand's tracking run completes (the same drain point Daily Pulse waits on),
+-- with a daily catch-up sweep as backstop — and the page reads the daily
+-- rows. Read cost then scales with days in the window, never with results.
+--
+-- Grain: (day, model_used, platform, region), because those are exactly the
+-- page's filter dimensions. Two extra tables carry the prompt dimension: the
+-- leaderboard's rate is COUNT(DISTINCT prompt_id) over the window, which
+-- cannot be summed across days. insights_prompt_daily mirrors one row per
+-- answered (prompt, engine, day); insights_competitor_prompt_daily keeps only
+-- VISIBLE competitor sightings — 9.4% of elements on the largest brand
+-- (53,331 of 566,908) — so the distinct-count input stays small.
+--
+-- Two deliberate semantic carriers, verified against the live definitions:
+-- * share_of_voice_aggregates counts competitor mentions WITHOUT a join to
+-- competitors (deleted competitors included); competitor_aggregates and
+-- ai_visibility_aggregates filter to live competitors. The rollups store
+-- every competitor_id seen in the jsonb, and the liveness join is applied
+-- by the read functions that had it — parity for both, and a competitor
+-- deleted tomorrow disappears from reads without touching stored rows.
+-- * Topic- and prompt-filtered calls stay on the raw RPCs: topic is a live
+-- prompt attribute (reassignment must move history with it), and both
+-- filters cut the scanned set far below the danger line.
+--
+-- The old RPCs are left untouched — MCP, reports and pulse call them under
+-- the service role, which has no statement timeout. Only day-window reads
+-- move here.
+
+-- ─── Tables ─────────────────────────────────────────────────────────────────
+
+-- Brand-side additive measures. One row per (day, engine, region).
+create table if not exists public.insights_brand_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ model_used text,
+ platform text,
+ region text,
+ answer_count integer not null,
+ mention_answers integer not null,
+ citation_answers integer not null,
+ -- mention OR citation — not derivable from the two columns above.
+ mentioning_answers integer not null,
+ sum_visibility numeric not null,
+ -- SUM(visibility_score) over mentioning answers only (visible_prompt_stats).
+ sum_visibility_visible numeric not null,
+ total_mentions bigint not null,
+ total_citations bigint not null,
+ positive_count integer not null,
+ -- AVG(1.0/mention_position) folds as sum/count across any window.
+ sum_inv_position numeric,
+ position_count integer not null,
+ max_created_at timestamptz not null
+);
+
+create index if not exists idx_insights_brand_daily_brand_day
+ on public.insights_brand_daily (brand_id, day);
+
+-- Per-competitor additive measures. Dense: every competitor_id present in an
+-- answer's jsonb gets a row, zeros included, because the comparison table
+-- shows a row (and an answer count) even for a competitor never mentioned.
+create table if not exists public.insights_competitor_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ -- Text, not uuid: it mirrors the jsonb payload verbatim, and the read
+ -- functions echo it back as the old RPCs did.
+ competitor_id text not null,
+ model_used text,
+ platform text,
+ region text,
+ answer_count integer not null,
+ sum_visibility numeric,
+ total_mentions bigint not null,
+ total_citations bigint not null,
+ mention_answers integer not null,
+ citation_answers integer not null,
+ sum_inv_position numeric,
+ position_count integer not null
+);
+
+create index if not exists idx_insights_competitor_daily_brand_day
+ on public.insights_competitor_daily (brand_id, day);
+
+-- One row per answered (prompt, engine, region, day) — the input for every
+-- COUNT(DISTINCT prompt_id) the page shows. The widest of the four tables,
+-- but each row is a few booleans; the largest brand adds ~1,800/day.
+create table if not exists public.insights_prompt_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ prompt_id uuid not null,
+ model_used text,
+ platform text,
+ region text,
+ answer_count integer not null,
+ has_mention boolean not null,
+ has_citation boolean not null
+);
+
+create index if not exists idx_insights_prompt_daily_brand_day
+ on public.insights_prompt_daily (brand_id, day);
+
+-- Visible competitor sightings only: (competitor, prompt, engine, day) rows
+-- where the competitor was actually mentioned, cited or scored. Existence is
+-- the datum — the per-competitor visible-prompt distinct counts read this.
+create table if not exists public.insights_competitor_prompt_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ competitor_id text not null,
+ prompt_id uuid not null,
+ model_used text,
+ platform text,
+ region text
+);
+
+create index if not exists idx_insights_competitor_prompt_daily_brand_day
+ on public.insights_competitor_prompt_daily (brand_id, day);
+
+-- ─── RLS — same shape as prompt_results ─────────────────────────────────────
+
+alter table public.insights_brand_daily enable row level security;
+alter table public.insights_competitor_daily enable row level security;
+alter table public.insights_prompt_daily enable row level security;
+alter table public.insights_competitor_prompt_daily enable row level security;
+
+create policy "Users can read own org insights rollups"
+ on public.insights_brand_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org competitor rollups"
+ on public.insights_competitor_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org prompt rollups"
+ on public.insights_prompt_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org competitor prompt rollups"
+ on public.insights_competitor_prompt_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+-- ─── Refresh ────────────────────────────────────────────────────────────────
+
+-- Recomputes a brand's rollup rows for a day range from prompt_results.
+-- Delete + insert in one transaction: idempotent by construction (no upsert
+-- arbiter needed, so NULL dimension values need no synthetic encoding), and
+-- readers never see a half-refreshed day. Day-scoped, so the jsonb explode
+-- that makes the read path unaffordable stays cheap here: one day of the
+-- largest brand is ~1,800 answers.
+--
+-- Service-role only. The web tier must never trigger writes; execute is
+-- revoked from anon/authenticated below.
+create or replace function public.refresh_insights_daily(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+begin
+ delete from public.insights_brand_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.insights_competitor_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.insights_prompt_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.insights_competitor_prompt_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+
+ insert into public.insights_brand_daily (
+ brand_id, day, model_used, platform, region,
+ answer_count, mention_answers, citation_answers, mentioning_answers,
+ sum_visibility, sum_visibility_visible, total_mentions, total_citations,
+ positive_count, sum_inv_position, position_count, max_created_at)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.model_used, pr.platform, pr.region,
+ count(*),
+ count(*) filter (where pr.mention_count > 0),
+ count(*) filter (where pr.citation_count > 0),
+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),
+ coalesce(sum(pr.visibility_score), 0),
+ coalesce(sum(pr.visibility_score)
+ filter (where pr.mention_count > 0 or pr.citation_count > 0), 0),
+ coalesce(sum(pr.mention_count), 0),
+ coalesce(sum(pr.citation_count), 0),
+ count(*) filter (where pr.sentiment = 'positive'),
+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),
+ count(*) filter (where pr.mention_position is not null),
+ max(pr.created_at)
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ group by 2, pr.model_used, pr.platform, pr.region;
+
+ insert into public.insights_prompt_daily (
+ brand_id, day, prompt_id, model_used, platform, region,
+ answer_count, has_mention, has_citation)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id, pr.model_used, pr.platform, pr.region,
+ count(*),
+ bool_or(pr.mention_count > 0),
+ bool_or(pr.citation_count > 0)
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ group by 2, pr.prompt_id, pr.model_used, pr.platform, pr.region;
+
+ insert into public.insights_competitor_daily (
+ brand_id, day, competitor_id, model_used, platform, region,
+ answer_count, sum_visibility, total_mentions, total_citations,
+ mention_answers, citation_answers, sum_inv_position, position_count)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ cm.value->>'competitor_id',
+ pr.model_used, pr.platform, pr.region,
+ count(*),
+ sum((cm.value->>'visibility_score')::numeric),
+ coalesce(sum(coalesce((cm.value->>'mention_count')::int, 0)), 0),
+ coalesce(sum(coalesce((cm.value->>'citation_count')::int, 0)), 0),
+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),
+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),
+ sum(1.0 / (cm.value->>'mention_position')::numeric)
+ filter (where (cm.value->>'mention_position') is not null),
+ count(*) filter (where (cm.value->>'mention_position') is not null)
+ from public.prompt_results pr,
+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ and cm.value ? 'competitor_id'
+ group by 2, cm.value->>'competitor_id', pr.model_used, pr.platform, pr.region;
+
+ insert into public.insights_competitor_prompt_daily (
+ brand_id, day, competitor_id, prompt_id, model_used, platform, region)
+ select distinct
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ cm.value->>'competitor_id',
+ pr.prompt_id, pr.model_used, pr.platform, pr.region
+ from public.prompt_results pr,
+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to
+ and cm.value ? 'competitor_id'
+ and (coalesce((cm.value->>'mention_count')::int, 0) > 0
+ or coalesce((cm.value->>'citation_count')::int, 0) > 0
+ or coalesce((cm.value->>'visibility_score')::numeric, 0) > 0);
+end;
+$$;
+
+revoke execute on function public.refresh_insights_daily(uuid, date, date)
+ from public, anon, authenticated;
+
+-- ─── Read functions ─────────────────────────────────────────────────────────
+--
+-- Each mirrors its raw counterpart's payload byte for byte — same keys, same
+-- ordering clauses — so the web mapping code cannot tell which one answered,
+-- and the cutover can be shadow-verified by diffing the two outputs. All are
+-- SECURITY INVOKER: the caller's RLS on the rollup tables scopes the read,
+-- exactly as the raw RPCs lean on prompt_results RLS.
+--
+-- Windows are whole days (p_day_from .. p_day_to inclusive, UTC), which is
+-- what makes the rollup readable at all. The one caller-visible consequence —
+-- a preset window covers calendar days instead of sliding with the clock —
+-- is deliberate: numbers move once per completed run instead of drifting
+-- within the day.
+
+-- insights_aggregates over rollups.
+create or replace function public.insights_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with filtered as (
+ select * from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ totals as (
+ select
+ coalesce(sum(answer_count), 0) as total_results,
+ coalesce(sum(sum_visibility), 0) as sum_visibility,
+ coalesce(sum(total_mentions), 0) as total_mentions,
+ coalesce(sum(total_citations), 0) as total_citations,
+ coalesce(sum(positive_count), 0) as positive_count,
+ coalesce(sum(mentioning_answers), 0) as mentioning_results,
+ max(max_created_at) as last_checked_at
+ from filtered
+ ),
+ by_model as (
+ select
+ coalesce(model_used, 'unknown') as model_used,
+ sum(sum_visibility) as sum_visibility,
+ sum(answer_count) as result_count
+ from filtered
+ group by coalesce(model_used, 'unknown')
+ )
+ select jsonb_build_object(
+ 'total_results', t.total_results,
+ 'sum_visibility', t.sum_visibility,
+ 'total_mentions', t.total_mentions,
+ 'total_citations', t.total_citations,
+ 'positive_count', t.positive_count,
+ 'mentioning_results', t.mentioning_results,
+ 'last_checked_at', t.last_checked_at,
+ 'by_model', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bm.model_used,
+ 'sum_visibility', bm.sum_visibility,
+ 'result_count', bm.result_count)
+ order by bm.result_count desc, bm.model_used)
+ from by_model bm),
+ '[]'::jsonb)
+ )
+ from totals t;
+$$;
+
+-- visible_prompt_stats over rollups.
+create or replace function public.visible_prompt_stats_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ select jsonb_build_object(
+ 'visible_prompts',
+ (select count(distinct pd.prompt_id)
+ from public.insights_prompt_daily pd
+ where pd.brand_id = p_brand_id
+ and (pd.has_mention or pd.has_citation)
+ and (p_platform is null or pd.platform = p_platform)
+ and (p_models is null or pd.model_used = any (p_models))
+ and (p_region is null or pd.region = p_region)
+ and (p_day_from is null or pd.day >= p_day_from)
+ and (p_day_to is null or pd.day <= p_day_to)),
+ 'visible_results',
+ coalesce((select sum(bd.mentioning_answers)
+ from public.insights_brand_daily bd
+ where bd.brand_id = p_brand_id
+ and (p_platform is null or bd.platform = p_platform)
+ and (p_models is null or bd.model_used = any (p_models))
+ and (p_region is null or bd.region = p_region)
+ and (p_day_from is null or bd.day >= p_day_from)
+ and (p_day_to is null or bd.day <= p_day_to)), 0),
+ 'sum_visibility_visible',
+ coalesce((select sum(bd.sum_visibility_visible)
+ from public.insights_brand_daily bd
+ where bd.brand_id = p_brand_id
+ and (p_platform is null or bd.platform = p_platform)
+ and (p_models is null or bd.model_used = any (p_models))
+ and (p_region is null or bd.region = p_region)
+ and (p_day_from is null or bd.day >= p_day_from)
+ and (p_day_to is null or bd.day <= p_day_to)), 0)
+ );
+$$;
+
+-- tracked_prompt_count over rollups.
+create or replace function public.tracked_prompt_count_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns integer
+language sql
+stable
+set search_path to 'public'
+as $$
+ select count(distinct pd.prompt_id)::integer
+ from public.insights_prompt_daily pd
+ where pd.brand_id = p_brand_id
+ and (p_platform is null or pd.platform = p_platform)
+ and (p_models is null or pd.model_used = any (p_models))
+ and (p_region is null or pd.region = p_region)
+ and (p_day_from is null or pd.day >= p_day_from)
+ and (p_day_to is null or pd.day <= p_day_to)
+$$;
+
+-- ai_visibility_aggregates over rollups. Liveness join preserved: only
+-- competitors that still exist appear, exactly like the raw RPC's EXISTS.
+-- Names come from competitors.name (live) rather than the jsonb snapshot the
+-- raw RPC MAX()es over — a renamed competitor shows its current name.
+create or replace function public.ai_visibility_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_agg as (
+ select
+ coalesce(sum(answer_count), 0) as answers,
+ coalesce(sum(mention_answers), 0) as mention_answers,
+ coalesce(sum(citation_answers), 0) as citation_answers,
+ sum(sum_inv_position) / nullif(sum(position_count), 0) as position_factor
+ from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ comp_agg as (
+ select
+ cd.competitor_id,
+ max(c.name) as name,
+ sum(cd.mention_answers) as mention_answers,
+ sum(cd.citation_answers) as citation_answers,
+ sum(cd.sum_inv_position) / nullif(sum(cd.position_count), 0) as position_factor
+ from public.insights_competitor_daily cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ where cd.brand_id = p_brand_id
+ and (p_platform is null or cd.platform = p_platform)
+ and (p_models is null or cd.model_used = any (p_models))
+ and (p_region is null or cd.region = p_region)
+ and (p_day_from is null or cd.day >= p_day_from)
+ and (p_day_to is null or cd.day <= p_day_to)
+ group by cd.competitor_id
+ )
+ select jsonb_build_object(
+ 'answers', b.answers,
+ 'mention_answers', b.mention_answers,
+ 'citation_answers', b.citation_answers,
+ 'position_factor', b.position_factor,
+ 'by_competitor', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'competitor_id', ca.competitor_id,
+ 'name', ca.name,
+ 'mention_answers', ca.mention_answers,
+ 'citation_answers', ca.citation_answers,
+ 'position_factor', ca.position_factor)
+ order by ca.mention_answers desc, ca.competitor_id)
+ from comp_agg ca),
+ '[]'::jsonb)
+ )
+ from brand_agg b;
+$$;
+
+-- competitor_aggregates over rollups. The distinct-prompt counts read the two
+-- prompt-grain tables; everything additive reads the day-grain ones. Engine
+-- keys join with IS NOT DISTINCT FROM because model_used can be null.
+create or replace function public.competitor_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_days as (
+ select * from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ prompt_days as (
+ select * from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ comp_days as (
+ select cd.* from public.insights_competitor_daily cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ where cd.brand_id = p_brand_id
+ and (p_platform is null or cd.platform = p_platform)
+ and (p_models is null or cd.model_used = any (p_models))
+ and (p_region is null or cd.region = p_region)
+ and (p_day_from is null or cd.day >= p_day_from)
+ and (p_day_to is null or cd.day <= p_day_to)
+ ),
+ comp_prompt_days as (
+ select cpd.* from public.insights_competitor_prompt_daily cpd
+ 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_platform is null or cpd.platform = p_platform)
+ and (p_models is null or cpd.model_used = any (p_models))
+ and (p_region is null or cpd.region = p_region)
+ and (p_day_from is null or cpd.day >= p_day_from)
+ and (p_day_to is null or cpd.day <= p_day_to)
+ ),
+ brand_totals as (
+ select
+ coalesce((select sum(answer_count) from brand_days), 0) as row_count,
+ coalesce((select sum(sum_visibility) from brand_days), 0) as sum_visibility,
+ coalesce((select sum(total_mentions) from brand_days), 0) as total_mentions,
+ coalesce((select sum(total_citations) from brand_days), 0) as total_citations,
+ (select count(distinct prompt_id) from prompt_days) as prompt_count,
+ (select count(distinct prompt_id) from prompt_days
+ where has_mention or has_citation) as visible_prompts
+ ),
+ by_brand_provider as (
+ select b.model_used, b.platform, b.sum_visibility, b.row_count,
+ p.prompt_count, p.visible_prompts
+ from (
+ select model_used, platform,
+ sum(sum_visibility) as sum_visibility,
+ sum(answer_count) as row_count
+ from brand_days group by model_used, platform
+ ) b
+ join (
+ select model_used, platform,
+ count(distinct prompt_id) as prompt_count,
+ count(distinct prompt_id)
+ filter (where has_mention or has_citation) as visible_prompts
+ from prompt_days group by model_used, platform
+ ) p on p.model_used is not distinct from b.model_used
+ and p.platform is not distinct from b.platform
+ ),
+ -- Grouped once each, then joined — a correlated subselect here rescans
+ -- comp_prompt_days per output group (13 + ~119 of them), which measured
+ -- 1.6s on the largest brand's all-time window against ~100ms this way.
+ visible_by_comp as (
+ select competitor_id, count(distinct prompt_id) as visible_prompts
+ from comp_prompt_days group by competitor_id
+ ),
+ visible_by_comp_engine as (
+ select competitor_id, model_used, platform,
+ count(distinct prompt_id) as visible_prompts
+ from comp_prompt_days group by competitor_id, model_used, platform
+ ),
+ by_competitor as (
+ select
+ cd.competitor_id,
+ max(c.name) as name,
+ sum(cd.sum_visibility) as sum_visibility,
+ sum(cd.answer_count) as row_count,
+ coalesce(sum(cd.total_mentions), 0)::bigint as total_mentions,
+ coalesce(sum(cd.total_citations), 0)::bigint as total_citations,
+ coalesce(max(v.visible_prompts), 0) as visible_prompts
+ from comp_days cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ left join visible_by_comp v on v.competitor_id = cd.competitor_id
+ group by cd.competitor_id
+ ),
+ by_competitor_provider as (
+ select
+ cd.model_used, cd.platform, cd.competitor_id,
+ max(c.name) as competitor_name,
+ sum(cd.sum_visibility) as sum_visibility,
+ sum(cd.answer_count) as row_count,
+ coalesce(max(v.visible_prompts), 0) as visible_prompts
+ from comp_days cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ left join visible_by_comp_engine v
+ on v.competitor_id = cd.competitor_id
+ and v.model_used is not distinct from cd.model_used
+ and v.platform is not distinct from cd.platform
+ group by cd.model_used, cd.platform, cd.competitor_id
+ )
+ select jsonb_build_object(
+ 'brand_row_count', b.row_count,
+ 'brand_sum_visibility', b.sum_visibility,
+ 'brand_total_mentions', b.total_mentions,
+ 'brand_total_citations', b.total_citations,
+ 'brand_prompt_count', b.prompt_count,
+ 'brand_visible_prompts', b.visible_prompts,
+ 'by_competitor', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'competitor_id', bc.competitor_id,
+ 'name', bc.name,
+ 'sum_visibility', bc.sum_visibility,
+ 'row_count', bc.row_count,
+ 'total_mentions', bc.total_mentions,
+ 'total_citations', bc.total_citations,
+ 'visible_prompts', bc.visible_prompts)
+ order by bc.row_count desc, bc.competitor_id)
+ from by_competitor bc),
+ '[]'::jsonb),
+ 'by_brand_provider', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bbp.model_used,
+ 'platform', bbp.platform,
+ 'sum_visibility', bbp.sum_visibility,
+ 'row_count', bbp.row_count,
+ 'prompt_count', bbp.prompt_count,
+ 'visible_prompts', bbp.visible_prompts)
+ order by bbp.platform nulls last, bbp.model_used nulls last)
+ from by_brand_provider bbp),
+ '[]'::jsonb),
+ 'by_competitor_provider', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bcp.model_used,
+ 'platform', bcp.platform,
+ 'competitor_id', bcp.competitor_id,
+ 'competitor_name', bcp.competitor_name,
+ 'sum_visibility', bcp.sum_visibility,
+ 'row_count', bcp.row_count,
+ 'visible_prompts', bcp.visible_prompts)
+ order by bcp.platform nulls last, bcp.model_used nulls last, bcp.competitor_id)
+ from by_competitor_provider bcp),
+ '[]'::jsonb)
+ )
+ from brand_totals b;
+$$;
+
+-- share_of_voice_aggregates over rollups. No competitors join anywhere — the
+-- raw RPC sums every jsonb element regardless of liveness, and SoV parity
+-- means keeping that.
+create or replace function public.share_of_voice_aggregates_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_days as (
+ select * from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ comp_days as (
+ select * from public.insights_competitor_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ ),
+ totals as (
+ select
+ coalesce((select sum(total_mentions) from brand_days), 0)::bigint as total_brand_mentions,
+ coalesce((select sum(total_mentions) from comp_days), 0)::bigint as total_competitor_mentions
+ ),
+ by_platform as (
+ select b.model_used, b.platform,
+ b.brand_mentions,
+ coalesce(c.competitor_mentions, 0) as competitor_mentions
+ from (
+ select model_used, platform,
+ coalesce(sum(total_mentions), 0)::bigint as brand_mentions
+ from brand_days group by model_used, platform
+ ) b
+ left join (
+ select model_used, platform,
+ coalesce(sum(total_mentions), 0)::bigint as competitor_mentions
+ from comp_days group by model_used, platform
+ ) c on c.model_used is not distinct from b.model_used
+ and c.platform is not distinct from b.platform
+ ),
+ by_day as (
+ select b.day,
+ b.brand_mentions,
+ coalesce(c.competitor_mentions, 0) as competitor_mentions
+ from (
+ select to_char(day, 'YYYY-MM-DD') as day,
+ coalesce(sum(total_mentions), 0)::bigint as brand_mentions
+ from brand_days group by day
+ ) b
+ left join (
+ select to_char(day, 'YYYY-MM-DD') as day,
+ coalesce(sum(total_mentions), 0)::bigint as competitor_mentions
+ from comp_days group by day
+ ) c on c.day = b.day
+ )
+ select jsonb_build_object(
+ 'total_brand_mentions', t.total_brand_mentions,
+ 'total_competitor_mentions', t.total_competitor_mentions,
+ 'by_platform', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', bp.model_used,
+ 'platform', bp.platform,
+ 'brand_mentions', bp.brand_mentions,
+ 'competitor_mentions', bp.competitor_mentions)
+ order by bp.platform nulls last, bp.model_used nulls last)
+ from by_platform bp),
+ '[]'::jsonb),
+ 'by_day', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'day', bd.day,
+ 'brand_mentions', bd.brand_mentions,
+ 'competitor_mentions', bd.competitor_mentions)
+ order by bd.day)
+ from by_day bd),
+ '[]'::jsonb)
+ )
+ from totals t;
+$$;
+
+-- visibility_rate_trend over rollups. Brand rows fold the day-grain and
+-- prompt-grain tables; competitor rows are the dense per-day counts left-
+-- joined with the visible-sighting distincts (liveness join preserved).
+create or replace function public.visibility_rate_trend_daily(
+ p_brand_id uuid,
+ p_platform text default null,
+ p_models text[] default null,
+ p_region text default null,
+ p_day_from date default null,
+ p_day_to date default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with brand_daily as (
+ select d.day,
+ sum(d.answer_count) as answers,
+ sum(d.mention_answers) as mention_answers,
+ sum(d.citation_answers) as citation_answers,
+ sum(d.sum_inv_position) / nullif(sum(d.position_count), 0) as position_factor,
+ sum(d.position_count) as position_n
+ from public.insights_brand_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ group by d.day
+ ),
+ prompt_daily as (
+ select d.day,
+ count(distinct d.prompt_id) as prompt_count,
+ count(distinct d.prompt_id)
+ filter (where d.has_mention or d.has_citation) as visible_prompts
+ from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and (p_platform is null or d.platform = p_platform)
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (p_day_from is null or d.day >= p_day_from)
+ and (p_day_to is null or d.day <= p_day_to)
+ group by d.day
+ ),
+ comp_daily as (
+ select cd.day, cd.competitor_id,
+ sum(cd.mention_answers) as mention_answers,
+ sum(cd.citation_answers) as citation_answers,
+ sum(cd.sum_inv_position) / nullif(sum(cd.position_count), 0) as position_factor,
+ sum(cd.position_count) as position_n
+ from public.insights_competitor_daily cd
+ join public.competitors c
+ on c.id::text = cd.competitor_id and c.brand_id = p_brand_id
+ where cd.brand_id = p_brand_id
+ and (p_platform is null or cd.platform = p_platform)
+ and (p_models is null or cd.model_used = any (p_models))
+ and (p_region is null or cd.region = p_region)
+ and (p_day_from is null or cd.day >= p_day_from)
+ and (p_day_to is null or cd.day <= p_day_to)
+ group by cd.day, cd.competitor_id
+ ),
+ comp_visible as (
+ select cpd.day, cpd.competitor_id,
+ count(distinct cpd.prompt_id) as visible_prompts
+ from public.insights_competitor_prompt_daily cpd
+ 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_platform is null or cpd.platform = p_platform)
+ and (p_models is null or cpd.model_used = any (p_models))
+ and (p_region is null or cpd.region = p_region)
+ and (p_day_from is null or cpd.day >= p_day_from)
+ and (p_day_to is null or cpd.day <= p_day_to)
+ group by cpd.day, cpd.competitor_id
+ )
+ select coalesce(
+ jsonb_agg(jsonb_build_object(
+ 'day', bd.day,
+ 'prompt_count', coalesce(pd.prompt_count, 0),
+ 'visible_prompts', coalesce(pd.visible_prompts, 0),
+ 'answers', bd.answers,
+ 'mention_answers', bd.mention_answers,
+ 'citation_answers', bd.citation_answers,
+ 'position_factor', bd.position_factor,
+ 'position_n', bd.position_n,
+ 'competitors', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'competitor_id', cd.competitor_id,
+ 'visible_prompts', coalesce(cv.visible_prompts, 0),
+ 'mention_answers', cd.mention_answers,
+ 'citation_answers', cd.citation_answers,
+ 'position_factor', cd.position_factor,
+ 'position_n', cd.position_n)
+ order by cd.competitor_id)
+ from comp_daily cd
+ left join comp_visible cv
+ on cv.day = cd.day and cv.competitor_id = cd.competitor_id
+ where cd.day = bd.day),
+ '[]'::jsonb)
+ ) order by bd.day),
+ '[]'::jsonb)
+ from brand_daily bd
+ left join prompt_daily pd on pd.day = bd.day;
+$$;
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 045a93347..e7af41f1e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -152,12 +152,29 @@ const INSIGHT_EXPORT_HEADERS = [
'competitor_mentions',
];
-function getDateRange(preset: DatePreset, custom: { from: string; to: string }) {
- if (preset === 'all') return { dateFrom: undefined, dateTo: undefined };
+/**
+ * Every preset except 24h describes whole UTC calendar days, carried in
+ * `days` — that is what lets the aggregate actions answer from the daily
+ * rollup tables (00066) instead of rescanning the brand's history. The
+ * timestamp fields are kept in step for the paths that still take
+ * timestamps (CSV export, topic-filtered raw fallbacks), so both paths
+ * describe the same window.
+ *
+ * A preset window is the trailing N calendar days ending today: numbers
+ * move when a tracking run completes, not continuously as the clock's
+ * trailing edge slides. 24h keeps its rolling window — it is anchored to
+ * the last completed run downstream and stays on the raw path.
+ */
+function getDateRange(
+ preset: DatePreset,
+ custom: { from: string; to: string },
+): { dateFrom?: string; dateTo?: string; days?: { dayFrom?: string; dayTo?: string } } {
+ if (preset === 'all') return { dateFrom: undefined, dateTo: undefined, days: {} };
if (preset === 'custom') {
return {
- dateFrom: custom.from || undefined,
+ dateFrom: custom.from ? `${custom.from}T00:00:00.000Z` : undefined,
dateTo: custom.to ? `${custom.to}T23:59:59.999Z` : undefined,
+ days: { dayFrom: custom.from || undefined, dayTo: custom.to || undefined },
};
}
if (preset === '24h') {
@@ -166,9 +183,12 @@ function getDateRange(preset: DatePreset, custom: { from: string; to: string })
return { dateFrom: from.toISOString(), dateTo: undefined };
}
const days = preset === '7d' ? 7 : preset === '30d' ? 30 : 90;
- const from = new Date();
- from.setDate(from.getDate() - days);
- return { dateFrom: from.toISOString(), dateTo: undefined };
+ const to = new Date();
+ const from = new Date(to);
+ from.setUTCDate(from.getUTCDate() - (days - 1));
+ const dayFrom = from.toISOString().slice(0, 10);
+ const dayTo = to.toISOString().slice(0, 10);
+ return { dateFrom: `${dayFrom}T00:00:00.000Z`, dateTo: undefined, days: { dayFrom, dayTo } };
}
// ─── Info Tooltip ─────────────────────────────────────────────────────────────
@@ -964,7 +984,8 @@ export default function InsightsPage() {
if (!silent) setIsLoading(true);
try {
const f = overrideFilters ?? filtersRef.current;
- let { dateFrom, dateTo } = getDateRange(f.datePreset, {
+ // eslint-disable-next-line prefer-const -- dateFrom/dateTo are reassigned by the 24h anchor below
+ let { dateFrom, dateTo, days } = getDateRange(f.datePreset, {
from: f.dateFrom,
to: f.dateTo,
});
@@ -992,6 +1013,10 @@ export default function InsightsPage() {
topicId: f.topic || undefined,
dateFrom,
dateTo,
+ // Whole-day window → the aggregate actions answer from the daily
+ // rollups (00066). Absent for 24h, whose anchored window above is
+ // timestamp-shaped and stays on the raw path.
+ days,
};
const hasFilters = Boolean(f.datePreset !== 'all' || f.model || f.region || f.topic);
@@ -1054,7 +1079,13 @@ export default function InsightsPage() {
if (/unexpected response/i.test(message)) {
console.debug('[insights] load aborted by navigation', err);
} else if (!silent) {
- toast.error(message || 'Failed to load insights');
+ // Next.js redacts server-action error messages in production
+ // builds ("An error occurred in the Server Components render…"),
+ // so relaying `message` verbatim shows the user that boilerplate
+ // instead of anything actionable. Anything unrecognizable gets the
+ // plain fallback.
+ const redacted = !message || /server components render|digest property/i.test(message);
+ toast.error(redacted ? 'Failed to load insights — please try again' : message);
} else {
// Silent refreshes fire every ~10s while a tracking job runs; a
// transient 5xx or network blip there shouldn't pop a red toast —
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 410b0525c..b52d38ff5 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -174,6 +174,71 @@ function modelFilterArray(model: string | undefined): string[] | undefined {
return list.length > 0 ? list : undefined;
}
+// ── Daily-rollup routing (00066) ────────────────────────────────────────────
+//
+// The aggregate RPCs used to rescan a brand's whole history per page load;
+// past ~55k results that exceeds the authenticated role's 8s statement
+// timeout and the wide presets die. Every preset except 24h now describes its
+// window as whole UTC days, and calls that carry one are answered from the
+// pre-aggregated daily tables instead — cost scales with days in the window,
+// never with accumulated results.
+//
+// Topic-filtered calls deliberately stay on the raw RPCs: topic is a live
+// prompt attribute (reassigning a prompt must move its history), the rollups
+// have no prompt dimension at brand grain, and a topic slice is a small
+// fraction of the scan that made the raw path unaffordable.
+
+/**
+ * Whole-day UTC window, 'YYYY-MM-DD' inclusive on both ends. Its presence in
+ * an action's opts marks the call as servable from the daily rollups; either
+ * bound may be absent (the All-time preset carries an empty window).
+ */
+export interface DayWindow {
+ dayFrom?: string;
+ dayTo?: string;
+}
+
+interface WindowedOpts {
+ topicId?: string;
+ days?: DayWindow;
+}
+
+/** The day window to serve from rollups, or null when the raw path must answer. */
+function dailyWindow(opts?: WindowedOpts): DayWindow | null {
+ return opts?.days && !opts.topicId ? opts.days : null;
+}
+
+const DAY_MS = 86_400_000;
+
+function utcToday(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
+function addDays(day: string, n: number): string {
+ return new Date(Date.parse(`${day}T00:00:00Z`) + n * DAY_MS).toISOString().slice(0, 10);
+}
+
+/**
+ * Current + previous equal-length day windows for the ↑/↓ delta math. An
+ * unbounded window anchors to the trailing 7 days, mirroring what the raw
+ * path's `now() - 7d` default has always compared against. The previous
+ * window ends the day BEFORE the current one starts — the raw path's
+ * timestamp arithmetic let the two windows share their boundary instant.
+ */
+function deltaDayWindows(days: DayWindow): {
+ cur: { dayFrom: string; dayTo: string };
+ prev: { dayFrom: string; dayTo: string };
+} {
+ const curTo = days.dayTo ?? utcToday();
+ const curFrom = days.dayFrom ?? addDays(curTo, -6);
+ const len = Math.round((Date.parse(curTo) - Date.parse(curFrom)) / DAY_MS) + 1;
+ const prevTo = addDays(curFrom, -1);
+ return {
+ cur: { dayFrom: curFrom, dayTo: curTo },
+ prev: { dayFrom: addDays(prevTo, -(len - 1)), dayTo: prevTo },
+ };
+}
+
// ── RPC return shapes (mirror supabase/migrations/00031_insights_sentiment_denominator.sql) ─
interface InsightsAggregates {
@@ -408,19 +473,36 @@ export interface VisibilityRateKpi {
*/
export async function getVisibilityRateKpi(
brandId: string,
- opts?: { model?: string; region?: string; dateFrom?: string; dateTo?: string; topicId?: string },
+ opts?: {
+ model?: string;
+ region?: string;
+ dateFrom?: string;
+ dateTo?: string;
+ topicId?: string;
+ days?: DayWindow;
+ },
): Promise<VisibilityRateKpi> {
const supabase = await createClient();
-
- const { data, error } = await supabase.rpc('visible_prompt_stats', {
- p_brand_id: brandId,
- p_platform: undefined,
- p_models: modelFilterArray(opts?.model),
- p_region: opts?.region ?? undefined,
- p_date_from: opts?.dateFrom ?? undefined,
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- p_topic_id: opts?.topicId ?? undefined,
- });
+ const daily = dailyWindow(opts);
+
+ const { data, error } = daily
+ ? await supabase.rpc('visible_prompt_stats_daily', {
+ p_brand_id: brandId,
+ p_platform: undefined,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? undefined,
+ p_day_from: daily.dayFrom,
+ p_day_to: daily.dayTo,
+ })
+ : await supabase.rpc('visible_prompt_stats', {
+ p_brand_id: brandId,
+ p_platform: undefined,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? undefined,
+ p_date_from: opts?.dateFrom ?? undefined,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
+ p_topic_id: opts?.topicId ?? undefined,
+ });
if (error) throw new Error(error.message);
const row = (data ?? {}) as {
@@ -448,9 +530,17 @@ export async function getVisibilityRateKpi(
*/
export async function getTrackedPromptsKpi(
brandId: string,
- opts?: { model?: string; region?: string; dateFrom?: string; dateTo?: string; topicId?: string },
+ opts?: {
+ model?: string;
+ region?: string;
+ dateFrom?: string;
+ dateTo?: string;
+ topicId?: string;
+ days?: DayWindow;
+ },
): Promise<TrackedPromptsKpi> {
const supabase = await createClient();
+ const daily = dailyWindow(opts);
const { data: brand } = await supabase
.from('brands')
@@ -472,15 +562,24 @@ export async function getTrackedPromptsKpi(
};
const [rpcResult, plan, quotaUsed] = await Promise.all([
- supabase.rpc('tracked_prompt_count', {
- p_brand_id: brandId,
- p_platform: undefined,
- p_models: modelFilterArray(opts?.model),
- p_region: opts?.region ?? undefined,
- p_date_from: opts?.dateFrom ?? undefined,
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- p_topic_id: opts?.topicId ?? undefined,
- }),
+ daily
+ ? supabase.rpc('tracked_prompt_count_daily', {
+ p_brand_id: brandId,
+ p_platform: undefined,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? undefined,
+ p_day_from: daily.dayFrom,
+ p_day_to: daily.dayTo,
+ })
+ : supabase.rpc('tracked_prompt_count', {
+ p_brand_id: brandId,
+ p_platform: undefined,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? undefined,
+ p_date_from: opts?.dateFrom ?? undefined,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
+ p_topic_id: opts?.topicId ?? undefined,
+ }),
orgId ? getOrgPlan(orgId) : Promise.resolve(null),
countOrgPrompts(),
]);
@@ -686,6 +785,7 @@ export async function getInsightsData(
topicId?: string;
dateFrom?: string;
dateTo?: string;
+ days?: DayWindow;
/** When the current view is filtered, check unfiltered data existence too. */
checkUnfiltered?: boolean;
},
@@ -696,8 +796,15 @@ export async function getInsightsData(
topicId: opts.topicId,
dateFrom: opts.dateFrom,
dateTo: opts.dateTo,
+ days: opts.days,
};
+ // The two heavyweight sections degrade instead of failing the page: a
+ // competitor or SoV error costs its own card, never the KPI header. Their
+ // empty shapes are exactly what the page already maps to "section hidden"
+ // (brands.length <= 1, byPlatform.length === 0). The summary and KPI reads
+ // stay fatal — the page is meaningless without them, and on the rollup
+ // path they are the cheap ones.
const [
summary,
competitors,
@@ -709,8 +816,19 @@ export async function getInsightsData(
unfilteredTotal,
] = await Promise.all([
getInsightsSummary(brandId, filterOpts),
- getCompetitorComparison(brandId, filterOpts),
- getShareOfVoiceData(brandId, filterOpts),
+ getCompetitorComparison(brandId, filterOpts).catch((err) => {
+ console.error('[insights] competitor comparison failed', err);
+ return { brands: [], providerRows: [] } satisfies CompetitorComparisonData;
+ }),
+ getShareOfVoiceData(brandId, filterOpts).catch((err) => {
+ console.error('[insights] share of voice failed', err);
+ return {
+ overallSov: 0,
+ overallSovChange: null,
+ byPlatform: [],
+ trend: [],
+ } satisfies ShareOfVoiceData;
+ }),
getTrackedPromptsKpi(brandId, filterOpts),
getVisibilityRateKpi(brandId, filterOpts),
getInsightsFilterOptions(brandId),
@@ -1128,10 +1246,12 @@ export async function getInsightsSummary(
dateFrom?: string;
dateTo?: string;
topicId?: string;
+ days?: DayWindow;
},
): Promise<InsightsSummary> {
const supabase = await createClient();
const p_models = modelFilterArray(opts?.model);
+ const daily = dailyWindow(opts);
// Sums + counts come from Postgres in one round trip; we still do the
// final divide + round in JS so the displayed numbers track the old
@@ -1144,12 +1264,24 @@ export async function getInsightsSummary(
p_prompt_id: undefined as string | undefined,
p_topic_id: opts?.topicId ?? undefined,
};
+ const dailyArgs = {
+ p_brand_id: brandId,
+ p_platform: undefined as string | undefined,
+ p_models,
+ p_region: opts?.region ?? undefined,
+ };
- const { data: curData, error } = await supabase.rpc('insights_aggregates', {
- ...baseArgs,
- p_date_from: opts?.dateFrom ?? undefined,
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- });
+ const { data: curData, error } = daily
+ ? await supabase.rpc('insights_aggregates_daily', {
+ ...dailyArgs,
+ p_day_from: daily.dayFrom,
+ p_day_to: daily.dayTo,
+ })
+ : await supabase.rpc('insights_aggregates', {
+ ...baseArgs,
+ p_date_from: opts?.dateFrom ?? undefined,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
+ });
if (error) throw new Error(error.message);
const cur = curData as unknown as InsightsAggregates;
@@ -1220,22 +1352,35 @@ export async function getInsightsSummary(
const duration = currentTo.getTime() - currentFrom.getTime();
const prevFrom = new Date(currentFrom.getTime() - duration);
+ const deltaDays = daily ? deltaDayWindows(daily) : null;
// Current-window aggregate: when no dateFrom was passed, the top-level
// call above is unbounded — for the delta math we need the same
// explicit "last 7 days" window the JS code used so the comparison
// stays anchored to recent momentum.
const [curRes, prevRes] = await Promise.all([
- supabase.rpc('insights_aggregates', {
- ...baseArgs,
- p_date_from: opts?.dateFrom ?? currentFrom.toISOString(),
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- }),
- supabase.rpc('insights_aggregates', {
- ...baseArgs,
- p_date_from: prevFrom.toISOString(),
- p_date_to: currentFrom.toISOString(),
- }),
+ deltaDays
+ ? supabase.rpc('insights_aggregates_daily', {
+ ...dailyArgs,
+ p_day_from: deltaDays.cur.dayFrom,
+ p_day_to: deltaDays.cur.dayTo,
+ })
+ : supabase.rpc('insights_aggregates', {
+ ...baseArgs,
+ p_date_from: opts?.dateFrom ?? currentFrom.toISOString(),
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
+ }),
+ deltaDays
+ ? supabase.rpc('insights_aggregates_daily', {
+ ...dailyArgs,
+ p_day_from: deltaDays.prev.dayFrom,
+ p_day_to: deltaDays.prev.dayTo,
+ })
+ : supabase.rpc('insights_aggregates', {
+ ...baseArgs,
+ p_date_from: prevFrom.toISOString(),
+ p_date_to: currentFrom.toISOString(),
+ }),
]);
// Surface RPC failures rather than silently emit null deltas — masking
// server-side errors here would hide real outages behind "no change."
@@ -1745,10 +1890,12 @@ export async function getCompetitorComparison(
dateFrom?: string;
dateTo?: string;
topicId?: string;
+ days?: DayWindow;
},
): Promise<CompetitorComparisonData> {
const supabase = await createClient();
const p_models = modelFilterArray(opts?.model);
+ const daily = dailyWindow(opts);
const baseArgs = {
p_brand_id: brandId,
@@ -1758,21 +1905,48 @@ export async function getCompetitorComparison(
p_prompt_id: undefined as string | undefined,
p_topic_id: opts?.topicId ?? undefined,
};
+ const dailyArgs = {
+ p_brand_id: brandId,
+ p_platform: undefined as string | undefined,
+ p_models,
+ p_region: opts?.region ?? undefined,
+ };
+
+ // The heaviest reads on the page: competitor_aggregates over the raw rows
+ // took 9.7s on the largest brand's all-time window — past the 8s statement
+ // timeout. The rollup variants answer the same payload from the daily
+ // tables (00066).
+ const compRpc = (win: { dayFrom?: string; dayTo?: string } | null, from?: string, to?: string) =>
+ win
+ ? supabase.rpc('competitor_aggregates_daily', {
+ ...dailyArgs,
+ p_day_from: win.dayFrom,
+ p_day_to: win.dayTo,
+ })
+ : supabase.rpc('competitor_aggregates', {
+ ...baseArgs,
+ p_date_from: from,
+ p_date_to: to,
+ });
+ const visRpc = (win: { dayFrom?: string; dayTo?: string } | null, from?: string, to?: string) =>
+ win
+ ? supabase.rpc('ai_visibility_aggregates_daily', {
+ ...dailyArgs,
+ p_day_from: win.dayFrom,
+ p_day_to: win.dayTo,
+ })
+ : supabase.rpc('ai_visibility_aggregates', {
+ ...baseArgs,
+ p_date_from: from,
+ p_date_to: to,
+ });
// Brand name + the displayed-period aggregates fire in parallel — all
// are needed before we can shape the response.
const [{ data: brand }, { data: aggDisplay, error: aggErr }, visDisplayRes] = await Promise.all([
supabase.from('brands').select('name').eq('id', brandId).single(),
- supabase.rpc('competitor_aggregates', {
- ...baseArgs,
- p_date_from: opts?.dateFrom ?? undefined,
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- }),
- supabase.rpc('ai_visibility_aggregates', {
- ...baseArgs,
- p_date_from: opts?.dateFrom ?? undefined,
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- }),
+ compRpc(daily, opts?.dateFrom ?? undefined, expandDateToEndOfDay(opts?.dateTo) ?? undefined),
+ visRpc(daily, opts?.dateFrom ?? undefined, expandDateToEndOfDay(opts?.dateTo) ?? undefined),
]);
if (aggErr) throw new Error(aggErr.message);
if (visDisplayRes.error) throw new Error(visDisplayRes.error.message);
@@ -1800,23 +1974,22 @@ export async function getCompetitorComparison(
const duration = currentTo.getTime() - currentFrom.getTime();
const prevFrom = new Date(currentFrom.getTime() - duration);
+ const deltaDays = daily ? deltaDayWindows(daily) : null;
const [curRes, prevRes, visPrevRes] = await Promise.all([
- supabase.rpc('competitor_aggregates', {
- ...baseArgs,
- p_date_from: opts?.dateFrom ?? currentFrom.toISOString(),
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- }),
- supabase.rpc('competitor_aggregates', {
- ...baseArgs,
- p_date_from: prevFrom.toISOString(),
- p_date_to: currentFrom.toISOString(),
- }),
- supabase.rpc('ai_visibility_aggregates', {
- ...baseArgs,
- p_date_from: prevFrom.toISOString(),
- p_date_to: currentFrom.toISOString(),
- }),
+ deltaDays
+ ? compRpc(deltaDays.cur)
+ : compRpc(
+ null,
+ opts?.dateFrom ?? currentFrom.toISOString(),
+ expandDateToEndOfDay(opts?.dateTo) ?? undefined,
+ ),
+ deltaDays
+ ? compRpc(deltaDays.prev)
+ : compRpc(null, prevFrom.toISOString(), currentFrom.toISOString()),
+ deltaDays
+ ? visRpc(deltaDays.prev)
+ : visRpc(null, prevFrom.toISOString(), currentFrom.toISOString()),
]);
if (curRes.error) throw new Error(curRes.error.message);
if (prevRes.error) throw new Error(prevRes.error.message);
@@ -2015,10 +2188,12 @@ export async function getShareOfVoiceData(
dateFrom?: string;
dateTo?: string;
topicId?: string;
+ days?: DayWindow;
},
): Promise<ShareOfVoiceData> {
const supabase = await createClient();
const p_models = modelFilterArray(opts?.model);
+ const daily = dailyWindow(opts);
const baseArgs = {
p_brand_id: brandId,
@@ -2028,6 +2203,21 @@ export async function getShareOfVoiceData(
p_prompt_id: undefined as string | undefined,
p_topic_id: opts?.topicId ?? undefined,
};
+ const sovRpc = (win: { dayFrom?: string; dayTo?: string } | null, from?: string, to?: string) =>
+ win
+ ? supabase.rpc('share_of_voice_aggregates_daily', {
+ p_brand_id: brandId,
+ p_platform: undefined as string | undefined,
+ p_models,
+ p_region: opts?.region ?? undefined,
+ p_day_from: win.dayFrom,
+ p_day_to: win.dayTo,
+ })
+ : supabase.rpc('share_of_voice_aggregates', {
+ ...baseArgs,
+ p_date_from: from,
+ p_date_to: to,
+ });
// Current-period aggregate + previous-period aggregate run in parallel —
// both server-side, no row transfer or JS reduce. The previous-period
@@ -2045,18 +2235,15 @@ export async function getShareOfVoiceData(
}
const duration = currentTo.getTime() - currentFrom.getTime();
const prevFrom = new Date(currentFrom.getTime() - duration);
+ const deltaDays = daily ? deltaDayWindows(daily) : null;
const [{ data: curData, error: curErr }, { data: prevData, error: prevErr }] = await Promise.all([
- supabase.rpc('share_of_voice_aggregates', {
- ...baseArgs,
- p_date_from: opts?.dateFrom ?? undefined,
- p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? undefined,
- }),
- supabase.rpc('share_of_voice_aggregates', {
- ...baseArgs,
- p_date_from: prevFrom.toISOString(),
- p_date_to: currentFrom.toISOString(),
- }),
+ daily
+ ? sovRpc(daily)
+ : sovRpc(null, opts?.dateFrom ?? undefined, expandDateToEndOfDay(opts?.dateTo) ?? undefined),
+ deltaDays
+ ? sovRpc(deltaDays.prev)
+ : sovRpc(null, prevFrom.toISOString(), currentFrom.toISOString()),
]);
if (curErr) throw new Error(curErr.message);
if (prevErr) throw new Error(prevErr.message);
@@ -2215,9 +2402,11 @@ export async function getVisibilityRateTrend(
dateFrom?: string;
dateTo?: string;
topicId?: string;
+ days?: DayWindow;
},
): Promise<VisibilityRateTrendData> {
const supabase = await createClient();
+ const daily = dailyWindow(opts);
// No explicit lower bound = the "All time" preset: the summary covers
// everything (matching the leaderboard) and the chart plots an expanding
// cumulative window instead of a fixed-length rolling one.
@@ -2247,6 +2436,17 @@ export async function getVisibilityRateTrend(
p_date_to: to,
p_topic_id: opts?.topicId ?? undefined,
});
+ const dayArgs = (dayFrom: string | undefined, dayTo: string | undefined) => ({
+ p_brand_id: brandId,
+ p_platform: undefined as string | undefined,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? undefined,
+ p_day_from: dayFrom,
+ p_day_to: dayTo,
+ });
+ // Day-window equivalents of the three timestamp windows above: display,
+ // warm-up-extended fetch range, and the previous window for the delta.
+ const deltaDays = daily?.dayFrom ? deltaDayWindows(daily) : null;
const [
{ data: brand },
@@ -2262,11 +2462,22 @@ export async function getVisibilityRateTrend(
// The chart plots a rolling window per day, so the earliest displayed
// days need trailing data from before the display range (all-time needs
// no warm-up — the window expands from the first row).
- supabase.rpc('visibility_rate_trend', rateArgs(prevFrom, dateTo)),
- supabase.rpc('ai_visibility_aggregates', rateArgs(boundedFrom, dateTo)),
- prevFrom && prevTo
- ? supabase.rpc('ai_visibility_aggregates', rateArgs(prevFrom, prevTo))
- : Promise.resolve({ data: null, error: new Error('no previous window') }),
+ daily
+ ? supabase.rpc('visibility_rate_trend_daily', dayArgs(deltaDays?.prev.dayFrom, daily.dayTo))
+ : supabase.rpc('visibility_rate_trend', rateArgs(prevFrom, dateTo)),
+ daily
+ ? supabase.rpc('ai_visibility_aggregates_daily', dayArgs(daily.dayFrom, daily.dayTo))
+ : supabase.rpc('ai_visibility_aggregates', rateArgs(boundedFrom, dateTo)),
+ daily
+ ? deltaDays
+ ? supabase.rpc(
+ 'ai_visibility_aggregates_daily',
+ dayArgs(deltaDays.prev.dayFrom, deltaDays.prev.dayTo),
+ )
+ : Promise.resolve({ data: null, error: new Error('no previous window') })
+ : prevFrom && prevTo
+ ? supabase.rpc('ai_visibility_aggregates', rateArgs(prevFrom, prevTo))
+ : Promise.resolve({ data: null, error: new Error('no previous window') }),
]);
if (rpcRes.error) throw new Error(rpcRes.error.message);
if (visCurRes.error) throw new Error(visCurRes.error.message);
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index a497ba0f4..6aa262e76 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -12,31 +12,6 @@ export type Database = {
__InternalSupabase: {
PostgrestVersion: "14.1"
}
- graphql_public: {
- Tables: {
- [_ in never]: never
- }
- Views: {
- [_ in never]: never
- }
- Functions: {
- graphql: {
- Args: {
- extensions?: Json
- operationName?: string
- query?: string
- variables?: Json
- }
- Returns: Json
- }
- }
- Enums: {
- [_ in never]: never
- }
- CompositeTypes: {
- [_ in never]: never
- }
- }
public: {
Tables: {
agent_conversations: {
@@ -485,6 +460,30 @@ export type Database = {
},
]
}
+ citation_urls: {
+ Row: {
+ domain: string
+ first_seen_at: string
+ id: number
+ title: string | null
+ url: string
+ }
+ Insert: {
+ domain: string
+ first_seen_at?: string
+ id?: never
+ title?: string | null
+ url: string
+ }
+ Update: {
+ domain?: string
+ first_seen_at?: string
+ id?: never
+ title?: string | null
+ url?: string
+ }
+ Relationships: []
+ }
cloro_pending_tasks: {
Row: {
brand_id: string
@@ -882,6 +881,215 @@ export type Database = {
},
]
}
+ insights_brand_daily: {
+ Row: {
+ answer_count: number
+ brand_id: string
+ citation_answers: number
+ day: string
+ max_created_at: string
+ mention_answers: number
+ mentioning_answers: number
+ model_used: string | null
+ platform: string | null
+ position_count: number
+ positive_count: number
+ region: string | null
+ sum_inv_position: number | null
+ sum_visibility: number
+ sum_visibility_visible: number
+ total_citations: number
+ total_mentions: number
+ }
+ Insert: {
+ answer_count: number
+ brand_id: string
+ citation_answers: number
+ day: string
+ max_created_at: string
+ mention_answers: number
+ mentioning_answers: number
+ model_used?: string | null
+ platform?: string | null
+ position_count: number
+ positive_count: number
+ region?: string | null
+ sum_inv_position?: number | null
+ sum_visibility: number
+ sum_visibility_visible: number
+ total_citations: number
+ total_mentions: number
+ }
+ Update: {
+ answer_count?: number
+ brand_id?: string
+ citation_answers?: number
+ day?: string
+ max_created_at?: string
+ mention_answers?: number
+ mentioning_answers?: number
+ model_used?: string | null
+ platform?: string | null
+ position_count?: number
+ positive_count?: number
+ region?: string | null
+ sum_inv_position?: number | null
+ sum_visibility?: number
+ sum_visibility_visible?: number
+ total_citations?: number
+ total_mentions?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "insights_brand_daily_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ insights_competitor_daily: {
+ Row: {
+ answer_count: number
+ brand_id: string
+ citation_answers: number
+ competitor_id: string
+ day: string
+ mention_answers: number
+ model_used: string | null
+ platform: string | null
+ position_count: number
+ region: string | null
+ sum_inv_position: number | null
+ sum_visibility: number | null
+ total_citations: number
+ total_mentions: number
+ }
+ Insert: {
+ answer_count: number
+ brand_id: string
+ citation_answers: number
+ competitor_id: string
+ day: string
+ mention_answers: number
+ model_used?: string | null
+ platform?: string | null
+ position_count: number
+ region?: string | null
+ sum_inv_position?: number | null
+ sum_visibility?: number | null
+ total_citations: number
+ total_mentions: number
+ }
+ Update: {
+ answer_count?: number
+ brand_id?: string
+ citation_answers?: number
+ competitor_id?: string
+ day?: string
+ mention_answers?: number
+ model_used?: string | null
+ platform?: string | null
+ position_count?: number
+ region?: string | null
+ sum_inv_position?: number | null
+ sum_visibility?: number | null
+ total_citations?: number
+ total_mentions?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "insights_competitor_daily_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ insights_competitor_prompt_daily: {
+ Row: {
+ brand_id: string
+ competitor_id: string
+ day: string
+ model_used: string | null
+ platform: string | null
+ prompt_id: string
+ region: string | null
+ }
+ Insert: {
+ brand_id: string
+ competitor_id: string
+ day: string
+ model_used?: string | null
+ platform?: string | null
+ prompt_id: string
+ region?: string | null
+ }
+ Update: {
+ brand_id?: string
+ competitor_id?: string
+ day?: string
+ model_used?: string | null
+ platform?: string | null
+ prompt_id?: string
+ region?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "insights_competitor_prompt_daily_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ insights_prompt_daily: {
+ Row: {
+ answer_count: number
+ brand_id: string
+ day: string
+ has_citation: boolean
+ has_mention: boolean
+ model_used: string | null
+ platform: string | null
+ prompt_id: string
+ region: string | null
+ }
+ Insert: {
+ answer_count: number
+ brand_id: string
+ day: string
+ has_citation: boolean
+ has_mention: boolean
+ model_used?: string | null
+ platform?: string | null
+ prompt_id: string
+ region?: string | null
+ }
+ Update: {
+ answer_count?: number
+ brand_id?: string
+ day?: string
+ has_citation?: boolean
+ has_mention?: boolean
+ model_used?: string | null
+ platform?: string | null
+ prompt_id?: string
+ region?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "insights_prompt_daily_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
integration_connections: {
Row: {
composio_account_id: string | null
@@ -1255,6 +1463,52 @@ export type Database = {
},
]
}
+ prompt_result_citations: {
+ Row: {
+ brand_id: string
+ created_at: string
+ position: number
+ prompt_result_id: string
+ url_id: number
+ }
+ Insert: {
+ brand_id: string
+ created_at: string
+ position: number
+ prompt_result_id: string
+ url_id: number
+ }
+ Update: {
+ brand_id?: string
+ created_at?: string
+ position?: number
+ prompt_result_id?: string
+ url_id?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "prompt_result_citations_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "prompt_result_citations_prompt_result_id_fkey"
+ columns: ["prompt_result_id"]
+ isOneToOne: false
+ referencedRelation: "prompt_results"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "prompt_result_citations_url_id_fkey"
+ columns: ["url_id"]
+ isOneToOne: false
+ referencedRelation: "citation_urls"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
prompt_result_shopping_cards: {
Row: {
brand_id: string
@@ -2141,6 +2395,24 @@ export type Database = {
}
Returns: Json
}
+ ai_visibility_aggregates_daily: {
+ Args: {
+ p_brand_id: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_platform?: string
+ p_region?: string
+ }
+ Returns: Json
+ }
+ citation_url_ids: {
+ Args: { p_urls: Json }
+ Returns: {
+ id: number
+ url: string
+ }[]
+ }
citations_domains: {
Args: {
p_brand_id: string
@@ -2207,6 +2479,31 @@ export type Database = {
}
Returns: Json
}
+ competitor_aggregates_daily: {
+ Args: {
+ p_brand_id: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_platform?: string
+ p_region?: string
+ }
+ Returns: Json
+ }
+ content_opportunity_aggregates: {
+ Args: {
+ p_brand_id: string
+ p_impact?: string
+ p_q?: string
+ p_status?: string
+ p_type?: string
+ }
+ Returns: {
+ avg_score: number
+ high_impact_count: number
+ sent_count: number
+ }[]
+ }
get_latest_prompt_results:
| {
Args: { p_brand_id: string; p_platform?: string }
@@ -2297,6 +2594,17 @@ export type Database = {
}
Returns: Json
}
+ insights_aggregates_daily: {
+ Args: {
+ p_brand_id: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_platform?: string
+ p_region?: string
+ }
+ Returns: Json
+ }
insights_filter_options: {
Args: { p_brand_id: string }
Returns: {
@@ -2331,6 +2639,10 @@ export type Database = {
visible_runs: number
}[]
}
+ refresh_insights_daily: {
+ Args: { p_brand_id: string; p_day_from: string; p_day_to: string }
+ Returns: undefined
+ }
report_citation_evidence: {
Args: {
p_brand_id: string
@@ -2347,16 +2659,19 @@ export type Database = {
url: string
}[]
}
- report_query_fanout_engines: {
- Args: {
- p_brand_id: string
- p_date_from: string
- p_date_to: string
- }
+ report_prompt_performance: {
+ Args: { p_brand_id: string; p_date_from: string; p_date_to: string }
Returns: {
- answers_with_fanout: number
- distinct_queries: number
- engine: string
+ citation_answers: number
+ mention_answers: number
+ pos_n: number
+ pos_sum: number
+ prompt_id: string
+ prompt_text: string
+ runs: number
+ sum_visibility: number
+ total_mentions: number
+ visible_runs: number
}[]
}
report_query_fanout: {
@@ -2372,23 +2687,12 @@ export type Database = {
times_searched: number
}[]
}
- report_prompt_performance: {
- Args: {
- p_brand_id: string
- p_date_from: string
- p_date_to: string
- }
+ report_query_fanout_engines: {
+ Args: { p_brand_id: string; p_date_from: string; p_date_to: string }
Returns: {
- citation_answers: number
- mention_answers: number
- pos_n: number
- pos_sum: number
- prompt_id: string
- prompt_text: string
- runs: number
- sum_visibility: number
- total_mentions: number
- visible_runs: number
+ answers_with_fanout: number
+ distinct_queries: number
+ engine: string
}[]
}
report_topic_performance: {
@@ -2429,6 +2733,17 @@ export type Database = {
}
Returns: Json
}
+ share_of_voice_aggregates_daily: {
+ Args: {
+ p_brand_id: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_platform?: string
+ p_region?: string
+ }
+ Returns: Json
+ }
topics_overview_aggregates: {
Args: { p_brand_id: string }
Returns: {
@@ -2470,6 +2785,17 @@ export type Database = {
}
Returns: number
}
+ tracked_prompt_count_daily: {
+ Args: {
+ p_brand_id: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_platform?: string
+ p_region?: string
+ }
+ Returns: number
+ }
visibility_rate_trend: {
Args: {
p_brand_id: string
@@ -2482,6 +2808,17 @@ export type Database = {
}
Returns: Json
}
+ visibility_rate_trend_daily: {
+ Args: {
+ p_brand_id: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_platform?: string
+ p_region?: string
+ }
+ Returns: Json
+ }
visibility_trend_aggregates: {
Args: {
p_brand_id: string
@@ -2506,6 +2843,17 @@ export type Database = {
}
Returns: Json
}
+ visible_prompt_stats_daily: {
+ Args: {
+ p_brand_id: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_platform?: string
+ p_region?: string
+ }
+ Returns: Json
+ }
}
Enums: {
invitation_status: "pending" | "accepted" | "expired" | "revoked"
@@ -2635,9 +2983,6 @@ export type CompositeTypes<
: never
export const Constants = {
- graphql_public: {
- Enums: {},
- },
public: {
Enums: {
invitation_status: ["pending", "accepted", "expired", "revoked"],