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): count one visit per session, show Low sample under 30 visits and format in English (#1159)

Cihan4ddc1509fbc6
diff --git a/server/src/lib/traffic-visits.js b/server/src/lib/traffic-visits.js
new file mode 100644
index 000000000..3bc61add9
--- /dev/null
+++ b/server/src/lib/traffic-visits.js
@@ -0,0 +1,52 @@
+/**
+ * Which visit a tracking-snippet pageview belongs to (AT-003).
+ *
+ * The snippet sends a beacon on every AI-referred page load, so a reload or a
+ * second link from the same answer arrives as another row. A visit is a
+ * session, as Google Analytics counts one: the same visitor (IP address and
+ * user agent) from the same AI platform, with less than VISIT_GAP_MINUTES
+ * between pageviews. A different platform starts a new visit, as a new
+ * traffic source starts a new session in GA4.
+ *
+ * The answer is stored on the row as `visit_of` (migration 00172, which
+ * grouped the rows stored before it with the same rule): null when the
+ * pageview starts a visit, otherwise the id of the pageview that did.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+
+export const VISIT_GAP_MINUTES = 30;
+
+/**
+ * The id of the visit this pageview continues, or null when it starts one.
+ *
+ * The gap is measured from the visitor's latest pageview, not the visit's
+ * first, so a visit stays open while its pageviews keep coming. A pageview
+ * with no IP address or user agent can't be matched to anyone's, so it
+ * starts a visit of its own.
+ */
+export async function findVisitOf({
+ brandId,
+ sourcePlatform,
+ ipAddress,
+ userAgent,
+ now = Date.now(),
+}) {
+ if (!ipAddress || !userAgent) return null;
+
+ const since = new Date(now - VISIT_GAP_MINUTES * 60_000).toISOString();
+ const { data, error } = await supabaseAdmin
+ .from('ai_traffic_logs')
+ .select('id, visit_of')
+ .eq('brand_id', brandId)
+ .eq('source_platform', sourcePlatform)
+ .eq('ip_address', ipAddress)
+ .eq('user_agent', userAgent)
+ .gt('created_at', since)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ if (error) throw new Error(error.message);
+ return data ? (data.visit_of ?? data.id) : null;
+}
diff --git a/server/src/lib/traffic-visits.test.js b/server/src/lib/traffic-visits.test.js
new file mode 100644
index 000000000..47732b938
--- /dev/null
+++ b/server/src/lib/traffic-visits.test.js
@@ -0,0 +1,88 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * AT-003: a reload or a second link from the same answer continues a visit
+ * instead of counting as another (F5).
+ */
+
+const db = vi.hoisted(() => ({ calls: [], result: { data: null, error: null } }));
+
+// A query builder that records every filter and answers with db.result.
+vi.mock('../config/supabase.js', () => {
+ const builder = {};
+ for (const method of ['select', 'eq', 'gt', 'order', 'limit']) {
+ builder[method] = (...args) => {
+ db.calls.push([method, ...args]);
+ return builder;
+ };
+ }
+ builder.maybeSingle = async () => db.result;
+ return {
+ default: {
+ from: (table) => {
+ db.calls.push(['from', table]);
+ return builder;
+ },
+ },
+ };
+});
+
+const { findVisitOf, VISIT_GAP_MINUTES } = await import('./traffic-visits.js');
+
+const NOW = Date.parse('2026-10-18T12:00:00.000Z');
+const pageview = {
+ brandId: 'b1',
+ sourcePlatform: 'gemini.google.com',
+ ipAddress: '203.0.113.7',
+ userAgent: 'Mozilla/5.0',
+ now: NOW,
+};
+
+beforeEach(() => {
+ db.calls.length = 0;
+ db.result = { data: null, error: null };
+});
+
+describe('findVisitOf', () => {
+ it('starts a visit when the visitor has no pageview in the last 30 minutes', async () => {
+ expect(await findVisitOf(pageview)).toBeNull();
+ });
+
+ it("looks for the same visitor's latest pageview from the same platform", async () => {
+ await findVisitOf(pageview);
+ expect(VISIT_GAP_MINUTES).toBe(30);
+ expect(db.calls).toEqual([
+ ['from', 'ai_traffic_logs'],
+ ['select', 'id, visit_of'],
+ ['eq', 'brand_id', 'b1'],
+ ['eq', 'source_platform', 'gemini.google.com'],
+ ['eq', 'ip_address', '203.0.113.7'],
+ ['eq', 'user_agent', 'Mozilla/5.0'],
+ ['gt', 'created_at', '2026-10-18T11:30:00.000Z'],
+ ['order', 'created_at', { ascending: false }],
+ ['limit', 1],
+ ]);
+ });
+
+ it('continues the visit its latest pageview started', async () => {
+ db.result = { data: { id: 'p1', visit_of: null }, error: null };
+ expect(await findVisitOf(pageview)).toBe('p1');
+ });
+
+ it('continues the visit its latest pageview belongs to', async () => {
+ // p2 was itself a repeat of p1, so this pageview joins p1's visit.
+ db.result = { data: { id: 'p2', visit_of: 'p1' }, error: null };
+ expect(await findVisitOf(pageview)).toBe('p1');
+ });
+
+ it("starts a visit when it can't tell who the visitor is", async () => {
+ expect(await findVisitOf({ ...pageview, ipAddress: null })).toBeNull();
+ expect(await findVisitOf({ ...pageview, userAgent: null })).toBeNull();
+ expect(db.calls).toEqual([]);
+ });
+
+ it('reports a failed lookup', async () => {
+ db.result = { data: null, error: { message: 'timeout' } };
+ await expect(findVisitOf(pageview)).rejects.toThrow('timeout');
+ });
+});
diff --git a/server/src/routes/traffic-track.test.js b/server/src/routes/traffic-track.test.js
new file mode 100644
index 000000000..27a916616
--- /dev/null
+++ b/server/src/routes/traffic-track.test.js
@@ -0,0 +1,105 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * POST /track/:trackingCode (AT-003): each pageview is stored with the visit
+ * it belongs to, and a failed visit lookup still stores the pageview.
+ */
+
+const inserted = [];
+const findVisitOf = vi.fn();
+
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => ({
+ select: () => ({
+ eq: () => ({ single: async () => ({ data: { id: 'b1' }, error: null }) }),
+ }),
+ insert: async (row) => {
+ inserted.push({ table, row });
+ return { error: null };
+ },
+ }),
+ },
+}));
+vi.mock('../middleware/rate-limiter.js', () => ({ trafficLimiter: (req, res, next) => next() }));
+vi.mock('../lib/logger.js', () => {
+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
+ return { default: logger, logger };
+});
+vi.mock('../lib/traffic-visits.js', () => ({ findVisitOf: (...args) => findVisitOf(...args) }));
+
+let server;
+let baseUrl;
+
+beforeAll(async () => {
+ const { default: router } = await import('./traffic.js');
+ const app = express();
+ app.use(router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/track/abcdef123`;
+});
+
+afterAll(() => new Promise((resolve) => server.close(resolve)));
+
+beforeEach(() => {
+ inserted.length = 0;
+ findVisitOf.mockReset();
+});
+
+const beacon = (body = {}) =>
+ fetch(baseUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'text/plain;charset=UTF-8', 'X-Forwarded-For': '203.0.113.7' },
+ body: JSON.stringify({
+ u: 'https://acme.example/menu',
+ r: 'https://gemini.google.com/',
+ s: 'gemini.google.com',
+ a: 'Mozilla/5.0',
+ ...body,
+ }),
+ });
+
+describe('POST /track/:trackingCode', () => {
+ it('stores a repeat pageview under the visit it continues', async () => {
+ findVisitOf.mockResolvedValue('p1');
+ const res = await beacon();
+ expect(res.status).toBe(204);
+ expect(findVisitOf).toHaveBeenCalledWith({
+ brandId: 'b1',
+ sourcePlatform: 'gemini.google.com',
+ ipAddress: '203.0.113.7',
+ userAgent: 'Mozilla/5.0',
+ });
+ expect(inserted[0].table).toBe('ai_traffic_logs');
+ expect(inserted[0].row).toMatchObject({
+ url: 'https://acme.example/menu',
+ ip_address: '203.0.113.7',
+ user_agent: 'Mozilla/5.0',
+ visit_of: 'p1',
+ });
+ });
+
+ it('stores a first pageview as a new visit', async () => {
+ findVisitOf.mockResolvedValue(null);
+ await beacon();
+ expect(inserted[0].row.visit_of).toBeNull();
+ });
+
+ it('still stores the pageview, as a new visit, when the lookup fails', async () => {
+ findVisitOf.mockRejectedValue(new Error('timeout'));
+ const res = await beacon();
+ expect(res.status).toBe(204);
+ expect(inserted).toHaveLength(1);
+ expect(inserted[0].row.visit_of).toBeNull();
+ });
+
+ it('stores nothing for a beacon without a platform', async () => {
+ const res = await beacon({ s: '' });
+ expect(res.status).toBe(204);
+ expect(findVisitOf).not.toHaveBeenCalled();
+ expect(inserted).toEqual([]);
+ });
+});
diff --git a/server/src/routes/traffic.js b/server/src/routes/traffic.js
index 9ee020ea3..e7fbf815d 100644
--- a/server/src/routes/traffic.js
+++ b/server/src/routes/traffic.js
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'url';
import supabaseAdmin from '../config/supabase.js';
import { trafficLimiter } from '../middleware/rate-limiter.js';
import logger from '../lib/logger.js';
+import { findVisitOf } from '../lib/traffic-visits.js';
const router = Router();
@@ -120,16 +121,30 @@ router.post('/track/:trackingCode', trafficLimiter, beaconBody, async (req, res)
return res.status(204).end();
}
+ const userAgent = (body.a || '').slice(0, 512) || null;
+ const ipAddress = ip || null;
+
+ // A reload or a second link from the same answer continues the visit
+ // rather than counting as another (AT-003). If the lookup fails the
+ // pageview is still stored, as a visit of its own.
+ let visitOf = null;
+ try {
+ visitOf = await findVisitOf({ brandId: brand.id, sourcePlatform, ipAddress, userAgent });
+ } catch (err) {
+ logger.warn({ err }, 'traffic visit lookup failed; stored as a new visit');
+ }
+
await supabaseAdmin.from('ai_traffic_logs').insert({
brand_id: brand.id,
url: (body.u || '').slice(0, 2048),
referrer: (body.r || '').slice(0, 2048) || null,
source_platform: sourcePlatform,
- user_agent: (body.a || '').slice(0, 512) || null,
- ip_address: ip || null,
+ user_agent: userAgent,
+ ip_address: ipAddress,
country,
language: (body.l || '').slice(0, 16) || null,
screen: (body.d || '').slice(0, 16) || null,
+ visit_of: visitOf,
});
return res.status(204).end();
diff --git a/supabase/migrations/00172_ai_traffic_visits.sql b/supabase/migrations/00172_ai_traffic_visits.sql
new file mode 100644
index 000000000..d4b4f242c
--- /dev/null
+++ b/supabase/migrations/00172_ai_traffic_visits.sql
@@ -0,0 +1,81 @@
+-- ============================================================================
+-- 00172: one visit per session in the tracking snippet's data (AT-003)
+-- ============================================================================
+-- The snippet sends a beacon on every AI-referred page load, so a reload, a
+-- back-and-forward or a second link from the same answer was stored, and
+-- counted, as another visit. Recent AI Referral Visits showed three
+-- identical Gemini rows for one person, and every count on the AI Traffic
+-- page was a pageview count (F5).
+--
+-- A visit is now a session, as Google Analytics counts one: the same
+-- visitor (IP address and user agent) from the same AI platform, with less
+-- than 30 minutes between pageviews. A different platform starts a new
+-- visit, as a new traffic source starts a new session in GA4.
+--
+-- * visit_of is null on the row that starts a visit and holds that row's
+-- id on each further pageview of it. The beacon route decides it when
+-- it stores a pageview (server/src/lib/traffic-visits.js); the rows
+-- already stored are grouped below with the same rule.
+-- * A row with no IP address or no user agent can't be matched to another,
+-- so it is a visit of its own.
+-- * Counting visits is counting rows where visit_of is null; pageviews are
+-- still every row. The partial index keeps the visit counts and the
+-- visit list on the rows they read.
+
+alter table public.ai_traffic_logs
+ add column if not exists visit_of uuid
+ references public.ai_traffic_logs (id) on delete cascade;
+
+comment on column public.ai_traffic_logs.visit_of is
+ 'Null when this pageview starts a visit; otherwise the id of the pageview that started it. Same IP address, user agent and platform, under 30 minutes apart (AT-003).';
+
+with ordered as (
+ select
+ id,
+ brand_id,
+ source_platform,
+ ip_address,
+ user_agent,
+ created_at,
+ ip_address is null or user_agent is null
+ or lag(created_at) over visitor is null
+ or created_at - lag(created_at) over visitor >= interval '30 minutes' as starts
+ from public.ai_traffic_logs
+ window visitor as (
+ partition by brand_id, source_platform, ip_address, user_agent
+ order by created_at, id
+ )
+),
+numbered as (
+ select
+ *,
+ count(*) filter (where starts) over (
+ partition by brand_id, source_platform, ip_address, user_agent
+ order by created_at, id
+ rows between unbounded preceding and current row
+ ) as visit_no
+ from ordered
+),
+firsts as (
+ select
+ id,
+ starts,
+ first_value(id) over (
+ partition by brand_id, source_platform, ip_address, user_agent, visit_no
+ order by created_at, id
+ ) as first_id
+ from numbered
+)
+update public.ai_traffic_logs l
+set visit_of = f.first_id
+from firsts f
+where l.id = f.id
+ and not f.starts;
+
+create index if not exists idx_ai_traffic_logs_brand_visits
+ on public.ai_traffic_logs (brand_id, created_at desc)
+ where visit_of is null;
+
+create index if not exists idx_ai_traffic_logs_visit_of
+ on public.ai_traffic_logs (visit_of)
+ where visit_of is not null;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 47ae3e565..9ea99e640 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -23245,3 +23245,88 @@ comment on function public.ga_page_ai_visibility(uuid, date, date) is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00172_ai_traffic_visits.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00172: one visit per session in the tracking snippet's data (AT-003)
+-- ============================================================================
+-- The snippet sends a beacon on every AI-referred page load, so a reload, a
+-- back-and-forward or a second link from the same answer was stored, and
+-- counted, as another visit. Recent AI Referral Visits showed three
+-- identical Gemini rows for one person, and every count on the AI Traffic
+-- page was a pageview count (F5).
+--
+-- A visit is now a session, as Google Analytics counts one: the same
+-- visitor (IP address and user agent) from the same AI platform, with less
+-- than 30 minutes between pageviews. A different platform starts a new
+-- visit, as a new traffic source starts a new session in GA4.
+--
+-- * visit_of is null on the row that starts a visit and holds that row's
+-- id on each further pageview of it. The beacon route decides it when
+-- it stores a pageview (server/src/lib/traffic-visits.js); the rows
+-- already stored are grouped below with the same rule.
+-- * A row with no IP address or no user agent can't be matched to another,
+-- so it is a visit of its own.
+-- * Counting visits is counting rows where visit_of is null; pageviews are
+-- still every row. The partial index keeps the visit counts and the
+-- visit list on the rows they read.
+
+alter table public.ai_traffic_logs
+ add column if not exists visit_of uuid
+ references public.ai_traffic_logs (id) on delete cascade;
+
+comment on column public.ai_traffic_logs.visit_of is
+ 'Null when this pageview starts a visit; otherwise the id of the pageview that started it. Same IP address, user agent and platform, under 30 minutes apart (AT-003).';
+
+with ordered as (
+ select
+ id,
+ brand_id,
+ source_platform,
+ ip_address,
+ user_agent,
+ created_at,
+ ip_address is null or user_agent is null
+ or lag(created_at) over visitor is null
+ or created_at - lag(created_at) over visitor >= interval '30 minutes' as starts
+ from public.ai_traffic_logs
+ window visitor as (
+ partition by brand_id, source_platform, ip_address, user_agent
+ order by created_at, id
+ )
+),
+numbered as (
+ select
+ *,
+ count(*) filter (where starts) over (
+ partition by brand_id, source_platform, ip_address, user_agent
+ order by created_at, id
+ rows between unbounded preceding and current row
+ ) as visit_no
+ from ordered
+),
+firsts as (
+ select
+ id,
+ starts,
+ first_value(id) over (
+ partition by brand_id, source_platform, ip_address, user_agent, visit_no
+ order by created_at, id
+ ) as first_id
+ from numbered
+)
+update public.ai_traffic_logs l
+set visit_of = f.first_id
+from firsts f
+where l.id = f.id
+ and not f.starts;
+
+create index if not exists idx_ai_traffic_logs_brand_visits
+ on public.ai_traffic_logs (brand_id, created_at desc)
+ where visit_of is null;
+
+create index if not exists idx_ai_traffic_logs_visit_of
+ on public.ai_traffic_logs (visit_of)
+ where visit_of is not null;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 5b7a484aa..7a99f6cc4 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3073,6 +3073,18 @@
"snippetDescription": "Paste this before the closing <code>{tag}</code> tag to track AI-referred visits.",
"copySnippet": "Copy tracking script",
"exportError": "Failed to export CSV",
+ "change": {
+ "new": "new",
+ "lowSample": "Low sample",
+ "lowSampleHint": "Fewer than 30 visits in this period or the one before, so a % change would mislead."
+ },
+ "visits": {
+ "kpiSub": "{pageviews, plural, one {# pageview} other {# pageviews}} · {previous, number} in the previous period",
+ "kpiSubNoPrevious": "{pageviews, plural, one {# pageview} other {# pageviews}}",
+ "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."
+ },
"sources": {
"label": "Data sources",
"snippet": "Tracking snippet",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts
index 208381a2b..190af841d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { getPlatformName } from '@/lib/traffic-platforms';
-import { getPlatformFilterItems } from './_charts';
+import { formatTrafficBucketDate, getPlatformFilterItems } from './_charts';
describe('getPlatformFilterItems', () => {
it('starts with the all-platforms option, whose value is empty', () => {
@@ -39,3 +39,22 @@ describe('getPlatformFilterItems', () => {
expect(values).toEqual(['', 'poe.com', 'bing.com', 'you.com']);
});
});
+
+describe('formatTrafficBucketDate', () => {
+ it('names a UTC day in English, whatever the browser language (F7)', () => {
+ // A Turkish browser used to show "12 Eki".
+ const toLocaleDateString = Date.prototype.toLocaleDateString;
+ Date.prototype.toLocaleDateString = function (
+ this: Date,
+ locales?: Intl.LocalesArgument,
+ options?: Intl.DateTimeFormatOptions,
+ ) {
+ return toLocaleDateString.call(this, locales ?? 'tr-TR', options);
+ };
+ try {
+ expect(formatTrafficBucketDate('2026-10-12')).toBe('Oct 12');
+ } finally {
+ Date.prototype.toLocaleDateString = toLocaleDateString;
+ }
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
index d487f0787..889d5ef5b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
@@ -2,6 +2,7 @@
import { useRef, useState, useEffect } from 'react';
import { getPlatformName } from '@/lib/traffic-platforms';
+import { formatNumber } from '@/lib/format';
import {
AreaChart,
Area,
@@ -92,10 +93,12 @@ export function getPlatformFilterItems(
];
}
-function formatTrafficBucketDate(value: string): string {
- const d = new Date(value);
-
- return d.toLocaleDateString(undefined, {
+/**
+ * A trend bucket's day ("Oct 12"). English like the rest of the UI, not the
+ * browser's language (F7), and in UTC because the buckets are UTC days.
+ */
+export function formatTrafficBucketDate(value: string): string {
+ return new Date(value).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
timeZone: 'UTC',
@@ -126,7 +129,7 @@ function AreaTooltip({
style={{ backgroundColor: entry.color }}
/>
<span className="text-muted-foreground">{getPlatformName(entry.name)}:</span>
- <span className="font-medium text-foreground">{entry.value.toLocaleString()}</span>
+ <span className="font-medium text-foreground">{formatNumber(entry.value)}</span>
</div>
))}
</div>
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 66c6e168d..d0bfc0cf9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx
@@ -14,6 +14,7 @@ import {
} from '@/components/ui/table';
import { Target } from 'lucide-react';
import { cn } from '@/lib/utils';
+import { formatNumber } from '@/lib/format';
import {
getPageOpportunities,
type PageOpportunities,
@@ -51,10 +52,10 @@ import {
/** 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();
- return inMinutes(Math.round(row.engagementSeconds / 60).toLocaleString());
+ if (row.valueSignal === 'revenue') return formatNumber(row.revenue);
+ if (row.valueSignal === 'transactions') return formatNumber(row.transactions);
+ if (row.valueSignal === 'key_events') return formatNumber(row.keyEvents);
+ return inMinutes(formatNumber(Math.round(row.engagementSeconds / 60)));
}
/** The count a citation state's detail line names. */
@@ -173,7 +174,7 @@ export function PageOpportunitiesCard({
</div>
</TableCell>
<TableCell className="text-right tabular-nums text-sm">
- {row.sessions.toLocaleString()}
+ {formatNumber(row.sessions)}
</TableCell>
<TableCell className="text-right font-semibold tabular-nums text-sm">
{signalValue(row, (minutes) => t('minutes', { minutes }))}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index e05442237..2ff0b28f2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -67,6 +67,8 @@ import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { toCsv } from '@/lib/csv';
import { formatRelative } from '@/lib/format-relative';
+import { formatNumber } from '@/lib/format';
+import { visitChange } from '@/lib/traffic-change';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
@@ -87,7 +89,7 @@ const PAGE_SIZE = 10;
*/
const TRAFFIC_EXPORT_LIMIT = 1000;
-const TRAFFIC_EXPORT_HEADERS = ['timestamp', 'platform', 'page_url', 'referrer'];
+const TRAFFIC_EXPORT_HEADERS = ['timestamp', 'platform', 'page_url', 'referrer', 'pageviews'];
// ─── Sub-components ───────────────────────────────────────────────────────────
@@ -96,13 +98,11 @@ function KpiCard({
icon: Icon,
value,
sub,
- subPositive,
}: {
title: string;
icon: React.ElementType;
value: React.ReactNode;
sub: React.ReactNode;
- subPositive?: boolean;
}) {
return (
<Card>
@@ -114,15 +114,10 @@ function KpiCard({
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{value}</div>
+ {/* One line, as in the approved mockup; the full text on hover. */}
<p
- className={cn(
- 'text-xs mt-1 flex items-center gap-0.5',
- subPositive === true
- ? 'text-green-600 dark:text-green-400'
- : subPositive === false
- ? 'text-red-500'
- : 'text-muted-foreground',
- )}
+ className="mt-1 truncate text-xs text-muted-foreground"
+ title={typeof sub === 'string' ? sub : undefined}
>
{sub}
</p>
@@ -131,29 +126,52 @@ function KpiCard({
);
}
-function DeltaBadge({ current, previous }: { current: number; previous: number }) {
- if (previous === 0 && current === 0)
- return <span className="text-xs text-muted-foreground">—</span>;
- if (previous === 0)
+/**
+ * A visit count against the previous period: a %, "new", "—", or "Low sample"
+ * when either period is too small for a % to mean anything (AT-003, F4).
+ * `comparable` is false when the range has no previous period (all time).
+ */
+function DeltaBadge({
+ current,
+ previous,
+ comparable = true,
+}: {
+ current: number;
+ previous: number;
+ comparable?: boolean;
+}) {
+ const t = useTranslations('traffic.change');
+ const change = visitChange(current, previous, { comparable });
+ if (change.kind === 'none') return <span className="text-xs text-muted-foreground">—</span>;
+ if (change.kind === 'low') {
+ return (
+ <span
+ title={t('lowSampleHint')}
+ className="whitespace-nowrap rounded-md border border-dashed px-1.5 text-[11px] font-medium leading-4 text-muted-foreground"
+ >
+ {t('lowSample')}
+ </span>
+ );
+ }
+ if (change.kind === 'new') {
return (
<span className="flex items-center gap-0.5 text-xs font-medium text-green-600 dark:text-green-400">
<TrendingUp className="h-3 w-3" />
- new
+ {t('new')}
</span>
);
- const delta = Math.round(((current - previous) / previous) * 100);
- if (delta === 0) return <span className="text-xs text-muted-foreground">—</span>;
- const pos = delta > 0;
+ }
+ const pos = change.pct > 0;
return (
<span
className={cn(
- 'flex items-center gap-0.5 text-xs font-medium',
+ 'flex items-center gap-0.5 whitespace-nowrap text-xs font-medium',
pos ? 'text-green-600 dark:text-green-400' : 'text-red-500',
)}
>
{pos ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
{pos ? '+' : ''}
- {delta}%
+ {formatNumber(change.pct)}%
</span>
);
}
@@ -412,6 +430,7 @@ export default function TrafficPage() {
function TrafficPageContent({ brand }: { brand: Brand }) {
const t = useTranslations('traffic');
const tCommon = useTranslations('common');
+ const tVisits = useTranslations('traffic.visits');
const [datePreset, setDatePreset] = useState<DatePreset>('7d');
const [customFrom, setCustomFrom] = useState('');
const [customTo, setCustomTo] = useState('');
@@ -425,6 +444,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
const [trend, setTrend] = useState<TrafficTrendPoint[]>([]);
const [logs, setLogs] = useState<TrafficLog[]>([]);
const [logsTotal, setLogsTotal] = useState(0);
+ const [logsPageviews, setLogsPageviews] = useState(0);
const [isLoadingSummary, setIsLoadingSummary] = useState(true);
const [isLoadingLogs, setIsLoadingLogs] = useState(false);
const [isExporting, setIsExporting] = useState(false);
@@ -499,6 +519,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
});
setLogs(result.logs);
setLogsTotal(result.total);
+ setLogsPageviews(result.pageviews);
} catch (err) {
console.error('Failed to load traffic logs:', err);
} finally {
@@ -522,6 +543,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
platform: log.sourcePlatform ? getPlatformName(log.sourcePlatform) : '',
page_url: log.url,
referrer: log.referrer ?? '',
+ pageviews: log.pageviews,
}));
const csv = toCsv(rows, TRAFFIC_EXPORT_HEADERS);
@@ -594,8 +616,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
const totalVisits = summary?.totalVisits ?? 0;
const totalVisitsPrev = summary?.totalVisitsPrev ?? 0;
- const visitsDelta =
- totalVisitsPrev > 0 ? Math.round(((totalVisits - totalVisitsPrev) / totalVisitsPrev) * 100) : 0;
+ const totalPageviews = summary?.totalPageviews ?? 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;
const topPlatform = summary?.platformBreakdown[0];
const isEmpty = totalVisits === 0 && logs.length === 0;
@@ -676,32 +700,35 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
<>
{/* KPI Cards */}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
+ {/* One visit per session; the sub-line gives the pageviews and
+ the previous period's visits (AT-003). */}
<KpiCard
title="AI-Referred Visits"
icon={Users}
- value={totalVisits.toLocaleString()}
+ value={
+ <span className="flex items-center gap-2">
+ {formatNumber(totalVisits)}
+ {/* The tables show "—" for no change; the card shows nothing. */}
+ {visitChange(totalVisits, totalVisitsPrev, { comparable }).kind !== 'none' && (
+ <DeltaBadge
+ current={totalVisits}
+ previous={totalVisitsPrev}
+ comparable={comparable}
+ />
+ )}
+ </span>
+ }
sub={
- totalVisitsPrev > 0 ? (
- <>
- {visitsDelta >= 0 ? (
- <TrendingUp className="h-3 w-3" />
- ) : (
- <TrendingDown className="h-3 w-3" />
- )}
- {visitsDelta >= 0 ? '+' : ''}
- {visitsDelta}% vs previous period
- </>
- ) : (
- rangeSubLabel
- )
+ comparable
+ ? tVisits('kpiSub', { pageviews: totalPageviews, previous: totalVisitsPrev })
+ : tVisits('kpiSubNoPrevious', { pageviews: totalPageviews })
}
- subPositive={visitsDelta > 0 ? true : visitsDelta < 0 ? false : undefined}
/>
<KpiCard
title="Top Platform"
icon={Globe}
value={topPlatform ? getPlatformName(topPlatform.platform) : '—'}
- sub={topPlatform ? `${topPlatform.visits} visits` : 'no data'}
+ sub={topPlatform ? `${formatNumber(topPlatform.visits)} visits` : 'no data'}
/>
<KpiCard
title="Platforms"
@@ -757,11 +784,15 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</span>
</TableCell>
<TableCell className="text-right font-semibold tabular-nums">
- {row.visits.toLocaleString()}
+ {formatNumber(row.visits)}
</TableCell>
<TableCell className="text-right pr-6">
<div className="flex justify-end">
- <DeltaBadge current={row.visits} previous={row.visitsPrev} />
+ <DeltaBadge
+ current={row.visits}
+ previous={row.visitsPrev}
+ comparable={comparable}
+ />
</div>
</TableCell>
</TableRow>
@@ -794,11 +825,15 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</span>
</TableCell>
<TableCell className="text-right font-semibold tabular-nums text-sm">
- {row.visits.toLocaleString()}
+ {formatNumber(row.visits)}
</TableCell>
<TableCell className="text-right pr-6">
<div className="flex justify-end">
- <DeltaBadge current={row.visits} previous={row.visitsPrev} />
+ <DeltaBadge
+ current={row.visits}
+ previous={row.visitsPrev}
+ comparable={comparable}
+ />
</div>
</TableCell>
</TableRow>
@@ -832,7 +867,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</div>
{logsTotal > 0 && (
<Badge variant="secondary" className="text-xs">
- {logsTotal} total
+ {tVisits('listTotal', { visits: logsTotal, pageviews: logsPageviews })}
</Badge>
)}
</div>
@@ -878,15 +913,23 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</span>
</TableCell>
<TableCell>
- <span className="font-mono text-xs text-muted-foreground line-clamp-1">
- {(() => {
- try {
- return new URL(row.url).pathname;
- } catch {
- return row.url;
- }
- })()}
- </span>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="font-mono text-xs text-muted-foreground line-clamp-1">
+ {(() => {
+ try {
+ return new URL(row.url).pathname;
+ } catch {
+ return row.url;
+ }
+ })()}
+ </span>
+ {/* A reload or a further link in the same visit (AT-003). */}
+ {row.pageviews > 1 && (
+ <span className="shrink-0 whitespace-nowrap rounded-full bg-muted px-1.5 text-[11px] font-medium leading-4 text-muted-foreground">
+ {tVisits('rowPageviews', { count: row.pageviews })}
+ </span>
+ )}
+ </div>
</TableCell>
<TableCell className="text-right pr-6">
<span className="text-xs text-muted-foreground">
@@ -914,6 +957,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
/>
);
})()}
+ <p className="px-6 pb-4 text-xs text-muted-foreground">{tVisits('listNote')}</p>
</>
)}
</CardContent>
diff --git a/web/src/lib/actions/traffic-visits.test.ts b/web/src/lib/actions/traffic-visits.test.ts
new file mode 100644
index 000000000..14fbe71a6
--- /dev/null
+++ b/web/src/lib/actions/traffic-visits.test.ts
@@ -0,0 +1,158 @@
+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.
+ */
+
+type Call = [string, ...unknown[]];
+type Result = { data?: unknown; count?: number | null; error: null };
+
+const queries: Call[][] = [];
+let answer: (calls: Call[]) => Result;
+
+// A query builder that records its calls and answers once awaited.
+function query(table: string) {
+ const calls: Call[] = [['from', table]];
+ queries.push(calls);
+ const builder: Record<string, unknown> = {};
+ for (const method of [
+ 'select',
+ 'eq',
+ 'is',
+ 'gte',
+ 'lte',
+ 'lt',
+ 'ilike',
+ 'order',
+ 'range',
+ 'in',
+ ]) {
+ builder[method] = (...args: unknown[]) => {
+ calls.push([method, ...args]);
+ return builder;
+ };
+ }
+ builder.then = (resolve: (r: Result) => unknown) => resolve(answer(calls));
+ return builder;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({ from: (table: string) => query(table) })),
+}));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
+
+import { getTrafficLogs, getTrafficSummary } 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)));
+const visitsOnly = (calls: Call[]) => has(calls, 'is', 'visit_of', null);
+const head = (calls: Call[]) =>
+ calls.some(([m, , opts]) => m === 'select' && (opts as { head?: boolean })?.head === true);
+
+const row = (id: string, url: string, platform = 'gemini.google.com') => ({
+ id,
+ brand_id: 'b1',
+ url,
+ referrer: null,
+ source_platform: platform,
+ country: 'US',
+ language: 'en',
+ screen: null,
+ created_at: '2026-10-17T10:00:00.000Z',
+ visit_of: null,
+});
+
+beforeEach(() => {
+ queries.length = 0;
+});
+
+describe('getTrafficLogs', () => {
+ beforeEach(() => {
+ answer = (calls) => {
+ if (has(calls, 'in')) {
+ // v1 had two more pageviews, v2 none.
+ return { data: [{ visit_of: 'v1' }, { visit_of: 'v1' }], error: null };
+ }
+ if (head(calls)) return { count: 7, error: null };
+ return {
+ data: [row('v1', 'https://acme.example/menu/'), row('v2', 'https://acme.example/beans')],
+ count: 4,
+ error: null,
+ };
+ };
+ });
+
+ it('lists one row per visit with its pageviews (F5)', async () => {
+ const result = await getTrafficLogs('b1', { limit: 10, dateFrom: '2026-10-11T00:00:00Z' });
+
+ expect(result.total).toBe(4);
+ expect(result.pageviews).toBe(7);
+ expect(result.logs.map((log) => [log.id, log.pageviews])).toEqual([
+ ['v1', 3],
+ ['v2', 1],
+ ]);
+
+ const [list, pageviews, repeats] = queries;
+ expect(visitsOnly(list)).toBe(true);
+ expect(has(list, 'range', 0, 9)).toBe(true);
+ // The pageview total counts every row, not just the visits.
+ expect(visitsOnly(pageviews)).toBe(false);
+ expect(has(repeats, 'select', 'visit_of')).toBe(true);
+ expect(repeats.find(([m]) => m === 'in')).toEqual(['in', 'visit_of', ['v1', 'v2']]);
+ });
+
+ it('applies the same filters to the visits and the pageview total', async () => {
+ await getTrafficLogs('b1', {
+ platform: 'gemini.google.com',
+ search: 'menu',
+ dateFrom: '2026-10-11T00:00:00Z',
+ });
+ for (const calls of queries.slice(0, 2)) {
+ expect(has(calls, 'eq', 'source_platform', 'gemini.google.com')).toBe(true);
+ expect(has(calls, 'ilike', 'url', '%menu%')).toBe(true);
+ expect(has(calls, 'gte', 'created_at', '2026-10-11T00:00:00Z')).toBe(true);
+ }
+ });
+
+ it('skips the pageview lookup when there are no visits', async () => {
+ answer = (calls) =>
+ head(calls) ? { count: 0, error: null } : { data: [], count: 0, error: null };
+ const result = await getTrafficLogs('b1');
+ expect(result).toEqual({ logs: [], total: 0, pageviews: 0 });
+ 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 f499dbef5..5236077b0 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -20,11 +20,22 @@ export interface TrafficLog {
language: string | null;
screen: string | null;
createdAt: string;
+ /** Pageviews in this visit: 1, plus each reload or further link (AT-003). */
+ pageviews: number;
}
+/**
+ * Every count here is of visits, one per session (AT-003): a row whose
+ * `visit_of` is null starts a visit, and the rows pointing at it are its
+ * further pageviews. Pageviews are counted on their own.
+ */
export interface TrafficSummary {
totalVisits: number;
totalVisitsPrev: number;
+ /** Every pageview in the window, the visits' first ones included. */
+ totalPageviews: number;
+ /** False for all time, which has no previous period to compare with. */
+ hasPreviousPeriod: boolean;
platformBreakdown: { platform: string; visits: number; visitsPrev: number }[];
topPages: { url: string; visits: number; visitsPrev: number }[];
hasAnyData: boolean;
@@ -79,6 +90,7 @@ function mapLogRow(row: Record<string, unknown>): TrafficLog {
language: row.language as string | null,
screen: row.screen as string | null,
createdAt: row.created_at as string,
+ pageviews: 1,
};
}
@@ -136,6 +148,9 @@ function listUtcDays(from: string, to: string): string[] {
* Totals come from exact count queries; the breakdown/trend scans page
* through the window with deterministic ordering and a hard ceiling so a
* pathological brand can't pin the server action.
+ *
+ * The scans read the rows that start a visit only, so the breakdowns and the
+ * trend count visits, not pageviews (AT-003).
*/
const TRAFFIC_PAGE_SIZE = 1000;
const TRAFFIC_MAX_ROWS = 50_000;
@@ -151,6 +166,7 @@ async function scanTrafficLogs(
.from('ai_traffic_logs')
.select(window.columns)
.eq('brand_id', brandId)
+ .is('visit_of', null)
// Deterministic order so .range() pages don't shuffle between requests.
.order('created_at', { ascending: true })
.order('id', { ascending: true })
@@ -179,11 +195,17 @@ export async function getTrafficSummary(
const { from, to, prevFrom, prevTo } = resolveTrafficWindow(window);
// Exact totals — count queries transfer no rows and are immune to the cap.
- const countVisits = async (fromTs?: string, toTs?: string, toInclusive = false) => {
+ const countRows = async (
+ fromTs?: string,
+ toTs?: string,
+ toInclusive = false,
+ { visits = true } = {},
+ ) => {
let query = supabase
.from('ai_traffic_logs')
.select('id', { count: 'exact', head: true })
.eq('brand_id', brandId);
+ if (visits) query = query.is('visit_of', null);
if (fromTs) query = query.gte('created_at', fromTs);
if (toTs) {
query = toInclusive ? query.lte('created_at', toTs) : query.lt('created_at', toTs);
@@ -221,9 +243,10 @@ export async function getTrafficSummary(
// 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, , , lifetimeVisits] = await Promise.all([
- countVisits(from, to, true),
- hasPrev ? countVisits(prevFrom, prevTo) : Promise.resolve(0),
+ 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,
@@ -238,7 +261,7 @@ export async function getTrafficSummary(
aggregate(platformMapPrev, pageMapPrev),
)
: Promise.resolve(),
- hasWindow ? countVisits() : Promise.resolve(null),
+ hasWindow ? countRows() : Promise.resolve(null),
]);
const hasAnyData = hasWindow ? (lifetimeVisits as number) > 0 : totalVisits > 0;
@@ -265,6 +288,8 @@ export async function getTrafficSummary(
return {
totalVisits,
totalVisitsPrev,
+ totalPageviews,
+ hasPreviousPeriod: hasPrev,
platformBreakdown,
topPages,
hasAnyData,
@@ -318,6 +343,11 @@ export async function getTrafficTrend(
});
}
+/**
+ * The window's visits, newest first, one row per visit with its pageviews
+ * (AT-003). `total` counts the visits that match; `pageviews` counts every
+ * pageview that does, so the list can say "4 visits (7 pageviews)".
+ */
export async function getTrafficLogs(
brandId: string,
opts?: {
@@ -328,7 +358,7 @@ export async function getTrafficLogs(
dateFrom?: string;
dateTo?: string;
},
-): Promise<{ logs: TrafficLog[]; total: number }> {
+): Promise<{ logs: TrafficLog[]; total: number; pageviews: number }> {
const supabase = await createClient();
const limit = opts?.limit ?? 20;
const offset = opts?.offset ?? 0;
@@ -339,35 +369,55 @@ export async function getTrafficLogs(
dateTo: opts?.dateTo,
});
- let query = supabase
- .from('ai_traffic_logs')
- .select('*', { count: 'exact' })
- .eq('brand_id', brandId);
-
- // Apply filters
- if (platform) {
- query = query.eq('source_platform', platform);
- }
-
- if (search) {
- // Escape \, % and _ for ILIKE to treat them as literals, not wildcards
- const escaped = search.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_');
- query = query.ilike('url', `%${escaped}%`);
- }
+ // One set of filters for the visits and for the pageview count.
+ const matching = (columns: string, head: boolean) => {
+ let query = supabase
+ .from('ai_traffic_logs')
+ .select(columns, { count: 'exact', head })
+ .eq('brand_id', brandId);
+ if (platform) query = query.eq('source_platform', platform);
+ if (search) {
+ // Escape \, % and _ for ILIKE to treat them as literals, not wildcards
+ const escaped = search.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_');
+ query = query.ilike('url', `%${escaped}%`);
+ }
+ if (from) query = query.gte('created_at', from);
+ if (to) query = query.lte('created_at', to);
+ return query;
+ };
- if (from) query = query.gte('created_at', from);
- if (to) query = query.lte('created_at', to);
+ const [visits, pageviews] = await Promise.all([
+ matching('*', false)
+ .is('visit_of', null)
+ .order('created_at', { ascending: false })
+ .range(offset, offset + limit - 1),
+ matching('id', true),
+ ]);
+ if (visits.error) throw new Error(visits.error.message);
+ if (pageviews.error) throw new Error(pageviews.error.message);
- const { data, error, count } = await query
- .order('created_at', { ascending: false })
- .range(offset, offset + limit - 1);
+ const logs = ((visits.data ?? []) as unknown as Record<string, unknown>[]).map(mapLogRow);
- if (error) throw new Error(error.message);
+ // Each listed visit's further pageviews, counted from the rows pointing
+ // at it. The repeats of one page of visits are few, so one read does it.
+ if (logs.length > 0) {
+ const { data: repeats, error } = await supabase
+ .from('ai_traffic_logs')
+ .select('visit_of')
+ .in(
+ 'visit_of',
+ logs.map((log) => log.id),
+ );
+ if (error) throw new Error(error.message);
+ const extra = new Map<string, number>();
+ for (const row of repeats ?? []) {
+ const id = row.visit_of as string;
+ extra.set(id, (extra.get(id) ?? 0) + 1);
+ }
+ for (const log of logs) log.pageviews += extra.get(log.id) ?? 0;
+ }
- return {
- logs: (data ?? []).map((r) => mapLogRow(r as Record<string, unknown>)),
- total: count ?? 0,
- };
+ return { logs, total: visits.count ?? 0, pageviews: pageviews.count ?? 0 };
}
/**
diff --git a/web/src/lib/format-relative.test.ts b/web/src/lib/format-relative.test.ts
index 41d448293..abfe62068 100644
--- a/web/src/lib/format-relative.test.ts
+++ b/web/src/lib/format-relative.test.ts
@@ -10,6 +10,7 @@
import { expect, test } from 'vitest';
import { formatRelative } from './format-relative.js';
+import { formatDate } from './format';
// ---------------------------------------------------------------------------
// Stub translator
@@ -128,19 +129,34 @@ test('29 days ago → 29d ago', () => {
expect(formatRelative(isoDaysAgo(29), t)).toBe('29d ago');
});
-test('30 days ago → locale date string, not "30d ago"', () => {
+test('30 days ago → a date, not "30d ago"', () => {
const iso = isoDaysAgo(30);
const result = formatRelative(iso, t);
// Must NOT look like "Xd ago"
expect(result).not.toMatch(/^\d+d ago$/);
- // Must be a non-empty date string (locale-formatted)
- expect(result.length).toBeGreaterThan(0);
- expect(result).toBe(new Date(iso).toLocaleDateString());
+ expect(result).toBe(formatDate(iso));
});
-test('412 days ago → locale date string, not "412d ago"', () => {
+test('412 days ago → a date, not "412d ago"', () => {
const iso = isoDaysAgo(412);
const result = formatRelative(iso, t);
expect(result).not.toMatch(/^\d+d ago$/);
- expect(result).toBe(new Date(iso).toLocaleDateString());
+ expect(result).toBe(formatDate(iso));
+});
+
+test('an older date reads in English whatever the browser language (F7)', () => {
+ // A Turkish browser used to show "10.09.2025" here.
+ const toLocaleDateString = Date.prototype.toLocaleDateString;
+ Date.prototype.toLocaleDateString = function (
+ this: Date,
+ locales?: Intl.LocalesArgument,
+ options?: Intl.DateTimeFormatOptions,
+ ) {
+ return toLocaleDateString.call(this, locales ?? 'tr-TR', options);
+ };
+ try {
+ expect(formatRelative('2025-09-10T12:00:00.000Z', t)).toBe('Sep 10, 2025');
+ } finally {
+ Date.prototype.toLocaleDateString = toLocaleDateString;
+ }
});
diff --git a/web/src/lib/format-relative.ts b/web/src/lib/format-relative.ts
index 8372afa5c..57065ea1e 100644
--- a/web/src/lib/format-relative.ts
+++ b/web/src/lib/format-relative.ts
@@ -9,7 +9,8 @@
* - < 60 min → t('common.relative.minutesAgo', { m }) (Math.floor)
* - < 24 h → t('common.relative.hoursAgo', { h }) (Math.floor)
* - < 30 d → t('common.relative.daysAgo', { d }) (Math.floor)
- * - ≥ 30 d → toLocaleDateString()
+ * - ≥ 30 d → formatDate(), e.g. "Sep 10, 2026": English like
+ * the rest of the UI, not the browser's language
*
* Signature: accepts an ISO string (or null/undefined) plus the next-intl
* translator scoped to 'common'. Call sites that previously received a Date
@@ -17,6 +18,7 @@
*/
import type { useTranslations } from 'next-intl';
+import { formatDate } from '@/lib/format';
type Translator = ReturnType<typeof useTranslations<'common'>>;
@@ -35,5 +37,5 @@ export function formatRelative(iso: string | null | undefined, t: Translator): s
const d = Math.floor(h / 24);
if (d < 30) return t('relative.daysAgo', { d });
- return new Date(iso).toLocaleDateString();
+ return formatDate(iso);
}
diff --git a/web/src/lib/traffic-change.test.ts b/web/src/lib/traffic-change.test.ts
new file mode 100644
index 000000000..d13c111c9
--- /dev/null
+++ b/web/src/lib/traffic-change.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+import { LOW_SAMPLE_VISITS, visitChange } from './traffic-change';
+
+describe('visitChange', () => {
+ it('shows a % once both periods have 30 visits', () => {
+ expect(LOW_SAMPLE_VISITS).toBe(30);
+ expect(visitChange(45, 30)).toEqual({ kind: 'pct', pct: 50 });
+ expect(visitChange(30, 60)).toEqual({ kind: 'pct', pct: -50 });
+ });
+
+ it('says Low sample instead of a big % on a few visits (F4)', () => {
+ // The live page: +367% on 14 visits, −65% on 11.
+ expect(visitChange(14, 3)).toEqual({ kind: 'low' });
+ expect(visitChange(11, 31)).toEqual({ kind: 'low' });
+ expect(visitChange(29, 100)).toEqual({ kind: 'low' });
+ });
+
+ it('says Low sample when the previous period is the small one', () => {
+ // 40 against 3 would read +1,233%.
+ expect(visitChange(40, 3)).toEqual({ kind: 'low' });
+ });
+
+ it('calls visits after none "new", however few', () => {
+ expect(visitChange(1, 0)).toEqual({ kind: 'new' });
+ expect(visitChange(120, 0)).toEqual({ kind: 'new' });
+ });
+
+ it('shows no change with no visits, no previous period, or the same count', () => {
+ expect(visitChange(0, 0)).toEqual({ kind: 'none' });
+ expect(visitChange(50, 0, { comparable: false })).toEqual({ kind: 'none' });
+ expect(visitChange(50, 50)).toEqual({ kind: 'none' });
+ });
+});
diff --git a/web/src/lib/traffic-change.ts b/web/src/lib/traffic-change.ts
new file mode 100644
index 000000000..ef9c28a76
--- /dev/null
+++ b/web/src/lib/traffic-change.ts
@@ -0,0 +1,33 @@
+/**
+ * How a visit count compares with the previous period on the AI Traffic page
+ * (AT-003, F4).
+ *
+ * A % change on a handful of visits says more about chance than about a
+ * trend: the live page showed +367% on 14 visits. So a % is shown only when
+ * both periods have at least LOW_SAMPLE_VISITS; otherwise the change reads
+ * "Low sample". The previous period counts too, because 40 visits against 3
+ * would read +1,233% — the same problem the other way round.
+ */
+
+export const LOW_SAMPLE_VISITS = 30;
+
+export type VisitChange =
+ /** Nothing to compare: no visits in either period, no previous period, or no change. */
+ | { kind: 'none' }
+ /** Visits now, none in the previous period. */
+ | { kind: 'new' }
+ /** Too few visits in one of the periods for a % to mean anything. */
+ | { kind: 'low' }
+ | { kind: 'pct'; pct: number };
+
+export function visitChange(
+ current: number,
+ previous: number,
+ { comparable = true }: { comparable?: boolean } = {},
+): VisitChange {
+ if (!comparable || (current === 0 && previous === 0)) return { kind: 'none' };
+ if (previous === 0) return { kind: 'new' };
+ if (current < LOW_SAMPLE_VISITS || previous < LOW_SAMPLE_VISITS) return { kind: 'low' };
+ const pct = Math.round(((current - previous) / previous) * 100);
+ return pct === 0 ? { kind: 'none' } : { kind: 'pct', pct };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 575d1ad34..5b4776a5e 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -405,6 +405,7 @@ export type Database = {
source_platform: string | null
url: string
user_agent: string | null
+ visit_of: string | null
}
Insert: {
brand_id: string
@@ -418,6 +419,7 @@ export type Database = {
source_platform?: string | null
url: string
user_agent?: string | null
+ visit_of?: string | null
}
Update: {
brand_id?: string
@@ -431,6 +433,7 @@ export type Database = {
source_platform?: string | null
url?: string
user_agent?: string | null
+ visit_of?: string | null
}
Relationships: [
{
@@ -440,6 +443,13 @@ export type Database = {
referencedRelation: "brands"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "ai_traffic_logs_visit_of_fkey"
+ columns: ["visit_of"]
+ isOneToOne: false
+ referencedRelation: "ai_traffic_logs"
+ referencedColumns: ["id"]
+ },
]
}
api_keys: {