Skip to content

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

feat(traffic): export the AI Traffic page as Excel or a zip of CSVs, and each table (#1162)

Cihan53e501eb6804
diff --git a/server/src/routes/integrations-page-opportunities.test.js b/server/src/routes/integrations-page-opportunities.test.js
index 170d53c93..f60b7cec0 100644
--- a/server/src/routes/integrations-page-opportunities.test.js
+++ b/server/src/routes/integrations-page-opportunities.test.js
@@ -57,6 +57,19 @@ describe('GET /google-analytics/page-opportunities', () => {
expect(detect).toHaveBeenCalledWith(BRAND, { since: '2026-10-11', until: '2026-10-17' });
});
+ it('passes a limit through, for an export of every finding', async () => {
+ await get({ brandId: BRAND, from: '2026-10-11', limit: '1000' });
+ expect(detect).toHaveBeenCalledWith(BRAND, { since: '2026-10-11', until: null, limit: 1000 });
+ });
+
+ it('refuses a limit outside 1–1000', async () => {
+ for (const limit of ['0', '1001', 'many']) {
+ const res = await get({ brandId: BRAND, limit });
+ expect(res.status).toBe(400);
+ }
+ expect(detect).not.toHaveBeenCalled();
+ });
+
it('leaves an end open when the page sends no bound for it', async () => {
await get({ brandId: BRAND });
expect(detect).toHaveBeenCalledWith(BRAND, { since: null, until: null });
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index c1039e230..10bf667e4 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -383,6 +383,8 @@ const pageOpportunitiesQuery = z.object({
// Inclusive days; either may be left open ("all time" sends neither).
from: z.iso.date().optional(),
to: z.iso.date().optional(),
+ // The card shows the best ten; an export asks for every finding (AT-015).
+ limit: z.coerce.number().int().min(1).max(1000).optional(),
});
/**
@@ -395,13 +397,14 @@ const pageOpportunitiesQuery = z.object({
router.get('/google-analytics/page-opportunities', async (req, res) => {
const parsed = pageOpportunitiesQuery.safeParse(req.query);
if (!parsed.success) return res.status(400).json({ error: 'Invalid request' });
- const { brandId, from, to } = parsed.data;
+ const { brandId, from, to, limit } = parsed.data;
try {
await assertBrandAccess(brandId, req.user.id);
const result = await detectPageOpportunitiesInWindow(brandId, {
since: from ?? null,
until: to ?? null,
+ ...(limit ? { limit } : {}),
});
return res.json(result);
} catch (err) {
diff --git a/web/messages/en.json b/web/messages/en.json
index 2d7f4322c..16bf999e3 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3072,7 +3072,110 @@
"snippetTitle": "Add this snippet to your website",
"snippetDescription": "Paste this before the closing <code>{tag}</code> tag to track AI-referred visits.",
"copySnippet": "Copy tracking script",
- "exportError": "Failed to export CSV",
+ "export": {
+ "button": "Export",
+ "exporting": "Exporting…",
+ "excel": "Excel (.xlsx)",
+ "excelHint": "Whole page, one sheet per section",
+ "csv": "CSV (.zip)",
+ "csvHint": "One CSV per section",
+ "tableExcel": "Excel",
+ "tableCsv": "CSV",
+ "failed": "The export failed. Please try again.",
+ "tooLarge": "This range has more than {max} visits, too many to export at once. Choose a shorter range.",
+ "sheets": {
+ "filters": "Filters",
+ "kpis": "KPIs",
+ "trend": "Trend",
+ "platforms": "Platforms",
+ "pages": "Top landing pages",
+ "opportunities": "Pages without AI traffic",
+ "visits": "Visits"
+ },
+ "columns": {
+ "setting": "Setting",
+ "metric": "Metric",
+ "value": "Value",
+ "note": "Note",
+ "day": "Day",
+ "platform": "Platform",
+ "visits": "Visits",
+ "previousVisits": "Visits, previous period",
+ "change": "Change (%)",
+ "share": "Share (%)",
+ "page": "Page",
+ "url": "URL",
+ "aiVisibility": "AI visibility",
+ "citations": "Citations",
+ "targetingPrompts": "Prompts targeting",
+ "sessions": "Sessions",
+ "rankedBy": "Ranked by",
+ "rank": "Rank",
+ "percentile": "Percentile",
+ "time": "Time (UTC)",
+ "referrer": "Referrer",
+ "country": "Country",
+ "pageviews": "Pageviews"
+ },
+ "metrics": {
+ "visits": "AI-referred visits",
+ "pageviews": "Pageviews",
+ "previousVisits": "Visits, previous period",
+ "change": "Change vs previous period (%)",
+ "topPlatform": "Top platform",
+ "topPlatformVisits": "Top platform visits",
+ "platforms": "Platforms"
+ },
+ "notes": {
+ "lowSample": "Low sample: fewer than 30 visits in this period or the one before",
+ "new": "New: no visits in the previous period",
+ "noPreviousPeriod": "No previous period for all time",
+ "analytics": {
+ "not_configured": "Google Analytics isn't set up on this server",
+ "not_connected": "Needs Google Analytics: not connected",
+ "unmapped": "Needs Google Analytics: no property chosen for this brand",
+ "syncing": "Google Analytics is importing its first data",
+ "noData": "No data for this range in Google Analytics",
+ "noFinding": "No high-value pages without AI traffic in this range",
+ "failed": "Google Analytics findings couldn't be read; try the export again"
+ }
+ },
+ "citationStates": {
+ "cited": "Cited",
+ "targeted_not_cited": "Not cited",
+ "not_targeted": "No prompt"
+ },
+ "signals": {
+ "revenue": "Revenue",
+ "transactions": "Orders",
+ "key_events": "Conversions",
+ "engagement": "Engagement (min)"
+ },
+ "sourceStates": {
+ "active": "Active",
+ "notDetected": "Not detected",
+ "connected": "Connected",
+ "syncing": "Syncing",
+ "unmapped": "Connected, no property for this brand",
+ "not_connected": "Not connected",
+ "not_configured": "Not set up on this server"
+ },
+ "filters": {
+ "brand": "Brand",
+ "range": "Range",
+ "from": "From",
+ "to": "To",
+ "start": "Start",
+ "platform": "Platform",
+ "allPlatforms": "All platforms",
+ "search": "Search",
+ "none": "None",
+ "snippet": "Tracking snippet",
+ "ga": "Google Analytics",
+ "gsc": "Google Search Console",
+ "exportedAt": "Exported at"
+ }
+ },
"change": {
"new": "new",
"lowSample": "Low sample",
diff --git a/web/package.json b/web/package.json
index ae5dd7927..94cbc07f2 100644
--- a/web/package.json
+++ b/web/package.json
@@ -34,6 +34,7 @@
"ai": "^6.0.116",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "fflate": "^0.8.3",
"lucide-react": "^0.577.0",
"marked": "^18.0.0",
"next": "16.4.2",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_export.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_export.test.tsx
new file mode 100644
index 000000000..4c9bfa1d3
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_export.test.tsx
@@ -0,0 +1,131 @@
+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';
+
+/**
+ * AT-015: the page's Export menu and each table's Excel / CSV buttons fetch
+ * the file the server built, save it under the server's name, and show a
+ * refusal as a toast instead of leaving the page.
+ */
+
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { TableExport, attachmentName, useTrafficExport } = await import('./_export');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+const fetchMock = vi.fn();
+const clicked: { href: string; download: string }[] = [];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ clicked.length = 0;
+ vi.stubGlobal('fetch', fetchMock);
+ URL.createObjectURL = vi.fn(() => 'blob:export');
+ URL.revokeObjectURL = vi.fn();
+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
+ this: HTMLAnchorElement,
+ ) {
+ clicked.push({ href: this.href, download: this.download });
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+function Harness() {
+ const exporter = useTrafficExport({
+ brandId: 'b1',
+ dateWindow: { dateFrom: '2026-10-11T09:00:00.000Z' },
+ rangeLabel: 'last 7 days',
+ platform: 'gemini.google.com',
+ search: '',
+ });
+ return <TableExport exporter={exporter} section="visits" />;
+}
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <Harness />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const buttons = () => [...container.querySelectorAll('button')];
+
+describe('table export', () => {
+ it("asks for the table with the page's range and the list's filters, and saves it", async () => {
+ fetchMock.mockResolvedValue(
+ new Response('Time (UTC)', {
+ status: 200,
+ headers: {
+ 'Content-Disposition':
+ 'attachment; filename="ansvisor-ai-traffic-acme-visits-2026-10-11_2026-10-18.csv"',
+ },
+ }),
+ );
+ await render();
+ expect(buttons().map((b) => b.textContent)).toEqual(['Excel', 'CSV']);
+
+ await act(async () => buttons()[1].click());
+
+ const url = new URL(fetchMock.mock.calls[0][0] as string, 'http://localhost');
+ expect(url.pathname).toBe('/api/traffic/export');
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ brandId: 'b1',
+ format: 'csv',
+ rangeLabel: 'last 7 days',
+ from: '2026-10-11T09:00:00.000Z',
+ platform: 'gemini.google.com',
+ section: 'visits',
+ });
+ expect(clicked).toEqual([
+ {
+ href: 'blob:export',
+ download: 'ansvisor-ai-traffic-acme-visits-2026-10-11_2026-10-18.csv',
+ },
+ ]);
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('says the range is too large to export, and saves nothing', async () => {
+ fetchMock.mockResolvedValue(Response.json({ error: 'too_large' }, { status: 413 }));
+ await render();
+ await act(async () => buttons()[0].click());
+
+ expect(toast.error).toHaveBeenCalledWith(
+ 'This range has more than 100,000 visits, too many to export at once. Choose a shorter range.',
+ );
+ expect(clicked).toEqual([]);
+ });
+
+ it('says the export failed when the server or the network does', async () => {
+ fetchMock.mockRejectedValue(new TypeError('offline'));
+ await render();
+ await act(async () => buttons()[0].click());
+ expect(toast.error).toHaveBeenCalledWith('The export failed. Please try again.');
+ });
+});
+
+describe('attachmentName', () => {
+ it("reads the server's file name", () => {
+ expect(attachmentName('attachment; filename="a-b.xlsx"')).toBe('a-b.xlsx');
+ expect(attachmentName(null)).toBeNull();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_export.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_export.tsx
new file mode 100644
index 000000000..3e66afda9
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_export.tsx
@@ -0,0 +1,167 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { ChevronDown, Download, FileArchive, FileSpreadsheet, Loader2 } from 'lucide-react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { formatNumber } from '@/lib/format';
+import type { TrafficDateWindow } from '@/lib/actions/traffic';
+import { TRAFFIC_EXPORT_MAX_ROWS, type TrafficExportSection } from '@/lib/traffic-export';
+
+/**
+ * Downloads from GET /api/traffic/export (AT-015): the whole page from the
+ * header's Export menu, one table from its own Excel / CSV buttons. The file
+ * is built on the server; this fetches it, so a refusal (too many rows) or a
+ * failure shows as a toast instead of replacing the page.
+ */
+
+export type ExportFormat = 'xlsx' | 'zip' | 'csv';
+
+export interface TrafficExporter {
+ /** What is being exported, e.g. "zip" or "visits:csv"; null when idle. */
+ busy: string | null;
+ run: (format: ExportFormat, section?: TrafficExportSection) => Promise<void>;
+}
+
+/** The file name the route gave, from `attachment; filename="…"`. */
+export function attachmentName(header: string | null): string | null {
+ return header?.match(/filename="([^"]+)"/)?.[1] ?? null;
+}
+
+export function useTrafficExport({
+ brandId,
+ dateWindow,
+ rangeLabel,
+ platform,
+ search,
+}: {
+ brandId: string;
+ dateWindow: TrafficDateWindow;
+ rangeLabel: string;
+ /** The visit list's filters; they apply to its rows. */
+ platform: string;
+ search: string;
+}): TrafficExporter {
+ const t = useTranslations('traffic.export');
+ const [busy, setBusy] = useState<string | null>(null);
+
+ async function run(format: ExportFormat, section?: TrafficExportSection) {
+ const params = new URLSearchParams({ brandId, format, rangeLabel });
+ if (dateWindow.dateFrom) params.set('from', dateWindow.dateFrom);
+ if (dateWindow.dateTo) params.set('to', dateWindow.dateTo);
+ if (platform) params.set('platform', platform);
+ if (search) params.set('search', search);
+ if (section) params.set('section', section);
+
+ setBusy(section ? `${section}:${format}` : format);
+ try {
+ const res = await fetch(`/api/traffic/export?${params}`);
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { error?: string };
+ toast.error(
+ body.error === 'too_large'
+ ? t('tooLarge', { max: formatNumber(TRAFFIC_EXPORT_MAX_ROWS) })
+ : t('failed'),
+ );
+ return;
+ }
+ const url = URL.createObjectURL(await res.blob());
+ const link = document.createElement('a');
+ link.href = url;
+ link.download =
+ attachmentName(res.headers.get('Content-Disposition')) ?? `ansvisor-ai-traffic.${format}`;
+ link.click();
+ URL.revokeObjectURL(url);
+ } catch {
+ toast.error(t('failed'));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ return { busy, run };
+}
+
+/** The header's Export menu: the whole page as Excel, or as a zip of CSVs. */
+export function ExportMenu({
+ exporter,
+ disabled,
+}: {
+ exporter: TrafficExporter;
+ disabled?: boolean;
+}) {
+ const t = useTranslations('traffic.export');
+ const working = exporter.busy === 'xlsx' || exporter.busy === 'zip';
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ className="gap-2"
+ disabled={disabled || exporter.busy !== null}
+ />
+ }
+ >
+ {working ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
+ {working ? t('exporting') : t('button')}
+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-64">
+ <DropdownMenuItem onClick={() => void exporter.run('xlsx')}>
+ <FileSpreadsheet className="mr-2 h-4 w-4 shrink-0" />
+ <div className="min-w-0">
+ <div className="text-sm font-medium">{t('excel')}</div>
+ <div className="text-xs text-muted-foreground">{t('excelHint')}</div>
+ </div>
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => void exporter.run('zip')}>
+ <FileArchive className="mr-2 h-4 w-4 shrink-0" />
+ <div className="min-w-0">
+ <div className="text-sm font-medium">{t('csv')}</div>
+ <div className="text-xs text-muted-foreground">{t('csvHint')}</div>
+ </div>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+/** A table's own Excel / CSV buttons, beside its title. */
+export function TableExport({
+ exporter,
+ section,
+}: {
+ exporter: TrafficExporter;
+ section: TrafficExportSection;
+}) {
+ const t = useTranslations('traffic.export');
+ const button = (format: 'xlsx' | 'csv', text: string) => {
+ const working = exporter.busy === `${section}:${format}`;
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ disabled={exporter.busy !== null}
+ onClick={() => void exporter.run(format, section)}
+ >
+ {working ? <Loader2 className="h-3 w-3 animate-spin" /> : <Download className="h-3 w-3" />}
+ {text}
+ </Button>
+ );
+ };
+ return (
+ <div className="flex shrink-0 items-center gap-1.5">
+ {button('xlsx', t('tableExcel'))}
+ {button('csv', t('tableCsv'))}
+ </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 f379e34fc..e9827be2e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_opportunities-card.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useEffect, useState } from 'react';
+import { useEffect, useState, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -82,6 +82,7 @@ export function PageOpportunitiesCard({
canConnect,
onConnected,
onShowAllTime,
+ actions,
}: {
brandId: string;
dateWindow: TrafficDateWindow;
@@ -97,6 +98,8 @@ export function PageOpportunitiesCard({
onConnected: () => void;
/** Widens the page's range; absent when it is already all time. */
onShowAllTime?: () => void;
+ /** The table's own Excel / CSV buttons (AT-015), shown once it has data. */
+ actions?: ReactNode;
}) {
const t = useTranslations('traffic.pageOpportunities');
const status = source ? googleSourceStatus(source) : sourceUnknown ? 'connected' : null;
@@ -157,9 +160,12 @@ export function PageOpportunitiesCard({
<NeedsTag provider={PROVIDER} />
</CardTitle>
{shown && (
- <Badge variant="outline" className="text-xs">
- {shown.rangeLabel}
- </Badge>
+ <div className="flex items-center gap-2">
+ <Badge variant="outline" className="text-xs">
+ {shown.rangeLabel}
+ </Badge>
+ {shown.result && shown.result.pages > 0 && actions}
+ </div>
)}
</div>
{shown?.result && shown.result.pages > 0 && (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index 4bcb01313..fb5bae45e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -37,6 +37,7 @@ import {
type DateRangePreset,
} from '@/components/filters/date-range-filter';
import { PageOpportunitiesCard } from './_opportunities-card';
+import { ExportMenu, TableExport, useTrafficExport } from './_export';
import { SourcesStrip } from './_sources-strip';
import { SnippetBanner, SnippetDialog } from './_snippet-code';
import { snippetDetected } from '@/lib/traffic-sources';
@@ -60,12 +61,9 @@ import {
Search,
X,
Loader2,
- Download,
CalendarX2,
} from 'lucide-react';
-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';
@@ -81,16 +79,6 @@ import {
const PAGE_SIZE = 10;
-/**
- * PostgREST silently caps un-paginated selects at 1000 rows (see the citations
- * export's note on the same limit) — fetch up to that ceiling in one request
- * for the export rather than scanning further pages, matching the "high limit"
- * scope in #607.
- */
-const TRAFFIC_EXPORT_LIMIT = 1000;
-
-const TRAFFIC_EXPORT_HEADERS = ['timestamp', 'platform', 'page_url', 'referrer', 'pageviews'];
-
// ─── Sub-components ───────────────────────────────────────────────────────────
function KpiCard({
@@ -447,7 +435,6 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
const [logsPageviews, setLogsPageviews] = useState(0);
const [isLoadingSummary, setIsLoadingSummary] = useState(true);
const [isLoadingLogs, setIsLoadingLogs] = useState(false);
- const [isExporting, setIsExporting] = useState(false);
// What feeds the page (AT-001); null while it loads.
const [sources, setSources] = useState<TrafficSources | null>(null);
// A failed read hides the strip and leaves the snippet code open, as before it.
@@ -472,6 +459,14 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
const [filters, setFilters] = useState<TrafficFilters>({ platform: '', search: '' });
const [searchInput, setSearchInput] = useState(filters.search);
const [page, setPage] = useState(0);
+ // The page as files (AT-015): the same range, and the visit list's filters.
+ const exporter = useTrafficExport({
+ brandId: brand.id,
+ dateWindow,
+ rangeLabel: rangeSubLabel,
+ platform: filters.platform,
+ search: filters.search,
+ });
useEffect(() => {
const id = window.setTimeout(() => {
@@ -527,43 +522,6 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
}
}, [brand.id, page, filters.platform, filters.search, dateWindow]);
- const handleExportCsv = useCallback(async () => {
- setIsExporting(true);
- try {
- const result = await getTrafficLogs(brand.id, {
- limit: TRAFFIC_EXPORT_LIMIT,
- platform: filters.platform || undefined,
- search: filters.search || undefined,
- dateFrom: dateWindow.dateFrom,
- dateTo: dateWindow.dateTo,
- });
-
- const rows = result.logs.map((log) => ({
- timestamp: log.createdAt,
- platform: log.sourcePlatform ? getPlatformName(log.sourcePlatform) : '',
- page_url: log.url,
- referrer: log.referrer ?? '',
- pageviews: log.pageviews,
- }));
-
- const csv = toCsv(rows, TRAFFIC_EXPORT_HEADERS);
- const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- const date = new Date().toISOString().slice(0, 10);
-
- link.href = url;
- link.download = `ansvisor_${brand.slug}_traffic_${date}.csv`;
- link.click();
-
- URL.revokeObjectURL(url);
- } catch (err) {
- toast.error(err instanceof Error ? err.message : t('exportError'));
- } finally {
- setIsExporting(false);
- }
- }, [brand.id, brand.slug, filters.platform, filters.search, dateWindow, t]);
-
const handleFiltersChange = useCallback((patch: Partial<TrafficFilters>) => {
setPage(0);
setFilters((f) => ({ ...f, ...patch }));
@@ -642,6 +600,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
canConnect={canManage}
onConnected={() => void loadSources()}
onShowAllTime={datePreset === 'all' ? undefined : () => handleDatePresetChange('all')}
+ actions={<TableExport exporter={exporter} section="opportunities" />}
/>
);
@@ -668,19 +627,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
onFromChange={handleCustomFromChange}
onToChange={handleCustomToChange}
/>
- <Button
- variant="outline"
- className="gap-2"
- onClick={() => void handleExportCsv()}
- disabled={isExporting || isEmpty}
- >
- {isExporting ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Download className="h-4 w-4" />
- )}
- {isExporting ? tCommon('exporting') : tCommon('exportCsv')}
- </Button>
+ <ExportMenu exporter={exporter} />
</div>
</div>
@@ -785,7 +732,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
{/* Platform table */}
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Referrals by Platform</CardTitle>
+ <div className="flex items-center justify-between gap-2">
+ <CardTitle className="text-sm font-medium">Referrals by Platform</CardTitle>
+ <TableExport exporter={exporter} section="platforms" />
+ </div>
</CardHeader>
<CardContent className="p-0">
<Table>
@@ -826,7 +776,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
{/* Top Pages */}
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Top Landing Pages</CardTitle>
+ <div className="flex items-center justify-between gap-2">
+ <CardTitle className="text-sm font-medium">Top Landing Pages</CardTitle>
+ <TableExport exporter={exporter} section="pages" />
+ </div>
</CardHeader>
<CardContent className="p-0">
<Table>
@@ -876,11 +829,14 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
<LayoutList className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-sm font-medium">Recent AI Referral Visits</CardTitle>
</div>
- {logsTotal > 0 && (
- <Badge variant="secondary" className="text-xs">
- {tVisits('listTotal', { visits: logsTotal, pageviews: logsPageviews })}
- </Badge>
- )}
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ {logsTotal > 0 && (
+ <Badge variant="secondary" className="text-xs">
+ {tVisits('listTotal', { visits: logsTotal, pageviews: logsPageviews })}
+ </Badge>
+ )}
+ <TableExport exporter={exporter} section="visits" />
+ </div>
</div>
<TrafficFilterBar
filters={filters}
diff --git a/web/src/app/api/traffic/export/route.test.ts b/web/src/app/api/traffic/export/route.test.ts
new file mode 100644
index 000000000..27d73e650
--- /dev/null
+++ b/web/src/app/api/traffic/export/route.test.ts
@@ -0,0 +1,246 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { strFromU8, unzipSync } from 'fflate';
+import type { SourceState } from '@/lib/actions/integrations';
+
+/**
+ * GET /api/traffic/export (AT-015): the page as a file, built on the server
+ * for a signed-in member of the brand's organization.
+ */
+
+const auth = vi.hoisted(() => ({
+ user: { id: 'u1' } as { id: string } | null,
+ brand: { id: 'b1', name: 'Acme Coffee', slug: 'acme-coffee' } as Record<string, string> | null,
+}));
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({
+ auth: { getUser: async () => ({ data: { user: auth.user } }) },
+ from: () => {
+ const builder = {
+ select: () => builder,
+ eq: () => builder,
+ maybeSingle: async () => ({ data: auth.brand, error: null }),
+ };
+ return builder;
+ },
+ }),
+}));
+
+const loaders = vi.hoisted(() => ({
+ getTrafficSummary: vi.fn(),
+ getTrafficTrend: vi.fn(),
+ getTrafficVisitsForExport: vi.fn(),
+ getTrafficSources: vi.fn(),
+ getPageOpportunities: vi.fn(),
+}));
+vi.mock('@/lib/actions/traffic', () => loaders);
+
+const { GET } = await import('./route');
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const ga = (over: Partial<SourceState> = {}): SourceState => ({
+ configured: true,
+ connected: true,
+ mapped: true,
+ firstDataAt: '2026-09-01T06:00:00Z',
+ lastDataAt: '2026-10-18T06:00:00Z',
+ property: '123',
+ ...over,
+});
+
+function get(params: Record<string, string>) {
+ const query = new URLSearchParams({ brandId: BRAND, rangeLabel: 'last 7 days', ...params });
+ return GET(new Request(`http://localhost/api/traffic/export?${query}`));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ auth.user = { id: 'u1' };
+ auth.brand = { id: BRAND, name: 'Acme Coffee', slug: 'acme-coffee' };
+ loaders.getTrafficSummary.mockResolvedValue({
+ totalVisits: 2,
+ totalVisitsPrev: 1,
+ totalPageviews: 4,
+ hasPreviousPeriod: true,
+ platformBreakdown: [{ platform: 'gemini.google.com', visits: 2, visitsPrev: 1 }],
+ topPages: [{ url: '/menu', visits: 2, visitsPrev: 1 }],
+ hasAnyData: true,
+ });
+ loaders.getTrafficTrend.mockResolvedValue([{ date: '2026-10-17', 'gemini.google.com': 2 }]);
+ loaders.getTrafficVisitsForExport.mockResolvedValue([
+ {
+ id: 'v1',
+ brandId: BRAND,
+ url: 'https://acme.example/menu',
+ referrer: null,
+ sourcePlatform: 'gemini.google.com',
+ country: 'TR',
+ language: null,
+ screen: null,
+ createdAt: '2026-10-17T09:30:00Z',
+ pageviews: 3,
+ },
+ ]);
+ loaders.getTrafficSources.mockResolvedValue({
+ snippetLastVisitAt: '2026-10-17T09:30:00Z',
+ ga: ga(),
+ gsc: ga({ connected: false }),
+ });
+ loaders.getPageOpportunities.mockResolvedValue({ pages: 8, rows: [] });
+});
+
+const WINDOW = { dateFrom: '2026-10-11T09:00:00.000Z' };
+
+// TextDecoder (and so res.text()) drops a leading byte order mark; read bytes.
+const BOM = [0xef, 0xbb, 0xbf];
+const startsWithBom = (bytes: Uint8Array) => BOM.every((b, i) => bytes[i] === b);
+async function csvOf(res: Response) {
+ const bytes = new Uint8Array(await res.arrayBuffer());
+ return { bom: startsWithBom(bytes), text: strFromU8(bytes.subarray(3)) };
+}
+
+describe('GET /api/traffic/export', () => {
+ it('builds the whole page as Excel, one sheet per section after Filters', async () => {
+ const res = await get({ format: 'xlsx', from: WINDOW.dateFrom });
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get('Content-Type')).toBe(
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ );
+ expect(res.headers.get('Content-Disposition')).toMatch(
+ /^attachment; filename="ansvisor-ai-traffic-acme-coffee-2026-10-11_\d{4}-\d{2}-\d{2}\.xlsx"$/,
+ );
+ const workbook = strFromU8(
+ unzipSync(new Uint8Array(await res.arrayBuffer()))['xl/workbook.xml'],
+ );
+ const sheets = [...workbook.matchAll(/<sheet\b[^>]*\bname="([^"]+)"/g)].map((m) => m[1]);
+ expect(sheets).toEqual([
+ 'Filters',
+ 'KPIs',
+ 'Trend',
+ 'Platforms',
+ 'Top landing pages',
+ 'Pages without AI traffic',
+ 'Visits',
+ ]);
+
+ // The page's range; every landing page; every visit, with the list's filters.
+ expect(loaders.getTrafficSummary).toHaveBeenCalledWith(BRAND, WINDOW, {
+ topPages: Number.MAX_SAFE_INTEGER,
+ });
+ expect(loaders.getTrafficVisitsForExport).toHaveBeenCalledWith(BRAND, {
+ ...WINDOW,
+ dateTo: undefined,
+ platform: undefined,
+ search: undefined,
+ max: 100_000,
+ });
+ expect(loaders.getPageOpportunities).toHaveBeenCalledWith(
+ BRAND,
+ { ...WINDOW, dateTo: undefined },
+ {
+ limit: 1000,
+ },
+ );
+ });
+
+ it('zips one CSV per section, each with a byte order mark', async () => {
+ const res = await get({ format: 'zip', platform: 'gemini.google.com', search: 'menu' });
+
+ expect(res.headers.get('Content-Type')).toBe('application/zip');
+ expect(res.headers.get('Content-Disposition')).toMatch(/all-time_\d{4}-\d{2}-\d{2}\.zip"$/);
+ const files = unzipSync(new Uint8Array(await res.arrayBuffer()));
+ expect(Object.keys(files)).toEqual([
+ 'filters.csv',
+ 'kpis.csv',
+ 'trend.csv',
+ 'platforms.csv',
+ 'top-landing-pages.csv',
+ 'pages-without-ai-traffic.csv',
+ 'visits.csv',
+ ]);
+ for (const file of Object.values(files)) expect(startsWithBom(file)).toBe(true);
+ const visits = strFromU8(files['visits.csv']);
+ expect(visits).toContain('2026-10-17 09:30,Gemini,/menu,https://acme.example/menu,,TR,3');
+ expect(strFromU8(files['filters.csv'])).toContain('Search,menu');
+ expect(loaders.getTrafficVisitsForExport).toHaveBeenCalledWith(
+ BRAND,
+ expect.objectContaining({ platform: 'gemini.google.com', search: 'menu' }),
+ );
+ });
+
+ it('reads only what one table needs, and names the file after it', async () => {
+ const res = await get({ format: 'csv', section: 'platforms' });
+
+ expect(res.headers.get('Content-Type')).toBe('text/csv; charset=utf-8');
+ expect(res.headers.get('Content-Disposition')).toContain('acme-coffee-platforms-all-time_');
+ const csv = await csvOf(res);
+ expect(csv.bom).toBe(true);
+ expect(csv.text).toBe(
+ [
+ 'Platform,Visits,"Visits, previous period",Change (%),Share (%),Note',
+ 'Gemini,2,1,,100,Low sample: fewer than 30 visits in this period or the one before',
+ ].join('\n'),
+ );
+ expect(loaders.getTrafficTrend).not.toHaveBeenCalled();
+ expect(loaders.getTrafficVisitsForExport).not.toHaveBeenCalled();
+ expect(loaders.getTrafficSources).not.toHaveBeenCalled();
+ });
+
+ it('says why Analytics has no rows instead of reading them', async () => {
+ loaders.getTrafficSources.mockResolvedValue({
+ snippetLastVisitAt: null,
+ ga: ga({ connected: false, mapped: false }),
+ gsc: ga({ connected: false }),
+ });
+ const res = await get({ format: 'csv', section: 'opportunities' });
+
+ const csv = await csvOf(res);
+ expect(csv).toEqual({ bom: true, text: 'Note\nNeeds Google Analytics: not connected' });
+ expect(loaders.getPageOpportunities).not.toHaveBeenCalled();
+ });
+
+ it("notes Analytics findings it couldn't read, rather than failing the export", async () => {
+ loaders.getPageOpportunities.mockRejectedValue(new Error('Server error: 500'));
+ const res = await get({ format: 'csv', section: 'opportunities' });
+
+ expect(res.status).toBe(200);
+ expect(await res.text()).toContain("couldn't be read");
+ });
+
+ it('refuses more visits than an export built on request should hold', async () => {
+ loaders.getTrafficVisitsForExport.mockResolvedValue(null);
+ const res = await get({ format: 'xlsx' });
+ expect(res.status).toBe(413);
+ expect(await res.json()).toEqual({ error: 'too_large' });
+ });
+
+ it('refuses a request that asks for the wrong shape', async () => {
+ const wrong: Record<string, string>[] = [
+ { format: 'zip', section: 'visits' },
+ { format: 'csv' },
+ { format: 'pdf' },
+ { format: 'xlsx', section: 'everything' },
+ { format: 'xlsx', brandId: 'not-a-brand' },
+ ];
+ for (const params of wrong) {
+ const res = await get(params);
+ expect(res.status).toBe(400);
+ }
+ });
+
+ it('needs a signed-in member who can see the brand', async () => {
+ auth.user = null;
+ expect((await get({ format: 'xlsx' })).status).toBe(401);
+ auth.user = { id: 'u1' };
+ auth.brand = null;
+ expect((await get({ format: 'xlsx' })).status).toBe(404);
+ });
+
+ it('reports a failed read as an error, not as an empty file', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ loaders.getTrafficSummary.mockRejectedValue(new Error('timeout'));
+ const res = await get({ format: 'xlsx' });
+ expect(res.status).toBe(500);
+ error.mockRestore();
+ });
+});
diff --git a/web/src/app/api/traffic/export/route.ts b/web/src/app/api/traffic/export/route.ts
new file mode 100644
index 000000000..da001b621
--- /dev/null
+++ b/web/src/app/api/traffic/export/route.ts
@@ -0,0 +1,187 @@
+import { createTranslator } from 'next-intl';
+import { strToU8, zipSync } from 'fflate';
+import writeXlsxFile from 'write-excel-file/node';
+import { z } from 'zod';
+import messages from '../../../../../messages/en.json';
+import { createClient } from '@/lib/supabase/server';
+import {
+ getPageOpportunities,
+ getTrafficSources,
+ getTrafficSummary,
+ getTrafficTrend,
+ getTrafficVisitsForExport,
+} from '@/lib/actions/traffic';
+import { utcDay } from '@/lib/dates';
+import { googleSourceStatus } from '@/lib/traffic-sources';
+import {
+ TRAFFIC_EXPORT_MAX_ROWS,
+ TRAFFIC_EXPORT_SECTIONS,
+ fileSlug,
+ filtersTable,
+ tableCsv,
+ trafficExportFileName,
+ trafficTable,
+ trafficWorkbook,
+ type ExportLabel,
+ type TrafficExportData,
+ type TrafficExportSection,
+} from '@/lib/traffic-export';
+
+/**
+ * GET /api/traffic/export — the AI Traffic page as a file (AT-015, spec
+ * §3.9), built here rather than in the browser: the whole page as Excel (a
+ * sheet per section and a Filters sheet) or as a zip of CSVs, or one table
+ * as Excel or CSV. Same range and filters as the page, every row.
+ *
+ * Reads through the signed-in member's session, so RLS decides whose brand
+ * this is: a brand outside their organization reads as not found.
+ */
+
+export const runtime = 'nodejs';
+
+const query = z
+ .object({
+ brandId: z.guid(),
+ // The page's window, as its loaders take it; absent for all time.
+ from: z.string().max(40).optional(),
+ to: z.string().max(40).optional(),
+ rangeLabel: z.string().max(80).default(''),
+ platform: z.string().max(255).optional(),
+ search: z.string().max(500).optional(),
+ format: z.enum(['xlsx', 'zip', 'csv']),
+ section: z.enum(TRAFFIC_EXPORT_SECTIONS).optional(),
+ })
+ // The zip is the whole page; a CSV is one table.
+ .refine((q) => (q.format === 'zip' ? !q.section : q.format === 'csv' ? !!q.section : true));
+
+const CONTENT_TYPES = {
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ zip: 'application/zip',
+ csv: 'text/csv; charset=utf-8',
+} as const;
+
+function exportLabels(): ExportLabel {
+ const t = createTranslator({ locale: 'en', messages, namespace: 'traffic.export' });
+ return (key, values) => t(key as never, values as never);
+}
+
+export async function GET(req: Request) {
+ const parsed = query.safeParse(Object.fromEntries(new URL(req.url).searchParams));
+ if (!parsed.success) return Response.json({ error: 'invalid' }, { status: 400 });
+ const q = parsed.data;
+
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return Response.json({ error: 'unauthorized' }, { status: 401 });
+
+ const { data: brand } = await supabase
+ .from('brands')
+ .select('id, name, slug')
+ .eq('id', q.brandId)
+ .maybeSingle();
+ if (!brand) return Response.json({ error: 'not_found' }, { status: 404 });
+
+ const sections: readonly TrafficExportSection[] = q.section
+ ? [q.section]
+ : TRAFFIC_EXPORT_SECTIONS;
+ const needs = (...wanted: TrafficExportSection[]) => sections.some((s) => wanted.includes(s));
+ const window = { dateFrom: q.from, dateTo: q.to };
+ const wholePage = !q.section;
+
+ try {
+ const [summary, trend, visits, sources] = await Promise.all([
+ needs('kpis', 'platforms', 'pages')
+ ? getTrafficSummary(q.brandId, window, { topPages: Number.MAX_SAFE_INTEGER })
+ : undefined,
+ needs('trend') ? getTrafficTrend(q.brandId, window) : undefined,
+ needs('visits')
+ ? getTrafficVisitsForExport(q.brandId, {
+ ...window,
+ platform: q.platform,
+ search: q.search,
+ max: TRAFFIC_EXPORT_MAX_ROWS,
+ })
+ : undefined,
+ // For the Filters sheet, and to know whether Analytics has findings.
+ needs('opportunities') || wholePage
+ ? getTrafficSources(q.brandId).catch(() => null)
+ : undefined,
+ ]);
+ // Larger than an export built on request should be (spec §3.9).
+ if (visits === null) return Response.json({ error: 'too_large' }, { status: 413 });
+
+ let opportunitiesStatus: TrafficExportData['opportunitiesStatus'];
+ let opportunities: TrafficExportData['opportunities'];
+ if (needs('opportunities')) {
+ // An unreadable state reads the findings anyway, as the page does.
+ opportunitiesStatus = sources ? googleSourceStatus(sources.ga) : 'connected';
+ if (opportunitiesStatus === 'connected') {
+ opportunities = await getPageOpportunities(q.brandId, window, { limit: 1000 }).catch(() => {
+ opportunitiesStatus = 'failed';
+ return null;
+ });
+ }
+ }
+
+ const label = exportLabels();
+ const from = utcDay(q.from) ?? null;
+ const to = utcDay(q.to) ?? new Date().toISOString().slice(0, 10);
+ const data: TrafficExportData = {
+ brandName: brand.name as string,
+ rangeLabel: q.rangeLabel,
+ from,
+ to,
+ platform: q.platform ?? null,
+ search: q.search ?? null,
+ exportedAt: new Date(),
+ summary,
+ trend,
+ visits: visits ?? undefined,
+ opportunities,
+ opportunitiesStatus,
+ sources,
+ };
+
+ const fileName = trafficExportFileName({
+ brand: (brand.slug as string | null) || (brand.name as string),
+ from,
+ to,
+ ext: q.format,
+ table: q.section ? label(`sheets.${q.section}`) : undefined,
+ });
+
+ let body: BodyInit;
+ if (q.format === 'xlsx') {
+ body = new Uint8Array(
+ await writeXlsxFile(
+ trafficWorkbook(data, sections, label, { withFilters: wholePage }),
+ ).toBuffer(),
+ );
+ } else if (q.format === 'csv') {
+ body = tableCsv(trafficTable(q.section!, data, label));
+ } else {
+ const files: Record<string, Uint8Array> = {
+ [`${fileSlug(label('sheets.filters'))}.csv`]: strToU8(tableCsv(filtersTable(data, label))),
+ };
+ for (const section of sections) {
+ files[`${fileSlug(label(`sheets.${section}`))}.csv`] = strToU8(
+ tableCsv(trafficTable(section, data, label)),
+ );
+ }
+ body = zipSync(files);
+ }
+
+ return new Response(body, {
+ headers: {
+ 'Content-Type': CONTENT_TYPES[q.format],
+ 'Content-Disposition': `attachment; filename="${fileName}"`,
+ 'Cache-Control': 'no-store',
+ },
+ });
+ } catch (err) {
+ console.error('[traffic-export] failed:', err);
+ return Response.json({ error: 'failed' }, { status: 500 });
+ }
+}
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index 5236077b0..87d7711fe 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -190,6 +190,8 @@ async function scanTrafficLogs(
export async function getTrafficSummary(
brandId: string,
window?: TrafficDateWindow,
+ /** The page shows the top 10 landing pages; an export takes them all. */
+ opts?: { topPages?: number },
): Promise<TrafficSummary> {
const supabase = await createClient();
const { from, to, prevFrom, prevTo } = resolveTrafficWindow(window);
@@ -283,7 +285,7 @@ export async function getTrafficSummary(
visitsPrev: pageMapPrev.get(url) ?? 0,
}))
.sort((a, b) => b.visits - a.visits)
- .slice(0, 10);
+ .slice(0, opts?.topPages ?? 10);
return {
totalVisits,
@@ -343,6 +345,33 @@ export async function getTrafficTrend(
});
}
+/**
+ * The visit list's filters over ai_traffic_logs: platform, a URL search and
+ * the window. Shared by the list and its export, so the file holds the rows
+ * the list shows.
+ */
+function visitListQuery(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ brandId: string,
+ filters: { platform?: string; search?: string; from?: string; to?: string },
+ columns: string,
+ head: boolean,
+) {
+ let query = supabase
+ .from('ai_traffic_logs')
+ .select(columns, { count: 'exact', head })
+ .eq('brand_id', brandId);
+ if (filters.platform) query = query.eq('source_platform', filters.platform);
+ if (filters.search) {
+ // Escape \, % and _ for ILIKE to treat them as literals, not wildcards
+ const escaped = filters.search.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_');
+ query = query.ilike('url', `%${escaped}%`);
+ }
+ if (filters.from) query = query.gte('created_at', filters.from);
+ if (filters.to) query = query.lte('created_at', filters.to);
+ return query;
+}
+
/**
* The window's visits, newest first, one row per visit with its pageviews
* (AT-003). `total` counts the visits that match; `pageviews` counts every
@@ -370,21 +399,9 @@ export async function getTrafficLogs(
});
// 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;
- };
+ const filters = { platform, search, from, to };
+ const matching = (columns: string, head: boolean) =>
+ visitListQuery(supabase, brandId, filters, columns, head);
const [visits, pageviews] = await Promise.all([
matching('*', false)
@@ -420,6 +437,67 @@ export async function getTrafficLogs(
return { logs, total: visits.count ?? 0, pageviews: pageviews.count ?? 0 };
}
+/**
+ * Every visit the list would show, for an export (AT-015): the list's
+ * filters, all of its pages, each visit with its pageviews. Null when there
+ * are more than `max`, which the export refuses rather than build slowly.
+ *
+ * The pageviews come from one scan of the window's repeat rows rather than
+ * an id list per page of visits: a thousand ids don't fit in a request URL.
+ * A visit's repeats follow it, so the scan starts with the window and has
+ * no end, as the list counts them.
+ */
+export async function getTrafficVisitsForExport(
+ brandId: string,
+ opts: { platform?: string; search?: string; dateFrom?: string; dateTo?: string; max: number },
+): Promise<TrafficLog[] | null> {
+ const supabase = await createClient();
+ const { from, to } = resolveTrafficWindow({ dateFrom: opts.dateFrom, dateTo: opts.dateTo });
+ const filters = { platform: opts.platform, search: opts.search, from, to };
+
+ const counted = await visitListQuery(supabase, brandId, filters, 'id', true).is('visit_of', null);
+ if (counted.error) throw new Error(counted.error.message);
+ const total = counted.count ?? 0;
+ if (total > opts.max) return null;
+
+ const visits: TrafficLog[] = [];
+ for (let start = 0; start < total; start += TRAFFIC_PAGE_SIZE) {
+ const { data, error } = await visitListQuery(supabase, brandId, filters, '*', false)
+ .is('visit_of', null)
+ .order('created_at', { ascending: false })
+ .order('id', { ascending: false })
+ .range(start, start + TRAFFIC_PAGE_SIZE - 1);
+ if (error) throw new Error(error.message);
+ const batch = (data ?? []) as unknown as Record<string, unknown>[];
+ visits.push(...batch.map(mapLogRow));
+ if (batch.length < TRAFFIC_PAGE_SIZE) break;
+ }
+ if (visits.length === 0) return visits;
+
+ const extra = new Map<string, number>();
+ for (let start = 0; ; start += TRAFFIC_PAGE_SIZE) {
+ let query = supabase
+ .from('ai_traffic_logs')
+ .select('id, visit_of')
+ .eq('brand_id', brandId)
+ .not('visit_of', 'is', null)
+ .order('created_at', { ascending: true })
+ .order('id', { ascending: true })
+ .range(start, start + TRAFFIC_PAGE_SIZE - 1);
+ if (from) query = query.gte('created_at', from);
+ if (opts.platform) query = query.eq('source_platform', opts.platform);
+ const { data, error } = await query;
+ if (error) throw new Error(error.message);
+ for (const row of data ?? []) {
+ const id = row.visit_of as string;
+ extra.set(id, (extra.get(id) ?? 0) + 1);
+ }
+ if ((data ?? []).length < TRAFFIC_PAGE_SIZE) break;
+ }
+ for (const visit of visits) visit.pageviews += extra.get(visit.id) ?? 0;
+ return visits;
+}
+
/**
* Pages that carry commercial weight and got no AI visit in the page's range
* (#719, AT-002), from Analytics' AI channel or the tracking snippet.
@@ -461,6 +539,8 @@ export interface PageOpportunities {
export async function getPageOpportunities(
brandId: string,
window?: TrafficDateWindow,
+ /** The card shows the best ten; an export asks for more. */
+ opts?: { limit?: number },
): Promise<PageOpportunities> {
const supabase = await createClient();
const {
@@ -475,6 +555,7 @@ export async function getPageOpportunities(
const to = utcDay(window?.dateTo);
if (from) params.set('from', from);
if (to) params.set('to', to);
+ if (opts?.limit) params.set('limit', String(opts.limit));
const res = await fetch(
`${API_BASE_URL}/api/integrations/google-analytics/page-opportunities?${params}`,
diff --git a/web/src/lib/traffic-export.test.ts b/web/src/lib/traffic-export.test.ts
new file mode 100644
index 000000000..bb6d88fef
--- /dev/null
+++ b/web/src/lib/traffic-export.test.ts
@@ -0,0 +1,274 @@
+import { createTranslator } from 'next-intl';
+import { describe, expect, it } from 'vitest';
+import messages from '../../messages/en.json';
+import type { SourceState } from '@/lib/actions/integrations';
+import {
+ BYTE_ORDER_MARK,
+ TRAFFIC_EXPORT_SECTIONS,
+ filtersTable,
+ tableCsv,
+ trafficExportFileName,
+ trafficTable,
+ trafficWorkbook,
+ type ExportLabel,
+ type TrafficExportData,
+} from './traffic-export';
+
+/**
+ * AT-015: the AI Traffic page as files. Every section as a table with the
+ * page's own numbers, numbers kept as numbers, and a reason wherever the
+ * page would show no number.
+ */
+
+const t = createTranslator({ locale: 'en', messages, namespace: 'traffic.export' });
+const label: ExportLabel = (key, values) => t(key as never, values as never);
+
+const source = (over: Partial<SourceState> = {}): SourceState => ({
+ configured: true,
+ connected: true,
+ mapped: true,
+ firstDataAt: '2026-09-01T06:00:00Z',
+ lastDataAt: '2026-10-18T06:00:00Z',
+ property: '123',
+ ...over,
+});
+
+const data = (over: Partial<TrafficExportData> = {}): TrafficExportData => ({
+ brandName: 'Acme Coffee',
+ rangeLabel: 'last 7 days',
+ from: '2026-10-11',
+ to: '2026-10-18',
+ platform: null,
+ search: null,
+ exportedAt: new Date('2026-10-18T10:05:00Z'),
+ summary: {
+ totalVisits: 55,
+ totalVisitsPrev: 39,
+ totalPageviews: 59,
+ hasPreviousPeriod: true,
+ platformBreakdown: [
+ { platform: 'chatgpt.com', visits: 40, visitsPrev: 33 },
+ { platform: 'gemini.google.com', visits: 12, visitsPrev: 5 },
+ { platform: 'claude.ai', visits: 3, visitsPrev: 0 },
+ ],
+ topPages: [{ url: '/pricing', visits: 35, visitsPrev: 30 }],
+ hasAnyData: true,
+ },
+ trend: [
+ { date: '2026-10-17', 'chatgpt.com': 5, 'gemini.google.com': 1 },
+ { date: '2026-10-18', 'chatgpt.com': 2, 'gemini.google.com': 0 },
+ ],
+ visits: [
+ {
+ id: 'v1',
+ brandId: 'b1',
+ url: 'https://acme.example/menu/?utm_source=gemini',
+ referrer: 'https://gemini.google.com/',
+ sourcePlatform: 'gemini.google.com',
+ country: 'TR',
+ language: 'tr',
+ screen: null,
+ createdAt: '2026-10-17T09:30:12.000Z',
+ pageviews: 3,
+ },
+ ],
+ opportunitiesStatus: 'connected',
+ opportunities: {
+ pages: 30,
+ rows: [
+ {
+ landingPage: '/shop/beans',
+ valueSignal: 'key_events',
+ valuePercentile: 90.9,
+ valueRank: 3,
+ sessions: 440,
+ engagedSessions: 220,
+ keyEvents: 70,
+ transactions: 0,
+ revenue: 0,
+ engagementSeconds: 0,
+ citationState: 'targeted_not_cited',
+ citations: 0,
+ citingPrompts: 0,
+ targetingPrompts: 2,
+ },
+ ],
+ },
+ sources: {
+ snippetLastVisitAt: new Date().toISOString(),
+ ga: source(),
+ gsc: source({ connected: false }),
+ },
+ ...over,
+});
+
+describe('trafficTable', () => {
+ it('gives the KPIs with the change as a number once both periods have 30 visits', () => {
+ const table = trafficTable('kpis', data(), label);
+ expect(table.headers).toEqual(['Metric', 'Value', 'Note']);
+ expect(table.rows).toEqual([
+ ['AI-referred visits', 55, null],
+ ['Pageviews', 59, null],
+ ['Visits, previous period', 39, null],
+ ['Change vs previous period (%)', 41, null],
+ ['Top platform', 'ChatGPT', null],
+ ['Top platform visits', 40, null],
+ ['Platforms', 3, null],
+ ]);
+ });
+
+ it('leaves a change the page would not show empty, and says why (F4)', () => {
+ const table = trafficTable('platforms', data(), label);
+ expect(table.rows).toEqual([
+ ['ChatGPT', 40, 33, 21, 72.7, null],
+ ['Gemini', 12, 5, null, 21.8, expect.stringContaining('Low sample')],
+ ['Claude', 3, 0, null, 5.5, expect.stringContaining('New')],
+ ]);
+ });
+
+ it('has no previous period for all time', () => {
+ const summary = { ...data().summary!, hasPreviousPeriod: false, totalVisitsPrev: 0 };
+ const kpis = trafficTable('kpis', data({ summary }), label);
+ expect(kpis.rows.map((r) => r[0])).not.toContain('Visits, previous period');
+ expect(kpis.rows.find((r) => r[0] === 'Change vs previous period (%)')).toEqual([
+ 'Change vs previous period (%)',
+ null,
+ 'No previous period for all time',
+ ]);
+ expect(trafficTable('pages', data({ summary }), label).rows[0]).toEqual([
+ '/pricing',
+ 35,
+ null,
+ null,
+ 'No previous period for all time',
+ ]);
+ });
+
+ it('gives the trend as one row per day and one column per platform', () => {
+ expect(trafficTable('trend', data(), label)).toEqual({
+ headers: ['Day', 'ChatGPT', 'Gemini'],
+ rows: [
+ ['2026-10-17', 5, 1],
+ ['2026-10-18', 2, 0],
+ ],
+ });
+ });
+
+ it('gives each visit with its page, full URL and pageviews', () => {
+ expect(trafficTable('visits', data(), label)).toEqual({
+ headers: ['Time (UTC)', 'Platform', 'Page', 'URL', 'Referrer', 'Country', 'Pageviews'],
+ rows: [
+ [
+ '2026-10-17 09:30',
+ 'Gemini',
+ '/menu/',
+ 'https://acme.example/menu/?utm_source=gemini',
+ 'https://gemini.google.com/',
+ 'TR',
+ 3,
+ ],
+ ],
+ });
+ });
+
+ it('gives the pages without AI traffic with the value that ranked them', () => {
+ const table = trafficTable('opportunities', data(), label);
+ expect(table.rows).toEqual([
+ ['/shop/beans', 'Not cited', 0, 2, 440, 'Conversions', 70, 3, 90.9],
+ ]);
+ });
+
+ it('says why there are no pages without AI traffic, never an empty sheet', () => {
+ const note = (over: Partial<TrafficExportData>) =>
+ trafficTable('opportunities', data(over), label);
+ expect(note({ opportunitiesStatus: 'not_connected' }).rows).toEqual([
+ ['Needs Google Analytics: not connected'],
+ ]);
+ expect(note({ opportunities: { pages: 0, rows: [] } }).rows).toEqual([
+ ['No data for this range in Google Analytics'],
+ ]);
+ expect(note({ opportunities: { pages: 30, rows: [] } }).rows).toEqual([
+ ['No high-value pages without AI traffic in this range'],
+ ]);
+ expect(note({ opportunitiesStatus: 'failed', opportunities: null }).rows[0][0]).toContain(
+ "couldn't be read",
+ );
+ });
+});
+
+describe('filtersTable', () => {
+ it('records the range, the filters, the sources and when', () => {
+ const table = filtersTable(
+ data({ platform: 'gemini.google.com', search: 'menu', from: null }),
+ label,
+ );
+ expect(Object.fromEntries(table.rows.map(([k, v]) => [k, v]))).toEqual({
+ Brand: 'Acme Coffee',
+ Range: 'last 7 days',
+ From: 'Start',
+ To: '2026-10-18',
+ Platform: 'Gemini',
+ Search: 'menu',
+ 'Tracking snippet': 'Active',
+ 'Google Analytics': 'Connected',
+ 'Google Search Console': 'Not connected',
+ 'Exported at': '2026-10-18 10:05 UTC',
+ });
+ });
+});
+
+describe('trafficWorkbook', () => {
+ it('puts the Filters sheet first and one sheet per section after it', () => {
+ const sheets = trafficWorkbook(data(), TRAFFIC_EXPORT_SECTIONS, label, { withFilters: true });
+ expect(sheets.map((s) => s.sheet)).toEqual([
+ 'Filters',
+ 'KPIs',
+ 'Trend',
+ 'Platforms',
+ 'Top landing pages',
+ 'Pages without AI traffic',
+ 'Visits',
+ ]);
+ // A bold header row, then the rows with their numbers as numbers.
+ expect(sheets[3].data[0][0]).toEqual({ value: 'Platform', fontWeight: 'bold' });
+ expect(sheets[3].data[1]).toEqual(['ChatGPT', 40, 33, 21, 72.7, null]);
+ });
+
+ it('holds only the table for a single table', () => {
+ const sheets = trafficWorkbook(data(), ['visits'], label, { withFilters: false });
+ expect(sheets.map((s) => s.sheet)).toEqual(['Visits']);
+ });
+});
+
+describe('tableCsv', () => {
+ it('starts with a byte order mark, so Excel reads it as UTF-8', () => {
+ const csv = tableCsv({ headers: ['Page', 'Visits'], rows: [['/çay, demlik', 3]] });
+ expect(csv.startsWith(BYTE_ORDER_MARK)).toBe(true);
+ expect(csv.slice(1)).toBe('Page,Visits\n"/çay, demlik",3');
+ });
+});
+
+describe('trafficExportFileName', () => {
+ it('names the whole page ansvisor-ai-traffic-{brand}-{from}_{to}', () => {
+ expect(
+ trafficExportFileName({
+ brand: 'Acme Coffee',
+ from: '2026-10-11',
+ to: '2026-10-18',
+ ext: 'xlsx',
+ }),
+ ).toBe('ansvisor-ai-traffic-acme-coffee-2026-10-11_2026-10-18.xlsx');
+ });
+
+ it('adds the table for a single table, and says all time when there is no start', () => {
+ expect(
+ trafficExportFileName({
+ brand: 'acme-coffee',
+ from: null,
+ to: '2026-10-18',
+ ext: 'csv',
+ table: 'Top landing pages',
+ }),
+ ).toBe('ansvisor-ai-traffic-acme-coffee-top-landing-pages-all-time_2026-10-18.csv');
+ });
+});
diff --git a/web/src/lib/traffic-export.ts b/web/src/lib/traffic-export.ts
new file mode 100644
index 000000000..692720aa0
--- /dev/null
+++ b/web/src/lib/traffic-export.ts
@@ -0,0 +1,364 @@
+/**
+ * The AI Traffic page as files (AT-015, spec §3.9): the whole page as an
+ * Excel workbook, one sheet per section plus a Filters sheet, or as a zip of
+ * one CSV per section; and each table on its own.
+ *
+ * Pure: the route reads the data and calls these. Numbers stay numbers, so a
+ * spreadsheet can sum them; a % change the page wouldn't show (below 30
+ * visits, or no previous period) is left empty with the reason beside it.
+ */
+
+import type { Sheet } from 'write-excel-file/node';
+import type {
+ PageOpportunities,
+ TrafficLog,
+ TrafficSources,
+ TrafficSummary,
+ TrafficTrendPoint,
+} from '@/lib/actions/traffic';
+import { csvLine } from '@/lib/csv';
+import { getPlatformName } from '@/lib/traffic-platforms';
+import { visitChange } from '@/lib/traffic-change';
+import {
+ googleSourceStatus,
+ snippetDetected,
+ type GoogleSourceStatus,
+} from '@/lib/traffic-sources';
+
+/** Every section, in the page's order. */
+export const TRAFFIC_EXPORT_SECTIONS = [
+ 'kpis',
+ 'trend',
+ 'platforms',
+ 'pages',
+ 'opportunities',
+ 'visits',
+] as const;
+
+export type TrafficExportSection = (typeof TRAFFIC_EXPORT_SECTIONS)[number];
+
+/** The tables that carry their own Excel / CSV buttons, as in the mockup. */
+export const TRAFFIC_TABLE_SECTIONS = ['platforms', 'pages', 'opportunities', 'visits'] as const;
+
+/** Beyond this many visits an export would take too long to build on request. */
+export const TRAFFIC_EXPORT_MAX_ROWS = 100_000;
+
+/** A label from en.json's traffic.export namespace. */
+export type ExportLabel = (key: string, values?: Record<string, string | number>) => string;
+
+export interface TrafficExportData {
+ brandName: string;
+ /** The page's words for the range, e.g. "last 7 days". */
+ rangeLabel: string;
+ /** First and last day (YYYY-MM-DD); no first day for all time. */
+ from: string | null;
+ to: string;
+ platform: string | null;
+ search: string | null;
+ exportedAt: Date;
+ summary?: TrafficSummary;
+ trend?: TrafficTrendPoint[];
+ visits?: TrafficLog[];
+ /** Null when Google Analytics has nothing to rank: see `opportunitiesStatus`. */
+ opportunities?: PageOpportunities | null;
+ /** The source's state, or 'failed' when its findings couldn't be read. */
+ opportunitiesStatus?: GoogleSourceStatus | 'failed';
+ sources?: TrafficSources | null;
+}
+
+type Cell = string | number | null;
+
+export interface ExportTable {
+ headers: string[];
+ rows: Cell[][];
+}
+
+/** A change the page would show, as a number, or why there is none. */
+function change(current: number, previous: number, comparable: boolean, label: ExportLabel) {
+ const c = visitChange(current, previous, { comparable });
+ if (c.kind === 'pct') return { pct: c.pct, note: '' };
+ if (c.kind === 'low') return { pct: null, note: label('notes.lowSample') };
+ if (c.kind === 'new') return { pct: null, note: label('notes.new') };
+ return { pct: null, note: comparable ? '' : label('notes.noPreviousPeriod') };
+}
+
+function pathOf(url: string): string {
+ try {
+ return new URL(url).pathname;
+ } catch {
+ return url;
+ }
+}
+
+/** "2026-10-17 09:30" in UTC: sorts and reads the same everywhere. */
+function utcMinute(iso: string): string {
+ return new Date(iso).toISOString().slice(0, 16).replace('T', ' ');
+}
+
+function kpis(data: TrafficExportData, label: ExportLabel): ExportTable {
+ const s = data.summary;
+ if (!s) return { headers: [], rows: [] };
+ const top = s.platformBreakdown[0];
+ const delta = change(s.totalVisits, s.totalVisitsPrev, s.hasPreviousPeriod, label);
+ return {
+ headers: [label('columns.metric'), label('columns.value'), label('columns.note')],
+ rows: [
+ [label('metrics.visits'), s.totalVisits, null],
+ [label('metrics.pageviews'), s.totalPageviews, null],
+ ...(s.hasPreviousPeriod
+ ? ([[label('metrics.previousVisits'), s.totalVisitsPrev, null]] as Cell[][])
+ : []),
+ [label('metrics.change'), delta.pct, delta.note || null],
+ [label('metrics.topPlatform'), top ? getPlatformName(top.platform) : null, null],
+ [label('metrics.topPlatformVisits'), top ? top.visits : null, null],
+ [label('metrics.platforms'), s.platformBreakdown.length, null],
+ ],
+ };
+}
+
+function trend(data: TrafficExportData, label: ExportLabel): ExportTable {
+ const points = data.trend ?? [];
+ const platforms = [...new Set(points.flatMap((p) => Object.keys(p).filter((k) => k !== 'date')))];
+ return {
+ headers: [label('columns.day'), ...platforms.map(getPlatformName)],
+ rows: points.map((p) => [p.date, ...platforms.map((k) => Number(p[k]) || 0)]),
+ };
+}
+
+function platforms(data: TrafficExportData, label: ExportLabel): ExportTable {
+ const s = data.summary;
+ const total = s?.totalVisits ?? 0;
+ return {
+ headers: [
+ label('columns.platform'),
+ label('columns.visits'),
+ label('columns.previousVisits'),
+ label('columns.change'),
+ label('columns.share'),
+ label('columns.note'),
+ ],
+ rows: (s?.platformBreakdown ?? []).map((row) => {
+ const delta = change(row.visits, row.visitsPrev, s!.hasPreviousPeriod, label);
+ return [
+ getPlatformName(row.platform),
+ row.visits,
+ s!.hasPreviousPeriod ? row.visitsPrev : null,
+ delta.pct,
+ total > 0 ? Math.round((row.visits / total) * 1000) / 10 : null,
+ delta.note || null,
+ ];
+ }),
+ };
+}
+
+function pages(data: TrafficExportData, label: ExportLabel): ExportTable {
+ const s = data.summary;
+ return {
+ headers: [
+ label('columns.page'),
+ label('columns.visits'),
+ label('columns.previousVisits'),
+ label('columns.change'),
+ label('columns.note'),
+ ],
+ rows: (s?.topPages ?? []).map((row) => {
+ const delta = change(row.visits, row.visitsPrev, s!.hasPreviousPeriod, label);
+ return [
+ row.url,
+ row.visits,
+ s!.hasPreviousPeriod ? row.visitsPrev : null,
+ delta.pct,
+ delta.note || null,
+ ];
+ }),
+ };
+}
+
+function opportunities(data: TrafficExportData, label: ExportLabel): ExportTable {
+ const status = data.opportunitiesStatus ?? 'connected';
+ const result = data.opportunities;
+ // Never an empty sheet: say why there are no rows (spec §3.8b).
+ const note = (text: string): ExportTable => ({
+ headers: [label('columns.note')],
+ rows: [[text]],
+ });
+ if (status !== 'connected') return note(label(`notes.analytics.${status}`));
+ if (!result || result.pages === 0) return note(label('notes.analytics.noData'));
+ if (result.rows.length === 0) return note(label('notes.analytics.noFinding'));
+ return {
+ headers: [
+ label('columns.page'),
+ label('columns.aiVisibility'),
+ label('columns.citations'),
+ label('columns.targetingPrompts'),
+ label('columns.sessions'),
+ label('columns.rankedBy'),
+ label('columns.value'),
+ label('columns.rank'),
+ label('columns.percentile'),
+ ],
+ rows: result.rows.map((row) => [
+ row.landingPage,
+ label(`citationStates.${row.citationState}`),
+ row.citations,
+ row.targetingPrompts,
+ row.sessions,
+ label(`signals.${row.valueSignal}`),
+ row.valueSignal === 'revenue'
+ ? row.revenue
+ : row.valueSignal === 'transactions'
+ ? row.transactions
+ : row.valueSignal === 'key_events'
+ ? row.keyEvents
+ : Math.round(row.engagementSeconds / 60),
+ row.valueRank,
+ row.valuePercentile,
+ ]),
+ };
+}
+
+function visits(data: TrafficExportData, label: ExportLabel): ExportTable {
+ return {
+ headers: [
+ label('columns.time'),
+ label('columns.platform'),
+ label('columns.page'),
+ label('columns.url'),
+ label('columns.referrer'),
+ label('columns.country'),
+ label('columns.pageviews'),
+ ],
+ rows: (data.visits ?? []).map((v) => [
+ utcMinute(v.createdAt),
+ getPlatformName(v.sourcePlatform ?? 'unknown'),
+ pathOf(v.url),
+ v.url,
+ v.referrer,
+ v.country,
+ v.pageviews,
+ ]),
+ };
+}
+
+/** One section as a table: its headers and its rows. */
+export function trafficTable(
+ section: TrafficExportSection,
+ data: TrafficExportData,
+ label: ExportLabel,
+): ExportTable {
+ switch (section) {
+ case 'kpis':
+ return kpis(data, label);
+ case 'trend':
+ return trend(data, label);
+ case 'platforms':
+ return platforms(data, label);
+ case 'pages':
+ return pages(data, label);
+ case 'opportunities':
+ return opportunities(data, label);
+ case 'visits':
+ return visits(data, label);
+ }
+}
+
+/** What the export was made from: the range, the filters, the sources and when. */
+export function filtersTable(data: TrafficExportData, label: ExportLabel): ExportTable {
+ const sourceState = (status: GoogleSourceStatus) => label(`sourceStates.${status}`);
+ const sources = data.sources;
+ return {
+ headers: [label('columns.setting'), label('columns.value')],
+ rows: [
+ [label('filters.brand'), data.brandName],
+ [label('filters.range'), data.rangeLabel],
+ [label('filters.from'), data.from ?? label('filters.start')],
+ [label('filters.to'), data.to],
+ [
+ label('filters.platform'),
+ data.platform ? getPlatformName(data.platform) : label('filters.allPlatforms'),
+ ],
+ [label('filters.search'), data.search || label('filters.none')],
+ [
+ label('filters.snippet'),
+ sources
+ ? snippetDetected(sources.snippetLastVisitAt)
+ ? label('sourceStates.active')
+ : label('sourceStates.notDetected')
+ : null,
+ ],
+ [label('filters.ga'), sources ? sourceState(googleSourceStatus(sources.ga)) : null],
+ [label('filters.gsc'), sources ? sourceState(googleSourceStatus(sources.gsc)) : null],
+ [label('filters.exportedAt'), `${utcMinute(data.exportedAt.toISOString())} UTC`],
+ ],
+ };
+}
+
+const bold = (value: string) => ({ value, fontWeight: 'bold' as const });
+
+function sheetOf(name: string, table: ExportTable): Sheet<Buffer> {
+ return {
+ sheet: name,
+ stickyRowsCount: 1,
+ columns: table.headers.map((_, i) => ({ width: i === 0 ? 44 : 18 })),
+ data: [table.headers.map(bold), ...table.rows],
+ };
+}
+
+/**
+ * The workbook: the sections asked for, one sheet each, and — for the whole
+ * page — the Filters sheet first, so whoever opens the file sees what it is.
+ */
+export function trafficWorkbook(
+ data: TrafficExportData,
+ sections: readonly TrafficExportSection[],
+ label: ExportLabel,
+ { withFilters }: { withFilters: boolean },
+): Sheet<Buffer>[] {
+ return [
+ ...(withFilters ? [sheetOf(label('sheets.filters'), filtersTable(data, label))] : []),
+ ...sections.map((section) =>
+ sheetOf(label(`sheets.${section}`), trafficTable(section, data, label)),
+ ),
+ ];
+}
+
+/** Excel opens a UTF-8 CSV as UTF-8 only when it starts with a byte order mark. */
+export const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
+
+export function tableCsv(table: ExportTable): string {
+ return BYTE_ORDER_MARK + [csvLine(table.headers), ...table.rows.map(csvLine)].join('\n');
+}
+
+/** "acme-coffee" from a brand name or a sheet name: safe in a file name. */
+export function fileSlug(value: string): string {
+ return (
+ value
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '') || 'brand'
+ );
+}
+
+/**
+ * ansvisor-ai-traffic-{brand}-{from}_{to}.{ext} (spec §3.9); a single table
+ * adds its name. All time has no first day.
+ */
+export function trafficExportFileName({
+ brand,
+ from,
+ to,
+ ext,
+ table,
+}: {
+ brand: string;
+ from: string | null;
+ to: string;
+ ext: 'xlsx' | 'zip' | 'csv';
+ /** The table's sheet name, for a single table. */
+ table?: string;
+}): string {
+ const range = from ? `${from}_${to}` : `all-time_${to}`;
+ const parts = ['ansvisor-ai-traffic', fileSlug(brand), table && fileSlug(table), range];
+ return `${parts.filter(Boolean).join('-')}.${ext}`;
+}