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): show what AI visitors are worth per platform and against Google organic (#1168)
Cihan18cddbe6161f
diff --git a/server/src/lib/ga-sync.js b/server/src/lib/ga-sync.jsindex 1191aaedc..ae4fbd091 100644--- a/server/src/lib/ga-sync.js+++ b/server/src/lib/ga-sync.js@@ -2,9 +2,10 @@* Daily Google Analytics sync (#704).** For every active brand mapped to a GA4 property (#694) whose org connection- * is live, pulls three reports through Composio and upserts them:+ * is live, pulls four reports through Composio and upserts them:** ga_ai_traffic_stats AI-sourced sessions per landing page+ * ga_channel_stats sessions per default channel group (AT-005)* ga_page_stats landing-page totals across every source* ga_item_stats product rows, when the property has ecommerce*@@ -74,6 +75,9 @@ const TRAFFIC_METRICS = ['sessions','engagedSessions','keyEvents',+ // The share of sessions with a key event (AT-005): key events alone can't+ // give a rate, as one session can hold several.+ 'sessionKeyEventRate','totalUsers','transactions','purchaseRevenue',@@ -128,10 +132,14 @@ export function readReportRows(report) {}function trafficMetricColumns(row) {+ const sessions = toInt(row.sessions);return {- sessions: toInt(row.sessions),+ sessions,engaged_sessions: toInt(row.engagedSessions),key_events: toInt(row.keyEvents),+ // A count rather than GA4's rate, so rows can be summed and a rate taken+ // over any range: sessions with a key event ÷ sessions.+ key_event_sessions: Math.round(toFloat(row.sessionKeyEventRate) * sessions),total_users: toInt(row.totalUsers),transactions: toInt(row.transactions),purchase_revenue: toFloat(row.purchaseRevenue),@@ -143,6 +151,7 @@ const SUMMED_COLUMNS = ['sessions','engaged_sessions','key_events',+ 'key_event_sessions','total_users','transactions','purchase_revenue',@@ -206,6 +215,25 @@ export function mapPageRows(brandId, report) {return mapped;}+/**+ * Sessions per day and default channel group → ga_channel_stats (AT-005):+ * Organic Search is what the AI Traffic page compares AI visitors with.+ */+export function mapChannelRows(brandId, report) {+ const mapped = [];+ for (const row of readReportRows(report)) {+ const date = gaDateToIso(row.date);+ if (!date) continue;+ mapped.push({+ brand_id: brandId,+ date,+ channel: row.sessionDefaultChannelGroup || '(not set)',+ ...trafficMetricColumns(row),+ });+ }+ return mapped;+}+/** Product rows → ga_item_stats. */export function mapItemRows(brandId, report) {const mapped = [];@@ -403,6 +431,20 @@ async function syncBrand(brand, { aiHistory = false } = {}) {}const aiRows = aiMapped.length;+ // Every channel's sessions over the same days (AT-005): a dozen rows a+ // day, so one call. Organic Search is the AI Traffic page's comparison.+ const channelReport = await runGaReport(entityId, brand.ga_property_id, {+ dateRanges: [{ startDate: aiDays[aiDays.length - 1], endDate: aiDays[0] }],+ dimensions: [{ name: 'date' }, { name: 'sessionDefaultChannelGroup' }],+ metrics,+ limit: 100_000,+ });+ const channelMapped = mapChannelRows(brand.id, channelReport);+ if (channelMapped.length) {+ await upsertAll('ga_channel_stats', channelMapped, 'brand_id,date,channel');+ }+ const channelRows = channelMapped.length;+const pageRows = await syncDays({brand,entityId,@@ -466,7 +508,7 @@ async function syncBrand(brand, { aiHistory = false } = {}) {logger.debug({ brandId: brand.id, err: err.message }, '[ga-sync] source discovery failed');}- return { first, aiRows, pageRows, itemRows };+ return { first, aiRows, channelRows, pageRows, itemRows };}async function prune(table) {@@ -527,7 +569,12 @@ export async function runGaSync({ organizationId, brandId, aiHistory = false } =// Retention is table-wide, so a single-brand sync leaves it to the daily run.if (!brandId) {- for (const table of ['ga_ai_traffic_stats', 'ga_page_stats', 'ga_item_stats']) {+ for (const table of [+ 'ga_ai_traffic_stats',+ 'ga_channel_stats',+ 'ga_page_stats',+ 'ga_item_stats',+ ]) {await prune(table);}}diff --git a/server/src/lib/ga-sync.test.js b/server/src/lib/ga-sync.test.jsindex 2a3e6aeff..371b5f482 100644--- a/server/src/lib/ga-sync.test.js+++ b/server/src/lib/ga-sync.test.js@@ -12,6 +12,7 @@ import {dayRange,gaDateToIso,mapAiTrafficRows,+ mapChannelRows,mapItemRows,mapPageRows,readReportRows,@@ -195,6 +196,8 @@ describe('mapAiTrafficRows', () => {sessions: 10,engaged_sessions: 3,key_events: 1,+ // No session key event rate in this report: none counted.+ key_event_sessions: 0,total_users: 9,transactions: 2,purchase_revenue: 149.9,@@ -336,6 +339,7 @@ describe('mapPageRows', () => {sessions: 29,engaged_sessions: 21,key_events: 2,+ key_event_sessions: 0,total_users: 23,transactions: 1,purchase_revenue: 80,@@ -345,6 +349,68 @@ describe('mapPageRows', () => {});});+describe('sessions with a key event (AT-005)', () => {+ const withRate = (rows) =>+ report({+ dims: ['date', 'sessionDefaultChannelGroup'],+ metrics: ['sessions', 'keyEvents', 'sessionKeyEventRate'],+ rows,+ });++ it("counts them from GA4's session key event rate, so a rate can be taken over any range", () => {+ // 40 sessions, 12 key events, but only a quarter of the sessions had one.+ const [row] = mapChannelRows(+ 'brand-1',+ withRate([['20260721', 'Organic Search', '40', '12', '0.25']]),+ );+ expect(row).toMatchObject({ sessions: 40, key_events: 12, key_event_sessions: 10 });+ });++ it('rounds to whole sessions, and reads a missing rate as none', () => {+ const rows = mapChannelRows(+ 'brand-1',+ withRate([+ ['20260721', 'Direct', '3', '1', '0.3333333'],+ ['20260721', 'Referral', '5', '0', ''],+ ]),+ );+ expect(rows.map((r) => r.key_event_sessions)).toEqual([1, 0]);+ });+});++describe('mapChannelRows', () => {+ it('stores sessions per day and default channel group', () => {+ const rows = mapChannelRows(+ 'brand-1',+ report({+ dims: ['date', 'sessionDefaultChannelGroup'],+ metrics: TRAFFIC_METRICS,+ rows: [+ ['20260721', 'Organic Search', '500', '300', '20', '450', '3', '99.5', '9000'],+ ['20260721', '', '7', '1', '0', '7', '0', '0', '30'],+ ['(other)', 'Direct', '9', '1', '0', '9', '0', '0', '30'],+ ],+ }),+ );+ expect(rows).toEqual([+ {+ brand_id: 'brand-1',+ date: '2026-07-21',+ channel: 'Organic Search',+ sessions: 500,+ engaged_sessions: 300,+ key_events: 20,+ key_event_sessions: 0,+ total_users: 450,+ transactions: 3,+ purchase_revenue: 99.5,+ engagement_duration_seconds: 9000,+ },+ expect.objectContaining({ channel: '(not set)', sessions: 7 }),+ ]);+ });+});+describe('mapItemRows', () => {it('maps product rows', () => {const raw = report({diff --git a/supabase/migrations/00177_traffic_platform_value.sql b/supabase/migrations/00177_traffic_platform_value.sqlnew file mode 100644index 000000000..f3d5f1763--- /dev/null+++ b/supabase/migrations/00177_traffic_platform_value.sql@@ -0,0 +1,194 @@+-- ============================================================================+-- 00177: what AI visitors are worth, per platform and against Google organic (AT-005)+-- ============================================================================+-- Spec §1 question 2, "are those visitors worth anything?": engagement, key+-- events and revenue per AI platform, compared with Google organic (F6).+--+-- * ga_channel_stats: Google Analytics' sessions per day and default+-- channel group (Organic Search, Direct, AI Assistant, …) for every+-- mapped brand, synced with the AI report. Organic Search is the+-- comparison the AI Traffic page draws; a dozen rows a day per brand.+-- * key_event_sessions: the sessions with at least one key event, from+-- GA4's session key event rate. Key events alone can't give a rate — one+-- session can hold several — so the rate is this count over sessions,+-- the figure GA4's own reports show. Added to the AI and page tables+-- too; rows synced before it stay 0 until the history backfill+-- (backfill-ga-ai-history.js) re-reads them.+-- * ga_traffic_totals (00174) also returns the AI sessions with a key+-- event, the AI purchase revenue, and Google organic's sessions, engaged+-- sessions and sessions with a key event, for the KPI cards.+-- * ga_platform_value: per AI platform, Analytics' sessions, engaged+-- sessions, key events and sessions with a key event, for the Referrals+-- by Platform table.+--+-- Both functions read as the caller (security invoker), so the tables'+-- member select policies decide whose brand they see.++-- ─── Channel totals ─────────────────────────────────────────────────────────++create table if not exists public.ga_channel_stats (+ id uuid primary key default gen_random_uuid(),+ brand_id uuid not null references public.brands(id) on delete cascade,+ date date not null,+ channel text not null,+ sessions integer not null default 0,+ engaged_sessions integer not null default 0,+ key_events integer not null default 0,+ key_event_sessions integer not null default 0,+ total_users integer not null default 0,+ transactions integer not null default 0,+ purchase_revenue double precision not null default 0,+ engagement_duration_seconds integer not null default 0,+ created_at timestamptz not null default now(),+ unique (brand_id, date, channel)+);++create index if not exists ga_channel_stats_brand_date_idx+ on public.ga_channel_stats (brand_id, date desc);++alter table public.ga_channel_stats enable row level security;++create policy "ga_channel_stats: member select" on public.ga_channel_stats+ for select using (+ brand_id in (+ select b.id+ from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++grant select on public.ga_channel_stats to authenticated;++comment on table public.ga_channel_stats is+ 'Google Analytics sessions per day and default channel group, per brand (AT-005). Written by the GA sync with the service role; Organic Search is the AI Traffic page''s comparison.';++-- ─── Sessions with a key event ──────────────────────────────────────────────++alter table public.ga_ai_traffic_stats+ add column if not exists key_event_sessions integer not null default 0;++alter table public.ga_page_stats+ add column if not exists key_event_sessions integer not null default 0;++comment on column public.ga_ai_traffic_stats.key_event_sessions is+ 'Sessions with at least one key event (GA4 session key event rate × sessions), for a rate GA4''s reports agree with (AT-005).';++comment on column public.ga_page_stats.key_event_sessions is+ 'Sessions with at least one key event (GA4 session key event rate × sessions), for a rate GA4''s reports agree with (AT-005).';++-- ─── The KPI cards' Analytics totals, with Google organic ───────────────────++drop function if exists public.ga_traffic_totals(uuid, date, date);++create 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,+ ai_key_event_sessions bigint,+ ai_revenue double precision,+ organic_sessions bigint,+ organic_engaged_sessions bigint,+ organic_key_events bigint,+ organic_key_event_sessions bigint+)+language sql+stable+security invoker+set search_path to 'public'+as $$+ with ai as (+ select+ coalesce(sum(gat.sessions), 0)::bigint as sessions,+ coalesce(sum(gat.engaged_sessions), 0)::bigint as engaged_sessions,+ coalesce(sum(gat.key_events), 0)::bigint as key_events,+ coalesce(sum(gat.key_event_sessions), 0)::bigint as key_event_sessions,+ coalesce(sum(gat.purchase_revenue), 0)::double precision as revenue+ 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+ ),+ organic as (+ select+ coalesce(sum(gcs.sessions), 0)::bigint as sessions,+ coalesce(sum(gcs.engaged_sessions), 0)::bigint as engaged_sessions,+ coalesce(sum(gcs.key_events), 0)::bigint as key_events,+ coalesce(sum(gcs.key_event_sessions), 0)::bigint as key_event_sessions+ from public.ga_channel_stats gcs+ where gcs.brand_id = p_brand_id+ and gcs.channel = 'Organic Search'+ and gcs.date >= coalesce(p_since, '-infinity'::date)+ and gcs.date <= p_until+ )+ 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+ ),+ ai.sessions,+ ai.engaged_sessions,+ ai.key_events,+ ai.key_event_sessions,+ ai.revenue,+ organic.sessions,+ organic.engaged_sessions,+ organic.key_events,+ organic.key_event_sessions+ from ai, organic;+$$;++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;++comment on function public.ga_traffic_totals(uuid, date, date) is+ 'AI Traffic KPIs (AT-017, AT-005): all sessions; the AI channel''s sessions, engaged sessions, key events, sessions with a key event and purchase revenue; and Google organic''s sessions, engaged sessions, key events and sessions with a key event — for one brand between two days (p_since null = from the start). Security invoker: RLS decides the brand.';++-- ─── Per AI platform, for the Referrals by Platform table ───────────────────++create or replace function public.ga_platform_value(+ p_brand_id uuid,+ p_since date,+ p_until date+)+returns table (+ platform text,+ sessions bigint,+ engaged_sessions bigint,+ key_events bigint,+ key_event_sessions bigint+)+language sql+stable+security invoker+set search_path to 'public'+as $$+ select+ coalesce(gat.platform, gat.source) as platform,+ coalesce(sum(gat.sessions), 0)::bigint,+ coalesce(sum(gat.engaged_sessions), 0)::bigint,+ coalesce(sum(gat.key_events), 0)::bigint,+ coalesce(sum(gat.key_event_sessions), 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+ group by 1;+$$;++revoke all on function public.ga_platform_value(uuid, date, date) from public, anon;+grant execute on function public.ga_platform_value(uuid, date, date) to authenticated, service_role;++comment on function public.ga_platform_value(uuid, date, date) is+ 'AI Traffic (AT-005): Google Analytics'' sessions, engaged sessions, key events and sessions with a key event per AI platform, for one brand between two days (p_since null = from the start). Security invoker: RLS decides the brand.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex e57a77aab..c95b3f48f 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -23794,3 +23794,201 @@ comment on function public.ai_traffic_merged(uuid, timestamptz, timestamptz, boonotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00177_traffic_platform_value.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00177: what AI visitors are worth, per platform and against Google organic (AT-005)+-- ============================================================================+-- Spec §1 question 2, "are those visitors worth anything?": engagement, key+-- events and revenue per AI platform, compared with Google organic (F6).+--+-- * ga_channel_stats: Google Analytics' sessions per day and default+-- channel group (Organic Search, Direct, AI Assistant, …) for every+-- mapped brand, synced with the AI report. Organic Search is the+-- comparison the AI Traffic page draws; a dozen rows a day per brand.+-- * key_event_sessions: the sessions with at least one key event, from+-- GA4's session key event rate. Key events alone can't give a rate — one+-- session can hold several — so the rate is this count over sessions,+-- the figure GA4's own reports show. Added to the AI and page tables+-- too; rows synced before it stay 0 until the history backfill+-- (backfill-ga-ai-history.js) re-reads them.+-- * ga_traffic_totals (00174) also returns the AI sessions with a key+-- event, the AI purchase revenue, and Google organic's sessions, engaged+-- sessions and sessions with a key event, for the KPI cards.+-- * ga_platform_value: per AI platform, Analytics' sessions, engaged+-- sessions, key events and sessions with a key event, for the Referrals+-- by Platform table.+--+-- Both functions read as the caller (security invoker), so the tables'+-- member select policies decide whose brand they see.++-- ─── Channel totals ─────────────────────────────────────────────────────────++create table if not exists public.ga_channel_stats (+ id uuid primary key default gen_random_uuid(),+ brand_id uuid not null references public.brands(id) on delete cascade,+ date date not null,+ channel text not null,+ sessions integer not null default 0,+ engaged_sessions integer not null default 0,+ key_events integer not null default 0,+ key_event_sessions integer not null default 0,+ total_users integer not null default 0,+ transactions integer not null default 0,+ purchase_revenue double precision not null default 0,+ engagement_duration_seconds integer not null default 0,+ created_at timestamptz not null default now(),+ unique (brand_id, date, channel)+);++create index if not exists ga_channel_stats_brand_date_idx+ on public.ga_channel_stats (brand_id, date desc);++alter table public.ga_channel_stats enable row level security;++create policy "ga_channel_stats: member select" on public.ga_channel_stats+ for select using (+ brand_id in (+ select b.id+ from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++grant select on public.ga_channel_stats to authenticated;++comment on table public.ga_channel_stats is+ 'Google Analytics sessions per day and default channel group, per brand (AT-005). Written by the GA sync with the service role; Organic Search is the AI Traffic page''s comparison.';++-- ─── Sessions with a key event ──────────────────────────────────────────────++alter table public.ga_ai_traffic_stats+ add column if not exists key_event_sessions integer not null default 0;++alter table public.ga_page_stats+ add column if not exists key_event_sessions integer not null default 0;++comment on column public.ga_ai_traffic_stats.key_event_sessions is+ 'Sessions with at least one key event (GA4 session key event rate × sessions), for a rate GA4''s reports agree with (AT-005).';++comment on column public.ga_page_stats.key_event_sessions is+ 'Sessions with at least one key event (GA4 session key event rate × sessions), for a rate GA4''s reports agree with (AT-005).';++-- ─── The KPI cards' Analytics totals, with Google organic ───────────────────++drop function if exists public.ga_traffic_totals(uuid, date, date);++create 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,+ ai_key_event_sessions bigint,+ ai_revenue double precision,+ organic_sessions bigint,+ organic_engaged_sessions bigint,+ organic_key_events bigint,+ organic_key_event_sessions bigint+)+language sql+stable+security invoker+set search_path to 'public'+as $$+ with ai as (+ select+ coalesce(sum(gat.sessions), 0)::bigint as sessions,+ coalesce(sum(gat.engaged_sessions), 0)::bigint as engaged_sessions,+ coalesce(sum(gat.key_events), 0)::bigint as key_events,+ coalesce(sum(gat.key_event_sessions), 0)::bigint as key_event_sessions,+ coalesce(sum(gat.purchase_revenue), 0)::double precision as revenue+ 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+ ),+ organic as (+ select+ coalesce(sum(gcs.sessions), 0)::bigint as sessions,+ coalesce(sum(gcs.engaged_sessions), 0)::bigint as engaged_sessions,+ coalesce(sum(gcs.key_events), 0)::bigint as key_events,+ coalesce(sum(gcs.key_event_sessions), 0)::bigint as key_event_sessions+ from public.ga_channel_stats gcs+ where gcs.brand_id = p_brand_id+ and gcs.channel = 'Organic Search'+ and gcs.date >= coalesce(p_since, '-infinity'::date)+ and gcs.date <= p_until+ )+ 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+ ),+ ai.sessions,+ ai.engaged_sessions,+ ai.key_events,+ ai.key_event_sessions,+ ai.revenue,+ organic.sessions,+ organic.engaged_sessions,+ organic.key_events,+ organic.key_event_sessions+ from ai, organic;+$$;++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;++comment on function public.ga_traffic_totals(uuid, date, date) is+ 'AI Traffic KPIs (AT-017, AT-005): all sessions; the AI channel''s sessions, engaged sessions, key events, sessions with a key event and purchase revenue; and Google organic''s sessions, engaged sessions, key events and sessions with a key event — for one brand between two days (p_since null = from the start). Security invoker: RLS decides the brand.';++-- ─── Per AI platform, for the Referrals by Platform table ───────────────────++create or replace function public.ga_platform_value(+ p_brand_id uuid,+ p_since date,+ p_until date+)+returns table (+ platform text,+ sessions bigint,+ engaged_sessions bigint,+ key_events bigint,+ key_event_sessions bigint+)+language sql+stable+security invoker+set search_path to 'public'+as $$+ select+ coalesce(gat.platform, gat.source) as platform,+ coalesce(sum(gat.sessions), 0)::bigint,+ coalesce(sum(gat.engaged_sessions), 0)::bigint,+ coalesce(sum(gat.key_events), 0)::bigint,+ coalesce(sum(gat.key_event_sessions), 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+ group by 1;+$$;++revoke all on function public.ga_platform_value(uuid, date, date) from public, anon;+grant execute on function public.ga_platform_value(uuid, date, date) to authenticated, service_role;++comment on function public.ga_platform_value(uuid, date, date) is+ 'AI Traffic (AT-005): Google Analytics'' sessions, engaged sessions, key events and sessions with a key event per AI platform, for one brand between two days (p_since null = from the start). Security invoker: RLS decides the brand.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex fb0b074a0..08620e0a6 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3096,6 +3096,8 @@"setting": "Setting","metric": "Metric","value": "Value",+ "engaged": "Engaged (%)",+ "keyEvents": "Key events","note": "Note","day": "Day","hour": "Hour (UTC)",@@ -3197,6 +3199,12 @@"trend": {"fromAnalytics": "from Google Analytics"},+ "platforms": {+ "engaged": "Engaged",+ "keyEvents": "Key events",+ "lowSample": "Low sample: {sessions, plural, one {# session} other {# sessions}} in Google Analytics",+ "needsAnalytics": "Engaged and key events need Google Analytics."+ },"kpis": {"visits": "AI-referred visits","visitsTip": "Visits from AI assistants, one per session: from the tracking snippet on days it sent any, and from Google Analytics on the other days, never added together. Below 30 visits in this period or the one before, the change shows Low sample.",@@ -3211,11 +3219,15 @@"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.",+ "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 — beside the same share for Google organic. Below 30 AI sessions the rate shows Low sample.","engagedSub": "{engaged, number} of {sessions, plural, one {# AI session} other {# AI sessions}}",+ "engagedVsOrganic": "vs {rate} Google organic","keyEvents": "Key events from AI",- "keyEventsTip": "Key events (conversions) Google Analytics recorded in sessions from AI assistants.",+ "keyEventsTip": "Key events (conversions) Google Analytics recorded in sessions from AI assistants. The rate is the share of AI sessions with a key event, as Google Analytics reports it, compared with Google organic once both have 30 sessions and 5 key events. Revenue shows when the property reports purchases.","keyEventsSub": "in {sessions, plural, one {# AI session} other {# AI sessions}}",+ "keyEventRate": "{rate} of AI sessions",+ "keyEventRateRevenue": "{rate} of AI sessions · {revenue} revenue",+ "vsOrganic": "{ratio} organic","keyEventsNone": "none in {range}","see30d": "see 30d","googleClicks": "Google clicks",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsxindex c3d112383..dd9a094c1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx@@ -59,9 +59,9 @@ const summary = (over: Partial<TrafficSummary> = {}): TrafficSummary => ({analyticsDays: [],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 },+ { platform: 'gemini.google.com', visits: 2, visitsPrev: 1, analytics: null },+ { platform: 'chatgpt.com', visits: 1, visitsPrev: 1, analytics: null },+ { platform: 'perplexity.ai', visits: 1, visitsPrev: 1, analytics: null },],topPages: [],hasAnyData: true,@@ -69,7 +69,16 @@ const summary = (over: Partial<TrafficSummary> = {}): TrafficSummary => ({});const TOTALS: TrafficGoogleTotals = {- ga: { sessions: 812, aiSessions: 4, aiEngagedSessions: 3, aiKeyEvents: 1 },+ ga: {+ sessions: 812,+ aiSessions: 4,+ aiEngagedSessions: 3,+ aiKeyEvents: 1,+ aiKeyEventSessions: 1,+ aiRevenue: 0,+ // Google organic: 58% engaged, as in the mockup.+ organic: { sessions: 1000, engagedSessions: 580, keyEvents: 60, keyEventSessions: 50 },+ },gsc: {since: '2026-10-16',until: '2026-10-16',@@ -210,8 +219,9 @@ describe('TrafficKpis', () => {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('Engaged visits')).toContain('75%Low samplevs 58% Google organic');+ // 1 of 4 AI sessions had a key event: a rate, on too few sessions to compare.+ expect(card('Key events from AI')).toContain('1Low sample25% of AI sessions');expect(card('Google clicks')).toContain('412−6%');expect(card('Google clicks')).toContain('Oct 16 · latest reported day');});@@ -234,6 +244,48 @@ describe('TrafficKpis', () => {expect(card('Google clicks')).toContain('438 in the previous period');});+ it('compares the key event rate with Google organic once both sides are big enough (AT-005)', async () => {+ getTrafficGoogleTotals.mockResolvedValue({+ ...TOTALS,+ // 10% of 100 AI sessions against 5% of organic's.+ ga: { ...TOTALS.ga!, aiSessions: 100, aiKeyEvents: 12, aiKeyEventSessions: 10 },+ });+ await render({ preset: '30d', dateWindow: { dateFrom: '2026-09-18T12:30:00.000Z' } });+ expect(card('Key events from AI')).toContain('122× organic10% of AI sessions');+ });++ it('adds purchase revenue when the property reports it', async () => {+ getTrafficGoogleTotals.mockResolvedValue({+ ...TOTALS,+ ga: {+ ...TOTALS.ga!,+ aiSessions: 100,+ aiKeyEvents: 3,+ aiKeyEventSessions: 3,+ aiRevenue: 1240.4,+ },+ });+ await render({ preset: '30d', dateWindow: { dateFrom: '2026-09-18T12:30:00.000Z' } });+ // 3 key events: too few to compare with organic (§5.4).+ expect(card('Key events from AI')).toBe('Key events from AI33% of AI sessions · 1,240 revenue');+ });++ it('keeps the plain line while a rate is unknown, and without organic data', async () => {+ getTrafficGoogleTotals.mockResolvedValue({+ ...TOTALS,+ // Synced before the session key event rate: key events, no sessions holding them.+ ga: {+ ...TOTALS.ga!,+ aiKeyEvents: 2,+ aiKeyEventSessions: 0,+ organic: { sessions: 0, engagedSessions: 0, keyEvents: 0, keyEventSessions: 0 },+ },+ });+ await render({ preset: '30d', dateWindow: { dateFrom: '2026-09-18T12:30:00.000Z' } });+ expect(card('Key events from AI')).toBe('Key events from AI2in 4 AI sessions');+ expect(card('Engaged visits')).toContain('3 of 4 AI sessions');+ });+it('offers 30 days when a short range has no key events', async () => {getTrafficGoogleTotals.mockResolvedValue({...TOTALS,@@ -252,7 +304,7 @@ describe('TrafficKpis', () => {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 },+ ga: { ...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');@@ -260,7 +312,7 @@ describe('TrafficKpis', () => {getTrafficGoogleTotals.mockResolvedValue({...TOTALS,- ga: { sessions: 812, aiSessions: 0, aiEngagedSessions: 0, aiKeyEvents: 0 },+ ga: { ...TOTALS.ga!, 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');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsxindex 2ed10e681..637655b17 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx@@ -25,9 +25,11 @@ import { LOW_SAMPLE_VISITS, visitChange, type VisitChange } from '@/lib/traffic-import {formatGoogleDays,formatPctChange,+ formatRatio,formatShare,gscLatestDays,isShortRange,+ organicRatio,} from '@/lib/traffic-kpis';import { getPlatformName } from '@/lib/traffic-platforms';import { googleSourceStatus, TRAFFIC_SECTION_SOURCES } from '@/lib/traffic-sources';@@ -267,14 +269,20 @@ export function TrafficKpis({{gate('engagedVisits', engaged) ?? (<MetricCard{...engaged}- {...fromGa(({ aiSessions, aiEngagedSessions }) =>+ {...fromGa(({ aiSessions, aiEngagedSessions, organic }) =>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 }),+ // Beside Google organic's, as the mockup draws it (AT-005).+ sub:+ organic.sessions > 0+ ? t('engagedVsOrganic', {+ rate: formatShare(organic.engagedSessions, organic.sessions)!,+ })+ : t('engagedSub', { engaged: aiEngagedSessions, sessions: aiSessions }),},)}/>@@ -282,19 +290,53 @@ export function TrafficKpis({{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) ? (+ {...fromGa((totals) => {+ const { aiSessions, aiKeyEvents, aiKeyEventSessions, aiRevenue, organic } = totals;+ // Rows synced before the session key event rate have key events+ // but no count of the sessions holding them: no rate until the+ // history is re-read.+ const rateKnown = aiKeyEventSessions > 0 || aiKeyEvents === 0;+ const rate = rateKnown ? formatShare(aiKeyEventSessions, aiSessions) : null;+ const ratio = organicRatio(+ {+ sessions: aiSessions,+ keyEvents: aiKeyEvents,+ keyEventSessions: aiKeyEventSessions,+ },+ organic,+ );+ // None in a short range is usual: the card offers the month (spec §3.2).+ const noneYet = aiKeyEvents === 0 && isShortRange(preset);+ return {+ value: formatNumber(aiKeyEvents),+ // With a rate on show — few sessions: it's chance (§5.4); enough+ // on both sides: against Google organic's (AT-005).+ delta:+ noneYet || rate === null+ ? null+ : aiSessions < LOW_SAMPLE_VISITS+ ? delta({ kind: 'low' })+ : ratio === null+ ? null+ : {+ text: t('vsOrganic', { ratio: formatRatio(ratio) }),+ tone: ratio > 1.05 ? 'good' : ratio < 0.95 ? 'bad' : 'neutral',+ },+ sub: noneYet ? (<>{t('keyEventsNone', { range: preset })} ·{' '}<SubAction onClick={() => onRangeChange('30d')}>{t('see30d')}</SubAction></>- ) : (+ ) : rate === null ? (t('keyEventsSub', { sessions: aiSessions })+ ) : aiRevenue > 0 ? (+ // Purchase revenue, when the property reports it (AT-005).+ t('keyEventRateRevenue', { rate, revenue: formatNumber(Math.round(aiRevenue)) })+ ) : (+ t('keyEventRate', { rate })),- }))}+ };+ })}/>)}{gate('googleClicks', clicks) ?? <MetricCard {...clicks} {...clicksBody()} />}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_platform-value.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_platform-value.test.tsxnew file mode 100644index 000000000..b4f659494--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_platform-value.test.tsx@@ -0,0 +1,85 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { TrafficEngagement } from '@/lib/actions/traffic';+import { EngagedCell, KeyEventsCell, PlatformValueNote } from './_platform-value';++/**+ * AT-005 (spec §3.4): Referrals by Platform shows what each platform's+ * visitors did in Google Analytics — engaged share and key events — muted+ * below 30 sessions, "—" for a platform Analytics never saw, and a note+ * while Analytics has no data.+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function render(node: React.ReactNode) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+ return container;+}++const ga = (sessions: number, engagedSessions: number, keyEvents = 0): TrafficEngagement => ({+ sessions,+ engagedSessions,+ keyEvents,+ keyEventSessions: 0,+});++describe('EngagedCell', () => {+ it("shows the share of the platform's sessions Analytics counts as engaged", () => {+ const span = render(<EngagedCell analytics={ga(120, 90)} />).querySelector('span')!;+ expect(span.textContent).toBe('75%');+ expect(span.title).toBe('');+ });++ it('mutes a rate on fewer than 30 sessions, with the count on hover (§5.4)', () => {+ const span = render(<EngagedCell analytics={ga(4, 3)} />).querySelector('span')!;+ expect(span.textContent).toBe('75%');+ expect(span.className).toContain('text-muted-foreground');+ expect(span.title).toBe('Low sample: 4 sessions in Google Analytics');+ });++ it('shows "—" for a platform Analytics never saw', () => {+ expect(render(<EngagedCell analytics={null} />).textContent).toBe('—');+ expect(render(<EngagedCell analytics={ga(0, 0)} />).textContent).toBe('—');+ });+});++describe('KeyEventsCell', () => {+ it("shows the platform's key events, or — without Analytics", () => {+ expect(render(<KeyEventsCell analytics={ga(120, 90, 7)} />).textContent).toBe('7');+ expect(render(<KeyEventsCell analytics={ga(120, 90, 0)} />).textContent).toBe('0');+ expect(render(<KeyEventsCell analytics={null} />).textContent).toBe('—');+ });+});++describe('PlatformValueNote', () => {+ it('says what the columns need', () => {+ expect(render(<PlatformValueNote />).textContent).toBe(+ 'Engaged and key events need Google Analytics.',+ );+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_platform-value.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_platform-value.tsxnew file mode 100644index 000000000..2d5e5f049--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_platform-value.tsx@@ -0,0 +1,48 @@+'use client';++import { useTranslations } from 'next-intl';+import type { TrafficEngagement } from '@/lib/actions/traffic';+import { formatNumber } from '@/lib/format';+import { LOW_SAMPLE_VISITS } from '@/lib/traffic-change';+import { formatShare } from '@/lib/traffic-kpis';+import { cn } from '@/lib/utils';++/**+ * Referrals by Platform's Google Analytics columns (AT-005, spec §3.4): what+ * each platform's visitors did. Engagement and key events are rates and+ * counts of Analytics' own sessions, so they read Analytics alone, whichever+ * origin counted the platform's visits; a platform Analytics never saw+ * shows "—".+ */++const NONE = <span className="text-muted-foreground">—</span>;++/** The share of the platform's sessions Analytics counts as engaged. */+export function EngagedCell({ analytics }: { analytics: TrafficEngagement | null }) {+ const t = useTranslations('traffic.platforms');+ const share = analytics ? formatShare(analytics.engagedSessions, analytics.sessions) : null;+ if (!analytics || share === null) return NONE;+ // A rate on a handful of sessions says more about chance (§5.4): shown,+ // but muted, with the session count on hover.+ const low = analytics.sessions < LOW_SAMPLE_VISITS;+ return (+ <span+ className={cn('tabular-nums', low && 'text-muted-foreground')}+ title={low ? t('lowSample', { sessions: analytics.sessions }) : undefined}+ >+ {share}+ </span>+ );+}++/** The key events Analytics recorded in the platform's sessions. */+export function KeyEventsCell({ analytics }: { analytics: TrafficEngagement | null }) {+ if (!analytics) return NONE;+ return <span className="tabular-nums">{formatNumber(analytics.keyEvents)}</span>;+}++/** Under the table while Analytics has no data for the brand (§3.8b's partial note). */+export function PlatformValueNote() {+ const t = useTranslations('traffic.platforms');+ return <p className="px-6 py-3 text-xs text-muted-foreground">{t('needsAnalytics')}</p>;+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex 2bf85341a..6f0d7fade 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -39,10 +39,11 @@ import {import { PageOpportunitiesCard } from './_opportunities-card';import { TRAFFIC_KPI_GRID, TrafficKpis } from './_kpis';import { VisitListSourceNote } from './_visit-list-note';+import { EngagedCell, KeyEventsCell, PlatformValueNote } from './_platform-value';import { ExportMenu, TableExport, useTrafficExport } from './_export';import { SourcesStrip } from './_sources-strip';import { SnippetBanner, SnippetDialog } from './_snippet-code';-import { snippetDetected } from '@/lib/traffic-sources';+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';@@ -569,6 +570,11 @@ function TrafficPageContent({ brand }: { brand: Brand }) {// 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;+ // Analytics isn't ready for this brand: the platform table's engagement+ // columns show "—", as the KPI cards do, and say what they need (AT-005,+ // §3.8b's partial note) — even with rows left from an earlier connection.+ const gaMissing =+ !sourcesFailed && sources !== null && googleSourceStatus(sources.ga) !== 'connected';const isEmpty = totalVisits === 0 && logs.length === 0;const hasAnyData = summary?.hasAnyData ?? false;@@ -692,8 +698,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {</Card></div>- {/* Tables row */}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ {/* Tables row: side by side from 1,280px. The platform table's five+ columns (AT-005) need more than half the page below that, and+ numeric cells never wrap (spec §3.2). */}+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">{/* Platform table */}<Card><CardHeader className="pb-2">@@ -708,7 +716,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {<TableRow><TableHead className="pl-6">Platform</TableHead><TableHead className="text-right">Visits</TableHead>- <TableHead className="text-right pr-6">Change</TableHead>+ <TableHead className="text-right">Change</TableHead>+ {/* From Google Analytics (AT-005). */}+ <TableHead className="text-right">{t('platforms.engaged')}</TableHead>+ <TableHead className="text-right pr-6">{t('platforms.keyEvents')}</TableHead></TableRow></TableHeader><TableBody>@@ -722,7 +733,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {<TableCell className="text-right font-semibold tabular-nums">{formatNumber(row.visits)}</TableCell>- <TableCell className="text-right pr-6">+ <TableCell className="text-right"><div className="flex justify-end"><DeltaBadgecurrent={row.visits}@@ -731,10 +742,17 @@ function TrafficPageContent({ brand }: { brand: Brand }) {/></div></TableCell>+ <TableCell className="text-right">+ <EngagedCell analytics={gaMissing ? null : row.analytics} />+ </TableCell>+ <TableCell className="text-right pr-6">+ <KeyEventsCell analytics={gaMissing ? null : row.analytics} />+ </TableCell></TableRow>))}</TableBody></Table>+ {gaMissing && <PlatformValueNote />}</CardContent></Card>diff --git a/web/src/app/api/traffic/export/route.test.ts b/web/src/app/api/traffic/export/route.test.tsindex 27d73e650..a96c395f7 100644--- a/web/src/app/api/traffic/export/route.test.ts+++ b/web/src/app/api/traffic/export/route.test.ts@@ -177,8 +177,8 @@ describe('GET /api/traffic/export', () => {expect(csv.bom).toBe(true);expect(csv.text).toBe([- 'Platform,Visits,"Visits, previous period",Change (%),Share (%),Note',- 'Gemini,2,1,,100,Low sample: fewer than 30 visits in this period or the one before',+ 'Platform,Visits,"Visits, previous period",Change (%),Share (%),Engaged (%),Key events,Note',+ 'Gemini,2,1,,100,,,Low sample: fewer than 30 visits in this period or the one before',].join('\n'),);expect(loaders.getTrafficTrend).not.toHaveBeenCalled();diff --git a/web/src/lib/actions/traffic-google-totals.test.ts b/web/src/lib/actions/traffic-google-totals.test.tsindex 30f0c6a7b..c03bd644b 100644--- a/web/src/lib/actions/traffic-google-totals.test.ts+++ b/web/src/lib/actions/traffic-google-totals.test.ts@@ -16,7 +16,18 @@ 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 GA_ROW = {+ sessions: 812,+ ai_sessions: 4,+ ai_engaged_sessions: 3,+ ai_key_events: 1,+ ai_key_event_sessions: 1,+ ai_revenue: 149.9,+ organic_sessions: 1000,+ organic_engaged_sessions: 580,+ organic_key_events: 60,+ organic_key_event_sessions: 50,+};const GSC_ROW = {since: '2026-10-16',until: '2026-10-16',@@ -61,7 +72,16 @@ describe('getTrafficGoogleTotals', () => {p_latest: true,});expect(totals).toEqual({- ga: { sessions: 812, aiSessions: 4, aiEngagedSessions: 3, aiKeyEvents: 1 },+ ga: {+ sessions: 812,+ aiSessions: 4,+ aiEngagedSessions: 3,+ aiKeyEvents: 1,+ aiKeyEventSessions: 1,+ aiRevenue: 149.9,+ // Google organic, the page's comparison (AT-005).+ organic: { sessions: 1000, engagedSessions: 580, keyEvents: 60, keyEventSessions: 50 },+ },gsc: {since: '2026-10-16',until: '2026-10-16',diff --git a/web/src/lib/actions/traffic-merged.test.ts b/web/src/lib/actions/traffic-merged.test.tsindex 30b111ec8..775fb8937 100644--- a/web/src/lib/actions/traffic-merged.test.ts+++ b/web/src/lib/actions/traffic-merged.test.ts@@ -42,7 +42,25 @@ const PREVIOUS: Merged = {days: [],};+// Google Analytics' engagement per platform (AT-005).+const PLATFORM_VALUE = [+ {+ platform: 'chatgpt.com',+ sessions: 120,+ engaged_sessions: 80,+ key_events: 9,+ key_event_sessions: 7,+ },+];+const rpc = vi.fn();++/** The merged read answers `merged`; the platform figures stay as above. */+const answerMerged = (merged: Merged) =>+ rpc.mockImplementation(async (fn: string) => ({+ data: fn === 'ga_platform_value' ? PLATFORM_VALUE : merged,+ error: null,+ }));let snippetCount = 0;let analyticsRows: { id: string }[] = [];@@ -71,8 +89,8 @@ beforeEach(() => {vi.useFakeTimers();vi.setSystemTime(new Date('2026-10-18T12:30:00.000Z'));rpc.mockReset();- rpc.mockImplementation(async (_fn: string, args: { p_to_inclusive: boolean }) => ({- data: args.p_to_inclusive ? CURRENT : PREVIOUS,+ rpc.mockImplementation(async (fn: string, args: { p_to_inclusive: boolean }) => ({+ data: fn === 'ga_platform_value' ? PLATFORM_VALUE : args.p_to_inclusive ? CURRENT : PREVIOUS,error: null,}));snippetCount = 6;@@ -116,16 +134,28 @@ describe('getTrafficSummary', () => {hasAnyData: true,});expect(summary.platformBreakdown).toEqual([- { platform: 'chatgpt.com', visits: 116, visitsPrev: 40 },- { platform: 'perplexity.ai', visits: 47, visitsPrev: 0 },- { platform: 'gemini.google.com', visits: 4, visitsPrev: 0 },+ {+ platform: 'chatgpt.com',+ visits: 116,+ visitsPrev: 40,+ analytics: { sessions: 120, engagedSessions: 80, keyEvents: 9, keyEventSessions: 7 },+ },+ // Platforms Analytics never saw have no engagement figures.+ { platform: 'perplexity.ai', visits: 47, visitsPrev: 0, analytics: null },+ { platform: 'gemini.google.com', visits: 4, visitsPrev: 0, analytics: null },]);+ // Over the range's days, as the KPI cards read Analytics.+ expect(rpc).toHaveBeenCalledWith('ga_platform_value', {+ p_brand_id: 'b1',+ p_since: '2026-10-11',+ p_until: '2026-10-18',+ });expect(summary.topPages[0]).toEqual({ url: '/menu', visits: 115, visitsPrev: 40 });});it('keeps the top 10 pages for the page, and all of them for an export', async () => {const pages = Array.from({ length: 12 }, (_, i) => ({ page: `/p${i}`, visits: 12 - i }));- rpc.mockResolvedValue({ data: { ...CURRENT, pages }, error: null });+ answerMerged({ ...CURRENT, pages });const window = { dateFrom: '2026-10-11T12:30:00.000Z' };expect((await getTrafficSummary('b1', window)).topPages).toHaveLength(10);expect(@@ -135,12 +165,14 @@ describe('getTrafficSummary', () => {it('reads the last 24 hours from the snippet alone: Google Analytics has no hours', async () => {await getTrafficSummary('b1', { dateFrom: '2026-10-17T12:30:00.000Z' });- for (const [, args] of rpc.mock.calls) expect(args.p_analytics).toBe(false);+ for (const [fn, args] of rpc.mock.calls) {+ if (fn === 'ai_traffic_merged') expect(args.p_analytics).toBe(false);+ }});it('reads all time from the start, with no period before', async () => {const summary = await getTrafficSummary('b1', {});- expect(rpc).toHaveBeenCalledTimes(1);+ expect(rpc.mock.calls.filter(([fn]) => fn === 'ai_traffic_merged')).toHaveLength(1);expect(rpc).toHaveBeenCalledWith('ai_traffic_merged',expect.objectContaining({ p_from: null, p_to: null }),@@ -151,10 +183,7 @@ describe('getTrafficSummary', () => {});it('counts a brand with only Google Analytics history as having data', async () => {- rpc.mockResolvedValue({- data: { ...CURRENT, visits: 0, platforms: [], pages: [] },- error: null,- });+ answerMerged({ ...CURRENT, visits: 0, platforms: [], pages: [] });snippetCount = 0;analyticsRows = [{ id: 'ga1' }];const window = { dateFrom: '2026-10-17T12:30:00.000Z' };@@ -166,6 +195,7 @@ describe('getTrafficSummary', () => {it('fails loudly when the read fails', async () => {rpc.mockResolvedValue({ data: null, error: { message: 'permission denied' } });+ // (Both the merged read and the platform figures fail; either one is enough.)await expect(getTrafficSummary('b1', { dateFrom: '2026-10-11T12:30:00.000Z' })).rejects.toThrow('permission denied',);diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.tsindex f05677560..20bc185f2 100644--- a/web/src/lib/actions/traffic.ts+++ b/web/src/lib/actions/traffic.ts@@ -44,7 +44,13 @@ export interface TrafficSummary {analyticsDays: string[];/** False for all time, which has no previous period to compare with. */hasPreviousPeriod: boolean;- platformBreakdown: { platform: string; visits: number; visitsPrev: number }[];+ platformBreakdown: {+ platform: string;+ visits: number;+ visitsPrev: number;+ /** Google Analytics' engagement for the platform over the range's days; null without any (AT-005). */+ analytics: TrafficEngagement | null;+ }[];topPages: { url: string; visits: number; visitsPrev: number }[];hasAnyData: boolean;}@@ -211,7 +217,7 @@ export async function getTrafficSummary(// Visits, platforms and pages from the snippet and Google Analytics, day// by day (AT-004), summed in the database: no row cap applies.- const [current, previous, lifetime] = await Promise.all([+ const [current, previous, lifetime, value] = await Promise.all([readMergedTraffic(supabase, brandId, { from, to, toInclusive: true }),hasPrev? readMergedTraffic(supabase, brandId, { from: prevFrom, to: prevTo, toInclusive: false })@@ -228,8 +234,28 @@ export async function getTrafficSummary(.limit(1),]): null,+ // What each platform's visitors did, from Analytics over the range's+ // days (AT-005): engagement and key events are rates of its sessions,+ // so they read Analytics alone, whichever origin counted the visits.+ supabase.rpc('ga_platform_value', {+ p_brand_id: brandId,+ p_since: utcDay(from) ?? null,+ p_until: utcDay(to) ?? new Date().toISOString().slice(0, 10),+ }),]);if (lifetime?.[1].error) throw new Error(lifetime[1].error.message);+ if (value.error) throw new Error(value.error.message);+ const valueByPlatform = new Map(+ (value.data ?? []).map((row) => [+ row.platform,+ {+ sessions: Number(row.sessions) || 0,+ engagedSessions: Number(row.engaged_sessions) || 0,+ keyEvents: Number(row.key_events) || 0,+ keyEventSessions: Number(row.key_event_sessions) || 0,+ },+ ]),+ );const hasAnyData = lifetime? lifetime[0] > 0 || (lifetime[1].data ?? []).length > 0: current.visits > 0;@@ -245,7 +271,11 @@ export async function getTrafficSummary(hasPreviousPeriod: hasPrev,platformBreakdown: current.platforms.filter((p) => p.visits > 0)- .map((p) => ({ ...p, visitsPrev: previousByPlatform.get(p.platform) ?? 0 })),+ .map((p) => ({+ ...p,+ visitsPrev: previousByPlatform.get(p.platform) ?? 0,+ analytics: valueByPlatform.get(p.platform) ?? null,+ })),topPages: current.pages.slice(0, opts?.topPages ?? 10).map((p) => ({url: p.page,visits: p.visits,@@ -556,12 +586,26 @@ export async function getPageOpportunities(* and key events; from Search Console, clicks against the period before.* Each is asked for only when its source has data for the brand.*/+/** Analytics' engagement figures for one group of sessions (AT-005). */+export interface TrafficEngagement {+ sessions: number;+ engagedSessions: number;+ keyEvents: number;+ /** Sessions with at least one key event: the key event rate is this over sessions. */+ keyEventSessions: number;+}+export interface TrafficGoogleTotals {ga: {sessions: number;aiSessions: number;aiEngagedSessions: number;aiKeyEvents: number;+ aiKeyEventSessions: number;+ /** AI sessions' purchase revenue, in the property's currency; 0 without e-commerce. */+ aiRevenue: number;+ /** Google organic (the Organic Search channel), the page's comparison (AT-005). */+ organic: TrafficEngagement;} | null;gsc: {/** The days the clicks cover; no first day for all time. */@@ -623,6 +667,14 @@ export async function getTrafficGoogleTotals(aiSessions: Number(gaRow.ai_sessions) || 0,aiEngagedSessions: Number(gaRow.ai_engaged_sessions) || 0,aiKeyEvents: Number(gaRow.ai_key_events) || 0,+ aiKeyEventSessions: Number(gaRow.ai_key_event_sessions) || 0,+ aiRevenue: Number(gaRow.ai_revenue) || 0,+ organic: {+ sessions: Number(gaRow.organic_sessions) || 0,+ engagedSessions: Number(gaRow.organic_engaged_sessions) || 0,+ keyEvents: Number(gaRow.organic_key_events) || 0,+ keyEventSessions: Number(gaRow.organic_key_event_sessions) || 0,+ },}: null,gsc: gscRowdiff --git a/web/src/lib/traffic-export.test.ts b/web/src/lib/traffic-export.test.tsindex 940250931..94e542c1c 100644--- a/web/src/lib/traffic-export.test.ts+++ b/web/src/lib/traffic-export.test.ts@@ -48,9 +48,14 @@ const data = (over: Partial<TrafficExportData> = {}): TrafficExportData => ({analyticsDays: [],hasPreviousPeriod: true,platformBreakdown: [- { platform: 'chatgpt.com', visits: 40, visitsPrev: 33 },- { platform: 'gemini.google.com', visits: 12, visitsPrev: 5 },- { platform: 'claude.ai', visits: 3, visitsPrev: 0 },+ {+ platform: 'chatgpt.com',+ visits: 40,+ visitsPrev: 33,+ analytics: { sessions: 44, engagedSessions: 33, keyEvents: 6, keyEventSessions: 5 },+ },+ { platform: 'gemini.google.com', visits: 12, visitsPrev: 5, analytics: null },+ { platform: 'claude.ai', visits: 3, visitsPrev: 0, analytics: null },],topPages: [{ url: '/pricing', visits: 35, visitsPrev: 30 }],hasAnyData: true,@@ -121,9 +126,23 @@ describe('trafficTable', () => {it('leaves a change the page would not show empty, and says why (F4)', () => {const table = trafficTable('platforms', data(), label);expect(table.rows).toEqual([- ['ChatGPT', 40, 33, 21, 72.7, null],- ['Gemini', 12, 5, null, 21.8, expect.stringContaining('Low sample')],- ['Claude', 3, 0, null, 5.5, expect.stringContaining('New')],+ ['ChatGPT', 40, 33, 21, 72.7, 75, 6, null],+ ['Gemini', 12, 5, null, 21.8, null, null, expect.stringContaining('Low sample')],+ ['Claude', 3, 0, null, 5.5, null, null, expect.stringContaining('New')],+ ]);+ });++ it("adds Google Analytics' engaged share and key events per platform, as the table does (AT-005)", () => {+ const table = trafficTable('platforms', data(), label);+ expect(table.headers).toEqual([+ 'Platform',+ 'Visits',+ 'Visits, previous period',+ 'Change (%)',+ 'Share (%)',+ 'Engaged (%)',+ 'Key events',+ 'Note',]);});@@ -246,7 +265,7 @@ describe('trafficWorkbook', () => {]);// A bold header row, then the rows with their numbers as numbers.expect(sheets[3].data[0][0]).toEqual({ value: 'Platform', fontWeight: 'bold' });- expect(sheets[3].data[1]).toEqual(['ChatGPT', 40, 33, 21, 72.7, null]);+ expect(sheets[3].data[1]).toEqual(['ChatGPT', 40, 33, 21, 72.7, 75, 6, null]);});it('holds only the table for a single table', () => {diff --git a/web/src/lib/traffic-export.ts b/web/src/lib/traffic-export.tsindex 01a68dafd..c708c6867 100644--- a/web/src/lib/traffic-export.ts+++ b/web/src/lib/traffic-export.ts@@ -143,16 +143,22 @@ function platforms(data: TrafficExportData, label: ExportLabel): ExportTable {label('columns.previousVisits'),label('columns.change'),label('columns.share'),+ // From Google Analytics, as the table shows them (AT-005).+ label('columns.engaged'),+ label('columns.keyEvents'),label('columns.note'),],rows: (s?.platformBreakdown ?? []).map((row) => {const delta = change(row.visits, row.visitsPrev, s!.hasPreviousPeriod, label);+ const ga = row.analytics;return [getPlatformName(row.platform),row.visits,s!.hasPreviousPeriod ? row.visitsPrev : null,delta.pct,total > 0 ? Math.round((row.visits / total) * 1000) / 10 : null,+ ga && ga.sessions > 0 ? Math.round((ga.engagedSessions / ga.sessions) * 1000) / 10 : null,+ ga ? ga.keyEvents : null,delta.note || null,];}),diff --git a/web/src/lib/traffic-kpis.test.ts b/web/src/lib/traffic-kpis.test.tsindex de15adfb6..3f7241410 100644--- a/web/src/lib/traffic-kpis.test.ts+++ b/web/src/lib/traffic-kpis.test.ts@@ -2,9 +2,11 @@ import { describe, expect, it } from 'vitest';import {formatGoogleDays,formatPctChange,+ formatRatio,formatShare,gscLatestDays,isShortRange,+ organicRatio,} from './traffic-kpis';/** AT-017 (spec §3.2): the rules behind the AI Traffic KPI cards. */@@ -60,3 +62,28 @@ describe('formatGoogleDays', () => {expect(formatGoogleDays(null, '2026-10-16')).toBe('Oct 16');});});++describe('organicRatio', () => {+ const side = (sessions: number, keyEvents: number, keyEventSessions: number) => ({+ sessions,+ keyEvents,+ keyEventSessions,+ });++ it("compares AI visitors' key event rate with Google organic's", () => {+ // 10% of AI sessions against 5% of organic ones.+ expect(organicRatio(side(100, 12, 10), side(1000, 60, 50))).toBeCloseTo(2);+ expect(formatRatio(2)).toBe('2×');+ expect(formatRatio(0.5833)).toBe('0.6×');+ });++ it('compares nothing below 30 sessions or 5 key events on either side (§5.4)', () => {+ expect(organicRatio(side(29, 12, 10), side(1000, 60, 50))).toBeNull();+ expect(organicRatio(side(100, 4, 4), side(1000, 60, 50))).toBeNull();+ expect(organicRatio(side(100, 12, 10), side(1000, 4, 4))).toBeNull();+ });++ it('compares nothing while a rate is unknown (rows synced before it)', () => {+ expect(organicRatio(side(100, 12, 0), side(1000, 60, 50))).toBeNull();+ });+});diff --git a/web/src/lib/traffic-kpis.ts b/web/src/lib/traffic-kpis.tsindex f9803d092..5a5fd7ae9 100644--- a/web/src/lib/traffic-kpis.ts+++ b/web/src/lib/traffic-kpis.ts@@ -55,3 +55,30 @@ export function formatGoogleDays(since: string | null, until: string): string {});return !since || since === until ? day(until) : `${day(since)} – ${day(until)}`;}++/** The sample a conversion comparison needs on each side (spec §5.4). */+export const COMPARISON_MIN_SESSIONS = 30;+export const COMPARISON_MIN_KEY_EVENTS = 5;++/**+ * AI visitors' key event rate against Google organic's, as a multiple+ * ("2x organic"), or null when either side is too small to compare (§5.4:+ * at least 30 sessions and 5 key events each) or a rate is unknown. The rate+ * is sessions with a key event over sessions, as GA4 reports it.+ */+export function organicRatio(+ ai: { sessions: number; keyEvents: number; keyEventSessions: number },+ organic: { sessions: number; keyEvents: number; keyEventSessions: number },+): number | null {+ const enough = (side: typeof ai) =>+ side.sessions >= COMPARISON_MIN_SESSIONS &&+ side.keyEvents >= COMPARISON_MIN_KEY_EVENTS &&+ side.keyEventSessions > 0;+ if (!enough(ai) || !enough(organic)) return null;+ return ai.keyEventSessions / ai.sessions / (organic.keyEventSessions / organic.sessions);+}++/** A multiple as the cards write it: "1.8×", "0.6×". */+export function formatRatio(ratio: number): string {+ return `${formatNumber(Math.round(ratio * 10) / 10)}×`;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 46ba0822c..d60dbf185 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3113,12 +3113,28 @@ export type Database = {transactions: number}[]}+ ga_platform_value: {+ Args: { p_brand_id: string; p_since: string | null; p_until: string }+ Returns: {+ engaged_sessions: number+ key_event_sessions: number+ key_events: number+ platform: string+ sessions: number+ }[]+ }ga_traffic_totals: {Args: { p_brand_id: string; p_since: string | null; p_until: string }Returns: {ai_engaged_sessions: number+ ai_key_event_sessions: numberai_key_events: number+ ai_revenue: numberai_sessions: number+ organic_engaged_sessions: number+ organic_key_event_sessions: number+ organic_key_events: number+ organic_sessions: numbersessions: number}[]}