Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(traffic): rank pages without AI traffic over the page's range and count snippet visits (#1158)

Cihan96ef7f1fe8e4
diff --git a/server/src/lib/page-opportunities.js b/server/src/lib/page-opportunities.js
index c021182a3..ed172e3a2 100644
--- a/server/src/lib/page-opportunities.js
+++ b/server/src/lib/page-opportunities.js
@@ -4,8 +4,9 @@
* Answers two questions per brand: which pages carry commercial weight and
* get nothing from AI engines, and — for each of those — why. The figures
* come from `ga_page_ai_visibility`, which aggregates the tables the GA sync
- * (#704) writes and joins the brand's own citations and prompt targeting to
- * them. No model runs in this path and no page is fetched.
+ * (#704) writes and joins the brand's own citations, prompt targeting and
+ * tracking-snippet visits to them. No model runs in this path and no page is
+ * fetched.
*
* The ranking signal is chosen from what the property actually reports rather
* than assumed. A shop with ecommerce ranks on money; a site with no
@@ -166,6 +167,11 @@ export function scorePages(pages, signalName) {
* The citation state explains a finding, it does not gate one: a page cited
* 104 times that still earns no AI visit is as real a problem as one nothing
* points to, and dropping it would hide the more surprising of the two.
+ *
+ * An AI visit is one either source saw: Analytics' AI channel or the
+ * tracking snippet (AT-002). Analytics alone missed visits the snippet
+ * recorded, so a page the AI Traffic page listed Gemini visitors on could be
+ * raised as getting nothing from AI in the same week.
*/
export function detectPageOpportunities({ pages, windowDays = WINDOW_DAYS }) {
const signal = pickValueSignal(pages);
@@ -175,7 +181,7 @@ export function detectPageOpportunities({ pages, windowDays = WINDOW_DAYS }) {
.filter((page) => page.sessions >= MIN_SESSIONS)
.filter((page) => page.value > 0)
.filter((page) => page.valuePercentile >= MIN_PERCENTILE)
- .filter((page) => !(page.aiSessions > 0))
+ .filter((page) => !(page.aiSessions > 0) && !(page.snippetVisits > 0))
.map((page) => ({
landing_page: page.landingPage,
kind: 'no_ai_traffic',
@@ -221,23 +227,25 @@ export function mapVisibilityRows(rows) {
citations: Number(row.citations) || 0,
citingPrompts: Number(row.citing_prompts) || 0,
targetingPrompts: Number(row.targeting_prompts) || 0,
+ snippetVisits: Number(row.snippet_visits) || 0,
}));
}
/**
- * Every page of the brand's window, read a thousand rows at a time.
+ * Every page of the brand's window, read a thousand rows at a time. Both
+ * bounds are inclusive dates (YYYY-MM-DD); null leaves that end open.
*
* Ordered by landing page rather than left to the planner: `range` without an
* order is a promise the database never made, and two requests could return
* the same row twice while another is never seen at all.
*/
-async function readVisibilityRows(brandId, since) {
+async function readVisibilityRows(brandId, since, until = null) {
const rows = [];
for (let page = 0; page < MAX_READ_PAGES; page++) {
const from = page * READ_PAGE_SIZE;
const { data, error } = await supabaseAdmin
- .rpc('ga_page_ai_visibility', { p_brand_id: brandId, p_since: since })
+ .rpc('ga_page_ai_visibility', { p_brand_id: brandId, p_since: since, p_until: until })
.order('landing_page', { ascending: true })
.range(from, from + READ_PAGE_SIZE - 1);
@@ -297,6 +305,28 @@ async function detectForBrand(brandId) {
};
}
+/**
+ * Findings for the range the AI Traffic page shows, computed on request
+ * (AT-002). The page used to list the nightly 28-day findings whatever range
+ * it showed; ranking the page's own range means the list can't disagree
+ * with the visits beside it.
+ *
+ * Nothing is written. The nightly findings stay the engine's record — Action
+ * Center and Site Audit read them — and a range someone looked at is not a
+ * finding to open or resolve. `pages` is how many pages Analytics reported
+ * in the range, so the page can tell "nothing qualifies" from "no data".
+ */
+export async function detectPageOpportunitiesInWindow(
+ brandId,
+ { since = null, until = null, limit = 10 } = {},
+) {
+ const pages = mapVisibilityRows(await readVisibilityRows(brandId, since, until));
+ // window_days describes the nightly run's fixed window; a page range has
+ // its own bounds, which the caller already holds.
+ const findings = detectPageOpportunities({ pages, windowDays: null });
+ return { pages: pages.length, findings: findings.slice(0, limit) };
+}
+
/**
* Detect for every brand with synced GA data; optionally scoped to one
* organization. Per-brand failures are logged and skipped.
diff --git a/server/src/lib/page-opportunities.test.js b/server/src/lib/page-opportunities.test.js
index ca75189ec..d226560d4 100644
--- a/server/src/lib/page-opportunities.test.js
+++ b/server/src/lib/page-opportunities.test.js
@@ -2,11 +2,13 @@ import { describe, expect, it, vi } from 'vitest';
// The module imports the supabase admin client, whose config hard-exits when
// SUPABASE_* env is absent (as in CI) — stub it before the import chain.
-vi.mock('../config/supabase.js', () => ({ default: {} }));
+const db = vi.hoisted(() => ({ rpc: vi.fn(), from: vi.fn() }));
+vi.mock('../config/supabase.js', () => ({ default: db }));
import {
classifyCitationState,
detectPageOpportunities,
+ detectPageOpportunitiesInWindow,
mapVisibilityRows,
pickValueSignal,
scorePages,
@@ -159,6 +161,28 @@ describe('detectPageOpportunities', () => {
expect(found.map((f) => f.landing_page)).not.toContain(top.landingPage);
});
+ it('does not raise a page the tracking snippet saw AI visitors on', () => {
+ // AT-002: Analytics' AI channel missed visits the snippet recorded, and
+ // the page listed them beside a finding that said there were none.
+ const pages = many();
+ const top = pages[pages.length - 1];
+ top.snippetVisits = 3;
+ const found = detectPageOpportunities({ pages });
+ expect(found.length).toBeGreaterThan(0);
+ expect(found.map((f) => f.landing_page)).not.toContain(top.landingPage);
+ });
+
+ it('keeps a page the snippet saw in the ranking, so the others keep their percentiles', () => {
+ // Excluded from the findings, not from the population: dropping it before
+ // scoring would move every other page up a place.
+ const pages = many();
+ const withVisits = detectPageOpportunities({
+ pages: pages.map((p) => (p.landingPage === '/p9' ? { ...p, snippetVisits: 1 } : p)),
+ });
+ const without = detectPageOpportunities({ pages }).filter((f) => f.landing_page !== '/p9');
+ expect(withVisits).toEqual(without);
+ });
+
it('ignores a page with too little traffic to argue from', () => {
// The absolute floor. A page can rank first on its site and still be one
// visit; raising it would be a finding about nothing.
@@ -305,6 +329,11 @@ describe('mapVisibilityRows', () => {
expect(a.targetingPrompts).toBe(4);
});
+ it('reads the snippet visits the RPC counted for the page', () => {
+ expect(mapVisibilityRows([row({ snippet_visits: '3' })])[0].snippetVisits).toBe(3);
+ expect(mapVisibilityRows([row()])[0].snippetVisits).toBe(0);
+ });
+
it('reads a count that arrived as a string, which bigint columns do', () => {
const [a] = mapVisibilityRows([row({ sessions: '4200', citations: '104' })]);
expect(a.sessions).toBe(4200);
@@ -344,3 +373,73 @@ describe('mapVisibilityRows', () => {
expect(mapVisibilityRows([])).toEqual([]);
});
});
+
+describe('detectPageOpportunitiesInWindow', () => {
+ // The RPC's rows for the window, answered a thousand at a time.
+ const rpcRows = (rows) => {
+ const calls = [];
+ db.rpc.mockImplementation((name, args) => {
+ calls.push({ name, args });
+ return {
+ order: () => ({
+ range: async (from, to) => ({ data: rows.slice(from, to + 1), error: null }),
+ }),
+ };
+ });
+ return calls;
+ };
+ const row = (i, over = {}) => ({
+ landing_page: `/p${i}`,
+ sessions: 100,
+ revenue: i + 1,
+ ...over,
+ });
+
+ it("ranks the page's own range, both bounds passed through", async () => {
+ const calls = rpcRows(Array.from({ length: 10 }, (_, i) => row(i)));
+ const result = await detectPageOpportunitiesInWindow('b1', {
+ since: '2026-10-11',
+ until: '2026-10-17',
+ });
+ expect(calls[0]).toEqual({
+ name: 'ga_page_ai_visibility',
+ args: { p_brand_id: 'b1', p_since: '2026-10-11', p_until: '2026-10-17' },
+ });
+ expect(result.pages).toBe(10);
+ expect(result.findings[0].landing_page).toBe('/p9');
+ });
+
+ it('leaves out a page with snippet visits in the range', async () => {
+ rpcRows(Array.from({ length: 10 }, (_, i) => row(i, i === 9 ? { snippet_visits: 2 } : {})));
+ const { findings } = await detectPageOpportunitiesInWindow('b1', { since: '2026-10-11' });
+ expect(findings.map((f) => f.landing_page)).not.toContain('/p9');
+ });
+
+ it('leaves both ends open when the page shows all time', async () => {
+ const calls = rpcRows([]);
+ const result = await detectPageOpportunitiesInWindow('b1');
+ expect(calls[0].args).toEqual({ p_brand_id: 'b1', p_since: null, p_until: null });
+ // No Analytics pages in the range: the page hides the card rather than
+ // saying nothing qualifies.
+ expect(result).toEqual({ pages: 0, findings: [] });
+ });
+
+ it('returns the best pages first, up to the limit', async () => {
+ rpcRows(Array.from({ length: 40 }, (_, i) => row(i)));
+ const { findings } = await detectPageOpportunitiesInWindow('b1', { limit: 3 });
+ expect(findings.map((f) => f.landing_page)).toEqual(['/p39', '/p38', '/p37']);
+ });
+
+ it('writes nothing: the nightly findings stay the record', async () => {
+ rpcRows(Array.from({ length: 10 }, (_, i) => row(i)));
+ await detectPageOpportunitiesInWindow('b1', { since: '2026-10-11' });
+ expect(db.from).not.toHaveBeenCalled();
+ });
+
+ it('reports a failed read rather than an empty range', async () => {
+ db.rpc.mockReturnValue({
+ order: () => ({ range: async () => ({ data: null, error: { message: 'timeout' } }) }),
+ });
+ await expect(detectPageOpportunitiesInWindow('b1')).rejects.toThrow('timeout');
+ });
+});
diff --git a/server/src/routes/integrations-page-opportunities.test.js b/server/src/routes/integrations-page-opportunities.test.js
new file mode 100644
index 000000000..170d53c93
--- /dev/null
+++ b/server/src/routes/integrations-page-opportunities.test.js
@@ -0,0 +1,90 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * GET /api/integrations/google-analytics/page-opportunities (AT-002): the AI
+ * Traffic page's "Pages AI engines aren't sending traffic to" for the range
+ * the page shows, for members of the brand's organization.
+ */
+
+const BRAND = '22222222-2222-2222-2222-222222222222';
+
+const detect = vi.fn();
+const access = vi.fn();
+
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+vi.mock('../lib/composio.js', () => ({}));
+vi.mock('../lib/ga-sync.js', () => ({ runGaSync: vi.fn() }));
+vi.mock('../lib/gsc-sync.js', () => ({ runGscSync: vi.fn() }));
+vi.mock('../lib/page-opportunities.js', () => ({
+ detectPageOpportunitiesInWindow: (...args) => detect(...args),
+}));
+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => access(...args) }));
+
+let server;
+let baseUrl;
+
+beforeAll(async () => {
+ const { default: router } = await import('./integrations.js');
+ const app = express();
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn() };
+ next();
+ });
+ app.use('/api/integrations', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/integrations/google-analytics/page-opportunities`;
+});
+
+afterAll(() => new Promise((resolve) => server.close(resolve)));
+
+beforeEach(() => {
+ detect.mockReset().mockResolvedValue({ pages: 12, findings: [{ landing_page: '/pricing' }] });
+ access.mockReset().mockResolvedValue({ orgId: 'org-1' });
+});
+
+const get = (query) => fetch(`${baseUrl}?${new URLSearchParams(query)}`);
+
+describe('GET /google-analytics/page-opportunities', () => {
+ it("returns the findings for the page's range", async () => {
+ const res = await get({ brandId: BRAND, from: '2026-10-11', to: '2026-10-17' });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ pages: 12, findings: [{ landing_page: '/pricing' }] });
+ expect(access).toHaveBeenCalledWith(BRAND, 'u1');
+ expect(detect).toHaveBeenCalledWith(BRAND, { since: '2026-10-11', until: '2026-10-17' });
+ });
+
+ it('leaves an end open when the page sends no bound for it', async () => {
+ await get({ brandId: BRAND });
+ expect(detect).toHaveBeenCalledWith(BRAND, { since: null, until: null });
+ });
+
+ it("refuses a bound that isn't a calendar day, and a missing or malformed brand", async () => {
+ for (const query of [
+ { brandId: BRAND, from: '2026-10-11T00:00:00Z' },
+ { brandId: BRAND, to: '2026-13-01' },
+ { brandId: 'not-a-brand', from: '2026-10-11' },
+ { from: '2026-10-11' },
+ ]) {
+ const res = await get(query);
+ expect(res.status).toBe(400);
+ }
+ expect(detect).not.toHaveBeenCalled();
+ });
+
+ it("refuses someone outside the brand's organization", async () => {
+ access.mockRejectedValue(Object.assign(new Error('Forbidden'), { status: 403 }));
+ const res = await get({ brandId: BRAND, from: '2026-10-11' });
+ expect(res.status).toBe(403);
+ expect(detect).not.toHaveBeenCalled();
+ });
+
+ it('reports a failed read as an error, not as an empty list', async () => {
+ detect.mockRejectedValue(new Error('timeout'));
+ const res = await get({ brandId: BRAND, from: '2026-10-11' });
+ expect(res.status).toBe(500);
+ });
+});
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index 365502819..c1039e230 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -1,4 +1,5 @@
import { Router } from 'express';
+import { z } from 'zod';
import supabaseAdmin from '../config/supabase.js';
import {
PROVIDERS,
@@ -12,6 +13,7 @@ import {
} from '../lib/composio.js';
import { runGscSync } from '../lib/gsc-sync.js';
import { runGaSync } from '../lib/ga-sync.js';
+import { detectPageOpportunitiesInWindow } from '../lib/page-opportunities.js';
import { assertBrandAccess } from '../lib/access.js';
const router = Router();
@@ -376,4 +378,36 @@ router.post('/google-analytics/sync', async (req, res) => {
}
});
+const pageOpportunitiesQuery = z.object({
+ brandId: z.guid(),
+ // Inclusive days; either may be left open ("all time" sends neither).
+ from: z.iso.date().optional(),
+ to: z.iso.date().optional(),
+});
+
+/**
+ * GET /api/integrations/google-analytics/page-opportunities?brandId=…&from=…&to=…
+ * The AI Traffic page's "Pages AI engines aren't sending traffic to" for the
+ * range the page shows (AT-002): valuable pages with no AI visit from
+ * Analytics or the tracking snippet in it. Reads synced data only, so it
+ * needs no Composio call, and any member of the brand's org may read it.
+ */
+router.get('/google-analytics/page-opportunities', async (req, res) => {
+ const parsed = pageOpportunitiesQuery.safeParse(req.query);
+ if (!parsed.success) return res.status(400).json({ error: 'Invalid request' });
+ const { brandId, from, to } = parsed.data;
+
+ try {
+ await assertBrandAccess(brandId, req.user.id);
+ const result = await detectPageOpportunitiesInWindow(brandId, {
+ since: from ?? null,
+ until: to ?? null,
+ });
+ return res.json(result);
+ } catch (err) {
+ if (!err.status) req.log.error({ err }, 'integrations GA page opportunities error');
+ return res.status(err.status || 500).json({ error: err.message });
+ }
+});
+
export default router;
diff --git a/supabase/migrations/00171_page_visibility_window.sql b/supabase/migrations/00171_page_visibility_window.sql
new file mode 100644
index 000000000..6d24cfebd
--- /dev/null
+++ b/supabase/migrations/00171_page_visibility_window.sql
@@ -0,0 +1,162 @@
+-- ============================================================================
+-- 00171: one window for "Pages AI engines aren't sending traffic to" (AT-002)
+-- ============================================================================
+-- The AI Traffic page's card listed the nightly findings, always the last 28
+-- days whatever range the page showed, and judged "no AI traffic" from
+-- Google Analytics' AI channel alone. A page the tracking snippet had seen
+-- Gemini visitors land on that week could sit in the card, under the visits
+-- that contradicted it.
+--
+-- ga_page_ai_visibility (00075) now takes the window's last day as well as
+-- its first, so the server can rank a page's own range on request, and
+-- reports each page's snippet visits in that window. The snippet's URLs go
+-- through the same normalize_page_path the Analytics pages do, so the two
+-- name a page the same way; ai_traffic_logs only keeps visits attributed to
+-- an AI platform, so every row counts. The snippet window runs over whole
+-- days, at least the timestamps the page itself counts, so a page with a
+-- visit in the page's range is never missed.
+--
+-- * p_since and p_until are both optional and inclusive: no p_since reads
+-- from the start, no p_until up to today. Nightly detection still passes
+-- only p_since.
+-- * The return type gains snippet_visits, so the function is dropped and
+-- recreated: CREATE OR REPLACE can't change a return type, and adding a
+-- parameter beside the old signature would leave PostgREST two overloads
+-- to choose between (00164). The body is otherwise 00075's.
+
+drop function if exists public.ga_page_ai_visibility(uuid, date);
+
+create function public.ga_page_ai_visibility(
+ p_brand_id uuid,
+ p_since date default null,
+ p_until date default null
+)
+returns table (
+ landing_page text,
+ sessions bigint,
+ engaged_sessions bigint,
+ key_events bigint,
+ transactions bigint,
+ revenue double precision,
+ engagement_seconds bigint,
+ ai_sessions bigint,
+ ai_platforms text[],
+ citations bigint,
+ citing_prompts bigint,
+ targeting_prompts bigint,
+ snippet_visits bigint
+)
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ 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
+ ),
+ own_urls as (
+ -- citation_urls.domain is already stored lowercased and without www, so
+ -- this is an index probe rather than a scan.
+ select cu.id, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ cited as (
+ select
+ ou.page_key,
+ count(*)::bigint as citations,
+ count(distinct pr.prompt_id)::bigint as citing_prompts
+ from own_urls ou
+ join public.prompt_result_citations prc
+ on prc.url_id = ou.id
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= coalesce(p_since, '-infinity'::date)
+ and prc.created_at < coalesce(p_until + 1, 'infinity'::date)
+ join public.prompt_results pr on pr.id = prc.prompt_result_id
+ group by ou.page_key
+ ),
+ targeted as (
+ -- Explicit targeting only. "A prompt covers this page's topic" is not
+ -- something SQL can decide, and guessing it would put a made-up reason on
+ -- a finding; a URL a customer attached to a prompt is a fact.
+ select
+ lower(public.normalize_page_path(ptu.url)) as page_key,
+ count(distinct ptu.prompt_id)::bigint as targeting_prompts
+ from public.prompt_target_urls ptu
+ join public.prompts p on p.id = ptu.prompt_id
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ group by 1
+ ),
+ pages as (
+ select
+ lower(public.normalize_page_path(gps.landing_page)) as page_key,
+ min(public.normalize_page_path(gps.landing_page)) as landing_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(p_since, '-infinity'::date)
+ and gps.date <= coalesce(p_until, 'infinity'::date)
+ group by 1
+ ),
+ ai as (
+ select
+ lower(public.normalize_page_path(gat.landing_page)) as page_key,
+ sum(gat.sessions)::bigint as ai_sessions,
+ array_remove(array_agg(distinct gat.platform), null) as ai_platforms
+ from public.ga_ai_traffic_stats gat
+ where gat.brand_id = p_brand_id
+ and gat.date >= coalesce(p_since, '-infinity'::date)
+ and gat.date <= coalesce(p_until, 'infinity'::date)
+ and gat.landing_page <> ''
+ group by 1
+ ),
+ snippet as (
+ -- (brand_id, created_at) is indexed, so this reads the window's visits
+ -- only.
+ select
+ lower(public.normalize_page_path(atl.url)) as page_key,
+ count(*)::bigint as snippet_visits
+ from public.ai_traffic_logs atl
+ where atl.brand_id = p_brand_id
+ and atl.created_at >= coalesce(p_since, '-infinity'::date)
+ and atl.created_at < coalesce(p_until + 1, 'infinity'::date)
+ group by 1
+ )
+ select
+ p.landing_page,
+ p.sessions,
+ p.engaged_sessions,
+ p.key_events,
+ p.transactions,
+ p.revenue,
+ p.engagement_seconds,
+ coalesce(a.ai_sessions, 0),
+ coalesce(a.ai_platforms, '{}'::text[]),
+ coalesce(c.citations, 0),
+ coalesce(c.citing_prompts, 0),
+ coalesce(t.targeting_prompts, 0),
+ coalesce(s.snippet_visits, 0)
+ from pages p
+ left join ai a on a.page_key = p.page_key
+ left join cited c on c.page_key = p.page_key
+ left join targeted t on t.page_key = p.page_key
+ left join snippet s on s.page_key = p.page_key;
+$$;
+
+-- Service-role only, as 00075 had it.
+revoke all on function public.ga_page_ai_visibility(uuid, date, date)
+ from public, anon, authenticated;
+grant execute on function public.ga_page_ai_visibility(uuid, date, date) to service_role;
+
+comment on function public.ga_page_ai_visibility(uuid, date, date) is
+ 'Per landing page for one brand (#719, AT-002): Analytics totals, AI-referred sessions, tracking-snippet AI visits, own-domain citations and prompt targeting, between p_since and p_until (both inclusive, both optional). Feeds nightly detection and the AI Traffic page''s range.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index fbdde12b9..47ae3e565 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -23079,3 +23079,169 @@ revoke execute on function public.topics_overview_window(uuid, timestamptz, time
grant execute on function public.topics_overview_window(uuid, timestamptz, timestamptz)
to authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00171_page_visibility_window.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00171: one window for "Pages AI engines aren't sending traffic to" (AT-002)
+-- ============================================================================
+-- The AI Traffic page's card listed the nightly findings, always the last 28
+-- days whatever range the page showed, and judged "no AI traffic" from
+-- Google Analytics' AI channel alone. A page the tracking snippet had seen
+-- Gemini visitors land on that week could sit in the card, under the visits
+-- that contradicted it.
+--
+-- ga_page_ai_visibility (00075) now takes the window's last day as well as
+-- its first, so the server can rank a page's own range on request, and
+-- reports each page's snippet visits in that window. The snippet's URLs go
+-- through the same normalize_page_path the Analytics pages do, so the two
+-- name a page the same way; ai_traffic_logs only keeps visits attributed to
+-- an AI platform, so every row counts. The snippet window runs over whole
+-- days, at least the timestamps the page itself counts, so a page with a
+-- visit in the page's range is never missed.
+--
+-- * p_since and p_until are both optional and inclusive: no p_since reads
+-- from the start, no p_until up to today. Nightly detection still passes
+-- only p_since.
+-- * The return type gains snippet_visits, so the function is dropped and
+-- recreated: CREATE OR REPLACE can't change a return type, and adding a
+-- parameter beside the old signature would leave PostgREST two overloads
+-- to choose between (00164). The body is otherwise 00075's.
+
+drop function if exists public.ga_page_ai_visibility(uuid, date);
+
+create function public.ga_page_ai_visibility(
+ p_brand_id uuid,
+ p_since date default null,
+ p_until date default null
+)
+returns table (
+ landing_page text,
+ sessions bigint,
+ engaged_sessions bigint,
+ key_events bigint,
+ transactions bigint,
+ revenue double precision,
+ engagement_seconds bigint,
+ ai_sessions bigint,
+ ai_platforms text[],
+ citations bigint,
+ citing_prompts bigint,
+ targeting_prompts bigint,
+ snippet_visits bigint
+)
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ 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
+ ),
+ own_urls as (
+ -- citation_urls.domain is already stored lowercased and without www, so
+ -- this is an index probe rather than a scan.
+ select cu.id, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ cited as (
+ select
+ ou.page_key,
+ count(*)::bigint as citations,
+ count(distinct pr.prompt_id)::bigint as citing_prompts
+ from own_urls ou
+ join public.prompt_result_citations prc
+ on prc.url_id = ou.id
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= coalesce(p_since, '-infinity'::date)
+ and prc.created_at < coalesce(p_until + 1, 'infinity'::date)
+ join public.prompt_results pr on pr.id = prc.prompt_result_id
+ group by ou.page_key
+ ),
+ targeted as (
+ -- Explicit targeting only. "A prompt covers this page's topic" is not
+ -- something SQL can decide, and guessing it would put a made-up reason on
+ -- a finding; a URL a customer attached to a prompt is a fact.
+ select
+ lower(public.normalize_page_path(ptu.url)) as page_key,
+ count(distinct ptu.prompt_id)::bigint as targeting_prompts
+ from public.prompt_target_urls ptu
+ join public.prompts p on p.id = ptu.prompt_id
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ group by 1
+ ),
+ pages as (
+ select
+ lower(public.normalize_page_path(gps.landing_page)) as page_key,
+ min(public.normalize_page_path(gps.landing_page)) as landing_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(p_since, '-infinity'::date)
+ and gps.date <= coalesce(p_until, 'infinity'::date)
+ group by 1
+ ),
+ ai as (
+ select
+ lower(public.normalize_page_path(gat.landing_page)) as page_key,
+ sum(gat.sessions)::bigint as ai_sessions,
+ array_remove(array_agg(distinct gat.platform), null) as ai_platforms
+ from public.ga_ai_traffic_stats gat
+ where gat.brand_id = p_brand_id
+ and gat.date >= coalesce(p_since, '-infinity'::date)
+ and gat.date <= coalesce(p_until, 'infinity'::date)
+ and gat.landing_page <> ''
+ group by 1
+ ),
+ snippet as (
+ -- (brand_id, created_at) is indexed, so this reads the window's visits
+ -- only.
+ select
+ lower(public.normalize_page_path(atl.url)) as page_key,
+ count(*)::bigint as snippet_visits
+ from public.ai_traffic_logs atl
+ where atl.brand_id = p_brand_id
+ and atl.created_at >= coalesce(p_since, '-infinity'::date)
+ and atl.created_at < coalesce(p_until + 1, 'infinity'::date)
+ group by 1
+ )
+ select
+ p.landing_page,
+ p.sessions,
+ p.engaged_sessions,
+ p.key_events,
+ p.transactions,
+ p.revenue,
+ p.engagement_seconds,
+ coalesce(a.ai_sessions, 0),
+ coalesce(a.ai_platforms, '{}'::text[]),
+ coalesce(c.citations, 0),
+ coalesce(c.citing_prompts, 0),
+ coalesce(t.targeting_prompts, 0),
+ coalesce(s.snippet_visits, 0)
+ from pages p
+ left join ai a on a.page_key = p.page_key
+ left join cited c on c.page_key = p.page_key
+ left join targeted t on t.page_key = p.page_key
+ left join snippet s on s.page_key = p.page_key;
+$$;
+
+-- Service-role only, as 00075 had it.
+revoke all on function public.ga_page_ai_visibility(uuid, date, date)
+ from public, anon, authenticated;
+grant execute on function public.ga_page_ai_visibility(uuid, date, date) to service_role;
+
+comment on function public.ga_page_ai_visibility(uuid, date, date) is
+ 'Per landing page for one brand (#719, AT-002): Analytics totals, AI-referred sessions, tracking-snippet AI visits, own-domain citations and prompt targeting, between p_since and p_until (both inclusive, both optional). Feeds nightly detection and the AI Traffic page''s range.';
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 619ffe6af..5b7a484aa 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3096,6 +3096,53 @@
"connecting": "Connecting…",
"manage": "Manage",
"connectNotAllowed": "Only admins and managers can connect a source."
+ },
+ "pageOpportunities": {
+ "title": "Pages AI engines aren't sending traffic to",
+ "badge": "Google Analytics · {range}",
+ "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": {
+ "revenue": {
+ "by": "by revenue",
+ "column": "Revenue",
+ "explain": "Ranked by the revenue these pages produced."
+ },
+ "transactions": {
+ "by": "by orders",
+ "column": "Orders",
+ "explain": "Ranked by how many orders started on these pages."
+ },
+ "key_events": {
+ "by": "by conversions",
+ "column": "Conversions",
+ "explain": "Ranked by the conversions Analytics records on these pages."
+ },
+ "engagement": {
+ "by": "by engagement",
+ "column": "Engagement",
+ "explain": "Ranked by time on page, because this property reports no revenue or conversions. Set up key events in Analytics to rank these by what they earn instead."
+ }
+ },
+ "citation": {
+ "cited": {
+ "label": "Cited",
+ "detail": "{count, plural, one {# citation} other {# citations}} in answers"
+ },
+ "targeted_not_cited": {
+ "label": "Not cited",
+ "detail": "{count, plural, one {# prompt targets} other {# prompts target}} this page"
+ },
+ "not_targeted": {
+ "label": "No prompt",
+ "detail": "nothing you track points here"
+ }
+ }
}
},
"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.tsx
new file mode 100644
index 000000000..b557fd80f
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsx
@@ -0,0 +1,152 @@
+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';
+
+/**
+ * AT-002: "Pages AI engines aren't sending traffic to" reads the range the
+ * page shows, says which range in its badge, and stays put with a note when
+ * nothing in that range qualifies.
+ */
+
+const getPageOpportunities = vi.fn();
+vi.mock('@/lib/actions/traffic', () => ({
+ getPageOpportunities: (...args: unknown[]) => getPageOpportunities(...args),
+}));
+
+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 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;
+
+beforeEach(() => {
+ getPageOpportunities.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) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <PageOpportunitiesCard brandId="b1" dateWindow={dateWindow} rangeLabel={rangeLabel} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const resolveWith = (result: PageOpportunities) => getPageOpportunities.mockResolvedValue(result);
+
+describe('PageOpportunitiesCard', () => {
+ it("asks for the page's range and names it in the badge", async () => {
+ resolveWith({ pages: 30, rows: [finding()] });
+ await render(WEEK, 'last 7 days');
+
+ expect(getPageOpportunities).toHaveBeenCalledWith('b1', WEEK);
+ expect(container.textContent).toContain('Google Analytics · last 7 days');
+ expect(container.textContent).not.toContain('28 days');
+ expect(container.textContent).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(container.textContent).toContain('Google Analytics · last 30 days');
+ expect(container.textContent).toContain('/demo');
+ expect(container.textContent).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('Google Analytics · 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');
+
+ const text = container.textContent ?? '';
+ 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(container.textContent).toContain('Google Analytics · last 24 hours');
+ expect(container.textContent).toContain(
+ 'No high-value pages without AI traffic in this range.',
+ );
+ expect(container.querySelector('table')).toBeNull();
+ });
+
+ it('renders nothing when Analytics has no data for the range', async () => {
+ resolveWith({ pages: 0, rows: [] });
+ await render(WEEK, 'last 7 days');
+ expect(container.innerHTML).toBe('');
+ });
+
+ it('renders nothing when the read fails, and leaves the page alone', 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.tsx
index a5d2c4689..66c6e168d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx
@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
@@ -12,197 +13,180 @@ import {
TableRow,
} from '@/components/ui/table';
import { Target } from 'lucide-react';
-import { getPageOpportunities, type PageOpportunity } from '@/lib/actions/traffic';
+import { cn } from '@/lib/utils';
+import {
+ getPageOpportunities,
+ type PageOpportunities,
+ type PageOpportunity,
+ type TrafficDateWindow,
+} from '@/lib/actions/traffic';
/**
- * Pages that carry weight and get nothing from AI engines (#719).
- *
- * Reads the nightly detection run rather than computing anything: the
- * ranking, the signal and the evidence were decided server-side, and
- * recomputing them here would let the card disagree with what the engine
- * stored.
+ * Pages that carry weight and get nothing from AI engines (#719), for the
+ * range the page shows (AT-002).
*
- * Renders nothing at all when there are no findings — a brand without a
- * mapped Analytics property should not meet an empty card explaining a
- * feature it has not connected.
- */
-
-/**
- * How the ranking is described, in the words of the metric that produced it.
+ * 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.
*
- * The engine ranks on whatever the property reports — money where there is
- * money, engagement where there is not — and this is the half that keeps the
- * page honest about which. Calling an engagement rank "your most valuable
- * page" would be a true sentence about the wrong thing.
+ * Renders nothing when Analytics has no data for the range — a brand
+ * without a mapped Analytics property should not meet an empty card
+ * explaining a feature it has not connected. With data but no finding, it
+ * says so, so the card doesn't vanish as the range changes.
*/
-const SIGNAL_COPY: Record<
- PageOpportunity['valueSignal'],
- { label: string; column: string; explain: string }
-> = {
- revenue: {
- label: 'by revenue',
- column: 'Revenue',
- explain: 'Ranked by the revenue these pages produced.',
- },
- transactions: {
- label: 'by orders',
- column: 'Orders',
- explain: 'Ranked by how many orders started on these pages.',
- },
- key_events: {
- label: 'by conversions',
- column: 'Conversions',
- explain: 'Ranked by the conversions Analytics records on these pages.',
- },
- engagement: {
- label: 'by engagement',
- column: 'Engagement',
- explain:
- 'Ranked by time on page, because this property reports no revenue or conversions. Set up key events in Analytics to rank these by what they earn instead.',
- },
-};
/**
- * Why a page that earns gets nothing from AI engines.
+ * 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.
*
- * The three states need three different actions, and the card exists to say
- * which. 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. Presenting them
- * identically — which this card did until the engine could tell them apart —
- * sends two customers in three to fix 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.
*/
-const CITATION_COPY: Record<
- Exclude<PageOpportunity['citationState'], null>,
- { label: string; detail: (row: PageOpportunity) => string }
-> = {
- cited: {
- label: 'Cited',
- detail: (row) =>
- `${row.citations.toLocaleString()} citation${row.citations === 1 ? '' : 's'} in answers`,
- },
- targeted_not_cited: {
- label: 'Not cited',
- detail: (row) =>
- `${row.targetingPrompts} prompt${row.targetingPrompts === 1 ? '' : 's'} target this page`,
- },
- not_targeted: {
- label: 'No prompt',
- detail: () => 'nothing you track points here',
- },
-};
-function signalValue(row: PageOpportunity): string {
+/** 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 row.revenue.toLocaleString();
if (row.valueSignal === 'transactions') return row.transactions.toLocaleString();
if (row.valueSignal === 'key_events') return row.keyEvents.toLocaleString();
- const minutes = Math.round(row.engagementSeconds / 60);
- return `${minutes.toLocaleString()} min`;
+ return inMinutes(Math.round(row.engagementSeconds / 60).toLocaleString());
}
-export function PageOpportunitiesCard({ brandId }: { brandId: string }) {
- // The loaded rows carry the brand they belong to, rather than a separate
- // loading flag reset inside the effect: resetting state synchronously there
- // costs a cascading render, and comparing the stored brand answers the same
- // question — whose data is this — without one.
- const [loaded, setLoaded] = useState<{ brandId: string; rows: PageOpportunity[] } | null>(null);
+/** 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,
+}: {
+ brandId: string;
+ dateWindow: TrafficDateWindow;
+ /** The page's own words for the range, e.g. "last 7 days". */
+ rangeLabel: string;
+}) {
+ const t = useTranslations('traffic.pageOpportunities');
+ 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;
+ result: PageOpportunities;
+ } | null>(null);
useEffect(() => {
let cancelled = false;
- getPageOpportunities(brandId)
- .then((rows) => {
- if (!cancelled) setLoaded({ brandId, rows });
+ 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, rows: [] });
+ if (!cancelled) {
+ setLoaded({ brandId, windowKey, rangeLabel, result: { pages: 0, rows: [] } });
+ }
});
return () => {
cancelled = true;
};
- }, [brandId]);
+ }, [brandId, dateWindow, windowKey, rangeLabel]);
- // While a brand switch is in flight the previous brand's findings must not
- // render under the new brand's name.
- if (loaded?.brandId !== brandId || loaded.rows.length === 0) 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.
+ if (loaded?.brandId !== brandId || loaded.result.pages === 0) return null;
+ const stale = loaded.windowKey !== windowKey;
- const rows = loaded.rows;
- const copy = SIGNAL_COPY[rows[0].valueSignal];
- const windowDays = rows[0].windowDays;
+ const { rows } = loaded.result;
+ const signal = rows[0]?.valueSignal;
return (
- <Card>
+ <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" />
- Pages AI engines aren&apos;t sending traffic to
+ {t('title')}
</CardTitle>
<Badge variant="outline" className="text-xs">
- Google Analytics · last {windowDays} days
+ {t('badge', { range: loaded.rangeLabel })}
</Badge>
</div>
<p className="text-xs text-muted-foreground">
- {copy.explain} None of these received a visit from an AI assistant in the window, and{' '}
- <span className="font-medium">AI visibility</span> says why: whether answers already cite
- the page, whether a prompt you track points at it, or whether nothing does.
+ {signal
+ ? t.rich('explain', {
+ ranking: t(`signals.${signal}.explain`),
+ b: (chunks) => <span className="font-medium">{chunks}</span>,
+ })
+ : t('empty')}
</p>
</CardHeader>
- <CardContent className="p-0">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="pl-6">Page</TableHead>
- <TableHead>AI visibility</TableHead>
- <TableHead className="text-right">Sessions</TableHead>
- <TableHead className="text-right">{copy.column}</TableHead>
- <TableHead className="text-right pr-6">Rank {copy.label}</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>
- {/* Null on findings raised before the classification landed:
- the next nightly run fills them, and saying nothing beats
- guessing which of the three they are. */}
- {row.citationState ? (
+ {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"
>
- {CITATION_COPY[row.citationState].label}
+ {t(`citation.${row.citationState}.label`)}
</Badge>
<div className="text-[10px] text-muted-foreground">
- {CITATION_COPY[row.citationState].detail(row)}
+ {t(`citation.${row.citationState}.detail`, { count: citationCount(row) })}
</div>
</div>
- ) : (
- <span className="text-xs text-muted-foreground">&mdash;</span>
- )}
- </TableCell>
- <TableCell className="text-right tabular-nums text-sm">
- {row.sessions.toLocaleString()}
- </TableCell>
- <TableCell className="text-right font-semibold tabular-nums text-sm">
- {signalValue(row)}
- </TableCell>
- <TableCell className="text-right pr-6 tabular-nums text-sm text-muted-foreground">
- #{row.valueRank}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </CardContent>
+ </TableCell>
+ <TableCell className="text-right tabular-nums text-sm">
+ {row.sessions.toLocaleString()}
+ </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/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index a93c66d4b..e05442237 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -809,12 +809,17 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</Card>
</div>
- {/* Findings from the Analytics connection (#719). Renders nothing
- for brands without a mapped property, so the page is unchanged
- for everyone who has not connected one. Kept visually distinct
- from the tables above, which count the tracking snippet's own
- visits — the two origins are never summed. */}
- <PageOpportunitiesCard brandId={brand.id} />
+ {/* Findings from the Analytics connection (#719), for the page's
+ range (AT-002). Renders nothing for brands without Analytics
+ data in it, so the page is unchanged for everyone who has not
+ connected one. Kept visually distinct from the tables above,
+ which count the tracking snippet's own visits — the two origins
+ are never summed; a page the snippet saw is just never listed. */}
+ <PageOpportunitiesCard
+ brandId={brand.id}
+ dateWindow={dateWindow}
+ rangeLabel={rangeSubLabel}
+ />
{/* Recent Visit Log with filtering and pagination*/}
<Card>
diff --git a/web/src/lib/actions/traffic-page-opportunities.test.ts b/web/src/lib/actions/traffic-page-opportunities.test.ts
new file mode 100644
index 000000000..4ded444a0
--- /dev/null
+++ b/web/src/lib/actions/traffic-page-opportunities.test.ts
@@ -0,0 +1,123 @@
+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.ts b/web/src/lib/actions/traffic.ts
index e8cfee46d..f499dbef5 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -1,7 +1,8 @@
'use server';
import { createClient } from '@/lib/supabase/server';
-import { expandDateToEndOfDay } from '@/lib/dates';
+import { API_BASE_URL } from '@/config/api';
+import { expandDateToEndOfDay, utcDay } from '@/lib/dates';
import { getSuggestionSourceStates, type SourceState } from '@/lib/actions/integrations';
export interface TrafficDateWindow {
@@ -370,15 +371,13 @@ export async function getTrafficLogs(
}
/**
- * Pages that carry commercial weight and get nothing from AI engines (#719).
+ * 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.
*
- * Read straight from the detection engine's table — the ranking, the signal
- * and the evidence were all decided server-side during the nightly run, so
- * this reads them rather than recomputing anything.
- *
- * Deliberately unfiltered by the page's date range: the findings describe the
- * engine's own 28-day window, and re-scoping them to an arbitrary range would
- * mean showing a ranking that was never computed for it.
+ * 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.
*/
export interface PageOpportunity {
landingPage: string;
@@ -392,52 +391,66 @@ export interface PageOpportunity {
transactions: number;
revenue: number;
engagementSeconds: number;
- windowDays: number;
- firstDetectedAt: string;
/**
* Why this page gets nothing from AI engines — cited anyway, targeted by a
- * prompt and not cited, or not targeted at all. Null on findings raised
- * before the classification existed; the next nightly run fills them.
+ * prompt and not cited, or not targeted at all.
*/
- citationState: 'cited' | 'targeted_not_cited' | 'not_targeted' | null;
+ citationState: 'cited' | 'targeted_not_cited' | 'not_targeted';
citations: number;
citingPrompts: number;
targetingPrompts: number;
}
+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 async function getPageOpportunities(
brandId: string,
- opts?: { limit?: number },
-): Promise<PageOpportunity[]> {
+ window?: TrafficDateWindow,
+): Promise<PageOpportunities> {
const supabase = await createClient();
- const { data, error } = await supabase
- .from('page_opportunities')
- .select(
- 'landing_page, value_signal, value_percentile, value_rank, sessions, engaged_sessions, key_events, transactions, revenue, engagement_seconds, window_days, first_detected_at, citation_state, citations, citing_prompts, targeting_prompts',
- )
- .eq('brand_id', brandId)
- .is('resolved_at', null)
- .order('value_percentile', { ascending: false })
- .limit(opts?.limit ?? 10);
-
- if (error) throw new Error(error.message);
+ 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);
+
+ 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}`);
- return (data ?? []).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,
- 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,
- windowDays: Number(row.window_days) || 0,
- firstDetectedAt: row.first_detected_at as string,
- citationState: row.citation_state as PageOpportunity['citationState'],
- citations: Number(row.citations) || 0,
- citingPrompts: Number(row.citing_prompts) || 0,
- targetingPrompts: Number(row.targeting_prompts) || 0,
- }));
+ const findings = (body.findings ?? []) as Record<string, unknown>[];
+ 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,
+ 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,
+ })),
+ };
}
diff --git a/web/src/lib/dates.test.ts b/web/src/lib/dates.test.ts
new file mode 100644
index 000000000..122e832ad
--- /dev/null
+++ b/web/src/lib/dates.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+import { expandDateToEndOfDay, utcDay } from './dates';
+
+describe('expandDateToEndOfDay', () => {
+ it('takes a bare day to its last millisecond and leaves a timestamp alone', () => {
+ expect(expandDateToEndOfDay('2026-05-31')).toBe('2026-05-31T23:59:59.999Z');
+ expect(expandDateToEndOfDay('2026-05-31T15:30:00Z')).toBe('2026-05-31T15:30:00Z');
+ expect(expandDateToEndOfDay(undefined)).toBeUndefined();
+ });
+});
+
+describe('utcDay', () => {
+ it('gives the UTC day a timestamp falls on', () => {
+ expect(utcDay('2026-10-11T09:30:00.000Z')).toBe('2026-10-11');
+ expect(utcDay('2026-10-17T23:59:59.999Z')).toBe('2026-10-17');
+ // An offset moves it to the day it is in UTC.
+ expect(utcDay('2026-10-12T01:00:00+03:00')).toBe('2026-10-11');
+ });
+
+ it('returns a bare day as it is', () => {
+ expect(utcDay('2026-10-11')).toBe('2026-10-11');
+ });
+
+ it('gives undefined for nothing or something unparseable', () => {
+ expect(utcDay(undefined)).toBeUndefined();
+ expect(utcDay(null)).toBeUndefined();
+ expect(utcDay('')).toBeUndefined();
+ expect(utcDay('not a date')).toBeUndefined();
+ });
+});
diff --git a/web/src/lib/dates.ts b/web/src/lib/dates.ts
index cf4945647..575ff6dd7 100644
--- a/web/src/lib/dates.ts
+++ b/web/src/lib/dates.ts
@@ -14,3 +14,15 @@ export function expandDateToEndOfDay(d?: string | null): string | undefined {
if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return `${d}T23:59:59.999Z`;
return d;
}
+
+/**
+ * The UTC calendar day (`YYYY-MM-DD`) a timestamp falls on, for reads over
+ * data stored by whole days, like the Analytics sync's. A bare day is
+ * returned as it is; nothing, or something unparseable, gives undefined.
+ */
+export function utcDay(d?: string | null): string | undefined {
+ if (!d) return undefined;
+ if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return d;
+ const ms = Date.parse(d);
+ return Number.isNaN(ms) ? undefined : new Date(ms).toISOString().slice(0, 10);
+}