Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(traffic): add a summary line above the AI Traffic KPI cards (#1175)
Cihanba2d5e85525b
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 6e8cd4d46..cdd30851b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3323,6 +3323,17 @@"pageValue": "which valuable pages get no AI traffic"}},+ "summaryLine": {+ "none": "{range}: no AI-referred visits yet.",+ "visits": "{range}: {count, plural, one {# AI-referred visit} other {# AI-referred visits}}",+ "share": "{share} of all traffic",+ "up": "up {pct}% on the previous period",+ "down": "down {pct}% on the previous period",+ "top": "{platform} sent the most ({count})",+ "best": "{platform} visitors convert best ({rate} of their visits had a key event)",+ "topAndBest": "{platform} sent the most ({count}), and its visitors convert best ({rate} of their visits had a key event).",+ "cited": "{count, plural, one {# page is cited in AI answers but gets no clicks.} other {# pages are cited in AI answers but get no clicks.}}"+ },"conversions": {"title": "Where AI visitors convert","rankedByKeyEvents": "Ranked by key events from AI visits",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsxindex dd9a094c1..75e4b8acb 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx@@ -19,8 +19,14 @@ import type { SourceState } from '@/lib/actions/integrations';*/const getTrafficGoogleTotals = vi.fn();+// The summary line above the cards (AT-007) counts the Cited, not clicked pages.+const getTrafficPages = vi.fn(async () => ({+ counts: { noAiTraffic: 0, citedNotClicked: 0, trafficNoPrompt: 0, all: 0 },+ rows: [],+}));vi.mock('@/lib/actions/traffic', () => ({getTrafficGoogleTotals: (...args: unknown[]) => getTrafficGoogleTotals(...args),+ getTrafficPages: (...args: unknown[]) => getTrafficPages(...(args as [])),}));const connect = vi.fn();vi.mock('@/hooks/use-integration-connect', () => ({@@ -138,6 +144,7 @@ async function render({canConnect={canConnect}onConnected={onConnected}onRangeChange={onRangeChange}+ rangeLabel="last 7 days"/></NextIntlClientProvider>,);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsxindex 637655b17..cd569cc2a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx@@ -34,6 +34,7 @@ import {import { getPlatformName } from '@/lib/traffic-platforms';import { googleSourceStatus, TRAFFIC_SECTION_SOURCES } from '@/lib/traffic-sources';import { MetricCard } from '../insights/_kpi-cards';+import { SummaryLine } from './_summary-line';import type { Change } from '../insights/kpi-format';import { SourceKpiCard } from './_source-gate';@@ -97,6 +98,7 @@ export function TrafficKpis({canConnect,onConnected,onRangeChange,+ rangeLabel,}: {brandId: string;dateWindow: TrafficDateWindow;@@ -112,6 +114,8 @@ export function TrafficKpis({onConnected: () => void;/** Switches the page's range, for "see 30d". */onRangeChange: (preset: DateRangePreset) => void;+ /** The page's own words for the range, for the summary line (AT-007). */+ rangeLabel: string;}) {const t = useTranslations('traffic.kpis');const tVisits = useTranslations('traffic.visits');@@ -216,130 +220,149 @@ export function TrafficKpis({};};+ // Analytics' sessions for the summary line: undefined while they load,+ // null without Analytics, so the line never states a fact from a source+ // that isn't connected (§3.8b rule 5).+ const gaSessions = !gaReady+ ? null+ : loaded?.key === key+ ? (loaded.totals?.ga?.sessions ?? null)+ : undefined;+return (- <div className={TRAFFIC_KPI_GRID}>- {/* One visit per session; the sub-line gives the pageviews and the- 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')}- icon={Users}- value={formatNumber(totalVisits)}- delta={delta(visitChange(totalVisits, totalVisitsPrev, { comparable }))}- sub={- 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- label={t('topPlatform')}- tooltip={t('topPlatformTip')}- icon={Globe}- value={topPlatform ? getPlatformName(topPlatform.platform) : '—'}- sub={topPlatform ? t('topPlatformSub', { visits: topPlatform.visits }) : t('noData')}- />- <MetricCard- label={t('platforms')}- tooltip={t('platformsTip')}- icon={LayoutGrid}- value={formatNumber(summary?.platformBreakdown.length ?? 0)}- sub={t('platformsSub')}+ <div className="space-y-3">+ <SummaryLine+ brandId={brandId}+ dateWindow={dateWindow}+ rangeLabel={rangeLabel}+ summary={summary}+ summaryLoading={summaryLoading}+ gaSessions={gaSessions}/>- {gate('aiShare', aiShare) ?? (+ <div className={TRAFFIC_KPI_GRID}>+ {/* One visit per session; the sub-line gives the pageviews and the+ 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- {...aiShare}- {...(summaryLoading- ? // The visits and the sessions must be the same range's.- PENDING- : fromGa(({ sessions }) => ({- value: formatShare(totalVisits, sessions) ?? '—',- sub: t('aiShareSub', { visits: totalVisits, sessions }),- })))}+ label={t('visits')}+ tooltip={t('visitsTip')}+ icon={Users}+ value={formatNumber(totalVisits)}+ delta={delta(visitChange(totalVisits, totalVisitsPrev, { comparable }))}+ sub={+ analyticsDays > 0+ ? comparable+ ? tVisits('kpiSubAnalytics', { previous: totalVisitsPrev, days: analyticsDays })+ : tVisits('kpiSubAnalyticsNoPrevious', { days: analyticsDays })+ : comparable+ ? tVisits('kpiSub', { pageviews: totalPageviews, previous: totalVisitsPrev })+ : tVisits('kpiSubNoPrevious', { pageviews: totalPageviews })+ }/>- )}- {/* Row 2: what AI visitors do, and Google's own clicks. */}- {gate('engagedVisits', engaged) ?? (<MetricCard- {...engaged}- {...fromGa(({ aiSessions, aiEngagedSessions, organic }) =>- aiSessions === 0- ? { value: '—', sub: t('noAiSessions') }- : {- value: formatShare(aiEngagedSessions, aiSessions) ?? '—',- // A rate on a handful of sessions says more about chance (§5.4).- delta: aiSessions < LOW_SAMPLE_VISITS ? delta({ kind: 'low' }) : null,- // Beside Google organic's, as the mockup draws it (AT-005).- sub:- organic.sessions > 0- ? t('engagedVsOrganic', {- rate: formatShare(organic.engagedSessions, organic.sessions)!,- })- : t('engagedSub', { engaged: aiEngagedSessions, sessions: aiSessions }),- },- )}+ label={t('topPlatform')}+ tooltip={t('topPlatformTip')}+ icon={Globe}+ value={topPlatform ? getPlatformName(topPlatform.platform) : '—'}+ sub={topPlatform ? t('topPlatformSub', { visits: topPlatform.visits }) : t('noData')}/>- )}- {gate('keyEvents', keyEvents) ?? (<MetricCard- {...keyEvents}- {...fromGa((totals) => {- const { aiSessions, aiKeyEvents, aiKeyEventSessions, aiRevenue, organic } = totals;- // Rows synced before the session key event rate have key events- // but no count of the sessions holding them: no rate until the- // history is re-read.- const rateKnown = aiKeyEventSessions > 0 || aiKeyEvents === 0;- const rate = rateKnown ? formatShare(aiKeyEventSessions, aiSessions) : null;- const ratio = organicRatio(- {- sessions: aiSessions,- keyEvents: aiKeyEvents,- keyEventSessions: aiKeyEventSessions,- },- organic,- );- // None in a short range is usual: the card offers the month (spec §3.2).- const noneYet = aiKeyEvents === 0 && isShortRange(preset);- return {- value: formatNumber(aiKeyEvents),- // With a rate on show — few sessions: it's chance (§5.4); enough- // on both sides: against Google organic's (AT-005).- delta:- noneYet || rate === null- ? null- : aiSessions < LOW_SAMPLE_VISITS- ? delta({ kind: 'low' })- : ratio === null- ? null- : {- text: t('vsOrganic', { ratio: formatRatio(ratio) }),- tone: ratio > 1.05 ? 'good' : ratio < 0.95 ? 'bad' : 'neutral',- },- sub: noneYet ? (- <>- {t('keyEventsNone', { range: preset })} ·{' '}- <SubAction onClick={() => onRangeChange('30d')}>{t('see30d')}</SubAction>- </>- ) : rate === null ? (- t('keyEventsSub', { sessions: aiSessions })- ) : aiRevenue > 0 ? (- // Purchase revenue, when the property reports it (AT-005).- t('keyEventRateRevenue', { rate, revenue: formatNumber(Math.round(aiRevenue)) })- ) : (- t('keyEventRate', { rate })- ),- };- })}+ label={t('platforms')}+ tooltip={t('platformsTip')}+ icon={LayoutGrid}+ value={formatNumber(summary?.platformBreakdown.length ?? 0)}+ sub={t('platformsSub')}/>- )}- {gate('googleClicks', clicks) ?? <MetricCard {...clicks} {...clicksBody()} />}+ {gate('aiShare', aiShare) ?? (+ <MetricCard+ {...aiShare}+ {...(summaryLoading+ ? // The visits and the sessions must be the same range's.+ PENDING+ : fromGa(({ sessions }) => ({+ value: formatShare(totalVisits, sessions) ?? '—',+ sub: t('aiShareSub', { visits: totalVisits, sessions }),+ })))}+ />+ )}+ {/* Row 2: what AI visitors do, and Google's own clicks. */}+ {gate('engagedVisits', engaged) ?? (+ <MetricCard+ {...engaged}+ {...fromGa(({ aiSessions, aiEngagedSessions, organic }) =>+ aiSessions === 0+ ? { value: '—', sub: t('noAiSessions') }+ : {+ value: formatShare(aiEngagedSessions, aiSessions) ?? '—',+ // A rate on a handful of sessions says more about chance (§5.4).+ delta: aiSessions < LOW_SAMPLE_VISITS ? delta({ kind: 'low' }) : null,+ // Beside Google organic's, as the mockup draws it (AT-005).+ sub:+ organic.sessions > 0+ ? t('engagedVsOrganic', {+ rate: formatShare(organic.engagedSessions, organic.sessions)!,+ })+ : t('engagedSub', { engaged: aiEngagedSessions, sessions: aiSessions }),+ },+ )}+ />+ )}+ {gate('keyEvents', keyEvents) ?? (+ <MetricCard+ {...keyEvents}+ {...fromGa((totals) => {+ const { aiSessions, aiKeyEvents, aiKeyEventSessions, aiRevenue, organic } = totals;+ // Rows synced before the session key event rate have key events+ // but no count of the sessions holding them: no rate until the+ // history is re-read.+ const rateKnown = aiKeyEventSessions > 0 || aiKeyEvents === 0;+ const rate = rateKnown ? formatShare(aiKeyEventSessions, aiSessions) : null;+ const ratio = organicRatio(+ {+ sessions: aiSessions,+ keyEvents: aiKeyEvents,+ keyEventSessions: aiKeyEventSessions,+ },+ organic,+ );+ // None in a short range is usual: the card offers the month (spec §3.2).+ const noneYet = aiKeyEvents === 0 && isShortRange(preset);+ return {+ value: formatNumber(aiKeyEvents),+ // With a rate on show — few sessions: it's chance (§5.4); enough+ // on both sides: against Google organic's (AT-005).+ delta:+ noneYet || rate === null+ ? null+ : aiSessions < LOW_SAMPLE_VISITS+ ? delta({ kind: 'low' })+ : ratio === null+ ? null+ : {+ text: t('vsOrganic', { ratio: formatRatio(ratio) }),+ tone: ratio > 1.05 ? 'good' : ratio < 0.95 ? 'bad' : 'neutral',+ },+ sub: noneYet ? (+ <>+ {t('keyEventsNone', { range: preset })} ·{' '}+ <SubAction onClick={() => onRangeChange('30d')}>{t('see30d')}</SubAction>+ </>+ ) : rate === null ? (+ t('keyEventsSub', { sessions: aiSessions })+ ) : aiRevenue > 0 ? (+ // Purchase revenue, when the property reports it (AT-005).+ t('keyEventRateRevenue', { rate, revenue: formatNumber(Math.round(aiRevenue)) })+ ) : (+ t('keyEventRate', { rate })+ ),+ };+ })}+ />+ )}+ {gate('googleClicks', clicks) ?? <MetricCard {...clicks} {...clicksBody()} />}+ </div></div>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsxnew file mode 100644index 000000000..e22775f25--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx@@ -0,0 +1,145 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { TrafficDateWindow, TrafficSummary } from '@/lib/actions/traffic';++/**+ * The summary line (AT-007, spec §3.1): fixed sentences from the page's+ * aggregates, only with facts from connected sources, and nothing until+ * every number it states has loaded.+ */++const getTrafficPages = vi.fn();+vi.mock('@/lib/actions/traffic', () => ({+ getTrafficPages: (...args: unknown[]) => getTrafficPages(...args),+}));++const { SummaryLine } = await import('./_summary-line');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const WEEK: TrafficDateWindow = { dateFrom: '2026-10-11T09:00:00.000Z' };+const ga = (sessions: number, keyEvents: number, keyEventSessions = keyEvents) => ({+ sessions,+ engagedSessions: sessions,+ keyEvents,+ keyEventSessions,+});++const summary = (over: Partial<TrafficSummary> = {}): TrafficSummary => ({+ totalVisits: 64,+ totalVisitsPrev: 57,+ totalPageviews: 80,+ analyticsDays: [],+ hasPreviousPeriod: true,+ hasAnyData: true,+ topPages: [],+ platformBreakdown: [+ { platform: 'chatgpt.com', visits: 38, visitsPrev: 30, analytics: ga(40, 5, 4) },+ { platform: 'perplexity.ai', visits: 20, visitsPrev: 20, analytics: ga(31, 6, 5) },+ ],+ ...over,+});++const cited = (count: number) => ({+ counts: { noAiTraffic: 0, citedNotClicked: count, trafficNoPrompt: 0, all: 0 },+ rows: [],+});++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ getTrafficPages.mockReset().mockResolvedValue(cited(2));+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render({+ sum = summary(),+ // 'loading' stands for undefined, which a default would swallow.+ gaSessions = 8000 as number | null | 'loading',+ summaryLoading = false,+} = {}) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <SummaryLine+ brandId="b1"+ dateWindow={WEEK}+ rangeLabel="last 7 days"+ summary={sum}+ summaryLoading={summaryLoading}+ gaSessions={gaSessions === 'loading' ? undefined : gaSessions}+ />+ </NextIntlClientProvider>,+ );+ });+}++const text = () => container.textContent ?? '';++describe('SummaryLine', () => {+ it('says the range in one or two sentences, with Analytics connected', async () => {+ await render();+ expect(getTrafficPages).toHaveBeenCalledWith('b1', WEEK, { tab: 'citedNotClicked', limit: 0 });+ expect(text()).toBe(+ 'Last 7 days: 64 AI-referred visits, 0.8% of all traffic, up 12% on the previous period. ' ++ 'ChatGPT sent the most (38); Perplexity visitors convert best (16.1% of their visits had a key event). ' ++ '2 pages are cited in AI answers but get no clicks.',+ );+ });++ it('states nothing from Analytics without it (§3.8b rule 5)', async () => {+ getTrafficPages.mockResolvedValue(cited(0));+ await render({ gaSessions: null });+ expect(text()).toBe(+ 'Last 7 days: 64 AI-referred visits, up 12% on the previous period. ChatGPT sent the most (38).',+ );+ });++ it('joins the top and best platform when they are the same', async () => {+ await render({+ sum: summary({+ platformBreakdown: [+ { platform: 'chatgpt.com', visits: 38, visitsPrev: 30, analytics: ga(40, 9, 8) },+ { platform: 'perplexity.ai', visits: 20, visitsPrev: 20, analytics: ga(31, 6, 5) },+ ],+ }),+ });+ expect(text()).toContain(+ 'ChatGPT sent the most (38), and its visitors convert best (20% of their visits had a key event).',+ );+ });++ it('says when there were no visits, and leaves out a change below 30 visits', async () => {+ getTrafficPages.mockResolvedValue(cited(1));+ await render({+ sum: summary({ totalVisits: 0, totalVisitsPrev: 0, platformBreakdown: [] }),+ });+ expect(text()).toBe(+ 'Last 7 days: no AI-referred visits yet. 1 page is cited in AI answers but gets no clicks.',+ );++ await render({ sum: summary({ totalVisits: 12, totalVisitsPrev: 9 }), gaSessions: null });+ expect(text()).not.toContain('previous period');+ });++ it('waits for Analytics and the summary rather than changing under the reader', async () => {+ await render({ gaSessions: 'loading' });+ expect(text()).toBe('');+ expect(container.querySelector('[data-slot="skeleton"]')).not.toBeNull();++ await render({ summaryLoading: true });+ expect(text()).toBe('');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsxnew file mode 100644index 000000000..20620082f--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx@@ -0,0 +1,117 @@+'use client';++import { useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Skeleton } from '@/components/ui/skeleton';+import { formatNumber } from '@/lib/format';+import { getPlatformName } from '@/lib/traffic-platforms';+import { summaryLine } from '@/lib/traffic-summary-line';+import {+ getTrafficPages,+ type TrafficDateWindow,+ type TrafficSummary,+} from '@/lib/actions/traffic';++/**+ * The summary line above the KPI cards (AT-007, spec §3.1): the range's+ * visits, their share of all traffic and change, the top and best-converting+ * platforms, and the pages answers cite that nobody clicks, in one or two+ * sentences with a fixed template. Analytics' facts appear only while it is+ * connected (§3.8b rule 5); the line waits for every number it states, so it+ * never changes under the reader.+ */+export function SummaryLine({+ brandId,+ dateWindow,+ rangeLabel,+ summary,+ summaryLoading,+ gaSessions,+}: {+ brandId: string;+ dateWindow: TrafficDateWindow;+ /** The page's own words for the range, e.g. "last 7 days". */+ rangeLabel: string;+ summary: TrafficSummary | null;+ /** The summary is still the previous range's while a new one loads. */+ summaryLoading: boolean;+ /**+ * Every session Analytics recorded on the range's days: null when it isn't+ * connected or couldn't be read, undefined while it loads.+ */+ gaSessions: number | null | undefined;+}) {+ const t = useTranslations('traffic.summaryLine');+ const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}`;+ // The Cited, not clicked count for the range (AT-006), as the Pages tab counts it.+ const [cited, setCited] = useState<{ key: string; count: number | null } | null>(null);++ useEffect(() => {+ let cancelled = false;+ getTrafficPages(brandId, dateWindow, { tab: 'citedNotClicked', limit: 0 })+ .then((pages) => {+ if (!cancelled) setCited({ key, count: pages.counts.citedNotClicked });+ })+ .catch(() => {+ // Best effort: the line still states what else it knows.+ if (!cancelled) setCited({ key, count: null });+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, dateWindow, key]);++ const citedNow = cited?.key === key ? cited : null;+ if (!summary || summaryLoading || gaSessions === undefined || !citedNow) {+ return <Skeleton className="h-4 w-2/3" />;+ }++ const line = summaryLine({+ totalVisits: summary.totalVisits,+ totalVisitsPrev: summary.totalVisitsPrev,+ hasPreviousPeriod: summary.hasPreviousPeriod,+ platforms: summary.platformBreakdown,+ gaSessions,+ citedNotClicked: citedNow.count,+ });+ const range = rangeLabel.charAt(0).toUpperCase() + rangeLabel.slice(1);++ const sentences: string[] = [];+ if (line.visits === 0) {+ sentences.push(t('none', { range }));+ } else {+ const first = [t('visits', { range, count: line.visits })];+ if (line.share) first.push(t('share', { share: line.share }));+ if (line.change !== null) {+ first.push(t(line.change > 0 ? 'up' : 'down', { pct: formatNumber(Math.abs(line.change)) }));+ }+ sentences.push(`${first.join(', ')}.`);++ const best = line.best;+ const rate = best ? `${best.rate.toLocaleString('en-US')}%` : '';+ if (line.top && best && best.platform === line.top.platform) {+ sentences.push(+ t('topAndBest', {+ platform: getPlatformName(line.top.platform),+ count: formatNumber(line.top.visits),+ rate,+ }),+ );+ } else {+ const second: string[] = [];+ if (line.top) {+ second.push(+ t('top', {+ platform: getPlatformName(line.top.platform),+ count: formatNumber(line.top.visits),+ }),+ );+ }+ if (best) second.push(t('best', { platform: getPlatformName(best.platform), rate }));+ if (second.length) sentences.push(`${second.join('; ')}.`);+ }+ }+ if (line.citedNotClicked > 0) sentences.push(t('cited', { count: line.citedNotClicked }));++ return <p className="text-sm text-muted-foreground">{sentences.join(' ')}</p>;+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex aa5e67a77..ed7687aef 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -681,6 +681,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {{/* KPI cards: two rows of four (AT-017, spec §3.2). */}<TrafficKpisbrandId={brand.id}+ rangeLabel={rangeSubLabel}dateWindow={dateWindow}preset={datePreset}summary={summary}diff --git a/web/src/lib/traffic-summary-line.test.ts b/web/src/lib/traffic-summary-line.test.tsnew file mode 100644index 000000000..3eea637cb--- /dev/null+++ b/web/src/lib/traffic-summary-line.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';+import { bestConvertingPlatform, summaryLine, type SummaryLineInput } from './traffic-summary-line';++/** The summary line's facts (AT-007): each kept only when the page would state it. */++const ga = (sessions: number, keyEvents: number, keyEventSessions = keyEvents) => ({+ sessions,+ engagedSessions: sessions,+ keyEvents,+ keyEventSessions,+});++const input = (over: Partial<SummaryLineInput> = {}): SummaryLineInput => ({+ totalVisits: 64,+ totalVisitsPrev: 57,+ hasPreviousPeriod: true,+ platforms: [+ { platform: 'chatgpt.com', visits: 38, analytics: ga(40, 5, 4) },+ { platform: 'perplexity.ai', visits: 20, analytics: ga(31, 6, 5) },+ { platform: 'gemini.google.com', visits: 6, analytics: ga(6, 3) },+ ],+ gaSessions: 8000,+ citedNotClicked: 2,+ ...over,+});++describe('summaryLine', () => {+ it('states the visits, share, change, top and best platforms, and cited pages', () => {+ expect(summaryLine(input())).toEqual({+ visits: 64,+ share: '0.8%',+ change: 12,+ top: { platform: 'chatgpt.com', visits: 38 },+ best: { platform: 'perplexity.ai', rate: 16.1 },+ citedNotClicked: 2,+ });+ });++ it('leaves out what needs Google Analytics without it (§3.8b rule 5)', () => {+ const line = summaryLine(input({ gaSessions: null }));+ expect(line.share).toBeNull();+ expect(line.best).toBeNull();+ expect(line.top).toEqual({ platform: 'chatgpt.com', visits: 38 });+ });++ it('states no change below 30 visits in either period, or without a previous one', () => {+ expect(summaryLine(input({ totalVisitsPrev: 29 })).change).toBeNull();+ expect(summaryLine(input({ hasPreviousPeriod: false })).change).toBeNull();+ expect(summaryLine(input({ totalVisits: 50, totalVisitsPrev: 100 })).change).toBe(-50);+ });++ it('says nothing about cited pages while their count is unknown or zero', () => {+ expect(summaryLine(input({ citedNotClicked: null })).citedNotClicked).toBe(0);+ expect(summaryLine(input({ platforms: [] })).top).toBeNull();+ });+});++describe('bestConvertingPlatform', () => {+ it('compares only platforms with 30 visits and 5 key events, two or more (§5.4)', () => {+ expect(+ bestConvertingPlatform([+ { platform: 'chatgpt.com', visits: 38, analytics: ga(40, 5, 4) },+ { platform: 'gemini.google.com', visits: 6, analytics: ga(6, 6) },+ ]),+ ).toBeNull();+ expect(+ bestConvertingPlatform([+ { platform: 'chatgpt.com', visits: 38, analytics: ga(40, 5, 4) },+ { platform: 'perplexity.ai', visits: 20, analytics: ga(31, 4, 4) },+ ]),+ ).toBeNull();+ });++ it('skips platforms without a session rate or Analytics figures', () => {+ expect(+ bestConvertingPlatform([+ { platform: 'chatgpt.com', visits: 38, analytics: ga(40, 5, 4) },+ { platform: 'perplexity.ai', visits: 20, analytics: ga(31, 9, 0) },+ { platform: 'claude.ai', visits: 9, analytics: null },+ ]),+ ).toBeNull();+ });+});diff --git a/web/src/lib/traffic-summary-line.ts b/web/src/lib/traffic-summary-line.tsnew file mode 100644index 000000000..b0e084713--- /dev/null+++ b/web/src/lib/traffic-summary-line.ts@@ -0,0 +1,79 @@+/**+ * The AI Traffic page's summary line (AT-007, spec §3.1): one or two+ * sentences from the page's own aggregates, with a fixed template and no+ * model. Each fact is kept only when the page itself would state it:+ *+ * - the change on the previous period, when both periods have 30 visits+ * (AT-003, F4);+ * - the share of all traffic and the best-converting platform, only from a+ * connected Google Analytics (§3.8b rule 5: without GA4 it never says+ * "Perplexity visitors convert best");+ * - the best-converting platform, only when at least two platforms have 30+ * visits and 5 key events, the bar for comparing conversions (§5.4).+ *+ * Pure: the component renders the words.+ */++import type { TrafficEngagement } from '@/lib/actions/traffic';+import { LOW_SAMPLE_VISITS, visitChange } from '@/lib/traffic-change';+import { formatShare } from '@/lib/traffic-kpis';++/** Key events a platform needs before its conversions are compared (§5.4). */+export const MIN_COMPARED_KEY_EVENTS = 5;++export interface SummaryLineInput {+ totalVisits: number;+ totalVisitsPrev: number;+ hasPreviousPeriod: boolean;+ /** The range's platforms, most visits first, with Analytics' figures for each. */+ platforms: { platform: string; visits: number; analytics: TrafficEngagement | null }[];+ /** Every session Analytics recorded on the range's days; null when it isn't connected. */+ gaSessions: number | null;+ /** Pages answers cite 20+ times with no AI visit (AT-006); null while unknown. */+ citedNotClicked: number | null;+}++export interface SummaryLine {+ visits: number;+ /** "0.8%" of all traffic. */+ share: string | null;+ /** The % change on the previous period, when there is one to state. */+ change: number | null;+ top: { platform: string; visits: number } | null;+ /** The platform whose visitors convert best, with its session key event rate. */+ best: { platform: string; rate: number } | null;+ /** 0 says nothing. */+ citedNotClicked: number;+}++/** The platform whose visits convert best, when two or more can be compared. */+export function bestConvertingPlatform(+ platforms: SummaryLineInput['platforms'],+): { platform: string; rate: number } | null {+ const compared = platforms.flatMap((p) => {+ const a = p.analytics;+ if (!a || a.sessions < LOW_SAMPLE_VISITS || a.keyEvents < MIN_COMPARED_KEY_EVENTS) return [];+ // No session rate yet (rows synced before it was read): nothing to compare.+ if (a.keyEventSessions <= 0) return [];+ return [{ platform: p.platform, rate: a.keyEventSessions / a.sessions }];+ });+ if (compared.length < 2) return null;+ const best = compared.reduce((a, b) => (b.rate > a.rate ? b : a));+ return { platform: best.platform, rate: Math.round(best.rate * 1000) / 10 };+}++export function summaryLine(input: SummaryLineInput): SummaryLine {+ const change = visitChange(input.totalVisits, input.totalVisitsPrev, {+ comparable: input.hasPreviousPeriod,+ });+ const top = input.platforms[0];+ const ga = input.gaSessions !== null;+ return {+ visits: input.totalVisits,+ share: ga ? formatShare(input.totalVisits, input.gaSessions ?? 0) : null,+ change: change.kind === 'pct' ? change.pct : null,+ top: top && top.visits > 0 ? { platform: top.platform, visits: top.visits } : null,+ best: ga ? bestConvertingPlatform(input.platforms) : null,+ citedNotClicked: input.citedNotClicked ?? 0,+ };+}