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(mentions): add Copy summary and Export CSV to the Mentions page (#1125)

Cihan0ca1ceb2409a
diff --git a/web/messages/en.json b/web/messages/en.json
index 40aee8cf6..a30afceee 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3275,6 +3275,38 @@
"clearSelection": "Clear",
"selectAll": "Select every answer on this page",
"selectRow": "Select the answer to “{prompt}” on {platform}"
+ },
+ "export": {
+ "copySummary": "Copy summary",
+ "copying": "Copying…",
+ "copied": "Summary copied",
+ "copyFailed": "Couldn't copy the summary. Try again in a moment.",
+ "copyBlocked": "Your browser didn't allow copying here. Allow clipboard access for this site and try again.",
+ "exportFailed": "Couldn't export the mentions. Try again in a moment.",
+ "nothing": "No mentions to export for these filters.",
+ "capped": "The file holds {shown} of {total} mentions. Narrow the filters to export the rest.",
+ "pickDates": "Choose a start or end date first.",
+ "reports": "Reports",
+ "exportSelected": "Export",
+ "facts": {
+ "period": "Period",
+ "periodDays": "{from} – {to} ({days, plural, one {# day} other {# days}}, UTC)",
+ "periodMoments": "{from} – {to} UTC",
+ "responses": "Tracked responses (n)",
+ "mentions": "Mentions (n)",
+ "prompts": "Prompts with mentions (n)",
+ "inFile": "Mentions in this file (n)",
+ "note": "Note",
+ "capped": "Only the first {shown} of {total} mentions, in the table's order. Narrow the filters to export the rest.",
+ "exported": "Exported (UTC)"
+ },
+ "summary": {
+ "title": "Mentions & Sentiment · {brand}",
+ "search": "Search: “{q}”",
+ "kpi": "{label}: {value}",
+ "kpiChange": "{label}: {value} ({change})",
+ "net": "{net} · {split} (n={count})"
+ }
}
},
"competitors": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.test.tsx
new file mode 100644
index 000000000..94bebc021
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.test.tsx
@@ -0,0 +1,336 @@
+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 {
+ DEFAULT_MENTIONS_FILTERS,
+ type MentionsFilters,
+ type MentionsTab,
+} from '@/lib/mentions-filters';
+import { DEFAULT_MENTIONS_TABLE, type MentionRow, type MentionsList } from '@/lib/mentions-list';
+import type { MentionTotals, MentionsOverview } from '@/lib/mentions-overview';
+import type { Competitor, Topic } from '@/types';
+import { MentionsHeaderActions } from './_header-actions';
+import { useMentionsExport } from './_use-mentions-export';
+
+const getMentionsOverview = vi.fn();
+const exportMentions = vi.fn();
+vi.mock('@/lib/actions/mentions', () => ({
+ getMentionsOverview: (...args: unknown[]) => getMentionsOverview(...args),
+ exportMentions: (...args: unknown[]) => exportMentions(...args),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+const toast = vi.hoisted(() => ({
+ success: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+}));
+vi.mock('sonner', () => ({ toast }));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const totals = (over: Partial<MentionTotals>): MentionTotals => ({
+ answers: 0,
+ mentions: 0,
+ occurrences: 0,
+ positive: 0,
+ negative: 0,
+ positionSum: 0,
+ positionCount: 0,
+ prompts: 0,
+ promptsWithMentions: 0,
+ lastAnswerAt: null,
+ ...over,
+});
+
+const overview: MentionsOverview = {
+ window: {
+ from: '2026-09-17T09:00:00Z',
+ to: '2026-10-17T09:00:00Z',
+ days: 30,
+ source: 'days',
+ dayFrom: '2026-09-18',
+ dayTo: '2026-10-17',
+ },
+ current: totals({
+ answers: 400,
+ mentions: 100,
+ positive: 48,
+ negative: 14,
+ prompts: 20,
+ promptsWithMentions: 15,
+ }),
+ previous: totals({ answers: 400, mentions: 80, positive: 40, negative: 8, prompts: 20 }),
+ platforms: [],
+ daily: [],
+ competitors: [
+ { competitorId: 'c1', name: 'Crema Club', mentions: 90, coMentions: 41, previousMentions: 0 },
+ ],
+};
+
+const row = (id: string): MentionRow => ({
+ id,
+ createdAt: '2026-10-16T11:28:06Z',
+ promptId: 'p1',
+ promptText: 'Best espresso beans?',
+ topicId: 't1',
+ topicName: 'Beans',
+ platform: 'gemini-web',
+ model: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ occurrences: 1,
+ position: 2,
+ brandsNamed: 2,
+ coMentioned: [{ competitorId: 'c1', name: 'Crema Club', position: 1 }],
+ excerpt: 'Crema Club is first; Acme Coffee is pricier.',
+ groupKey: null,
+ groupCount: null,
+});
+
+const list = (over: Partial<MentionsList> = {}): MentionsList => ({
+ total: 2,
+ prompts: 1,
+ rows: [row('r1'), row('r2')],
+ brandTerms: ['Acme Coffee'],
+ ...over,
+});
+
+const topics = [{ id: 't1', name: 'Beans' }] as Topic[];
+const competitors = [{ id: 'c1', name: 'Crema Club' }] as Competitor[];
+
+function Harness({ tab, filters }: { tab: MentionsTab; filters: MentionsFilters }) {
+ const exporter = useMentionsExport({
+ brandId: 'b1',
+ brand: 'Acme Coffee',
+ slug: 'acme-coffee',
+ filters,
+ topics,
+ competitors,
+ });
+ return <MentionsHeaderActions tab={tab} exporter={exporter} />;
+}
+
+let container: HTMLDivElement;
+let root: Root;
+let saved: { name: string; blob: Blob }[];
+const writeText = vi.fn();
+
+function render(tab: MentionsTab = 'overview', filters = DEFAULT_MENTIONS_FILTERS) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <Harness tab={tab} filters={filters} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const button = (label: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === label) as
+ | HTMLButtonElement
+ | undefined;
+
+async function click(label: string) {
+ await act(async () => {
+ button(label)!.click();
+ });
+}
+
+// The saved file's text, after checking it opens with UTF-8's byte order mark (for Excel).
+async function savedText() {
+ const bytes = await new Promise<Uint8Array>((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));
+ reader.readAsArrayBuffer(saved[0].blob);
+ });
+ expect([...bytes.slice(0, 3)]).toEqual([0xef, 0xbb, 0xbf]);
+ return new TextDecoder().decode(bytes);
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ saved = [];
+ let blob: Blob | null = null;
+ URL.createObjectURL = vi.fn((b: Blob) => ((blob = b), 'blob:mentions'));
+ URL.revokeObjectURL = vi.fn();
+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
+ this: HTMLAnchorElement,
+ ) {
+ saved.push({ name: this.download, blob: blob! });
+ });
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
+ window.history.replaceState(null, '', '/dashboard/mentions');
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ getMentionsOverview.mockReset();
+ exportMentions.mockReset();
+ writeText.mockReset();
+ Object.values(toast).forEach((fn) => fn.mockReset());
+ vi.restoreAllMocks();
+});
+
+describe('MentionsHeaderActions', () => {
+ it('copies the Overview as text, with the filters and the n values', async () => {
+ getMentionsOverview.mockResolvedValue(overview);
+ render();
+ await click('Copy summary');
+ expect(getMentionsOverview).toHaveBeenCalledWith('b1', expect.objectContaining({}));
+ expect(writeText.mock.calls[0][0]).toBe(
+ [
+ 'Mentions & Sentiment · Acme Coffee',
+ 'All platforms · All countries · All topics',
+ 'Net sentiment is +34 (↓ 6 vs the previous 30 days). AI usually names Acme Coffee next to Crema Club.',
+ 'Total mentions: 100 (+25%)',
+ 'Mention rate: 25.0% of 400 tracked responses',
+ 'Prompts with mentions: 15 of 20 tracked prompts',
+ 'Net sentiment: +34 · 48% positive, 38% neutral, 14% negative (n=100)',
+ 'Built from aggregates with a fixed template, no LLM call · Sep 18 – Oct 17 · ' +
+ '400 tracked responses · 100 mentions',
+ ].join('\n'),
+ );
+ expect(toast.success).toHaveBeenCalledWith('Summary copied');
+ });
+
+ it('names the filters in use, and marks a low sample instead of a split', async () => {
+ getMentionsOverview.mockResolvedValue({
+ ...overview,
+ current: totals({
+ answers: 12,
+ mentions: 3,
+ positive: 2,
+ prompts: 2,
+ promptsWithMentions: 1,
+ }),
+ previous: totals({}),
+ competitors: [],
+ });
+ render('overview', {
+ ...DEFAULT_MENTIONS_FILTERS,
+ platform: 'gemini-web',
+ region: 'DE',
+ topic: 't1',
+ q: 'espresso',
+ });
+ await click('Copy summary');
+ const lines = (writeText.mock.calls[0][0] as string).split('\n');
+ expect(lines[1]).toBe('Gemini · Germany · Beans · Search: “espresso”');
+ expect(lines.slice(3, 7)).toEqual([
+ 'Total mentions: 3',
+ 'Mention rate: 25.0% · Low sample · 12 responses',
+ 'Prompts with mentions: 1 of 2 tracked prompts',
+ 'Net sentiment: +67 · Low sample · 3 responses',
+ ]);
+ });
+
+ it('says so when the summary could not be read, or the browser refused the clipboard', async () => {
+ getMentionsOverview.mockResolvedValue(null);
+ render();
+ await click('Copy summary');
+ expect(writeText).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith("Couldn't copy the summary. Try again in a moment.");
+
+ getMentionsOverview.mockResolvedValue(overview);
+ writeText.mockRejectedValueOnce(
+ new DOMException('Write permission denied.', 'NotAllowedError'),
+ );
+ await click('Copy summary');
+ expect(toast.error).toHaveBeenLastCalledWith(
+ "Your browser didn't allow copying here. Allow clipboard access for this site and try again.",
+ );
+ });
+
+ it('exports every mention under the filters, below what the file holds', async () => {
+ getMentionsOverview.mockResolvedValue(overview);
+ exportMentions.mockResolvedValue(list());
+ render();
+ await click('Export CSV');
+ expect(exportMentions).toHaveBeenCalledWith(
+ 'b1',
+ expect.objectContaining({}),
+ DEFAULT_MENTIONS_TABLE,
+ );
+ expect(saved[0].name).toMatch(/^ansvisor_acme-coffee_mentions_\d{4}-\d{2}-\d{2}\.csv$/);
+ const lines = (await savedText()).split('\n');
+ expect(lines.slice(0, 10)).toEqual([
+ 'Mentions & Sentiment,Acme Coffee',
+ 'Period,"2026-09-18 – 2026-10-17 (30 days, UTC)"',
+ 'Platform,All platforms',
+ 'Country,All countries',
+ 'Topic,All topics',
+ 'Tracked responses (n),400',
+ 'Mentions (n),2',
+ 'Prompts with mentions (n),1',
+ 'Mentions in this file (n),2',
+ expect.stringMatching(/^Exported \(UTC\),\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/),
+ ]);
+ expect(lines[10]).toBe('');
+ expect(lines[11]).toMatch(/^date_utc,prompt,topic,platform/);
+ expect(lines).toHaveLength(14);
+ });
+
+ it("takes the table's filters from the Mentions tab, and notes a file cut at the cap", async () => {
+ window.history.replaceState(
+ null,
+ '',
+ '/dashboard/mentions?tab=mentions&sentiment=negative&with=c1',
+ );
+ getMentionsOverview.mockResolvedValue(overview);
+ exportMentions.mockResolvedValue(list({ total: 12_345 }));
+ render('mentions');
+ await click('Export CSV');
+ expect(exportMentions.mock.calls[0][2]).toEqual({
+ ...DEFAULT_MENTIONS_TABLE,
+ sentiment: 'negative',
+ competitor: 'c1',
+ });
+ const text = await savedText();
+ expect(text).toContain('Sentiment,Negative\nCo-mentioned,Crema Club\n');
+ expect(text).toContain(
+ 'Note,"Only the first 2 of 12,345 mentions, in the table\'s order. Narrow the filters to export the rest."',
+ );
+ expect(toast.warning).toHaveBeenCalledWith(
+ 'The file holds 2 of 12,345 mentions. Narrow the filters to export the rest.',
+ );
+ });
+
+ it('says when there is nothing to export, or the export failed', async () => {
+ getMentionsOverview.mockResolvedValue(overview);
+ exportMentions.mockResolvedValueOnce(list({ total: 0, prompts: 0, rows: [] }));
+ render();
+ await click('Export CSV');
+ expect(saved).toHaveLength(0);
+ expect(toast.info).toHaveBeenCalledWith('No mentions to export for these filters.');
+
+ exportMentions.mockRejectedValueOnce(new Error('statement timeout'));
+ await click('Export CSV');
+ expect(toast.error).toHaveBeenCalledWith(
+ "Couldn't export the mentions. Try again in a moment.",
+ );
+ });
+
+ it('waits for dates on a custom range, and links Reports', () => {
+ render('overview', { ...DEFAULT_MENTIONS_FILTERS, range: 'custom' });
+ expect(button('Copy summary')!.disabled).toBe(true);
+ expect(button('Export CSV')!.disabled).toBe(true);
+ expect(button('Export CSV')!.parentElement!.title).toBe('Choose a start or end date first.');
+ expect(container.querySelector('a[href="/dashboard/reports"]')?.textContent).toBe('Reports');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.tsx
new file mode 100644
index 000000000..ac221ee0c
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.tsx
@@ -0,0 +1,76 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Copy, Download, FileText, Loader2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { buttonVariants } from '@/components/ui/button-variants';
+import { Link } from '@/i18n/navigation';
+import type { MentionsTab } from '@/lib/mentions-filters';
+import { DEFAULT_MENTIONS_TABLE, readMentionsTable } from '@/lib/mentions-list';
+import { cn } from '@/lib/utils';
+import type { useMentionsExport } from './_use-mentions-export';
+
+/**
+ * The page's header actions, as in the mockup: Copy summary, Export CSV and
+ * Reports. From the Mentions tab, Export takes the table's own filters and
+ * sort too (read from the URL, where the tab keeps them), so the file holds
+ * what the table lists.
+ */
+export function MentionsHeaderActions({
+ tab,
+ exporter,
+}: {
+ tab: MentionsTab;
+ exporter: ReturnType<typeof useMentionsExport>;
+}) {
+ const t = useTranslations('mentions.export');
+ const common = useTranslations('common');
+ const { ready, busy } = exporter;
+ const hint = ready ? undefined : t('pickDates');
+
+ const exportAll = () =>
+ exporter.exportCsv(
+ tab === 'mentions'
+ ? readMentionsTable(new URLSearchParams(window.location.search))
+ : DEFAULT_MENTIONS_TABLE,
+ );
+
+ return (
+ <div className="flex shrink-0 flex-wrap items-center gap-2">
+ <span title={hint}>
+ <Button
+ variant="outline"
+ className="gap-2"
+ onClick={() => void exporter.copySummary()}
+ disabled={!ready || busy !== null}
+ >
+ {busy === 'copy' ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Copy className="h-4 w-4" />
+ )}
+ {busy === 'copy' ? t('copying') : t('copySummary')}
+ </Button>
+ </span>
+ <span title={hint}>
+ <Button
+ variant="outline"
+ className="gap-2"
+ onClick={() => void exportAll()}
+ disabled={!ready || busy !== null}
+ >
+ {busy === 'csv' ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Download className="h-4 w-4" />
+ )}
+ {busy === 'csv' ? common('exporting') : common('exportCsv')}
+ </Button>
+ </span>
+ <Link href="/dashboard/reports" className={cn(buttonVariants(), 'gap-2')}>
+ <FileText className="h-4 w-4" />
+ {t('reports')}
+ </Link>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx
index e2b489801..50c819ced 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx
@@ -1,5 +1,6 @@
'use client';
+import { Fragment } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';
import { mentionPlatformLabel, mentionsHeadline } from '@/lib/mentions-headline';
@@ -10,6 +11,7 @@ import {
signedChange,
signedValue,
TONE_TEXT,
+ type Tone,
} from '../insights/kpi-format';
/** "Oct 16, 9:40 AM": the 24h view's bounds, in local time. */
@@ -22,6 +24,74 @@ function momentLabel(value: string, locale: string): string {
});
}
+/** The window as the summary names it: "Sep 18 – Oct 17", or its moments under two days. */
+export function windowRange(w: MentionsOverview['window'], locale: string): string {
+ return w.source === 'answers'
+ ? `${momentLabel(w.from, locale)} – ${momentLabel(w.to, locale)}`
+ : `${dayLabel(w.dayFrom, locale)} – ${dayLabel(w.dayTo, locale)}`;
+}
+
+/** The message lookup, as next-intl's `t` for `mentions.overview.headline`. */
+type Translate = (key: string, values?: Record<string, string | number>) => string;
+
+export interface HeadlineSentence {
+ key: string;
+ values: Record<string, string | number>;
+ /** The change's colour, for the sentence that has one. */
+ tone?: Tone;
+}
+
+/**
+ * The summary line's sentences as messages, chosen once for the page (with
+ * bold and coloured parts) and Copy summary (as plain text), so the two
+ * can't drift apart.
+ */
+export function headlineSentences(
+ overview: MentionsOverview,
+ brand: string,
+ locale: string,
+ t: Translate,
+): HeadlineSentence[] {
+ const { net, lowSample, netChange, mover, companions } = mentionsHeadline(overview);
+ const { window: w, current } = overview;
+ const period = w.source === 'answers' ? t('period24h') : t('period', { days: w.days });
+ const change = arrowChange(netChange, locale);
+ const sentences: HeadlineSentence[] = [];
+
+ if (net === null) sentences.push({ key: 'noMentions', values: { brand } });
+ else if (change) {
+ sentences.push({
+ key: 'netChange',
+ values: { net: signedValue(net, locale), change: change.text, period },
+ tone: change.tone,
+ });
+ } else if (lowSample) {
+ sentences.push({
+ key: 'netLowSample',
+ values: { net: signedValue(net, locale), count: current.mentions },
+ });
+ } else sentences.push({ key: 'net', values: { net: signedValue(net, locale) } });
+
+ if (mover) {
+ sentences.push({
+ key: mover.change < 0 ? 'moverDown' : 'moverUp',
+ values: {
+ platform: mentionPlatformLabel(mover.platform),
+ change: signedChange(mover.change, locale),
+ },
+ });
+ }
+ if (companions.length === 1) {
+ sentences.push({ key: 'companionsOne', values: { brand, first: companions[0] } });
+ } else if (companions.length > 1) {
+ sentences.push({
+ key: 'companionsTwo',
+ values: { brand, first: companions[0], second: companions[1] },
+ });
+ }
+ return sentences;
+}
+
/**
* The Overview's summary line (MS-06), as in the mockup: net sentiment and
* its change, the platform behind most of it, and the brands AI names you
@@ -31,66 +101,32 @@ function momentLabel(value: string, locale: string): string {
export function Headline({ overview, brand }: { overview: MentionsOverview; brand: string }) {
const t = useTranslations('mentions.overview.headline');
const locale = useLocale();
- const { net, lowSample, netChange, mover, companions } = mentionsHeadline(overview);
- const { window: w, current } = overview;
const b = (chunks: React.ReactNode) => <b className="font-semibold">{chunks}</b>;
- const period = w.source === 'answers' ? t('period24h') : t('period', { days: w.days });
- const change = arrowChange(netChange, locale);
- const range =
- w.source === 'answers'
- ? `${momentLabel(w.from, locale)} – ${momentLabel(w.to, locale)}`
- : `${dayLabel(w.dayFrom, locale)} – ${dayLabel(w.dayTo, locale)}`;
-
return (
<section
aria-label={t('label')}
className="rounded-xl border border-l-[3px] border-l-foreground bg-card px-4 py-3 text-sm"
>
<p>
- {net === null
- ? t('noMentions', { brand })
- : change
- ? t.rich('netChange', {
- net: signedValue(net, locale),
- change: change.text,
- period,
- b,
- tone: (chunks) => (
- <span className={cn('font-medium', TONE_TEXT[change.tone])}>{chunks}</span>
- ),
- })
- : lowSample
- ? t.rich('netLowSample', {
- net: signedValue(net, locale),
- count: current.mentions,
- b,
- })
- : t.rich('net', { net: signedValue(net, locale), b })}
- {mover && (
- <>
- {' '}
- {t.rich(mover.change < 0 ? 'moverDown' : 'moverUp', {
- platform: mentionPlatformLabel(mover.platform),
- change: signedChange(mover.change, locale),
+ {headlineSentences(overview, brand, locale, t).map((s, i) => (
+ <Fragment key={s.key}>
+ {i > 0 && ' '}
+ {t.rich(s.key, {
+ ...s.values,
b,
+ tone: (chunks) => (
+ <span className={cn('font-medium', TONE_TEXT[s.tone ?? 'neutral'])}>{chunks}</span>
+ ),
})}
- </>
- )}
- {companions.length > 0 && (
- <>
- {' '}
- {companions.length === 1
- ? t.rich('companionsOne', { brand, first: companions[0], b })
- : t.rich('companionsTwo', { brand, first: companions[0], second: companions[1], b })}
- </>
- )}
+ </Fragment>
+ ))}
</p>
<p className="mt-1 text-xs text-muted-foreground">
{t('basis', {
- range,
- answers: current.answers,
- mentions: current.mentions,
+ range: windowRange(overview.window, locale),
+ answers: overview.current.answers,
+ mentions: overview.current.mentions,
})}
</p>
</section>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
index 05ed0f0af..ff28b4878 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
@@ -4,7 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
import { DEFAULT_MENTIONS_FILTERS } from '@/lib/mentions-filters';
-import type { MentionRow, MentionsList } from '@/lib/mentions-list';
+import { DEFAULT_MENTIONS_TABLE, type MentionRow, type MentionsList } from '@/lib/mentions-list';
import type { Competitor } from '@/types';
import { MentionsListTab } from './_mentions-tab';
@@ -102,6 +102,9 @@ async function settle() {
});
}
+// Export CSV itself is covered in _header-actions.test.tsx; the table hands it the ticked rows.
+const exporter = { ready: true, busy: null, exportCsv: vi.fn(), copySummary: vi.fn() };
+
const tab = (props: Partial<React.ComponentProps<typeof MentionsListTab>> = {}) => (
<MentionsListTab
brandId="b1"
@@ -109,6 +112,7 @@ const tab = (props: Partial<React.ComponentProps<typeof MentionsListTab>> = {})
competitors={competitors}
brandDomains={['acme.com']}
showCountry={false}
+ exporter={exporter}
{...props}
/>
);
@@ -128,6 +132,7 @@ afterEach(() => {
getMentionResponse.mockReset();
sendMentionsToActionCenter.mockReset();
overrideMentionSentiment.mockReset();
+ exporter.exportCsv.mockReset();
canManage = true;
suggestContentForPrompt.mockReset();
push.mockReset();
@@ -271,6 +276,24 @@ describe('MentionsListTab', () => {
expect(container.textContent).not.toContain('selected');
});
+ it("exports the ticked answers under the table's controls", async () => {
+ window.history.replaceState(null, '', '/dashboard/mentions?tab=mentions&sentiment=negative');
+ listMentions.mockResolvedValue(list());
+ render(tab());
+ await settle();
+ const boxes = [...container.querySelectorAll('button[role="checkbox"]')] as HTMLElement[];
+ act(() => boxes[2].click());
+
+ const exportButton = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Export',
+ ) as HTMLElement;
+ act(() => exportButton.click());
+ expect(exporter.exportCsv).toHaveBeenCalledWith(
+ { ...DEFAULT_MENTIONS_TABLE, sentiment: 'negative' },
+ { total: 2, prompts: 1, rows: [expect.objectContaining({ id: 'r2' })] },
+ );
+ });
+
it('sends one answer, and suggests content for its prompt, from the drawer', async () => {
listMentions.mockResolvedValue(list());
getMentionResponse.mockResolvedValue({ response: 'Acme Coffee.', citations: [] });
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
index 0ac83377c..8fc4bd8f7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
@@ -3,7 +3,7 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { TablePager, usePagination } from '@/components/table-pager';
-import { Send } from 'lucide-react';
+import { Download, Send } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
@@ -29,6 +29,7 @@ import type { MentionNames } from './_mention-parts';
import { MentionsTable } from './_mentions-table';
import { ResponseDrawer } from './_response-drawer';
import { useMentionActions } from './_use-mention-actions';
+import type { useMentionsExport } from './_use-mentions-export';
/** Typing in the search box reads once it pauses, not on every key. */
const READ_DELAY_MS = 250;
@@ -53,7 +54,7 @@ function Message({ children }: { children: React.ReactNode }) {
* a time, under the page's filters and the table's own (sentiment, a
* competitor named in the same answer, grouping, sort), which live in the
* URL too. A row opens the response drawer; ticked rows go to the Action
- * Center together.
+ * Center together, or into a CSV.
*/
export function MentionsListTab({
brandId,
@@ -61,15 +62,18 @@ export function MentionsListTab({
competitors,
brandDomains,
showCountry,
+ exporter,
}: {
brandId: string;
filters: MentionsFilters;
competitors: Competitor[];
brandDomains: string[];
showCountry: boolean;
+ exporter: ReturnType<typeof useMentionsExport>;
}) {
const t = useTranslations('mentions.table');
const tActions = useTranslations('mentions.actions');
+ const tExport = useTranslations('mentions.export');
const tSentiment = useTranslations('mentions.overview.sentiment');
const query = useMemo(() => mentionsQuery(filters), [filters]);
@@ -165,6 +169,14 @@ export function MentionsListTab({
const sendSelected = async () => {
if (await actions.send(selectedRows)) setSelected(new Set());
};
+ const exportSelected = () => {
+ if (loaded?.status !== 'ok' || !loaded.list) return;
+ void exporter.exportCsv(table, {
+ total: loaded.list.total,
+ prompts: loaded.list.prompts,
+ rows: selectedRows,
+ });
+ };
// A new page starts at its first row: the table scrolls inside its own box.
const tableBox = useRef<HTMLDivElement>(null);
@@ -296,6 +308,15 @@ export function MentionsListTab({
<Send className="h-3.5 w-3.5" />
{tActions('sendToActionCenter')}
</Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={exportSelected}
+ disabled={exporter.busy !== null}
+ >
+ <Download className="h-3.5 w-3.5" />
+ {tExport('exportSelected')}
+ </Button>
<Button variant="ghost" size="sm" onClick={() => setSelected(new Set())}>
{tActions('clearSelection')}
</Button>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mentions-export.ts b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mentions-export.ts
new file mode 100644
index 000000000..05acd28ec
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mentions-export.ts
@@ -0,0 +1,265 @@
+'use client';
+
+import { useMemo, useState } from 'react';
+import { useLocale, useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { exportMentions, getMentionsOverview } from '@/lib/actions/mentions';
+import {
+ mentionsCsv,
+ mentionsExportFileName,
+ utcMinute,
+ type ExportFact,
+} from '@/lib/mentions-export';
+import { mentionsQuery, type MentionsFilters } from '@/lib/mentions-filters';
+import { mentionPlatformLabel, wholeNet } from '@/lib/mentions-headline';
+import { NO_COMPETITOR, type MentionsList, type MentionsTableState } from '@/lib/mentions-list';
+import {
+ isLowSample,
+ LOW_SAMPLE_MENTIONS,
+ mentionRate,
+ relativeChange,
+ sentimentSplit,
+ type MentionsOverview,
+} from '@/lib/mentions-overview';
+import { numberFormat } from '@/lib/number-format';
+import { regionLabel } from '@/lib/region';
+import type { Competitor, Topic } from '@/types';
+import { signedValue, upIsGood } from '../insights/kpi-format';
+import { headlineSentences, windowRange } from './_headline';
+
+// Written out so Excel reads the CSV as UTF-8 and keeps Turkish characters.
+const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
+
+/** Saves a file the browser built, as the Action Center's export does. */
+function save(blob: Blob, fileName: string) {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = fileName;
+ link.click();
+ // Revoked once the download has started; at once, some browsers drop it.
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
+/**
+ * Puts text on the clipboard that is still being read. Safari lets a page
+ * write the clipboard only within the click, so the text goes over as a
+ * promise where the browser takes one; elsewhere it is written once ready.
+ */
+async function copyText(text: Promise<string>) {
+ // Missing outside a secure context (e.g. a self-hosted install over http).
+ if (!navigator.clipboard) throw new Error('Clipboard unavailable');
+ if (typeof ClipboardItem !== 'undefined' && navigator.clipboard.write) {
+ try {
+ const blob = text.then((s) => new Blob([s], { type: 'text/plain' }));
+ await navigator.clipboard.write([new ClipboardItem({ 'text/plain': blob })]);
+ return;
+ } catch {
+ // A browser that doesn't take a promise: write the text itself below.
+ }
+ }
+ await navigator.clipboard.writeText(await text);
+}
+
+/**
+ * Export CSV and Copy summary for the Mentions & Sentiment page (MS-13).
+ * Both read what they need when clicked, under the page's filters, and say
+ * which filters and how many responses and mentions they rest on (spec §16).
+ */
+export function useMentionsExport({
+ brandId,
+ brand,
+ slug,
+ filters,
+ topics,
+ competitors,
+}: {
+ brandId: string;
+ brand: string;
+ slug: string;
+ filters: MentionsFilters;
+ topics: Topic[];
+ competitors: Competitor[];
+}) {
+ const t = useTranslations('mentions.export');
+ const tMentions = useTranslations('mentions');
+ const tFilters = useTranslations('mentions.filters');
+ const tTable = useTranslations('mentions.table');
+ const tSentiment = useTranslations('mentions.overview.sentiment');
+ const tHeadline = useTranslations('mentions.overview.headline');
+ const tKpi = useTranslations('mentions.overview.kpi');
+ const locale = useLocale();
+ const f = numberFormat(locale);
+ const query = useMemo(() => mentionsQuery(filters), [filters]);
+ const [busy, setBusy] = useState<'csv' | 'copy' | null>(null);
+
+ // The page's filters, an "All …" value for each one left open.
+ const filterValues = () => {
+ const topic = topics.find((x) => x.id === filters.topic)?.name ?? filters.topic;
+ return {
+ platform: filters.platform
+ ? mentionPlatformLabel(filters.platform)
+ : tFilters('allPlatforms'),
+ country: filters.region ? regionLabel(filters.region) : tFilters('allCountries'),
+ topic: filters.topic ? topic : tFilters('allTopics'),
+ search: filters.q.trim(),
+ };
+ };
+
+ const period = (w: MentionsOverview['window']) =>
+ w.source === 'answers'
+ ? t('facts.periodMoments', { from: utcMinute(w.from), to: utcMinute(w.to) })
+ : t('facts.periodDays', { from: w.dayFrom, to: w.dayTo, days: w.days });
+
+ /**
+ * Saves the mentions as CSV: every one under the filters (and, from the
+ * Mentions tab, the table's), or the rows ticked in the table.
+ */
+ const exportCsv = async (
+ table: MentionsTableState,
+ selection?: Pick<MentionsList, 'total' | 'prompts' | 'rows'>,
+ ) => {
+ if (!query || busy) return;
+ setBusy('csv');
+ try {
+ const [overview, list] = await Promise.all([
+ getMentionsOverview(brandId, query),
+ selection ?? exportMentions(brandId, query, table),
+ ]);
+ if (!overview || !list) throw new Error('Mentions are unavailable');
+ if (list.rows.length === 0) {
+ toast.info(t('nothing'));
+ return;
+ }
+
+ const shown = { shown: f.number(list.rows.length), total: f.number(list.total) };
+ const capped = !selection && list.rows.length < list.total;
+ const values = filterValues();
+ const competitor =
+ table.competitor === NO_COMPETITOR
+ ? tTable('noCompetitor')
+ : (competitors.find((c) => c.id === table.competitor)?.name ?? table.competitor);
+ const facts: ExportFact[] = [
+ { label: tMentions('title'), value: brand },
+ { label: t('facts.period'), value: period(overview.window) },
+ { label: tFilters('platform'), value: values.platform },
+ { label: tFilters('country'), value: values.country },
+ { label: tFilters('topic'), value: values.topic },
+ ...(values.search ? [{ label: tFilters('search'), value: values.search }] : []),
+ ...(table.sentiment
+ ? [{ label: tTable('sentiment'), value: tSentiment(table.sentiment) }]
+ : []),
+ ...(table.competitor ? [{ label: tTable('coMentioned'), value: competitor }] : []),
+ { label: t('facts.responses'), value: overview.current.answers },
+ { label: t('facts.mentions'), value: list.total },
+ { label: t('facts.prompts'), value: list.prompts },
+ { label: t('facts.inFile'), value: list.rows.length },
+ ...(capped ? [{ label: t('facts.note'), value: t('facts.capped', shown) }] : []),
+ { label: t('facts.exported'), value: utcMinute(new Date()) },
+ ];
+ save(
+ new Blob([BYTE_ORDER_MARK, mentionsCsv(facts, list.rows)], {
+ type: 'text/csv;charset=utf-8;',
+ }),
+ mentionsExportFileName(slug),
+ );
+ if (capped) toast.warning(t('capped', shown));
+ } catch {
+ toast.error(t('exportFailed'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ /** The Overview's figures as text: the summary line, the KPIs with their n, and the filters. */
+ const summaryText = (overview: MentionsOverview): string => {
+ const { current: cur, previous: prev } = overview;
+ const plain = (key: string, values: Record<string, string | number>) =>
+ tHeadline.markup(key, { ...values, b: (chunks) => chunks, tone: (chunks) => chunks });
+ const line = (label: string, value: string, change?: string) =>
+ change
+ ? t('summary.kpiChange', { label, value, change })
+ : t('summary.kpi', { label, value });
+
+ const values = filterValues();
+ const change = relativeChange(cur.mentions, prev.mentions);
+ const total = upIsGood(change === null ? null : Math.round(change), { percent: true, locale });
+ const rate = mentionRate(cur);
+ const net = wholeNet(cur);
+ const split = sentimentSplit(cur);
+
+ return [
+ t('summary.title', { brand }),
+ [
+ values.platform,
+ values.country,
+ values.topic,
+ ...(values.search ? [t('summary.search', { q: values.search })] : []),
+ ].join(' · '),
+ headlineSentences(overview, brand, locale, tHeadline)
+ .map((s) => plain(s.key, s.values))
+ .join(' '),
+ line(tKpi('totalMentions'), f.number(cur.mentions), total?.text),
+ line(
+ tKpi('mentionRate'),
+ rate === null
+ ? '—'
+ : cur.answers < LOW_SAMPLE_MENTIONS
+ ? `${f.percent(rate, 1)} · ${tKpi('lowSample', { count: cur.answers })}`
+ : `${f.percent(rate, 1)} ${tKpi('mentionRateSub', { count: f.number(cur.answers) })}`,
+ ),
+ line(
+ tKpi('promptsWithMentions'),
+ `${f.number(cur.promptsWithMentions)} ${tKpi('promptsWithMentionsSub', {
+ count: f.number(cur.prompts),
+ })}`,
+ ),
+ line(
+ tKpi('netSentiment'),
+ net === null || !split
+ ? '—'
+ : isLowSample(cur)
+ ? `${signedValue(net, locale)} · ${tKpi('lowSample', { count: cur.mentions })}`
+ : t('summary.net', {
+ net: signedValue(net, locale),
+ split: tKpi('splitLabel', {
+ positive: f.percent(split.positive, 0),
+ neutral: f.percent(split.neutral, 0),
+ negative: f.percent(split.negative, 0),
+ }),
+ count: cur.mentions,
+ }),
+ ),
+ tHeadline('basis', {
+ range: windowRange(overview.window, locale),
+ answers: cur.answers,
+ mentions: cur.mentions,
+ }),
+ ].join('\n');
+ };
+
+ /** Copies the Overview's summary under the page's filters. */
+ const copySummary = async () => {
+ if (!query || busy) return;
+ setBusy('copy');
+ const text = getMentionsOverview(brandId, query).then((overview) => {
+ if (!overview) throw new Error('Mentions are unavailable');
+ return summaryText(overview);
+ });
+ try {
+ await copyText(text);
+ toast.success(t('copied'));
+ } catch {
+ // A failed read can be tried again; a clipboard the browser refused needs the reader.
+ const read = await text.then(
+ () => true,
+ () => false,
+ );
+ toast.error(read ? t('copyBlocked') : t('copyFailed'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ return { ready: query !== null, busy, exportCsv, copySummary };
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx
index 52eb61799..1a863b52c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx
@@ -20,16 +20,19 @@ import { writeUrlParams } from '@/lib/url-state';
import { useBrandStore } from '@/stores/use-brand-store';
import type { Competitor, Topic } from '@/types';
import { MentionsFilterBar } from './_filter-bar';
+import { MentionsHeaderActions } from './_header-actions';
import { MentionsListTab } from './_mentions-tab';
import { MentionsOverviewTab } from './_overview';
+import { useMentionsExport } from './_use-mentions-export';
/**
* Mentions & Sentiment (MS-05): where AI mentions the brand, how it describes
* it, and what to do about it — built from the answers tracking already
* stores, so opening the page or changing a filter never calls an LLM.
*
- * Top-down as the spec orders it: the tabs, then the filters every tab
- * shares, then the tab's content. Tab and filters live in the URL.
+ * Top-down as the spec orders it: the header's Copy summary, Export CSV and
+ * Reports, the tabs, then the filters every tab shares, then the tab's
+ * content. Tab and filters live in the URL.
*/
export default function MentionsPage() {
const t = useTranslations('mentions');
@@ -83,6 +86,15 @@ export default function MentionsPage() {
};
}, [activeBrandId]);
+ const exporter = useMentionsExport({
+ brandId: activeBrandId ?? '',
+ brand: brandName,
+ slug: activeBrand?.slug ?? '',
+ filters,
+ topics,
+ competitors,
+ });
+
if (!activeBrandId) {
return (
<div className="flex min-h-[400px] items-center justify-center">
@@ -93,9 +105,12 @@ export default function MentionsPage() {
return (
<div className="space-y-6">
- <div>
- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
- <p className="text-sm text-muted-foreground">{t('description')}</p>
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-sm text-muted-foreground">{t('description')}</p>
+ </div>
+ {urlRead && <MentionsHeaderActions tab={tab} exporter={exporter} />}
</div>
<Tabs value={tab} onValueChange={(v) => setTab(v as MentionsTab)}>
@@ -130,6 +145,7 @@ export default function MentionsPage() {
competitors={competitors}
brandDomains={brandDomains}
showCountry={regions.length > 1}
+ exporter={exporter}
/>
)}
</TabsContent>
diff --git a/web/src/lib/actions/mentions.test.ts b/web/src/lib/actions/mentions.test.ts
index 82f5b6705..206b75b46 100644
--- a/web/src/lib/actions/mentions.test.ts
+++ b/web/src/lib/actions/mentions.test.ts
@@ -29,6 +29,7 @@ vi.mock('@/lib/supabase/server', () => ({
vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
import {
+ exportMentions,
getMentionResponse,
getMentionsOverview,
listMentions,
@@ -38,7 +39,8 @@ import {
import { DEFAULT_MENTIONS_TABLE } from '@/lib/mentions-list';
beforeEach(() => {
- rpc.mockClear();
+ rpc.mockReset();
+ rpc.mockImplementation(async () => result);
from.mockClear();
tableCalls.length = 0;
result = { data: null, error: null };
@@ -185,6 +187,71 @@ describe('listMentions', () => {
});
});
+describe('exportMentions', () => {
+ // A page of the list for an offset: `total` mentions, ids m0…, 100 a page; with
+ // `overlap`, the pages after the first start that many rows early.
+ const pages = (total: number, overlap = 0) =>
+ rpc.mockImplementation((async (_fn: string, args: { p_offset: number }) => {
+ const start = Math.max(0, args.p_offset - (args.p_offset > 0 ? overlap : 0));
+ const ids = Array.from({ length: Math.max(0, Math.min(100, total - start)) }, (_, i) => i);
+ return {
+ data: {
+ total,
+ prompts: 3,
+ rows: ids.map((i) => ({ id: `m${start + i}`, response: 'Acme Coffee is good.' })),
+ },
+ error: null,
+ };
+ }) as never);
+
+ it('reads every page under the filters, ungrouped, and cuts each answer to its excerpt', async () => {
+ pages(250);
+ tableResult = { data: { name: 'Acme Coffee', brand_domains: [] }, error: null };
+ const list = await exportMentions(
+ 'b1',
+ { from: '2026-10-10T00:00:00.000Z' },
+ { ...DEFAULT_MENTIONS_TABLE, sentiment: 'negative', group: 'prompt' },
+ );
+ expect(rpc.mock.calls.map((c) => (c as unknown[])[1])).toEqual(
+ [0, 100, 200].map((offset) =>
+ expect.objectContaining({
+ p_sentiment: 'negative',
+ p_group: undefined,
+ p_limit: 100,
+ p_offset: offset,
+ }),
+ ),
+ );
+ expect(list).toMatchObject({ total: 250, prompts: 3, brandTerms: ['Acme Coffee'] });
+ expect(list?.rows).toHaveLength(250);
+ expect(list?.rows[249]).toMatchObject({ id: 'm249', excerpt: 'Acme Coffee is good.' });
+ expect(list?.rows[0]).not.toHaveProperty('response');
+ });
+
+ it('stops at 5,000 mentions, and keeps each answer once when the pages shift', async () => {
+ pages(12_345, 1);
+ const list = await exportMentions('b1', { from: 'f' }, DEFAULT_MENTIONS_TABLE);
+ expect(rpc).toHaveBeenCalledTimes(50);
+ expect(list?.total).toBe(12_345);
+ // An answer stored after the first page shifts the rest by one: its repeat is dropped.
+ expect(list?.rows).toHaveLength(4999);
+ expect(new Set(list?.rows.map((r) => r.id)).size).toBe(list?.rows.length);
+ });
+
+ it('is null before the migration has run, and throws when a later page fails', async () => {
+ result = { data: null, error: { code: 'PGRST202', message: 'not found' } };
+ await expect(exportMentions('b1', { from: 'f' }, DEFAULT_MENTIONS_TABLE)).resolves.toBeNull();
+
+ rpc.mockImplementation((async (_fn: string, args: { p_offset: number }) =>
+ args.p_offset === 0
+ ? { data: { total: 150, prompts: 1, rows: [] }, error: null }
+ : { data: null, error: { code: '57014', message: 'statement timeout' } }) as never);
+ await expect(exportMentions('b1', { from: 'f' }, DEFAULT_MENTIONS_TABLE)).rejects.toThrow(
+ 'statement timeout',
+ );
+ });
+});
+
describe('getMentionResponse', () => {
it("reads the answer's text, citations and latest correction within the brand", async () => {
tableResults.prompt_results = {
diff --git a/web/src/lib/actions/mentions.ts b/web/src/lib/actions/mentions.ts
index fd490f874..19ea4622b 100644
--- a/web/src/lib/actions/mentions.ts
+++ b/web/src/lib/actions/mentions.ts
@@ -3,6 +3,7 @@
import { API_BASE_URL } from '@/config/api';
import { createClient } from '@/lib/supabase/server';
import { mentionExcerpt } from '@/lib/mention-match';
+import { MENTIONS_EXPORT_CAP } from '@/lib/mentions-export';
import type { MentionsQuery } from '@/lib/mentions-filters';
import {
MENTIONS_PAGE_SIZE,
@@ -59,37 +60,108 @@ export async function listMentions(
page: number,
): Promise<MentionsList | null> {
const supabase = await createClient();
- const [list, brand] = await Promise.all([
- supabase.rpc('mentions_list', {
- p_brand_id: brandId,
- p_date_from: query.from,
- p_date_to: query.to,
- p_platform: query.platform,
- p_region: query.region,
- p_topic_id: query.topicId,
- p_search: query.search,
- p_sentiment: table.sentiment || undefined,
- p_competitor_id: table.competitor || undefined,
- p_sort: table.sort,
- p_group: table.group || undefined,
- p_limit: MENTIONS_PAGE_SIZE,
- p_offset: Math.max(0, page) * MENTIONS_PAGE_SIZE,
- }),
- supabase.from('brands').select('name, brand_domains(domain)').eq('id', brandId).maybeSingle(),
+ const [list, brandTerms] = await Promise.all([
+ readMentionsPage(supabase, brandId, query, table, page),
+ readBrandTerms(supabase, brandId),
]);
if (list.error?.code === 'PGRST202') return null;
if (list.error) throw new Error(list.error.message);
- // The names tracking matches the brand by: its name and its domains.
- const row = brand.data as { name?: string; brand_domains?: { domain?: string }[] } | null;
- const brandTerms = [
- row?.name ?? '',
- ...(row?.brand_domains ?? []).map((d) => d.domain ?? ''),
- ].filter(Boolean);
const parsed = parseMentionsList(list.data, (response) => mentionExcerpt(response, brandTerms));
return parsed ? { ...parsed, brandTerms } : null;
}
+/** The table's pages Export CSV reads at once. */
+const EXPORT_PAGES_AT_ONCE = 5;
+
+/**
+ * Every mention for Export CSV (MS-13): the table's pages under the same
+ * filters, read a few at a time up to MENTIONS_EXPORT_CAP, in the table's sort
+ * and ungrouped, each cut to its excerpt as listMentions does. `total` is
+ * every match, so the caller can tell when the file holds fewer.
+ *
+ * Null as getMentionsOverview: no function yet (PGRST202), or no access.
+ */
+export async function exportMentions(
+ brandId: string,
+ query: MentionsQuery,
+ table: MentionsTableState,
+): Promise<MentionsList | null> {
+ const supabase = await createClient();
+ const flat: MentionsTableState = { ...table, group: '' };
+ const [first, brandTerms] = await Promise.all([
+ readMentionsPage(supabase, brandId, query, flat, 0),
+ readBrandTerms(supabase, brandId),
+ ]);
+ if (first.error?.code === 'PGRST202') return null;
+ if (first.error) throw new Error(first.error.message);
+
+ const excerptOf = (response: string) => mentionExcerpt(response, brandTerms);
+ const head = parseMentionsList(first.data, excerptOf);
+ if (!head) return null;
+
+ const pages = Math.ceil(Math.min(head.total, MENTIONS_EXPORT_CAP) / MENTIONS_PAGE_SIZE);
+ const rows = [...head.rows];
+ for (let next = 1; next < pages; next += EXPORT_PAGES_AT_ONCE) {
+ const batch = await Promise.all(
+ Array.from({ length: Math.min(EXPORT_PAGES_AT_ONCE, pages - next) }, (_, i) =>
+ readMentionsPage(supabase, brandId, query, flat, next + i),
+ ),
+ );
+ for (const page of batch) {
+ if (page.error) throw new Error(page.error.message);
+ rows.push(...(parseMentionsList(page.data, excerptOf)?.rows ?? []));
+ }
+ }
+ // An answer stored mid-export shifts the pages by a row: keep each answer once.
+ const seen = new Set<string>();
+ const unique = rows.filter((row) => {
+ if (seen.has(row.id)) return false;
+ seen.add(row.id);
+ return true;
+ });
+ return { total: head.total, prompts: head.prompts, rows: unique, brandTerms };
+}
+
+type Supabase = Awaited<ReturnType<typeof createClient>>;
+
+function readMentionsPage(
+ supabase: Supabase,
+ brandId: string,
+ query: MentionsQuery,
+ table: MentionsTableState,
+ page: number,
+) {
+ return supabase.rpc('mentions_list', {
+ p_brand_id: brandId,
+ p_date_from: query.from,
+ p_date_to: query.to,
+ p_platform: query.platform,
+ p_region: query.region,
+ p_topic_id: query.topicId,
+ p_search: query.search,
+ p_sentiment: table.sentiment || undefined,
+ p_competitor_id: table.competitor || undefined,
+ p_sort: table.sort,
+ p_group: table.group || undefined,
+ p_limit: MENTIONS_PAGE_SIZE,
+ p_offset: Math.max(0, page) * MENTIONS_PAGE_SIZE,
+ });
+}
+
+/** The names tracking matches the brand by: its name and its domains. */
+async function readBrandTerms(supabase: Supabase, brandId: string): Promise<string[]> {
+ const { data } = await supabase
+ .from('brands')
+ .select('name, brand_domains(domain)')
+ .eq('id', brandId)
+ .maybeSingle();
+ const row = data as { name?: string; brand_domains?: { domain?: string }[] } | null;
+ return [row?.name ?? '', ...(row?.brand_domains ?? []).map((d) => d.domain ?? '')].filter(
+ Boolean,
+ );
+}
+
/**
* One answer's stored text and citations, and its latest sentiment
* correction, for the response drawer. Read as the caller, so row-level
diff --git a/web/src/lib/csv.test.ts b/web/src/lib/csv.test.ts
index be3e564b4..8e928baf4 100644
--- a/web/src/lib/csv.test.ts
+++ b/web/src/lib/csv.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
-import { toCsv } from './csv.js';
+import { csvLine, toCsv } from './csv.js';
test('plain values pass through unquoted', () => {
const result = toCsv([{ name: 'hello', value: 'world' }], ['name', 'value']);
@@ -81,3 +81,7 @@ test('negative numbers remain untouched as numeric values', () => {
const result = toCsv([{ score: -3.2, rank: -5 }], ['score', 'rank']);
expect(result).toBe('score,rank\n-3.2,-5');
});
+
+test('csvLine escapes each value as a cell', () => {
+ expect(csvLine(['Search', 'a, "b"', '=1+1', null])).toBe(`Search,"a, ""b""",'=1+1,`);
+});
diff --git a/web/src/lib/csv.ts b/web/src/lib/csv.ts
index 81979956c..653ee23e6 100644
--- a/web/src/lib/csv.ts
+++ b/web/src/lib/csv.ts
@@ -12,9 +12,14 @@ function escape(value: unknown): string {
return s;
}
+/** One line of values, each escaped as toCsv escapes a cell. */
+export function csvLine(values: unknown[]): string {
+ return values.map(escape).join(',');
+}
+
export function toCsv(rows: Record<string, unknown>[], headers: string[]): string {
const headerLine = headers.join(',');
- const dataLines = rows.map((row) => headers.map((header) => escape(row[header])).join(','));
+ const dataLines = rows.map((row) => csvLine(headers.map((header) => row[header])));
return [headerLine, ...dataLines].join('\n');
}
diff --git a/web/src/lib/mentions-export.test.ts b/web/src/lib/mentions-export.test.ts
new file mode 100644
index 000000000..bba7dcc9a
--- /dev/null
+++ b/web/src/lib/mentions-export.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest';
+import type { MentionRow } from './mentions-list';
+import { mentionsCsv, mentionsExportFileName, utcMinute } from './mentions-export';
+
+const row = (over: Partial<MentionRow> = {}): MentionRow => ({
+ id: 'r1',
+ createdAt: '2026-10-16T11:28:06Z',
+ promptId: 'p1',
+ promptText: 'Best espresso beans?',
+ topicId: 't1',
+ topicName: 'Beans',
+ platform: 'gemini-web',
+ model: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ occurrences: 2,
+ position: 2,
+ brandsNamed: 4,
+ coMentioned: [
+ { competitorId: 'c1', name: 'Crema Club', position: 1 },
+ { competitorId: 'c2', name: 'Origin Box', position: 3 },
+ ],
+ excerpt: 'Try Crema Club first. Acme Coffee is pricier, "but fresh".',
+ groupKey: null,
+ groupCount: null,
+ ...over,
+});
+
+describe('mentionsCsv', () => {
+ it('writes the facts, a blank line, then a row per mention', () => {
+ const csv = mentionsCsv(
+ [
+ { label: 'Mentions & Sentiment', value: 'Acme Coffee' },
+ { label: 'Search', value: 'price, "deals"' },
+ { label: 'Mentions (n)', value: 107 },
+ ],
+ [
+ row(),
+ row({
+ id: 'r2',
+ topicName: null,
+ model: null,
+ region: null,
+ sentiment: null,
+ position: null,
+ brandsNamed: null,
+ coMentioned: [],
+ excerpt: '=SUM(A1) Acme Coffee',
+ }),
+ ],
+ );
+ expect(csv.split('\n')).toEqual([
+ 'Mentions & Sentiment,Acme Coffee',
+ 'Search,"price, ""deals"""',
+ 'Mentions (n),107',
+ '',
+ 'date_utc,prompt,topic,platform,model,country,sentiment,times_named,position,brands_named,co_mentioned,excerpt',
+ '2026-10-16 11:28,Best espresso beans?,Beans,Gemini,gemini-2.5-flash,DE,negative,2,2,4,' +
+ 'Crema Club; Origin Box,"Try Crema Club first. Acme Coffee is pricier, ""but fresh""."',
+ // A formula-looking excerpt gets a leading ' so a spreadsheet won't run it.
+ "2026-10-16 11:28,Best espresso beans?,,Gemini,,,,2,,,,'=SUM(A1) Acme Coffee",
+ ]);
+ });
+});
+
+describe('mentionsExportFileName', () => {
+ it("names the file after the brand and the day, as the other pages' exports", () => {
+ const day = new Date('2026-10-17T09:00:00Z');
+ expect(mentionsExportFileName('acme-coffee', day)).toBe(
+ 'ansvisor_acme-coffee_mentions_2026-10-17.csv',
+ );
+ expect(mentionsExportFileName('', day)).toBe('ansvisor_brand_mentions_2026-10-17.csv');
+ });
+});
+
+describe('utcMinute', () => {
+ it('states a moment to the minute in UTC, and nothing for an invalid one', () => {
+ expect(utcMinute('2026-10-16T11:28:06+03:00')).toBe('2026-10-16 08:28');
+ expect(utcMinute(new Date('2026-10-17T00:05:59Z'))).toBe('2026-10-17 00:05');
+ expect(utcMinute('')).toBe('');
+ });
+});
diff --git a/web/src/lib/mentions-export.ts b/web/src/lib/mentions-export.ts
new file mode 100644
index 000000000..dfcf378da
--- /dev/null
+++ b/web/src/lib/mentions-export.ts
@@ -0,0 +1,68 @@
+import { csvLine, toCsv } from '@/lib/csv';
+import { mentionPlatformLabel } from '@/lib/mentions-headline';
+import type { MentionRow } from '@/lib/mentions-list';
+
+/**
+ * Export CSV on the Mentions & Sentiment page (MS-13): the mentions under the
+ * page's filters, one row per answer naming the brand, under a few lines that
+ * say what the file holds (the filters and the n values, spec §16), so a file
+ * read later or elsewhere still says what it was taken over.
+ */
+
+/** The most mentions one file holds: 50 of the table's pages. */
+export const MENTIONS_EXPORT_CAP = 5000;
+
+/** A line above the rows: a label and its value, in the reader's language. */
+export interface ExportFact {
+ label: string;
+ value: string | number;
+}
+
+export const MENTION_EXPORT_HEADERS = [
+ 'date_utc',
+ 'prompt',
+ 'topic',
+ 'platform',
+ 'model',
+ 'country',
+ 'sentiment',
+ 'times_named',
+ 'position',
+ 'brands_named',
+ 'co_mentioned',
+ 'excerpt',
+];
+
+function exportRow(row: MentionRow): Record<string, string | number | null> {
+ return {
+ date_utc: utcMinute(row.createdAt),
+ prompt: row.promptText,
+ topic: row.topicName,
+ platform: mentionPlatformLabel(row.platform),
+ model: row.model,
+ country: row.region,
+ sentiment: row.sentiment,
+ times_named: row.occurrences,
+ position: row.position,
+ brands_named: row.brandsNamed,
+ co_mentioned: row.coMentioned.map((c) => c.name).join('; '),
+ excerpt: row.excerpt,
+ };
+}
+
+/** The file: the facts, a blank line, then the rows under their header. */
+export function mentionsCsv(facts: ExportFact[], rows: MentionRow[]): string {
+ const head = facts.map((fact) => csvLine([fact.label, fact.value]));
+ return [...head, '', toCsv(rows.map(exportRow), MENTION_EXPORT_HEADERS)].join('\n');
+}
+
+/** "ansvisor_acme-coffee_mentions_2026-10-17.csv", as the other pages name theirs. */
+export function mentionsExportFileName(slug: string, now = new Date()): string {
+ return `ansvisor_${slug || 'brand'}_mentions_${now.toISOString().slice(0, 10)}.csv`;
+}
+
+/** A moment as the file states it: "2026-10-17 09:12", in UTC. */
+export function utcMinute(value: string | Date): string {
+ const date = typeof value === 'string' ? new Date(value) : value;
+ return Number.isNaN(date.getTime()) ? '' : date.toISOString().slice(0, 16).replace('T', ' ');
+}