Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(traffic): compare AI visits with Google clicks on the AI Referral Trend card (#1176)
Cihana98c35c19011
diff --git a/supabase/migrations/00180_ai_traffic_google_trend.sql b/supabase/migrations/00180_ai_traffic_google_trend.sqlnew file mode 100644index 000000000..e1835c15f--- /dev/null+++ b/supabase/migrations/00180_ai_traffic_google_trend.sql@@ -0,0 +1,88 @@+-- ============================================================================+-- 00180: AI visits vs Google clicks (AT-008, part A)+-- ============================================================================+-- Spec §3.3: the AI Referral Trend card gets a "vs Google clicks" view. It+-- shows AI visits and Google organic clicks, each indexed to 100 at the+-- start of the range, with markers on the days actions entered the Action+-- Center and prompts were added. The AI line is the page's own trend; this+-- reads the rest, by UTC day like the trend's buckets:+--+-- * clicks: Search Console clicks per day, summed over the brand's queries+-- the way the Google clicks card sums them (00174);+-- * first_day / last_day: the first and latest day Search Console has rows+-- for the brand. Before the first the sync has no history (it keeps 90+-- days); after the latest Google hasn't reported yet (about two days+-- late, §3.01). The chart leaves both blank rather than drawing 0;+-- * markers: per day, the actions created in the Action Center and the+-- prompts added to the brand's sets.+--+-- Security invoker: gsc_query_stats, actions and prompts each have a member+-- select policy, so RLS decides the brand.++create or replace function public.ai_traffic_google_trend(+ p_brand_id uuid,+ p_since date,+ p_until date+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ select jsonb_build_object(+ 'first_day', (+ select min(g.date) from public.gsc_query_stats g where g.brand_id = p_brand_id+ ),+ 'last_day', (+ select max(g.date) from public.gsc_query_stats g where g.brand_id = p_brand_id+ ),+ 'clicks', coalesce((+ select jsonb_agg(jsonb_build_object('day', d.day, 'clicks', d.clicks) order by d.day)+ from (+ select g.date as day, sum(g.clicks)::bigint as clicks+ from public.gsc_query_stats g+ where g.brand_id = p_brand_id+ and g.date >= p_since+ and g.date <= p_until+ group by g.date+ ) d+ ), '[]'::jsonb),+ 'markers', coalesce((+ select jsonb_agg(+ jsonb_build_object('day', m.day, 'actions', m.actions, 'prompts', m.prompts)+ order by m.day+ )+ from (+ select+ e.day,+ count(*) filter (where e.kind = 'action') as actions,+ count(*) filter (where e.kind = 'prompt') as prompts+ from (+ select (a.created_at at time zone 'UTC')::date as day, 'action' as kind+ from public.actions a+ where a.brand_id = p_brand_id+ and a.created_at >= p_since::timestamp at time zone 'UTC'+ and a.created_at < (p_until + 1)::timestamp at time zone 'UTC'+ union all+ select (p.created_at at time zone 'UTC')::date, 'prompt'+ from public.prompts p+ join public.prompt_sets s on s.id = p.prompt_set_id+ where s.brand_id = p_brand_id+ and p.created_at >= p_since::timestamp at time zone 'UTC'+ and p.created_at < (p_until + 1)::timestamp at time zone 'UTC'+ ) e+ group by e.day+ ) m+ ), '[]'::jsonb)+ );+$$;++revoke all on function public.ai_traffic_google_trend(uuid, date, date) from public, anon;+grant execute on function public.ai_traffic_google_trend(uuid, date, date)+ to authenticated, service_role;++comment on function public.ai_traffic_google_trend(uuid, date, date) is+ 'AI Traffic "vs Google clicks" trend (AT-008, spec §3.3): Search Console clicks per UTC day, the first and latest day Search Console has rows for the brand, and per day the actions created in the Action Center and the prompts added. Security invoker: RLS decides the brand.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 63a316c55..747a757c6 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -24487,3 +24487,95 @@ comment on function public.ai_traffic_conversions(uuid, date, date, integer) isnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00180_ai_traffic_google_trend.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00180: AI visits vs Google clicks (AT-008, part A)+-- ============================================================================+-- Spec §3.3: the AI Referral Trend card gets a "vs Google clicks" view. It+-- shows AI visits and Google organic clicks, each indexed to 100 at the+-- start of the range, with markers on the days actions entered the Action+-- Center and prompts were added. The AI line is the page's own trend; this+-- reads the rest, by UTC day like the trend's buckets:+--+-- * clicks: Search Console clicks per day, summed over the brand's queries+-- the way the Google clicks card sums them (00174);+-- * first_day / last_day: the first and latest day Search Console has rows+-- for the brand. Before the first the sync has no history (it keeps 90+-- days); after the latest Google hasn't reported yet (about two days+-- late, §3.01). The chart leaves both blank rather than drawing 0;+-- * markers: per day, the actions created in the Action Center and the+-- prompts added to the brand's sets.+--+-- Security invoker: gsc_query_stats, actions and prompts each have a member+-- select policy, so RLS decides the brand.++create or replace function public.ai_traffic_google_trend(+ p_brand_id uuid,+ p_since date,+ p_until date+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ select jsonb_build_object(+ 'first_day', (+ select min(g.date) from public.gsc_query_stats g where g.brand_id = p_brand_id+ ),+ 'last_day', (+ select max(g.date) from public.gsc_query_stats g where g.brand_id = p_brand_id+ ),+ 'clicks', coalesce((+ select jsonb_agg(jsonb_build_object('day', d.day, 'clicks', d.clicks) order by d.day)+ from (+ select g.date as day, sum(g.clicks)::bigint as clicks+ from public.gsc_query_stats g+ where g.brand_id = p_brand_id+ and g.date >= p_since+ and g.date <= p_until+ group by g.date+ ) d+ ), '[]'::jsonb),+ 'markers', coalesce((+ select jsonb_agg(+ jsonb_build_object('day', m.day, 'actions', m.actions, 'prompts', m.prompts)+ order by m.day+ )+ from (+ select+ e.day,+ count(*) filter (where e.kind = 'action') as actions,+ count(*) filter (where e.kind = 'prompt') as prompts+ from (+ select (a.created_at at time zone 'UTC')::date as day, 'action' as kind+ from public.actions a+ where a.brand_id = p_brand_id+ and a.created_at >= p_since::timestamp at time zone 'UTC'+ and a.created_at < (p_until + 1)::timestamp at time zone 'UTC'+ union all+ select (p.created_at at time zone 'UTC')::date, 'prompt'+ from public.prompts p+ join public.prompt_sets s on s.id = p.prompt_set_id+ where s.brand_id = p_brand_id+ and p.created_at >= p_since::timestamp at time zone 'UTC'+ and p.created_at < (p_until + 1)::timestamp at time zone 'UTC'+ ) e+ group by e.day+ ) m+ ), '[]'::jsonb)+ );+$$;++revoke all on function public.ai_traffic_google_trend(uuid, date, date) from public, anon;+grant execute on function public.ai_traffic_google_trend(uuid, date, date)+ to authenticated, service_role;++comment on function public.ai_traffic_google_trend(uuid, date, date) is+ 'AI Traffic "vs Google clicks" trend (AT-008, spec §3.3): Search Console clicks per UTC day, the first and latest day Search Console has rows for the brand, and per day the actions created in the Action Center and the prompts added. Security invoker: RLS decides the brand.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex cdd30851b..bd9f5cd50 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3226,7 +3226,28 @@"showLast7Days": "Show last 7 days"},"trend": {- "fromAnalytics": "from Google Analytics"+ "fromAnalytics": "from Google Analytics",+ "tabs": {+ "platforms": "By platform",+ "google": "vs Google clicks"+ },+ "google": {+ "aiLine": "AI visits",+ "googleLine": "Google clicks",+ "withIndex": "{count} · index {index}",+ "notReported": "not reported yet",+ "noData": "no data",+ "actions": "{count, plural, one {# action} other {# actions}} entered the Action Center",+ "prompts": "{count, plural, one {# prompt} other {# prompts}} added",+ "daily": "Google reports clicks by day. Pick 7 days or longer to compare them with AI visits.",+ "showWeek": "Show last 7 days",+ "needsGsc": "The Google clicks line needs Google Search Console.",+ "failed": "Google clicks couldn't be loaded.",+ "noClicks": "No Google clicks for this range in Google Search Console.",+ "until": "Google clicks until {day}: Google reports about two days late.",+ "legend": "Each line starts at 100 on its first day with data. AI Overviews and AI Mode clicks are part of Google organic clicks and can't be separated.",+ "markers": "Dashed amber lines mark the days actions entered the Action Center or prompts were added."+ }},"platforms": {"engaged": "Engaged",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsxindex 29605d6ec..5ef9140ad 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx@@ -7,6 +7,9 @@ import { formatNumber } from '@/lib/format';import {AreaChart,Area,+ LineChart,+ Line,+ ReferenceLine,XAxis,YAxis,CartesianGrid,@@ -17,6 +20,7 @@ import {Cell,} from 'recharts';import type { TrafficTrendPoint } from '@/lib/actions/traffic';+import type { GoogleTrendPoint } from '@/lib/traffic-google-trend';// ─── Auto-sizing wrapper ─────────────────────────────────────────────────────@@ -283,6 +287,153 @@ export function ReferralTrendChart({);}+// ─── AI visits vs Google clicks (AT-008) ─────────────────────────────────────++/** The AI line in the platforms' indigo, Google's in its green, markers in amber. */+const AI_LINE = '#6366f1';+const GOOGLE_LINE = '#34a853';+const MARKER = '#f59e0b';+const BASELINE = '#94a3b8';++function GoogleTrendTooltip({+ active,+ payload,+ label,+ googleUntil,+ hasGoogle,+}: {+ active?: boolean;+ payload?: { payload: GoogleTrendPoint }[];+ label?: string;+ googleUntil: string | null;+ hasGoogle: boolean;+}) {+ const t = useTranslations('traffic.trend.google');+ if (!active || !payload?.length || !label) return null;+ const point = payload[0].payload;+ const line = (color: string, name: string, value: string) => (+ <div className="flex items-center gap-2">+ <span+ className="inline-block h-2 w-2 rounded-full shrink-0"+ style={{ backgroundColor: color }}+ />+ <span className="text-muted-foreground">{name}:</span>+ <span className="font-medium text-foreground">{value}</span>+ </div>+ );+ const indexed = (count: number, index: number | null) =>+ index === null+ ? formatNumber(count)+ : t('withIndex', { count: formatNumber(count), index: formatNumber(index) });+ return (+ <div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">+ <p className="font-medium text-foreground mb-1">+ {formatTrafficBucketDate(label, { withDay: true })}+ </p>+ {line(AI_LINE, t('aiLine'), indexed(point.visits, point.ai))}+ {hasGoogle &&+ line(+ GOOGLE_LINE,+ t('googleLine'),+ point.clicks === null+ ? googleUntil && point.date > googleUntil+ ? t('notReported')+ : t('noData')+ : indexed(point.clicks, point.google),+ )}+ {point.actions > 0 && (+ <p className="mt-1 text-muted-foreground">{t('actions', { count: point.actions })}</p>+ )}+ {point.prompts > 0 && (+ <p className="text-muted-foreground">{t('prompts', { count: point.prompts })}</p>+ )}+ </div>+ );+}++/**+ * AI visits and Google organic clicks, each indexed to 100 on its first day+ * with any (spec §3.3), with a dashed amber line on each day actions entered+ * the Action Center or prompts were added.+ */+export function GoogleTrendChart({+ points,+ googleUntil,+}: {+ points: GoogleTrendPoint[];+ /** Google's latest reported day, when the range runs past it. */+ googleUntil: string | null;+}) {+ const t = useTranslations('traffic.trend.google');+ if (!points.length) return null;+ const markerDays = points.filter((p) => p.actions > 0 || p.prompts > 0).map((p) => p.date);+ // Without Google's days (no Search Console) the legend shows the AI line alone.+ const hasGoogle = points.some((p) => p.google !== null);++ return (+ <ChartContainer height={220}>+ {(width) => (+ <LineChart+ width={width}+ height={220}+ data={points}+ margin={{ top: 4, right: 4, left: -24, bottom: 0 }}+ >+ <CartesianGrid strokeDasharray="3 3" className="stroke-border" vertical={false} />+ <XAxis+ dataKey="date"+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ tickFormatter={(v: string) => formatTrafficBucketDate(v)}+ />+ <YAxis+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ allowDecimals={false}+ />+ <ReferenceLine y={100} stroke={BASELINE} strokeDasharray="2 4" />+ {markerDays.map((day) => (+ <ReferenceLine key={day} x={day} stroke={MARKER} strokeDasharray="3 3" />+ ))}+ <Tooltip+ content={<GoogleTrendTooltip googleUntil={googleUntil} hasGoogle={hasGoogle} />}+ />+ <Legend+ iconType="circle"+ iconSize={8}+ wrapperStyle={{ fontSize: 11, paddingTop: 8 }}+ formatter={(value: string) => (value === 'ai' ? t('aiLine') : t('googleLine'))}+ />+ <Line+ type="monotone"+ dataKey="ai"+ name="ai"+ stroke={AI_LINE}+ strokeWidth={2}+ dot={false}+ activeDot={{ r: 3 }}+ />+ {hasGoogle && (+ <Line+ type="monotone"+ dataKey="google"+ name="google"+ stroke={GOOGLE_LINE}+ strokeWidth={2}+ dot={false}+ activeDot={{ r: 3 }}+ />+ )}+ </LineChart>+ )}+ </ChartContainer>+ );+}+export function PlatformBreakdownChart({ data }: { data: { platform: string; visits: number }[] }) {const [hovered, setHovered] = useState<string | null>(null);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.test.tsxnew file mode 100644index 000000000..58af33ecf--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.test.tsx@@ -0,0 +1,157 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { TrafficTrendPoint } from '@/lib/actions/traffic';+import type { GoogleTrendPoint } from '@/lib/traffic-google-trend';++/**+ * The trend's "vs Google clicks" view (AT-008, spec §3.3): the AI line+ * against Google clicks, the 24-hour range offering the last 7 days, and+ * §3.8b's partial note without Search Console.+ */++const getTrafficGoogleTrend = vi.fn();+vi.mock('@/lib/actions/traffic', () => ({+ getTrafficGoogleTrend: (...args: unknown[]) => getTrafficGoogleTrend(...args),+}));++// The chart draws with recharts; the test reads the points it is given.+const drawn: { points: GoogleTrendPoint[]; googleUntil: string | null }[] = [];+vi.mock('./_charts', async (original) => ({+ ...(await original<typeof import('./_charts')>()),+ GoogleTrendChart: (props: { points: GoogleTrendPoint[]; googleUntil: string | null }) => {+ drawn.push(props);+ return <div data-testid="chart" />;+ },+}));++const { GoogleTrendView } = await import('./_google-trend');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const WEEK: TrafficTrendPoint[] = [+ { date: '2026-10-12', 'chatgpt.com': 2 },+ { date: '2026-10-13', 'chatgpt.com': 4 },+ { date: '2026-10-14', 'chatgpt.com': 3 },+];++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ drawn.length = 0;+ getTrafficGoogleTrend.mockReset().mockResolvedValue({+ firstDay: '2026-07-20',+ lastDay: '2026-10-13',+ clicks: [+ { day: '2026-10-12', clicks: 400 },+ { day: '2026-10-13', clicks: 300 },+ ],+ markers: [{ day: '2026-10-13', actions: 1, prompts: 3 }],+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render(+ trend: TrafficTrendPoint[],+ gscConnected: boolean | null = true,+ onShowWeek = () => {},+ rangeStart?: string,+) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <GoogleTrendView+ brandId="b1"+ trend={trend}+ rangeStart={rangeStart}+ gscConnected={gscConnected}+ onShowWeek={onShowWeek}+ />+ </NextIntlClientProvider>,+ );+ });+}++const text = () => container.textContent ?? '';++describe('GoogleTrendView', () => {+ it('draws both lines over the trend days and says where Google stops', async () => {+ await render(WEEK);+ expect(getTrafficGoogleTrend).toHaveBeenCalledWith('b1', '2026-10-12', '2026-10-14');+ const { points, googleUntil } = drawn.at(-1)!;+ expect(points.map((p) => [p.ai, p.google])).toEqual([+ [100, 100],+ [200, 75],+ [150, null],+ ]);+ expect(points[1]).toMatchObject({ actions: 1, prompts: 3 });+ expect(googleUntil).toBe('2026-10-13');+ expect(text()).toContain('Google clicks until Oct 13: Google reports about two days late.');+ expect(text()).toContain("can't be separated");+ expect(text()).toContain('Dashed amber lines mark the days');+ });++ it('keeps the AI line and says what the Google line needs without Search Console', async () => {+ await render(WEEK, false);+ const { points } = drawn.at(-1)!;+ expect(points.map((p) => p.ai)).toEqual([100, 200, 150]);+ expect(points.every((p) => p.google === null)).toBe(true);+ expect(text()).toContain('The Google clicks line needs Google Search Console.');+ expect(text()).not.toContain('Google clicks until');+ });++ it('says so when Google has no clicks for the range, or they failed to load', async () => {+ getTrafficGoogleTrend.mockResolvedValue({+ firstDay: null,+ lastDay: null,+ clicks: [],+ markers: [],+ });+ await render(WEEK);+ expect(text()).toContain('No Google clicks for this range in Google Search Console.');+ expect(text()).not.toContain('Dashed amber lines');++ const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});+ getTrafficGoogleTrend.mockRejectedValue(new Error('boom'));+ await render([...WEEK, { date: '2026-10-15', 'chatgpt.com': 1 }]);+ expect(text()).toContain("Google clicks couldn't be loaded.");+ expect(drawn.at(-1)!.points.map((p) => p.ai)).toEqual([100, 200, 150, 50]);+ quiet.mockRestore();+ });++ it('starts on the first whole day, and waits for the source states', async () => {+ await render(WEEK, null, () => {}, '2026-10-12T09:00:00.000Z');+ expect(getTrafficGoogleTrend).toHaveBeenCalledWith('b1', '2026-10-13', '2026-10-14');+ expect(container.querySelector('[data-slot="skeleton"]')).not.toBeNull();+ expect(text()).toBe('');++ await render(WEEK, true, () => {}, '2026-10-12T09:00:00.000Z');+ expect(drawn.at(-1)!.points.map((p) => [p.date, p.ai, p.google])).toEqual([+ ['2026-10-13', 100, 100],+ ['2026-10-14', 75, null],+ ]);+ });++ it('offers the last 7 days on the 24-hour range instead of a window of its own', async () => {+ const onShowWeek = vi.fn();+ await render([{ date: '2026-10-17T13:00:00.000Z', 'chatgpt.com': 1 }], true, onShowWeek);+ expect(getTrafficGoogleTrend).not.toHaveBeenCalled();+ expect(text()).toContain('Pick 7 days or longer');+ const button = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Show last 7 days',+ );+ act(() => button!.click());+ expect(onShowWeek).toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.tsxnew file mode 100644index 000000000..148ff58d6--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.tsx@@ -0,0 +1,110 @@+'use client';++import { useEffect, useMemo, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { formatTrafficBucketDate, GoogleTrendChart } from './_charts';+import { googleTrend, googleTrendDays } from '@/lib/traffic-google-trend';+import {+ getTrafficGoogleTrend,+ type TrafficGoogleTrend,+ type TrafficTrendPoint,+} from '@/lib/actions/traffic';++/** Search Console's part when it isn't connected: no clicks, no days. */+const NO_GOOGLE = { clicks: [], firstDay: null, lastDay: null };++/**+ * The AI Referral Trend card's "vs Google clicks" view (AT-008, spec §3.3):+ * the page's AI visits against Google organic clicks, each indexed to 100,+ * with markers on the days actions entered the Action Center and prompts+ * were added.+ *+ * Google reports by day, so the 24-hour range offers the last 7 days rather+ * than reading a window of its own. Without Search Console the view keeps+ * the AI line and says what the Google line needs (§3.8b's partial note).+ */+export function GoogleTrendView({+ brandId,+ trend,+ rangeStart,+ gscConnected,+ onShowWeek,+}: {+ brandId: string;+ /** The page's trend for the range, by day or, for 24 hours, by hour. */+ trend: TrafficTrendPoint[];+ /** When the range starts; none for all time. */+ rangeStart?: string;+ /** Search Console has data for the brand; null while its state loads. */+ gscConnected: boolean | null;+ /** Switches the page to the last 7 days. */+ onShowWeek: () => void;+}) {+ const t = useTranslations('traffic.trend.google');+ const days = useMemo(() => googleTrendDays(trend, rangeStart), [trend, rangeStart]);+ const since = days?.[0];+ const until = days?.[days.length - 1];+ const key = `${brandId}|${since ?? ''}|${until ?? ''}`;+ // The loaded data carries the request it answers, so a new range never+ // draws the previous one's Google line.+ const [loaded, setLoaded] = useState<{ key: string; data: TrafficGoogleTrend | null } | null>(+ null,+ );++ useEffect(() => {+ if (!since || !until) return;+ let cancelled = false;+ getTrafficGoogleTrend(brandId, since, until)+ .then((data) => {+ if (!cancelled) setLoaded({ key, data });+ })+ .catch((err) => {+ // Best effort: the view still draws the AI line.+ console.error('Failed to load the Google trend:', err);+ if (!cancelled) setLoaded({ key, data: null });+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, since, until, key]);++ if (days === null) {+ return (+ <div className="flex h-[220px] flex-col items-center justify-center gap-3 text-center">+ <p className="max-w-[380px] text-sm text-muted-foreground">{t('daily')}</p>+ <Button variant="outline" size="sm" onClick={onShowWeek}>+ {t('showWeek')}+ </Button>+ </div>+ );+ }++ if (!days.length) return null;+ const current = loaded?.key === key ? loaded : null;+ if (!current || gscConnected === null) return <Skeleton className="h-[220px] w-full" />;++ const data = current.data ?? { ...NO_GOOGLE, markers: [] };+ const view = googleTrend(trend, gscConnected ? data : { ...data, ...NO_GOOGLE }, days);+ const status = !gscConnected+ ? t('needsGsc')+ : current.data === null+ ? t('failed')+ : !view.hasGoogle+ ? t('noClicks')+ : view.googleUntil+ ? t('until', { day: formatTrafficBucketDate(view.googleUntil) })+ : null;++ return (+ <div className="space-y-2">+ <GoogleTrendChart points={view.points} googleUntil={view.googleUntil} />+ <div className="space-y-0.5 text-xs text-muted-foreground">+ {status && <p>{status}</p>}+ <p>{t('legend')}</p>+ {view.points.some((p) => p.actions > 0 || p.prompts > 0) && <p>{t('markers')}</p>}+ </div>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex ed7687aef..2d6bba8fe 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -44,10 +44,13 @@ import { EngagedCell, KeyEventsCell, PlatformValueNote } from './_platform-valueimport { ExportMenu, TableExport, useTrafficExport } from './_export';import { SourcesStrip } from './_sources-strip';import { SnippetBanner, SnippetDialog } from './_snippet-code';+import { GoogleTrendView } from './_google-trend';+import { NeedsTag } from './_source-gate';import { googleSourceStatus, snippetDetected } from '@/lib/traffic-sources';import { useUserRole } from '@/hooks/use-user-role';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import {Table,TableBody,@@ -406,6 +409,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {const t = useTranslations('traffic');const tCommon = useTranslations('common');const tVisits = useTranslations('traffic.visits');+ const tTrend = useTranslations('traffic.trend');// The page opens on the member's last range, or the last 24 hours (AT-017,// spec §3.01). This only renders in the browser, once the brand has loaded,// so the stored choice is read before the first load rather than after it.@@ -424,6 +428,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {const trendTitle = getTrendTitle(datePreset, { from: customFrom, to: customTo });const [summary, setSummary] = useState<TrafficSummary | null>(null);const [trend, setTrend] = useState<TrafficTrendPoint[]>([]);+ const [trendView, setTrendView] = useState<'platforms' | 'google'>('platforms');const [logs, setLogs] = useState<TrafficLog[]>([]);const [logsTotal, setLogsTotal] = useState(0);const [logsPageviews, setLogsPageviews] = useState(0);@@ -576,6 +581,12 @@ function TrafficPageContent({ brand }: { brand: Brand }) {// §3.8b's partial note) — even with rows left from an earlier connection.const gaMissing =!sourcesFailed && sources !== null && googleSourceStatus(sources.ga) !== 'connected';+ // The trend's Google line reads Search Console once it has data, or when+ // the states couldn't be read, as the Google clicks card does; null while+ // they load (AT-008).+ const gscConnected = sources+ ? googleSourceStatus(sources.gsc) === 'connected'+ : sourcesFailed || null;const isEmpty = totalVisits === 0 && logs.length === 0;const hasAnyData = summary?.hasAnyData ?? false;@@ -697,10 +708,35 @@ function TrafficPageContent({ brand }: { brand: Brand }) {<div className="grid grid-cols-1 gap-4 lg:grid-cols-3"><Card className="lg:col-span-2"><CardHeader className="pb-2">- <CardTitle className="font-medium text-sm">{trendTitle}</CardTitle>+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">+ <div className="flex items-center gap-2">+ <CardTitle className="font-medium text-sm">{trendTitle}</CardTitle>+ {trendView === 'google' && <NeedsTag provider="google-search-console" />}+ </div>+ {/* By platform, or AI visits against Google clicks (AT-008, spec §3.3). */}+ <Tabs+ value={trendView}+ onValueChange={(v) => setTrendView(v as 'platforms' | 'google')}+ >+ <TabsList variant="line" aria-label={trendTitle}>+ <TabsTrigger value="platforms">{tTrend('tabs.platforms')}</TabsTrigger>+ <TabsTrigger value="google">{tTrend('tabs.google')}</TabsTrigger>+ </TabsList>+ </Tabs>+ </div></CardHeader><CardContent>- <ReferralTrendChart data={trend} analyticsDays={summary?.analyticsDays} />+ {trendView === 'google' ? (+ <GoogleTrendView+ brandId={brand.id}+ trend={trend}+ rangeStart={dateWindow.dateFrom}+ gscConnected={gscConnected}+ onShowWeek={() => handleDatePresetChange('7d')}+ />+ ) : (+ <ReferralTrendChart data={trend} analyticsDays={summary?.analyticsDays} />+ )}</CardContent></Card>diff --git a/web/src/lib/actions/traffic-google-trend.test.ts b/web/src/lib/actions/traffic-google-trend.test.tsnew file mode 100644index 000000000..62c2610ac--- /dev/null+++ b/web/src/lib/actions/traffic-google-trend.test.ts@@ -0,0 +1,69 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * AT-008 (spec §3.3): the trend's "vs Google clicks" view reads Search+ * Console's clicks per day and the event markers from ai_traffic_google_trend+ * (00180), between the trend's first and last day.+ */++const rpc = vi.fn();+vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({ rpc }),+}));+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));++import { getTrafficGoogleTrend } from './traffic';++beforeEach(() => {+ rpc.mockReset();+});++describe('getTrafficGoogleTrend', () => {+ it('reads the days between the two given, with the markers', async () => {+ rpc.mockResolvedValue({+ data: {+ first_day: '2026-07-21',+ last_day: '2026-10-16',+ clicks: [+ { day: '2026-10-12', clicks: '410' },+ { day: '2026-10-13', clicks: 388 },+ ],+ markers: [{ day: '2026-10-13', actions: 2, prompts: '5' }],+ },+ error: null,+ });++ await expect(getTrafficGoogleTrend('b1', '2026-10-12', '2026-10-18')).resolves.toEqual({+ firstDay: '2026-07-21',+ lastDay: '2026-10-16',+ clicks: [+ { day: '2026-10-12', clicks: 410 },+ { day: '2026-10-13', clicks: 388 },+ ],+ markers: [{ day: '2026-10-13', actions: 2, prompts: 5 }],+ });+ expect(rpc).toHaveBeenCalledWith('ai_traffic_google_trend', {+ p_brand_id: 'b1',+ p_since: '2026-10-12',+ p_until: '2026-10-18',+ });+ });++ it('reads no Search Console days as none', async () => {+ rpc.mockResolvedValue({+ data: { first_day: null, last_day: null, clicks: [], markers: [] },+ error: null,+ });+ await expect(getTrafficGoogleTrend('b1', '2026-10-12', '2026-10-18')).resolves.toEqual({+ firstDay: null,+ lastDay: null,+ clicks: [],+ markers: [],+ });+ });++ it('throws when the read fails', async () => {+ rpc.mockResolvedValue({ data: null, error: { message: 'boom' } });+ await expect(getTrafficGoogleTrend('b1', '2026-10-12', '2026-10-18')).rejects.toThrow('boom');+ });+});diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.tsindex fd78e5b5c..8b93418de 100644--- a/web/src/lib/actions/traffic.ts+++ b/web/src/lib/actions/traffic.ts@@ -919,3 +919,48 @@ export async function getTrafficGoogleTotals(: null,};}++/** The Google side of the trend's "vs Google clicks" view (AT-008), by UTC day. */+export interface TrafficGoogleTrend {+ /** Search Console clicks on the days it has rows for. */+ clicks: { day: string; clicks: number }[];+ /** The first day Search Console has rows for the brand; null with none. */+ firstDay: string | null;+ /** The latest day Google has reported; null with none. */+ lastDay: string | null;+ /** The days actions entered the Action Center or prompts were added. */+ markers: { day: string; actions: number; prompts: number }[];+}++/**+ * Search Console clicks and the event markers for the trend's "vs Google+ * clicks" view (AT-008, spec §3.3; 00180), between two UTC days. The AI+ * line is the page's own trend.+ */+export async function getTrafficGoogleTrend(+ brandId: string,+ since: string,+ until: string,+): Promise<TrafficGoogleTrend> {+ const supabase = await createClient();+ const { data, error } = await supabase.rpc('ai_traffic_google_trend', {+ p_brand_id: brandId,+ p_since: since,+ p_until: until,+ });+ if (error) throw new Error(error.message);+ const raw = (data ?? {}) as Record<string, unknown>;+ const n = (v: unknown) => Number(v) || 0;+ const list = (v: unknown) => (Array.isArray(v) ? (v as Record<string, unknown>[]) : []);+ const day = (v: unknown) => (typeof v === 'string' ? v : null);+ return {+ clicks: list(raw.clicks).map((r) => ({ day: String(r.day), clicks: n(r.clicks) })),+ firstDay: day(raw.first_day),+ lastDay: day(raw.last_day),+ markers: list(raw.markers).map((r) => ({+ day: String(r.day),+ actions: n(r.actions),+ prompts: n(r.prompts),+ })),+ };+}diff --git a/web/src/lib/traffic-google-trend.test.ts b/web/src/lib/traffic-google-trend.test.tsnew file mode 100644index 000000000..b8f4deace--- /dev/null+++ b/web/src/lib/traffic-google-trend.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from 'vitest';+import { GOOGLE_TREND_MAX_DAYS, googleTrend, googleTrendDays } from './traffic-google-trend';+import type { TrafficGoogleTrend, TrafficTrendPoint } from '@/lib/actions/traffic';++/** The trend's "vs Google clicks" view (AT-008, spec §3.3). */++const trend: TrafficTrendPoint[] = [+ { date: '2026-10-10', 'chatgpt.com': 0, 'perplexity.ai': 0 },+ { date: '2026-10-11', 'chatgpt.com': 2, 'perplexity.ai': 2 },+ { date: '2026-10-12', 'chatgpt.com': 5, 'perplexity.ai': 1 },+ { date: '2026-10-13', 'chatgpt.com': 0, 'perplexity.ai': 0 },+ { date: '2026-10-14', 'chatgpt.com': 8, 'perplexity.ai': 2 },+];++const google = (over: Partial<TrafficGoogleTrend> = {}): TrafficGoogleTrend => ({+ firstDay: '2026-10-11',+ lastDay: '2026-10-13',+ clicks: [+ { day: '2026-10-11', clicks: 200 },+ { day: '2026-10-12', clicks: 150 },+ ],+ markers: [{ day: '2026-10-12', actions: 2, prompts: 0 }],+ ...over,+});++describe('googleTrendDays', () => {+ it('lists every day from the first to the last, quiet days included', () => {+ expect(+ googleTrendDays([+ { date: '2026-10-10', 'chatgpt.com': 1 },+ { date: '2026-10-13', 'chatgpt.com': 2 },+ ]),+ ).toEqual(['2026-10-10', '2026-10-11', '2026-10-12', '2026-10-13']);+ });++ it('leaves out a first day the range starts in the middle of', () => {+ const week = [+ { date: '2026-10-12', 'chatgpt.com': 1 },+ { date: '2026-10-13', 'chatgpt.com': 4 },+ { date: '2026-10-14', 'chatgpt.com': 5 },+ ];+ expect(googleTrendDays(week, '2026-10-12T09:30:00.000Z')).toEqual(['2026-10-13', '2026-10-14']);+ expect(googleTrendDays(week, '2026-10-12')).toEqual(['2026-10-12', '2026-10-13', '2026-10-14']);+ expect(googleTrendDays(week)).toHaveLength(3);+ });++ it('is null for an hourly trend, and keeps at most a year', () => {+ expect(googleTrendDays([{ date: '2026-10-17T13:00:00.000Z', 'chatgpt.com': 1 }])).toBeNull();+ const days = googleTrendDays([+ { date: '2024-01-01', 'chatgpt.com': 1 },+ { date: '2026-10-13', 'chatgpt.com': 1 },+ ]);+ expect(days).toHaveLength(GOOGLE_TREND_MAX_DAYS);+ expect(days?.at(-1)).toBe('2026-10-13');+ expect(googleTrendDays([])).toEqual([]);+ });+});++describe('googleTrend', () => {+ const days = googleTrendDays(trend)!;++ it('indexes each line to 100 on its first day with any', () => {+ const { points } = googleTrend(trend, google(), days);+ expect(points.map((p) => p.ai)).toEqual([null, 100, 150, 0, 250]);+ expect(points.map((p) => p.visits)).toEqual([0, 4, 6, 0, 10]);+ expect(points.map((p) => p.google)).toEqual([null, 100, 75, 0, null]);+ });++ it('leaves Google blank before its first day and after its latest, 0 between', () => {+ const view = googleTrend(trend, google(), days);+ expect(view.points.map((p) => p.clicks)).toEqual([null, 200, 150, 0, null]);+ expect(view.googleUntil).toBe('2026-10-13');+ expect(view.hasGoogle).toBe(true);+ });++ it('puts the markers on their days', () => {+ const { points } = googleTrend(trend, google(), days);+ expect(points.find((p) => p.date === '2026-10-12')).toMatchObject({ actions: 2, prompts: 0 });+ expect(points.filter((p) => p.actions || p.prompts)).toHaveLength(1);+ });++ it('says when Google has no clicks for the range or reports past it', () => {+ const none = googleTrend(trend, google({ firstDay: null, lastDay: null, clicks: [] }), days);+ expect(none.hasGoogle).toBe(false);+ expect(none.googleUntil).toBeNull();+ expect(none.points.every((p) => p.google === null)).toBe(true);++ const current = googleTrend(trend, google({ lastDay: '2026-10-16' }), days);+ expect(current.googleUntil).toBeNull();+ });+});diff --git a/web/src/lib/traffic-google-trend.ts b/web/src/lib/traffic-google-trend.tsnew file mode 100644index 000000000..5ca4e1c9f--- /dev/null+++ b/web/src/lib/traffic-google-trend.ts@@ -0,0 +1,108 @@+/**+ * The AI Referral Trend's "vs Google clicks" view (AT-008, spec §3.3): AI+ * visits and Google organic clicks day by day, each indexed to 100 on its+ * first day with any, so two lines of very different sizes compare by shape.+ * Markers show the days actions entered the Action Center and prompts were+ * added.+ *+ * A Google day is left blank, not 0, before Search Console's first day for+ * the brand (the sync keeps no older history) and after the latest day+ * Google has reported (about two days late, §3.01).+ *+ * Pure: the chart draws it.+ */++import type { TrafficGoogleTrend, TrafficTrendPoint } from '@/lib/actions/traffic';++/** The longest stretch the view draws, as the trend does (365 days). */+export const GOOGLE_TREND_MAX_DAYS = 365;++const DAY_MS = 86_400_000;++export interface GoogleTrendPoint {+ /** A UTC day, "2026-10-12". */+ date: string;+ /** AI visits indexed: 100 = the line's first day with any; null before it. */+ ai: number | null;+ /** Google clicks indexed the same way; null where Google has no data for the day. */+ google: number | null;+ visits: number;+ /** Null where Google has no data for the day. */+ clicks: number | null;+ actions: number;+ prompts: number;+}++export interface GoogleTrendView {+ points: GoogleTrendPoint[];+ /** Google's latest reported day when the range runs past it, for the label. */+ googleUntil: string | null;+ /** Any Google clicks in the range; without, the view says so. */+ hasGoogle: boolean;+}++/**+ * The days the view draws: every UTC day from the trend's first to its last,+ * the all-time trend's quiet days included, at most a year. A range that+ * starts mid-day (the rolling 7 and 30 days) leaves out its first, partial+ * day, whose few visits would set a misleading 100. Null for an hourly trend+ * (the 24-hour range): Google reports by day.+ */+export function googleTrendDays(trend: TrafficTrendPoint[], rangeStart?: string): string[] | null {+ if (trend.some((p) => p.date.includes('T'))) return null;+ if (!trend.length) return [];+ let first = Date.parse(`${trend[0].date}T00:00:00Z`);+ if (rangeStart && Date.parse(rangeStart) > first && trend.length > 1) first += DAY_MS;+ const last = Date.parse(`${trend[trend.length - 1].date}T00:00:00Z`);+ const start = Math.max(first, last - (GOOGLE_TREND_MAX_DAYS - 1) * DAY_MS);+ const days: string[] = [];+ for (let t = start; t <= last; t += DAY_MS) days.push(new Date(t).toISOString().slice(0, 10));+ return days;+}++/** Each value over the series' first value above 0, × 100; null before that day. */+function indexed(values: (number | null)[]): (number | null)[] {+ const start = values.findIndex((v) => v !== null && v > 0);+ if (start === -1) return values.map(() => null);+ const base = values[start] as number;+ return values.map((v, i) => (i < start || v === null ? null : Math.round((v / base) * 100)));+}++/** The view's points for `days` (from `googleTrendDays`). */+export function googleTrend(+ trend: TrafficTrendPoint[],+ google: TrafficGoogleTrend,+ days: string[],+): GoogleTrendView {+ const visitsByDay = new Map(+ trend.map((p) => [+ p.date,+ Object.entries(p).reduce((sum, [key, v]) => (key === 'date' ? sum : sum + Number(v)), 0),+ ]),+ );+ const clicksByDay = new Map(google.clicks.map((c) => [c.day, c.clicks]));+ const markers = new Map(google.markers.map((m) => [m.day, m]));+ const { firstDay, lastDay } = google;++ const visits = days.map((day) => visitsByDay.get(day) ?? 0);+ const clicks = days.map((day) =>+ !firstDay || !lastDay || day < firstDay || day > lastDay ? null : (clicksByDay.get(day) ?? 0),+ );+ const ai = indexed(visits);+ const googleLine = indexed(clicks);+ const last = days[days.length - 1];++ return {+ points: days.map((date, i) => ({+ date,+ ai: ai[i],+ google: googleLine[i],+ visits: visits[i],+ clicks: clicks[i],+ actions: markers.get(date)?.actions ?? 0,+ prompts: markers.get(date)?.prompts ?? 0,+ })),+ googleUntil: lastDay && last && lastDay < last ? lastDay : null,+ hasGoogle: clicks.some((c) => c !== null && c > 0),+ };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex c0f607ae1..78284f4ad 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -2870,6 +2870,14 @@ export type Database = {}Returns: Json}+ ai_traffic_google_trend: {+ Args: {+ p_brand_id: string+ p_since: string+ p_until: string+ }+ Returns: Json+ }ai_visibility_aggregates: {Args: {p_brand_id: string