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): show a Google-dependent section's source state instead of hiding it (#1160)
Cihana44421c2ef7b
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 7a99f6cc4..2d7f4322c 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3109,9 +3109,30 @@"manage": "Manage","connectNotAllowed": "Only admins and managers can connect a source."},+ "gate": {+ "needs": "Needs {source}",+ "notConnectedTitle": "Connect {source} to see this",+ "notConnectedGa": "Shows which AI visits engage, convert and earn revenue. Read-only access, takes about a minute.",+ "notConnectedGsc": "Shows Google clicks and AI Overviews / AI Mode impressions per page. Read-only access.",+ "connect": "Connect {source}",+ "neededFor": "Needed for: {sections}",+ "syncingTitleGa": "Importing your Google Analytics data",+ "syncingTitleGsc": "Google Search Console data is on its way",+ "syncingGa": "First numbers in about 15 minutes. Up to 14 months of history can take up to 24 hours.",+ "syncingGsc": "Google reports with about a 2-day delay, so the first numbers can take up to 48 hours.",+ "connectedTo": "Connected to {property}",+ "unmappedTitle": "Choose a property for this brand",+ "unmapped": "{source} is connected, but no property is chosen for this brand yet.",+ "notConfiguredTitle": "Not set up on this server",+ "notConfigured": "{source} needs its connection keys on this Ansvisor server before anyone can connect it.",+ "noData": "No data for this range in {source}",+ "showAllTime": "Show all time",+ "sections": {+ "pageOpportunities": "pages AI engines aren't sending traffic to"+ }+ },"pageOpportunities": {"title": "Pages AI engines aren't sending traffic to",- "badge": "Google Analytics · {range}","explain": "{ranking} None of these got a visit from an AI assistant in this range, in Google Analytics or through the tracking snippet, and <b>AI visibility</b> says why: whether answers already cite the page, whether a prompt you track points at it, or whether nothing does.","empty": "No high-value pages without AI traffic in this range.","page": "Page",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsxindex b557fd80f..9ea0eedba 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.test.tsx@@ -4,17 +4,24 @@ import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../messages/en.json';import type { PageOpportunities, PageOpportunity, TrafficDateWindow } from '@/lib/actions/traffic';+import type { SourceState } from '@/lib/actions/integrations';/**- * AT-002: "Pages AI engines aren't sending traffic to" reads the range the- * page shows, says which range in its badge, and stays put with a note when- * nothing in that range qualifies.+ * "Pages AI engines aren't sending traffic to" reads the range the page+ * shows and names it (AT-002), says it needs Google Analytics, and shows+ * Analytics' own state until there is data from it (AT-016).*/const getPageOpportunities = vi.fn();vi.mock('@/lib/actions/traffic', () => ({getPageOpportunities: (...args: unknown[]) => getPageOpportunities(...args),}));+vi.mock('@/hooks/use-integration-connect', () => ({+ useIntegrationConnect: () => ({ connecting: false, connect: vi.fn() }),+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,+}));const { PageOpportunitiesCard } = await import('./_opportunities-card');@@ -39,14 +46,26 @@ const finding = (over: Partial<PageOpportunity> = {}): PageOpportunity => ({...over,});+const ga = (over: Partial<SourceState> = {}): SourceState => ({+ configured: true,+ connected: true,+ mapped: true,+ firstDataAt: '2026-09-01T06:00:00.000Z',+ lastDataAt: '2026-10-18T06:00:00.000Z',+ property: '123456789',+ ...over,+});+const WEEK: TrafficDateWindow = { dateFrom: '2026-10-11T09:00:00.000Z' };const MONTH: TrafficDateWindow = { dateFrom: '2026-09-18T09:00:00.000Z' };let container: HTMLDivElement;let root: Root;+const onShowAllTime = vi.fn();beforeEach(() => {getPageOpportunities.mockReset();+ onShowAllTime.mockReset();container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -57,27 +76,47 @@ afterEach(() => {container.remove();});-async function render(dateWindow: TrafficDateWindow, rangeLabel: string) {+async function render(+ dateWindow: TrafficDateWindow,+ rangeLabel: string,+ {+ source = ga(),+ sourceUnknown = false,+ showAll = true,+ }: { source?: SourceState | null; sourceUnknown?: boolean; showAll?: boolean } = {},+) {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">- <PageOpportunitiesCard brandId="b1" dateWindow={dateWindow} rangeLabel={rangeLabel} />+ <PageOpportunitiesCard+ brandId="b1"+ dateWindow={dateWindow}+ rangeLabel={rangeLabel}+ source={source}+ sourceUnknown={sourceUnknown}+ domain="acme.example"+ canConnect+ onConnected={() => {}}+ onShowAllTime={showAll ? onShowAllTime : undefined}+ /></NextIntlClientProvider>,);});}const resolveWith = (result: PageOpportunities) => getPageOpportunities.mockResolvedValue(result);+const text = () => container.textContent ?? '';describe('PageOpportunitiesCard', () => {- it("asks for the page's range and names it in the badge", async () => {+ it("asks for the page's range, names it, and says it needs Google Analytics", async () => {resolveWith({ pages: 30, rows: [finding()] });await render(WEEK, 'last 7 days');expect(getPageOpportunities).toHaveBeenCalledWith('b1', WEEK);- expect(container.textContent).toContain('Google Analytics · last 7 days');- expect(container.textContent).not.toContain('28 days');- expect(container.textContent).toContain('in this range');+ expect(text()).toContain('Needs Google Analytics');+ expect(text()).toContain('last 7 days');+ expect(text()).not.toContain('28 days');+ expect(text()).toContain('in this range');});it('reads the new range when the page changes it', async () => {@@ -87,9 +126,9 @@ describe('PageOpportunitiesCard', () => {await render(MONTH, 'last 30 days');expect(getPageOpportunities).toHaveBeenLastCalledWith('b1', MONTH);- expect(container.textContent).toContain('Google Analytics · last 30 days');- expect(container.textContent).toContain('/demo');- expect(container.textContent).not.toContain('/pricing');+ expect(text()).toContain('last 30 days');+ expect(text()).toContain('/demo');+ expect(text()).not.toContain('/pricing');});it('keeps the previous range on screen, faded, while the new one loads', async () => {@@ -102,7 +141,7 @@ describe('PageOpportunitiesCard', () => {expect(card).not.toBeNull();expect(card!.textContent).toContain('/pricing');// The faded rows still name the range they were ranked for.- expect(card!.textContent).toContain('Google Analytics · last 7 days');+ expect(card!.textContent).toContain('last 7 days');expect(card!.textContent).not.toContain('last 30 days');});@@ -116,33 +155,71 @@ describe('PageOpportunitiesCard', () => {});await render(WEEK, 'last 7 days');- const text = container.textContent ?? '';- expect(text).toContain('Ranked by the conversions Analytics records on these pages.');- expect(text).toContain('Conversions');- expect(text).toContain('Rank by conversions');- expect(text).toContain('Not cited');- expect(text).toContain('1 prompt targets this page');- expect(text).toContain('3 citations in answers');+ expect(text()).toContain('Ranked by the conversions Analytics records on these pages.');+ expect(text()).toContain('Conversions');+ expect(text()).toContain('Rank by conversions');+ expect(text()).toContain('Not cited');+ expect(text()).toContain('1 prompt targets this page');+ expect(text()).toContain('3 citations in answers');});it('says nothing qualifies when Analytics has data for the range', async () => {resolveWith({ pages: 30, rows: [] });await render(WEEK, 'last 24 hours');- expect(container.textContent).toContain('Google Analytics · last 24 hours');- expect(container.textContent).toContain(- 'No high-value pages without AI traffic in this range.',- );+ expect(text()).toContain('No high-value pages without AI traffic in this range.');expect(container.querySelector('table')).toBeNull();});- it('renders nothing when Analytics has no data for the range', async () => {+ it('says Analytics has no data for the range, with a way to widen it', async () => {resolveWith({ pages: 0, rows: [] });await render(WEEK, 'last 7 days');++ expect(text()).toContain('No data for this range in Google Analytics');+ const showAll = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Show all time',+ );+ await act(async () => showAll!.click());+ expect(onShowAllTime).toHaveBeenCalled();+ });++ it('offers no wider range when it already shows all time', async () => {+ resolveWith({ pages: 0, rows: [] });+ await render({}, 'all time', { showAll: false });+ expect(text()).toContain('No data for this range in Google Analytics');+ expect(text()).not.toContain('Show all time');+ });++ it("shows Analytics' state, and reads nothing, until Analytics has data", async () => {+ await render(WEEK, 'last 7 days', { source: ga({ connected: false, mapped: false }) });+ expect(text()).toContain('Needs Google Analytics');+ expect(text()).toContain('Connect Google Analytics to see this');++ await render(WEEK, 'last 7 days', { source: ga({ lastDataAt: null }) });+ expect(text()).toContain('Importing your Google Analytics data');++ await render(WEEK, 'last 7 days', { source: ga({ mapped: false }) });+ expect(text()).toContain('Choose a property for this brand');++ expect(getPageOpportunities).not.toHaveBeenCalled();+ // The range belongs to the data, so it shows only with data.+ expect(text()).not.toContain('last 7 days');+ });++ it('waits for the state before showing anything', async () => {+ await render(WEEK, 'last 7 days', { source: null });expect(container.innerHTML).toBe('');+ expect(getPageOpportunities).not.toHaveBeenCalled();+ });++ it('reads the range anyway when the state could not be read', async () => {+ resolveWith({ pages: 30, rows: [finding()] });+ await render(WEEK, 'last 7 days', { source: null, sourceUnknown: true });+ expect(getPageOpportunities).toHaveBeenCalledWith('b1', WEEK);+ expect(text()).toContain('/pricing');});- it('renders nothing when the read fails, and leaves the page alone', async () => {+ it('hides itself when the read fails, rather than claim there is no data', async () => {const error = vi.spyOn(console, 'error').mockImplementation(() => {});getPageOpportunities.mockRejectedValue(new Error('Server error: 500'));await render(WEEK, 'last 7 days');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsxindex d0bfc0cf9..f379e34fc 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx@@ -12,6 +12,7 @@ import {TableHeader,TableRow,} from '@/components/ui/table';+import { Skeleton } from '@/components/ui/skeleton';import { Target } from 'lucide-react';import { cn } from '@/lib/utils';import { formatNumber } from '@/lib/format';@@ -21,6 +22,9 @@ import {type PageOpportunity,type TrafficDateWindow,} from '@/lib/actions/traffic';+import type { SourceState } from '@/lib/actions/integrations';+import { TRAFFIC_SECTION_SOURCES, googleSourceStatus } from '@/lib/traffic-sources';+import { NeedsTag, SourceNoData, SourceUnavailable } from './_source-gate';/*** Pages that carry weight and get nothing from AI engines (#719), for the@@ -30,12 +34,15 @@ import {* so no section of the page has its own hidden window, and a page the* tracking snippet saw AI visitors on is never listed here.*- * Renders nothing when Analytics has no data for the range — a brand- * without a mapped Analytics property should not meet an empty card- * explaining a feature it has not connected. With data but no finding, it- * says so, so the card doesn't vanish as the range changes.+ * It needs Google Analytics, and says so beside its title (AT-016). Until+ * Analytics has data it shows the source's state in place of the list — not+ * connected, syncing, or no property for this brand — and with no Analytics+ * data for the range it says that. With data but no finding it says so too,+ * so the card never vanishes or stands blank.*/+const PROVIDER = TRAFFIC_SECTION_SOURCES.pageOpportunities;+/*** The ranking is described in the words of the metric that produced it* (`signals.*` in the messages). The engine ranks on whatever the property@@ -69,13 +76,31 @@ export function PageOpportunitiesCard({brandId,dateWindow,rangeLabel,+ source,+ sourceUnknown = false,+ domain,+ canConnect,+ onConnected,+ onShowAllTime,}: {brandId: string;dateWindow: TrafficDateWindow;/** The page's own words for the range, e.g. "last 7 days". */rangeLabel: string;+ /** Google Analytics' state for the brand; null while it loads. */+ source: SourceState | null;+ /** The state couldn't be read: show what the range has, as before AT-016. */+ sourceUnknown?: boolean;+ /** The brand's primary domain, for the property line. */+ domain: string | undefined;+ canConnect: boolean;+ onConnected: () => void;+ /** Widens the page's range; absent when it is already all time. */+ onShowAllTime?: () => void;}) {const t = useTranslations('traffic.pageOpportunities');+ const status = source ? googleSourceStatus(source) : sourceUnknown ? 'connected' : null;+ const connected = status === 'connected';const windowKey = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}`;// The loaded result carries the brand and range it belongs to, rather than// a separate loading flag reset inside the effect: resetting state@@ -86,10 +111,13 @@ export function PageOpportunitiesCard({windowKey: string;/** The range the rows were ranked for, which a faded card still names. */rangeLabel: string;- result: PageOpportunities;+ /** Null when the read failed. */+ result: PageOpportunities | null;} | null>(null);useEffect(() => {+ // Nothing to rank until Analytics has data for this brand.+ if (!connected) return;let cancelled = false;getPageOpportunities(brandId, dateWindow).then((result) => {@@ -99,22 +127,24 @@ export function PageOpportunitiesCard({// Best effort: this card is an addition to the page, and a failure// here must not take the traffic analytics down with it.console.error('Failed to load page opportunities:', err);- if (!cancelled) {- setLoaded({ brandId, windowKey, rangeLabel, result: { pages: 0, rows: [] } });- }+ if (!cancelled) setLoaded({ brandId, windowKey, rangeLabel, result: null });});return () => {cancelled = true;};- }, [brandId, dateWindow, windowKey, rangeLabel]);+ }, [connected, brandId, dateWindow, windowKey, rangeLabel]);++ // The state is still loading: a moment, not worth a placeholder. A failed+ // read hides the card rather than claim Analytics has no data.+ if (!status) return null;+ if (connected && loaded?.brandId === brandId && loaded.result === null) return null;// Another brand's findings must never render under this brand's name. A// new range keeps the previous one's card, faded, until it loads, as the// rest of the page does.- if (loaded?.brandId !== brandId || loaded.result.pages === 0) return null;- const stale = loaded.windowKey !== windowKey;-- const { rows } = loaded.result;+ const shown = connected && loaded?.brandId === brandId ? loaded : null;+ const stale = shown !== null && shown.windowKey !== windowKey;+ const rows = shown?.result?.rows ?? [];const signal = rows[0]?.valueSignal;return (@@ -124,20 +154,44 @@ export function PageOpportunitiesCard({<CardTitle className="flex items-center gap-2 text-sm font-medium"><Target className="h-4 w-4 text-muted-foreground" />{t('title')}+ <NeedsTag provider={PROVIDER} /></CardTitle>- <Badge variant="outline" className="text-xs">- {t('badge', { range: loaded.rangeLabel })}- </Badge>+ {shown && (+ <Badge variant="outline" className="text-xs">+ {shown.rangeLabel}+ </Badge>+ )}</div>- <p className="text-xs text-muted-foreground">- {signal- ? t.rich('explain', {- ranking: t(`signals.${signal}.explain`),- b: (chunks) => <span className="font-medium">{chunks}</span>,- })- : t('empty')}- </p>+ {shown?.result && shown.result.pages > 0 && (+ <p className="text-xs text-muted-foreground">+ {signal+ ? t.rich('explain', {+ ranking: t(`signals.${signal}.explain`),+ b: (chunks) => <span className="font-medium">{chunks}</span>,+ })+ : t('empty')}+ </p>+ )}</CardHeader>+ {!connected && source && (+ <CardContent className="p-0">+ <SourceUnavailable+ provider={PROVIDER}+ state={source}+ domain={domain}+ canConnect={canConnect}+ onConnected={onConnected}+ />+ </CardContent>+ )}+ {connected && !shown && (+ <CardContent className="pb-4">+ <Skeleton className="h-4 w-64" />+ </CardContent>+ )}+ {shown?.result?.pages === 0 && (+ <SourceNoData provider={PROVIDER} onShowAllTime={onShowAllTime} />+ )}{signal && (<CardContent className="p-0"><Table>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.test.tsxnew file mode 100644index 000000000..481771313--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.test.tsx@@ -0,0 +1,169 @@+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 { IntegrationProvider, SourceState } from '@/lib/actions/integrations';++/**+ * AT-016: a section that needs Google Analytics or Google Search Console+ * says so, and is never blank: it shows what's missing and what happens next.+ */++const hook = vi.hoisted(() => ({+ connect: vi.fn(),+ options: null as null | { onStatus: (status: string) => void },+}));+vi.mock('@/hooks/use-integration-connect', () => ({+ useIntegrationConnect: (_provider: string, options: { onStatus: (s: string) => void }) => {+ hook.options = options;+ return { connecting: false, connect: hook.connect };+ },+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,+}));++const { NeedsTag, SourceNoData, SourceUnavailable } = await import('./_source-gate');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const source = (over: Partial<SourceState> = {}): SourceState => ({+ configured: true,+ connected: false,+ mapped: false,+ firstDataAt: null,+ lastDataAt: null,+ property: null,+ ...over,+});++let container: HTMLDivElement;+let root: Root;+const onConnected = vi.fn();++beforeEach(() => {+ vi.clearAllMocks();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function render(node: React.ReactNode) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+}++function renderState(+ state: SourceState,+ { provider = 'google-analytics', canConnect = true } = {} as {+ provider?: IntegrationProvider;+ canConnect?: boolean;+ },+) {+ render(+ <SourceUnavailable+ provider={provider}+ state={state}+ domain="acme.example"+ canConnect={canConnect}+ onConnected={onConnected}+ />,+ );+}++const text = () => container.textContent ?? '';+const button = () => container.querySelector('button');++describe('SourceUnavailable', () => {+ it('offers Connect in place, says what it shows, and what it unlocks', () => {+ renderState(source());+ expect(text()).toContain('Connect Google Analytics to see this');+ expect(text()).toContain('Read-only access, takes about a minute.');+ expect(text()).toContain("Needed for: pages AI engines aren't sending traffic to");++ act(() => button()!.click());+ expect(hook.connect).toHaveBeenCalled();+ // Once the account connects, the page reads the sources again.+ act(() => hook.options!.onStatus('connected'));+ expect(onConnected).toHaveBeenCalled();+ });++ it("keeps Connect off, with a reason, for members who can't connect", () => {+ renderState(source(), { canConnect: false });+ expect(button()!.disabled).toBe(true);+ expect(button()!.parentElement!.title).toBe('Only admins and managers can connect a source.');+ });++ it('says how long the first sync takes, and what is connected', () => {+ renderState(source({ connected: true, mapped: true, property: '123456789' }));+ expect(text()).toContain('Importing your Google Analytics data');+ expect(text()).toContain('First numbers in about 15 minutes.');+ expect(text()).toContain('Connected to acme.example (GA4)');+ expect(button()).toBeNull();+ });++ it("names Search Console's wait and property its own way", () => {+ renderState(source({ connected: true, mapped: true, property: 'sc-domain:acme.example' }), {+ provider: 'google-search-console',+ });+ expect(text()).toContain('Google Search Console data is on its way');+ expect(text()).toContain('up to 48 hours');+ expect(text()).toContain('Connected to acme.example (GSC)');+ });++ it('sends a connection with no property for the brand to Manage', () => {+ renderState(source({ connected: true }));+ expect(text()).toContain('Choose a property for this brand');+ expect(text()).toContain('Google Analytics is connected');+ expect(container.querySelector('a')!.getAttribute('href')).toBe(+ '/dashboard/settings?tab=integrations',+ );+ });++ it('offers nothing to click on a server without the connection keys', () => {+ renderState(source({ configured: false }));+ expect(text()).toContain('Not set up on this server');+ expect(button()).toBeNull();+ expect(container.querySelector('a')).toBeNull();+ });++ it('lists nothing it unlocks for a source no section needs yet', () => {+ renderState(source(), { provider: 'google-search-console' });+ expect(text()).toContain('Connect Google Search Console to see this');+ expect(text()).not.toContain('Needed for');+ });++ it('renders nothing once the source has data', () => {+ renderState(source({ connected: true, mapped: true, lastDataAt: '2026-10-18T06:00:00Z' }));+ expect(container.innerHTML).toBe('');+ });+});++describe('NeedsTag', () => {+ it('names the source a section needs', () => {+ render(<NeedsTag provider="google-search-console" />);+ expect(text()).toBe('Needs Google Search Console');+ });+});++describe('SourceNoData', () => {+ it('says the source has no data for the range, with a way to widen it', () => {+ const onShowAllTime = vi.fn();+ render(<SourceNoData provider="google-analytics" onShowAllTime={onShowAllTime} />);+ expect(text()).toContain('No data for this range in Google Analytics');+ act(() => button()!.click());+ expect(onShowAllTime).toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.tsxnew file mode 100644index 000000000..6d4783ff2--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_source-gate.tsx@@ -0,0 +1,208 @@+'use client';++import type { ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2, Plug } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { cn } from '@/lib/utils';+import { useIntegrationConnect } from '@/hooks/use-integration-connect';+import type { IntegrationProvider, SourceState } from '@/lib/actions/integrations';+import {+ INTEGRATIONS_SETTINGS_PATH,+ googleSourceStatus,+ sectionsNeeding,+ sourceHost,+} from '@/lib/traffic-sources';++/**+ * What a section that needs Google Analytics or Google Search Console shows+ * (AT-016, spec §3.8b), so that none is ever blank: a "Needs …" tag beside+ * its title, always, and — until the source has data — a state in place of+ * the data that says what's missing and what happens next.+ *+ * The full state is the one a section uses today. The compact KPI version+ * and the partial note come with the sections that need them.+ */++const isGa = (provider: IntegrationProvider) => provider === 'google-analytics';++/** "Needs Google Analytics": shown even when connected, so users learn where each number comes from. */+export function NeedsTag({ provider }: { provider: IntegrationProvider }) {+ const t = useTranslations('traffic');+ return (+ <span className="whitespace-nowrap rounded-md border px-1.5 text-[11px] font-medium leading-4 text-muted-foreground">+ {t('gate.needs', { source: isGa(provider) ? t('sources.ga') : t('sources.gsc') })}+ </span>+ );+}++function StateBlock({+ icon,+ title,+ body,+ action,+ footer,+}: {+ icon: ReactNode;+ title: string;+ body: string;+ action?: ReactNode;+ footer?: string;+}) {+ return (+ <div className="flex min-h-[120px] flex-col items-start justify-center gap-1.5 px-6 py-4">+ <div className="flex items-center gap-2 text-sm font-semibold">+ {icon}+ {title}+ </div>+ <p className="max-w-[460px] text-xs text-muted-foreground">{body}</p>+ {action}+ {footer && <p className="text-xs text-muted-foreground">{footer}</p>}+ </div>+ );+}++const plugIcon = (+ <span className="inline-flex h-[26px] w-[26px] items-center justify-center rounded-lg border bg-card text-muted-foreground">+ <Plug className="h-3.5 w-3.5" />+ </span>+);++/**+ * The state a section shows while its source has no data for it: not+ * connected (with Connect, in place), syncing (with the expected wait),+ * connected with no property for this brand (with Manage), or a server+ * without the keys to connect at all. Renders nothing once the source is+ * connected and synced; the section shows its data, or `SourceNoData`.+ */+export function SourceUnavailable({+ provider,+ state,+ domain,+ canConnect,+ onConnected,+}: {+ provider: IntegrationProvider;+ state: SourceState;+ /** The brand's primary domain, for the property line. */+ domain: string | undefined;+ /** Admins and managers; the server refuses anyone else. */+ canConnect: boolean;+ onConnected: () => void;+}) {+ const t = useTranslations('traffic');+ const source = isGa(provider) ? t('sources.ga') : t('sources.gsc');+ const { connecting, connect } = useIntegrationConnect(provider, {+ label: source,+ callbackUrl: () => window.location.href,+ onStatus: (status) => {+ if (status === 'connected') onConnected();+ },+ });++ const status = googleSourceStatus(state);+ if (status === 'connected') return null;++ if (status === 'syncing') {+ return (+ <StateBlock+ icon={<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />}+ title={isGa(provider) ? t('gate.syncingTitleGa') : t('gate.syncingTitleGsc')}+ body={isGa(provider) ? t('gate.syncingGa') : t('gate.syncingGsc')}+ footer={t('gate.connectedTo', {+ property: t('sources.property', {+ host: sourceHost(provider, state.property, domain),+ source: isGa(provider) ? 'GA4' : 'GSC',+ }),+ })}+ />+ );+ }++ if (status === 'unmapped') {+ return (+ <StateBlock+ icon={plugIcon}+ title={t('gate.unmappedTitle')}+ body={t('gate.unmapped', { source })}+ action={+ <Link+ href={INTEGRATIONS_SETTINGS_PATH}+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 text-xs')}+ >+ {t('sources.manage')}+ </Link>+ }+ />+ );+ }++ if (status === 'not_configured') {+ return (+ <StateBlock+ icon={plugIcon}+ title={t('gate.notConfiguredTitle')}+ body={t('gate.notConfigured', { source })}+ />+ );+ }++ const sections = new Intl.ListFormat('en', { type: 'conjunction' }).format(+ sectionsNeeding(provider).map((section) => t(`gate.sections.${section}`)),+ );+ return (+ <StateBlock+ icon={plugIcon}+ title={t('gate.notConnectedTitle', { source })}+ body={isGa(provider) ? t('gate.notConnectedGa') : t('gate.notConnectedGsc')}+ action={+ // A span carries the tooltip: a disabled button gets no hover.+ <span title={canConnect ? undefined : t('sources.connectNotAllowed')}>+ <Button+ size="sm"+ className="h-7 gap-1.5 text-xs"+ disabled={!canConnect || connecting}+ onClick={() => void connect()}+ >+ {connecting && <Loader2 className="h-3 w-3 animate-spin" />}+ {connecting ? t('sources.connecting') : t('gate.connect', { source })}+ </Button>+ </span>+ }+ footer={sections ? t('gate.neededFor', { sections }) : undefined}+ />+ );+}++/**+ * A connected source with no rows for the range: says so, with a way to+ * widen it. Never an empty table without text.+ */+export function SourceNoData({+ provider,+ onShowAllTime,+}: {+ provider: IntegrationProvider;+ /** Absent when the range is already all time. */+ onShowAllTime?: () => void;+}) {+ const t = useTranslations('traffic');+ return (+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-6 pb-4 text-xs text-muted-foreground">+ <span>+ {t('gate.noData', { source: isGa(provider) ? t('sources.ga') : t('sources.gsc') })}+ </span>+ {onShowAllTime && (+ <button+ type="button"+ onClick={onShowAllTime}+ className="font-medium text-foreground underline-offset-4 hover:underline"+ >+ {t('gate.showAllTime')}+ </button>+ )}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.tsxindex 3ef197665..fa9c78986 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.tsx@@ -12,7 +12,12 @@ import { formatRelative } from '@/lib/format-relative';import { useIntegrationConnect } from '@/hooks/use-integration-connect';import type { IntegrationProvider, SourceState } from '@/lib/actions/integrations';import type { TrafficSources } from '@/lib/actions/traffic';-import { googleSourceStatus, gscPropertyHost, snippetDetected } from '@/lib/traffic-sources';+import {+ INTEGRATIONS_SETTINGS_PATH,+ googleSourceStatus,+ snippetDetected,+ sourceHost,+} from '@/lib/traffic-sources';type Tone = 'on' | 'sync' | 'off';@@ -22,8 +27,6 @@ const DOT: Record<Tone, string> = {off: 'bg-muted-foreground/30',};-const SETTINGS_INTEGRATIONS = '/dashboard/settings?tab=integrations';-/** One source: a status dot by the title, a sub-line, and its button. */function SourceCard({tone,@@ -82,7 +85,7 @@ function GoogleSource({const manage = (<Link- href={SETTINGS_INTEGRATIONS}+ href={INTEGRATIONS_SETTINGS_PATH}className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 text-xs')}>{t('manage')}@@ -91,8 +94,7 @@ function GoogleSource({const status = googleSourceStatus(state);if (status === 'connected' || status === 'syncing') {- const host =- (!isGa && state.property ? gscPropertyHost(state.property) : domain) ?? state.property;+ const host = sourceHost(provider, state.property, domain);return (<SourceCardtone={status === 'connected' ? 'on' : 'sync'}@@ -100,7 +102,7 @@ function GoogleSource({line={status === 'connected'? t('synced', {- property: t('property', { host: host ?? '', source: isGa ? 'GA4' : 'GSC' }),+ property: t('property', { host, source: isGa ? 'GA4' : 'GSC' }),when: formatRelative(state.lastDataAt, tCommon),}): isGadiff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex 2ff0b28f2..4bcb01313 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -626,6 +626,25 @@ function TrafficPageContent({ brand }: { brand: Brand }) {const hasAnyData = summary?.hasAnyData ?? false;const trulyEmpty = isEmpty && !hasAnyData;+ // Findings from the Analytics connection (#719), for the page's range+ // (AT-002). They need Google Analytics, not the snippet, so the card shows+ // whatever the snippet has sent, with Analytics' own state until there is+ // data from it (AT-016). Kept apart from the snippet's tables: the two+ // origins are never summed; a page the snippet saw is just never listed.+ const opportunitiesCard = (+ <PageOpportunitiesCard+ brandId={brand.id}+ dateWindow={dateWindow}+ rangeLabel={rangeSubLabel}+ source={sources?.ga ?? null}+ sourceUnknown={sourcesFailed}+ domain={primaryDomain}+ canConnect={canManage}+ onConnected={() => void loadSources()}+ onShowAllTime={datePreset === 'all' ? undefined : () => handleDatePresetChange('all')}+ />+ );+return (<div className="space-y-6">{/* Header */}@@ -696,7 +715,9 @@ function TrafficPageContent({ brand }: { brand: Brand }) {rangeLabel={rangeSubLabel}onReset={() => handleDatePresetChange('all')}/>- ) : (+ ) : null}+ {isEmpty && opportunitiesCard}+ {!isEmpty && (<>{/* KPI Cards */}<div className="grid grid-cols-2 gap-4 sm:grid-cols-3">@@ -844,17 +865,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {</Card></div>- {/* Findings from the Analytics connection (#719), for the page's- range (AT-002). Renders nothing for brands without Analytics- data in it, so the page is unchanged for everyone who has not- connected one. Kept visually distinct from the tables above,- which count the tracking snippet's own visits — the two origins- are never summed; a page the snippet saw is just never listed. */}- <PageOpportunitiesCard- brandId={brand.id}- dateWindow={dateWindow}- rangeLabel={rangeSubLabel}- />+ {opportunitiesCard}{/* Recent Visit Log with filtering and pagination*/}<Card>diff --git a/web/src/lib/traffic-sources.test.ts b/web/src/lib/traffic-sources.test.tsindex 43fa46461..daefb138c 100644--- a/web/src/lib/traffic-sources.test.ts+++ b/web/src/lib/traffic-sources.test.ts@@ -1,5 +1,12 @@import { describe, expect, it } from 'vitest';-import { googleSourceStatus, gscPropertyHost, snippetDetected } from './traffic-sources';+import {+ TRAFFIC_SECTION_SOURCES,+ googleSourceStatus,+ gscPropertyHost,+ sectionsNeeding,+ snippetDetected,+ sourceHost,+} from './traffic-sources';const NOW = Date.parse('2026-10-18T12:00:00Z');const daysAgo = (d: number) => new Date(NOW - d * 86_400_000).toISOString();@@ -49,3 +56,31 @@ describe('gscPropertyHost', () => {expect(gscPropertyHost('ansvisor.com')).toBe('ansvisor.com');});});++describe('sectionsNeeding', () => {+ it('lists the sections a source unlocks (AT-016)', () => {+ expect(TRAFFIC_SECTION_SOURCES.pageOpportunities).toBe('google-analytics');+ expect(sectionsNeeding('google-analytics')).toEqual(['pageOpportunities']);+ });++ it('lists nothing for a source no section needs yet', () => {+ expect(sectionsNeeding('google-search-console')).toEqual([]);+ });+});++describe('sourceHost', () => {+ it('names a Search Console property by its own host', () => {+ expect(sourceHost('google-search-console', 'sc-domain:acme.example', 'other.example')).toBe(+ 'acme.example',+ );+ expect(sourceHost('google-search-console', 'https://blog.acme.example/', undefined)).toBe(+ 'blog.acme.example',+ );+ });++ it("names Google Analytics by the brand's domain, its property id names no site", () => {+ expect(sourceHost('google-analytics', '123456789', 'acme.example')).toBe('acme.example');+ expect(sourceHost('google-analytics', '123456789', undefined)).toBe('123456789');+ expect(sourceHost('google-analytics', null, undefined)).toBe('');+ });+});diff --git a/web/src/lib/traffic-sources.ts b/web/src/lib/traffic-sources.tsindex 53e90793d..e619b0ef8 100644--- a/web/src/lib/traffic-sources.ts+++ b/web/src/lib/traffic-sources.ts@@ -1,8 +1,11 @@/**- * The AI Traffic page's data sources strip (AT-001): which state each source- * is in, and how a Google property is named on it.+ * The AI Traffic page's data sources (AT-001, AT-016): which state each+ * source is in, how a Google property is named, and which sections need+ * which source.*/+import type { IntegrationProvider } from '@/lib/actions/integrations';+/** A snippet with no visit for this long reads as not detected, and its code box opens. */export const SNIPPET_ACTIVE_DAYS = 7;@@ -39,6 +42,9 @@ export function googleSourceStatus(source: {return source.lastDataAt ? 'connected' : 'syncing';}+/** Where a Google source's connection and property are managed. */+export const INTEGRATIONS_SETTINGS_PATH = '/dashboard/settings?tab=integrations';+/*** A Search Console property as the strip names it: the plain domain, never* "sc-domain:", and a URL-prefix property by its host.@@ -51,3 +57,37 @@ export function gscPropertyHost(property: string): string {return property;}}++/**+ * The host a connected source's property line names: the Search Console+ * property's own host, or the brand's domain for Google Analytics, whose+ * property id names no site. The property itself when nothing better is known.+ */+export function sourceHost(+ provider: IntegrationProvider,+ property: string | null,+ domain: string | undefined,+): string {+ if (provider === 'google-search-console' && property) return gscPropertyHost(property);+ return domain ?? property ?? '';+}++/**+ * The AI Traffic sections that need a Google source, and which one: the+ * spec's dependency matrix (§3.8b). A section shows its source's state when+ * it isn't connected, and the not-connected state lists every section the+ * source unlocks. Sections that read only the snippet aren't listed; each+ * later section adds its own entry.+ */+export const TRAFFIC_SECTION_SOURCES = {+ pageOpportunities: 'google-analytics',+} as const satisfies Record<string, IntegrationProvider>;++export type TrafficSection = keyof typeof TRAFFIC_SECTION_SOURCES;++/** The sections a source unlocks, in the page's order. */+export function sectionsNeeding(provider: IntegrationProvider): TrafficSection[] {+ return (Object.keys(TRAFFIC_SECTION_SOURCES) as TrafficSection[]).filter(+ (section) => TRAFFIC_SECTION_SOURCES[section] === provider,+ );+}