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): show where AI visitors convert, by landing page and by platform and topic (#1174)

Cihan12843d6de7fb
diff --git a/supabase/migrations/00179_ai_traffic_conversions.sql b/supabase/migrations/00179_ai_traffic_conversions.sql
new file mode 100644
index 000000000..70c1d0d18
--- /dev/null
+++ b/supabase/migrations/00179_ai_traffic_conversions.sql
@@ -0,0 +1,169 @@
+-- ============================================================================
+-- 00179: where AI visitors convert (AT-014)
+-- ============================================================================
+-- Spec §3.4b, two cards that need Google Analytics:
+--
+-- * Top converting pages from AI — landing pages ranked by the key events
+-- (or revenue, when the property reports purchases) of their AI-referred
+-- sessions, with those sessions, the sessions with a key event (the rate,
+-- 00177) and the platform whose visitors converted most.
+-- * Which answers bring buyers — AI platform × topic: the key events of a
+-- platform's visitors on the pages that tracked answers in a topic cite,
+-- so the topics worth protecting first are the ones that bring buyers.
+--
+-- Both read Analytics' own AI sessions (ga_ai_traffic_stats): the key events
+-- are theirs, so the visits and the rate come from the same sessions. Pages
+-- are keyed by lower(normalize_page_path(...)), as the Pages section's are
+-- (00178). A topic is one of the tracked prompts whose answers cited the page
+-- in the window, on any platform; a page cited in two topics counts in both.
+--
+-- citation_urls has no member select policy, so this runs as its owner after
+-- checking the caller belongs to the brand's organization; a caller from
+-- elsewhere gets nothing.
+
+create or replace function public.ai_traffic_conversions(
+ p_brand_id uuid,
+ p_since date,
+ p_until date,
+ p_limit integer default 50
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_result jsonb;
+begin
+ if not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) and auth.role() is distinct from 'service_role' then
+ return null;
+ end if;
+
+ with
+ -- Analytics' AI sessions per page and platform over the window's days.
+ by_platform as (
+ select
+ lower(public.normalize_page_path(g.landing_page)) as page_key,
+ min(public.normalize_page_path(g.landing_page)) as page,
+ coalesce(g.platform, g.source) as platform,
+ sum(g.sessions)::bigint as sessions,
+ sum(g.key_events)::bigint as key_events,
+ sum(g.key_event_sessions)::bigint as key_event_sessions,
+ sum(g.transactions)::bigint as transactions,
+ coalesce(sum(g.purchase_revenue), 0)::numeric as revenue
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.landing_page <> ''
+ and g.date >= coalesce(p_since, '-infinity'::date)
+ and g.date <= coalesce(p_until, 'infinity'::date)
+ group by 1, 3
+ ),
+ pages as (
+ select
+ page_key,
+ min(page) as page,
+ sum(sessions)::bigint as sessions,
+ sum(key_events)::bigint as key_events,
+ sum(key_event_sessions)::bigint as key_event_sessions,
+ sum(transactions)::bigint as transactions,
+ sum(revenue) as revenue
+ from by_platform
+ group by page_key
+ ),
+ -- The platform whose visitors converted most on each page.
+ best as (
+ select distinct on (page_key) page_key, platform
+ from by_platform
+ where key_events > 0 or revenue > 0
+ order by page_key, revenue desc, key_events desc, sessions desc, platform
+ ),
+ converting as (
+ select p.*, b.platform as best_platform
+ from pages p
+ left join best b on b.page_key = p.page_key
+ where p.key_events > 0 or p.revenue > 0
+ ),
+ -- The topics of the tracked prompts whose answers cited a converting page.
+ own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ own_urls as (
+ -- citation_urls.domain is stored lowercased and without www: an index probe.
+ select cu.id, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ cited_topics as (
+ select distinct ou.page_key, t.id as topic_id, t.name as topic
+ from own_urls ou
+ join converting c on c.page_key = ou.page_key
+ join public.prompt_result_citations prc
+ on prc.url_id = ou.id
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= coalesce(p_since::timestamp at time zone 'utc', '-infinity'::timestamptz)
+ and prc.created_at < coalesce((p_until + 1)::timestamp at time zone 'utc', 'infinity'::timestamptz)
+ join public.prompt_results pr on pr.id = prc.prompt_result_id
+ join public.prompts p on p.id = pr.prompt_id
+ join public.topics t on t.id = p.topic_id
+ ),
+ answers as (
+ select
+ bp.platform,
+ ct.topic_id,
+ min(ct.topic) as topic,
+ count(distinct bp.page_key)::bigint as pages,
+ sum(bp.sessions)::bigint as sessions,
+ sum(bp.key_events)::bigint as key_events,
+ sum(bp.key_event_sessions)::bigint as key_event_sessions,
+ sum(bp.revenue) as revenue
+ from by_platform bp
+ join cited_topics ct on ct.page_key = bp.page_key
+ group by bp.platform, ct.topic_id
+ having sum(bp.key_events) > 0 or sum(bp.revenue) > 0
+ )
+ select jsonb_build_object(
+ -- All AI sessions in the window, converting or not: the caller widens a
+ -- short range that has too few to say anything.
+ 'sessions', (select coalesce(sum(sessions), 0) from pages),
+ 'has_revenue', exists (select 1 from pages where revenue > 0),
+ 'page_count', (select count(*) from converting),
+ 'answer_count', (select count(*) from answers),
+ -- Ranked by revenue, which is 0 everywhere without purchases, then key events.
+ 'pages', coalesce((
+ select jsonb_agg(to_jsonb(r) - 'page_key')
+ from (
+ select * from converting
+ order by revenue desc, key_events desc, sessions desc, page
+ limit p_limit
+ ) r
+ ), '[]'::jsonb),
+ 'answers', coalesce((
+ select jsonb_agg(to_jsonb(a))
+ from (
+ select * from answers
+ order by revenue desc, key_events desc, sessions desc, platform, topic
+ limit p_limit
+ ) a
+ ), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke all on function public.ai_traffic_conversions(uuid, date, date, integer) from public, anon;
+grant execute on function public.ai_traffic_conversions(uuid, date, date, integer)
+ to authenticated, service_role;
+
+comment on function public.ai_traffic_conversions(uuid, date, date, integer) is
+ 'AI Traffic "Where AI visitors convert" (AT-014, spec §3.4b): converting landing pages from Analytics'' AI sessions (sessions, key events, sessions with a key event, revenue, best platform) and AI platform × topic of the tracked prompts whose answers cite them. Security definer with an organization check: citation_urls has no member select policy.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 723b29dd7..63a316c55 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -24314,3 +24314,176 @@ comment on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00179_ai_traffic_conversions.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00179: where AI visitors convert (AT-014)
+-- ============================================================================
+-- Spec §3.4b, two cards that need Google Analytics:
+--
+-- * Top converting pages from AI — landing pages ranked by the key events
+-- (or revenue, when the property reports purchases) of their AI-referred
+-- sessions, with those sessions, the sessions with a key event (the rate,
+-- 00177) and the platform whose visitors converted most.
+-- * Which answers bring buyers — AI platform × topic: the key events of a
+-- platform's visitors on the pages that tracked answers in a topic cite,
+-- so the topics worth protecting first are the ones that bring buyers.
+--
+-- Both read Analytics' own AI sessions (ga_ai_traffic_stats): the key events
+-- are theirs, so the visits and the rate come from the same sessions. Pages
+-- are keyed by lower(normalize_page_path(...)), as the Pages section's are
+-- (00178). A topic is one of the tracked prompts whose answers cited the page
+-- in the window, on any platform; a page cited in two topics counts in both.
+--
+-- citation_urls has no member select policy, so this runs as its owner after
+-- checking the caller belongs to the brand's organization; a caller from
+-- elsewhere gets nothing.
+
+create or replace function public.ai_traffic_conversions(
+ p_brand_id uuid,
+ p_since date,
+ p_until date,
+ p_limit integer default 50
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_result jsonb;
+begin
+ if not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) and auth.role() is distinct from 'service_role' then
+ return null;
+ end if;
+
+ with
+ -- Analytics' AI sessions per page and platform over the window's days.
+ by_platform as (
+ select
+ lower(public.normalize_page_path(g.landing_page)) as page_key,
+ min(public.normalize_page_path(g.landing_page)) as page,
+ coalesce(g.platform, g.source) as platform,
+ sum(g.sessions)::bigint as sessions,
+ sum(g.key_events)::bigint as key_events,
+ sum(g.key_event_sessions)::bigint as key_event_sessions,
+ sum(g.transactions)::bigint as transactions,
+ coalesce(sum(g.purchase_revenue), 0)::numeric as revenue
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.landing_page <> ''
+ and g.date >= coalesce(p_since, '-infinity'::date)
+ and g.date <= coalesce(p_until, 'infinity'::date)
+ group by 1, 3
+ ),
+ pages as (
+ select
+ page_key,
+ min(page) as page,
+ sum(sessions)::bigint as sessions,
+ sum(key_events)::bigint as key_events,
+ sum(key_event_sessions)::bigint as key_event_sessions,
+ sum(transactions)::bigint as transactions,
+ sum(revenue) as revenue
+ from by_platform
+ group by page_key
+ ),
+ -- The platform whose visitors converted most on each page.
+ best as (
+ select distinct on (page_key) page_key, platform
+ from by_platform
+ where key_events > 0 or revenue > 0
+ order by page_key, revenue desc, key_events desc, sessions desc, platform
+ ),
+ converting as (
+ select p.*, b.platform as best_platform
+ from pages p
+ left join best b on b.page_key = p.page_key
+ where p.key_events > 0 or p.revenue > 0
+ ),
+ -- The topics of the tracked prompts whose answers cited a converting page.
+ own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ own_urls as (
+ -- citation_urls.domain is stored lowercased and without www: an index probe.
+ select cu.id, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ cited_topics as (
+ select distinct ou.page_key, t.id as topic_id, t.name as topic
+ from own_urls ou
+ join converting c on c.page_key = ou.page_key
+ join public.prompt_result_citations prc
+ on prc.url_id = ou.id
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= coalesce(p_since::timestamp at time zone 'utc', '-infinity'::timestamptz)
+ and prc.created_at < coalesce((p_until + 1)::timestamp at time zone 'utc', 'infinity'::timestamptz)
+ join public.prompt_results pr on pr.id = prc.prompt_result_id
+ join public.prompts p on p.id = pr.prompt_id
+ join public.topics t on t.id = p.topic_id
+ ),
+ answers as (
+ select
+ bp.platform,
+ ct.topic_id,
+ min(ct.topic) as topic,
+ count(distinct bp.page_key)::bigint as pages,
+ sum(bp.sessions)::bigint as sessions,
+ sum(bp.key_events)::bigint as key_events,
+ sum(bp.key_event_sessions)::bigint as key_event_sessions,
+ sum(bp.revenue) as revenue
+ from by_platform bp
+ join cited_topics ct on ct.page_key = bp.page_key
+ group by bp.platform, ct.topic_id
+ having sum(bp.key_events) > 0 or sum(bp.revenue) > 0
+ )
+ select jsonb_build_object(
+ -- All AI sessions in the window, converting or not: the caller widens a
+ -- short range that has too few to say anything.
+ 'sessions', (select coalesce(sum(sessions), 0) from pages),
+ 'has_revenue', exists (select 1 from pages where revenue > 0),
+ 'page_count', (select count(*) from converting),
+ 'answer_count', (select count(*) from answers),
+ -- Ranked by revenue, which is 0 everywhere without purchases, then key events.
+ 'pages', coalesce((
+ select jsonb_agg(to_jsonb(r) - 'page_key')
+ from (
+ select * from converting
+ order by revenue desc, key_events desc, sessions desc, page
+ limit p_limit
+ ) r
+ ), '[]'::jsonb),
+ 'answers', coalesce((
+ select jsonb_agg(to_jsonb(a))
+ from (
+ select * from answers
+ order by revenue desc, key_events desc, sessions desc, platform, topic
+ limit p_limit
+ ) a
+ ), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke all on function public.ai_traffic_conversions(uuid, date, date, integer) from public, anon;
+grant execute on function public.ai_traffic_conversions(uuid, date, date, integer)
+ to authenticated, service_role;
+
+comment on function public.ai_traffic_conversions(uuid, date, date, integer) is
+ 'AI Traffic "Where AI visitors convert" (AT-014, spec §3.4b): converting landing pages from Analytics'' AI sessions (sessions, key events, sessions with a key event, revenue, best platform) and AI platform × topic of the tracked prompts whose answers cite them. Security definer with an organization check: citation_urls has no member select policy.';
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 4576e95b5..6e8cd4d46 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3115,6 +3115,8 @@
"trend": "Trend",
"platforms": "Platforms",
"pages": "Top landing pages",
+ "convertingPages": "Top converting pages",
+ "buyerAnswers": "Answers that bring buyers",
"pageStatus": "Pages by status",
"visits": "Visits"
},
@@ -3149,7 +3151,12 @@
"aiKeyEvents": "Key events from AI",
"topPlatforms": "Top platforms",
"inSitemap": "In sitemap",
- "status": "Status"
+ "status": "Status",
+ "revenue": "Revenue",
+ "conversionRate": "Rate (%)",
+ "bestPlatform": "Best platform",
+ "topic": "Topic",
+ "citedPages": "Cited pages"
},
"metrics": {
"visits": "AI-referred visits",
@@ -3164,7 +3171,10 @@
"lowSample": "Low sample: fewer than 30 visits in this period or the one before",
"new": "New: no visits in the previous period",
"noPreviousPeriod": "No previous period for all time",
- "noPages": "No pages in this range"
+ "noPages": "No pages in this range",
+ "noConversions": "No key events from AI visitors in this range",
+ "lastThirtyDays": "Last 30 days: the selected range has fewer than 30 AI visits",
+ "conversionLowSample": "Low sample: fewer than 30 AI visits"
},
"sourceStates": {
"active": "Active",
@@ -3309,9 +3319,40 @@
"engagedVisits": "engaged visits",
"keyEvents": "key events from AI",
"googleClicks": "Google clicks",
+ "conversions": "where AI visitors convert",
"pageValue": "which valuable pages get no AI traffic"
}
},
+ "conversions": {
+ "title": "Where AI visitors convert",
+ "rankedByKeyEvents": "Ranked by key events from AI visits",
+ "rankedByRevenue": "Ranked by revenue from AI visits",
+ "widened": "fewer than 30 AI visits in the selected range, so this uses the last 30 days",
+ "last30Days": "Last 30 days",
+ "lowSample": "Low sample",
+ "lowSampleHint": "{visits, plural, one {# AI visit} other {# AI visits}}: fewer than 30, so a rate would mislead.",
+ "rateUnknown": "Google Analytics hasn't reported the rate for these sessions yet.",
+ "failed": "Couldn't load where AI visitors convert.",
+ "empty": "No key events from AI visitors in this range.",
+ "pages": {
+ "title": "Top converting pages from AI",
+ "legend": "AI visits are Google Analytics sessions from AI assistants. The rate is the share with a key event, shown from 30 visits."
+ },
+ "answers": {
+ "title": "Which answers bring buyers",
+ "legend": "Topics of the tracked prompts whose answers cite the converting pages, by the AI platform the visitors came from. Shows which topics bring buyers, not just visits."
+ },
+ "columns": {
+ "page": "Landing page",
+ "aiVisits": "AI visits",
+ "keyEvents": "Key events",
+ "revenue": "Revenue",
+ "rate": "Rate",
+ "bestPlatform": "Best platform",
+ "platform": "Platform",
+ "topic": "Topic"
+ }
+ },
"pageOpportunities": {
"rank": "Rank {by}",
"minutes": "{minutes} min",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.test.tsx
new file mode 100644
index 000000000..490373c51
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.test.tsx
@@ -0,0 +1,180 @@
+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 { SourceState } from '@/lib/actions/integrations';
+import type { TrafficConversions, TrafficDateWindow } from '@/lib/actions/traffic';
+
+/**
+ * Where AI visitors convert (AT-014, spec §3.4b): its two cards for the
+ * page's range, ranked by key events or revenue, with Low sample below 30 AI
+ * visits; the last 30 days when the range is too thin, said in the header;
+ * and Google Analytics' own state in full until it has data (§3.8b).
+ */
+
+const getTrafficConversions = vi.fn();
+vi.mock('@/lib/actions/traffic', () => ({
+ getTrafficConversions: (...args: unknown[]) => getTrafficConversions(...args),
+}));
+vi.mock('@/hooks/use-integration-connect', () => ({
+ useIntegrationConnect: () => ({ connecting: false, connect: vi.fn() }),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,
+}));
+
+const { ConversionsSection } = await import('./_conversions');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const WEEK: TrafficDateWindow = { dateFrom: '2026-10-11T09:00:00.000Z' };
+
+const ga = (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 conversions = (over: Partial<TrafficConversions> = {}): TrafficConversions => ({
+ aiVisits: 64,
+ hasRevenue: false,
+ widened: false,
+ pageCount: 2,
+ answerCount: 1,
+ pages: [
+ {
+ page: '/gifts',
+ aiVisits: 50,
+ keyEvents: 5,
+ keyEventSessions: 4,
+ transactions: 1,
+ revenue: 120.5,
+ bestPlatform: 'chatgpt.com',
+ },
+ {
+ page: '/pricing',
+ aiVisits: 5,
+ keyEvents: 2,
+ keyEventSessions: 2,
+ transactions: 0,
+ revenue: 0,
+ bestPlatform: 'gemini.google.com',
+ },
+ ],
+ answers: [
+ {
+ platform: 'perplexity.ai',
+ topicId: 't1',
+ topic: 'Coffee gifts',
+ pages: 2,
+ aiVisits: 40,
+ keyEvents: 4,
+ keyEventSessions: 3,
+ revenue: 0,
+ },
+ ],
+ ...over,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ getTrafficConversions.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render(source: SourceState | null = ga()) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <ConversionsSection
+ brandId={BRAND}
+ dateWindow={WEEK}
+ rangeLabel="Last 7 days"
+ source={source}
+ domain="acme-coffee.example.com"
+ canConnect
+ onConnected={vi.fn()}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const text = () => container.textContent ?? '';
+const rows = (card: number) =>
+ [...container.querySelectorAll('table')[card].querySelectorAll('tbody tr')].map((tr) =>
+ [...tr.querySelectorAll('td')].map((td) => td.textContent),
+ );
+
+describe('ConversionsSection', () => {
+ it('ranks converting pages and platform × topic for the page range', async () => {
+ getTrafficConversions.mockResolvedValue(conversions());
+ await render();
+
+ expect(getTrafficConversions).toHaveBeenCalledWith(BRAND, WEEK);
+ expect(text()).toContain('Where AI visitors convert');
+ expect(text()).toContain('Needs Google Analytics');
+ expect(text()).toContain('Ranked by key events from AI visits');
+ expect(text()).toContain('Last 7 days');
+ expect(rows(0)).toEqual([
+ ['/gifts', '50', '5', '8%', 'ChatGPT'],
+ ['/pricing', '5', '2', 'Low sample', 'Gemini'],
+ ]);
+ expect(rows(1)).toEqual([['Perplexity', 'Coffee gifts', '4', '7.5%']]);
+ });
+
+ it('adds revenue and ranks by it when the property reports purchases', async () => {
+ getTrafficConversions.mockResolvedValue(conversions({ hasRevenue: true }));
+ await render();
+ expect(text()).toContain('Ranked by revenue from AI visits');
+ expect(rows(0)[0]).toEqual(['/gifts', '50', '5', '121', '8%', 'ChatGPT']);
+ });
+
+ it('says when a thin range read the last 30 days instead', async () => {
+ getTrafficConversions.mockResolvedValue(conversions({ widened: true }));
+ await render();
+ expect(text()).toContain(
+ 'Ranked by key events from AI visits · fewer than 30 AI visits in the selected range, so this uses the last 30 days',
+ );
+ expect(text()).toContain('Last 30 days');
+ expect(text()).not.toContain('Last 7 days');
+ });
+
+ it('says when there are no conversions', async () => {
+ getTrafficConversions.mockResolvedValue(conversions({ pages: [], answers: [] }));
+ await render();
+ expect(text()).toContain('No key events from AI visitors in this range.');
+ expect(container.querySelector('table')).toBeNull();
+ });
+
+ it("says when they couldn't be read", async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getTrafficConversions.mockRejectedValue(new Error('boom'));
+ await render();
+ expect(text()).toContain("Couldn't load where AI visitors convert.");
+ });
+
+ it("shows Google Analytics' state in full instead of the cards until it has data", async () => {
+ await render(ga({ connected: false, mapped: false }));
+ expect(getTrafficConversions).not.toHaveBeenCalled();
+ expect(text()).toContain('Connect Google Analytics');
+ expect(text()).toContain('where AI visitors convert');
+ expect(container.querySelector('table')).toBeNull();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.tsx
new file mode 100644
index 000000000..b587942a1
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.tsx
@@ -0,0 +1,297 @@
+'use client';
+
+import { useEffect, useState, type ReactNode } from 'react';
+import { useTranslations } from 'next-intl';
+import { ShoppingCart } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { cn } from '@/lib/utils';
+import { formatNumber } from '@/lib/format';
+import { getPlatformName } from '@/lib/traffic-platforms';
+import { conversionRate, type ConversionFigures } from '@/lib/traffic-conversions';
+import { googleSourceStatus } from '@/lib/traffic-sources';
+import type { SourceState } from '@/lib/actions/integrations';
+import {
+ getTrafficConversions,
+ type TrafficConversions,
+ type TrafficDateWindow,
+} from '@/lib/actions/traffic';
+import { NeedsTag, SourceUnavailable } from './_source-gate';
+
+/**
+ * Where AI visitors convert (AT-014, spec §3.4b): which landing pages turn
+ * AI visitors into key events (or revenue, when the property reports
+ * purchases), and which AI platform × topic of the tracked answers citing
+ * them brings buyers. Both cards need Google Analytics: until it has data
+ * the section shows its state in full (§3.8b). A short range with fewer than
+ * 30 AI visits reads the last 30 days, and the header says so.
+ */
+
+const num = (n: number) => <span className="tabular-nums">{formatNumber(n)}</span>;
+
+/** The rate, "Low sample" below 30 AI visits (§5.4), or "—" when it isn't known. */
+function RateCell({ figures }: { figures: ConversionFigures }) {
+ const t = useTranslations('traffic.conversions');
+ const rate = conversionRate(figures);
+ if (rate.kind === 'low') {
+ return (
+ <span
+ title={t('lowSampleHint', { visits: figures.aiVisits })}
+ className="whitespace-nowrap rounded-md border border-dashed px-1.5 text-[11px] font-medium leading-4 text-muted-foreground"
+ >
+ {t('lowSample')}
+ </span>
+ );
+ }
+ if (rate.kind === 'unknown') {
+ return (
+ <span className="text-muted-foreground" title={t('rateUnknown')}>
+ —
+ </span>
+ );
+ }
+ return <span className="tabular-nums">{`${rate.pct.toLocaleString('en-US')}%`}</span>;
+}
+
+function ConversionCard({
+ title,
+ legend,
+ actions,
+ children,
+}: {
+ title: string;
+ legend: string;
+ actions?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between gap-2">
+ <CardTitle className="text-sm font-medium">{title}</CardTitle>
+ {actions}
+ </div>
+ </CardHeader>
+ <CardContent className="p-0">
+ {children}
+ <p className="px-6 py-3 text-xs text-muted-foreground">{legend}</p>
+ </CardContent>
+ </Card>
+ );
+}
+
+export function ConversionsSection({
+ brandId,
+ dateWindow,
+ rangeLabel,
+ source,
+ domain,
+ canConnect,
+ onConnected,
+ pagesActions,
+ answersActions,
+}: {
+ brandId: string;
+ dateWindow: TrafficDateWindow;
+ /** The page's own words for the range, e.g. "last 7 days". */
+ rangeLabel: string;
+ /** Google Analytics' state for the brand; null while unknown. */
+ source: SourceState | null;
+ domain: string | undefined;
+ canConnect: boolean;
+ onConnected: () => void;
+ /** Each card's Excel / CSV buttons (AT-015). */
+ pagesActions?: ReactNode;
+ answersActions?: ReactNode;
+}) {
+ const t = useTranslations('traffic.conversions');
+ const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}`;
+ // The result carries the range it answers, as the Pages section does.
+ const [loaded, setLoaded] = useState<{
+ key: string;
+ result: TrafficConversions | null;
+ } | null>(null);
+
+ const gaReady = source === null || googleSourceStatus(source) === 'connected';
+
+ useEffect(() => {
+ if (!gaReady) return;
+ let cancelled = false;
+ getTrafficConversions(brandId, dateWindow)
+ .then((result) => {
+ if (!cancelled) setLoaded({ key, result });
+ })
+ .catch((err) => {
+ // Best effort: the rest of the page doesn't depend on this section.
+ console.error('Failed to load where AI visitors convert:', err);
+ if (!cancelled) setLoaded({ key, result: null });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, dateWindow, key, gaReady]);
+
+ const current = loaded?.key === key ? loaded : null;
+ const result = current?.result ?? null;
+ const ranked = result?.hasRevenue ? t('rankedByRevenue') : t('rankedByKeyEvents');
+ const revenueColumn = result?.hasRevenue === true;
+
+ const body = (rows: ReactNode, empty: boolean) =>
+ !current ? (
+ <div className="px-6 py-4">
+ <Skeleton className="h-4 w-56" />
+ </div>
+ ) : !result ? (
+ <p className="px-6 py-4 text-sm text-muted-foreground">{t('failed')}</p>
+ ) : empty ? (
+ <p className="px-6 py-4 text-sm text-muted-foreground">{t('empty')}</p>
+ ) : (
+ rows
+ );
+
+ return (
+ <section className="space-y-3" aria-labelledby="ai-conversions-title">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <h2 id="ai-conversions-title" className="flex items-center gap-2 text-base font-semibold">
+ <ShoppingCart className="h-4 w-4 text-muted-foreground" />
+ {t('title')}
+ </h2>
+ <NeedsTag provider="google-analytics" />
+ <span className="text-xs text-muted-foreground">
+ {ranked}
+ {result?.widened && ` · ${t('widened')}`}
+ </span>
+ <Badge variant="outline" className="ml-auto text-xs">
+ {result?.widened ? t('last30Days') : rangeLabel}
+ </Badge>
+ </div>
+
+ {!gaReady && source ? (
+ <Card>
+ <CardContent className="p-0">
+ <SourceUnavailable
+ provider="google-analytics"
+ state={source}
+ domain={domain}
+ canConnect={canConnect}
+ onConnected={onConnected}
+ />
+ </CardContent>
+ </Card>
+ ) : (
+ <div
+ className={cn('grid grid-cols-1 gap-4 xl:grid-cols-2', !current && 'opacity-80')}
+ aria-busy={!current}
+ >
+ <ConversionCard
+ title={t('pages.title')}
+ legend={t('pages.legend')}
+ actions={pagesActions}
+ >
+ {body(
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-6">{t('columns.page')}</TableHead>
+ <TableHead className="text-right">{t('columns.aiVisits')}</TableHead>
+ <TableHead className="text-right">{t('columns.keyEvents')}</TableHead>
+ {revenueColumn && (
+ <TableHead className="text-right">{t('columns.revenue')}</TableHead>
+ )}
+ <TableHead className="text-right">{t('columns.rate')}</TableHead>
+ <TableHead className="pr-6">{t('columns.bestPlatform')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {result?.pages.map((row) => (
+ <TableRow key={row.page} className="hover:bg-muted/50">
+ <TableCell className="pl-6 max-w-[180px] xl:max-w-[240px]">
+ <span
+ className="font-mono text-xs text-muted-foreground line-clamp-1"
+ title={row.page}
+ >
+ {row.page}
+ </span>
+ </TableCell>
+ <TableCell className="text-right text-sm">{num(row.aiVisits)}</TableCell>
+ <TableCell className="text-right text-sm font-semibold">
+ {num(row.keyEvents)}
+ </TableCell>
+ {revenueColumn && (
+ <TableCell className="text-right text-sm">
+ {num(Math.round(row.revenue))}
+ </TableCell>
+ )}
+ <TableCell className="text-right text-sm">
+ <RateCell figures={row} />
+ </TableCell>
+ <TableCell className="pr-6 text-sm">
+ {row.bestPlatform ? getPlatformName(row.bestPlatform) : '—'}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>,
+ (result?.pages.length ?? 0) === 0,
+ )}
+ </ConversionCard>
+
+ <ConversionCard
+ title={t('answers.title')}
+ legend={t('answers.legend')}
+ actions={answersActions}
+ >
+ {body(
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-6">{t('columns.platform')}</TableHead>
+ <TableHead>{t('columns.topic')}</TableHead>
+ <TableHead className="text-right">{t('columns.keyEvents')}</TableHead>
+ {revenueColumn && (
+ <TableHead className="text-right">{t('columns.revenue')}</TableHead>
+ )}
+ <TableHead className="pr-6 text-right">{t('columns.rate')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {result?.answers.map((row) => (
+ <TableRow key={`${row.platform}|${row.topicId}`} className="hover:bg-muted/50">
+ <TableCell className="pl-6 text-sm">
+ {getPlatformName(row.platform)}
+ </TableCell>
+ <TableCell className="min-w-28 whitespace-normal text-sm">
+ {row.topic}
+ </TableCell>
+ <TableCell className="text-right text-sm font-semibold">
+ {num(row.keyEvents)}
+ </TableCell>
+ {revenueColumn && (
+ <TableCell className="text-right text-sm">
+ {num(Math.round(row.revenue))}
+ </TableCell>
+ )}
+ <TableCell className="pr-6 text-right text-sm">
+ <RateCell figures={row} />
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>,
+ (result?.answers.length ?? 0) === 0,
+ )}
+ </ConversionCard>
+ </div>
+ )}
+ </section>
+ );
+}
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 e851c0e5e..83df31d7d 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
@@ -93,8 +93,8 @@ describe('SourceUnavailable', () => {
expect(text()).toContain('Connect Google Analytics to see this');
expect(text()).toContain('Read-only access, takes about a minute.');
expect(text()).toContain(
- 'Needed for: AI share of traffic, engaged visits, key events from AI, and which valuable ' +
- 'pages get no AI traffic',
+ 'Needed for: AI share of traffic, engaged visits, key events from AI, where AI visitors ' +
+ 'convert, and which valuable pages get no AI traffic',
);
act(() => button()!.click());
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index acbcf23f8..aa5e67a77 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 { PagesCard } from './_pages-card';
+import { ConversionsSection } from './_conversions';
import { TRAFFIC_KPI_GRID, TrafficKpis } from './_kpis';
import { VisitListSourceNote } from './_visit-list-note';
import { EngagedCell, KeyEventsCell, PlatformValueNote } from './_platform-value';
@@ -585,6 +586,23 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
// whose list is now its No AI traffic tab, and reads the snippet,
// Analytics, citations and the sitemap; without Analytics it says what's
// partial rather than hiding.
+ // Where AI visitors convert (AT-014, spec §3.4b): Google Analytics' own
+ // sessions, so it shows even when the snippet saw no visit in the range; a
+ // thin range reads the last 30 days.
+ const conversionsSection = (
+ <ConversionsSection
+ brandId={brand.id}
+ dateWindow={dateWindow}
+ rangeLabel={rangeSubLabel}
+ source={sourcesFailed ? null : (sources?.ga ?? null)}
+ domain={primaryDomain}
+ canConnect={canManage}
+ onConnected={() => void loadSources()}
+ pagesActions={<TableExport exporter={exporter} section="convertingPages" />}
+ answersActions={<TableExport exporter={exporter} section="buyerAnswers" />}
+ />
+ );
+
const pagesCard = (
<PagesCard
brandId={brand.id}
@@ -656,6 +674,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
onShowWeek={datePreset === '24h' ? () => handleDatePresetChange('7d') : undefined}
/>
) : null}
+ {isEmpty && conversionsSection}
{isEmpty && pagesCard}
{!isEmpty && (
<>
@@ -804,6 +823,8 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</Card>
</div>
+ {conversionsSection}
+
{pagesCard}
{/* Recent Visit Log with filtering and pagination*/}
diff --git a/web/src/app/api/traffic/export/route.test.ts b/web/src/app/api/traffic/export/route.test.ts
index 053771000..eb896a99a 100644
--- a/web/src/app/api/traffic/export/route.test.ts
+++ b/web/src/app/api/traffic/export/route.test.ts
@@ -32,6 +32,7 @@ const loaders = vi.hoisted(() => ({
getTrafficVisitsForExport: vi.fn(),
getTrafficSources: vi.fn(),
getTrafficPages: vi.fn(),
+ getTrafficConversions: vi.fn(),
}));
vi.mock('@/lib/actions/traffic', () => loaders);
@@ -86,6 +87,15 @@ beforeEach(() => {
ga: ga(),
gsc: ga({ connected: false }),
});
+ loaders.getTrafficConversions.mockResolvedValue({
+ aiVisits: 0,
+ hasRevenue: false,
+ widened: false,
+ pageCount: 0,
+ answerCount: 0,
+ pages: [],
+ answers: [],
+ });
loaders.getTrafficPages.mockResolvedValue({
counts: { noAiTraffic: 0, citedNotClicked: 0, trafficNoPrompt: 0, all: 0 },
rows: [],
@@ -123,6 +133,8 @@ describe('GET /api/traffic/export', () => {
'Trend',
'Platforms',
'Top landing pages',
+ 'Top converting pages',
+ 'Answers that bring buyers',
'Pages by status',
'Visits',
]);
@@ -157,6 +169,8 @@ describe('GET /api/traffic/export', () => {
'trend.csv',
'platforms.csv',
'top-landing-pages.csv',
+ 'top-converting-pages.csv',
+ 'answers-that-bring-buyers.csv',
'pages-by-status.csv',
'visits.csv',
]);
@@ -202,6 +216,19 @@ describe('GET /api/traffic/export', () => {
expect(loaders.getTrafficSources).not.toHaveBeenCalled();
});
+ it('reads every row of where AI visitors convert for its tables (AT-014)', async () => {
+ const res = await get({ format: 'csv', section: 'buyerAnswers' });
+
+ const csv = await csvOf(res);
+ expect(csv).toEqual({ bom: true, text: 'Note\nNo key events from AI visitors in this range' });
+ expect(loaders.getTrafficConversions).toHaveBeenCalledWith(
+ BRAND,
+ { dateFrom: undefined, dateTo: undefined },
+ { limit: TRAFFIC_EXPORT_MAX_ROWS },
+ );
+ expect(loaders.getTrafficPages).not.toHaveBeenCalled();
+ });
+
it('refuses more visits than an export built on request should hold', async () => {
loaders.getTrafficVisitsForExport.mockResolvedValue(null);
const res = await get({ format: 'xlsx' });
diff --git a/web/src/app/api/traffic/export/route.ts b/web/src/app/api/traffic/export/route.ts
index 2c9d7c5a8..8164a25ff 100644
--- a/web/src/app/api/traffic/export/route.ts
+++ b/web/src/app/api/traffic/export/route.ts
@@ -5,6 +5,7 @@ import { z } from 'zod';
import messages from '../../../../../messages/en.json';
import { createClient } from '@/lib/supabase/server';
import {
+ getTrafficConversions,
getTrafficPages,
getTrafficSources,
getTrafficSummary,
@@ -90,7 +91,7 @@ export async function GET(req: Request) {
const wholePage = !q.section;
try {
- const [summary, trend, visits, sources, pageStatus] = await Promise.all([
+ const [summary, trend, visits, sources, pageStatus, conversions] = await Promise.all([
needs('kpis', 'platforms', 'pages')
? getTrafficSummary(q.brandId, window, { topPages: Number.MAX_SAFE_INTEGER })
: undefined,
@@ -109,6 +110,10 @@ export async function GET(req: Request) {
needs('pageStatus')
? getTrafficPages(q.brandId, window, { tab: 'all', limit: TRAFFIC_EXPORT_MAX_ROWS })
: undefined,
+ // Every row of where AI visitors convert, over the window the page reads (AT-014).
+ needs('convertingPages', 'buyerAnswers')
+ ? getTrafficConversions(q.brandId, window, { limit: TRAFFIC_EXPORT_MAX_ROWS })
+ : undefined,
]);
// Larger than an export built on request should be (spec §3.9).
if (visits === null) return Response.json({ error: 'too_large' }, { status: 413 });
@@ -128,6 +133,7 @@ export async function GET(req: Request) {
trend,
visits: visits ?? undefined,
pageStatus,
+ conversions,
sources,
};
diff --git a/web/src/lib/actions/traffic-conversions.test.ts b/web/src/lib/actions/traffic-conversions.test.ts
new file mode 100644
index 000000000..fbff85b18
--- /dev/null
+++ b/web/src/lib/actions/traffic-conversions.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * AT-014 (spec §3.4b): where AI visitors convert reads ai_traffic_conversions
+ * (00179) over the page's days, and a short range with fewer than 30 AI
+ * visits reads the last 30 days instead.
+ */
+
+const rpc = vi.fn();
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ rpc }),
+}));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
+
+import { getTrafficConversions } from './traffic';
+
+const answer = (sessions: number) => ({
+ data: {
+ sessions,
+ has_revenue: true,
+ page_count: 1,
+ answer_count: 1,
+ pages: [
+ {
+ page: '/gifts',
+ sessions: 50,
+ key_events: 5,
+ key_event_sessions: 4,
+ transactions: 1,
+ revenue: '120.5',
+ best_platform: 'chatgpt.com',
+ },
+ ],
+ answers: [
+ {
+ platform: 'chatgpt.com',
+ topic_id: 't1',
+ topic: 'Coffee gifts',
+ pages: 1,
+ sessions: 40,
+ key_events: 4,
+ key_event_sessions: 3,
+ revenue: 120.5,
+ },
+ ],
+ },
+ error: null,
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-18T12:30:00.000Z'));
+ rpc.mockReset();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('getTrafficConversions', () => {
+ it("reads the range's days and turns the rows into the cards' shape", async () => {
+ rpc.mockResolvedValue(answer(75));
+ const result = await getTrafficConversions('b1', { dateFrom: '2026-10-11T12:30:00.000Z' });
+
+ expect(rpc).toHaveBeenCalledTimes(1);
+ expect(rpc).toHaveBeenCalledWith('ai_traffic_conversions', {
+ p_brand_id: 'b1',
+ p_since: '2026-10-11',
+ p_until: '2026-10-18',
+ p_limit: 10,
+ });
+ expect(result).toEqual({
+ aiVisits: 75,
+ hasRevenue: true,
+ widened: false,
+ pageCount: 1,
+ answerCount: 1,
+ pages: [
+ {
+ page: '/gifts',
+ aiVisits: 50,
+ keyEvents: 5,
+ keyEventSessions: 4,
+ transactions: 1,
+ revenue: 120.5,
+ bestPlatform: 'chatgpt.com',
+ },
+ ],
+ answers: [
+ {
+ platform: 'chatgpt.com',
+ topicId: 't1',
+ topic: 'Coffee gifts',
+ pages: 1,
+ aiVisits: 40,
+ keyEvents: 4,
+ keyEventSessions: 3,
+ revenue: 120.5,
+ },
+ ],
+ });
+ });
+
+ it('reads the last 30 days when a short range has fewer than 30 AI visits', async () => {
+ rpc.mockResolvedValueOnce(answer(4)).mockResolvedValueOnce(answer(64));
+ const result = await getTrafficConversions(
+ 'b1',
+ { dateFrom: '2026-10-17T12:30:00.000Z' },
+ { limit: 100 },
+ );
+
+ expect(rpc).toHaveBeenLastCalledWith('ai_traffic_conversions', {
+ p_brand_id: 'b1',
+ p_since: '2026-09-18',
+ p_until: '2026-10-18',
+ p_limit: 100,
+ });
+ expect(result).toMatchObject({ widened: true, aiVisits: 64 });
+ });
+
+ it('keeps all time as it is, and gives empty cards for a brand outside the organization', async () => {
+ rpc.mockResolvedValue({ data: null, error: null });
+ expect(await getTrafficConversions('b1', undefined)).toEqual({
+ aiVisits: 0,
+ hasRevenue: false,
+ widened: false,
+ pageCount: 0,
+ answerCount: 0,
+ pages: [],
+ answers: [],
+ });
+ expect(rpc).toHaveBeenCalledTimes(1);
+ expect(rpc.mock.calls[0][1]).toMatchObject({ p_since: null, p_until: null });
+ });
+
+ it('fails loudly when the read fails', async () => {
+ rpc.mockResolvedValue({ data: null, error: { message: 'boom' } });
+ await expect(getTrafficConversions('b1', undefined)).rejects.toThrow('boom');
+ });
+});
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index 2e3aff46e..fd78e5b5c 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -5,6 +5,7 @@ import { API_BASE_URL } from '@/config/api';
import { TRAFFIC_PAGE_SIZE, countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';
import { expandDateToEndOfDay, utcDay } from '@/lib/dates';
import { isHourlyWindow, listUtcHours, utcHourKey } from '@/lib/traffic-buckets';
+import { CONVERSIONS_FALLBACK_DAYS, widensToLast30Days } from '@/lib/traffic-conversions';
import { getSuggestionSourceStates, type SourceState } from '@/lib/actions/integrations';
export interface TrafficDateWindow {
@@ -693,6 +694,123 @@ export async function suggestPagePrompts(
return res.json();
}
+/** A landing page AI visitors converted on (AT-014). */
+export interface ConvertingPage {
+ page: string;
+ /** Analytics' AI-referred sessions on the page. */
+ aiVisits: number;
+ keyEvents: number;
+ /** Sessions with at least one key event: the rate is this over aiVisits. */
+ keyEventSessions: number;
+ transactions: number;
+ revenue: number;
+ /** The platform whose visitors converted most on the page. */
+ bestPlatform: string | null;
+}
+
+/** An AI platform × topic, over the pages the topic's tracked answers cite (AT-014). */
+export interface BuyerAnswer {
+ platform: string;
+ topicId: string;
+ topic: string;
+ pages: number;
+ aiVisits: number;
+ keyEvents: number;
+ keyEventSessions: number;
+ revenue: number;
+}
+
+export interface TrafficConversions {
+ /** All AI sessions Analytics counted in the window read. */
+ aiVisits: number;
+ /** The property reports purchases: the cards rank by revenue. */
+ hasRevenue: boolean;
+ /** The range had fewer than 30 AI visits, so the last 30 days were read instead. */
+ widened: boolean;
+ pageCount: number;
+ answerCount: number;
+ pages: ConvertingPage[];
+ answers: BuyerAnswer[];
+}
+
+async function readConversions(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ brandId: string,
+ since: string | null,
+ until: string | null,
+ limit: number,
+): Promise<Omit<TrafficConversions, 'widened'>> {
+ const { data, error } = await supabase.rpc('ai_traffic_conversions', {
+ p_brand_id: brandId,
+ p_since: since,
+ p_until: until,
+ p_limit: limit,
+ });
+ if (error) throw new Error(error.message);
+ const raw = (data ?? {}) as Record<string, unknown>;
+ const n = (v: unknown) => Number(v) || 0;
+ const list = (v: unknown) => (Array.isArray(v) ? (v as Record<string, unknown>[]) : []);
+ return {
+ aiVisits: n(raw.sessions),
+ hasRevenue: raw.has_revenue === true,
+ pageCount: n(raw.page_count),
+ answerCount: n(raw.answer_count),
+ pages: list(raw.pages).map((r) => ({
+ page: String(r.page),
+ aiVisits: n(r.sessions),
+ keyEvents: n(r.key_events),
+ keyEventSessions: n(r.key_event_sessions),
+ transactions: n(r.transactions),
+ revenue: n(r.revenue),
+ bestPlatform: typeof r.best_platform === 'string' ? r.best_platform : null,
+ })),
+ answers: list(raw.answers).map((r) => ({
+ platform: String(r.platform),
+ topicId: String(r.topic_id),
+ topic: String(r.topic),
+ pages: n(r.pages),
+ aiVisits: n(r.sessions),
+ keyEvents: n(r.key_events),
+ keyEventSessions: n(r.key_event_sessions),
+ revenue: n(r.revenue),
+ })),
+ };
+}
+
+/**
+ * Where AI visitors convert (AT-014, spec §3.4b; 00179): the landing pages
+ * whose AI-referred sessions convert, and AI platform × topic of the tracked
+ * answers citing them, from Analytics' days in the page's range. A short
+ * range with fewer than 30 AI visits reads the last 30 days instead and says
+ * so (spec §3.01).
+ */
+export async function getTrafficConversions(
+ brandId: string,
+ window: TrafficDateWindow | undefined,
+ { limit = 10 }: { limit?: number } = {},
+): Promise<TrafficConversions> {
+ const supabase = await createClient();
+ const { from, to } = resolveTrafficWindow(window);
+ const inRange = await readConversions(
+ supabase,
+ brandId,
+ utcDay(from) ?? null,
+ utcDay(to) ?? null,
+ limit,
+ );
+ if (!widensToLast30Days({ from, to }, inRange.aiVisits)) return { ...inRange, widened: false };
+
+ const now = Date.now();
+ const last30 = await readConversions(
+ supabase,
+ brandId,
+ new Date(now - CONVERSIONS_FALLBACK_DAYS * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
+ new Date(now).toISOString().slice(0, 10),
+ limit,
+ );
+ return { ...last30, widened: true };
+}
+
/** Analytics' engagement figures for one group of sessions (AT-005). */
export interface TrafficEngagement {
sessions: number;
diff --git a/web/src/lib/traffic-conversions.test.ts b/web/src/lib/traffic-conversions.test.ts
new file mode 100644
index 000000000..273e244e8
--- /dev/null
+++ b/web/src/lib/traffic-conversions.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+import { conversionRate, widensToLast30Days } from './traffic-conversions';
+
+/** Where AI visitors convert (AT-014): its rate and its 30-day fallback. */
+
+describe('conversionRate', () => {
+ it("is Analytics' session key event rate, from 30 AI visits", () => {
+ expect(conversionRate({ aiVisits: 40, keyEvents: 6, keyEventSessions: 5 })).toEqual({
+ kind: 'rate',
+ pct: 12.5,
+ });
+ expect(conversionRate({ aiVisits: 30, keyEvents: 0, keyEventSessions: 0 })).toEqual({
+ kind: 'rate',
+ pct: 0,
+ });
+ });
+
+ it('says Low sample below 30 AI visits (§5.4)', () => {
+ expect(conversionRate({ aiVisits: 29, keyEvents: 9, keyEventSessions: 9 })).toEqual({
+ kind: 'low',
+ });
+ });
+
+ it('has no rate for key events synced before the session rate was read', () => {
+ expect(conversionRate({ aiVisits: 80, keyEvents: 4, keyEventSessions: 0 })).toEqual({
+ kind: 'unknown',
+ });
+ });
+});
+
+describe('widensToLast30Days', () => {
+ const NOW = '2026-10-18T12:00:00.000Z';
+ const ago = (days: number) => new Date(Date.parse(NOW) - days * 86_400_000).toISOString();
+
+ it('widens a short range with fewer than 30 AI visits', () => {
+ expect(widensToLast30Days({ from: ago(1), to: NOW }, 4)).toBe(true);
+ expect(widensToLast30Days({ from: ago(7), to: NOW }, 29)).toBe(true);
+ });
+
+ it('keeps a range with enough visits, a 30-day or longer one, and all time', () => {
+ expect(widensToLast30Days({ from: ago(7), to: NOW }, 30)).toBe(false);
+ expect(widensToLast30Days({ from: ago(30), to: NOW }, 2)).toBe(false);
+ expect(widensToLast30Days({ from: ago(90), to: NOW }, 2)).toBe(false);
+ expect(widensToLast30Days({ to: NOW }, 0)).toBe(false);
+ });
+});
diff --git a/web/src/lib/traffic-conversions.ts b/web/src/lib/traffic-conversions.ts
new file mode 100644
index 000000000..8ff5c9537
--- /dev/null
+++ b/web/src/lib/traffic-conversions.ts
@@ -0,0 +1,45 @@
+/**
+ * Where AI visitors convert (AT-014, spec §3.4b): the rules its two cards and
+ * their export share. Pure, so the page and the export say the same thing.
+ */
+
+import { LOW_SAMPLE_VISITS } from '@/lib/traffic-change';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+/** The window the section falls back to when the range is too thin (spec §3.01). */
+export const CONVERSIONS_FALLBACK_DAYS = 30;
+
+/** A row's Analytics figures: its AI sessions and those with a key event. */
+export interface ConversionFigures {
+ aiVisits: number;
+ keyEvents: number;
+ keyEventSessions: number;
+}
+
+export type ConversionRate =
+ | { kind: 'rate'; pct: number }
+ /** Below 30 AI visits a rate would mislead (§5.4). */
+ | { kind: 'low' }
+ /** Key events from sessions synced before Analytics' session rate was read (00177). */
+ | { kind: 'unknown' };
+
+/** The share of AI sessions with a key event, as GA4's session key event rate. */
+export function conversionRate(f: ConversionFigures): ConversionRate {
+ if (f.aiVisits < LOW_SAMPLE_VISITS) return { kind: 'low' };
+ if (f.keyEvents > 0 && f.keyEventSessions === 0) return { kind: 'unknown' };
+ return { kind: 'rate', pct: Math.round((f.keyEventSessions / f.aiVisits) * 1000) / 10 };
+}
+
+/**
+ * Whether a range is too thin to rank conversions on: shorter than the
+ * fallback window and with fewer than 30 AI visits. All time and the long
+ * ranges keep their own window, however few visits they have.
+ */
+export function widensToLast30Days(
+ window: { from?: string; to?: string },
+ aiVisits: number,
+): boolean {
+ if (!window.from || aiVisits >= LOW_SAMPLE_VISITS) return false;
+ const to = window.to ? Date.parse(window.to) : Date.now();
+ return to - Date.parse(window.from) < CONVERSIONS_FALLBACK_DAYS * DAY_MS - 60 * 60 * 1000;
+}
diff --git a/web/src/lib/traffic-export.test.ts b/web/src/lib/traffic-export.test.ts
index 9971cfe80..3eb19751a 100644
--- a/web/src/lib/traffic-export.test.ts
+++ b/web/src/lib/traffic-export.test.ts
@@ -2,6 +2,7 @@ import { createTranslator } from 'next-intl';
import { describe, expect, it } from 'vitest';
import messages from '../../messages/en.json';
import type { SourceState } from '@/lib/actions/integrations';
+import type { TrafficConversions } from '@/lib/actions/traffic';
import {
BYTE_ORDER_MARK,
TRAFFIC_EXPORT_SECTIONS,
@@ -247,6 +248,114 @@ describe('trafficTable', () => {
});
});
+describe('where AI visitors convert (AT-014)', () => {
+ const conversions = (over: Partial<TrafficConversions> = {}): TrafficConversions => ({
+ aiVisits: 64,
+ hasRevenue: false,
+ widened: false,
+ pageCount: 2,
+ answerCount: 1,
+ pages: [
+ {
+ page: '/gifts',
+ aiVisits: 50,
+ keyEvents: 5,
+ keyEventSessions: 4,
+ transactions: 1,
+ revenue: 120.5,
+ bestPlatform: 'chatgpt.com',
+ },
+ {
+ page: '/pricing',
+ aiVisits: 5,
+ keyEvents: 2,
+ keyEventSessions: 2,
+ transactions: 0,
+ revenue: 0,
+ bestPlatform: null,
+ },
+ ],
+ answers: [
+ {
+ platform: 'perplexity.ai',
+ topicId: 't1',
+ topic: 'Coffee gifts',
+ pages: 2,
+ aiVisits: 40,
+ keyEvents: 4,
+ keyEventSessions: 3,
+ revenue: 0,
+ },
+ ],
+ ...over,
+ });
+
+ it('gives every converting page with its rate, or why there is none', () => {
+ const table = trafficTable('convertingPages', data({ conversions: conversions() }), label);
+ expect(table.headers).toEqual([
+ 'Page',
+ 'AI visits',
+ 'Key events',
+ 'Revenue',
+ 'Rate (%)',
+ 'Best platform',
+ 'Note',
+ ]);
+ expect(table.rows).toEqual([
+ ['/gifts', 50, 5, null, 8, 'ChatGPT', null],
+ ['/pricing', 5, 2, null, null, null, 'Low sample: fewer than 30 AI visits'],
+ ]);
+ // Revenue only when the property reports purchases.
+ const sold = trafficTable(
+ 'convertingPages',
+ data({ conversions: conversions({ hasRevenue: true }) }),
+ label,
+ );
+ expect(sold.rows[0][3]).toBe(120.5);
+ });
+
+ it('gives each platform × topic, and says when the last 30 days were read', () => {
+ const table = trafficTable(
+ 'buyerAnswers',
+ data({ conversions: conversions({ widened: true }) }),
+ label,
+ );
+ expect(table.headers).toEqual([
+ 'Platform',
+ 'Topic',
+ 'Cited pages',
+ 'AI visits',
+ 'Key events',
+ 'Revenue',
+ 'Rate (%)',
+ 'Note',
+ ]);
+ expect(table.rows).toEqual([
+ ['Perplexity', 'Coffee gifts', 2, 40, 4, null, 7.5, null],
+ [
+ 'Last 30 days: the selected range has fewer than 30 AI visits',
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ],
+ ]);
+ });
+
+ it('says there are no conversions, never an empty sheet', () => {
+ const none = conversions({ pages: [], answers: [] });
+ expect(trafficTable('convertingPages', data({ conversions: none }), label).rows).toEqual([
+ ['No key events from AI visitors in this range'],
+ ]);
+ expect(trafficTable('buyerAnswers', data({ conversions: null }), label).rows).toEqual([
+ ['No key events from AI visitors in this range'],
+ ]);
+ });
+});
+
describe('filtersTable', () => {
it('records the range, the filters, the sources and when', () => {
const table = filtersTable(
@@ -277,6 +386,8 @@ describe('trafficWorkbook', () => {
'Trend',
'Platforms',
'Top landing pages',
+ 'Top converting pages',
+ 'Answers that bring buyers',
'Pages by status',
'Visits',
]);
diff --git a/web/src/lib/traffic-export.ts b/web/src/lib/traffic-export.ts
index 03fa16deb..2ce975889 100644
--- a/web/src/lib/traffic-export.ts
+++ b/web/src/lib/traffic-export.ts
@@ -10,6 +10,7 @@
import type { Sheet } from 'write-excel-file/node';
import type {
+ TrafficConversions,
TrafficLog,
TrafficPages,
TrafficSources,
@@ -19,6 +20,7 @@ import type {
import { csvLine } from '@/lib/csv';
import { getPlatformName } from '@/lib/traffic-platforms';
import { pageStatuses } from '@/lib/traffic-pages';
+import { conversionRate } from '@/lib/traffic-conversions';
import { visitChange } from '@/lib/traffic-change';
import {
googleSourceStatus,
@@ -32,6 +34,8 @@ export const TRAFFIC_EXPORT_SECTIONS = [
'trend',
'platforms',
'pages',
+ 'convertingPages',
+ 'buyerAnswers',
'pageStatus',
'visits',
] as const;
@@ -39,7 +43,14 @@ export const TRAFFIC_EXPORT_SECTIONS = [
export type TrafficExportSection = (typeof TRAFFIC_EXPORT_SECTIONS)[number];
/** The tables that carry their own Excel / CSV buttons, as in the mockup. */
-export const TRAFFIC_TABLE_SECTIONS = ['platforms', 'pages', 'pageStatus', 'visits'] as const;
+export const TRAFFIC_TABLE_SECTIONS = [
+ 'platforms',
+ 'pages',
+ 'convertingPages',
+ 'buyerAnswers',
+ 'pageStatus',
+ 'visits',
+] as const;
/** Beyond this many visits an export would take too long to build on request. */
export const TRAFFIC_EXPORT_MAX_ROWS = 100_000;
@@ -62,6 +73,8 @@ export interface TrafficExportData {
visits?: TrafficLog[];
/** Every page of the Pages section, with the lists it is on (AT-006). */
pageStatus?: TrafficPages | null;
+ /** Where AI visitors convert, every row (AT-014). */
+ conversions?: TrafficConversions | null;
sources?: TrafficSources | null;
}
@@ -229,6 +242,89 @@ function pageStatus(data: TrafficExportData, label: ExportLabel): ExportTable {
};
}
+/** A row's rate as a number, or why the page shows none (§5.4). */
+function rateCells(
+ figures: { aiVisits: number; keyEvents: number; keyEventSessions: number },
+ label: ExportLabel,
+): { pct: number | null; note: string | null } {
+ const rate = conversionRate(figures);
+ if (rate.kind === 'rate') return { pct: rate.pct, note: null };
+ return { pct: null, note: rate.kind === 'low' ? label('notes.conversionLowSample') : null };
+}
+
+/**
+ * Where AI visitors convert (AT-014): its two tables, every row, with a row
+ * saying when a thin range read the last 30 days, as the page says.
+ */
+function conversionsTable(
+ data: TrafficExportData,
+ label: ExportLabel,
+ build: (c: TrafficConversions) => ExportTable,
+): ExportTable {
+ const c = data.conversions;
+ const table = c ? build(c) : null;
+ if (!c || !table || table.rows.length === 0) {
+ return { headers: [label('columns.note')], rows: [[label('notes.noConversions')]] };
+ }
+ if (!c.widened) return table;
+ const filler = table.headers.slice(1).map(() => null);
+ return { ...table, rows: [...table.rows, [label('notes.lastThirtyDays'), ...filler]] };
+}
+
+function convertingPages(data: TrafficExportData, label: ExportLabel): ExportTable {
+ return conversionsTable(data, label, (c) => ({
+ headers: [
+ label('columns.page'),
+ label('columns.aiVisits'),
+ label('columns.keyEvents'),
+ label('columns.revenue'),
+ label('columns.conversionRate'),
+ label('columns.bestPlatform'),
+ label('columns.note'),
+ ],
+ rows: c.pages.map((row) => {
+ const rate = rateCells(row, label);
+ return [
+ row.page,
+ row.aiVisits,
+ row.keyEvents,
+ c.hasRevenue ? row.revenue : null,
+ rate.pct,
+ row.bestPlatform ? getPlatformName(row.bestPlatform) : null,
+ rate.note,
+ ];
+ }),
+ }));
+}
+
+function buyerAnswers(data: TrafficExportData, label: ExportLabel): ExportTable {
+ return conversionsTable(data, label, (c) => ({
+ headers: [
+ label('columns.platform'),
+ label('columns.topic'),
+ label('columns.citedPages'),
+ label('columns.aiVisits'),
+ label('columns.keyEvents'),
+ label('columns.revenue'),
+ label('columns.conversionRate'),
+ label('columns.note'),
+ ],
+ rows: c.answers.map((row) => {
+ const rate = rateCells(row, label);
+ return [
+ getPlatformName(row.platform),
+ row.topic,
+ row.pages,
+ row.aiVisits,
+ row.keyEvents,
+ c.hasRevenue ? row.revenue : null,
+ rate.pct,
+ rate.note,
+ ];
+ }),
+ }));
+}
+
function visits(data: TrafficExportData, label: ExportLabel): ExportTable {
return {
headers: [
@@ -267,6 +363,10 @@ export function trafficTable(
return platforms(data, label);
case 'pages':
return pages(data, label);
+ case 'convertingPages':
+ return convertingPages(data, label);
+ case 'buyerAnswers':
+ return buyerAnswers(data, label);
case 'pageStatus':
return pageStatus(data, label);
case 'visits':
diff --git a/web/src/lib/traffic-sources.test.ts b/web/src/lib/traffic-sources.test.ts
index af7696f07..0e2774b27 100644
--- a/web/src/lib/traffic-sources.test.ts
+++ b/web/src/lib/traffic-sources.test.ts
@@ -64,6 +64,7 @@ describe('sectionsNeeding', () => {
'aiShare',
'engagedVisits',
'keyEvents',
+ 'conversions',
'pageValue',
]);
expect(sectionsNeeding('google-search-console')).toEqual(['googleClicks']);
diff --git a/web/src/lib/traffic-sources.ts b/web/src/lib/traffic-sources.ts
index d049f15f7..70b15ef07 100644
--- a/web/src/lib/traffic-sources.ts
+++ b/web/src/lib/traffic-sources.ts
@@ -84,6 +84,7 @@ export const TRAFFIC_SECTION_SOURCES = {
engagedVisits: 'google-analytics',
keyEvents: 'google-analytics',
googleClicks: 'google-search-console',
+ conversions: 'google-analytics',
pageValue: 'google-analytics',
} as const satisfies Record<string, IntegrationProvider>;
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 3d078dc50..c0f607ae1 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -2861,6 +2861,15 @@ export type Database = {
}
Returns: Json
}
+ ai_traffic_conversions: {
+ Args: {
+ p_brand_id: string
+ p_limit?: number | null
+ p_since: string | null
+ p_until: string | null
+ }
+ Returns: Json
+ }
ai_visibility_aggregates: {
Args: {
p_brand_id: string