Skip to content

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

feat(traffic): count AI visits from the snippet and Google Analytics, day by day (#1167)

Cihan615c48c7c344
diff --git a/supabase/migrations/00176_ai_traffic_merged.sql b/supabase/migrations/00176_ai_traffic_merged.sql
new file mode 100644
index 000000000..988e8393f
--- /dev/null
+++ b/supabase/migrations/00176_ai_traffic_merged.sql
@@ -0,0 +1,130 @@
+-- ============================================================================
+-- 00176: AI traffic from the snippet and Google Analytics, day by day (AT-004)
+-- ============================================================================
+-- The AI Traffic page counted only the tracking snippet, so a brand saw no
+-- history from before it installed the snippet, and nothing for days the
+-- snippet was missing, although Google Analytics had those visits. Spec §5.2:
+-- the snippet is the primary source for days when it was active; Google
+-- Analytics fills the history before installation and any days the snippet
+-- was missing. The two are never added together.
+--
+-- A UTC day is the snippet's when the brand has at least one snippet visit
+-- that day; any other day is Google Analytics' (its AI sessions, as
+-- ga_ai_traffic_stats stores them). Both now name engines by the same keys
+-- (00175), so a day's platforms read the same whichever origin it came from.
+--
+-- * The window is [p_from, p_to] (p_to included unless p_to_inclusive is
+-- false, as the previous period ends where the current one starts; a
+-- null p_from reads from the start, a null p_to up to now). Snippet visits are counted by their
+-- time; Analytics counts whole days, so it fills only the days fully
+-- inside the window — the partial first day is left to the snippet — up
+-- to p_to's day, today included.
+-- * p_analytics = false reads the snippet alone: the 24-hour range trends
+-- hour by hour, which Analytics can't fill.
+-- * Pages are keyed by normalize_page_path (path, no query or trailing
+-- slash), so a snippet URL and an Analytics landing page name one page.
+--
+-- Returns one jsonb value — no row cap applies — with the visits, the
+-- snippet's pageviews in the window, the days Analytics filled, and the
+-- visits by platform, by page and by day and platform. Security invoker: the
+-- tables' member select policies decide whose brand it reads.
+
+create or replace function public.ai_traffic_merged(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz,
+ p_to_inclusive boolean default true,
+ p_analytics boolean default true
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with bounds as (
+ select
+ -- The first whole UTC day inside the window.
+ case
+ when p_from is null then null
+ when (p_from at time zone 'utc')::time = time '00:00' then (p_from at time zone 'utc')::date
+ else (p_from at time zone 'utc')::date + 1
+ end as first_day,
+ coalesce((p_to at time zone 'utc')::date, (now() at time zone 'utc')::date) as last_day
+ ),
+ snippet as (
+ select
+ (l.created_at at time zone 'utc')::date as day,
+ coalesce(nullif(l.source_platform, ''), 'unknown') as platform,
+ public.normalize_page_path(l.url) as page
+ 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 or (p_to_inclusive and l.created_at = p_to))
+ ),
+ -- Days the snippet was active, over the whole day, not just the window.
+ snippet_days as (
+ select distinct (l.created_at at time zone 'utc')::date as day
+ from public.ai_traffic_logs l, bounds b
+ where p_analytics
+ and l.brand_id = p_brand_id
+ and l.visit_of is null
+ and l.created_at >= coalesce((b.first_day::timestamp at time zone 'utc'), '-infinity'::timestamptz)
+ and l.created_at < ((b.last_day + 1)::timestamp at time zone 'utc')
+ ),
+ analytics as (
+ select
+ g.date as day,
+ coalesce(g.platform, g.source) as platform,
+ public.normalize_page_path(g.landing_page) as page,
+ g.sessions as visits
+ from public.ga_ai_traffic_stats g, bounds b
+ where p_analytics
+ and g.brand_id = p_brand_id
+ and g.sessions > 0
+ and g.date >= coalesce(b.first_day, '-infinity'::date)
+ and g.date <= b.last_day
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ merged as (
+ select day, platform, page, 1::bigint as visits, 'snippet' as origin from snippet
+ union all
+ select day, platform, page, visits::bigint, 'analytics' from analytics
+ )
+ select jsonb_build_object(
+ 'visits', (select coalesce(sum(visits), 0) from merged),
+ 'pageviews', (
+ select count(*)
+ from public.ai_traffic_logs l
+ where l.brand_id = p_brand_id
+ and l.created_at >= coalesce(p_from, '-infinity'::timestamptz)
+ and (p_to is null or l.created_at < p_to or (p_to_inclusive and l.created_at = p_to))
+ ),
+ 'analytics_days', (
+ select coalesce(jsonb_agg(distinct day order by day), '[]'::jsonb) from analytics
+ ),
+ 'platforms', (
+ select coalesce(jsonb_agg(jsonb_build_object('platform', platform, 'visits', visits) order by visits desc, platform), '[]'::jsonb)
+ from (select platform, sum(visits) as visits from merged group by platform) t
+ ),
+ 'pages', (
+ select coalesce(jsonb_agg(jsonb_build_object('page', page, 'visits', visits) order by visits desc, page), '[]'::jsonb)
+ from (select page, sum(visits) as visits from merged group by page) t
+ ),
+ 'days', (
+ select coalesce(jsonb_agg(jsonb_build_object('day', day, 'platform', platform, 'visits', visits) order by day, platform), '[]'::jsonb)
+ from (select day, platform, sum(visits) as visits from merged group by day, platform) t
+ )
+ );
+$$;
+
+revoke all on function public.ai_traffic_merged(uuid, timestamptz, timestamptz, boolean, boolean)
+ from public, anon;
+grant execute on function public.ai_traffic_merged(uuid, timestamptz, timestamptz, boolean, boolean)
+ to authenticated, service_role;
+
+comment on function public.ai_traffic_merged(uuid, timestamptz, timestamptz, boolean, boolean) is
+ 'AI Traffic (AT-004, spec §5.2): AI-referred visits for one brand in a window, from the tracking snippet on days it was active and from Google Analytics on other whole days, never summed. Returns visits, the snippet''s pageviews, the days Analytics filled, and visits by platform, page and day. Security invoker: RLS decides the brand.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 3476a2d0a..e57a77aab 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -23660,3 +23660,137 @@ from (
) as m (raw, key)
where lower(t.source_platform) = m.raw;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00176_ai_traffic_merged.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00176: AI traffic from the snippet and Google Analytics, day by day (AT-004)
+-- ============================================================================
+-- The AI Traffic page counted only the tracking snippet, so a brand saw no
+-- history from before it installed the snippet, and nothing for days the
+-- snippet was missing, although Google Analytics had those visits. Spec §5.2:
+-- the snippet is the primary source for days when it was active; Google
+-- Analytics fills the history before installation and any days the snippet
+-- was missing. The two are never added together.
+--
+-- A UTC day is the snippet's when the brand has at least one snippet visit
+-- that day; any other day is Google Analytics' (its AI sessions, as
+-- ga_ai_traffic_stats stores them). Both now name engines by the same keys
+-- (00175), so a day's platforms read the same whichever origin it came from.
+--
+-- * The window is [p_from, p_to] (p_to included unless p_to_inclusive is
+-- false, as the previous period ends where the current one starts; a
+-- null p_from reads from the start, a null p_to up to now). Snippet visits are counted by their
+-- time; Analytics counts whole days, so it fills only the days fully
+-- inside the window — the partial first day is left to the snippet — up
+-- to p_to's day, today included.
+-- * p_analytics = false reads the snippet alone: the 24-hour range trends
+-- hour by hour, which Analytics can't fill.
+-- * Pages are keyed by normalize_page_path (path, no query or trailing
+-- slash), so a snippet URL and an Analytics landing page name one page.
+--
+-- Returns one jsonb value — no row cap applies — with the visits, the
+-- snippet's pageviews in the window, the days Analytics filled, and the
+-- visits by platform, by page and by day and platform. Security invoker: the
+-- tables' member select policies decide whose brand it reads.
+
+create or replace function public.ai_traffic_merged(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz,
+ p_to_inclusive boolean default true,
+ p_analytics boolean default true
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with bounds as (
+ select
+ -- The first whole UTC day inside the window.
+ case
+ when p_from is null then null
+ when (p_from at time zone 'utc')::time = time '00:00' then (p_from at time zone 'utc')::date
+ else (p_from at time zone 'utc')::date + 1
+ end as first_day,
+ coalesce((p_to at time zone 'utc')::date, (now() at time zone 'utc')::date) as last_day
+ ),
+ snippet as (
+ select
+ (l.created_at at time zone 'utc')::date as day,
+ coalesce(nullif(l.source_platform, ''), 'unknown') as platform,
+ public.normalize_page_path(l.url) as page
+ 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 or (p_to_inclusive and l.created_at = p_to))
+ ),
+ -- Days the snippet was active, over the whole day, not just the window.
+ snippet_days as (
+ select distinct (l.created_at at time zone 'utc')::date as day
+ from public.ai_traffic_logs l, bounds b
+ where p_analytics
+ and l.brand_id = p_brand_id
+ and l.visit_of is null
+ and l.created_at >= coalesce((b.first_day::timestamp at time zone 'utc'), '-infinity'::timestamptz)
+ and l.created_at < ((b.last_day + 1)::timestamp at time zone 'utc')
+ ),
+ analytics as (
+ select
+ g.date as day,
+ coalesce(g.platform, g.source) as platform,
+ public.normalize_page_path(g.landing_page) as page,
+ g.sessions as visits
+ from public.ga_ai_traffic_stats g, bounds b
+ where p_analytics
+ and g.brand_id = p_brand_id
+ and g.sessions > 0
+ and g.date >= coalesce(b.first_day, '-infinity'::date)
+ and g.date <= b.last_day
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ merged as (
+ select day, platform, page, 1::bigint as visits, 'snippet' as origin from snippet
+ union all
+ select day, platform, page, visits::bigint, 'analytics' from analytics
+ )
+ select jsonb_build_object(
+ 'visits', (select coalesce(sum(visits), 0) from merged),
+ 'pageviews', (
+ select count(*)
+ from public.ai_traffic_logs l
+ where l.brand_id = p_brand_id
+ and l.created_at >= coalesce(p_from, '-infinity'::timestamptz)
+ and (p_to is null or l.created_at < p_to or (p_to_inclusive and l.created_at = p_to))
+ ),
+ 'analytics_days', (
+ select coalesce(jsonb_agg(distinct day order by day), '[]'::jsonb) from analytics
+ ),
+ 'platforms', (
+ select coalesce(jsonb_agg(jsonb_build_object('platform', platform, 'visits', visits) order by visits desc, platform), '[]'::jsonb)
+ from (select platform, sum(visits) as visits from merged group by platform) t
+ ),
+ 'pages', (
+ select coalesce(jsonb_agg(jsonb_build_object('page', page, 'visits', visits) order by visits desc, page), '[]'::jsonb)
+ from (select page, sum(visits) as visits from merged group by page) t
+ ),
+ 'days', (
+ select coalesce(jsonb_agg(jsonb_build_object('day', day, 'platform', platform, 'visits', visits) order by day, platform), '[]'::jsonb)
+ from (select day, platform, sum(visits) as visits from merged group by day, platform) t
+ )
+ );
+$$;
+
+revoke all on function public.ai_traffic_merged(uuid, timestamptz, timestamptz, boolean, boolean)
+ from public, anon;
+grant execute on function public.ai_traffic_merged(uuid, timestamptz, timestamptz, boolean, boolean)
+ to authenticated, service_role;
+
+comment on function public.ai_traffic_merged(uuid, timestamptz, timestamptz, boolean, boolean) is
+ 'AI Traffic (AT-004, spec §5.2): AI-referred visits for one brand in a window, from the tracking snippet on days it was active and from Google Analytics on other whole days, never summed. Returns visits, the snippet''s pageviews, the days Analytics filled, and visits by platform, page and day. Security invoker: RLS decides the brand.';
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index dd9e87faa..fb0b074a0 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3185,15 +3185,21 @@
"visits": {
"kpiSub": "{pageviews, plural, one {# pageview} other {# pageviews}} · {previous, number} in the previous period",
"kpiSubNoPrevious": "{pageviews, plural, one {# pageview} other {# pageviews}}",
+ "kpiSubAnalytics": "{previous, number} in the previous period · {days, plural, one {# day} other {# days}} from Google Analytics",
+ "kpiSubAnalyticsNoPrevious": "{days, plural, one {# day} other {# days}} from Google Analytics",
"listTotal": "{visits, plural, one {# visit} other {# visits}} ({pageviews, plural, one {# pageview} other {# pageviews}})",
"rowPageviews": "{count, plural, one {# pageview} other {# pageviews}}",
"listNote": "One row per visit (session). Repeated pageviews in the same visit are grouped.",
+ "listAnalyticsNote": "Google Analytics doesn't report single visits: this list shows the tracking snippet's, while the totals above also count {days, plural, one {# day} other {# days}} from Google Analytics.",
"listRange": "{visits, plural, one {# visit} other {# visits}} ({pageviews, plural, one {# pageview} other {# pageviews}}) {preset, select, last {in the {range}} other {· {range}}}",
"showLast7Days": "Show last 7 days"
},
+ "trend": {
+ "fromAnalytics": "from Google Analytics"
+ },
"kpis": {
"visits": "AI-referred visits",
- "visitsTip": "Visits from AI assistants, counted once per session by the tracking snippet. Below 30 visits in this period or the one before, the change shows Low sample.",
+ "visitsTip": "Visits from AI assistants, one per session: from the tracking snippet on days it sent any, and from Google Analytics on the other days, never added together. Below 30 visits in this period or the one before, the change shows Low sample.",
"topPlatform": "Top platform",
"topPlatformTip": "The AI platform that sent the most visits in this range.",
"topPlatformSub": "{visits, plural, one {# visit} other {# visits}}",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts-tooltip.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts-tooltip.test.tsx
new file mode 100644
index 000000000..eae4fabaa
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts-tooltip.test.tsx
@@ -0,0 +1,54 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import { AreaTooltip } from './_charts';
+
+/**
+ * AT-004: the trend's tooltip names a day whose visits came from Google
+ * Analytics rather than the snippet.
+ */
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+function render(label: string) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <AreaTooltip
+ active
+ label={label}
+ payload={[{ name: 'chatgpt.com', value: 5, color: '#6366f1' }]}
+ analyticsDays={new Set(['2026-10-12'])}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+ return container.textContent ?? '';
+}
+
+describe('the trend tooltip', () => {
+ it('says a day came from Google Analytics', () => {
+ expect(render('2026-10-12')).toBe('Oct 12 · from Google AnalyticsChatGPT:5');
+ });
+
+ it('says nothing more for a day from the snippet', () => {
+ expect(render('2026-10-13')).toBe('Oct 13ChatGPT:5');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
index 93c94571b..29605d6ec 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
@@ -1,6 +1,7 @@
'use client';
import { useRef, useState, useEffect } from 'react';
+import { useTranslations } from 'next-intl';
import { getPlatformName } from '@/lib/traffic-platforms';
import { formatNumber } from '@/lib/format';
import {
@@ -121,20 +122,27 @@ export function formatTrafficBucketDate(
// ─── Custom Tooltips ──────────────────────────────────────────────────────────
-function AreaTooltip({
+export function AreaTooltip({
active,
payload,
label,
+ analyticsDays,
}: {
active?: boolean;
payload?: { name: string; value: number; color: string }[];
label?: string;
+ /** Days whose visits came from Google Analytics rather than the snippet (AT-004). */
+ analyticsDays?: Set<string>;
}) {
+ const t = useTranslations('traffic.trend');
if (!active || !payload?.length) return null;
return (
<div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">
<p className="font-medium text-foreground mb-1">
{label ? formatTrafficBucketDate(label, { withDay: true }) : ''}
+ {label && analyticsDays?.has(label) && (
+ <span className="font-normal text-muted-foreground"> · {t('fromAnalytics')}</span>
+ )}
</p>
{payload.map((entry) => (
<div key={entry.name} className="flex items-center gap-2">
@@ -202,8 +210,16 @@ function BarList({ data }: { data: { name: string; value: number; color: string
// ─── Exported Charts ──────────────────────────────────────────────────────────
-export function ReferralTrendChart({ data }: { data: TrafficTrendPoint[] }) {
+export function ReferralTrendChart({
+ data,
+ analyticsDays,
+}: {
+ data: TrafficTrendPoint[];
+ /** Days filled from Google Analytics, named in the tooltip (AT-004). */
+ analyticsDays?: string[];
+}) {
if (!data.length) return null;
+ const fromAnalytics = new Set(analyticsDays);
// Extract platform keys (everything except 'date')
const platformKeys = Object.keys(data[0]).filter((k) => k !== 'date');
@@ -241,7 +257,7 @@ export function ReferralTrendChart({ data }: { data: TrafficTrendPoint[] }) {
className="fill-muted-foreground"
allowDecimals={false}
/>
- <Tooltip content={<AreaTooltip />} />
+ <Tooltip content={<AreaTooltip analyticsDays={fromAnalytics} />} />
<Legend
iconType="circle"
iconSize={8}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
index 266968ff7..c3d112383 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
@@ -56,6 +56,7 @@ const summary = (over: Partial<TrafficSummary> = {}): TrafficSummary => ({
totalVisits: 4,
totalVisitsPrev: 3,
totalPageviews: 7,
+ analyticsDays: [],
hasPreviousPeriod: true,
platformBreakdown: [
{ platform: 'gemini.google.com', visits: 2, visitsPrev: 1 },
@@ -172,6 +173,25 @@ describe('TrafficKpis', () => {
expect(card('Platforms')).toContain('3unique AI sources');
});
+ it('says how many days came from Google Analytics instead of a partial pageview count (AT-004)', async () => {
+ await render({
+ preset: '30d',
+ dateWindow: { dateFrom: '2026-09-18T12:30:00.000Z' },
+ sum: summary({ analyticsDays: ['2026-10-01', '2026-10-02', '2026-10-03'] }),
+ });
+ expect(card('AI-referred visits')).toContain(
+ '3 in the previous period · 3 days from Google Analytics',
+ );
+ expect(card('AI-referred visits')).not.toContain('pageviews');
+
+ await render({
+ preset: 'all',
+ dateWindow: {},
+ sum: summary({ analyticsDays: ['2026-10-01'], hasPreviousPeriod: false }),
+ });
+ expect(card('AI-referred visits')).toContain('1 day from Google Analytics');
+ });
+
it('shows a % change once both periods have 30 visits', async () => {
await render({ sum: summary({ totalVisits: 45, totalVisitsPrev: 30 }) });
expect(card('AI-referred visits')).toContain('45+50%');
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
index 391bec556..2ed10e681 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
@@ -156,6 +156,7 @@ export function TrafficKpis({
const totalVisits = summary?.totalVisits ?? 0;
const totalVisitsPrev = summary?.totalVisitsPrev ?? 0;
const totalPageviews = summary?.totalPageviews ?? 0;
+ const analyticsDays = summary?.analyticsDays.length ?? 0;
// From the summary, not the selected range: while a new range loads, the
// numbers on screen are still the previous range's.
const comparable = summary?.hasPreviousPeriod ?? false;
@@ -216,7 +217,10 @@ export function TrafficKpis({
return (
<div className={TRAFFIC_KPI_GRID}>
{/* One visit per session; the sub-line gives the pageviews and the
- previous period's visits (AT-003). */}
+ previous period's visits (AT-003). Google Analytics reports no
+ pageviews, so when it filled any day (AT-004) the line says how
+ many instead of a pageview count that would cover only part of
+ the range. */}
<MetricCard
label={t('visits')}
tooltip={t('visitsTip')}
@@ -224,9 +228,13 @@ export function TrafficKpis({
value={formatNumber(totalVisits)}
delta={delta(visitChange(totalVisits, totalVisitsPrev, { comparable }))}
sub={
- comparable
- ? tVisits('kpiSub', { pageviews: totalPageviews, previous: totalVisitsPrev })
- : tVisits('kpiSubNoPrevious', { pageviews: totalPageviews })
+ analyticsDays > 0
+ ? comparable
+ ? tVisits('kpiSubAnalytics', { previous: totalVisitsPrev, days: analyticsDays })
+ : tVisits('kpiSubAnalyticsNoPrevious', { days: analyticsDays })
+ : comparable
+ ? tVisits('kpiSub', { pageviews: totalPageviews, previous: totalVisitsPrev })
+ : tVisits('kpiSubNoPrevious', { pageviews: totalPageviews })
}
/>
<MetricCard
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_visit-list-note.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_visit-list-note.test.tsx
new file mode 100644
index 000000000..6b1ab56ca
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_visit-list-note.test.tsx
@@ -0,0 +1,53 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import { VisitListSourceNote } from './_visit-list-note';
+
+/**
+ * AT-004: when Google Analytics filled days of the range, the visit list
+ * says it holds the snippet's visits only, so its count can be lower than
+ * the KPI's.
+ */
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+function render(analyticsDays: number) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <VisitListSourceNote analyticsDays={analyticsDays} />
+ </NextIntlClientProvider>,
+ );
+ });
+ return container.textContent ?? '';
+}
+
+describe('VisitListSourceNote', () => {
+ it('says the list is the snippet’s when Google Analytics filled days', () => {
+ expect(render(4)).toBe(
+ "Google Analytics doesn't report single visits: this list shows the tracking snippet's, while the totals above also count 4 days from Google Analytics.",
+ );
+ expect(render(1)).toContain('also count 1 day from Google Analytics');
+ });
+
+ it('says nothing when every day came from the snippet', () => {
+ expect(render(0)).toBe('');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_visit-list-note.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_visit-list-note.tsx
new file mode 100644
index 000000000..c36fd14fb
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_visit-list-note.tsx
@@ -0,0 +1,19 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+
+/**
+ * Under the visit list, when Google Analytics filled any day of the range
+ * (AT-004): the list holds the tracking snippet's visits only — Analytics
+ * reports totals, not single visits — so its count can be lower than the
+ * KPI's, and this says why. Nothing otherwise.
+ */
+export function VisitListSourceNote({ analyticsDays }: { analyticsDays: number }) {
+ const t = useTranslations('traffic.visits');
+ if (analyticsDays <= 0) return null;
+ return (
+ <p className="px-6 pb-1 text-xs text-muted-foreground">
+ {t('listAnalyticsNote', { days: analyticsDays })}
+ </p>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index 50c1bef00..2bf85341a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -38,6 +38,7 @@ import {
} from '@/components/filters/date-range-filter';
import { PageOpportunitiesCard } from './_opportunities-card';
import { TRAFFIC_KPI_GRID, TrafficKpis } from './_kpis';
+import { VisitListSourceNote } from './_visit-list-note';
import { ExportMenu, TableExport, useTrafficExport } from './_export';
import { SourcesStrip } from './_sources-strip';
import { SnippetBanner, SnippetDialog } from './_snippet-code';
@@ -677,7 +678,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
<CardTitle className="font-medium text-sm">{trendTitle}</CardTitle>
</CardHeader>
<CardContent>
- <ReferralTrendChart data={trend} />
+ <ReferralTrendChart data={trend} analyticsDays={summary?.analyticsDays} />
</CardContent>
</Card>
@@ -909,6 +910,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</button>
)}
</div>
+ <VisitListSourceNote analyticsDays={summary?.analyticsDays.length ?? 0} />
<p className="px-6 pb-4 text-xs text-muted-foreground">{tVisits('listNote')}</p>
</>
)}
diff --git a/web/src/lib/actions/traffic-merged.test.ts b/web/src/lib/actions/traffic-merged.test.ts
new file mode 100644
index 000000000..30b111ec8
--- /dev/null
+++ b/web/src/lib/actions/traffic-merged.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * AT-004 (spec §5.2): the AI Traffic page's summary reads the snippet and
+ * Google Analytics day by day through ai_traffic_merged (00176) — the
+ * snippet on days it was active, Analytics on the others, never summed —
+ * for the range and the period before it. The 24-hour range reads the
+ * snippet alone.
+ */
+
+type Merged = {
+ visits: number;
+ pageviews: number;
+ analytics_days: string[];
+ platforms: { platform: string; visits: number }[];
+ pages: { page: string; visits: number }[];
+ days: { day: string; platform: string; visits: number }[];
+};
+
+const CURRENT: Merged = {
+ visits: 167,
+ pageviews: 6,
+ analytics_days: ['2026-10-12', '2026-10-13'],
+ platforms: [
+ { platform: 'chatgpt.com', visits: 116 },
+ { platform: 'perplexity.ai', visits: 47 },
+ { platform: 'gemini.google.com', visits: 4 },
+ ],
+ pages: [
+ { page: '/menu', visits: 115 },
+ { page: '/pricing', visits: 46 },
+ { page: '/faq', visits: 6 },
+ ],
+ days: [],
+};
+const PREVIOUS: Merged = {
+ visits: 40,
+ pageviews: 0,
+ analytics_days: [],
+ platforms: [{ platform: 'chatgpt.com', visits: 40 }],
+ pages: [{ page: '/menu', visits: 40 }],
+ days: [],
+};
+
+const rpc = vi.fn();
+let snippetCount = 0;
+let analyticsRows: { id: string }[] = [];
+
+function query() {
+ const builder: Record<string, unknown> = {};
+ let head = false;
+ for (const method of ['select', 'eq', 'is', 'gt', 'gte', 'lte', 'lt', 'limit']) {
+ builder[method] = (...args: unknown[]) => {
+ if (method === 'select') head = (args[1] as { head?: boolean } | undefined)?.head === true;
+ return builder;
+ };
+ }
+ builder.then = (resolve: (v: unknown) => unknown) =>
+ resolve(head ? { count: snippetCount, error: null } : { data: analyticsRows, error: null });
+ return builder;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ from: () => query(), rpc }),
+}));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
+
+import { getTrafficSummary } from './traffic';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-18T12:30:00.000Z'));
+ rpc.mockReset();
+ rpc.mockImplementation(async (_fn: string, args: { p_to_inclusive: boolean }) => ({
+ data: args.p_to_inclusive ? CURRENT : PREVIOUS,
+ error: null,
+ }));
+ snippetCount = 6;
+ analyticsRows = [];
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('getTrafficSummary', () => {
+ it('reads the range and the period before from the snippet and Google Analytics', async () => {
+ await getTrafficSummary('b1', { dateFrom: '2026-10-11T12:30:00.000Z' });
+
+ expect(rpc).toHaveBeenCalledWith('ai_traffic_merged', {
+ p_brand_id: 'b1',
+ p_from: '2026-10-11T12:30:00.000Z',
+ p_to: '2026-10-18T12:30:00.000Z',
+ p_to_inclusive: true,
+ p_analytics: true,
+ });
+ // The previous period ends where the range starts, without its last moment.
+ expect(rpc).toHaveBeenCalledWith('ai_traffic_merged', {
+ p_brand_id: 'b1',
+ p_from: '2026-10-04T12:30:00.000Z',
+ p_to: '2026-10-11T12:30:00.000Z',
+ p_to_inclusive: false,
+ p_analytics: true,
+ });
+ });
+
+ it('gives the visits, pageviews, Analytics days and breakdowns against the period before', async () => {
+ const summary = await getTrafficSummary('b1', { dateFrom: '2026-10-11T12:30:00.000Z' });
+
+ expect(summary).toMatchObject({
+ totalVisits: 167,
+ totalVisitsPrev: 40,
+ totalPageviews: 6,
+ analyticsDays: ['2026-10-12', '2026-10-13'],
+ hasPreviousPeriod: true,
+ hasAnyData: true,
+ });
+ expect(summary.platformBreakdown).toEqual([
+ { platform: 'chatgpt.com', visits: 116, visitsPrev: 40 },
+ { platform: 'perplexity.ai', visits: 47, visitsPrev: 0 },
+ { platform: 'gemini.google.com', visits: 4, visitsPrev: 0 },
+ ]);
+ expect(summary.topPages[0]).toEqual({ url: '/menu', visits: 115, visitsPrev: 40 });
+ });
+
+ it('keeps the top 10 pages for the page, and all of them for an export', async () => {
+ const pages = Array.from({ length: 12 }, (_, i) => ({ page: `/p${i}`, visits: 12 - i }));
+ rpc.mockResolvedValue({ data: { ...CURRENT, pages }, error: null });
+ const window = { dateFrom: '2026-10-11T12:30:00.000Z' };
+ expect((await getTrafficSummary('b1', window)).topPages).toHaveLength(10);
+ expect(
+ (await getTrafficSummary('b1', window, { topPages: Number.MAX_SAFE_INTEGER })).topPages,
+ ).toHaveLength(12);
+ });
+
+ it('reads the last 24 hours from the snippet alone: Google Analytics has no hours', async () => {
+ await getTrafficSummary('b1', { dateFrom: '2026-10-17T12:30:00.000Z' });
+ for (const [, args] of rpc.mock.calls) expect(args.p_analytics).toBe(false);
+ });
+
+ it('reads all time from the start, with no period before', async () => {
+ const summary = await getTrafficSummary('b1', {});
+ expect(rpc).toHaveBeenCalledTimes(1);
+ expect(rpc).toHaveBeenCalledWith(
+ 'ai_traffic_merged',
+ expect.objectContaining({ p_from: null, p_to: null }),
+ );
+ expect(summary.hasPreviousPeriod).toBe(false);
+ expect(summary.totalVisitsPrev).toBe(0);
+ expect(summary.hasAnyData).toBe(true);
+ });
+
+ it('counts a brand with only Google Analytics history as having data', async () => {
+ rpc.mockResolvedValue({
+ data: { ...CURRENT, visits: 0, platforms: [], pages: [] },
+ error: null,
+ });
+ snippetCount = 0;
+ analyticsRows = [{ id: 'ga1' }];
+ const window = { dateFrom: '2026-10-17T12:30:00.000Z' };
+ expect((await getTrafficSummary('b1', window)).hasAnyData).toBe(true);
+
+ analyticsRows = [];
+ expect((await getTrafficSummary('b1', window)).hasAnyData).toBe(false);
+ });
+
+ it('fails loudly when the read fails', async () => {
+ rpc.mockResolvedValue({ data: null, error: { message: 'permission denied' } });
+ await expect(getTrafficSummary('b1', { dateFrom: '2026-10-11T12:30:00.000Z' })).rejects.toThrow(
+ 'permission denied',
+ );
+ });
+});
diff --git a/web/src/lib/actions/traffic-trend.test.ts b/web/src/lib/actions/traffic-trend.test.ts
index 77d024041..e30c6db32 100644
--- a/web/src/lib/actions/traffic-trend.test.ts
+++ b/web/src/lib/actions/traffic-trend.test.ts
@@ -20,8 +20,20 @@ function query() {
return builder;
}
+// Longer windows read the snippet and Google Analytics day by day (AT-004).
+const rpc = vi.fn(async () => ({
+ data: {
+ days: [
+ { day: '2026-10-12', platform: 'chatgpt.com', visits: 5 },
+ { day: '2026-10-18', platform: 'gemini.google.com', visits: 2 },
+ { day: '2026-10-18', platform: 'chatgpt.com', visits: 1 },
+ ],
+ },
+ error: null,
+}));
+
vi.mock('@/lib/supabase/server', () => ({
- createClient: async () => ({ from: () => query() }),
+ createClient: async () => ({ from: () => query(), rpc }),
}));
vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
@@ -52,9 +64,16 @@ describe('getTrafficTrend', () => {
expect(hour('2026-10-18T11:00:00.000Z')['chatgpt.com']).toBe(1);
});
- it('reads 7 days day by day', async () => {
+ it('reads 7 days day by day, from the snippet or Google Analytics', async () => {
const points = await getTrafficTrend('b1', { dateFrom: '2026-10-11T12:30:00.000Z' });
+ expect(rpc).toHaveBeenCalledWith('ai_traffic_merged', {
+ p_brand_id: 'b1',
+ p_from: '2026-10-11T12:30:00.000Z',
+ p_to: '2026-10-18T12:30:00.000Z',
+ p_to_inclusive: true,
+ p_analytics: true,
+ });
expect(points.map((p) => p.date)).toEqual([
'2026-10-11',
'2026-10-12',
@@ -65,10 +84,17 @@ describe('getTrafficTrend', () => {
'2026-10-17',
'2026-10-18',
]);
+ expect(points[1]).toEqual({ date: '2026-10-12', 'chatgpt.com': 5, 'gemini.google.com': 0 });
expect(points.at(-1)).toEqual({
date: '2026-10-18',
- 'gemini.google.com': 2,
'chatgpt.com': 1,
+ 'gemini.google.com': 2,
});
});
+
+ it('reads 24 hours from the snippet alone: Google Analytics has no hours', async () => {
+ rpc.mockClear();
+ await getTrafficTrend('b1', { dateFrom: '2026-10-17T12:30:00.000Z' });
+ expect(rpc).not.toHaveBeenCalled();
+ });
});
diff --git a/web/src/lib/actions/traffic-visits.test.ts b/web/src/lib/actions/traffic-visits.test.ts
index 14fbe71a6..18f98a735 100644
--- a/web/src/lib/actions/traffic-visits.test.ts
+++ b/web/src/lib/actions/traffic-visits.test.ts
@@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* AT-003: the AI Traffic page counts visits, one per session, and pageviews
- * on their own (F5). A row starts a visit when its `visit_of` is null.
+ * on their own (F5). A row starts a visit when its `visit_of` is null. The
+ * summary counts them in the database since AT-004 (traffic-merged.test.ts).
*/
type Call = [string, ...unknown[]];
@@ -42,7 +43,7 @@ vi.mock('@/lib/supabase/server', () => ({
}));
vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
-import { getTrafficLogs, getTrafficSummary } from './traffic';
+import { getTrafficLogs } from './traffic';
const has = (calls: Call[], method: string, ...args: unknown[]) =>
calls.some(([m, ...rest]) => m === method && args.every((a, i) => Object.is(rest[i], a)));
@@ -123,36 +124,3 @@ describe('getTrafficLogs', () => {
expect(queries).toHaveLength(2);
});
});
-
-describe('getTrafficSummary', () => {
- it('counts visits for the totals, breakdowns and pages, and pageviews on their own', async () => {
- answer = (calls) => {
- if (head(calls)) return { count: visitsOnly(calls) ? 2 : 5, error: null };
- return {
- data: [
- row('v1', 'https://acme.example/menu/'),
- row('v2', 'https://acme.example/menu/', 'chatgpt.com'),
- ],
- error: null,
- };
- };
-
- const summary = await getTrafficSummary('b1', { dateFrom: '2026-10-11T00:00:00Z' });
-
- expect(summary.totalVisits).toBe(2);
- expect(summary.totalPageviews).toBe(5);
- expect(summary.hasPreviousPeriod).toBe(true);
- expect(summary.topPages).toEqual([{ url: '/menu/', visits: 2, visitsPrev: 2 }]);
- // Every scan behind the breakdowns reads the visits only.
- for (const calls of queries.filter((c) => !head(c))) {
- expect(visitsOnly(calls)).toBe(true);
- }
- });
-
- it('has no previous period for all time', async () => {
- answer = (calls) => (head(calls) ? { count: 3, error: null } : { data: [], error: null });
- const summary = await getTrafficSummary('b1', {});
- expect(summary.hasPreviousPeriod).toBe(false);
- expect(summary.totalVisitsPrev).toBe(0);
- });
-});
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index 8a09845c2..f05677560 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -34,8 +34,14 @@ export interface TrafficLog {
export interface TrafficSummary {
totalVisits: number;
totalVisitsPrev: number;
- /** Every pageview in the window, the visits' first ones included. */
+ /**
+ * The snippet's pageviews in the window, the visits' first ones included.
+ * Google Analytics reports none, so on days it filled (AT-004) there are
+ * visits without pageviews.
+ */
totalPageviews: number;
+ /** The UTC days in the window whose visits came from Google Analytics (AT-004). */
+ analyticsDays: string[];
/** False for all time, which has no previous period to compare with. */
hasPreviousPeriod: boolean;
platformBreakdown: { platform: string; visits: number; visitsPrev: number }[];
@@ -145,6 +151,54 @@ function listUtcDays(from: string, to: string): string[] {
return days;
}
+/**
+ * AI-referred visits in a window from the snippet and Google Analytics, day
+ * by day (AT-004, spec §5.2; 00176): a UTC day with a snippet visit is the
+ * snippet's, any other whole day in the window is Analytics'. Never summed.
+ */
+interface MergedTraffic {
+ visits: number;
+ pageviews: number;
+ analyticsDays: string[];
+ platforms: { platform: string; visits: number }[];
+ pages: { page: string; visits: number }[];
+ days: { day: string; platform: string; visits: number }[];
+}
+
+async function readMergedTraffic(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ brandId: string,
+ window: { from?: string; to?: string; toInclusive?: boolean },
+): Promise<MergedTraffic> {
+ // The 24-hour range trends hour by hour, which Analytics can't fill: it
+ // reads the snippet alone (AT-004).
+ const hourly = Boolean(window.from && window.to && isHourlyWindow(window.from, window.to));
+ const { data, error } = await supabase.rpc('ai_traffic_merged', {
+ p_brand_id: brandId,
+ p_from: window.from ?? null,
+ p_to: window.to ?? null,
+ p_to_inclusive: window.toInclusive ?? true,
+ p_analytics: !hourly,
+ });
+ if (error) throw new Error(error.message);
+ const raw = (data ?? {}) as {
+ visits?: number;
+ pageviews?: number;
+ analytics_days?: string[];
+ platforms?: { platform: string; visits: number }[];
+ pages?: { page: string; visits: number }[];
+ days?: { day: string; platform: string; visits: number }[];
+ };
+ return {
+ visits: Number(raw.visits) || 0,
+ pageviews: Number(raw.pageviews) || 0,
+ analyticsDays: raw.analytics_days ?? [],
+ platforms: (raw.platforms ?? []).map((p) => ({ ...p, visits: Number(p.visits) || 0 })),
+ pages: (raw.pages ?? []).map((p) => ({ ...p, visits: Number(p.visits) || 0 })),
+ days: (raw.days ?? []).map((d) => ({ ...d, visits: Number(d.visits) || 0 })),
+ };
+}
+
export async function getTrafficSummary(
brandId: string,
window?: TrafficDateWindow,
@@ -153,92 +207,50 @@ export async function getTrafficSummary(
): Promise<TrafficSummary> {
const supabase = await createClient();
const { from, to, prevFrom, prevTo } = resolveTrafficWindow(window);
-
- // Exact totals — count queries transfer no rows and are immune to the cap.
- const countRows = (
- fromTs?: string,
- toTs?: string,
- toInclusive = false,
- opts?: { visits?: boolean },
- ) => countTrafficLogs(supabase, brandId, { from: fromTs, to: toTs, toInclusive }, opts);
-
- // Platform breakdown + top pages, aggregated per batch.
- const platformMap = new Map<string, number>();
- const platformMapPrev = new Map<string, number>();
- const pageMap = new Map<string, number>();
- const pageMapPrev = new Map<string, number>();
-
- const aggregate = (platforms: Map<string, number>, pages: Map<string, number>) => {
- return (r: Record<string, unknown>) => {
- const p = (r.source_platform as string) || 'unknown';
- platforms.set(p, (platforms.get(p) ?? 0) + 1);
-
- const url = r.url as string;
- let key = url;
- try {
- key = new URL(url).pathname;
- } catch {
- // Not a parseable URL — bucket by the raw value.
- }
- pages.set(key, (pages.get(key) ?? 0) + 1);
- };
- };
-
- const columns = 'source_platform, url, created_at, id';
const hasPrev = Boolean(prevFrom && prevTo);
- // The window is already the full lifetime when neither bound is set, so
- // totalVisits doubles as the lifetime check — only worth a second cheap
- // count query when the window actually narrows the result.
- const hasWindow = Boolean(from || to);
- const [totalVisits, totalVisitsPrev, totalPageviews, , , lifetimeVisits] = await Promise.all([
- countRows(from, to, true),
- hasPrev ? countRows(prevFrom, prevTo) : Promise.resolve(0),
- countRows(from, to, true, { visits: false }),
- scanTrafficLogs(
- supabase,
- brandId,
- { columns, from, to, toInclusive: true },
- aggregate(platformMap, pageMap),
- ),
+
+ // Visits, platforms and pages from the snippet and Google Analytics, day
+ // by day (AT-004), summed in the database: no row cap applies.
+ const [current, previous, lifetime] = await Promise.all([
+ readMergedTraffic(supabase, brandId, { from, to, toInclusive: true }),
hasPrev
- ? scanTrafficLogs(
- supabase,
- brandId,
- { columns, from: prevFrom, to: prevTo },
- aggregate(platformMapPrev, pageMapPrev),
- )
- : Promise.resolve(),
- hasWindow ? countRows() : Promise.resolve(null),
+ ? readMergedTraffic(supabase, brandId, { from: prevFrom, to: prevTo, toInclusive: false })
+ : null,
+ // Whether the brand has any AI traffic at all, from either origin.
+ from || to
+ ? Promise.all([
+ countTrafficLogs(supabase, brandId, {}),
+ supabase
+ .from('ga_ai_traffic_stats')
+ .select('id')
+ .eq('brand_id', brandId)
+ .gt('sessions', 0)
+ .limit(1),
+ ])
+ : null,
]);
+ if (lifetime?.[1].error) throw new Error(lifetime[1].error.message);
+ const hasAnyData = lifetime
+ ? lifetime[0] > 0 || (lifetime[1].data ?? []).length > 0
+ : current.visits > 0;
- const hasAnyData = hasWindow ? (lifetimeVisits as number) > 0 : totalVisits > 0;
-
- const allPlatforms = new Set([...platformMap.keys(), ...platformMapPrev.keys()]);
- const platformBreakdown = Array.from(allPlatforms)
- .map((platform) => ({
- platform,
- visits: platformMap.get(platform) ?? 0,
- visitsPrev: platformMapPrev.get(platform) ?? 0,
- }))
- .filter((p) => p.visits > 0)
- .sort((a, b) => b.visits - a.visits);
-
- const topPages = Array.from(pageMap.entries())
- .map(([url, visits]) => ({
- url,
- visits,
- visitsPrev: pageMapPrev.get(url) ?? 0,
- }))
- .sort((a, b) => b.visits - a.visits)
- .slice(0, opts?.topPages ?? 10);
+ const previousByPlatform = new Map(previous?.platforms.map((p) => [p.platform, p.visits]));
+ const previousByPage = new Map(previous?.pages.map((p) => [p.page, p.visits]));
return {
- totalVisits,
- totalVisitsPrev,
- totalPageviews,
+ totalVisits: current.visits,
+ totalVisitsPrev: previous?.visits ?? 0,
+ totalPageviews: current.pageviews,
+ analyticsDays: current.analyticsDays,
hasPreviousPeriod: hasPrev,
- platformBreakdown,
- topPages,
+ platformBreakdown: current.platforms
+ .filter((p) => p.visits > 0)
+ .map((p) => ({ ...p, visitsPrev: previousByPlatform.get(p.platform) ?? 0 })),
+ topPages: current.pages.slice(0, opts?.topPages ?? 10).map((p) => ({
+ url: p.page,
+ visits: p.visits,
+ visitsPrev: previousByPage.get(p.page) ?? 0,
+ })),
hasAnyData,
};
}
@@ -252,25 +264,29 @@ export async function getTrafficTrend(
// A day or less reads hour by hour (AT-017); longer windows by day.
const hourly = Boolean(from && to && isHourlyWindow(from, to));
- // Group by day (or hour) + platform, aggregated per batch (#450).
+ // Group by day (or hour) + platform.
const dayMap = new Map<string, Map<string, number>>();
const allPlatforms = new Set<string>();
+ const add = (day: string, platform: string, visits: number) => {
+ allPlatforms.add(platform);
+ if (!dayMap.has(day)) dayMap.set(day, new Map());
+ const dm = dayMap.get(day)!;
+ dm.set(platform, (dm.get(platform) ?? 0) + visits);
+ };
- await scanTrafficLogs(
- supabase,
- brandId,
- { columns: 'source_platform, created_at, id', from, to, toInclusive: true },
- (r) => {
- const created = r.created_at as string;
- const day = hourly ? utcHourKey(created) : created.slice(0, 10);
- const platform = (r.source_platform as string) || 'unknown';
- allPlatforms.add(platform);
-
- if (!dayMap.has(day)) dayMap.set(day, new Map());
- const dm = dayMap.get(day)!;
- dm.set(platform, (dm.get(platform) ?? 0) + 1);
- },
- );
+ if (hourly) {
+ // The snippet alone: Analytics has no hours (AT-004).
+ await scanTrafficLogs(
+ supabase,
+ brandId,
+ { columns: 'source_platform, created_at, id', from, to, toInclusive: true },
+ (r) => add(utcHourKey(r.created_at as string), (r.source_platform as string) || 'unknown', 1),
+ );
+ } else {
+ // Day by day from the snippet or Google Analytics (AT-004).
+ const merged = await readMergedTraffic(supabase, brandId, { from, to, toInclusive: true });
+ for (const d of merged.days) add(d.day, d.platform, d.visits);
+ }
let days: string[];
if (from && to) {
diff --git a/web/src/lib/traffic-export.test.ts b/web/src/lib/traffic-export.test.ts
index 034faf4f0..940250931 100644
--- a/web/src/lib/traffic-export.test.ts
+++ b/web/src/lib/traffic-export.test.ts
@@ -45,6 +45,7 @@ const data = (over: Partial<TrafficExportData> = {}): TrafficExportData => ({
totalVisits: 55,
totalVisitsPrev: 39,
totalPageviews: 59,
+ analyticsDays: [],
hasPreviousPeriod: true,
platformBreakdown: [
{ platform: 'chatgpt.com', visits: 40, visitsPrev: 33 },
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 62ad1c1d8..46ba0822c 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -2832,6 +2832,16 @@ export type Database = {
[_ in never]: never
}
Functions: {
+ ai_traffic_merged: {
+ Args: {
+ p_analytics?: boolean
+ p_brand_id: string
+ p_from: string | null
+ p_to: string | null
+ p_to_inclusive?: boolean
+ }
+ Returns: Json
+ }
ai_visibility_aggregates: {
Args: {
p_brand_id: string