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(action-center): add affected items to the actions list CSV and copy toast (#1083)

Cihane7a41b6d5744
diff --git a/web/messages/en.json b/web/messages/en.json
index ccf6095be..c8a2a5a39 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -922,7 +922,7 @@
"copyAll": "Copy Data",
"csv": "Export CSV",
"excel": "Export Excel",
- "copied": "Action {ref} copied: {tasks, plural, one {# task} other {# tasks}}, {signals, plural, one {# signal} other {# signals}}",
+ "copied": "Action {ref} copied: {entity, select, prompts {{affected, plural, one {# prompt} other {# prompts}}, } pages {{affected, plural, one {# page} other {# pages}}, } other {}}{tasks, plural, one {# task} other {# tasks}}, {signals, plural, one {# signal} other {# signals}}",
"exportFailed": "Couldn't create the export.",
"preview": {
"copy": "Copy all",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.test.tsx
new file mode 100644
index 000000000..e56d0393d
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.test.tsx
@@ -0,0 +1,149 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Brand } from '@/types';
+import type { ActionItem } from '@/lib/actions/action-center';
+
+/**
+ * The actions list's Export CSV (AC-005): it reads what each listed action's
+ * Affected tab names, then downloads the list with it, as UTF-8 Excel reads.
+ */
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const brand: Brand = {
+ id: 'brand-id',
+ organizationId: 'organization-id',
+ name: 'Acme',
+ slug: 'acme',
+ industry: 'Technology',
+ region: 'US',
+ shoppingModeEnabled: false,
+ isActive: true,
+ domains: [],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+};
+
+const action: ActionItem = {
+ id: 'a1',
+ actionNo: 35,
+ category: 'recover',
+ kind: 'recover_lost_citations',
+ impact: 'high',
+ status: 'new',
+ payload: {},
+ kpiKeys: [],
+ assignee: null,
+ dueDate: null,
+ createdAt: '2026-10-16T09:05:31Z',
+ updatedAt: '2026-10-16T09:05:31Z',
+ taskTotal: 8,
+ taskCompleted: 0,
+ signalCount: 3,
+ priorityScore: 90,
+ priorityLevel: 'critical',
+ priorityReason: null,
+};
+
+const { getActionsAffected, saveBlob, toast } = vi.hoisted(() => ({
+ getActionsAffected: vi.fn(),
+ saveBlob: vi.fn(),
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('next-intl', () => ({
+ useTranslations: () => (key: string) => key,
+}));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (selector: (state: { getActiveBrand: () => Brand }) => unknown) =>
+ selector({ getActiveBrand: () => brand }),
+}));
+vi.mock('@/lib/actions/action-center', () => ({
+ getActions: vi.fn(async () => [action]),
+ getActionsAffected,
+}));
+vi.mock('@/lib/actions/team', () => ({ listMembers: vi.fn(async () => []) }));
+vi.mock('@/lib/download', () => ({ saveBlob }));
+vi.mock('sonner', () => ({ toast }));
+vi.mock('@/components/action-center/action-center-tabs', () => ({ ActionCenterTabs: () => null }));
+vi.mock('@/components/action-center/action-table', () => ({ ActionTable: () => null }));
+vi.mock('@/components/action-center/action-drawer', () => ({ ActionDrawer: () => null }));
+
+const { default: ActionCenterActionsPage } = await import('./page');
+
+let container: HTMLDivElement;
+let root: Root;
+
+const exportButton = () =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === 'exportCsv')!;
+
+async function render() {
+ await act(async () => root.render(<ActionCenterActionsPage />));
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+ getActionsAffected.mockReset();
+ saveBlob.mockReset();
+ toast.error.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('the actions list Export CSV', () => {
+ it("adds each action's affected count and names, in a file Excel reads as UTF-8", async () => {
+ getActionsAffected.mockResolvedValue({
+ a1: { count: 3, items: ['Best coffee subscription?', 'Coffee delivery'] },
+ });
+ await render();
+ await act(async () => exportButton().click());
+
+ expect(getActionsAffected).toHaveBeenCalledWith('brand-id', ['a1']);
+ const [blob, fileName] = saveBlob.mock.calls[0] as [Blob, string];
+ expect(fileName).toMatch(/^ansvisor_acme_actions_\d{4}-\d{2}-\d{2}\.csv$/);
+ const bytes = await new Promise<Uint8Array>((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));
+ reader.readAsArrayBuffer(blob);
+ });
+ expect([...bytes.slice(0, 3)]).toEqual([0xef, 0xbb, 0xbf]);
+ const [header, row] = new TextDecoder().decode(bytes.slice(3)).split('\n');
+ expect(header).toContain(',signal_count,affected_count,affected_items,created');
+ expect(row).toContain(',3,3,Best coffee subscription?; Coffee delivery,');
+ expect(exportButton().disabled).toBe(false);
+ });
+
+ it('says so when the affected items cannot be read, and downloads nothing', async () => {
+ getActionsAffected.mockRejectedValue(new Error('offline'));
+ await render();
+ await act(async () => exportButton().click());
+
+ expect(toast.error).toHaveBeenCalledWith('export.exportFailed');
+ expect(saveBlob).not.toHaveBeenCalled();
+ expect(exportButton().disabled).toBe(false);
+ });
+
+ it("holds the button while it reads, and drops the file once the brand's view is gone", async () => {
+ let answer: (value: unknown) => void = () => {};
+ getActionsAffected.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ await render();
+ await act(async () => exportButton().click());
+ expect(exportButton().disabled).toBe(true);
+
+ act(() => root.unmount());
+ await act(async () => answer({}));
+ expect(saveBlob).not.toHaveBeenCalled();
+ // Mounted again for afterEach's unmount.
+ root = createRoot(container);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx
index 49b552e9b..fb6df952c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx
@@ -1,13 +1,15 @@
'use client';
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
import {
AlertCircle,
ArrowUpDown,
CircleDot,
Download,
ListChecks,
+ Loader2,
Search,
Shield,
Sparkles,
@@ -16,7 +18,7 @@ import {
} from 'lucide-react';
import { useBrandStore } from '@/stores/use-brand-store';
import type { Brand } from '@/types';
-import { getActions, type ActionItem } from '@/lib/actions/action-center';
+import { getActions, getActionsAffected, type ActionItem } from '@/lib/actions/action-center';
import { listMembers, type TeamMember } from '@/lib/actions/team';
import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';
import {
@@ -51,21 +53,8 @@ import {
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
-import { toCsv } from '@/lib/csv';
-
-const ACTION_EXPORT_HEADERS = [
- 'number',
- 'priority_score',
- 'priority_level',
- 'title',
- 'category',
- 'status',
- 'assignee',
- 'due_date',
- 'tasks_done_total',
- 'signal_count',
- 'created',
-];
+import { BYTE_ORDER_MARK, actionListCsv } from '@/lib/action-center/export';
+import { saveBlob } from '@/lib/download';
const isOpen = (action: ActionItem) => OPEN_ACTION_STATUSES.includes(action.status);
@@ -128,6 +117,16 @@ function ActionsContent({ brand }: { brand: Brand }) {
const [assignee, setAssignee] = useState<string>('all');
const [sort, setSort] = useState<ActionSort>('priority');
const [search, setSearch] = useState('');
+ const [isExporting, setIsExporting] = useState(false);
+ // False once this brand's view is gone, so an export still reading doesn't
+ // download the previous brand's file after a switch.
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
const [focus, setFocus] = useState<CardFocus | null>(null);
// Filters, sort and search live in the URL (#896) so a refresh keeps them
@@ -248,36 +247,49 @@ function ActionsContent({ brand }: { brand: Brand }) {
});
}, [actions, topIds, focus, category, priority, status, assignee, search, sort, tTexts, t]);
- const handleExportCsv = useCallback(() => {
+ const handleExportCsv = useCallback(async () => {
if (visible.length === 0) return;
- const rows = visible.map((action) => ({
- number: action.actionNo,
- priority_score: action.priorityScore ?? '',
- priority_level: action.priorityLevel ? t(`priority.levels.${action.priorityLevel}`) : '',
- title: actionTexts(action, tTexts).title,
- category: tCategories(action.category),
- status: t(`status.${action.status}`),
- assignee: action.assignee?.fullName ?? '',
- due_date: action.dueDate ?? '',
- tasks_done_total: `${action.taskCompleted} / ${action.taskTotal}`,
- signal_count: action.signalCount,
- created: action.createdAt,
- }));
-
- const csv = toCsv(rows, ACTION_EXPORT_HEADERS);
- const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
+ setIsExporting(true);
+ let affected: Awaited<ReturnType<typeof getActionsAffected>>;
+ try {
+ // What each action's Affected tab lists (AC-005), read for the export only.
+ affected = await getActionsAffected(
+ brand.id,
+ visible.map((action) => action.id),
+ );
+ } catch {
+ if (mounted.current) toast.error(t('export.exportFailed'));
+ return;
+ } finally {
+ setIsExporting(false);
+ }
+ if (!mounted.current) return;
+
+ const csv = actionListCsv(
+ visible.map((action) => ({
+ number: action.actionNo,
+ priorityScore: action.priorityScore,
+ priorityLevel: action.priorityLevel ? t(`priority.levels.${action.priorityLevel}`) : '',
+ title: actionTexts(action, tTexts).title,
+ category: tCategories(action.category),
+ status: t(`status.${action.status}`),
+ assignee: action.assignee?.fullName ?? '',
+ dueDate: action.dueDate ?? '',
+ tasksDone: action.taskCompleted,
+ tasksTotal: action.taskTotal,
+ signalCount: action.signalCount,
+ affected: affected[action.id],
+ created: action.createdAt,
+ })),
+ );
const date = new Date().toISOString().slice(0, 10);
const slug = brand.slug ?? 'brand';
-
- link.href = url;
- link.download = `ansvisor_${slug}_actions_${date}.csv`;
- link.click();
-
- URL.revokeObjectURL(url);
- }, [brand.slug, visible, tTexts, tCategories, t]);
+ saveBlob(
+ new Blob([BYTE_ORDER_MARK, csv], { type: 'text/csv;charset=utf-8;' }),
+ `ansvisor_${slug}_actions_${date}.csv`,
+ );
+ }, [brand.id, brand.slug, visible, tTexts, tCategories, t]);
const categoryCounts = useMemo(() => {
const counts = new Map<ActionCategory, number>();
@@ -494,9 +506,13 @@ function ActionsContent({ brand }: { brand: Brand }) {
size="sm"
className="ml-auto gap-2 text-xs"
onClick={handleExportCsv}
- disabled={visible.length === 0}
+ disabled={visible.length === 0 || isExporting}
>
- <Download className="h-3.5 w-3.5" />
+ {isExporting ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Download className="h-3.5 w-3.5" />
+ )}
{common('exportCsv')}
</Button>
</div>
diff --git a/web/src/components/action-center/action-export-buttons.test.tsx b/web/src/components/action-center/action-export-buttons.test.tsx
index 450a3508b..6a8defa56 100644
--- a/web/src/components/action-center/action-export-buttons.test.tsx
+++ b/web/src/components/action-center/action-export-buttons.test.tsx
@@ -4,6 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../messages/en.json';
import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';
+import type { Affected } from '@/lib/action-center/affected';
const { toast, written } = vi.hoisted(() => ({
toast: { success: vi.fn(), error: vi.fn() },
@@ -214,6 +215,67 @@ describe('ActionExportButtons', () => {
expect(toast.success).toHaveBeenCalledWith('Action AC-52 copied: 1 task, 1 signal');
});
+ const affected = (over: Partial<Affected>): Affected => ({
+ prompts: [],
+ pages: [],
+ promptTotal: 0,
+ pageTotal: 0,
+ platforms: [],
+ lostPages: [],
+ competitors: [],
+ topics: [],
+ ...over,
+ });
+ const prompt = (text: string) => ({
+ id: null,
+ text,
+ platforms: [],
+ lostPages: [],
+ citedInstead: [],
+ leaders: [],
+ topics: [],
+ });
+
+ it('says how many prompts it copied, counting a group past the ones it names (AC-005)', async () => {
+ render(
+ <ActionExportButtons
+ action={action}
+ detail={detail}
+ affected={affected({
+ prompts: [prompt('Best coffee subscription?'), prompt('Coffee delivery')],
+ promptTotal: 7,
+ })}
+ />,
+ );
+ await act(async () => button('Copy Data').click());
+ await act(async () => copyButton().click());
+ expect(toast.success).toHaveBeenCalledWith('Action AC-52 copied: 7 prompts, 1 task, 1 signal');
+ });
+
+ it('counts the pages of an action about pages', async () => {
+ render(
+ <ActionExportButtons
+ action={action}
+ detail={detail}
+ affected={affected({
+ pages: [
+ {
+ url: 'https://acme.example/pricing',
+ sessions: 32,
+ before: 40,
+ platforms: [],
+ issues: [],
+ },
+ ],
+ pageTotal: 1,
+ })}
+ />,
+ );
+ await act(async () => button('Copy Data').click());
+ await act(async () => copyButton().click());
+ expect(toast.success).toHaveBeenCalledWith('Action AC-52 copied: 1 page, 1 task, 1 signal');
+ });
+
it('says so when neither way can copy', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsx
index e08ba091d..306cb4408 100644
--- a/web/src/components/action-center/action-export-buttons.tsx
+++ b/web/src/components/action-center/action-export-buttons.tsx
@@ -16,6 +16,7 @@ import {
taskText,
} from '@/lib/action-center/display';
import {
+ BYTE_ORDER_MARK,
actionCsv,
actionExportFileName,
actionMarkdown,
@@ -31,28 +32,15 @@ import { isKpiKey } from '@/lib/kpis/registry';
import { signalAffected, signalTexts, signalTypeLabel } from '@/lib/signals/display';
import { viewerTimeZone } from '@/lib/time-zone';
import { isSuperseded } from './signal-table';
-import { leaderText, type Affected } from '@/lib/action-center/affected';
+import { affectedCounts, leaderText, type Affected } from '@/lib/action-center/affected';
import type { ActionStory } from '@/lib/action-center/story';
import { platformName } from '@/lib/signals/names';
import { getPlatformName } from '@/lib/traffic-platforms';
import { formatCompactNumber } from '@/lib/format';
-
-// Written out so Excel reads the CSV as UTF-8 and keeps Turkish characters.
-const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
+import { saveBlob } from '@/lib/download';
const IMPROVE_STATES = ['not_mentioned', 'mentioned_late', 'not_cited', 'doing_well', 'no_runs'];
-/** Saves a file the browser built, as the actions list'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);
-}
-
/**
* Copy all, Export CSV and Export Excel for one action (AC-005): what every
* tab of the drawer shows, to take into a doc, a ticket or a spreadsheet.
@@ -311,13 +299,21 @@ export function ActionExportButtons({
}
};
- /** Copy Data: the whole action, every tab, shown to copy in one click. */
+ /**
+ * Copy Data: the whole action, every tab, shown to copy in one click. Once
+ * copied it says what went: "7 prompts, 6 tasks, 87 signals", or the pages
+ * for an action about pages.
+ */
const showData = (data: ActionExport) => {
+ const counts = affected ? affectedCounts(affected) : { prompts: 0, pages: 0 };
+ const entity = counts.prompts ? 'prompts' : counts.pages ? 'pages' : 'none';
setJustCopied(false);
setPreview({
text: actionMarkdown(data, tExport),
copied: tExport('copied', {
ref: data.ref,
+ entity,
+ affected: entity === 'pages' ? counts.pages : counts.prompts,
tasks: data.tasks.length,
signals: data.signals.length,
}),
@@ -353,7 +349,7 @@ export function ActionExportButtons({
};
const downloadCsv = (data: ActionExport) =>
- save(
+ saveBlob(
new Blob([BYTE_ORDER_MARK, actionCsv(data)], { type: 'text/csv;charset=utf-8;' }),
actionExportFileName(data, 'csv'),
);
diff --git a/web/src/lib/action-center/affected.test.ts b/web/src/lib/action-center/affected.test.ts
index 2bcdb9229..9003ba15b 100644
--- a/web/src/lib/action-center/affected.test.ts
+++ b/web/src/lib/action-center/affected.test.ts
@@ -1,6 +1,14 @@
import { describe, expect, it } from 'vitest';
import type { Signal } from '@/lib/signals/map';
-import { affectedChips, affectedCounts, affectedOf, affectedTotal, leaderText } from './affected';
+import {
+ affectedChips,
+ affectedCounts,
+ affectedOf,
+ affectedSummary,
+ affectedTotal,
+ leaderText,
+ type Affected,
+} from './affected';
const signal = (over: Partial<Signal> = {}): Signal =>
({
@@ -326,3 +334,55 @@ describe('affectedChips', () => {
expect(chips[0]).toEqual({ entity: 'signals', count: 1, tab: 'signals' });
});
});
+
+describe('affectedSummary', () => {
+ const affected = (over: Partial<Affected>): Affected => ({
+ prompts: [],
+ pages: [],
+ promptTotal: 0,
+ pageTotal: 0,
+ platforms: [],
+ lostPages: [],
+ competitors: [],
+ topics: [],
+ ...over,
+ });
+ const prompt = (text: string) => ({
+ id: null,
+ text,
+ platforms: [],
+ lostPages: [],
+ citedInstead: [],
+ leaders: [],
+ topics: [],
+ });
+
+ it("names the tab's rows, and counts a group past the 50 it names", () => {
+ expect(
+ affectedSummary(
+ affected({
+ prompts: [prompt('Best coffee subscription?')],
+ promptTotal: 62,
+ pages: [
+ {
+ url: 'https://acme.example/pricing',
+ sessions: null,
+ before: null,
+ platforms: [],
+ issues: [],
+ },
+ ],
+ pageTotal: 1,
+ competitors: ['Trade Coffee'],
+ }),
+ ),
+ ).toEqual({ count: 63, items: ['Best coffee subscription?', 'https://acme.example/pricing'] });
+ });
+
+ it('names the competitors and topics when there are no rows, as the tab lists them', () => {
+ expect(
+ affectedSummary(affected({ competitors: ['Trade Coffee'], topics: ['Subscriptions'] })),
+ ).toEqual({ count: 2, items: ['Trade Coffee', 'Subscriptions'] });
+ expect(affectedSummary(affected({}))).toEqual({ count: 0, items: [] });
+ });
+});
diff --git a/web/src/lib/action-center/affected.ts b/web/src/lib/action-center/affected.ts
index a04eec549..fc383aae4 100644
--- a/web/src/lib/action-center/affected.ts
+++ b/web/src/lib/action-center/affected.ts
@@ -355,6 +355,19 @@ export function affectedTotal(affected: Affected): number {
return rows > 0 ? rows : affected.competitors.length + affected.topics.length;
}
+/**
+ * The actions list's export of an action's affected items (AC-005): the
+ * Affected tab's count and the names it lists. A group cut at its first 50
+ * prompts names those and counts them all, as the tab does.
+ */
+export function affectedSummary(affected: Affected): { count: number; items: string[] } {
+ const rows = [...affected.prompts.map((p) => p.text), ...affected.pages.map((p) => p.url)];
+ return {
+ count: affectedTotal(affected),
+ items: rows.length > 0 ? rows : [...affected.competitors, ...affected.topics],
+ };
+}
+
type Translator = (key: string, values?: Record<string, string | number>) => string;
/** "#1", or "—" when not named. */
diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.ts
index f37dec44c..c815a63f3 100644
--- a/web/src/lib/action-center/export.test.ts
+++ b/web/src/lib/action-center/export.test.ts
@@ -4,7 +4,9 @@ import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';
import type { Signal } from '@/lib/signals/map';
import {
ACTION_CSV_HEADERS,
+ ACTION_LIST_CSV_HEADERS,
actionCsv,
+ actionListCsv,
actionExportFileName,
actionMarkdown,
actionWorkbook,
@@ -253,6 +255,47 @@ describe('actionCsv', () => {
});
});
+describe('actionListCsv', () => {
+ const listRow = {
+ number: 52,
+ priorityScore: 84,
+ priorityLevel: 'High',
+ title: 'Recover lost citations on 3 prompts',
+ category: 'Recover',
+ status: 'New',
+ assignee: '',
+ dueDate: '',
+ tasksDone: 1,
+ tasksTotal: 6,
+ signalCount: 3,
+ created: '2026-10-15T00:00:00Z',
+ };
+
+ it("adds each action's affected count and names to the list's columns (AC-005)", () => {
+ const [header, row] = actionListCsv([
+ {
+ ...listRow,
+ affected: { count: 7, items: ['Best coffee subscription?', 'Coffee, delivered'] },
+ },
+ ]).split('\n');
+ expect(header).toBe(ACTION_LIST_CSV_HEADERS.join(','));
+ expect(header).toContain('priority_score,priority_level,');
+ expect(header).toContain(',signal_count,affected_count,affected_items,created');
+ expect(row).toBe(
+ '52,84,High,Recover lost citations on 3 prompts,Recover,New,,,1 / 6,3,7,"Best coffee subscription?; Coffee, delivered",2026-10-15T00:00:00Z',
+ );
+ });
+
+ it('writes none for an action whose affected items were not read, and no score before one', () => {
+ const [, row] = actionListCsv([{ ...listRow, priorityScore: null, priorityLevel: '' }]).split(
+ '\n',
+ );
+ expect(row).toBe(
+ '52,,,Recover lost citations on 3 prompts,Recover,New,,,1 / 6,3,0,,2026-10-15T00:00:00Z',
+ );
+ });
+});
+
describe('actionWorkbook', () => {
it('gives the action, its affected items, tasks, signals and history a sheet each', () => {
const sheets = actionWorkbook(exported, label);
diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.ts
index 3e333c8a4..741d4b2ff 100644
--- a/web/src/lib/action-center/export.ts
+++ b/web/src/lib/action-center/export.ts
@@ -408,6 +408,70 @@ export function actionCsv(a: ActionExport): string {
return toCsv(rows, ACTION_CSV_HEADERS);
}
+/** Written first so Excel reads a CSV as UTF-8 and keeps Turkish characters. */
+export const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
+
+/**
+ * The actions list's Export CSV: a row per action. Besides its priority, it
+ * says what each action's Affected tab counts and names (AC-005).
+ */
+export const ACTION_LIST_CSV_HEADERS = [
+ 'number',
+ 'priority_score',
+ 'priority_level',
+ 'title',
+ 'category',
+ 'status',
+ 'assignee',
+ 'due_date',
+ 'tasks_done_total',
+ 'signal_count',
+ 'affected_count',
+ 'affected_items',
+ 'created',
+];
+
+/** One action of the list, labelled in the reader's language. */
+export interface ActionListRow {
+ number: number;
+ priorityScore: number | null;
+ /** "High"; empty before the action is scored. */
+ priorityLevel: string;
+ title: string;
+ category: string;
+ status: string;
+ assignee: string;
+ dueDate: string;
+ tasksDone: number;
+ tasksTotal: number;
+ signalCount: number;
+ /** What its Affected tab counts and names; missing reads as none. */
+ affected?: { count: number; items: string[] };
+ created: string;
+}
+
+/** The actions list's Export CSV, without the byte order mark the download adds. */
+export function actionListCsv(rows: ActionListRow[]): string {
+ return toCsv(
+ rows.map((row) => ({
+ number: row.number,
+ priority_score: row.priorityScore ?? '',
+ priority_level: row.priorityLevel,
+ title: row.title,
+ category: row.category,
+ status: row.status,
+ assignee: row.assignee,
+ due_date: row.dueDate,
+ tasks_done_total: `${row.tasksDone} / ${row.tasksTotal}`,
+ signal_count: row.signalCount,
+ affected_count: row.affected?.count ?? 0,
+ affected_items: (row.affected?.items ?? []).join('; '),
+ created: row.created,
+ })),
+ ACTION_LIST_CSV_HEADERS,
+ );
+}
+
const bold = (value: string) => ({ value, fontWeight: 'bold' as const });
/** "Export Excel": a sheet each for the action, its tasks, its signals and its history. */
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index bae2700c2..a05b0e5ee 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -21,6 +21,7 @@ import {
import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';
import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry';
import { readPromptPlaces } from '@/lib/signals/prompt-places';
+import { affectedOf, affectedSignals, affectedSummary } from '@/lib/action-center/affected';
import { supabaseAdmin } from '@/lib/supabase/admin';
import type { KpiTimeframe } from '@/lib/kpis/registry';
import { parseImproveOutcome, type ImproveOutcome } from '@/lib/improve-outcome';
@@ -577,3 +578,77 @@ export async function getPromptDemand(
}
return demand;
}
+
+/** Action ids per request, and signal rows per page, for the list's export. */
+const AFFECTED_ID_CHUNK = 100;
+const AFFECTED_PAGE_SIZE = 1000;
+
+/**
+ * Each action's affected items, for the actions list's Export CSV (AC-005):
+ * the count and names the drawer's Affected tab shows, from the signals the
+ * action rests on — or, for one a person sent, from what it was sent about.
+ * Read page by page, so a brand with many signals is read whole.
+ */
+export async function getActionsAffected(
+ brandId: string,
+ actionIds: string[],
+): Promise<Record<string, { count: number; items: string[] }>> {
+ const ids = [...new Set(actionIds)];
+ if (ids.length === 0) return {};
+ const supabase = await createClient();
+ const chunks: string[][] = [];
+ for (let i = 0; i < ids.length; i += AFFECTED_ID_CHUNK) {
+ chunks.push(ids.slice(i, i + AFFECTED_ID_CHUNK));
+ }
+
+ const readSignals = async (chunk: string[]) => {
+ const rows: (SignalRow & { action_signals: { action_id: string }[] })[] = [];
+ for (let from = 0; ; from += AFFECTED_PAGE_SIZE) {
+ const { data, error } = await supabase
+ .from('signals')
+ .select(`${SIGNAL_ROW_COLUMNS}, action_signals!inner(action_id)`)
+ .eq('brand_id', brandId)
+ .in('action_signals.action_id', chunk)
+ // The drawer's order, made stable so pages don't shuffle.
+ .order('detected_at', { ascending: false })
+ .order('id')
+ .range(from, from + AFFECTED_PAGE_SIZE - 1);
+ if (error) throw new Error(error.message);
+ const batch = (data ?? []) as unknown as typeof rows;
+ rows.push(...batch);
+ if (batch.length < AFFECTED_PAGE_SIZE) return rows;
+ }
+ };
+ const readPayloads = async (chunk: string[]) => {
+ const { data, error } = await supabase
+ .from('actions')
+ .select('id, payload')
+ .eq('brand_id', brandId)
+ .in('id', chunk);
+ if (error) throw new Error(error.message);
+ return (data ?? []) as { id: string; payload: Record<string, unknown> | null }[];
+ };
+
+ const [signalChunks, payloadChunks, places] = await Promise.all([
+ Promise.all(chunks.map(readSignals)),
+ Promise.all(chunks.map(readPayloads)),
+ readPromptPlaces(supabase, brandId),
+ ]);
+
+ const rowsByAction = new Map<string, SignalRow[]>();
+ for (const row of signalChunks.flat()) {
+ for (const link of row.action_signals ?? []) {
+ const list = rowsByAction.get(link.action_id) ?? [];
+ list.push(row);
+ rowsByAction.set(link.action_id, list);
+ }
+ }
+ const summaries: Record<string, { count: number; items: string[] }> = {};
+ for (const action of payloadChunks.flat()) {
+ const signals = mapSignalRows(rowsByAction.get(action.id) ?? [], places);
+ summaries[action.id] = affectedSummary(
+ affectedOf(affectedSignals(signals, action.id), action.payload ?? {}),
+ );
+ }
+ return summaries;
+}
diff --git a/web/src/lib/actions/actions-affected.test.ts b/web/src/lib/actions/actions-affected.test.ts
new file mode 100644
index 000000000..3e760f9b4
--- /dev/null
+++ b/web/src/lib/actions/actions-affected.test.ts
@@ -0,0 +1,136 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The actions list's Export CSV (AC-005): each action's affected count and
+ * names, read for many actions at once, page by page, as the drawer's
+ * Affected tab reads one.
+ */
+
+type Call = [string, ...unknown[]];
+type Row = Record<string, unknown>;
+let queries: { table: string; calls: Call[] }[];
+let rows: Record<string, Row[]>;
+
+/** What PostgREST would answer: the `in` filters, embedded ones included, then the range. */
+function answer(table: string, calls: Call[]): Row[] {
+ let out = rows[table] ?? [];
+ for (const [method, column, values] of calls) {
+ if (method !== 'in') continue;
+ const wanted = values as string[];
+ if (column === 'action_signals.action_id') {
+ out = out
+ .map((row) => ({
+ ...row,
+ action_signals: (row.action_signals as { action_id: string }[]).filter((link) =>
+ wanted.includes(link.action_id),
+ ),
+ }))
+ .filter((row) => row.action_signals.length > 0);
+ } else {
+ out = out.filter((row) => wanted.includes(row[column as string] as string));
+ }
+ }
+ const range = calls.find(([method]) => method === 'range');
+ return range ? out.slice(range[1] as number, (range[2] as number) + 1) : out;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ from: (table: string) => {
+ const query = { table, calls: [] as Call[] };
+ queries.push(query);
+ const chain: Record<string, unknown> = {};
+ for (const method of ['select', 'eq', 'in', 'order', 'range']) {
+ chain[method] = (...args: unknown[]) => {
+ query.calls.push([method, ...args]);
+ return chain;
+ };
+ }
+ chain.then = (resolve: (value: unknown) => unknown) =>
+ resolve({ data: answer(table, query.calls), error: null });
+ return chain;
+ },
+ })),
+}));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+
+const { getActionsAffected } = await import('./action-center');
+
+const lost = (id: string, promptId: string, promptText: string, actions: string[]): Row => ({
+ id,
+ category: 'citation',
+ kind: 'lost_citations',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ detected_at: '2026-10-09T00:00:00Z',
+ last_detected_at: '2026-10-09T00:00:00Z',
+ resolved_at: null,
+ previous_value: null,
+ current_value: null,
+ change_value: null,
+ payload: { promptId, promptText },
+ kpi_keys: [],
+ action_id: actions[0],
+ action_signals: actions.map((action_id) => ({ action_id })),
+});
+
+beforeEach(() => {
+ queries = [];
+ rows = {
+ actions: [
+ { id: 'a1', payload: {} },
+ { id: 'a2', payload: {} },
+ // Sent from the Improve tab: no signals, so what it was sent about.
+ { id: 'a3', payload: { promptId: 'p9', promptText: 'Is Acme any good?' } },
+ ],
+ signals: [
+ lost('s1', 'p1', 'Best coffee subscription?', ['a1']),
+ lost('s2', 'p2', 'Coffee delivery near me', ['a1', 'a2']),
+ // A second finding on the same prompt: one item.
+ lost('s3', 'p1', 'Best coffee subscription?', ['a1']),
+ ],
+ };
+});
+
+describe('getActionsAffected', () => {
+ it("gives each action the Affected tab's count and names", async () => {
+ expect(await getActionsAffected('b1', ['a1', 'a2', 'a3'])).toEqual({
+ a1: { count: 2, items: ['Best coffee subscription?', 'Coffee delivery near me'] },
+ // A signal two actions took counts for both.
+ a2: { count: 1, items: ['Coffee delivery near me'] },
+ a3: { count: 1, items: ['Is Acme any good?'] },
+ });
+ });
+
+ it("reads past one response's rows, a page at a time", async () => {
+ rows.signals = Array.from({ length: 1001 }, (_, i) =>
+ lost(`s${i}`, `p${i}`, `Prompt ${i}`, ['a1']),
+ );
+ const result = await getActionsAffected('b1', ['a1']);
+
+ expect(result.a1.count).toBe(1001);
+ const ranges = queries
+ .filter((q) => q.table === 'signals')
+ .map((q) => q.calls.find(([method]) => method === 'range'));
+ expect(ranges).toEqual([
+ ['range', 0, 999],
+ ['range', 1000, 1999],
+ ]);
+ });
+
+ it('asks for at most 100 actions a request, so the URL stays short', async () => {
+ const ids = Array.from({ length: 150 }, (_, i) => `x${i}`);
+ await getActionsAffected('b1', ids);
+
+ const sizes = queries
+ .filter((q) => q.table === 'signals')
+ .map((q) => (q.calls.find(([method]) => method === 'in')![2] as string[]).length);
+ expect(sizes).toEqual([100, 50]);
+ });
+
+ it('reads nothing for no actions', async () => {
+ expect(await getActionsAffected('b1', [])).toEqual({});
+ expect(queries).toEqual([]);
+ });
+});
diff --git a/web/src/lib/download.ts b/web/src/lib/download.ts
new file mode 100644
index 000000000..aa0642953
--- /dev/null
+++ b/web/src/lib/download.ts
@@ -0,0 +1,12 @@
+/**
+ * Saves a file the browser built (an export). The object URL is revoked once
+ * the download has started; revoked at once, some browsers drop it.
+ */
+export function saveBlob(blob: Blob, fileName: string) {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = fileName;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}