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): add the Pages section with No AI traffic, Cited not clicked and Traffic no prompt tabs (#1170)
Cihanfae319322a16
diff --git a/server/src/lib/page-paths-sql.test.js b/server/src/lib/page-paths-sql.test.jsnew file mode 100644index 000000000..42e1e9f2a--- /dev/null+++ b/server/src/lib/page-paths-sql.test.js@@ -0,0 +1,28 @@+import { readFileSync } from 'fs';+import { describe, expect, it } from 'vitest';+import { EXCLUDED_SEGMENTS, isExcludedPath } from './page-paths.js';++/**+ * The AI Traffic Pages section (00178, AT-006) leaves out the same pages as+ * the nightly page detection: its SQL carries a copy of EXCLUDED_SEGMENTS,+ * which must not drift from this list.+ */++const migration = readFileSync(+ new URL('../../../supabase/migrations/00178_ai_traffic_pages.sql', import.meta.url),+ 'utf8',+);+const sqlList = migration.match(/seg = any \(array\[([\s\S]*?)\]\)/)?.[1] ?? '';+const sqlSegments = [...sqlList.matchAll(/'([^']+)'/g)].map((m) => m[1]);++describe("00178's excluded path segments", () => {+ it('are exactly the nightly detection’s', () => {+ expect(sqlSegments.length).toBeGreaterThan(30);+ expect(new Set(sqlSegments)).toEqual(new Set(EXCLUDED_SEGMENTS));+ expect(sqlSegments).toHaveLength(EXCLUDED_SEGMENTS.size);+ });++ it('each exclude a page on its own, as isExcludedPath does', () => {+ for (const segment of sqlSegments) expect(isExcludedPath(`/${segment}`), segment).toBe(true);+ });+});diff --git a/server/src/lib/page-paths.js b/server/src/lib/page-paths.jsindex bfa0d699f..af9f19f83 100644--- a/server/src/lib/page-paths.js+++ b/server/src/lib/page-paths.js@@ -21,7 +21,7 @@* the list with findings nobody will act on.*/-const EXCLUDED_SEGMENTS = new Set([+export const EXCLUDED_SEGMENTS = new Set([// Transactional'checkout','cart',diff --git a/supabase/migrations/00178_ai_traffic_pages.sql b/supabase/migrations/00178_ai_traffic_pages.sqlnew file mode 100644index 000000000..74f4999a7--- /dev/null+++ b/supabase/migrations/00178_ai_traffic_pages.sql@@ -0,0 +1,318 @@+-- ============================================================================+-- 00178: the AI Traffic page's Pages section and its status tabs (AT-006)+-- ============================================================================+-- Spec §3.5, "which answers send visitors": one table of the brand's pages+-- for the page's range, joining AI visits with how often tracked AI answers+-- cite the page and the prompts that point to it, with three work lists:+--+-- * No AI traffic — pages with traffic in Google Analytics or in the+-- site's sitemap (site_pages) that got no AI visit, ranked by value:+-- revenue, key events, then sessions and engagement. Replaces "Pages AI+-- engines aren't sending traffic to", in the page's own window (F2).+-- * Cited, not clicked — cited at least 20 times in the range, no AI visit.+-- * Traffic, no prompt — AI visits, but no tracked prompt's answer cited+-- the page in the range.+--+-- Pages are keyed by lower(normalize_page_path(...)), so a snippet URL, an+-- Analytics landing page, a cited URL and a sitemap URL name one page. AI+-- visits are ai_traffic_merged's (00176): the snippet on days it was active,+-- Analytics on the others, never summed. Checkout, login, legal and similar+-- pages are left out, as the nightly page detection leaves them out+-- (server/src/lib/page-paths.js; a server test keeps the two lists equal).+--+-- citation_urls has no member select policy, so both functions run as their+-- owner, after checking the caller belongs to the brand's organization; a+-- caller from elsewhere gets nothing.++-- ─── Citations of the brand's own pages ─────────────────────────────────────++create or replace function public.ai_traffic_page_citations(+ p_brand_id uuid,+ p_since date,+ p_until date+)+returns table (page_key text, page text, citations bigint)+language plpgsql+stable+security definer+set search_path to 'public'+as $$+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;+ end if;++ return query+ with own_domains as (+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain+ from public.brand_domains bd+ where bd.brand_id = p_brand_id+ )+ select+ lower(public.normalize_page_path(cu.url)),+ min(public.normalize_page_path(cu.url)),+ sum(d.citations)::bigint+ from public.citation_url_daily d+ join public.citation_urls cu on cu.id = d.url_id+ where d.brand_id = p_brand_id+ and d.day >= coalesce(p_since, '-infinity'::date)+ and d.day <= coalesce(p_until, 'infinity'::date)+ and cu.domain in (select domain from own_domains)+ group by 1;+end;+$$;++revoke all on function public.ai_traffic_page_citations(uuid, date, date) from public, anon;+grant execute on function public.ai_traffic_page_citations(uuid, date, date)+ to authenticated, service_role;++comment on function public.ai_traffic_page_citations(uuid, date, date) is+ 'AI Traffic (AT-006): how often tracked AI answers cited each of the brand''s own pages between two days, keyed by lower(normalize_page_path). Security definer with an organization check: citation_urls has no member select policy.';++-- ─── The Pages section ──────────────────────────────────────────────────────++create or replace function public.ai_traffic_pages(+ p_brand_id uuid,+ p_from timestamptz,+ p_to timestamptz,+ p_tab text default 'all',+ p_limit integer default 50,+ p_offset integer default 0+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+as $$+declare+ v_since date := (p_from at time zone 'utc')::date;+ v_until date := coalesce((p_to at time zone 'utc')::date, (now() at time zone 'utc')::date);+ -- The 24-hour range reads the snippet alone, as the rest of the page does:+ -- Analytics has no hours (00176).+ v_hourly boolean := p_from is not null and coalesce(p_to, now()) - p_from <= interval '25 hours';+ v_result jsonb;+begin+ if p_tab not in ('all', 'no_ai_traffic', 'cited_not_clicked', 'traffic_no_prompt') then+ raise exception 'unknown tab %', p_tab;+ end if;+ 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+ -- AI visits per page, day by day from the snippet or Analytics (00176).+ ai as (+ select lower(e->>'page') as page_key, min(e->>'page') as page, sum((e->>'visits')::bigint) as visits+ from jsonb_array_elements(+ public.ai_traffic_merged(p_brand_id, p_from, p_to, true, not v_hourly) -> 'pages'+ ) e+ group by 1+ ),+ -- Days the snippet was active, over the whole UTC day (00176's rule).+ snippet_days as (+ select distinct (l.created_at at time zone 'utc')::date as day+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= coalesce(v_since::timestamp at time zone 'utc', '-infinity'::timestamptz)+ and l.created_at < (v_until + 1)::timestamp at time zone 'utc'+ ),+ -- Which assistants sent them, counted as the AI visits are: the snippet,+ -- and Analytics on days without it (never within 24 hours).+ platform_visits as (+ select lower(public.normalize_page_path(l.url)) as page_key,+ coalesce(nullif(l.source_platform, ''), 'unknown') as platform,+ count(*)::bigint as visits+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= coalesce(p_from, '-infinity'::timestamptz)+ and (p_to is null or l.created_at <= p_to)+ group by 1, 2+ union all+ select lower(public.normalize_page_path(g.landing_page)),+ coalesce(g.platform, g.source),+ sum(g.sessions)::bigint+ from public.ga_ai_traffic_stats g+ where not v_hourly+ and g.brand_id = p_brand_id+ and g.landing_page <> ''+ and g.sessions > 0+ and g.date >= coalesce(v_since, '-infinity'::date)+ and g.date <= v_until+ and not exists (select 1 from snippet_days s where s.day = g.date)+ group by 1, 2+ ),+ platforms as (+ select page_key, (array_agg(platform order by visits desc, platform))[1:3] as platforms+ from (select page_key, platform, sum(visits) as visits from platform_visits group by 1, 2) t+ group by 1+ ),+ -- Key events in AI sessions: only Analytics has them, and it has no hours.+ ai_key_events as (+ select lower(public.normalize_page_path(g.landing_page)) as page_key, sum(g.key_events)::bigint as key_events+ from public.ga_ai_traffic_stats g+ where not v_hourly+ and g.brand_id = p_brand_id+ and g.landing_page <> ''+ and g.date >= coalesce(v_since, '-infinity'::date)+ and g.date <= v_until+ group by 1+ ),+ -- Every channel's traffic, for the No AI traffic list's value.+ traffic as (+ select+ lower(public.normalize_page_path(gps.landing_page)) as page_key,+ min(public.normalize_page_path(gps.landing_page)) as page,+ sum(gps.sessions)::bigint as sessions,+ sum(gps.engaged_sessions)::bigint as engaged_sessions,+ sum(gps.key_events)::bigint as key_events,+ sum(gps.transactions)::bigint as transactions,+ sum(gps.purchase_revenue) as revenue,+ sum(gps.engagement_duration_seconds)::bigint as engagement_seconds+ from public.ga_page_stats gps+ where gps.brand_id = p_brand_id+ and gps.date >= coalesce(v_since, '-infinity'::date)+ and gps.date <= v_until+ group by 1+ ),+ cited as (+ select c.page_key, c.page, c.citations+ from public.ai_traffic_page_citations(p_brand_id, v_since, v_until) c+ ),+ -- Prompts pointing to the page: an active prompt's target URL.+ targeted as (+ select lower(public.normalize_page_path(ptu.url)) as page_key,+ count(distinct ptu.prompt_id)::bigint as prompts+ from public.prompt_target_urls ptu+ join public.prompts p on p.id = ptu.prompt_id and p.is_active+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where ps.brand_id = p_brand_id+ group by 1+ ),+ in_sitemap as (+ select distinct lower(public.normalize_page_path(sp.url)) as page_key,+ public.normalize_page_path(sp.url) as page+ from public.site_pages sp+ where sp.brand_id = p_brand_id+ and 'sitemap' = any(sp.sources)+ ),+ keys as (+ select page_key, page from ai+ union select page_key, page from traffic+ union select page_key, page from cited+ union select page_key, page from in_sitemap+ ),+ pages as (+ select+ k.page_key,+ min(k.page) as page,+ coalesce(max(ai.visits), 0) as ai_visits,+ coalesce(max(ke.key_events), 0) as ai_key_events,+ coalesce(max(pl.platforms), '{}'::text[]) as ai_platforms,+ coalesce(max(c.citations), 0) as citations,+ coalesce(max(t.prompts), 0) as targeting_prompts,+ coalesce(max(tr.sessions), 0) as sessions,+ coalesce(max(tr.engaged_sessions), 0) as engaged_sessions,+ coalesce(max(tr.key_events), 0) as key_events,+ coalesce(max(tr.transactions), 0) as transactions,+ coalesce(max(tr.revenue), 0) as revenue,+ coalesce(max(tr.engagement_seconds), 0) as engagement_seconds,+ bool_or(s.page_key is not null) as in_sitemap+ from keys k+ left join ai on ai.page_key = k.page_key+ left join ai_key_events ke on ke.page_key = k.page_key+ left join platforms pl on pl.page_key = k.page_key+ left join cited c on c.page_key = k.page_key+ left join targeted t on t.page_key = k.page_key+ left join traffic tr on tr.page_key = k.page_key+ left join in_sitemap s on s.page_key = k.page_key+ group by k.page_key+ ),+ kept as (+ select p.*,+ -- The page's place on the site by value, among pages with traffic.+ case when p.sessions > 0 then+ rank() over (+ partition by (p.sessions > 0)+ order by p.revenue desc, p.key_events desc, p.sessions desc, p.engagement_seconds desc+ )+ end as value_rank,+ p.ai_visits = 0 and (p.sessions > 0 or p.in_sitemap) as no_ai_traffic,+ p.citations >= 20 and p.ai_visits = 0 as cited_not_clicked,+ p.ai_visits > 0 and p.citations = 0 as traffic_no_prompt+ from pages p+ where p.page not in ('', '(not set)', '(other)')+ -- The nightly detection's excluded segments (page-paths.js).+ and not exists (+ select 1+ from unnest(string_to_array(lower(p.page), '/')) seg+ where seg = any (array[+ 'checkout', 'cart', 'basket', 'order', 'orders', 'order-confirmation',+ 'confirmation', 'thank-you', 'thanks', 'payment', 'pay', 'login', 'signin',+ 'sign-in', 'signup', 'sign-up', 'register', 'logout', 'account', 'my-account',+ 'profile', 'dashboard', 'admin', 'wishlist', 'favorites', 'search', 'career',+ 'careers', 'jobs', 'job', 'cookie-policy', 'privacy', 'privacy-policy', 'terms',+ 'terms-of-service', 'legal', 'unsubscribe'+ ])+ )+ ),+ tab as (+ select * from kept+ where case p_tab+ when 'no_ai_traffic' then no_ai_traffic+ when 'cited_not_clicked' then cited_not_clicked+ when 'traffic_no_prompt' then traffic_no_prompt+ else true+ end+ )+ select jsonb_build_object(+ 'counts', (+ select jsonb_build_object(+ 'all', count(*),+ 'no_ai_traffic', count(*) filter (where no_ai_traffic),+ 'cited_not_clicked', count(*) filter (where cited_not_clicked),+ 'traffic_no_prompt', count(*) filter (where traffic_no_prompt)+ )+ from kept+ ),+ 'rows', coalesce((+ select jsonb_agg(to_jsonb(r) - 'page_key' - 'no_ai_traffic' - 'cited_not_clicked' - 'traffic_no_prompt')+ from (+ select * from tab+ order by+ -- Each list in the order it's worked through.+ case when p_tab = 'no_ai_traffic' then revenue end desc nulls last,+ case when p_tab = 'no_ai_traffic' then key_events end desc nulls last,+ case when p_tab = 'no_ai_traffic' then sessions end desc nulls last,+ case when p_tab = 'no_ai_traffic' then engagement_seconds end desc nulls last,+ case when p_tab = 'cited_not_clicked' then citations end desc nulls last,+ ai_visits desc, citations desc, sessions desc, page+ limit greatest(p_limit, 0) offset greatest(p_offset, 0)+ ) r+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke all on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text, integer, integer)+ from public, anon;+grant execute on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text, integer, integer)+ to authenticated, service_role;++comment on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text, integer, integer) is+ 'AI Traffic Pages section (AT-006, spec §3.5): the brand''s pages in a window with AI visits (ai_traffic_merged), AI key events, top platforms, citations, prompts pointing to them, all-channel traffic and sitemap presence; the counts of the No AI traffic / Cited, not clicked / Traffic, no prompt lists and one page of the asked tab''s rows. Security definer with an organization check.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex c95b3f48f..723b29dd7 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -23992,3 +23992,325 @@ comment on function public.ga_platform_value(uuid, date, date) isnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00178_ai_traffic_pages.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00178: the AI Traffic page's Pages section and its status tabs (AT-006)+-- ============================================================================+-- Spec §3.5, "which answers send visitors": one table of the brand's pages+-- for the page's range, joining AI visits with how often tracked AI answers+-- cite the page and the prompts that point to it, with three work lists:+--+-- * No AI traffic — pages with traffic in Google Analytics or in the+-- site's sitemap (site_pages) that got no AI visit, ranked by value:+-- revenue, key events, then sessions and engagement. Replaces "Pages AI+-- engines aren't sending traffic to", in the page's own window (F2).+-- * Cited, not clicked — cited at least 20 times in the range, no AI visit.+-- * Traffic, no prompt — AI visits, but no tracked prompt's answer cited+-- the page in the range.+--+-- Pages are keyed by lower(normalize_page_path(...)), so a snippet URL, an+-- Analytics landing page, a cited URL and a sitemap URL name one page. AI+-- visits are ai_traffic_merged's (00176): the snippet on days it was active,+-- Analytics on the others, never summed. Checkout, login, legal and similar+-- pages are left out, as the nightly page detection leaves them out+-- (server/src/lib/page-paths.js; a server test keeps the two lists equal).+--+-- citation_urls has no member select policy, so both functions run as their+-- owner, after checking the caller belongs to the brand's organization; a+-- caller from elsewhere gets nothing.++-- ─── Citations of the brand's own pages ─────────────────────────────────────++create or replace function public.ai_traffic_page_citations(+ p_brand_id uuid,+ p_since date,+ p_until date+)+returns table (page_key text, page text, citations bigint)+language plpgsql+stable+security definer+set search_path to 'public'+as $$+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;+ end if;++ return query+ with own_domains as (+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain+ from public.brand_domains bd+ where bd.brand_id = p_brand_id+ )+ select+ lower(public.normalize_page_path(cu.url)),+ min(public.normalize_page_path(cu.url)),+ sum(d.citations)::bigint+ from public.citation_url_daily d+ join public.citation_urls cu on cu.id = d.url_id+ where d.brand_id = p_brand_id+ and d.day >= coalesce(p_since, '-infinity'::date)+ and d.day <= coalesce(p_until, 'infinity'::date)+ and cu.domain in (select domain from own_domains)+ group by 1;+end;+$$;++revoke all on function public.ai_traffic_page_citations(uuid, date, date) from public, anon;+grant execute on function public.ai_traffic_page_citations(uuid, date, date)+ to authenticated, service_role;++comment on function public.ai_traffic_page_citations(uuid, date, date) is+ 'AI Traffic (AT-006): how often tracked AI answers cited each of the brand''s own pages between two days, keyed by lower(normalize_page_path). Security definer with an organization check: citation_urls has no member select policy.';++-- ─── The Pages section ──────────────────────────────────────────────────────++create or replace function public.ai_traffic_pages(+ p_brand_id uuid,+ p_from timestamptz,+ p_to timestamptz,+ p_tab text default 'all',+ p_limit integer default 50,+ p_offset integer default 0+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+as $$+declare+ v_since date := (p_from at time zone 'utc')::date;+ v_until date := coalesce((p_to at time zone 'utc')::date, (now() at time zone 'utc')::date);+ -- The 24-hour range reads the snippet alone, as the rest of the page does:+ -- Analytics has no hours (00176).+ v_hourly boolean := p_from is not null and coalesce(p_to, now()) - p_from <= interval '25 hours';+ v_result jsonb;+begin+ if p_tab not in ('all', 'no_ai_traffic', 'cited_not_clicked', 'traffic_no_prompt') then+ raise exception 'unknown tab %', p_tab;+ end if;+ 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+ -- AI visits per page, day by day from the snippet or Analytics (00176).+ ai as (+ select lower(e->>'page') as page_key, min(e->>'page') as page, sum((e->>'visits')::bigint) as visits+ from jsonb_array_elements(+ public.ai_traffic_merged(p_brand_id, p_from, p_to, true, not v_hourly) -> 'pages'+ ) e+ group by 1+ ),+ -- Days the snippet was active, over the whole UTC day (00176's rule).+ snippet_days as (+ select distinct (l.created_at at time zone 'utc')::date as day+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= coalesce(v_since::timestamp at time zone 'utc', '-infinity'::timestamptz)+ and l.created_at < (v_until + 1)::timestamp at time zone 'utc'+ ),+ -- Which assistants sent them, counted as the AI visits are: the snippet,+ -- and Analytics on days without it (never within 24 hours).+ platform_visits as (+ select lower(public.normalize_page_path(l.url)) as page_key,+ coalesce(nullif(l.source_platform, ''), 'unknown') as platform,+ count(*)::bigint as visits+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= coalesce(p_from, '-infinity'::timestamptz)+ and (p_to is null or l.created_at <= p_to)+ group by 1, 2+ union all+ select lower(public.normalize_page_path(g.landing_page)),+ coalesce(g.platform, g.source),+ sum(g.sessions)::bigint+ from public.ga_ai_traffic_stats g+ where not v_hourly+ and g.brand_id = p_brand_id+ and g.landing_page <> ''+ and g.sessions > 0+ and g.date >= coalesce(v_since, '-infinity'::date)+ and g.date <= v_until+ and not exists (select 1 from snippet_days s where s.day = g.date)+ group by 1, 2+ ),+ platforms as (+ select page_key, (array_agg(platform order by visits desc, platform))[1:3] as platforms+ from (select page_key, platform, sum(visits) as visits from platform_visits group by 1, 2) t+ group by 1+ ),+ -- Key events in AI sessions: only Analytics has them, and it has no hours.+ ai_key_events as (+ select lower(public.normalize_page_path(g.landing_page)) as page_key, sum(g.key_events)::bigint as key_events+ from public.ga_ai_traffic_stats g+ where not v_hourly+ and g.brand_id = p_brand_id+ and g.landing_page <> ''+ and g.date >= coalesce(v_since, '-infinity'::date)+ and g.date <= v_until+ group by 1+ ),+ -- Every channel's traffic, for the No AI traffic list's value.+ traffic as (+ select+ lower(public.normalize_page_path(gps.landing_page)) as page_key,+ min(public.normalize_page_path(gps.landing_page)) as page,+ sum(gps.sessions)::bigint as sessions,+ sum(gps.engaged_sessions)::bigint as engaged_sessions,+ sum(gps.key_events)::bigint as key_events,+ sum(gps.transactions)::bigint as transactions,+ sum(gps.purchase_revenue) as revenue,+ sum(gps.engagement_duration_seconds)::bigint as engagement_seconds+ from public.ga_page_stats gps+ where gps.brand_id = p_brand_id+ and gps.date >= coalesce(v_since, '-infinity'::date)+ and gps.date <= v_until+ group by 1+ ),+ cited as (+ select c.page_key, c.page, c.citations+ from public.ai_traffic_page_citations(p_brand_id, v_since, v_until) c+ ),+ -- Prompts pointing to the page: an active prompt's target URL.+ targeted as (+ select lower(public.normalize_page_path(ptu.url)) as page_key,+ count(distinct ptu.prompt_id)::bigint as prompts+ from public.prompt_target_urls ptu+ join public.prompts p on p.id = ptu.prompt_id and p.is_active+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where ps.brand_id = p_brand_id+ group by 1+ ),+ in_sitemap as (+ select distinct lower(public.normalize_page_path(sp.url)) as page_key,+ public.normalize_page_path(sp.url) as page+ from public.site_pages sp+ where sp.brand_id = p_brand_id+ and 'sitemap' = any(sp.sources)+ ),+ keys as (+ select page_key, page from ai+ union select page_key, page from traffic+ union select page_key, page from cited+ union select page_key, page from in_sitemap+ ),+ pages as (+ select+ k.page_key,+ min(k.page) as page,+ coalesce(max(ai.visits), 0) as ai_visits,+ coalesce(max(ke.key_events), 0) as ai_key_events,+ coalesce(max(pl.platforms), '{}'::text[]) as ai_platforms,+ coalesce(max(c.citations), 0) as citations,+ coalesce(max(t.prompts), 0) as targeting_prompts,+ coalesce(max(tr.sessions), 0) as sessions,+ coalesce(max(tr.engaged_sessions), 0) as engaged_sessions,+ coalesce(max(tr.key_events), 0) as key_events,+ coalesce(max(tr.transactions), 0) as transactions,+ coalesce(max(tr.revenue), 0) as revenue,+ coalesce(max(tr.engagement_seconds), 0) as engagement_seconds,+ bool_or(s.page_key is not null) as in_sitemap+ from keys k+ left join ai on ai.page_key = k.page_key+ left join ai_key_events ke on ke.page_key = k.page_key+ left join platforms pl on pl.page_key = k.page_key+ left join cited c on c.page_key = k.page_key+ left join targeted t on t.page_key = k.page_key+ left join traffic tr on tr.page_key = k.page_key+ left join in_sitemap s on s.page_key = k.page_key+ group by k.page_key+ ),+ kept as (+ select p.*,+ -- The page's place on the site by value, among pages with traffic.+ case when p.sessions > 0 then+ rank() over (+ partition by (p.sessions > 0)+ order by p.revenue desc, p.key_events desc, p.sessions desc, p.engagement_seconds desc+ )+ end as value_rank,+ p.ai_visits = 0 and (p.sessions > 0 or p.in_sitemap) as no_ai_traffic,+ p.citations >= 20 and p.ai_visits = 0 as cited_not_clicked,+ p.ai_visits > 0 and p.citations = 0 as traffic_no_prompt+ from pages p+ where p.page not in ('', '(not set)', '(other)')+ -- The nightly detection's excluded segments (page-paths.js).+ and not exists (+ select 1+ from unnest(string_to_array(lower(p.page), '/')) seg+ where seg = any (array[+ 'checkout', 'cart', 'basket', 'order', 'orders', 'order-confirmation',+ 'confirmation', 'thank-you', 'thanks', 'payment', 'pay', 'login', 'signin',+ 'sign-in', 'signup', 'sign-up', 'register', 'logout', 'account', 'my-account',+ 'profile', 'dashboard', 'admin', 'wishlist', 'favorites', 'search', 'career',+ 'careers', 'jobs', 'job', 'cookie-policy', 'privacy', 'privacy-policy', 'terms',+ 'terms-of-service', 'legal', 'unsubscribe'+ ])+ )+ ),+ tab as (+ select * from kept+ where case p_tab+ when 'no_ai_traffic' then no_ai_traffic+ when 'cited_not_clicked' then cited_not_clicked+ when 'traffic_no_prompt' then traffic_no_prompt+ else true+ end+ )+ select jsonb_build_object(+ 'counts', (+ select jsonb_build_object(+ 'all', count(*),+ 'no_ai_traffic', count(*) filter (where no_ai_traffic),+ 'cited_not_clicked', count(*) filter (where cited_not_clicked),+ 'traffic_no_prompt', count(*) filter (where traffic_no_prompt)+ )+ from kept+ ),+ 'rows', coalesce((+ select jsonb_agg(to_jsonb(r) - 'page_key' - 'no_ai_traffic' - 'cited_not_clicked' - 'traffic_no_prompt')+ from (+ select * from tab+ order by+ -- Each list in the order it's worked through.+ case when p_tab = 'no_ai_traffic' then revenue end desc nulls last,+ case when p_tab = 'no_ai_traffic' then key_events end desc nulls last,+ case when p_tab = 'no_ai_traffic' then sessions end desc nulls last,+ case when p_tab = 'no_ai_traffic' then engagement_seconds end desc nulls last,+ case when p_tab = 'cited_not_clicked' then citations end desc nulls last,+ ai_visits desc, citations desc, sessions desc, page+ limit greatest(p_limit, 0) offset greatest(p_offset, 0)+ ) r+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke all on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text, integer, integer)+ from public, anon;+grant execute on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text, integer, integer)+ to authenticated, service_role;++comment on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text, integer, integer) is+ 'AI Traffic Pages section (AT-006, spec §3.5): the brand''s pages in a window with AI visits (ai_traffic_merged), AI key events, top platforms, citations, prompts pointing to them, all-channel traffic and sitemap presence; the counts of the No AI traffic / Cited, not clicked / Traffic, no prompt lists and one page of the asked tab''s rows. Security definer with an organization check.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 08620e0a6..71a56b255 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3089,7 +3089,7 @@"trend": "Trend","platforms": "Platforms","pages": "Top landing pages",- "opportunities": "Pages without AI traffic",+ "pageStatus": "Pages by status","visits": "Visits"},"columns": {@@ -3118,7 +3118,12 @@"time": "Time (UTC)","referrer": "Referrer","country": "Country",- "pageviews": "Pageviews"+ "pageviews": "Pageviews",+ "aiVisits": "AI visits",+ "aiKeyEvents": "Key events from AI",+ "topPlatforms": "Top platforms",+ "inSitemap": "In sitemap",+ "status": "Status"},"metrics": {"visits": "AI-referred visits",@@ -3133,26 +3138,7 @@"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",- "analytics": {- "not_configured": "Google Analytics isn't set up on this server",- "not_connected": "Needs Google Analytics: not connected",- "unmapped": "Needs Google Analytics: no property chosen for this brand",- "syncing": "Google Analytics is importing its first data",- "noData": "No data for this range in Google Analytics",- "noFinding": "No high-value pages without AI traffic in this range",- "failed": "Google Analytics findings couldn't be read; try the export again"- }- },- "citationStates": {- "cited": "Cited",- "targeted_not_cited": "Not cited",- "not_targeted": "No prompt"- },- "signals": {- "revenue": "Revenue",- "transactions": "Orders",- "key_events": "Conversions",- "engagement": "Engagement (min)"+ "noPages": "No pages in this range"},"sourceStates": {"active": "Active",@@ -3177,7 +3163,14 @@"ga": "Google Analytics","gsc": "Google Search Console","exportedAt": "Exported at"- }+ },+ "pageStatuses": {+ "noAiTraffic": "No AI traffic",+ "citedNotClicked": "Cited, not clicked",+ "trafficNoPrompt": "Traffic, no prompt"+ },+ "yes": "Yes",+ "no": "No"},"change": {"new": "new",@@ -3290,16 +3283,10 @@"engagedVisits": "engaged visits","keyEvents": "key events from AI","googleClicks": "Google clicks",- "pageOpportunities": "pages AI engines aren't sending traffic to"+ "pageValue": "which valuable pages get no AI traffic"}},"pageOpportunities": {- "title": "Pages AI engines aren't sending traffic to",- "explain": "{ranking} None of these got a visit from an AI assistant in this range, in Google Analytics or through the tracking snippet, and <b>AI visibility</b> says why: whether answers already cite the page, whether a prompt you track points at it, or whether nothing does.",- "empty": "No high-value pages without AI traffic in this range.",- "page": "Page",- "aiVisibility": "AI visibility",- "sessions": "Sessions","rank": "Rank {by}","minutes": "{minutes} min","signals": {@@ -3338,6 +3325,52 @@"detail": "nothing you track points here"}}+ },+ "pageList": {+ "title": "Pages",+ "subtitle": "Which pages get AI visits, which don't, and why",+ "needsAnalytics": "Key events and the No AI traffic list need Google Analytics; without it they show what the snippet and your sitemap know.",+ "tabs": {+ "noAiTraffic": {+ "label": "No AI traffic",+ "explain": "Pages with traffic in Google Analytics or in your sitemap that got no AI visit in this range, most valuable first. AI visibility says why.",+ "empty": "Every page with traffic or in your sitemap got AI visits in this range."+ },+ "citedNotClicked": {+ "label": "Cited, not clicked",+ "explain": "Pages AI answers cited at least 20 times in this range that got no AI visit: answers show them, nobody clicks through.",+ "empty": "No page was cited 20 times or more without an AI visit in this range."+ },+ "trafficNoPrompt": {+ "label": "Traffic, no prompt",+ "explain": "Pages AI assistants sent visitors to that no tracked prompt's answer cited in this range: the visits come from questions you don't track.",+ "empty": "Every page with AI visits is cited by a prompt you track in this range."+ },+ "all": {+ "label": "All pages",+ "explain": "Every page with AI visits, citations, traffic or a sitemap entry in this range.",+ "empty": "No pages in this range."+ }+ },+ "columns": {+ "page": "Page",+ "aiVisibility": "AI visibility",+ "sessions": "Sessions",+ "citations": "Cited in answers",+ "prompts": "Prompts pointing here",+ "aiVisits": "AI visits",+ "platforms": "Top platforms",+ "keyEvents": "Key events",+ "status": "Status",+ "citedInAnswers": "Cited in answers"+ },+ "auditPage": "Audit page",+ "addPrompts": "Add prompts",+ "auditFailed": "The audit couldn't start.",+ "failed": "The pages couldn't be loaded.",+ "shown": "{shown, number} of {total, plural, one {# page} other {# pages}}",+ "sameWindow": "same range as the rest of the page",+ "showMore": "Show more"}},"prompts": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsxdeleted file mode 100644index 9ea0eedba..000000000--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsx+++ /dev/null@@ -1,229 +0,0 @@-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 { PageOpportunities, PageOpportunity, TrafficDateWindow } from '@/lib/actions/traffic';-import type { SourceState } from '@/lib/actions/integrations';--/**- * "Pages AI engines aren't sending traffic to" reads the range the page- * shows and names it (AT-002), says it needs Google Analytics, and shows- * Analytics' own state until there is data from it (AT-016).- */--const getPageOpportunities = vi.fn();-vi.mock('@/lib/actions/traffic', () => ({- getPageOpportunities: (...args: unknown[]) => getPageOpportunities(...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 { PageOpportunitiesCard } = await import('./_opportunities-card');--(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =- true;--const finding = (over: Partial<PageOpportunity> = {}): PageOpportunity => ({- landingPage: '/pricing',- valueSignal: 'key_events',- valuePercentile: 95,- valueRank: 1,- sessions: 1200,- engagedSessions: 800,- keyEvents: 40,- transactions: 0,- revenue: 0,- engagementSeconds: 0,- citationState: 'targeted_not_cited',- citations: 0,- citingPrompts: 0,- targetingPrompts: 1,- ...over,-});--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 WEEK: TrafficDateWindow = { dateFrom: '2026-10-11T09:00:00.000Z' };-const MONTH: TrafficDateWindow = { dateFrom: '2026-09-18T09:00:00.000Z' };--let container: HTMLDivElement;-let root: Root;-const onShowAllTime = vi.fn();--beforeEach(() => {- getPageOpportunities.mockReset();- onShowAllTime.mockReset();- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);-});--afterEach(() => {- act(() => root.unmount());- container.remove();-});--async function render(- dateWindow: TrafficDateWindow,- rangeLabel: string,- {- source = ga(),- sourceUnknown = false,- showAll = true,- }: { source?: SourceState | null; sourceUnknown?: boolean; showAll?: boolean } = {},-) {- await act(async () => {- root.render(- <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">- <PageOpportunitiesCard- brandId="b1"- dateWindow={dateWindow}- rangeLabel={rangeLabel}- source={source}- sourceUnknown={sourceUnknown}- domain="acme.example"- canConnect- onConnected={() => {}}- onShowAllTime={showAll ? onShowAllTime : undefined}- />- </NextIntlClientProvider>,- );- });-}--const resolveWith = (result: PageOpportunities) => getPageOpportunities.mockResolvedValue(result);-const text = () => container.textContent ?? '';--describe('PageOpportunitiesCard', () => {- it("asks for the page's range, names it, and says it needs Google Analytics", async () => {- resolveWith({ pages: 30, rows: [finding()] });- await render(WEEK, 'last 7 days');-- expect(getPageOpportunities).toHaveBeenCalledWith('b1', WEEK);- expect(text()).toContain('Needs Google Analytics');- expect(text()).toContain('last 7 days');- expect(text()).not.toContain('28 days');- expect(text()).toContain('in this range');- });-- it('reads the new range when the page changes it', async () => {- resolveWith({ pages: 30, rows: [finding()] });- await render(WEEK, 'last 7 days');- resolveWith({ pages: 30, rows: [finding({ landingPage: '/demo' })] });- await render(MONTH, 'last 30 days');-- expect(getPageOpportunities).toHaveBeenLastCalledWith('b1', MONTH);- expect(text()).toContain('last 30 days');- expect(text()).toContain('/demo');- expect(text()).not.toContain('/pricing');- });-- it('keeps the previous range on screen, faded, while the new one loads', async () => {- resolveWith({ pages: 30, rows: [finding()] });- await render(WEEK, 'last 7 days');- getPageOpportunities.mockReturnValue(new Promise(() => {}));- await render(MONTH, 'last 30 days');-- const card = container.querySelector('[aria-busy="true"]');- expect(card).not.toBeNull();- expect(card!.textContent).toContain('/pricing');- // The faded rows still name the range they were ranked for.- expect(card!.textContent).toContain('last 7 days');- expect(card!.textContent).not.toContain('last 30 days');- });-- it('shows the ranking signal and why each page gets nothing from AI', async () => {- resolveWith({- pages: 30,- rows: [- finding(),- finding({ landingPage: '/guide', citationState: 'cited', citations: 3, valueRank: 2 }),- ],- });- await render(WEEK, 'last 7 days');-- expect(text()).toContain('Ranked by the conversions Analytics records on these pages.');- expect(text()).toContain('Conversions');- expect(text()).toContain('Rank by conversions');- expect(text()).toContain('Not cited');- expect(text()).toContain('1 prompt targets this page');- expect(text()).toContain('3 citations in answers');- });-- it('says nothing qualifies when Analytics has data for the range', async () => {- resolveWith({ pages: 30, rows: [] });- await render(WEEK, 'last 24 hours');-- expect(text()).toContain('No high-value pages without AI traffic in this range.');- expect(container.querySelector('table')).toBeNull();- });-- it('says Analytics has no data for the range, with a way to widen it', async () => {- resolveWith({ pages: 0, rows: [] });- await render(WEEK, 'last 7 days');-- expect(text()).toContain('No data for this range in Google Analytics');- const showAll = [...container.querySelectorAll('button')].find(- (b) => b.textContent === 'Show all time',- );- await act(async () => showAll!.click());- expect(onShowAllTime).toHaveBeenCalled();- });-- it('offers no wider range when it already shows all time', async () => {- resolveWith({ pages: 0, rows: [] });- await render({}, 'all time', { showAll: false });- expect(text()).toContain('No data for this range in Google Analytics');- expect(text()).not.toContain('Show all time');- });-- it("shows Analytics' state, and reads nothing, until Analytics has data", async () => {- await render(WEEK, 'last 7 days', { source: ga({ connected: false, mapped: false }) });- expect(text()).toContain('Needs Google Analytics');- expect(text()).toContain('Connect Google Analytics to see this');-- await render(WEEK, 'last 7 days', { source: ga({ lastDataAt: null }) });- expect(text()).toContain('Importing your Google Analytics data');-- await render(WEEK, 'last 7 days', { source: ga({ mapped: false }) });- expect(text()).toContain('Choose a property for this brand');-- expect(getPageOpportunities).not.toHaveBeenCalled();- // The range belongs to the data, so it shows only with data.- expect(text()).not.toContain('last 7 days');- });-- it('waits for the state before showing anything', async () => {- await render(WEEK, 'last 7 days', { source: null });- expect(container.innerHTML).toBe('');- expect(getPageOpportunities).not.toHaveBeenCalled();- });-- it('reads the range anyway when the state could not be read', async () => {- resolveWith({ pages: 30, rows: [finding()] });- await render(WEEK, 'last 7 days', { source: null, sourceUnknown: true });- expect(getPageOpportunities).toHaveBeenCalledWith('b1', WEEK);- expect(text()).toContain('/pricing');- });-- it('hides itself when the read fails, rather than claim there is no data', async () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- getPageOpportunities.mockRejectedValue(new Error('Server error: 500'));- await render(WEEK, 'last 7 days');- expect(container.innerHTML).toBe('');- error.mockRestore();- });-});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsxdeleted file mode 100644index e9827be2e..000000000--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx+++ /dev/null@@ -1,253 +0,0 @@-'use client';--import { useEffect, useState, type ReactNode } from 'react';-import { useTranslations } from 'next-intl';-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';-import { Badge } from '@/components/ui/badge';-import {- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,-} from '@/components/ui/table';-import { Skeleton } from '@/components/ui/skeleton';-import { Target } from 'lucide-react';-import { cn } from '@/lib/utils';-import { formatNumber } from '@/lib/format';-import {- getPageOpportunities,- type PageOpportunities,- type PageOpportunity,- type TrafficDateWindow,-} from '@/lib/actions/traffic';-import type { SourceState } from '@/lib/actions/integrations';-import { TRAFFIC_SECTION_SOURCES, googleSourceStatus } from '@/lib/traffic-sources';-import { NeedsTag, SourceNoData, SourceUnavailable } from './_source-gate';--/**- * Pages that carry weight and get nothing from AI engines (#719), for the- * range the page shows (AT-002).- *- * The server ranks that range on request with the nightly engine's rules,- * so no section of the page has its own hidden window, and a page the- * tracking snippet saw AI visitors on is never listed here.- *- * It needs Google Analytics, and says so beside its title (AT-016). Until- * Analytics has data it shows the source's state in place of the list — not- * connected, syncing, or no property for this brand — and with no Analytics- * data for the range it says that. With data but no finding it says so too,- * so the card never vanishes or stands blank.- */--const PROVIDER = TRAFFIC_SECTION_SOURCES.pageOpportunities;--/**- * The ranking is described in the words of the metric that produced it- * (`signals.*` in the messages). The engine ranks on whatever the property- * reports — money where there is money, engagement where there is not — and- * the copy keeps the page honest about which. Calling an engagement rank- * "your most valuable page" would be a true sentence about the wrong thing.- *- * Why a page that earns gets nothing from AI engines is one of three states- * (`citation.*`), because they need three different actions. A page cited a- * hundred times that still earns no visit is a click-through problem; a page- * nothing points at is a coverage gap; a page a prompt targets and no answer- * cites is a visibility loss.- */--/** The ranked page's figure on the signal that ranked it. */-function signalValue(row: PageOpportunity, inMinutes: (minutes: string) => string): string {- if (row.valueSignal === 'revenue') return formatNumber(row.revenue);- if (row.valueSignal === 'transactions') return formatNumber(row.transactions);- if (row.valueSignal === 'key_events') return formatNumber(row.keyEvents);- return inMinutes(formatNumber(Math.round(row.engagementSeconds / 60)));-}--/** The count a citation state's detail line names. */-function citationCount(row: PageOpportunity): number {- if (row.citationState === 'cited') return row.citations;- if (row.citationState === 'targeted_not_cited') return row.targetingPrompts;- return 0;-}--export function PageOpportunitiesCard({- brandId,- dateWindow,- rangeLabel,- source,- sourceUnknown = false,- domain,- canConnect,- onConnected,- onShowAllTime,- actions,-}: {- 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 it loads. */- source: SourceState | null;- /** The state couldn't be read: show what the range has, as before AT-016. */- sourceUnknown?: boolean;- /** The brand's primary domain, for the property line. */- domain: string | undefined;- canConnect: boolean;- onConnected: () => void;- /** Widens the page's range; absent when it is already all time. */- onShowAllTime?: () => void;- /** The table's own Excel / CSV buttons (AT-015), shown once it has data. */- actions?: ReactNode;-}) {- const t = useTranslations('traffic.pageOpportunities');- const status = source ? googleSourceStatus(source) : sourceUnknown ? 'connected' : null;- const connected = status === 'connected';- const windowKey = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}`;- // The loaded result carries the brand and range it belongs to, rather than- // a separate loading flag reset inside the effect: resetting state- // synchronously there costs a cascading render, and comparing the stored- // key answers the same question — whose data is this — without one.- const [loaded, setLoaded] = useState<{- brandId: string;- windowKey: string;- /** The range the rows were ranked for, which a faded card still names. */- rangeLabel: string;- /** Null when the read failed. */- result: PageOpportunities | null;- } | null>(null);-- useEffect(() => {- // Nothing to rank until Analytics has data for this brand.- if (!connected) return;- let cancelled = false;- getPageOpportunities(brandId, dateWindow)- .then((result) => {- if (!cancelled) setLoaded({ brandId, windowKey, rangeLabel, result });- })- .catch((err) => {- // Best effort: this card is an addition to the page, and a failure- // here must not take the traffic analytics down with it.- console.error('Failed to load page opportunities:', err);- if (!cancelled) setLoaded({ brandId, windowKey, rangeLabel, result: null });- });- return () => {- cancelled = true;- };- }, [connected, brandId, dateWindow, windowKey, rangeLabel]);-- // The state is still loading: a moment, not worth a placeholder. A failed- // read hides the card rather than claim Analytics has no data.- if (!status) return null;- if (connected && loaded?.brandId === brandId && loaded.result === null) return null;-- // Another brand's findings must never render under this brand's name. A- // new range keeps the previous one's card, faded, until it loads, as the- // rest of the page does.- const shown = connected && loaded?.brandId === brandId ? loaded : null;- const stale = shown !== null && shown.windowKey !== windowKey;- const rows = shown?.result?.rows ?? [];- const signal = rows[0]?.valueSignal;-- return (- <Card aria-busy={stale} className={cn('transition-opacity', stale && 'opacity-60')}>- <CardHeader className="pb-2">- <div className="flex flex-wrap items-center justify-between gap-2">- <CardTitle className="flex items-center gap-2 text-sm font-medium">- <Target className="h-4 w-4 text-muted-foreground" />- {t('title')}- <NeedsTag provider={PROVIDER} />- </CardTitle>- {shown && (- <div className="flex items-center gap-2">- <Badge variant="outline" className="text-xs">- {shown.rangeLabel}- </Badge>- {shown.result && shown.result.pages > 0 && actions}- </div>- )}- </div>- {shown?.result && shown.result.pages > 0 && (- <p className="text-xs text-muted-foreground">- {signal- ? t.rich('explain', {- ranking: t(`signals.${signal}.explain`),- b: (chunks) => <span className="font-medium">{chunks}</span>,- })- : t('empty')}- </p>- )}- </CardHeader>- {!connected && source && (- <CardContent className="p-0">- <SourceUnavailable- provider={PROVIDER}- state={source}- domain={domain}- canConnect={canConnect}- onConnected={onConnected}- />- </CardContent>- )}- {connected && !shown && (- <CardContent className="pb-4">- <Skeleton className="h-4 w-64" />- </CardContent>- )}- {shown?.result?.pages === 0 && (- <SourceNoData provider={PROVIDER} onShowAllTime={onShowAllTime} />- )}- {signal && (- <CardContent className="p-0">- <Table>- <TableHeader>- <TableRow>- <TableHead className="pl-6">{t('page')}</TableHead>- <TableHead>{t('aiVisibility')}</TableHead>- <TableHead className="text-right">{t('sessions')}</TableHead>- <TableHead className="text-right">{t(`signals.${signal}.column`)}</TableHead>- <TableHead className="text-right pr-6">- {t('rank', { by: t(`signals.${signal}.by`) })}- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {rows.map((row) => (- <TableRow key={row.landingPage} className="hover:bg-muted/50">- <TableCell className="pl-6 max-w-[280px]">- <span className="font-mono text-xs text-muted-foreground line-clamp-1">- {row.landingPage}- </span>- </TableCell>- <TableCell>- <div className="space-y-0.5">- <Badge- variant={row.citationState === 'cited' ? 'secondary' : 'outline'}- className="text-xs"- >- {t(`citation.${row.citationState}.label`)}- </Badge>- <div className="text-[10px] text-muted-foreground">- {t(`citation.${row.citationState}.detail`, { count: citationCount(row) })}- </div>- </div>- </TableCell>- <TableCell className="text-right tabular-nums text-sm">- {formatNumber(row.sessions)}- </TableCell>- <TableCell className="text-right font-semibold tabular-nums text-sm">- {signalValue(row, (minutes) => t('minutes', { minutes }))}- </TableCell>- <TableCell className="text-right pr-6 tabular-nums text-sm text-muted-foreground">- #{row.valueRank}- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </CardContent>- )}- </Card>- );-}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsxnew file mode 100644index 000000000..a85a648ec--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx@@ -0,0 +1,236 @@+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 { TrafficDateWindow, TrafficPageRow, TrafficPages } from '@/lib/actions/traffic';++/**+ * The Pages section (AT-006): three work lists and the full list, each with+ * its count, read for the page's range; a row's next step is an audit or+ * prompts that point to the page.+ */++const getTrafficPages = vi.fn();+const runAudit = vi.fn();+const push = vi.fn();+vi.mock('@/lib/actions/traffic', () => ({+ getTrafficPages: (...args: unknown[]) => getTrafficPages(...args),+}));+vi.mock('@/lib/actions/audits', () => ({+ runAudit: (...args: unknown[]) => runAudit(...args),+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,+ useRouter: () => ({ push }),+}));+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }));++const { PagesCard } = await import('./_pages-card');++(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 page = (over: Partial<TrafficPageRow> = {}): TrafficPageRow => ({+ page: '/gifts',+ aiVisits: 0,+ aiKeyEvents: 0,+ aiPlatforms: [],+ citations: 0,+ targetingPrompts: 0,+ sessions: 320,+ engagedSessions: 200,+ keyEvents: 12,+ transactions: 0,+ revenue: 0,+ engagementSeconds: 0,+ inSitemap: true,+ valueRank: 1,+ ...over,+});++const pages = (rows: TrafficPageRow[], counts: Partial<TrafficPages['counts']> = {}) => ({+ counts: { noAiTraffic: 3, citedNotClicked: 1, trafficNoPrompt: 2, all: 14, ...counts },+ rows,+});++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ getTrafficPages.mockReset();+ runAudit.mockReset();+ push.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render({+ domain = 'acme-coffee.example.com',+ analyticsMissing = false,+}: { domain?: string; analyticsMissing?: boolean } = {}) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <PagesCard+ brandId={BRAND}+ dateWindow={WEEK}+ rangeLabel="Last 7 days"+ domain={domain}+ analyticsMissing={analyticsMissing}+ />+ </NextIntlClientProvider>,+ );+ });+}++const text = () => container.textContent ?? '';+const tab = (label: string) =>+ [...container.querySelectorAll<HTMLElement>('[role="tab"]')].find((el) =>+ el.textContent?.startsWith(label),+ )!;+const button = (label: string) =>+ [...container.querySelectorAll<HTMLElement>('button, a')].find((el) => el.textContent === label)!;++describe('PagesCard', () => {+ it('opens on No AI traffic for the page range, with every list counted', async () => {+ getTrafficPages.mockResolvedValue(+ pages([+ page({ citations: 6 }),+ page({ page: '/menu', targetingPrompts: 2, keyEvents: 4, valueRank: 2 }),+ page({ page: '/about', keyEvents: 0, valueRank: 3 }),+ ]),+ );+ await render();++ expect(getTrafficPages).toHaveBeenCalledWith(BRAND, WEEK, { tab: 'noAiTraffic', limit: 10 });+ expect(tab('No AI traffic').textContent).toBe('No AI traffic3');+ expect(tab('Cited, not clicked').textContent).toBe('Cited, not clicked1');+ expect(tab('Traffic, no prompt').textContent).toBe('Traffic, no prompt2');+ expect(tab('All pages').textContent).toBe('All pages14');++ // Why AI engines skip each page, ranked by key events.+ expect(text()).toContain('6 citations in answers');+ expect(text()).toContain('2 prompts target this page');+ expect(text()).toContain('nothing you track points here');+ expect(text()).toContain('ConversionsRank by conversions');+ expect(text()).toContain('32012#1');+ expect(text()).toContain('3 of 3 pages · same range as the rest of the page');+ expect(text()).not.toContain('Show more');+ });++ it('audits a cited page and offers prompts for one nothing points at', async () => {+ getTrafficPages.mockResolvedValue(+ pages([page({ citations: 6 }), page({ page: '/about', valueRank: 2 })]),+ );+ runAudit.mockResolvedValue({ id: 'audit-1' });+ await render();++ const links = [...container.querySelectorAll('a')].map((a) => a.getAttribute('href'));+ expect(links).toEqual(['/dashboard/prompts']);++ await act(async () => button('Audit page').click());+ expect(runAudit).toHaveBeenCalledWith(BRAND, 'https://acme-coffee.example.com/gifts');+ expect(push).toHaveBeenCalledWith('/dashboard/audit/audit-1');+ });++ it("can't audit without the brand's domain", async () => {+ getTrafficPages.mockResolvedValue(pages([page({ citations: 6 })]));+ await render({ domain: '' });+ expect(button('Audit page').hasAttribute('disabled')).toBe(true);+ });++ it('reads another list from the first ten, with its own columns', async () => {+ getTrafficPages.mockResolvedValue(pages([]));+ await render();+ getTrafficPages.mockResolvedValue(+ pages([+ page({+ page: '/subscriptions',+ aiVisits: 7,+ aiKeyEvents: 2,+ aiPlatforms: ['chatgpt.com', 'perplexity.ai'],+ }),+ ]),+ );+ await act(async () => tab('Traffic, no prompt').click());++ expect(getTrafficPages).toHaveBeenLastCalledWith(BRAND, WEEK, {+ tab: 'trafficNoPrompt',+ limit: 10,+ });+ expect(text()).toContain('/subscriptions');+ expect(text()).toContain('ChatGPT, Perplexity');+ expect(button('Add prompts').getAttribute('href')).toBe('/dashboard/prompts');+ });++ it("never shows one list's rows under another's columns while it loads", async () => {+ getTrafficPages.mockResolvedValue(pages([page({ citations: 25 })]));+ await render();+ expect(text()).toContain('/gifts');++ getTrafficPages.mockReturnValue(new Promise(() => {}));+ await act(async () => tab('Traffic, no prompt').click());+ expect(text()).not.toContain('/gifts');+ expect(text()).not.toContain('Show more');+ expect(container.querySelector('table')).toBeNull();+ });++ it('shows ten more pages at a time', async () => {+ getTrafficPages.mockResolvedValue(+ pages(+ Array.from({ length: 10 }, (_, i) => page({ page: `/p${i}` })),+ { noAiTraffic: 12 },+ ),+ );+ await render();+ expect(text()).toContain('10 of 12 pages');++ await act(async () => button('Show more').click());+ expect(getTrafficPages).toHaveBeenLastCalledWith(BRAND, WEEK, {+ tab: 'noAiTraffic',+ limit: 20,+ });+ });++ it('labels every list a page is on in All pages', async () => {+ getTrafficPages.mockResolvedValue(pages([]));+ await render();+ getTrafficPages.mockResolvedValue(+ pages([+ page({ citations: 25, sessions: 40 }),+ page({ page: '/subscriptions', aiVisits: 8, citations: 4 }),+ ]),+ );+ await act(async () => tab('All pages').click());++ const badges = [...container.querySelectorAll('tbody [data-slot="badge"]')].map(+ (b) => b.textContent,+ );+ expect(badges).toEqual(['No AI traffic', 'Cited, not clicked']);+ // A page on no list is doing fine.+ const status = [...container.querySelectorAll('tbody tr')][1].lastElementChild;+ expect(status?.textContent).toBe('—');+ });++ it("says when a list is empty, when it couldn't load, and what needs Analytics", async () => {+ getTrafficPages.mockResolvedValue(pages([], { noAiTraffic: 0 }));+ await render({ analyticsMissing: true });+ expect(text()).toContain('Every page with traffic or in your sitemap got AI visits');+ expect(text()).toContain('the No AI traffic list need Google Analytics');++ getTrafficPages.mockRejectedValue(new Error('Server error'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await act(async () => tab('Cited, not clicked').click());+ expect(text()).toContain("The pages couldn't be loaded.");+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsxnew file mode 100644index 000000000..4ff2b5342--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx@@ -0,0 +1,415 @@+'use client';++import { useEffect, useState, type ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { FileSearch, Loader2 } from 'lucide-react';+import { Link, useRouter } from '@/i18n/navigation';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { Skeleton } from '@/components/ui/skeleton';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+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 { citationState, pageStatuses } from '@/lib/traffic-pages';+import {+ getTrafficPages,+ type TrafficDateWindow,+ type TrafficPageRow,+ type TrafficPages,+ type TrafficPagesTab,+} from '@/lib/actions/traffic';+import { runAudit } from '@/lib/actions/audits';++/**+ * Pages: which answers send visitors (AT-006, spec §3.5, "the+ * differentiator"). The brand's pages in the page's range, with their AI+ * visits, how often tracked answers cite them and the prompts pointing to+ * them, in three work lists and the full list:+ *+ * - No AI traffic: pages with traffic in Google Analytics or in the+ * sitemap that got no AI visit, ranked by value, with why (replaces+ * "Pages AI engines aren't sending traffic to", in the same window).+ * - Cited, not clicked: answers cite them at least 20 times, nobody clicks.+ * - Traffic, no prompt: AI visitors arrive from questions no tracked+ * prompt's answer covers.+ *+ * A row's action is the next step for it: audit the page, or track prompts+ * that point to it. Sending pages to Action Center and suggested prompts+ * come with AT-006 part B.+ */++const TABS: TrafficPagesTab[] = ['noAiTraffic', 'citedNotClicked', 'trafficNoPrompt', 'all'];+const PAGE_SIZE = 10;++/** Which figure ranks No AI traffic, in the words of what the property reports. */+type ValueSignal = 'revenue' | 'transactions' | 'key_events' | 'engagement';++function valueSignal(rows: TrafficPageRow[]): ValueSignal {+ if (rows.some((r) => r.revenue > 0)) return 'revenue';+ if (rows.some((r) => r.transactions > 0)) return 'transactions';+ if (rows.some((r) => r.keyEvents > 0)) return 'key_events';+ return 'engagement';+}++function TabCount({ count }: { count: number }) {+ return (+ <span className="rounded-full bg-muted px-1.5 text-[11px] font-medium tabular-nums text-muted-foreground">+ {formatNumber(count)}+ </span>+ );+}++function PageCell({ page }: { page: string }) {+ return (+ <TableCell className="pl-6 max-w-[180px] xl:max-w-[280px]">+ <span className="font-mono text-xs text-muted-foreground line-clamp-1" title={page}>+ {page}+ </span>+ </TableCell>+ );+}++const num = (n: number) => <span className="tabular-nums">{formatNumber(n)}</span>;++export function PagesCard({+ brandId,+ dateWindow,+ rangeLabel,+ domain,+ analyticsMissing,+ actions,+}: {+ brandId: string;+ dateWindow: TrafficDateWindow;+ /** The page's own words for the range, e.g. "last 7 days". */+ rangeLabel: string;+ /** The brand's primary domain, for auditing a page. */+ domain: string | undefined;+ /** Google Analytics has no data for the brand: key events and No AI traffic are partial (§3.8b). */+ analyticsMissing: boolean;+ /** The section's Excel / CSV buttons (AT-015). */+ actions?: ReactNode;+}) {+ const t = useTranslations('traffic.pageList');+ const tReason = useTranslations('traffic.pageOpportunities');+ const router = useRouter();+ const [tab, setTab] = useState<TrafficPagesTab>('noAiTraffic');+ const [limit, setLimit] = useState(PAGE_SIZE);+ const [auditing, setAuditing] = useState<string | null>(null);++ const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}|${tab}|${limit}`;+ // The loaded result carries the request it answers, as the KPI cards do:+ // no loading flag reset inside the effect, and the last list stays on+ // screen, faded, while another loads.+ const [loaded, setLoaded] = useState<{+ key: string;+ tab: TrafficPagesTab;+ result: TrafficPages | null;+ } | null>(null);++ useEffect(() => {+ let cancelled = false;+ getTrafficPages(brandId, dateWindow, { tab, limit })+ .then((result) => {+ if (!cancelled) setLoaded({ key, tab, result });+ })+ .catch((err) => {+ // Best effort: the rest of the page doesn't depend on this list.+ console.error('Failed to load the Pages section:', err);+ if (!cancelled) setLoaded({ key, tab, result: null });+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, dateWindow, tab, limit, key]);++ const result = loaded?.result ?? null;+ const stale = loaded !== null && loaded.key !== key;+ // Another tab's rows don't fit this tab's columns: wait for its own.+ const loading = !loaded || loaded.tab !== tab;+ const rows = loading ? [] : (result?.rows ?? []);+ const total = result?.counts[tab] ?? 0;+ const signal = valueSignal(rows);++ const changeTab = (next: TrafficPagesTab) => {+ setTab(next);+ setLimit(PAGE_SIZE);+ };++ const auditPage = async (page: string) => {+ if (!domain) return;+ setAuditing(page);+ try {+ // A running audit opens on its own page, which follows it to the end.+ const started = await runAudit(brandId, `https://${domain}${page}`);+ router.push(`/dashboard/audit/${started.id}`);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : t('auditFailed'));+ setAuditing(null);+ }+ };++ const auditButton = (page: string) => (+ <Button+ size="sm"+ variant="outline"+ className="h-7 gap-1.5 text-xs"+ disabled={!domain || auditing !== null}+ onClick={() => void auditPage(page)}+ >+ {auditing === page && <Loader2 className="h-3 w-3 animate-spin" />}+ {t('auditPage')}+ </Button>+ );++ const addPromptsLink = (+ <Link+ href="/dashboard/prompts"+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 text-xs')}+ >+ {t('addPrompts')}+ </Link>+ );++ /** A No AI traffic row's next step, by why AI engines skip it. */+ const reasonAction = (row: TrafficPageRow) =>+ citationState(row) === 'not_targeted' ? addPromptsLink : auditButton(row.page);++ const platforms = (row: TrafficPageRow) =>+ row.aiPlatforms.length ? row.aiPlatforms.map(getPlatformName).join(', ') : '—';++ return (+ <Card aria-busy={stale} className={cn('transition-opacity', stale && 'opacity-60')}>+ <CardHeader className="pb-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <CardTitle className="flex items-center gap-2 text-sm font-medium">+ <FileSearch className="h-4 w-4 text-muted-foreground" />+ {t('title')}+ </CardTitle>+ <div className="flex items-center gap-2">+ <Badge variant="outline" className="text-xs">+ {rangeLabel}+ </Badge>+ {actions}+ </div>+ </div>+ <p className="text-xs text-muted-foreground">{t('subtitle')}</p>+ {analyticsMissing && <p className="text-xs text-muted-foreground">{t('needsAnalytics')}</p>}+ </CardHeader>+ <CardContent className="p-0">+ <Tabs value={tab} onValueChange={(v) => changeTab(v as TrafficPagesTab)}>+ <div className="px-6">+ <TabsList variant="line" aria-label={t('title')}>+ {TABS.map((id) => (+ <TabsTrigger key={id} value={id}>+ {t(`tabs.${id}.label`)}+ {result && <TabCount count={result.counts[id]} />}+ </TabsTrigger>+ ))}+ </TabsList>+ </div>+ </Tabs>+ <p className="px-6 pt-2 pb-1 text-xs text-muted-foreground">{t(`tabs.${tab}.explain`)}</p>++ {loading ? (+ <div className="px-6 py-4">+ <Skeleton className="h-4 w-64" />+ </div>+ ) : !result ? (+ <p className="px-6 py-4 text-sm text-muted-foreground">{t('failed')}</p>+ ) : rows.length === 0 ? (+ <p className="px-6 py-4 text-sm text-muted-foreground">{t(`tabs.${tab}.empty`)}</p>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6">{t('columns.page')}</TableHead>+ {tab === 'noAiTraffic' && (+ <>+ <TableHead className="whitespace-normal">{t('columns.aiVisibility')}</TableHead>+ <TableHead className="whitespace-normal text-right">+ {t('columns.sessions')}+ </TableHead>+ <TableHead className="whitespace-normal text-right">+ {tReason(`signals.${signal}.column`)}+ </TableHead>+ <TableHead className="whitespace-normal text-right">+ {tReason('rank', { by: tReason(`signals.${signal}.by`) })}+ </TableHead>+ </>+ )}+ {tab === 'citedNotClicked' && (+ <>+ <TableHead className="whitespace-normal text-right">+ {t('columns.citations')}+ </TableHead>+ <TableHead className="whitespace-normal text-right">+ {t('columns.prompts')}+ </TableHead>+ <TableHead className="whitespace-normal text-right">+ {t('columns.sessions')}+ </TableHead>+ </>+ )}+ {tab === 'trafficNoPrompt' && (+ <>+ <TableHead className="whitespace-normal text-right">+ {t('columns.aiVisits')}+ </TableHead>+ <TableHead className="whitespace-normal">{t('columns.platforms')}</TableHead>+ <TableHead className="whitespace-normal text-right">+ {t('columns.keyEvents')}+ </TableHead>+ </>+ )}+ {tab === 'all' && (+ <>+ <TableHead className="whitespace-normal text-right">+ {t('columns.aiVisits')}+ </TableHead>+ <TableHead className="whitespace-normal text-right">+ {t('columns.keyEvents')}+ </TableHead>+ <TableHead className="whitespace-normal text-right">+ {t('columns.citations')}+ </TableHead>+ <TableHead className="whitespace-normal">{t('columns.platforms')}</TableHead>+ <TableHead className="whitespace-normal text-right">+ {t('columns.prompts')}+ </TableHead>+ <TableHead className="pr-6">{t('columns.status')}</TableHead>+ </>+ )}+ {tab !== 'all' && <TableHead className="pr-6" />}+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row) => (+ <TableRow key={row.page} className="hover:bg-muted/50">+ <PageCell page={row.page} />+ {tab === 'noAiTraffic' && (+ <>+ <TableCell>+ <div className="space-y-0.5">+ <Badge+ variant={citationState(row) === 'cited' ? 'secondary' : 'outline'}+ className="text-xs"+ >+ {tReason(`citation.${citationState(row)}.label`)}+ </Badge>+ <div className="text-[10px] text-muted-foreground">+ {tReason(`citation.${citationState(row)}.detail`, {+ count:+ citationState(row) === 'cited'+ ? row.citations+ : row.targetingPrompts,+ })}+ </div>+ </div>+ </TableCell>+ <TableCell className="text-right text-sm">{num(row.sessions)}</TableCell>+ <TableCell className="text-right font-semibold text-sm">+ {signal === 'revenue'+ ? num(Math.round(row.revenue))+ : signal === 'transactions'+ ? num(row.transactions)+ : signal === 'key_events'+ ? num(row.keyEvents)+ : tReason('minutes', {+ minutes: formatNumber(Math.round(row.engagementSeconds / 60)),+ })}+ </TableCell>+ <TableCell className="text-right text-sm text-muted-foreground tabular-nums">+ {row.valueRank === null ? '—' : `#${row.valueRank}`}+ </TableCell>+ <TableCell className="pr-6 text-right">{reasonAction(row)}</TableCell>+ </>+ )}+ {tab === 'citedNotClicked' && (+ <>+ <TableCell className="text-right font-semibold text-sm">+ {num(row.citations)}+ </TableCell>+ <TableCell className="text-right text-sm">+ {num(row.targetingPrompts)}+ </TableCell>+ <TableCell className="text-right text-sm">{num(row.sessions)}</TableCell>+ <TableCell className="pr-6 text-right">{auditButton(row.page)}</TableCell>+ </>+ )}+ {tab === 'trafficNoPrompt' && (+ <>+ <TableCell className="text-right font-semibold text-sm">+ {num(row.aiVisits)}+ </TableCell>+ <TableCell className="min-w-24 whitespace-normal text-sm text-muted-foreground">+ {platforms(row)}+ </TableCell>+ <TableCell className="text-right text-sm">{num(row.aiKeyEvents)}</TableCell>+ <TableCell className="pr-6 text-right">{addPromptsLink}</TableCell>+ </>+ )}+ {tab === 'all' && (+ <>+ <TableCell className="text-right font-semibold text-sm">+ {num(row.aiVisits)}+ </TableCell>+ <TableCell className="text-right text-sm">{num(row.aiKeyEvents)}</TableCell>+ <TableCell className="text-right text-sm">{num(row.citations)}</TableCell>+ <TableCell className="min-w-24 whitespace-normal text-sm text-muted-foreground">+ {platforms(row)}+ </TableCell>+ <TableCell className="text-right text-sm">+ {num(row.targetingPrompts)}+ </TableCell>+ <TableCell className="pr-6">+ <div className="flex flex-wrap gap-1 text-sm text-muted-foreground">+ {pageStatuses(row).map((status) => (+ <Badge key={status} variant="outline" className="text-[10px]">+ {t(`tabs.${status}.label`)}+ </Badge>+ ))}+ {pageStatuses(row).length === 0 && '—'}+ </div>+ </TableCell>+ </>+ )}+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}++ {!loading && result && (+ <div className="flex flex-wrap items-center justify-between gap-2 px-6 py-3 text-xs text-muted-foreground">+ <span>+ {t('shown', { shown: rows.length, total })} · {t('sameWindow')}+ </span>+ {rows.length < total && (+ <button+ type="button"+ disabled={stale}+ onClick={() => setLimit((n) => n + PAGE_SIZE)}+ className="font-medium text-foreground underline-offset-4 hover:underline disabled:opacity-50"+ >+ {t('showMore')}+ </button>+ )}+ </div>+ )}+ </CardContent>+ </Card>+ );+}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.tsxindex 62a99fe52..e851c0e5e 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 pages AI engines ' +- "aren't sending traffic to",+ 'Needed for: AI share of traffic, engaged visits, key events from AI, 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.tsxindex 6f0d7fade..acbcf23f8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -36,7 +36,7 @@ import {DateRangeFilter,type DateRangePreset,} from '@/components/filters/date-range-filter';-import { PageOpportunitiesCard } from './_opportunities-card';+import { PagesCard } from './_pages-card';import { TRAFFIC_KPI_GRID, TrafficKpis } from './_kpis';import { VisitListSourceNote } from './_visit-list-note';import { EngagedCell, KeyEventsCell, PlatformValueNote } from './_platform-value';@@ -580,23 +580,19 @@ function TrafficPageContent({ brand }: { brand: Brand }) {const hasAnyData = summary?.hasAnyData ?? false;const trulyEmpty = isEmpty && !hasAnyData;- // Findings from the Analytics connection (#719), for the page's range- // (AT-002). They need Google Analytics, not the snippet, so the card shows- // whatever the snippet has sent, with Analytics' own state until there is- // data from it (AT-016). Kept apart from the snippet's tables: the two- // origins are never summed; a page the snippet saw is just never listed.- const opportunitiesCard = (- <PageOpportunitiesCard+ // Pages: which answers send visitors (AT-006), in the page's range. It+ // replaces "Pages AI engines aren't sending traffic to" (#719, AT-002),+ // 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.+ const pagesCard = (+ <PagesCardbrandId={brand.id}dateWindow={dateWindow}rangeLabel={rangeSubLabel}- source={sources?.ga ?? null}- sourceUnknown={sourcesFailed}domain={primaryDomain}- canConnect={canManage}- onConnected={() => void loadSources()}- onShowAllTime={datePreset === 'all' ? undefined : () => handleDatePresetChange('all')}- actions={<TableExport exporter={exporter} section="opportunities" />}+ analyticsMissing={gaMissing}+ actions={<TableExport exporter={exporter} section="pageStatus" />}/>);@@ -660,7 +656,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {onShowWeek={datePreset === '24h' ? () => handleDatePresetChange('7d') : undefined}/>) : null}- {isEmpty && opportunitiesCard}+ {isEmpty && pagesCard}{!isEmpty && (<>{/* KPI cards: two rows of four (AT-017, spec §3.2). */}@@ -770,7 +766,11 @@ function TrafficPageContent({ brand }: { brand: Brand }) {<TableRow><TableHead className="pl-6">Page</TableHead><TableHead className="text-right">Visits</TableHead>- <TableHead className="text-right pr-6">Change</TableHead>+ <TableHead className="text-right">Change</TableHead>+ {/* How often tracked AI answers cite the page (AT-006). */}+ <TableHead className="text-right pr-6">+ {t('pageList.columns.citedInAnswers')}+ </TableHead></TableRow></TableHeader><TableBody>@@ -784,7 +784,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {<TableCell className="text-right font-semibold tabular-nums text-sm">{formatNumber(row.visits)}</TableCell>- <TableCell className="text-right pr-6">+ <TableCell className="text-right"><div className="flex justify-end"><DeltaBadgecurrent={row.visits}@@ -793,6 +793,9 @@ function TrafficPageContent({ brand }: { brand: Brand }) {/></div></TableCell>+ <TableCell className="text-right pr-6 tabular-nums text-sm">+ {formatNumber(row.citations)}+ </TableCell></TableRow>))}</TableBody>@@ -801,7 +804,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {</Card></div>- {opportunitiesCard}+ {pagesCard}{/* Recent Visit Log with filtering and pagination*/}<Card>diff --git a/web/src/app/api/traffic/export/route.test.ts b/web/src/app/api/traffic/export/route.test.tsindex a96c395f7..053771000 100644--- a/web/src/app/api/traffic/export/route.test.ts+++ b/web/src/app/api/traffic/export/route.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { strFromU8, unzipSync } from 'fflate';import type { SourceState } from '@/lib/actions/integrations';+import { TRAFFIC_EXPORT_MAX_ROWS } from '@/lib/traffic-export';/*** GET /api/traffic/export (AT-015): the page as a file, built on the server@@ -30,7 +31,7 @@ const loaders = vi.hoisted(() => ({getTrafficTrend: vi.fn(),getTrafficVisitsForExport: vi.fn(),getTrafficSources: vi.fn(),- getPageOpportunities: vi.fn(),+ getTrafficPages: vi.fn(),}));vi.mock('@/lib/actions/traffic', () => loaders);@@ -85,7 +86,10 @@ beforeEach(() => {ga: ga(),gsc: ga({ connected: false }),});- loaders.getPageOpportunities.mockResolvedValue({ pages: 8, rows: [] });+ loaders.getTrafficPages.mockResolvedValue({+ counts: { noAiTraffic: 0, citedNotClicked: 0, trafficNoPrompt: 0, all: 0 },+ rows: [],+ });});const WINDOW = { dateFrom: '2026-10-11T09:00:00.000Z' };@@ -119,7 +123,7 @@ describe('GET /api/traffic/export', () => {'Trend','Platforms','Top landing pages',- 'Pages without AI traffic',+ 'Pages by status','Visits',]);@@ -134,12 +138,10 @@ describe('GET /api/traffic/export', () => {search: undefined,max: 100_000,});- expect(loaders.getPageOpportunities).toHaveBeenCalledWith(+ expect(loaders.getTrafficPages).toHaveBeenCalledWith(BRAND,{ ...WINDOW, dateTo: undefined },- {- limit: 1000,- },+ { tab: 'all', limit: TRAFFIC_EXPORT_MAX_ROWS },);});@@ -155,7 +157,7 @@ describe('GET /api/traffic/export', () => {'trend.csv','platforms.csv','top-landing-pages.csv',- 'pages-without-ai-traffic.csv',+ 'pages-by-status.csv','visits.csv',]);for (const file of Object.values(files)) expect(startsWithBom(file)).toBe(true);@@ -186,25 +188,18 @@ describe('GET /api/traffic/export', () => {expect(loaders.getTrafficSources).not.toHaveBeenCalled();});- it('says why Analytics has no rows instead of reading them', async () => {- loaders.getTrafficSources.mockResolvedValue({- snippetLastVisitAt: null,- ga: ga({ connected: false, mapped: false }),- gsc: ga({ connected: false }),- });- const res = await get({ format: 'csv', section: 'opportunities' });+ it('reads every page of the Pages section, whatever tab the page shows (AT-006)', async () => {+ const res = await get({ format: 'csv', section: 'pageStatus' });const csv = await csvOf(res);- expect(csv).toEqual({ bom: true, text: 'Note\nNeeds Google Analytics: not connected' });- expect(loaders.getPageOpportunities).not.toHaveBeenCalled();- });-- it("notes Analytics findings it couldn't read, rather than failing the export", async () => {- loaders.getPageOpportunities.mockRejectedValue(new Error('Server error: 500'));- const res = await get({ format: 'csv', section: 'opportunities' });-- expect(res.status).toBe(200);- expect(await res.text()).toContain("couldn't be read");+ expect(csv).toEqual({ bom: true, text: 'Note\nNo pages in this range' });+ expect(loaders.getTrafficPages).toHaveBeenCalledWith(+ BRAND,+ { dateFrom: undefined, dateTo: undefined },+ { tab: 'all', limit: TRAFFIC_EXPORT_MAX_ROWS },+ );+ expect(loaders.getTrafficSummary).not.toHaveBeenCalled();+ expect(loaders.getTrafficSources).not.toHaveBeenCalled();});it('refuses more visits than an export built on request should hold', async () => {diff --git a/web/src/app/api/traffic/export/route.ts b/web/src/app/api/traffic/export/route.tsindex da001b621..2c9d7c5a8 100644--- a/web/src/app/api/traffic/export/route.ts+++ b/web/src/app/api/traffic/export/route.ts@@ -5,14 +5,13 @@ import { z } from 'zod';import messages from '../../../../../messages/en.json';import { createClient } from '@/lib/supabase/server';import {- getPageOpportunities,+ getTrafficPages,getTrafficSources,getTrafficSummary,getTrafficTrend,getTrafficVisitsForExport,} from '@/lib/actions/traffic';import { utcDay } from '@/lib/dates';-import { googleSourceStatus } from '@/lib/traffic-sources';import {TRAFFIC_EXPORT_MAX_ROWS,TRAFFIC_EXPORT_SECTIONS,@@ -91,7 +90,7 @@ export async function GET(req: Request) {const wholePage = !q.section;try {- const [summary, trend, visits, sources] = await Promise.all([+ const [summary, trend, visits, sources, pageStatus] = await Promise.all([needs('kpis', 'platforms', 'pages')? getTrafficSummary(q.brandId, window, { topPages: Number.MAX_SAFE_INTEGER }): undefined,@@ -104,27 +103,16 @@ export async function GET(req: Request) {max: TRAFFIC_EXPORT_MAX_ROWS,}): undefined,- // For the Filters sheet, and to know whether Analytics has findings.- needs('opportunities') || wholePage- ? getTrafficSources(q.brandId).catch(() => null)+ // For the Filters sheet.+ wholePage ? getTrafficSources(q.brandId).catch(() => null) : undefined,+ // Every page of the Pages section, with its lists (AT-006).+ needs('pageStatus')+ ? getTrafficPages(q.brandId, window, { tab: 'all', 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 });- let opportunitiesStatus: TrafficExportData['opportunitiesStatus'];- let opportunities: TrafficExportData['opportunities'];- if (needs('opportunities')) {- // An unreadable state reads the findings anyway, as the page does.- opportunitiesStatus = sources ? googleSourceStatus(sources.ga) : 'connected';- if (opportunitiesStatus === 'connected') {- opportunities = await getPageOpportunities(q.brandId, window, { limit: 1000 }).catch(() => {- opportunitiesStatus = 'failed';- return null;- });- }- }-const label = exportLabels();const from = utcDay(q.from) ?? null;const to = utcDay(q.to) ?? new Date().toISOString().slice(0, 10);@@ -139,8 +127,7 @@ export async function GET(req: Request) {summary,trend,visits: visits ?? undefined,- opportunities,- opportunitiesStatus,+ pageStatus,sources,};diff --git a/web/src/lib/actions/traffic-merged.test.ts b/web/src/lib/actions/traffic-merged.test.tsindex 775fb8937..f74d31312 100644--- a/web/src/lib/actions/traffic-merged.test.ts+++ b/web/src/lib/actions/traffic-merged.test.ts@@ -53,12 +53,21 @@ const PLATFORM_VALUE = [},];+// How often tracked answers cite each page, by its lower-cased path (AT-006).+const CITATIONS = [{ page_key: '/menu', page: '/Menu', citations: 9 }];++/** The reads beside the merged one, which answer the same whatever the range. */+const OTHER_READS: Record<string, unknown> = {+ ga_platform_value: PLATFORM_VALUE,+ ai_traffic_page_citations: CITATIONS,+};+const rpc = vi.fn();-/** The merged read answers `merged`; the platform figures stay as above. */+/** The merged read answers `merged`; the other reads stay as above. */const answerMerged = (merged: Merged) =>rpc.mockImplementation(async (fn: string) => ({- data: fn === 'ga_platform_value' ? PLATFORM_VALUE : merged,+ data: OTHER_READS[fn] ?? merged,error: null,}));let snippetCount = 0;@@ -90,7 +99,7 @@ beforeEach(() => {vi.setSystemTime(new Date('2026-10-18T12:30:00.000Z'));rpc.mockReset();rpc.mockImplementation(async (fn: string, args: { p_to_inclusive: boolean }) => ({- data: fn === 'ga_platform_value' ? PLATFORM_VALUE : args.p_to_inclusive ? CURRENT : PREVIOUS,+ data: OTHER_READS[fn] ?? (args.p_to_inclusive ? CURRENT : PREVIOUS),error: null,}));snippetCount = 6;@@ -150,7 +159,19 @@ describe('getTrafficSummary', () => {p_since: '2026-10-11',p_until: '2026-10-18',});- expect(summary.topPages[0]).toEqual({ url: '/menu', visits: 115, visitsPrev: 40 });+ // Answers cite /menu whatever the case of its path (AT-006).+ expect(summary.topPages[0]).toEqual({+ url: '/menu',+ visits: 115,+ visitsPrev: 40,+ citations: 9,+ });+ expect(summary.topPages[1].citations).toBe(0);+ expect(rpc).toHaveBeenCalledWith('ai_traffic_page_citations', {+ p_brand_id: 'b1',+ p_since: '2026-10-11',+ p_until: '2026-10-18',+ });});it('keeps the top 10 pages for the page, and all of them for an export', async () => {diff --git a/web/src/lib/actions/traffic-page-opportunities.test.ts b/web/src/lib/actions/traffic-page-opportunities.test.tsdeleted file mode 100644index 4ded444a0..000000000--- a/web/src/lib/actions/traffic-page-opportunities.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--/**- * AT-002: the AI Traffic page asks the server for its own range's findings,- * as the first and last day Analytics stores.- */--let session: { access_token: string } | null = { access_token: 'tok' };-vi.mock('@/lib/supabase/server', () => ({- createClient: vi.fn(async () => ({- auth: { getSession: async () => ({ data: { session } }) },- })),-}));-vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));--import { getPageOpportunities } from './traffic';--const fetchMock = vi.fn();--beforeEach(() => {- session = { access_token: 'tok' };- fetchMock.mockReset().mockResolvedValue(- new Response(- JSON.stringify({- pages: '42',- findings: [- {- landing_page: '/pricing',- value_signal: 'revenue',- value_percentile: 97.5,- value_rank: 1,- sessions: '310',- engaged_sessions: 200,- key_events: 4,- transactions: 3,- revenue: 1290.5,- engagement_seconds: 5400,- citation_state: 'cited',- citations: '12',- citing_prompts: 2,- targeting_prompts: 0,- },- ],- }),- { status: 200 },- ),- );- vi.stubGlobal('fetch', fetchMock);-});--afterEach(() => {- vi.unstubAllGlobals();-});--const requested = () => new URL(fetchMock.mock.calls[0][0] as string);--describe('getPageOpportunities', () => {- it("sends the range's first and last UTC day", async () => {- await getPageOpportunities('b1', {- dateFrom: '2026-10-11T09:30:00.000Z',- dateTo: '2026-10-17T23:59:59.999Z',- });- const url = requested();- expect(url.pathname).toBe('/api/integrations/google-analytics/page-opportunities');- expect(Object.fromEntries(url.searchParams)).toEqual({- brandId: 'b1',- from: '2026-10-11',- to: '2026-10-17',- });- expect(fetchMock.mock.calls[0][1]).toMatchObject({- headers: { Authorization: 'Bearer tok' },- cache: 'no-store',- });- });-- it('leaves the end open for a preset, and both for all time', async () => {- await getPageOpportunities('b1', { dateFrom: '2026-10-11T09:30:00.000Z' });- expect(Object.fromEntries(requested().searchParams)).toEqual({- brandId: 'b1',- from: '2026-10-11',- });-- fetchMock.mockClear();- await getPageOpportunities('b1', {});- expect(Object.fromEntries(requested().searchParams)).toEqual({ brandId: 'b1' });- });-- it('reads the findings into the shape the card shows', async () => {- const result = await getPageOpportunities('b1', {});- expect(result.pages).toBe(42);- expect(result.rows).toEqual([- {- landingPage: '/pricing',- valueSignal: 'revenue',- valuePercentile: 97.5,- valueRank: 1,- sessions: 310,- engagedSessions: 200,- keyEvents: 4,- transactions: 3,- revenue: 1290.5,- engagementSeconds: 5400,- citationState: 'cited',- citations: 12,- citingPrompts: 2,- targetingPrompts: 0,- },- ]);- });-- it("throws the server's error rather than returning an empty range", async () => {- fetchMock.mockResolvedValue(- new Response(JSON.stringify({ error: 'Forbidden' }), { status: 403 }),- );- await expect(getPageOpportunities('b1', {})).rejects.toThrow('Forbidden');- });-- it('needs a signed-in user', async () => {- session = null;- await expect(getPageOpportunities('b1', {})).rejects.toThrow('Not authenticated');- expect(fetchMock).not.toHaveBeenCalled();- });-});diff --git a/web/src/lib/actions/traffic-pages.test.ts b/web/src/lib/actions/traffic-pages.test.tsnew file mode 100644index 000000000..1c2e86add--- /dev/null+++ b/web/src/lib/actions/traffic-pages.test.ts@@ -0,0 +1,134 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * AT-006 (spec §3.5): the Pages section reads one tab of ai_traffic_pages+ * (00178) at a time, with every tab's count, and turns its rows into the+ * card's shape.+ */++const rpc = vi.fn();+vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({ rpc }),+}));++import { getTrafficPages } from './traffic';++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-10-18T12:30:00.000Z'));+ rpc.mockReset();+});++afterEach(() => {+ vi.useRealTimers();+});++describe('getTrafficPages', () => {+ it('reads one tab of the range, a slice at a time', async () => {+ rpc.mockResolvedValue({ data: null, error: null });+ await getTrafficPages(+ 'b1',+ { dateFrom: '2026-10-11T12:30:00.000Z' },+ { tab: 'citedNotClicked', limit: 20, offset: 10 },+ );+ expect(rpc).toHaveBeenCalledWith('ai_traffic_pages', {+ p_brand_id: 'b1',+ p_from: '2026-10-11T12:30:00.000Z',+ p_to: '2026-10-18T12:30:00.000Z',+ p_tab: 'cited_not_clicked',+ p_limit: 20,+ p_offset: 10,+ });++ // All time has no start; ten rows unless asked for more.+ await getTrafficPages('b1', undefined, { tab: 'all' });+ expect(rpc).toHaveBeenLastCalledWith('ai_traffic_pages', {+ p_brand_id: 'b1',+ p_from: null,+ p_to: null,+ p_tab: 'all',+ p_limit: 10,+ p_offset: 0,+ });+ });++ it('gives every tab its count and each row in the card’s terms', async () => {+ rpc.mockResolvedValue({+ data: {+ counts: { all: 14, no_ai_traffic: 8, cited_not_clicked: 1, traffic_no_prompt: 5 },+ rows: [+ {+ page: '/subscriptions',+ ai_visits: 2,+ ai_key_events: 1,+ ai_platforms: ['chatgpt.com'],+ citations: 4,+ targeting_prompts: 1,+ sessions: 90,+ engaged_sessions: 60,+ key_events: 7,+ transactions: 3,+ revenue: '129.50',+ engagement_seconds: 5400,+ in_sitemap: true,+ value_rank: 2,+ },+ { page: '/menu', ai_platforms: null, in_sitemap: false, value_rank: null },+ ],+ },+ error: null,+ });++ expect(await getTrafficPages('b1', undefined, { tab: 'all' })).toEqual({+ counts: { noAiTraffic: 8, citedNotClicked: 1, trafficNoPrompt: 5, all: 14 },+ rows: [+ {+ page: '/subscriptions',+ aiVisits: 2,+ aiKeyEvents: 1,+ aiPlatforms: ['chatgpt.com'],+ citations: 4,+ targetingPrompts: 1,+ sessions: 90,+ engagedSessions: 60,+ keyEvents: 7,+ transactions: 3,+ revenue: 129.5,+ engagementSeconds: 5400,+ inSitemap: true,+ valueRank: 2,+ },+ {+ page: '/menu',+ aiVisits: 0,+ aiKeyEvents: 0,+ aiPlatforms: [],+ citations: 0,+ targetingPrompts: 0,+ sessions: 0,+ engagedSessions: 0,+ keyEvents: 0,+ transactions: 0,+ revenue: 0,+ engagementSeconds: 0,+ inSitemap: false,+ valueRank: null,+ },+ ],+ });+ });++ it('gives empty lists for a brand outside the organization', async () => {+ // 00178 answers null rather than another brand's pages.+ rpc.mockResolvedValue({ data: null, error: null });+ expect(await getTrafficPages('b1', undefined, { tab: 'noAiTraffic' })).toEqual({+ counts: { noAiTraffic: 0, citedNotClicked: 0, trafficNoPrompt: 0, all: 0 },+ rows: [],+ });+ });++ it('fails loudly when the read fails', async () => {+ rpc.mockResolvedValue({ data: null, error: { message: 'unknown tab' } });+ await expect(getTrafficPages('b1', undefined, { tab: 'all' })).rejects.toThrow('unknown tab');+ });+});diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.tsindex 20bc185f2..4fda79b40 100644--- a/web/src/lib/actions/traffic.ts+++ b/web/src/lib/actions/traffic.ts@@ -1,7 +1,6 @@'use server';import { createClient } from '@/lib/supabase/server';-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';@@ -51,7 +50,13 @@ export interface TrafficSummary {/** 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 }[];+ topPages: {+ url: string;+ visits: number;+ visitsPrev: number;+ /** Times tracked AI answers cited the page in the range (AT-006). */+ citations: number;+ }[];hasAnyData: boolean;}@@ -217,7 +222,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, value] = await Promise.all([+ const [current, previous, lifetime, value, cited] = await Promise.all([readMergedTraffic(supabase, brandId, { from, to, toInclusive: true }),hasPrev? readMergedTraffic(supabase, brandId, { from: prevFrom, to: prevTo, toInclusive: false })@@ -242,7 +247,17 @@ export async function getTrafficSummary(p_since: utcDay(from) ?? null,p_until: utcDay(to) ?? new Date().toISOString().slice(0, 10),}),+ // How often tracked answers cite each page, for Top Landing Pages (AT-006).+ supabase.rpc('ai_traffic_page_citations', {+ p_brand_id: brandId,+ p_since: utcDay(from) ?? null,+ p_until: utcDay(to) ?? null,+ }),]);+ if (cited.error) throw new Error(cited.error.message);+ const citationsByPage = new Map(+ (cited.data ?? []).map((row) => [row.page_key, Number(row.citations) || 0]),+ );if (lifetime?.[1].error) throw new Error(lifetime[1].error.message);if (value.error) throw new Error(value.error.message);const valueByPlatform = new Map(@@ -280,6 +295,7 @@ export async function getTrafficSummary(url: p.page,visits: p.visits,visitsPrev: previousByPage.get(p.page) ?? 0,+ citations: citationsByPage.get(p.page.toLowerCase()) ?? 0,})),hasAnyData,};@@ -493,99 +509,95 @@ export async function getTrafficVisitsForExport(}/**- * Pages that carry commercial weight and got no AI visit in the page's range- * (#719, AT-002), from Analytics' AI channel or the tracking snippet.- *- * The server ranks the range the page shows when asked, with the nightly- * engine's signal, floors and exclusions. The page used to read the nightly- * findings, always the last 28 days, so the list could contradict the- * snippet visits beside it.+ * The Pages section (AT-006, spec §3.5; 00178): the brand's pages in the+ * page's range with their AI visits (the snippet or Analytics, day by day),+ * how often tracked answers cite them, the prompts pointing to them and+ * their traffic from every channel, sorted into three work lists.*/-export interface PageOpportunity {- landingPage: string;- /** Which metric ranked this page — never present it as anything else. */- valueSignal: 'revenue' | 'transactions' | 'key_events' | 'engagement';- valuePercentile: number;- valueRank: number;+export type TrafficPagesTab = 'noAiTraffic' | 'citedNotClicked' | 'trafficNoPrompt' | 'all';++const TAB_PARAM: Record<TrafficPagesTab, string> = {+ noAiTraffic: 'no_ai_traffic',+ citedNotClicked: 'cited_not_clicked',+ trafficNoPrompt: 'traffic_no_prompt',+ all: 'all',+};++export interface TrafficPageRow {+ /** The path, as normalize_page_path writes it. */+ page: string;+ aiVisits: number;+ /** Key events in AI sessions, from Analytics. */+ aiKeyEvents: number;+ /** The assistants that sent the most visits, most first (up to three). */+ aiPlatforms: string[];+ /** Times tracked AI answers cited the page in the range. */+ citations: number;+ /** Active prompts with the page as a target URL. */+ targetingPrompts: number;+ /** Every channel's traffic, from Analytics. */sessions: number;engagedSessions: number;keyEvents: number;transactions: number;revenue: number;engagementSeconds: number;- /**- * Why this page gets nothing from AI engines — cited anyway, targeted by a- * prompt and not cited, or not targeted at all.- */- citationState: 'cited' | 'targeted_not_cited' | 'not_targeted';- citations: number;- citingPrompts: number;- targetingPrompts: number;+ inSitemap: boolean;+ /** The page's place on the site by value, among pages with traffic. */+ valueRank: number | null;}-export interface PageOpportunities {- /** Pages Analytics reported in the range; 0 when it has no data there. */- pages: number;- /** The best ten, best first. */- rows: PageOpportunity[];+export interface TrafficPages {+ counts: Record<TrafficPagesTab, number>;+ rows: TrafficPageRow[];}-export async function getPageOpportunities(+export async function getTrafficPages(brandId: string,- window?: TrafficDateWindow,- /** The card shows the best ten; an export asks for more. */- opts?: { limit?: number },-): Promise<PageOpportunities> {+ window: TrafficDateWindow | undefined,+ opts: { tab: TrafficPagesTab; limit?: number; offset?: number },+): Promise<TrafficPages> {const supabase = await createClient();- const {- data: { session },- } = await supabase.auth.getSession();- if (!session) throw new Error('Not authenticated');-- // Analytics stores whole days, so the range goes as its first and last- // day; an open end stays open.- const params = new URLSearchParams({ brandId });- const from = utcDay(window?.dateFrom);- const to = utcDay(window?.dateTo);- if (from) params.set('from', from);- if (to) params.set('to', to);- if (opts?.limit) params.set('limit', String(opts.limit));-- const res = await fetch(- `${API_BASE_URL}/api/integrations/google-analytics/page-opportunities?${params}`,- { headers: { Authorization: `Bearer ${session.access_token}` }, cache: 'no-store' },- );- const body = await res.json().catch(() => ({}));- if (!res.ok) throw new Error(body.error || `Server error: ${res.status}`);+ const { from, to } = resolveTrafficWindow(window);+ const { data, error } = await supabase.rpc('ai_traffic_pages', {+ p_brand_id: brandId,+ p_from: from ?? null,+ p_to: to ?? null,+ p_tab: TAB_PARAM[opts.tab],+ p_limit: opts.limit ?? 10,+ p_offset: opts.offset ?? 0,+ });+ if (error) throw new Error(error.message);- const findings = (body.findings ?? []) as Record<string, unknown>[];+ const raw = (data ?? {}) as { counts?: Record<string, number>; rows?: Record<string, unknown>[] };+ const counts = raw.counts ?? {};return {- pages: Number(body.pages) || 0,- rows: findings.map((row) => ({- landingPage: row.landing_page as string,- valueSignal: row.value_signal as PageOpportunity['valueSignal'],- valuePercentile: Number(row.value_percentile) || 0,- valueRank: Number(row.value_rank) || 0,+ counts: {+ noAiTraffic: Number(counts.no_ai_traffic) || 0,+ citedNotClicked: Number(counts.cited_not_clicked) || 0,+ trafficNoPrompt: Number(counts.traffic_no_prompt) || 0,+ all: Number(counts.all) || 0,+ },+ rows: (raw.rows ?? []).map((row) => ({+ page: row.page as string,+ aiVisits: Number(row.ai_visits) || 0,+ aiKeyEvents: Number(row.ai_key_events) || 0,+ aiPlatforms: (row.ai_platforms as string[] | null) ?? [],+ citations: Number(row.citations) || 0,+ targetingPrompts: Number(row.targeting_prompts) || 0,sessions: Number(row.sessions) || 0,engagedSessions: Number(row.engaged_sessions) || 0,keyEvents: Number(row.key_events) || 0,transactions: Number(row.transactions) || 0,revenue: Number(row.revenue) || 0,engagementSeconds: Number(row.engagement_seconds) || 0,- citationState: row.citation_state as PageOpportunity['citationState'],- citations: Number(row.citations) || 0,- citingPrompts: Number(row.citing_prompts) || 0,- targetingPrompts: Number(row.targeting_prompts) || 0,+ inSitemap: Boolean(row.in_sitemap),+ valueRank:+ row.value_rank === null || row.value_rank === undefined ? null : Number(row.value_rank),})),};}-/**- * The Google side of the AI Traffic KPI cards (AT-017, spec §3.2): from- * Analytics, all sessions and the AI channel's sessions, engaged sessions- * and key events; from Search Console, clicks against the period before.- * Each is asked for only when its source has data for the brand.- *//** Analytics' engagement figures for one group of sessions (AT-005). */export interface TrafficEngagement {sessions: number;@@ -595,6 +607,13 @@ export interface TrafficEngagement {keyEventSessions: number;}+/**+ * The Google side of the AI Traffic KPI cards (AT-017, spec §3.2): from+ * Analytics, all sessions and the AI channel's sessions, engaged sessions+ * and key events; from Search Console, clicks against the period before.+ * Each is asked for only when its source has data for the brand.+ */+export interface TrafficGoogleTotals {ga: {sessions: number;diff --git a/web/src/lib/traffic-export.test.ts b/web/src/lib/traffic-export.test.tsindex 94e542c1c..9971cfe80 100644--- a/web/src/lib/traffic-export.test.ts+++ b/web/src/lib/traffic-export.test.ts@@ -57,7 +57,7 @@ const data = (over: Partial<TrafficExportData> = {}): TrafficExportData => ({{ 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 }],+ topPages: [{ url: '/pricing', visits: 35, visitsPrev: 30, citations: 4 }],hasAnyData: true,},trend: [@@ -78,25 +78,40 @@ const data = (over: Partial<TrafficExportData> = {}): TrafficExportData => ({pageviews: 3,},],- opportunitiesStatus: 'connected',- opportunities: {- pages: 30,+ pageStatus: {+ counts: { noAiTraffic: 1, citedNotClicked: 1, trafficNoPrompt: 1, all: 3 },rows: [{- landingPage: '/shop/beans',- valueSignal: 'key_events',- valuePercentile: 90.9,- valueRank: 3,+ page: '/shop/beans',+ aiVisits: 0,+ aiKeyEvents: 0,+ aiPlatforms: [],+ citations: 25,+ targetingPrompts: 2,sessions: 440,engagedSessions: 220,keyEvents: 70,transactions: 0,revenue: 0,engagementSeconds: 0,- citationState: 'targeted_not_cited',+ inSitemap: true,+ valueRank: 3,+ },+ {+ page: '/menu',+ aiVisits: 12,+ aiKeyEvents: 2,+ aiPlatforms: ['chatgpt.com', 'gemini.google.com'],citations: 0,- citingPrompts: 0,- targetingPrompts: 2,+ targetingPrompts: 0,+ sessions: 0,+ engagedSessions: 0,+ keyEvents: 0,+ transactions: 0,+ revenue: 0,+ engagementSeconds: 0,+ inSitemap: false,+ valueRank: null,},],},@@ -160,6 +175,7 @@ describe('trafficTable', () => {35,null,null,+ 4,'No previous period for all time',]);});@@ -205,28 +221,29 @@ describe('trafficTable', () => {});});- it('gives the pages without AI traffic with the value that ranked them', () => {- const table = trafficTable('opportunities', data(), label);+ it('lists every page with the lists it is on, so each tab can be filtered (AT-006)', () => {+ const table = trafficTable('pageStatus', data(), label);+ expect(table.headers).toEqual([+ 'Page',+ 'AI visits',+ 'Key events from AI',+ 'Citations',+ 'Top platforms',+ 'Prompts targeting',+ 'Sessions',+ 'Rank',+ 'In sitemap',+ 'Status',+ ]);expect(table.rows).toEqual([- ['/shop/beans', 'Not cited', 0, 2, 440, 'Conversions', 70, 3, 90.9],+ ['/shop/beans', 0, 0, 25, null, 2, 440, 3, 'Yes', 'No AI traffic; Cited, not clicked'],+ ['/menu', 12, 2, 0, 'ChatGPT, Gemini', 0, 0, null, 'No', 'Traffic, no prompt'],]);});- it('says why there are no pages without AI traffic, never an empty sheet', () => {- const note = (over: Partial<TrafficExportData>) =>- trafficTable('opportunities', data(over), label);- expect(note({ opportunitiesStatus: 'not_connected' }).rows).toEqual([- ['Needs Google Analytics: not connected'],- ]);- expect(note({ opportunities: { pages: 0, rows: [] } }).rows).toEqual([- ['No data for this range in Google Analytics'],- ]);- expect(note({ opportunities: { pages: 30, rows: [] } }).rows).toEqual([- ['No high-value pages without AI traffic in this range'],- ]);- expect(note({ opportunitiesStatus: 'failed', opportunities: null }).rows[0][0]).toContain(- "couldn't be read",- );+ it('says there are no pages, never an empty sheet', () => {+ const table = trafficTable('pageStatus', data({ pageStatus: null }), label);+ expect(table.rows).toEqual([['No pages in this range']]);});});@@ -260,7 +277,7 @@ describe('trafficWorkbook', () => {'Trend','Platforms','Top landing pages',- 'Pages without AI traffic',+ 'Pages by status','Visits',]);// A bold header row, then the rows with their numbers as numbers.diff --git a/web/src/lib/traffic-export.ts b/web/src/lib/traffic-export.tsindex c708c6867..03fa16deb 100644--- a/web/src/lib/traffic-export.ts+++ b/web/src/lib/traffic-export.ts@@ -10,14 +10,15 @@import type { Sheet } from 'write-excel-file/node';import type {- PageOpportunities,TrafficLog,+ TrafficPages,TrafficSources,TrafficSummary,TrafficTrendPoint,} from '@/lib/actions/traffic';import { csvLine } from '@/lib/csv';import { getPlatformName } from '@/lib/traffic-platforms';+import { pageStatuses } from '@/lib/traffic-pages';import { visitChange } from '@/lib/traffic-change';import {googleSourceStatus,@@ -31,14 +32,14 @@ export const TRAFFIC_EXPORT_SECTIONS = ['trend','platforms','pages',- 'opportunities',+ 'pageStatus','visits',] as const;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', 'opportunities', 'visits'] as const;+export const TRAFFIC_TABLE_SECTIONS = ['platforms', 'pages', '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;@@ -59,10 +60,8 @@ export interface TrafficExportData {summary?: TrafficSummary;trend?: TrafficTrendPoint[];visits?: TrafficLog[];- /** Null when Google Analytics has nothing to rank: see `opportunitiesStatus`. */- opportunities?: PageOpportunities | null;- /** The source's state, or 'failed' when its findings couldn't be read. */- opportunitiesStatus?: GoogleSourceStatus | 'failed';+ /** Every page of the Pages section, with the lists it is on (AT-006). */+ pageStatus?: TrafficPages | null;sources?: TrafficSources | null;}@@ -173,6 +172,8 @@ function pages(data: TrafficExportData, label: ExportLabel): ExportTable {label('columns.visits'),label('columns.previousVisits'),label('columns.change'),+ // How often tracked AI answers cite the page (AT-006).+ label('columns.citations'),label('columns.note'),],rows: (s?.topPages ?? []).map((row) => {@@ -182,51 +183,48 @@ function pages(data: TrafficExportData, label: ExportLabel): ExportTable {row.visits,s!.hasPreviousPeriod ? row.visitsPrev : null,delta.pct,+ row.citations,delta.note || null,];}),};}-function opportunities(data: TrafficExportData, label: ExportLabel): ExportTable {- const status = data.opportunitiesStatus ?? 'connected';- const result = data.opportunities;+/**+ * The Pages section (AT-006): every page, with the work lists it is on in a+ * Status column, so a spreadsheet can filter each tab (spec §3.9).+ */+function pageStatus(data: TrafficExportData, label: ExportLabel): ExportTable {+ const rows = data.pageStatus?.rows ?? [];// Never an empty sheet: say why there are no rows (spec §3.8b).- const note = (text: string): ExportTable => ({- headers: [label('columns.note')],- rows: [[text]],- });- if (status !== 'connected') return note(label(`notes.analytics.${status}`));- if (!result || result.pages === 0) return note(label('notes.analytics.noData'));- if (result.rows.length === 0) return note(label('notes.analytics.noFinding'));+ if (rows.length === 0)+ return { headers: [label('columns.note')], rows: [[label('notes.noPages')]] };return {headers: [label('columns.page'),- label('columns.aiVisibility'),+ label('columns.aiVisits'),+ label('columns.aiKeyEvents'),label('columns.citations'),+ label('columns.topPlatforms'),label('columns.targetingPrompts'),label('columns.sessions'),- label('columns.rankedBy'),- label('columns.value'),label('columns.rank'),- label('columns.percentile'),+ label('columns.inSitemap'),+ label('columns.status'),],- rows: result.rows.map((row) => [- row.landingPage,- label(`citationStates.${row.citationState}`),+ rows: rows.map((row) => [+ row.page,+ row.aiVisits,+ row.aiKeyEvents,row.citations,+ row.aiPlatforms.map(getPlatformName).join(', ') || null,row.targetingPrompts,row.sessions,- label(`signals.${row.valueSignal}`),- row.valueSignal === 'revenue'- ? row.revenue- : row.valueSignal === 'transactions'- ? row.transactions- : row.valueSignal === 'key_events'- ? row.keyEvents- : Math.round(row.engagementSeconds / 60),row.valueRank,- row.valuePercentile,+ row.inSitemap ? label('yes') : label('no'),+ pageStatuses(row)+ .map((status) => label(`pageStatuses.${status}`))+ .join('; ') || null,]),};}@@ -269,8 +267,8 @@ export function trafficTable(return platforms(data, label);case 'pages':return pages(data, label);- case 'opportunities':- return opportunities(data, label);+ case 'pageStatus':+ return pageStatus(data, label);case 'visits':return visits(data, label);}diff --git a/web/src/lib/traffic-pages.test.ts b/web/src/lib/traffic-pages.test.tsnew file mode 100644index 000000000..f70bb2d99--- /dev/null+++ b/web/src/lib/traffic-pages.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';+import { CITED_NOT_CLICKED_MIN, citationState, pageStatuses } from './traffic-pages';++/** The Pages section's lists, as 00178 sorts pages into them (AT-006). */++const row = (over: Partial<Parameters<typeof pageStatuses>[0]> = {}) => ({+ aiVisits: 0,+ citations: 0,+ sessions: 0,+ inSitemap: false,+ ...over,+});++describe('pageStatuses', () => {+ it('puts a page with traffic or a sitemap entry and no AI visit on No AI traffic', () => {+ expect(pageStatuses(row({ sessions: 12 }))).toEqual(['noAiTraffic']);+ expect(pageStatuses(row({ inSitemap: true }))).toEqual(['noAiTraffic']);+ // Known only from citations: nothing says it has visitors to win.+ expect(pageStatuses(row({ citations: 3 }))).toEqual([]);+ });++ it('counts a page as cited, not clicked from 20 citations', () => {+ expect(pageStatuses(row({ citations: CITED_NOT_CLICKED_MIN - 1 }))).toEqual([]);+ expect(pageStatuses(row({ citations: CITED_NOT_CLICKED_MIN, sessions: 5 }))).toEqual([+ 'noAiTraffic',+ 'citedNotClicked',+ ]);+ expect(pageStatuses(row({ citations: 40, aiVisits: 1 }))).toEqual([]);+ });++ it('puts AI visits that no tracked answer cites on Traffic, no prompt', () => {+ expect(pageStatuses(row({ aiVisits: 3 }))).toEqual(['trafficNoPrompt']);+ expect(pageStatuses(row({ aiVisits: 3, citations: 1 }))).toEqual([]);+ });+});++describe('citationState', () => {+ it('says why AI engines skip a page', () => {+ expect(citationState({ citations: 2, targetingPrompts: 1 })).toBe('cited');+ expect(citationState({ citations: 0, targetingPrompts: 1 })).toBe('targeted_not_cited');+ expect(citationState({ citations: 0, targetingPrompts: 0 })).toBe('not_targeted');+ });+});diff --git a/web/src/lib/traffic-pages.ts b/web/src/lib/traffic-pages.tsnew file mode 100644index 000000000..81c6210d8--- /dev/null+++ b/web/src/lib/traffic-pages.ts@@ -0,0 +1,38 @@+/**+ * The Pages section's work lists (AT-006, spec §3.5), as 00178 sorts pages+ * into them, for the card's labels and the export's Status column.+ */++import type { TrafficPageRow } from '@/lib/actions/traffic';++/** Cited at least this often with no AI visit: answers show the page, nobody clicks. */+export const CITED_NOT_CLICKED_MIN = 20;++export type TrafficPageStatus = 'noAiTraffic' | 'citedNotClicked' | 'trafficNoPrompt';++/** The lists a page is on, in the tabs' order; none for a page doing fine. */+export function pageStatuses(+ row: Pick<TrafficPageRow, 'aiVisits' | 'citations' | 'sessions' | 'inSitemap'>,+): TrafficPageStatus[] {+ const statuses: TrafficPageStatus[] = [];+ if (row.aiVisits === 0 && (row.sessions > 0 || row.inSitemap)) statuses.push('noAiTraffic');+ if (row.aiVisits === 0 && row.citations >= CITED_NOT_CLICKED_MIN)+ statuses.push('citedNotClicked');+ if (row.aiVisits > 0 && row.citations === 0) statuses.push('trafficNoPrompt');+ return statuses;+}++/**+ * Why a page gets no AI visit, as the old "Pages AI engines aren't sending+ * traffic to" card said it: answers cite it anyway, a tracked prompt points+ * at it and no answer cites it, or nothing you track points at it.+ */+export type CitationState = 'cited' | 'targeted_not_cited' | 'not_targeted';++export function citationState(+ row: Pick<TrafficPageRow, 'citations' | 'targetingPrompts'>,+): CitationState {+ if (row.citations > 0) return 'cited';+ if (row.targetingPrompts > 0) return 'targeted_not_cited';+ return 'not_targeted';+}diff --git a/web/src/lib/traffic-sources.test.ts b/web/src/lib/traffic-sources.test.tsindex 95a5f6aea..af7696f07 100644--- a/web/src/lib/traffic-sources.test.ts+++ b/web/src/lib/traffic-sources.test.ts@@ -59,12 +59,12 @@ describe('gscPropertyHost', () => {describe('sectionsNeeding', () => {it('lists the sections a source unlocks, in the page order (AT-016, AT-017)', () => {- expect(TRAFFIC_SECTION_SOURCES.pageOpportunities).toBe('google-analytics');+ expect(TRAFFIC_SECTION_SOURCES.pageValue).toBe('google-analytics');expect(sectionsNeeding('google-analytics')).toEqual(['aiShare','engagedVisits','keyEvents',- 'pageOpportunities',+ 'pageValue',]);expect(sectionsNeeding('google-search-console')).toEqual(['googleClicks']);});diff --git a/web/src/lib/traffic-sources.ts b/web/src/lib/traffic-sources.tsindex ae118f0c8..d049f15f7 100644--- a/web/src/lib/traffic-sources.ts+++ b/web/src/lib/traffic-sources.ts@@ -84,7 +84,7 @@ export const TRAFFIC_SECTION_SOURCES = {engagedVisits: 'google-analytics',keyEvents: 'google-analytics',googleClicks: 'google-search-console',- pageOpportunities: 'google-analytics',+ pageValue: 'google-analytics',} as const satisfies Record<string, IntegrationProvider>;export type TrafficSection = keyof typeof TRAFFIC_SECTION_SOURCES;diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex d60dbf185..3d078dc50 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -2842,6 +2842,25 @@ export type Database = {}Returns: Json}+ ai_traffic_page_citations: {+ Args: { p_brand_id: string; p_since: string | null; p_until: string | null }+ Returns: {+ citations: number+ page: string+ page_key: string+ }[]+ }+ ai_traffic_pages: {+ Args: {+ p_brand_id: string+ p_from: string | null+ p_limit?: number+ p_offset?: number+ p_tab?: string+ p_to: string | null+ }+ Returns: Json+ }ai_visibility_aggregates: {Args: {p_brand_id: string