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(traffic): add AI share, engaged visits, key events and Google clicks KPI cards (#1164)

Cihan0b10b09496ca
diff --git a/supabase/migrations/00174_traffic_google_totals.sql b/supabase/migrations/00174_traffic_google_totals.sql
new file mode 100644
index 000000000..862eba9e1
--- /dev/null
+++ b/supabase/migrations/00174_traffic_google_totals.sql
@@ -0,0 +1,128 @@
+-- ============================================================================
+-- 00174: Google Analytics and Search Console totals for the AI Traffic KPIs
+-- ============================================================================
+-- The AI Traffic page's second row of KPI cards (AT-017, spec §3.2) reads
+-- Google: AI share of traffic and engaged visits and key events from AI
+-- (Analytics), and Google clicks (Search Console). The tables hold a row per
+-- page or query per day — up to 5,000 pages a day for Analytics — so the
+-- sums are taken here rather than shipped to the browser row by row.
+--
+-- Both read as the caller (security invoker), so the tables' member select
+-- policies decide whose brand they see, and both are granted to signed-in
+-- members: the page calls them through the member's session. A null p_since
+-- reads from the start (all time).
+
+-- ─── Analytics: all sessions, and the AI channel's ─────────────────────────
+
+create or replace function public.ga_traffic_totals(
+ p_brand_id uuid,
+ p_since date,
+ p_until date
+)
+returns table (
+ sessions bigint,
+ ai_sessions bigint,
+ ai_engaged_sessions bigint,
+ ai_key_events bigint
+)
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ select
+ (
+ select coalesce(sum(gps.sessions), 0)::bigint
+ from public.ga_page_stats gps
+ where gps.brand_id = p_brand_id
+ and gps.date >= coalesce(p_since, '-infinity'::date)
+ and gps.date <= p_until
+ ),
+ coalesce(sum(gat.sessions), 0)::bigint,
+ coalesce(sum(gat.engaged_sessions), 0)::bigint,
+ coalesce(sum(gat.key_events), 0)::bigint
+ from public.ga_ai_traffic_stats gat
+ where gat.brand_id = p_brand_id
+ and gat.date >= coalesce(p_since, '-infinity'::date)
+ and gat.date <= p_until;
+$$;
+
+-- ─── Search Console: clicks, against the period before ─────────────────────
+--
+-- Google reports with about a two-day delay, so a short range ending today
+-- would read as zero clicks. With p_latest the window ends on the latest day
+-- Google has reported instead, keeping its length, and the result says which
+-- days it covers so the card can label them (spec §3.01). The previous
+-- period is the same length, just before; all time has none.
+
+create or replace function public.gsc_click_totals(
+ p_brand_id uuid,
+ p_since date,
+ p_until date,
+ p_latest boolean default false
+)
+returns table (
+ since date,
+ until date,
+ clicks bigint,
+ prev_clicks bigint,
+ last_date date
+)
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with latest as (
+ select max(g.date) as d
+ from public.gsc_query_stats g
+ where g.brand_id = p_brand_id
+ ),
+ w as (
+ select
+ case
+ when p_latest and l.d < p_until then l.d - (p_until - p_since)
+ else p_since
+ end as since,
+ case when p_latest and l.d < p_until then l.d else p_until end as until,
+ l.d as last_date
+ from latest l
+ )
+ select
+ w.since,
+ w.until,
+ (
+ select coalesce(sum(g.clicks), 0)::bigint
+ from public.gsc_query_stats g
+ where g.brand_id = p_brand_id
+ and g.date >= coalesce(w.since, '-infinity'::date)
+ and g.date <= w.until
+ ),
+ case
+ when w.since is null then null
+ else (
+ select coalesce(sum(g.clicks), 0)::bigint
+ from public.gsc_query_stats g
+ where g.brand_id = p_brand_id
+ and g.date >= w.since - (w.until - w.since) - 1
+ and g.date < w.since
+ )
+ end,
+ w.last_date
+ from w;
+$$;
+
+revoke all on function public.ga_traffic_totals(uuid, date, date) from public, anon;
+grant execute on function public.ga_traffic_totals(uuid, date, date) to authenticated, service_role;
+
+revoke all on function public.gsc_click_totals(uuid, date, date, boolean) from public, anon;
+grant execute on function public.gsc_click_totals(uuid, date, date, boolean)
+ to authenticated, service_role;
+
+comment on function public.ga_traffic_totals(uuid, date, date) is
+ 'AI Traffic KPIs (AT-017): all sessions and the AI channel''s sessions, engaged sessions and key events for one brand between two days (p_since null = from the start). Security invoker: RLS decides the brand.';
+
+comment on function public.gsc_click_totals(uuid, date, date, boolean) is
+ 'AI Traffic KPIs (AT-017): Search Console clicks for one brand and the same-length period before. p_latest ends the window on the latest reported day. Security invoker: RLS decides the brand.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 8c8f80dcf..be07de880 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -23470,3 +23470,135 @@ as $$
)
$$;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00174_traffic_google_totals.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00174: Google Analytics and Search Console totals for the AI Traffic KPIs
+-- ============================================================================
+-- The AI Traffic page's second row of KPI cards (AT-017, spec §3.2) reads
+-- Google: AI share of traffic and engaged visits and key events from AI
+-- (Analytics), and Google clicks (Search Console). The tables hold a row per
+-- page or query per day — up to 5,000 pages a day for Analytics — so the
+-- sums are taken here rather than shipped to the browser row by row.
+--
+-- Both read as the caller (security invoker), so the tables' member select
+-- policies decide whose brand they see, and both are granted to signed-in
+-- members: the page calls them through the member's session. A null p_since
+-- reads from the start (all time).
+
+-- ─── Analytics: all sessions, and the AI channel's ─────────────────────────
+
+create or replace function public.ga_traffic_totals(
+ p_brand_id uuid,
+ p_since date,
+ p_until date
+)
+returns table (
+ sessions bigint,
+ ai_sessions bigint,
+ ai_engaged_sessions bigint,
+ ai_key_events bigint
+)
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ select
+ (
+ select coalesce(sum(gps.sessions), 0)::bigint
+ from public.ga_page_stats gps
+ where gps.brand_id = p_brand_id
+ and gps.date >= coalesce(p_since, '-infinity'::date)
+ and gps.date <= p_until
+ ),
+ coalesce(sum(gat.sessions), 0)::bigint,
+ coalesce(sum(gat.engaged_sessions), 0)::bigint,
+ coalesce(sum(gat.key_events), 0)::bigint
+ from public.ga_ai_traffic_stats gat
+ where gat.brand_id = p_brand_id
+ and gat.date >= coalesce(p_since, '-infinity'::date)
+ and gat.date <= p_until;
+$$;
+
+-- ─── Search Console: clicks, against the period before ─────────────────────
+--
+-- Google reports with about a two-day delay, so a short range ending today
+-- would read as zero clicks. With p_latest the window ends on the latest day
+-- Google has reported instead, keeping its length, and the result says which
+-- days it covers so the card can label them (spec §3.01). The previous
+-- period is the same length, just before; all time has none.
+
+create or replace function public.gsc_click_totals(
+ p_brand_id uuid,
+ p_since date,
+ p_until date,
+ p_latest boolean default false
+)
+returns table (
+ since date,
+ until date,
+ clicks bigint,
+ prev_clicks bigint,
+ last_date date
+)
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with latest as (
+ select max(g.date) as d
+ from public.gsc_query_stats g
+ where g.brand_id = p_brand_id
+ ),
+ w as (
+ select
+ case
+ when p_latest and l.d < p_until then l.d - (p_until - p_since)
+ else p_since
+ end as since,
+ case when p_latest and l.d < p_until then l.d else p_until end as until,
+ l.d as last_date
+ from latest l
+ )
+ select
+ w.since,
+ w.until,
+ (
+ select coalesce(sum(g.clicks), 0)::bigint
+ from public.gsc_query_stats g
+ where g.brand_id = p_brand_id
+ and g.date >= coalesce(w.since, '-infinity'::date)
+ and g.date <= w.until
+ ),
+ case
+ when w.since is null then null
+ else (
+ select coalesce(sum(g.clicks), 0)::bigint
+ from public.gsc_query_stats g
+ where g.brand_id = p_brand_id
+ and g.date >= w.since - (w.until - w.since) - 1
+ and g.date < w.since
+ )
+ end,
+ w.last_date
+ from w;
+$$;
+
+revoke all on function public.ga_traffic_totals(uuid, date, date) from public, anon;
+grant execute on function public.ga_traffic_totals(uuid, date, date) to authenticated, service_role;
+
+revoke all on function public.gsc_click_totals(uuid, date, date, boolean) from public, anon;
+grant execute on function public.gsc_click_totals(uuid, date, date, boolean)
+ to authenticated, service_role;
+
+comment on function public.ga_traffic_totals(uuid, date, date) is
+ 'AI Traffic KPIs (AT-017): all sessions and the AI channel''s sessions, engaged sessions and key events for one brand between two days (p_since null = from the start). Security invoker: RLS decides the brand.';
+
+comment on function public.gsc_click_totals(uuid, date, date, boolean) is
+ 'AI Traffic KPIs (AT-017): Search Console clicks for one brand and the same-length period before. p_latest ends the window on the latest reported day. Security invoker: RLS decides the brand.';
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 508d0708d..ff47ed9ce 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3191,6 +3191,40 @@
"listRange": "{visits, plural, one {# visit} other {# visits}} ({pageviews, plural, one {# pageview} other {# pageviews}}) {preset, select, last {in the {range}} other {· {range}}}",
"showLast7Days": "Show last 7 days"
},
+ "kpis": {
+ "visits": "AI-referred visits",
+ "visitsTip": "Visits from AI assistants, counted once per session by the tracking snippet. Below 30 visits in this period or the one before, the change shows Low sample.",
+ "topPlatform": "Top platform",
+ "topPlatformTip": "The AI platform that sent the most visits in this range.",
+ "topPlatformSub": "{visits, plural, one {# visit} other {# visits}}",
+ "platforms": "Platforms",
+ "platformsTip": "AI platforms that sent at least one visit in this range.",
+ "platformsSub": "unique AI sources",
+ "noData": "no data",
+ "aiShare": "AI share of traffic",
+ "aiShareTip": "AI-referred visits as a share of all the sessions Google Analytics recorded on the range's days. Analytics counts whole days, so the last 24 hours are compared with yesterday and today.",
+ "aiShareSub": "{visits, number} of {sessions, plural, one {# session} other {# sessions}}",
+ "engaged": "Engaged visits",
+ "engagedTip": "The share of AI sessions Google Analytics counts as engaged: 10 seconds or longer, with a key event, or with two or more page views. Below 30 AI sessions the rate shows Low sample.",
+ "engagedSub": "{engaged, number} of {sessions, plural, one {# AI session} other {# AI sessions}}",
+ "keyEvents": "Key events from AI",
+ "keyEventsTip": "Key events (conversions) Google Analytics recorded in sessions from AI assistants.",
+ "keyEventsSub": "in {sessions, plural, one {# AI session} other {# AI sessions}}",
+ "keyEventsNone": "none in {range}",
+ "see30d": "see 30d",
+ "googleClicks": "Google clicks",
+ "googleClicksTip": "Clicks from Google Search, from Google Search Console. Google reports about two days late, so the 24-hour and 7-day ranges show its latest reported days. Searches Google keeps private aren't included, so the total can be a little lower than in Search Console.",
+ "latestDay": "{days} · latest reported day",
+ "latestDays": "{days} · latest reported days",
+ "clicksPrevious": "{previous, number} in the previous period",
+ "allTime": "all time",
+ "noRangeData": "No data in this range",
+ "noAiSessions": "No AI sessions in this range",
+ "syncing": "Syncing…",
+ "waitGa": "about 15 min",
+ "waitGsc": "up to 48 h",
+ "unmapped": "Choose a property for this brand"
+ },
"sources": {
"label": "Data sources",
"snippet": "Tracking snippet",
@@ -3234,6 +3268,10 @@
"noData": "No data for this range in {source}",
"showAllTime": "Show all time",
"sections": {
+ "aiShare": "AI share of traffic",
+ "engagedVisits": "engaged visits",
+ "keyEvents": "key events from AI",
+ "googleClicks": "Google clicks",
"pageOpportunities": "pages AI engines aren't sending traffic to"
}
},
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
index f6565edeb..30e63b4cf 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
@@ -217,7 +217,10 @@ export function MetricCard({
)}
>
<div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
- <span className="truncate">{label}</span>
+ {/* One line, cut with an ellipsis on narrow cards; the full text on hover. */}
+ <span className="truncate" title={label}>
+ {label}
+ </span>
<InfoTip content={tooltip} />
<span className="flex-1" />
<span className="relative flex h-4 w-4 items-center justify-center">
@@ -245,7 +248,12 @@ export function MetricCard({
</span>
)}
</div>
- <div className="truncate text-xs text-muted-foreground">{sub}</div>
+ <div
+ className="truncate text-xs text-muted-foreground"
+ title={typeof sub === 'string' ? sub : undefined}
+ >
+ {sub}
+ </div>
{footer ? (
footer
) : quota ? (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
new file mode 100644
index 000000000..266968ff7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
@@ -0,0 +1,324 @@
+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 { DateRangePreset } from '@/components/filters/date-range-filter';
+import type {
+ TrafficDateWindow,
+ TrafficGoogleTotals,
+ TrafficSources,
+ TrafficSummary,
+} from '@/lib/actions/traffic';
+import type { SourceState } from '@/lib/actions/integrations';
+
+/**
+ * AT-017 (spec §3.2): the AI Traffic page's KPI cards, two rows of four —
+ * the snippet's visits, and what Google Analytics and Google Search Console
+ * add — with each Google card's connection state until its source has data.
+ */
+
+const getTrafficGoogleTotals = vi.fn();
+vi.mock('@/lib/actions/traffic', () => ({
+ getTrafficGoogleTotals: (...args: unknown[]) => getTrafficGoogleTotals(...args),
+}));
+const connect = vi.fn();
+vi.mock('@/hooks/use-integration-connect', () => ({
+ useIntegrationConnect: () => ({ connecting: false, connect }),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,
+}));
+
+const { TrafficKpis } = await import('./_kpis');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const synced = (over: Partial<SourceState> = {}): SourceState => ({
+ configured: true,
+ connected: true,
+ mapped: true,
+ firstDataAt: '2026-09-01T06:00:00.000Z',
+ lastDataAt: '2026-10-18T06:00:00.000Z',
+ property: '123456789',
+ ...over,
+});
+const notConnected = synced({ connected: false, mapped: false, lastDataAt: null, property: null });
+
+const sources = (ga: SourceState, gsc: SourceState): TrafficSources => ({
+ snippetLastVisitAt: '2026-10-18T09:00:00.000Z',
+ ga,
+ gsc,
+});
+
+const summary = (over: Partial<TrafficSummary> = {}): TrafficSummary => ({
+ totalVisits: 4,
+ totalVisitsPrev: 3,
+ totalPageviews: 7,
+ hasPreviousPeriod: true,
+ platformBreakdown: [
+ { platform: 'gemini.google.com', visits: 2, visitsPrev: 1 },
+ { platform: 'chatgpt.com', visits: 1, visitsPrev: 1 },
+ { platform: 'perplexity.ai', visits: 1, visitsPrev: 1 },
+ ],
+ topPages: [],
+ hasAnyData: true,
+ ...over,
+});
+
+const TOTALS: TrafficGoogleTotals = {
+ ga: { sessions: 812, aiSessions: 4, aiEngagedSessions: 3, aiKeyEvents: 1 },
+ gsc: {
+ since: '2026-10-16',
+ until: '2026-10-16',
+ clicks: 412,
+ prevClicks: 438,
+ },
+};
+
+const DAY: TrafficDateWindow = { dateFrom: '2026-10-17T12:30:00.000Z' };
+
+let container: HTMLDivElement;
+let root: Root;
+const onRangeChange = vi.fn();
+const onConnected = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getTrafficGoogleTotals.mockResolvedValue(TOTALS);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render({
+ preset = '24h',
+ dateWindow = DAY,
+ sum = summary(),
+ summaryLoading = false,
+ src = sources(synced(), synced({ property: 'sc-domain:acme.example' })),
+ sourcesFailed = false,
+ canConnect = true,
+}: {
+ preset?: DateRangePreset;
+ dateWindow?: TrafficDateWindow;
+ sum?: TrafficSummary | null;
+ summaryLoading?: boolean;
+ src?: TrafficSources | null;
+ sourcesFailed?: boolean;
+ canConnect?: boolean;
+} = {}) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <TrafficKpis
+ brandId="b1"
+ dateWindow={dateWindow}
+ preset={preset}
+ summary={sum}
+ summaryLoading={summaryLoading}
+ sources={src}
+ sourcesFailed={sourcesFailed}
+ canConnect={canConnect}
+ onConnected={onConnected}
+ onRangeChange={onRangeChange}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+/** Each card's text, by its label. */
+function card(label: string): string {
+ const cards = [...container.querySelectorAll('[data-slot="card"]')];
+ const found = cards.find((c) => c.textContent?.startsWith(label));
+ if (!found) throw new Error(`No card "${label}" in: ${container.textContent}`);
+ return found.textContent ?? '';
+}
+
+describe('TrafficKpis', () => {
+ it('shows the snippet and Google cards in the spec order, the AI Overviews card hidden', async () => {
+ await render();
+ const labels = [...container.querySelectorAll('[data-slot="card"]')].map(
+ (c) => c.querySelector('.truncate')?.textContent,
+ );
+ expect(labels).toEqual([
+ 'AI-referred visits',
+ 'Top platform',
+ 'Platforms',
+ 'AI share of traffic',
+ 'Engaged visits',
+ 'Key events from AI',
+ 'Google clicks',
+ ]);
+ });
+
+ it('writes the snippet cards, with Low sample below 30 visits', async () => {
+ await render();
+ expect(card('AI-referred visits')).toContain('4Low sample');
+ expect(card('AI-referred visits')).toContain('7 pageviews · 3 in the previous period');
+ // Cut off on a narrow card, it reads in full on hover.
+ expect(
+ container.querySelector('[title="7 pageviews · 3 in the previous period"]'),
+ ).not.toBeNull();
+ expect(card('Top platform')).toContain('Gemini');
+ expect(card('Top platform')).toContain('2 visits');
+ expect(card('Platforms')).toContain('3unique AI sources');
+ });
+
+ it('shows a % change once both periods have 30 visits', async () => {
+ await render({ sum: summary({ totalVisits: 45, totalVisitsPrev: 30 }) });
+ expect(card('AI-referred visits')).toContain('45+50%');
+ });
+
+ it("asks for the range's Google totals, Search Console's latest day for 24 hours", async () => {
+ await render();
+ expect(getTrafficGoogleTotals).toHaveBeenCalledWith('b1', DAY, {
+ ga: true,
+ gsc: true,
+ gscLatestDays: 1,
+ });
+ });
+
+ it('writes the spec examples on the Google cards', async () => {
+ await render();
+ expect(card('AI share of traffic')).toContain('0.5%4 of 812 sessions');
+ // 4 AI sessions: a rate, marked Low sample (§5.4).
+ expect(card('Engaged visits')).toContain('75%Low sample3 of 4 AI sessions');
+ expect(card('Key events from AI')).toContain('1in 4 AI sessions');
+ expect(card('Google clicks')).toContain('412−6%');
+ expect(card('Google clicks')).toContain('Oct 16 · latest reported day');
+ });
+
+ it("names a week's latest days, and a longer range's previous period", async () => {
+ getTrafficGoogleTotals.mockResolvedValue({
+ ...TOTALS,
+ gsc: { ...TOTALS.gsc!, since: '2026-10-10', until: '2026-10-16' },
+ });
+ await render({ preset: '7d', dateWindow: { dateFrom: '2026-10-11T12:30:00.000Z' } });
+ expect(card('Google clicks')).toContain('Oct 10 – Oct 16 · latest reported days');
+
+ getTrafficGoogleTotals.mockResolvedValue(TOTALS);
+ await render({ preset: '30d', dateWindow: { dateFrom: '2026-09-18T12:30:00.000Z' } });
+ expect(getTrafficGoogleTotals).toHaveBeenLastCalledWith(
+ 'b1',
+ { dateFrom: '2026-09-18T12:30:00.000Z' },
+ { ga: true, gsc: true, gscLatestDays: null },
+ );
+ expect(card('Google clicks')).toContain('438 in the previous period');
+ });
+
+ it('offers 30 days when a short range has no key events', async () => {
+ getTrafficGoogleTotals.mockResolvedValue({
+ ...TOTALS,
+ ga: { ...TOTALS.ga!, aiKeyEvents: 0 },
+ });
+ await render();
+ expect(card('Key events from AI')).toContain('0none in 24h · see 30d');
+
+ const see30d = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'see 30d',
+ )!;
+ act(() => see30d.click());
+ expect(onRangeChange).toHaveBeenCalledWith('30d');
+ });
+
+ it('says when Analytics has nothing for the days, or no AI sessions', async () => {
+ getTrafficGoogleTotals.mockResolvedValue({
+ ...TOTALS,
+ ga: { sessions: 0, aiSessions: 0, aiEngagedSessions: 0, aiKeyEvents: 0 },
+ });
+ await render({ preset: '30d' });
+ expect(card('AI share of traffic')).toContain('—No data in this range');
+ expect(card('Engaged visits')).toContain('—No data in this range');
+
+ getTrafficGoogleTotals.mockResolvedValue({
+ ...TOTALS,
+ ga: { sessions: 812, aiSessions: 0, aiEngagedSessions: 0, aiKeyEvents: 0 },
+ });
+ await render({ preset: '90d', dateWindow: { dateFrom: '2026-07-20T12:30:00.000Z' } });
+ expect(card('Engaged visits')).toContain('—No AI sessions in this range');
+ });
+
+ it('shows each Google card as needing its source, with Connect', async () => {
+ await render({ src: sources(notConnected, notConnected) });
+ expect(getTrafficGoogleTotals).not.toHaveBeenCalled();
+ for (const label of ['AI share of traffic', 'Engaged visits', 'Key events from AI']) {
+ expect(card(label)).toContain('—Needs Google Analytics');
+ }
+ expect(card('Google clicks')).toContain('—Needs Google Search Console');
+
+ const buttons = [...container.querySelectorAll('button')].filter(
+ (b) => b.textContent === 'Connect',
+ );
+ expect(buttons).toHaveLength(4);
+ act(() => buttons[0].click());
+ expect(connect).toHaveBeenCalled();
+ });
+
+ it('reads only the source that has data', async () => {
+ await render({ src: sources(notConnected, synced({ property: 'sc-domain:acme.example' })) });
+ expect(getTrafficGoogleTotals).toHaveBeenCalledWith('b1', DAY, {
+ ga: false,
+ gsc: true,
+ gscLatestDays: 1,
+ });
+ expect(card('Google clicks')).toContain('412');
+ });
+
+ it('says how long the first sync takes, and where to choose a property', async () => {
+ await render({
+ src: sources(
+ synced({ lastDataAt: null }),
+ synced({ mapped: false, lastDataAt: null, property: null }),
+ ),
+ });
+ expect(card('Engaged visits')).toContain('Syncing… · about 15 min');
+ expect(card('Google clicks')).toContain('Choose a property for this brand');
+ expect(container.querySelector('a')!.getAttribute('href')).toBe(
+ '/dashboard/settings?tab=integrations',
+ );
+ });
+
+ it('shows "—" while the sources load, and tries the numbers when they fail to', async () => {
+ await render({ src: null });
+ expect(getTrafficGoogleTotals).not.toHaveBeenCalled();
+ expect(card('Google clicks')).toContain('—');
+
+ await render({ src: null, sourcesFailed: true });
+ expect(getTrafficGoogleTotals).toHaveBeenCalledWith('b1', DAY, {
+ ga: true,
+ gsc: true,
+ gscLatestDays: 1,
+ });
+ expect(card('AI share of traffic')).toContain('0.5%');
+ });
+
+ it('shows "—" when the totals fail, and never a previous range\'s totals', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ getTrafficGoogleTotals.mockRejectedValue(new Error('boom'));
+ await render();
+ expect(card('AI share of traffic')).toBe('AI share of traffic—');
+ error.mockRestore();
+
+ getTrafficGoogleTotals.mockResolvedValue(TOTALS);
+ await render({ preset: '7d', dateWindow: { dateFrom: '2026-10-11T12:30:00.000Z' } });
+ expect(card('AI share of traffic')).toContain('0.5%');
+ // A new range: until its totals arrive, the old ones aren't shown.
+ getTrafficGoogleTotals.mockReturnValue(new Promise(() => {}));
+ await render({ preset: 'all', dateWindow: {} });
+ expect(card('AI share of traffic')).toBe('AI share of traffic—');
+ });
+
+ it("waits for the range's visits before writing AI share of traffic", async () => {
+ await render({ summaryLoading: true });
+ expect(card('AI share of traffic')).toBe('AI share of traffic—');
+ expect(card('Engaged visits')).toContain('75%');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
new file mode 100644
index 000000000..391bec556
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
@@ -0,0 +1,295 @@
+'use client';
+
+import { useEffect, useState, type ReactNode } from 'react';
+import { useTranslations } from 'next-intl';
+import {
+ Flag,
+ Globe,
+ LayoutGrid,
+ MousePointerClick,
+ PieChart,
+ Timer,
+ Users,
+ type LucideIcon,
+} from 'lucide-react';
+import type { DateRangePreset } from '@/components/filters/date-range-filter';
+import {
+ getTrafficGoogleTotals,
+ type TrafficDateWindow,
+ type TrafficGoogleTotals,
+ type TrafficSources,
+ type TrafficSummary,
+} from '@/lib/actions/traffic';
+import { formatNumber } from '@/lib/format';
+import { LOW_SAMPLE_VISITS, visitChange, type VisitChange } from '@/lib/traffic-change';
+import {
+ formatGoogleDays,
+ formatPctChange,
+ formatShare,
+ gscLatestDays,
+ isShortRange,
+} from '@/lib/traffic-kpis';
+import { getPlatformName } from '@/lib/traffic-platforms';
+import { googleSourceStatus, TRAFFIC_SECTION_SOURCES } from '@/lib/traffic-sources';
+import { MetricCard } from '../insights/_kpi-cards';
+import type { Change } from '../insights/kpi-format';
+import { SourceKpiCard } from './_source-gate';
+
+// Four in a row from 1,100px, two below (spec §3.2), one on a phone. In rem,
+// so Tailwind orders it after sm: (a px breakpoint would sort before it).
+export const TRAFFIC_KPI_GRID = 'grid grid-cols-1 gap-4 sm:grid-cols-2 min-[68.75rem]:grid-cols-4';
+
+type CardHead = { label: string; tooltip: string; icon: LucideIcon };
+type CardBody = { value: string; delta?: Change | null; sub?: ReactNode };
+type GaTotals = NonNullable<TrafficGoogleTotals['ga']>;
+
+/** A Google card while its numbers load, or when they failed to. */
+const PENDING: CardBody = { value: '—' };
+
+/** A count's change as a card shows it: none, "new", "Low sample", or a %. */
+function useChangeDelta() {
+ const t = useTranslations('traffic.change');
+ return (change: VisitChange): Change | null => {
+ if (change.kind === 'none') return null;
+ if (change.kind === 'new') return { text: t('new'), tone: 'good' };
+ if (change.kind === 'low') return { text: t('lowSample'), tone: 'neutral' };
+ return { text: formatPctChange(change.pct), tone: change.pct > 0 ? 'good' : 'bad' };
+ };
+}
+
+/** A link-styled button inside a card's sub-line. */
+function SubAction({ onClick, children }: { onClick: () => void; children: ReactNode }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="font-medium text-foreground underline underline-offset-2"
+ >
+ {children}
+ </button>
+ );
+}
+
+/**
+ * The AI Traffic page's KPI cards (AT-017, spec §3.2), Insights style, in
+ * two rows of four:
+ *
+ * 1. AI-referred visits, top platform and platforms, from the tracking
+ * snippet; and AI share of traffic: those visits against every session
+ * Google Analytics recorded on the same days ("0.5% · 4 of 812 sessions").
+ * 2. From Google Analytics, engaged visits and key events from AI; from
+ * Google Search Console, Google clicks. The spec's AI Overviews card waits
+ * for Google to expose that report (§10.1), so the row has three.
+ *
+ * A Google card whose source has no data yet shows the compact connection
+ * state instead (AT-016). Comparisons with Google organic come with AT-005.
+ */
+export function TrafficKpis({
+ brandId,
+ dateWindow,
+ preset,
+ summary,
+ summaryLoading,
+ sources,
+ sourcesFailed,
+ canConnect,
+ onConnected,
+ onRangeChange,
+}: {
+ brandId: string;
+ dateWindow: TrafficDateWindow;
+ preset: DateRangePreset;
+ summary: TrafficSummary | null;
+ /** The summary is still the previous range's while a new one loads. */
+ summaryLoading: boolean;
+ /** The Google sources' states; null while they load. */
+ sources: TrafficSources | null;
+ /** The states couldn't be read: try the numbers anyway, as the GA card does. */
+ sourcesFailed: boolean;
+ canConnect: boolean;
+ onConnected: () => void;
+ /** Switches the page's range, for "see 30d". */
+ onRangeChange: (preset: DateRangePreset) => void;
+}) {
+ const t = useTranslations('traffic.kpis');
+ const tVisits = useTranslations('traffic.visits');
+ const delta = useChangeDelta();
+
+ const sourceReady = (state: TrafficSources['ga'] | undefined) =>
+ state ? googleSourceStatus(state) === 'connected' : sourcesFailed;
+ const gaReady = sourceReady(sources?.ga);
+ const gscReady = sourceReady(sources?.gsc);
+ const latestDays = gscLatestDays(preset);
+ const key = [brandId, dateWindow.dateFrom, dateWindow.dateTo, gaReady, gscReady, latestDays].join(
+ '|',
+ );
+ // The loaded totals carry the request they answer, as on the GA card, so
+ // no loading flag is reset inside the effect. Totals for another range
+ // show as "—" until the new ones arrive, and AI share of traffic waits for
+ // the summary too: it divides one range's visits by the same range's
+ // sessions, and either one from the old range would give a wrong share.
+ const [loaded, setLoaded] = useState<{ key: string; totals: TrafficGoogleTotals | null } | null>(
+ null,
+ );
+
+ useEffect(() => {
+ if (!gaReady && !gscReady) return;
+ let cancelled = false;
+ getTrafficGoogleTotals(brandId, dateWindow, {
+ ga: gaReady,
+ gsc: gscReady,
+ gscLatestDays: latestDays,
+ })
+ .then((totals) => {
+ if (!cancelled) setLoaded({ key, totals });
+ })
+ .catch((err) => {
+ // Best effort: these cards add to the page and must not take it down.
+ console.error('Failed to load the Google totals:', err);
+ if (!cancelled) setLoaded({ key, totals: null });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, dateWindow, gaReady, gscReady, latestDays, key]);
+
+ const totalVisits = summary?.totalVisits ?? 0;
+ const totalVisitsPrev = summary?.totalVisitsPrev ?? 0;
+ const totalPageviews = summary?.totalPageviews ?? 0;
+ // From the summary, not the selected range: while a new range loads, the
+ // numbers on screen are still the previous range's.
+ const comparable = summary?.hasPreviousPeriod ?? false;
+ const topPlatform = summary?.platformBreakdown[0];
+ const totals = loaded?.key === key ? loaded.totals : null;
+ const ga = totals?.ga ?? null;
+ const gsc = totals?.gsc ?? null;
+
+ /** A Google card's compact state while its source has no data yet; null once it has. */
+ const gate = (section: keyof typeof TRAFFIC_SECTION_SOURCES, card: CardHead) => {
+ const provider = TRAFFIC_SECTION_SOURCES[section];
+ const state = provider === 'google-analytics' ? sources?.ga : sources?.gsc;
+ if (!state || googleSourceStatus(state) === 'connected') return null;
+ return (
+ <SourceKpiCard
+ {...card}
+ provider={provider}
+ state={state}
+ canConnect={canConnect}
+ onConnected={onConnected}
+ />
+ );
+ };
+
+ /** An Analytics card's numbers: "—" while they load, and a note when the days have none. */
+ const fromGa = (fill: (totals: GaTotals) => CardBody): CardBody =>
+ !ga ? PENDING : ga.sessions === 0 ? { value: '—', sub: t('noRangeData') } : fill(ga);
+
+ const aiShare = { label: t('aiShare'), tooltip: t('aiShareTip'), icon: PieChart };
+ const engaged = { label: t('engaged'), tooltip: t('engagedTip'), icon: Timer };
+ const keyEvents = { label: t('keyEvents'), tooltip: t('keyEventsTip'), icon: Flag };
+ const clicks = {
+ label: t('googleClicks'),
+ tooltip: t('googleClicksTip'),
+ icon: MousePointerClick,
+ };
+
+ const clicksBody = (): CardBody => {
+ if (!gsc) return PENDING;
+ const days = formatGoogleDays(gsc.since, gsc.until);
+ return {
+ value: formatNumber(gsc.clicks),
+ delta: delta(
+ visitChange(gsc.clicks, gsc.prevClicks ?? 0, { comparable: gsc.prevClicks !== null }),
+ ),
+ sub:
+ // Short ranges read Google's latest reported days (§3.01).
+ latestDays === 1
+ ? t('latestDay', { days })
+ : latestDays
+ ? t('latestDays', { days })
+ : gsc.prevClicks === null
+ ? t('allTime')
+ : t('clicksPrevious', { previous: gsc.prevClicks }),
+ };
+ };
+
+ return (
+ <div className={TRAFFIC_KPI_GRID}>
+ {/* One visit per session; the sub-line gives the pageviews and the
+ previous period's visits (AT-003). */}
+ <MetricCard
+ label={t('visits')}
+ tooltip={t('visitsTip')}
+ icon={Users}
+ value={formatNumber(totalVisits)}
+ delta={delta(visitChange(totalVisits, totalVisitsPrev, { comparable }))}
+ sub={
+ comparable
+ ? tVisits('kpiSub', { pageviews: totalPageviews, previous: totalVisitsPrev })
+ : tVisits('kpiSubNoPrevious', { pageviews: totalPageviews })
+ }
+ />
+ <MetricCard
+ label={t('topPlatform')}
+ tooltip={t('topPlatformTip')}
+ icon={Globe}
+ value={topPlatform ? getPlatformName(topPlatform.platform) : '—'}
+ sub={topPlatform ? t('topPlatformSub', { visits: topPlatform.visits }) : t('noData')}
+ />
+ <MetricCard
+ label={t('platforms')}
+ tooltip={t('platformsTip')}
+ icon={LayoutGrid}
+ value={formatNumber(summary?.platformBreakdown.length ?? 0)}
+ sub={t('platformsSub')}
+ />
+ {gate('aiShare', aiShare) ?? (
+ <MetricCard
+ {...aiShare}
+ {...(summaryLoading
+ ? // The visits and the sessions must be the same range's.
+ PENDING
+ : fromGa(({ sessions }) => ({
+ value: formatShare(totalVisits, sessions) ?? '—',
+ sub: t('aiShareSub', { visits: totalVisits, sessions }),
+ })))}
+ />
+ )}
+ {/* Row 2: what AI visitors do, and Google's own clicks. */}
+ {gate('engagedVisits', engaged) ?? (
+ <MetricCard
+ {...engaged}
+ {...fromGa(({ aiSessions, aiEngagedSessions }) =>
+ aiSessions === 0
+ ? { value: '—', sub: t('noAiSessions') }
+ : {
+ value: formatShare(aiEngagedSessions, aiSessions) ?? '—',
+ // A rate on a handful of sessions says more about chance (§5.4).
+ delta: aiSessions < LOW_SAMPLE_VISITS ? delta({ kind: 'low' }) : null,
+ sub: t('engagedSub', { engaged: aiEngagedSessions, sessions: aiSessions }),
+ },
+ )}
+ />
+ )}
+ {gate('keyEvents', keyEvents) ?? (
+ <MetricCard
+ {...keyEvents}
+ {...fromGa(({ aiSessions, aiKeyEvents }) => ({
+ value: formatNumber(aiKeyEvents),
+ sub:
+ // None in a short range is usual: offer the month (spec §3.2).
+ aiKeyEvents === 0 && isShortRange(preset) ? (
+ <>
+ {t('keyEventsNone', { range: preset })} ·{' '}
+ <SubAction onClick={() => onRangeChange('30d')}>{t('see30d')}</SubAction>
+ </>
+ ) : (
+ t('keyEventsSub', { sessions: aiSessions })
+ ),
+ }))}
+ />
+ )}
+ {gate('googleClicks', clicks) ?? <MetricCard {...clicks} {...clicksBody()} />}
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.test.tsx
index 481771313..62a99fe52 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.test.tsx
@@ -3,6 +3,7 @@ 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 { Timer } from 'lucide-react';
import type { IntegrationProvider, SourceState } from '@/lib/actions/integrations';
/**
@@ -24,7 +25,7 @@ vi.mock('@/i18n/navigation', () => ({
Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,
}));
-const { NeedsTag, SourceNoData, SourceUnavailable } = await import('./_source-gate');
+const { NeedsTag, SourceKpiCard, SourceNoData, SourceUnavailable } = await import('./_source-gate');
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
true;
@@ -91,7 +92,10 @@ describe('SourceUnavailable', () => {
renderState(source());
expect(text()).toContain('Connect Google Analytics to see this');
expect(text()).toContain('Read-only access, takes about a minute.');
- expect(text()).toContain("Needed for: pages AI engines aren't sending traffic to");
+ expect(text()).toContain(
+ 'Needed for: AI share of traffic, engaged visits, key events from AI, and pages AI engines ' +
+ "aren't sending traffic to",
+ );
act(() => button()!.click());
expect(hook.connect).toHaveBeenCalled();
@@ -139,10 +143,10 @@ describe('SourceUnavailable', () => {
expect(container.querySelector('a')).toBeNull();
});
- it('lists nothing it unlocks for a source no section needs yet', () => {
+ it('lists what Search Console unlocks', () => {
renderState(source(), { provider: 'google-search-console' });
expect(text()).toContain('Connect Google Search Console to see this');
- expect(text()).not.toContain('Needed for');
+ expect(text()).toContain('Needed for: Google clicks');
});
it('renders nothing once the source has data', () => {
@@ -167,3 +171,66 @@ describe('SourceNoData', () => {
expect(onShowAllTime).toHaveBeenCalled();
});
});
+
+describe('SourceKpiCard', () => {
+ function renderCard(
+ state: SourceState,
+ { provider = 'google-analytics', canConnect = true } = {} as {
+ provider?: IntegrationProvider;
+ canConnect?: boolean;
+ },
+ ) {
+ render(
+ <SourceKpiCard
+ label="Engaged visits"
+ tooltip="Engaged AI sessions."
+ icon={Timer}
+ provider={provider}
+ state={state}
+ canConnect={canConnect}
+ onConnected={onConnected}
+ />,
+ );
+ }
+
+ it('keeps the label, shows "—", and offers Connect in place (AT-017)', () => {
+ renderCard(source());
+ expect(text()).toBe('Engaged visits—Needs Google AnalyticsConnect');
+ act(() => button()!.click());
+ expect(hook.connect).toHaveBeenCalled();
+ act(() => hook.options!.onStatus('connected'));
+ expect(onConnected).toHaveBeenCalled();
+ });
+
+ it("keeps Connect off, with a reason, for members who can't connect", () => {
+ renderCard(source(), { canConnect: false });
+ expect(button()!.disabled).toBe(true);
+ expect(button()!.parentElement!.title).toBe('Only admins and managers can connect a source.');
+ });
+
+ it("gives each source's wait while it syncs", () => {
+ renderCard(source({ connected: true, mapped: true }));
+ expect(text()).toContain('Syncing… · about 15 min');
+ renderCard(source({ connected: true, mapped: true }), { provider: 'google-search-console' });
+ expect(text()).not.toContain('Needs');
+ expect(text()).toContain('Syncing… · up to 48 h');
+ });
+
+ it('sends a connection without a property to Manage, and offers nothing on a server without keys', () => {
+ renderCard(source({ connected: true }));
+ expect(text()).toContain('Choose a property for this brand');
+ expect(container.querySelector('a')!.getAttribute('href')).toBe(
+ '/dashboard/settings?tab=integrations',
+ );
+
+ renderCard(source({ configured: false }));
+ expect(text()).toContain('Not set up on this server');
+ expect(button()).toBeNull();
+ expect(container.querySelector('a')).toBeNull();
+ });
+
+ it('renders nothing once the source has data', () => {
+ renderCard(source({ connected: true, mapped: true, lastDataAt: '2026-10-18T06:00:00Z' }));
+ expect(container.innerHTML).toBe('');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.tsx
index 6d4783ff2..4f01ea6c5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.tsx
@@ -2,7 +2,7 @@
import type { ReactNode } from 'react';
import { useTranslations } from 'next-intl';
-import { Loader2, Plug } from 'lucide-react';
+import { Loader2, Plug, type LucideIcon } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import { buttonVariants } from '@/components/ui/button-variants';
@@ -15,6 +15,7 @@ import {
sectionsNeeding,
sourceHost,
} from '@/lib/traffic-sources';
+import { MetricCard } from '../insights/_kpi-cards';
/**
* What a section that needs Google Analytics or Google Search Console shows
@@ -22,8 +23,8 @@ import {
* its title, always, and — until the source has data — a state in place of
* the data that says what's missing and what happens next.
*
- * The full state is the one a section uses today. The compact KPI version
- * and the partial note come with the sections that need them.
+ * Sections show the full state; KPI cards the compact one (AT-017). The
+ * partial note comes with the sections that need it.
*/
const isGa = (provider: IntegrationProvider) => provider === 'google-analytics';
@@ -206,3 +207,95 @@ export function SourceNoData({
</div>
);
}
+
+/**
+ * A KPI card whose source has no data for it yet: the compact state (spec
+ * §3.8b). The card keeps its label and shows "—", and one line says what's
+ * missing — "Needs Google Analytics" with Connect, "Syncing…" with the wait,
+ * a property to choose with Manage, or a server without the keys. Renders
+ * nothing once the source is connected and synced; the card shows its data.
+ */
+export function SourceKpiCard({
+ label,
+ tooltip,
+ icon,
+ provider,
+ state,
+ canConnect,
+ onConnected,
+}: {
+ label: string;
+ tooltip: string;
+ icon: LucideIcon;
+ provider: IntegrationProvider;
+ state: SourceState;
+ canConnect: boolean;
+ onConnected: () => void;
+}) {
+ const t = useTranslations('traffic');
+ const source = isGa(provider) ? t('sources.ga') : t('sources.gsc');
+ const { connecting, connect } = useIntegrationConnect(provider, {
+ label: source,
+ callbackUrl: () => window.location.href,
+ onStatus: (status) => {
+ if (status === 'connected') onConnected();
+ },
+ });
+
+ const status = googleSourceStatus(state);
+ if (status === 'connected') return null;
+
+ const card = (sub: ReactNode, footer?: ReactNode) => (
+ <MetricCard
+ label={label}
+ tooltip={tooltip}
+ icon={icon}
+ value="—"
+ sub={sub}
+ // The sparkline's height, so a card with a button and one without line up.
+ footer={footer ?? <div className="h-6" aria-hidden />}
+ />
+ );
+
+ if (status === 'syncing') {
+ return card(
+ <span className="flex items-center gap-1.5">
+ <Loader2 className="h-3 w-3 shrink-0 animate-spin" />
+ <span className="truncate">
+ {t('kpis.syncing')} · {isGa(provider) ? t('kpis.waitGa') : t('kpis.waitGsc')}
+ </span>
+ </span>,
+ );
+ }
+
+ if (status === 'unmapped') {
+ return card(
+ t('kpis.unmapped'),
+ <Link
+ href={INTEGRATIONS_SETTINGS_PATH}
+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-6 self-start text-xs')}
+ >
+ {t('sources.manage')}
+ </Link>,
+ );
+ }
+
+ if (status === 'not_configured') return card(t('sources.notConfigured'));
+
+ return card(
+ t('gate.needs', { source }),
+ // A span carries the tooltip: a disabled button gets no hover.
+ <span className="self-start" title={canConnect ? undefined : t('sources.connectNotAllowed')}>
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-6 gap-1.5 text-xs"
+ disabled={!canConnect || connecting}
+ onClick={() => void connect()}
+ >
+ {connecting && <Loader2 className="h-3 w-3 animate-spin" />}
+ {connecting ? t('sources.connecting') : t('sources.connect')}
+ </Button>
+ </span>,
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index 39e76819d..50c1bef00 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -37,6 +37,7 @@ import {
type DateRangePreset,
} from '@/components/filters/date-range-filter';
import { PageOpportunitiesCard } from './_opportunities-card';
+import { TRAFFIC_KPI_GRID, TrafficKpis } from './_kpis';
import { ExportMenu, TableExport, useTrafficExport } from './_export';
import { SourcesStrip } from './_sources-strip';
import { SnippetBanner, SnippetDialog } from './_snippet-code';
@@ -56,7 +57,6 @@ import {
Globe,
TrendingUp,
TrendingDown,
- Users,
LayoutList,
Search,
X,
@@ -82,39 +82,6 @@ const PAGE_SIZE = 10;
// ─── Sub-components ───────────────────────────────────────────────────────────
-function KpiCard({
- title,
- icon: Icon,
- value,
- sub,
-}: {
- title: string;
- icon: React.ElementType;
- value: React.ReactNode;
- sub: React.ReactNode;
-}) {
- return (
- <Card>
- <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-1">
- <CardTitle className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- {title}
- </CardTitle>
- <Icon className="h-3.5 w-3.5 text-muted-foreground" />
- </CardHeader>
- <CardContent>
- <div className="text-3xl font-bold">{value}</div>
- {/* One line, as in the approved mockup; the full text on hover. */}
- <p
- className="mt-1 truncate text-xs text-muted-foreground"
- title={typeof sub === 'string' ? sub : undefined}
- >
- {sub}
- </p>
- </CardContent>
- </Card>
- );
-}
-
/**
* A visit count against the previous period: a %, "new", "—", or "Low sample"
* when either period is too small for a % to mean anything (AT-003, F4).
@@ -583,9 +550,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
<Skeleton className="h-8 w-64" />
<Skeleton className="h-4 w-96 mt-2" />
</div>
- <div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
- {[1, 2, 3].map((i) => (
- <Skeleton key={i} className="h-24" />
+ <div className={TRAFFIC_KPI_GRID}>
+ {Array.from({ length: 7 }, (_, i) => (
+ // The cards' own height, so nothing shifts when they arrive.
+ <Skeleton key={i} className="h-[133px] rounded-xl" />
))}
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
@@ -597,12 +565,9 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
}
const totalVisits = summary?.totalVisits ?? 0;
- const totalVisitsPrev = summary?.totalVisitsPrev ?? 0;
- const totalPageviews = summary?.totalPageviews ?? 0;
// From the summary, not the selected range: while a new range loads, the
// numbers on screen are still the previous range's.
const comparable = summary?.hasPreviousPeriod ?? false;
- const topPlatform = summary?.platformBreakdown[0];
const isEmpty = totalVisits === 0 && logs.length === 0;
const hasAnyData = summary?.hasAnyData ?? false;
@@ -691,45 +656,19 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
{isEmpty && opportunitiesCard}
{!isEmpty && (
<>
- {/* KPI Cards */}
- <div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
- {/* One visit per session; the sub-line gives the pageviews and
- the previous period's visits (AT-003). */}
- <KpiCard
- title="AI-Referred Visits"
- icon={Users}
- value={
- <span className="flex items-center gap-2">
- {formatNumber(totalVisits)}
- {/* The tables show "—" for no change; the card shows nothing. */}
- {visitChange(totalVisits, totalVisitsPrev, { comparable }).kind !== 'none' && (
- <DeltaBadge
- current={totalVisits}
- previous={totalVisitsPrev}
- comparable={comparable}
- />
- )}
- </span>
- }
- sub={
- comparable
- ? tVisits('kpiSub', { pageviews: totalPageviews, previous: totalVisitsPrev })
- : tVisits('kpiSubNoPrevious', { pageviews: totalPageviews })
- }
- />
- <KpiCard
- title="Top Platform"
- icon={Globe}
- value={topPlatform ? getPlatformName(topPlatform.platform) : '—'}
- sub={topPlatform ? `${formatNumber(topPlatform.visits)} visits` : 'no data'}
- />
- <KpiCard
- title="Platforms"
- icon={Globe}
- value={summary?.platformBreakdown.length ?? 0}
- sub="unique AI sources"
- />
- </div>
+ {/* KPI cards: two rows of four (AT-017, spec §3.2). */}
+ <TrafficKpis
+ brandId={brand.id}
+ dateWindow={dateWindow}
+ preset={datePreset}
+ summary={summary}
+ summaryLoading={isLoadingSummary}
+ sources={sources}
+ sourcesFailed={sourcesFailed}
+ canConnect={canManage}
+ onConnected={() => void loadSources()}
+ onRangeChange={handleDatePresetChange}
+ />
{/* Charts row */}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
diff --git a/web/src/lib/actions/traffic-google-totals.test.ts b/web/src/lib/actions/traffic-google-totals.test.ts
new file mode 100644
index 000000000..30f0c6a7b
--- /dev/null
+++ b/web/src/lib/actions/traffic-google-totals.test.ts
@@ -0,0 +1,143 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * AT-017 (spec §3.2): the KPI cards' Google totals come from two database
+ * functions, asked for only when their source has data, with Search
+ * Console's short ranges ending on its latest reported day.
+ */
+
+const rpc = vi.fn();
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({
+ rpc: (fn: string, args: Record<string, unknown>) => ({ single: () => rpc(fn, args) }),
+ }),
+}));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
+
+import { getTrafficGoogleTotals } from './traffic';
+
+const GA_ROW = { sessions: 812, ai_sessions: 4, ai_engaged_sessions: 3, ai_key_events: 1 };
+const GSC_ROW = {
+ since: '2026-10-16',
+ until: '2026-10-16',
+ clicks: 36,
+ prev_clicks: 30,
+ last_date: '2026-10-16',
+};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-18T12:30:00.000Z'));
+ rpc.mockReset();
+ rpc.mockImplementation(async (fn: string) => ({
+ data: fn === 'ga_traffic_totals' ? GA_ROW : GSC_ROW,
+ error: null,
+ }));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+const DAY = { dateFrom: '2026-10-17T12:30:00.000Z' };
+
+describe('getTrafficGoogleTotals', () => {
+ it("reads the range's days, and Search Console's latest reported day for 24 hours", async () => {
+ const totals = await getTrafficGoogleTotals('b1', DAY, {
+ ga: true,
+ gsc: true,
+ gscLatestDays: 1,
+ });
+
+ expect(rpc).toHaveBeenCalledWith('ga_traffic_totals', {
+ p_brand_id: 'b1',
+ p_since: '2026-10-17',
+ p_until: '2026-10-18',
+ });
+ expect(rpc).toHaveBeenCalledWith('gsc_click_totals', {
+ p_brand_id: 'b1',
+ p_since: '2026-10-18',
+ p_until: '2026-10-18',
+ p_latest: true,
+ });
+ expect(totals).toEqual({
+ ga: { sessions: 812, aiSessions: 4, aiEngagedSessions: 3, aiKeyEvents: 1 },
+ gsc: {
+ since: '2026-10-16',
+ until: '2026-10-16',
+ clicks: 36,
+ prevClicks: 30,
+ },
+ });
+ });
+
+ it("asks for a week's worth of Search Console's latest days", async () => {
+ await getTrafficGoogleTotals(
+ 'b1',
+ { dateFrom: '2026-10-11T12:30:00.000Z' },
+ { ga: false, gsc: true, gscLatestDays: 7 },
+ );
+ expect(rpc).toHaveBeenCalledWith('gsc_click_totals', {
+ p_brand_id: 'b1',
+ p_since: '2026-10-12',
+ p_until: '2026-10-18',
+ p_latest: true,
+ });
+ });
+
+ it('reads a custom range as it is, and all time from the start', async () => {
+ await getTrafficGoogleTotals(
+ 'b1',
+ { dateFrom: '2026-09-01', dateTo: '2026-09-30T23:59:59.999Z' },
+ { ga: true, gsc: true, gscLatestDays: null },
+ );
+ expect(rpc).toHaveBeenCalledWith('gsc_click_totals', {
+ p_brand_id: 'b1',
+ p_since: '2026-09-01',
+ p_until: '2026-09-30',
+ p_latest: false,
+ });
+
+ rpc.mockClear();
+ await getTrafficGoogleTotals('b1', {}, { ga: true, gsc: false, gscLatestDays: null });
+ expect(rpc).toHaveBeenCalledWith('ga_traffic_totals', {
+ p_brand_id: 'b1',
+ p_since: null,
+ p_until: '2026-10-18',
+ });
+ });
+
+ it("doesn't ask a source without data", async () => {
+ const totals = await getTrafficGoogleTotals('b1', DAY, {
+ ga: false,
+ gsc: false,
+ gscLatestDays: 1,
+ });
+ expect(rpc).not.toHaveBeenCalled();
+ expect(totals).toEqual({ ga: null, gsc: null });
+ });
+
+ it('keeps no previous period for all time', async () => {
+ rpc.mockResolvedValue({
+ data: { ...GSC_ROW, since: null, prev_clicks: null },
+ error: null,
+ });
+ const totals = await getTrafficGoogleTotals(
+ 'b1',
+ {},
+ {
+ ga: false,
+ gsc: true,
+ gscLatestDays: null,
+ },
+ );
+ expect(totals.gsc).toMatchObject({ since: null, prevClicks: null });
+ });
+
+ it('fails loudly when a read fails', async () => {
+ rpc.mockResolvedValue({ data: null, error: { message: 'permission denied' } });
+ await expect(
+ getTrafficGoogleTotals('b1', DAY, { ga: true, gsc: false, gscLatestDays: 1 }),
+ ).rejects.toThrow('permission denied');
+ });
+});
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index 5f8f10b2e..d86944663 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -590,3 +590,89 @@ export async function getPageOpportunities(
})),
};
}
+
+/**
+ * The Google side of the AI Traffic KPI cards (AT-017, spec §3.2): from
+ * Analytics, all sessions and the AI channel's sessions, engaged sessions
+ * and key events; from Search Console, clicks against the period before.
+ * Each is asked for only when its source has data for the brand.
+ */
+export interface TrafficGoogleTotals {
+ ga: {
+ sessions: number;
+ aiSessions: number;
+ aiEngagedSessions: number;
+ aiKeyEvents: number;
+ } | null;
+ gsc: {
+ /** The days the clicks cover; no first day for all time. */
+ since: string | null;
+ until: string;
+ clicks: number;
+ /** The same-length period before; null for all time. */
+ prevClicks: number | null;
+ } | null;
+}
+
+export async function getTrafficGoogleTotals(
+ brandId: string,
+ window: TrafficDateWindow,
+ opts: {
+ ga: boolean;
+ gsc: boolean;
+ /**
+ * Short ranges read Search Console's latest reported day(s) — 1 for the
+ * 24-hour range, 7 for the week — because Google reports about two days
+ * late (spec §3.01). Null reads the range as it is.
+ */
+ gscLatestDays: number | null;
+ },
+): Promise<TrafficGoogleTotals> {
+ const supabase = await createClient();
+ // Both sources store whole days, so the range goes as its first and last.
+ const since = utcDay(window.dateFrom) ?? null;
+ const until = utcDay(window.dateTo) ?? new Date().toISOString().slice(0, 10);
+ const shift = (day: string, days: number) =>
+ new Date(Date.parse(`${day}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10);
+
+ const [ga, gsc] = await Promise.all([
+ opts.ga
+ ? supabase
+ .rpc('ga_traffic_totals', { p_brand_id: brandId, p_since: since, p_until: until })
+ .single()
+ : null,
+ opts.gsc
+ ? supabase
+ .rpc('gsc_click_totals', {
+ p_brand_id: brandId,
+ p_since: opts.gscLatestDays ? shift(until, 1 - opts.gscLatestDays) : since,
+ p_until: until,
+ p_latest: Boolean(opts.gscLatestDays),
+ })
+ .single()
+ : null,
+ ]);
+ if (ga?.error) throw new Error(ga.error.message);
+ if (gsc?.error) throw new Error(gsc.error.message);
+
+ const gaRow = ga?.data;
+ const gscRow = gsc?.data;
+ return {
+ ga: gaRow
+ ? {
+ sessions: Number(gaRow.sessions) || 0,
+ aiSessions: Number(gaRow.ai_sessions) || 0,
+ aiEngagedSessions: Number(gaRow.ai_engaged_sessions) || 0,
+ aiKeyEvents: Number(gaRow.ai_key_events) || 0,
+ }
+ : null,
+ gsc: gscRow
+ ? {
+ since: gscRow.since,
+ until: gscRow.until ?? until,
+ clicks: Number(gscRow.clicks) || 0,
+ prevClicks: gscRow.prev_clicks === null ? null : Number(gscRow.prev_clicks) || 0,
+ }
+ : null,
+ };
+}
diff --git a/web/src/lib/traffic-kpis.test.ts b/web/src/lib/traffic-kpis.test.ts
new file mode 100644
index 000000000..de15adfb6
--- /dev/null
+++ b/web/src/lib/traffic-kpis.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest';
+import {
+ formatGoogleDays,
+ formatPctChange,
+ formatShare,
+ gscLatestDays,
+ isShortRange,
+} from './traffic-kpis';
+
+/** AT-017 (spec §3.2): the rules behind the AI Traffic KPI cards. */
+
+describe('gscLatestDays', () => {
+ it("reads Google's latest reported day for 24 hours and its last 7 for the week", () => {
+ expect(gscLatestDays('24h')).toBe(1);
+ expect(gscLatestDays('7d')).toBe(7);
+ });
+
+ it('reads longer ranges, all time and custom ranges as they are', () => {
+ for (const preset of ['30d', '90d', 'all', 'custom'] as const) {
+ expect(gscLatestDays(preset)).toBeNull();
+ expect(isShortRange(preset)).toBe(false);
+ }
+ expect(isShortRange('24h')).toBe(true);
+ expect(isShortRange('7d')).toBe(true);
+ });
+});
+
+describe('formatShare', () => {
+ it('writes the spec example with one decimal below 10%', () => {
+ expect(formatShare(4, 812)).toBe('0.5%');
+ expect(formatShare(3, 4)).toBe('75%');
+ expect(formatShare(77, 812)).toBe('9.5%');
+ });
+
+ it('writes a sliver as <0.1%, and nothing as 0%', () => {
+ expect(formatShare(1, 5000)).toBe('<0.1%');
+ expect(formatShare(0, 812)).toBe('0%');
+ });
+
+ it('has no share without a whole', () => {
+ expect(formatShare(4, 0)).toBeNull();
+ });
+});
+
+describe('formatPctChange', () => {
+ it('signs a change with a true minus', () => {
+ expect(formatPctChange(12)).toBe('+12%');
+ expect(formatPctChange(-6)).toBe('−6%');
+ expect(formatPctChange(1250)).toBe('+1,250%');
+ });
+});
+
+describe('formatGoogleDays', () => {
+ it("names one day, or the range's first and last", () => {
+ expect(formatGoogleDays('2026-10-15', '2026-10-15')).toBe('Oct 15');
+ expect(formatGoogleDays('2026-10-10', '2026-10-16')).toBe('Oct 10 – Oct 16');
+ });
+
+ it('names the last day alone for all time', () => {
+ expect(formatGoogleDays(null, '2026-10-16')).toBe('Oct 16');
+ });
+});
diff --git a/web/src/lib/traffic-kpis.ts b/web/src/lib/traffic-kpis.ts
new file mode 100644
index 000000000..f9803d092
--- /dev/null
+++ b/web/src/lib/traffic-kpis.ts
@@ -0,0 +1,57 @@
+/**
+ * The rules behind the AI Traffic page's KPI cards (AT-017, spec §3.2), kept
+ * apart from the cards so they're tested on their own.
+ */
+
+import type { DateRangePreset } from '@/components/filters/date-range-filter';
+import { formatNumber } from '@/lib/format';
+
+/**
+ * How many of Search Console's latest reported days a short range reads, or
+ * null to read the range as it is. Google reports about two days late, so
+ * the last 24 hours or 7 days ending today would read as no clicks at all
+ * (spec §3.01).
+ */
+export function gscLatestDays(preset: DateRangePreset): number | null {
+ if (preset === '24h') return 1;
+ if (preset === '7d') return 7;
+ return null;
+}
+
+/** The ranges where a quiet stretch is likely, so an empty card offers 30 days instead. */
+export function isShortRange(preset: DateRangePreset): boolean {
+ return gscLatestDays(preset) !== null;
+}
+
+/**
+ * A part of a whole as a percent: "0.5%", "75%". One decimal below 10%, where
+ * whole percents would read as 0 or 1; "<0.1%" for a sliver that isn't zero.
+ * Null when there is no whole to take a share of.
+ */
+export function formatShare(part: number, whole: number): string | null {
+ if (whole <= 0) return null;
+ const pct = (part / whole) * 100;
+ if (pct > 0 && pct < 0.1) return '<0.1%';
+ const rounded = pct < 10 ? Math.round(pct * 10) / 10 : Math.round(pct);
+ return `${formatNumber(rounded)}%`;
+}
+
+/** A change as the cards write it: "+12%", "−6%" (a true minus, as on the Insights cards). */
+export function formatPctChange(pct: number): string {
+ return `${pct > 0 ? '+' : '−'}${formatNumber(Math.abs(pct))}%`;
+}
+
+/**
+ * Search Console's days as a card names them: "Oct 15", or "Oct 10 – Oct 16".
+ * They are calendar days in UTC, so they're written in UTC: read in the
+ * member's own zone, a day west of Greenwich would show as the day before.
+ */
+export function formatGoogleDays(since: string | null, until: string): string {
+ const day = (d: string) =>
+ new Date(`${d}T00:00:00Z`).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC',
+ });
+ return !since || since === until ? day(until) : `${day(since)} – ${day(until)}`;
+}
diff --git a/web/src/lib/traffic-sources.test.ts b/web/src/lib/traffic-sources.test.ts
index daefb138c..95a5f6aea 100644
--- a/web/src/lib/traffic-sources.test.ts
+++ b/web/src/lib/traffic-sources.test.ts
@@ -58,13 +58,15 @@ describe('gscPropertyHost', () => {
});
describe('sectionsNeeding', () => {
- it('lists the sections a source unlocks (AT-016)', () => {
+ it('lists the sections a source unlocks, in the page order (AT-016, AT-017)', () => {
expect(TRAFFIC_SECTION_SOURCES.pageOpportunities).toBe('google-analytics');
- expect(sectionsNeeding('google-analytics')).toEqual(['pageOpportunities']);
- });
-
- it('lists nothing for a source no section needs yet', () => {
- expect(sectionsNeeding('google-search-console')).toEqual([]);
+ expect(sectionsNeeding('google-analytics')).toEqual([
+ 'aiShare',
+ 'engagedVisits',
+ 'keyEvents',
+ 'pageOpportunities',
+ ]);
+ expect(sectionsNeeding('google-search-console')).toEqual(['googleClicks']);
});
});
diff --git a/web/src/lib/traffic-sources.ts b/web/src/lib/traffic-sources.ts
index e619b0ef8..ae118f0c8 100644
--- a/web/src/lib/traffic-sources.ts
+++ b/web/src/lib/traffic-sources.ts
@@ -80,6 +80,10 @@ export function sourceHost(
* later section adds its own entry.
*/
export const TRAFFIC_SECTION_SOURCES = {
+ aiShare: 'google-analytics',
+ engagedVisits: 'google-analytics',
+ keyEvents: 'google-analytics',
+ googleClicks: 'google-search-console',
pageOpportunities: 'google-analytics',
} as const satisfies Record<string, IntegrationProvider>;
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 5b4776a5e..62ad1c1d8 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3103,6 +3103,15 @@ export type Database = {
transactions: number
}[]
}
+ ga_traffic_totals: {
+ Args: { p_brand_id: string; p_since: string | null; p_until: string }
+ Returns: {
+ ai_engaged_sessions: number
+ ai_key_events: number
+ ai_sessions: number
+ sessions: number
+ }[]
+ }
get_latest_prompt_results:
| {
Args: { p_brand_id: string; p_platform?: string }
@@ -3180,6 +3189,21 @@ export type Database = {
query: string
}[]
}
+ gsc_click_totals: {
+ Args: {
+ p_brand_id: string
+ p_latest?: boolean
+ p_since: string | null
+ p_until: string
+ }
+ Returns: {
+ clicks: number
+ last_date: string | null
+ prev_clicks: number | null
+ since: string | null
+ until: string | null
+ }[]
+ }
head_to_head_daily: {
Args: { p_brand_id: string; p_competitor_id: string }
Returns: Json