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): visibility rate trend chart with per-brand lines and end-of-line logos (#571)

Gökhan Geyik546f031ab7b1
diff --git a/supabase/migrations/00039_visibility_rate_trend.sql b/supabase/migrations/00039_visibility_rate_trend.sql
new file mode 100644
index 000000000..8221f3472
--- /dev/null
+++ b/supabase/migrations/00039_visibility_rate_trend.sql
@@ -0,0 +1,93 @@
+-- Daily Visibility Rate series for the brand and each live competitor.
+--
+-- Powers the Insights "AI Visibility — Brand vs Competitors" trend chart:
+-- one line per entity, each day's value being the prompt-level rate for
+-- that day. Rules match the rest of the rate family:
+-- - a prompt is "visible" on a day when any of its runs that day carries
+-- a brand mention or citation (00027 semantics)
+-- - a competitor is "visible" on a prompt when its mention entry has a
+-- mention, citation or score (00028 semantics)
+-- - competitor rows only count while the competitor still exists (00035)
+-- - the denominator is the BRAND's per-day distinct prompt count, shared
+-- by every entity so lines are comparable (getCompetitorComparison rule)
+-- - chatgpt-shopping excluded (#155)
+--
+-- Days are UTC buckets. Rates are computed by the caller (visible/prompts),
+-- keeping all rounding in one place (the web action).
+
+CREATE OR REPLACE FUNCTION public.visibility_rate_trend(
+ p_brand_id uuid,
+ p_platform text DEFAULT NULL,
+ p_models text[] DEFAULT NULL,
+ p_region text DEFAULT NULL,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.prompt_id, pr.mention_count, pr.citation_count, pr.competitor_mentions,
+ (pr.created_at AT TIME ZONE 'UTC')::date AS day
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ AND (p_platform IS NULL OR pr.platform = p_platform)
+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))
+ AND (p_region IS NULL OR pr.region = p_region)
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ AND (p_topic_id IS NULL OR EXISTS (
+ SELECT 1 FROM public.prompts p
+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))
+ ),
+ brand_daily AS (
+ SELECT day,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ GROUP BY day
+ ),
+ comp_daily AS (
+ SELECT f.day,
+ cm.value->>'competitor_id' AS competitor_id,
+ COUNT(DISTINCT f.prompt_id)
+ FILTER (WHERE 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)
+ AS visible_prompts
+ FROM filtered f,
+ LATERAL jsonb_array_elements(
+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm
+ WHERE cm.value ? 'competitor_id'
+ AND EXISTS (
+ SELECT 1 FROM public.competitors c
+ WHERE c.id::text = cm.value->>'competitor_id'
+ AND c.brand_id = p_brand_id
+ )
+ GROUP BY f.day, cm.value->>'competitor_id'
+ )
+ SELECT COALESCE(
+ jsonb_agg(jsonb_build_object(
+ 'day', bd.day,
+ 'prompt_count', bd.prompt_count,
+ 'visible_prompts', bd.visible_prompts,
+ 'competitors', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'competitor_id', cd.competitor_id,
+ 'visible_prompts', cd.visible_prompts))
+ FROM comp_daily cd WHERE cd.day = bd.day),
+ '[]'::jsonb)
+ ) ORDER BY bd.day),
+ '[]'::jsonb)
+ FROM brand_daily bd;
+$$;
+
+GRANT EXECUTE ON FUNCTION public.visibility_rate_trend(uuid, text, text[], text, timestamptz, timestamptz, uuid)
+ TO authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index bf54e5ac9..c46344c05 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -4274,3 +4274,100 @@ ALTER TABLE "public"."prompt_results"
ADD COLUMN IF NOT EXISTS "mention_position" integer,
ADD COLUMN IF NOT EXISTS "mentioned_entity_count" integer;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00039_visibility_rate_trend.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Daily Visibility Rate series for the brand and each live competitor.
+--
+-- Powers the Insights "AI Visibility — Brand vs Competitors" trend chart:
+-- one line per entity, each day's value being the prompt-level rate for
+-- that day. Rules match the rest of the rate family:
+-- - a prompt is "visible" on a day when any of its runs that day carries
+-- a brand mention or citation (00027 semantics)
+-- - a competitor is "visible" on a prompt when its mention entry has a
+-- mention, citation or score (00028 semantics)
+-- - competitor rows only count while the competitor still exists (00035)
+-- - the denominator is the BRAND's per-day distinct prompt count, shared
+-- by every entity so lines are comparable (getCompetitorComparison rule)
+-- - chatgpt-shopping excluded (#155)
+--
+-- Days are UTC buckets. Rates are computed by the caller (visible/prompts),
+-- keeping all rounding in one place (the web action).
+
+CREATE OR REPLACE FUNCTION public.visibility_rate_trend(
+ p_brand_id uuid,
+ p_platform text DEFAULT NULL,
+ p_models text[] DEFAULT NULL,
+ p_region text DEFAULT NULL,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.prompt_id, pr.mention_count, pr.citation_count, pr.competitor_mentions,
+ (pr.created_at AT TIME ZONE 'UTC')::date AS day
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ AND (p_platform IS NULL OR pr.platform = p_platform)
+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))
+ AND (p_region IS NULL OR pr.region = p_region)
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ AND (p_topic_id IS NULL OR EXISTS (
+ SELECT 1 FROM public.prompts p
+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))
+ ),
+ brand_daily AS (
+ SELECT day,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ GROUP BY day
+ ),
+ comp_daily AS (
+ SELECT f.day,
+ cm.value->>'competitor_id' AS competitor_id,
+ COUNT(DISTINCT f.prompt_id)
+ FILTER (WHERE 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)
+ AS visible_prompts
+ FROM filtered f,
+ LATERAL jsonb_array_elements(
+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm
+ WHERE cm.value ? 'competitor_id'
+ AND EXISTS (
+ SELECT 1 FROM public.competitors c
+ WHERE c.id::text = cm.value->>'competitor_id'
+ AND c.brand_id = p_brand_id
+ )
+ GROUP BY f.day, cm.value->>'competitor_id'
+ )
+ SELECT COALESCE(
+ jsonb_agg(jsonb_build_object(
+ 'day', bd.day,
+ 'prompt_count', bd.prompt_count,
+ 'visible_prompts', bd.visible_prompts,
+ 'competitors', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'competitor_id', cd.competitor_id,
+ 'visible_prompts', cd.visible_prompts))
+ FROM comp_daily cd WHERE cd.day = bd.day),
+ '[]'::jsonb)
+ ) ORDER BY bd.day),
+ '[]'::jsonb)
+ FROM brand_daily bd;
+$$;
+
+GRANT EXECUTE ON FUNCTION public.visibility_rate_trend(uuid, text, text[], text, timestamptz, timestamptz, uuid)
+ TO authenticated;
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
index 05abfa325..fb76a320f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
@@ -15,14 +15,18 @@ import {
Cell,
BarChart,
Bar,
+ LineChart,
+ Line,
} from 'recharts';
import type {
CompetitorComparisonEntry,
ProviderComparisonRow,
VisibilityTrendPoint,
+ VisibilityRateTrendData,
SoVByPlatform,
SoVTrendPoint,
} from '@/lib/actions/tracking';
+import { getFaviconUrl } from '@/lib/favicon';
// ─── Adaptive Y-axis ─────────────────────────────────────────────────────────
// Visibility scores are theoretically 0–100 but realistic values for most
@@ -386,6 +390,217 @@ function CompetitorTooltip({
);
}
+// ─── Visibility Rate trend (one line per brand, logo at the line's end) ──────
+
+// 5 lines total, matching the leaderboard: the own brand + top 4 competitors.
+// Fixed color order across the five lines: green (own brand), then navy,
+// purple, orange, red for the competitors by rate.
+const RATE_TREND_PALETTE = ['#1e3a8a', '#a855f7', '#f97316', '#ef4444'];
+const RATE_TREND_MAX_COMPETITORS = 4;
+const OWN_BRAND_COLOR = '#22c55e';
+
+/** Circle-clipped logo rendered on a line's last data point. */
+function LogoDot(props: {
+ cx?: number;
+ cy?: number;
+ index?: number;
+ lastIndex: number;
+ color: string;
+ logoUrl: string;
+ entityKey: string;
+ dimmed?: boolean;
+}) {
+ const { cx, cy, index, lastIndex, color, logoUrl, entityKey, dimmed } = props;
+ if (index !== lastIndex || cx == null || cy == null) return <g />;
+ const r = 11;
+ const clipId = `rate-trend-logo-${entityKey}`;
+ return (
+ <g opacity={dimmed ? 0.25 : 1}>
+ <defs>
+ <clipPath id={clipId}>
+ <circle cx={cx} cy={cy} r={r - 2.5} />
+ </clipPath>
+ </defs>
+ <circle cx={cx} cy={cy} r={r} fill="#ffffff" stroke={color} strokeWidth={2} />
+ <image
+ href={logoUrl}
+ x={cx - (r - 2.5)}
+ y={cy - (r - 2.5)}
+ width={(r - 2.5) * 2}
+ height={(r - 2.5) * 2}
+ clipPath={`url(#${clipId})`}
+ preserveAspectRatio="xMidYMid slice"
+ />
+ </g>
+ );
+}
+
+export function VisibilityRateTrendChart({ data }: { data: VisibilityRateTrendData }) {
+ const { entities, points } = data;
+ // Hovering a line (or its legend entry) brings it forward and dims the rest.
+ const [hoveredKey, setHoveredKey] = useState<string | null>(null);
+
+ if (points.length === 0) {
+ return (
+ <div className="flex items-center justify-center h-[280px] text-sm text-muted-foreground">
+ No visibility data for this period yet
+ </div>
+ );
+ }
+
+ // Own brand always plots; competitors capped by period-average rate so a
+ // long roster doesn't turn the chart into spaghetti.
+ const avgRate = (key: string) =>
+ points.reduce((sum, p) => sum + (p.values[key] ?? 0), 0) / points.length;
+ const shown = [
+ ...entities.filter((e) => e.isOwnBrand),
+ ...entities
+ .filter((e) => !e.isOwnBrand)
+ .sort((a, b) => avgRate(b.key) - avgRate(a.key))
+ .slice(0, RATE_TREND_MAX_COMPETITORS),
+ ].map((entity, i) => ({
+ ...entity,
+ // Own brand is index 0, so competitor #1 (highest rate) starts the
+ // palette at navy.
+ color: entity.isOwnBrand
+ ? OWN_BRAND_COLOR
+ : RATE_TREND_PALETTE[(i - 1) % RATE_TREND_PALETTE.length],
+ logoUrl: entity.logoUrl ?? (entity.domain ? getFaviconUrl(entity.domain, 64) : ''),
+ }));
+
+ const chartData = points.map((p) => ({ date: p.date, ...p.values }));
+ const lastIndex = points.length - 1;
+
+ // Y axis ticks run 5, 15, 25, … and the top one sits just above the
+ // highest rate in view (60% peak → axis ends at 65%), so the lines use
+ // the full canvas instead of being squashed under an always-100% scale.
+ const dataMax = Math.max(0, ...shown.flatMap((e) => points.map((p) => p.values[e.key] ?? 0)));
+ let yTop = 5;
+ while (yTop <= dataMax) yTop += 10;
+ const yTicks: number[] = [];
+ for (let tick = 5; tick <= yTop; tick += 10) yTicks.push(tick);
+
+ return (
+ <div className="flex flex-col gap-3">
+ <ChartContainer height={320}>
+ {(width) => (
+ <LineChart
+ width={width}
+ height={320}
+ data={chartData}
+ margin={{ top: 8, right: 26, left: -24, bottom: 0 }}
+ >
+ <XAxis
+ dataKey="date"
+ tick={{ fontSize: 11 }}
+ tickLine={false}
+ axisLine={false}
+ className="fill-muted-foreground"
+ />
+ <YAxis
+ domain={[0, yTop]}
+ ticks={yTicks}
+ tick={{ fontSize: 11 }}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={(v: number) => `${v}%`}
+ className="fill-muted-foreground"
+ />
+ <Tooltip
+ isAnimationActive={false}
+ content={({ active, payload, label }) => {
+ if (!active || !payload?.length) return null;
+ const ordered = [...payload].sort(
+ (a, b) => ((b.value as number) ?? 0) - ((a.value as number) ?? 0),
+ );
+ return (
+ <div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">
+ <p className="font-medium text-foreground mb-1">{label}</p>
+ {ordered.map((entry) => {
+ const entity = shown.find((e) => e.key === entry.dataKey);
+ if (!entity) return null;
+ return (
+ <div key={entity.key} className="flex items-center gap-2">
+ <span
+ className="inline-block h-2 w-2 rounded-full shrink-0"
+ style={{ backgroundColor: entity.color }}
+ />
+ <span className="text-muted-foreground">{entity.name}:</span>
+ <span className="font-medium text-foreground">{entry.value}%</span>
+ </div>
+ );
+ })}
+ </div>
+ );
+ }}
+ />
+ {/* Render order = z-order: lines are drawn lowest-rate first so
+ when end-of-line logos overlap, the higher rate sits on top.
+ A hovered line always wins. */}
+ {[...shown]
+ .sort((a, b) => {
+ if (a.key === hoveredKey) return 1;
+ if (b.key === hoveredKey) return -1;
+ return (
+ (points[lastIndex]?.values[a.key] ?? 0) - (points[lastIndex]?.values[b.key] ?? 0)
+ );
+ })
+ .map((entity) => {
+ const dimmed = hoveredKey !== null && hoveredKey !== entity.key;
+ return (
+ <Line
+ key={entity.key}
+ type="monotone"
+ dataKey={entity.key}
+ stroke={entity.color}
+ strokeOpacity={dimmed ? 0.15 : 1}
+ strokeWidth={entity.key === hoveredKey ? 3 : entity.isOwnBrand ? 2.5 : 1.5}
+ isAnimationActive={false}
+ onMouseEnter={() => setHoveredKey(entity.key)}
+ onMouseLeave={() => setHoveredKey(null)}
+ dot={
+ <LogoDot
+ lastIndex={lastIndex}
+ color={entity.color}
+ logoUrl={entity.logoUrl}
+ entityKey={entity.key}
+ dimmed={dimmed}
+ />
+ }
+ activeDot={{ r: 3 }}
+ />
+ );
+ })}
+ </LineChart>
+ )}
+ </ChartContainer>
+
+ <ul className="flex flex-wrap justify-center gap-x-4 gap-y-1.5">
+ {shown.map((entity) => (
+ <li
+ key={entity.key}
+ className="flex cursor-default items-center gap-1.5 text-xs transition-opacity"
+ style={{
+ opacity: hoveredKey !== null && hoveredKey !== entity.key ? 0.35 : 1,
+ }}
+ onMouseEnter={() => setHoveredKey(entity.key)}
+ onMouseLeave={() => setHoveredKey(null)}
+ >
+ <span
+ className="h-2.5 w-2.5 shrink-0 rounded-sm"
+ style={{ background: entity.color }}
+ aria-hidden
+ />
+ <span className={entity.isOwnBrand ? 'font-medium' : 'text-muted-foreground'}>
+ {entity.name}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
export function CompetitorChart({
providerRows,
brands,
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index b5ea79075..64947fc9b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -7,10 +7,13 @@ import { createPortal } from 'react-dom';
import { useTranslations } from 'next-intl';
import dynamic from 'next/dynamic';
import { Skeleton } from '@/components/ui/skeleton';
-const CompetitorChart = dynamic(() => import('./_charts').then((m) => m.CompetitorChart), {
- ssr: false,
- loading: () => <Skeleton className="h-64 w-full" />,
-});
+const VisibilityRateTrendChart = dynamic(
+ () => import('./_charts').then((m) => m.VisibilityRateTrendChart),
+ {
+ ssr: false,
+ loading: () => <Skeleton className="h-64 w-full" />,
+ },
+);
const CompetitorLeaderboard = dynamic(
() => import('./_charts').then((m) => m.CompetitorLeaderboard),
@@ -39,6 +42,8 @@ import { MetricBreakdownSheet } from './_metric-breakdown-sheet';
import { useBrandStore } from '@/stores/use-brand-store';
import {
getInsightsData,
+ getVisibilityRateTrend,
+ type VisibilityRateTrendData,
triggerTrackingCheck,
getJobStatus,
cancelTrackingJob,
@@ -932,6 +937,7 @@ export default function InsightsPage() {
const [availableModels, setAvailableModels] = useState<string[]>([]);
const [availableTopics, setAvailableTopics] = useState<Topic[]>([]);
const [competitorData, setCompetitorData] = useState<CompetitorComparisonData | null>(null);
+ const [rateTrend, setRateTrend] = useState<VisibilityRateTrendData | null>(null);
const [sovData, setSovData] = useState<ShareOfVoiceData | null>(null);
const [recommendations, setRecommendations] = useState<InsightsRecommendations | null>(null);
const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);
@@ -963,10 +969,17 @@ export default function InsightsPage() {
// run in a real server-side Promise.all (one round trip instead of
// five serialized POSTs), and "has any data" comes from a cheap
// count instead of an unbounded full-table scan.
- const insights = await getInsightsData(brand.id, {
- ...filterOpts,
- checkUnfiltered: hasFilters,
- });
+ // The trend chart follows the page filters exactly — same window as
+ // every other number on the page, so the headline rate never
+ // contradicts the KPI header.
+ const [insights, trend] = await Promise.all([
+ getInsightsData(brand.id, {
+ ...filterOpts,
+ checkUnfiltered: hasFilters,
+ }),
+ getVisibilityRateTrend(brand.id, filterOpts).catch(() => null),
+ ]);
+ setRateTrend(trend && trend.points.length > 0 ? trend : null);
setSummary(insights.summary);
setTrackedPrompts(insights.trackedPrompts);
setVisibilityRate(insights.visibilityRate);
@@ -1478,16 +1491,61 @@ export default function InsightsPage() {
<div className="grid grid-cols-1 gap-4 lg:grid-cols-5">
<Card className="lg:col-span-3">
<CardHeader className="pb-2">
- <CardTitle className="flex items-center gap-2 text-sm font-medium">
- <Users className="h-4 w-4" />
- AI Visibility — Brand vs Competitors
- </CardTitle>
+ {rateTrend ? (
+ <div>
+ <div className="text-3xl font-bold tabular-nums">
+ {rateTrend.summary.rate}%
+ </div>
+ <div className="mt-1 flex items-center gap-2 text-xs">
+ {rateTrend.summary.change !== null && (
+ <span
+ className={cn(
+ 'flex items-center gap-0.5 font-medium',
+ rateTrend.summary.change >= 0
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : 'text-red-600 dark:text-red-400',
+ )}
+ >
+ {rateTrend.summary.change >= 0 ? (
+ <TrendingUp className="h-3 w-3" />
+ ) : (
+ <TrendingDown className="h-3 w-3" />
+ )}
+ {rateTrend.summary.change >= 0 ? '+' : ''}
+ {rateTrend.summary.change} pts
+ </span>
+ )}
+ <span className="text-muted-foreground">
+ vs{' '}
+ {new Date(rateTrend.summary.prevFrom).toLocaleDateString('en-US', {
+ month: 'short',
+ day: '2-digit',
+ year: 'numeric',
+ })}{' '}
+ –{' '}
+ {new Date(rateTrend.summary.prevTo).toLocaleDateString('en-US', {
+ month: 'short',
+ day: '2-digit',
+ year: 'numeric',
+ })}
+ </span>
+ </div>
+ </div>
+ ) : (
+ <CardTitle className="flex items-center gap-2 text-sm font-medium">
+ <Users className="h-4 w-4" />
+ AI Visibility — Brand vs Competitors
+ </CardTitle>
+ )}
</CardHeader>
<CardContent>
- <CompetitorChart
- providerRows={competitorData.providerRows}
- brands={competitorData.brands}
- />
+ {rateTrend ? (
+ <VisibilityRateTrendChart data={rateTrend} />
+ ) : (
+ <div className="flex items-center justify-center h-[280px] text-sm text-muted-foreground">
+ No visibility data for this period yet
+ </div>
+ )}
</CardContent>
</Card>
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index c8e263d47..6462b68e7 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -1955,6 +1955,170 @@ export async function getVisibilityTrend(
return points;
}
+// ─── Visibility Rate trend (brand + each competitor) ────────────────────────
+
+export interface VisibilityRateTrendEntity {
+ /** 'you' for the own brand, competitor id otherwise. */
+ key: string;
+ name: string;
+ isOwnBrand: boolean;
+ /** Domain used for the favicon fallback at the line's end. */
+ domain: string | null;
+ /** Explicit logo (own brand only); falls back to the domain favicon. */
+ logoUrl: string | null;
+}
+
+export interface VisibilityRateTrendPoint {
+ /** Short label for the X axis, e.g. "Jul 28". */
+ date: string;
+ /** Per-entity rate for the day, keyed by entity key. 0 = tracked but not visible. */
+ values: Record<string, number>;
+}
+
+export interface VisibilityRateTrendSummary {
+ /** Overall rate for the charted window (distinct prompts, not a daily average). */
+ rate: number;
+ /** Rate over the equal-length window immediately before; null without data. */
+ prevRate: number | null;
+ /** rate − prevRate in points, one decimal; null when prevRate is null. */
+ change: number | null;
+ /** ISO bounds of the previous window, for the "vs <range>" label. */
+ prevFrom: string;
+ prevTo: string;
+}
+
+export interface VisibilityRateTrendData {
+ entities: VisibilityRateTrendEntity[];
+ points: VisibilityRateTrendPoint[];
+ summary: VisibilityRateTrendSummary;
+}
+
+interface VisibilityRateTrendRow {
+ day: string;
+ prompt_count: number;
+ visible_prompts: number;
+ competitors: { competitor_id: string; visible_prompts: number }[];
+}
+
+/**
+ * Daily Visibility Rate series for the brand and each live competitor
+ * (visibility_rate_trend RPC, migration 00039). Every entity divides by the
+ * brand's per-day prompt count — the shared-denominator rule from
+ * getCompetitorComparison — so the lines are directly comparable.
+ * Defaults to the last 7 days when no explicit range is given.
+ */
+export async function getVisibilityRateTrend(
+ brandId: string,
+ opts?: {
+ model?: string;
+ region?: string;
+ dateFrom?: string;
+ dateTo?: string;
+ topicId?: string;
+ },
+): Promise<VisibilityRateTrendData> {
+ const supabase = await createClient();
+ const dateFrom = opts?.dateFrom ?? new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
+ const dateTo = expandDateToEndOfDay(opts?.dateTo) ?? new Date().toISOString();
+
+ // Equal-length window immediately before, for the headline delta.
+ const windowMs = new Date(dateTo).getTime() - new Date(dateFrom).getTime();
+ const prevFrom = new Date(new Date(dateFrom).getTime() - windowMs).toISOString();
+ const prevTo = dateFrom;
+
+ const rateArgs = (from: string, to: string) => ({
+ p_brand_id: brandId,
+ p_platform: null as string | null,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? null,
+ p_date_from: from,
+ p_date_to: to,
+ p_topic_id: opts?.topicId ?? null,
+ });
+
+ const [
+ { data: brand },
+ { data: brandDomains },
+ { data: competitors },
+ rpcRes,
+ curStats,
+ curTracked,
+ prevStats,
+ prevTracked,
+ ] = await Promise.all([
+ supabase.from('brands').select('name, logo_url').eq('id', brandId).single(),
+ supabase.from('brand_domains').select('domain, is_primary').eq('brand_id', brandId),
+ supabase.from('competitors').select('id, name, domain').eq('brand_id', brandId),
+ supabase.rpc('visibility_rate_trend', rateArgs(dateFrom, dateTo)),
+ supabase.rpc('visible_prompt_stats', rateArgs(dateFrom, dateTo)),
+ supabase.rpc('tracked_prompt_count', rateArgs(dateFrom, dateTo)),
+ supabase.rpc('visible_prompt_stats', rateArgs(prevFrom, prevTo)),
+ supabase.rpc('tracked_prompt_count', rateArgs(prevFrom, prevTo)),
+ ]);
+ if (rpcRes.error) throw new Error(rpcRes.error.message);
+
+ const rows = (rpcRes.data ?? []) as unknown as VisibilityRateTrendRow[];
+ const rate = (visible: number, total: number) =>
+ total > 0 ? Math.round((visible / total) * 1000) / 10 : 0;
+
+ const primaryDomain =
+ (brandDomains ?? []).find((d) => d.is_primary)?.domain ?? brandDomains?.[0]?.domain ?? null;
+
+ const entities: VisibilityRateTrendEntity[] = [
+ {
+ key: 'you',
+ name: brand?.name ?? 'You',
+ isOwnBrand: true,
+ domain: primaryDomain,
+ logoUrl: brand?.logo_url ?? null,
+ },
+ ...(competitors ?? []).map((c) => ({
+ key: c.id,
+ name: c.name,
+ isOwnBrand: false,
+ domain: c.domain || null,
+ logoUrl: null,
+ })),
+ ];
+
+ const points: VisibilityRateTrendPoint[] = rows.map((row) => {
+ const values: Record<string, number> = {
+ you: rate(row.visible_prompts, row.prompt_count),
+ };
+ const byId = new Map(row.competitors.map((c) => [c.competitor_id, c.visible_prompts]));
+ for (const c of competitors ?? []) {
+ values[c.id] = rate(byId.get(c.id) ?? 0, row.prompt_count);
+ }
+ return {
+ date: new Date(row.day + 'T00:00:00').toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ }),
+ values,
+ };
+ });
+
+ // Headline: overall window rate (distinct prompts over the whole window —
+ // not an average of the daily points) plus the delta vs the previous
+ // equal-length window, same RPC pair as the Insights KPI header.
+ const curVisible = (curStats.data as { visible_prompts?: number } | null)?.visible_prompts ?? 0;
+ const curCount = (curTracked.data as number | null) ?? 0;
+ const prevVisible = (prevStats.data as { visible_prompts?: number } | null)?.visible_prompts ?? 0;
+ const prevCount = (prevTracked.data as number | null) ?? 0;
+ const headlineRate = rate(curVisible, curCount);
+ const prevRate = prevCount > 0 ? rate(prevVisible, prevCount) : null;
+
+ const summary: VisibilityRateTrendSummary = {
+ rate: headlineRate,
+ prevRate,
+ change: prevRate === null ? null : Math.round((headlineRate - prevRate) * 10) / 10,
+ prevFrom,
+ prevTo,
+ };
+
+ return { entities, points, summary };
+}
+
// ─── Head-to-Head Competitor Comparison ─────────────────────────────────────
export interface HeadToHeadPromptRow {
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index b528a18d3..a3aa5578b 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1486,6 +1486,18 @@ export type Database = {
};
Returns: Json;
};
+ visibility_rate_trend: {
+ Args: {
+ p_brand_id: string;
+ p_platform?: string | null;
+ p_models?: string[] | null;
+ p_region?: string | null;
+ p_date_from?: string | null;
+ p_date_to?: string | null;
+ p_topic_id?: string | null;
+ };
+ Returns: Json;
+ };
visibility_trend_aggregates: {
Args: {
p_brand_id: string;