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(audit): list pages worth auditing in a Site Audit Opportunities tab (#1136)

Cihanbb4e09dc25cc
diff --git a/server/src/lib/audit/opportunities.js b/server/src/lib/audit/opportunities.js
new file mode 100644
index 000000000..3db53bcfb
--- /dev/null
+++ b/server/src/lib/audit/opportunities.js
@@ -0,0 +1,190 @@
+/**
+ * Site Audit's Opportunities inbox (SA-004): the brand's pages worth auditing,
+ * each with why. Pure, so the route only reads rows and this decides what
+ * they add up to.
+ *
+ * Sources in this version:
+ * - Google Analytics: page_opportunities' open "no AI traffic" pages,
+ * valuable pages AI engines send no visitors to (refreshed nightly).
+ * - Site pages (site_pages: the sitemap, GA and cited pages): pages never
+ * audited, or whose last audit is older than auditMaxAgeDays.
+ *
+ * Pinned pages always show, first. Excluded pages are left out of the rows
+ * and listed apart, so they can be put back.
+ */
+
+import { isExcludedPath } from '../page-paths.js';
+import { pageKey } from './history.js';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/**
+ * One key per page across GA paths, site_pages URLs, audits and prefs: the
+ * Pages list's key (host without www., path without a trailing slash),
+ * lowercased, since GA lowercases its paths. Null for something that isn't a
+ * URL.
+ */
+export function opportunityKey(url) {
+ return pageKey(url)?.key.toLowerCase() ?? null;
+}
+
+const pathOf = (url) => pageKey(url)?.path ?? '/';
+
+/**
+ * @param {object} input
+ * @param {string|null} input.primaryHost the brand's primary host (normStoredDomain)
+ * @param {Array<{ landing_page: string, value_signal: string, value_percentile: number|string, sessions: number, citation_state: string|null, citations: number|null }>} input.gaPages
+ * open page_opportunities rows (paths on the primary host)
+ * @param {Array<{ url: string, title: string|null, ga_sessions: number|null, ai_citations: number|null }>} input.sitePages
+ * @param {Array<{ key: string, url: string, score: number|null, auditId: string, lastAuditedAt: string, status: string }>} input.auditPages
+ * buildAuditPages output
+ * @param {Array<{ page_key: string, url: string, state: 'pinned'|'excluded' }>} input.prefs
+ * @param {number} input.staleDays an audit older than this no longer counts
+ * @param {number} [input.now]
+ */
+export function buildOpportunities({
+ primaryHost,
+ gaPages = [],
+ sitePages = [],
+ auditPages = [],
+ prefs = [],
+ staleDays,
+ now = Date.now(),
+}) {
+ const audits = new Map(auditPages.map((p) => [p.key.toLowerCase(), p]));
+ const prefsByKey = new Map(prefs.map((p) => [p.page_key, p]));
+ const pages = new Map();
+
+ const pageFor = (url) => {
+ const key = opportunityKey(url);
+ if (!key) return null;
+ if (!pages.has(key)) {
+ pages.set(key, {
+ key,
+ url,
+ path: pathOf(url),
+ title: null,
+ reasons: [],
+ pinned: false,
+ sessions: null,
+ citations: null,
+ });
+ }
+ return pages.get(key);
+ };
+
+ if (primaryHost) {
+ for (const row of gaPages) {
+ const page = pageFor(`https://${primaryHost}${row.landing_page}`);
+ if (!page) continue;
+ page.reasons.push({
+ type: 'no_ai_traffic',
+ signal: row.value_signal,
+ percentile: Number(row.value_percentile),
+ citationState: row.citation_state ?? null,
+ });
+ page.sessions = row.sessions ?? page.sessions;
+ page.citations = row.citations ?? page.citations;
+ }
+ }
+
+ const staleBefore = now - staleDays * DAY_MS;
+ for (const row of sitePages) {
+ const key = opportunityKey(row.url);
+ if (!key) continue;
+ const audit = audits.get(key);
+ const audited = audit && audit.score !== null;
+ const stale = audited && Date.parse(audit.lastAuditedAt) < staleBefore;
+ if (audited && !stale && !pages.has(key)) continue;
+ const page = pageFor(row.url);
+ page.title = row.title ?? page.title;
+ page.sessions = page.sessions ?? row.ga_sessions ?? null;
+ page.citations = page.citations ?? row.ai_citations ?? null;
+ if (!audited) page.reasons.push({ type: 'never_audited' });
+ else if (stale) {
+ page.reasons.push({
+ type: 'stale_audit',
+ days: Math.floor((now - Date.parse(audit.lastAuditedAt)) / DAY_MS),
+ });
+ }
+ }
+
+ for (const pref of prefs) {
+ const page = pref.state === 'pinned' ? pageFor(pref.url) : null;
+ if (page) page.pinned = true;
+ }
+
+ const rows = [];
+ const excluded = [];
+ for (const page of pages.values()) {
+ const pref = prefsByKey.get(page.key);
+ if (pref?.state === 'excluded') {
+ excluded.push({ key: page.key, url: page.url, path: page.path, title: page.title });
+ continue;
+ }
+ // Checkout, login, legal and the like carry no opportunity, unless a team pinned one.
+ if (!page.pinned && isExcludedPath(page.path)) continue;
+ if (!page.pinned && page.reasons.length === 0) continue;
+
+ const audit = audits.get(page.key);
+ rows.push({
+ ...page,
+ running: audit?.status === 'running',
+ lastAudit:
+ audit && audit.score !== null
+ ? { at: audit.lastAuditedAt, score: audit.score, auditId: audit.auditId }
+ : null,
+ });
+ }
+ // Excluded pages the inbox no longer lists still show, to be put back.
+ for (const pref of prefs) {
+ if (pref.state === 'excluded' && !excluded.some((e) => e.key === pref.page_key)) {
+ excluded.push({ key: pref.page_key, url: pref.url, path: pathOf(pref.url), title: null });
+ }
+ }
+
+ rows.sort(compareOpportunities);
+ excluded.sort((a, b) => a.path.localeCompare(b.path));
+ return { rows, excluded };
+}
+
+const gaPercentile = (row) => row.reasons.find((r) => r.type === 'no_ai_traffic')?.percentile ?? -1;
+const neverAudited = (row) => row.reasons.some((r) => r.type === 'never_audited');
+
+/**
+ * Until the priority score (SA-005): pinned first, then GA's most valuable
+ * pages without AI traffic, then pages never audited before stale ones, then
+ * the most cited and visited.
+ */
+export function compareOpportunities(a, b) {
+ return (
+ Number(b.pinned) - Number(a.pinned) ||
+ gaPercentile(b) - gaPercentile(a) ||
+ Number(neverAudited(b)) - Number(neverAudited(a)) ||
+ (b.citations ?? 0) - (a.citations ?? 0) ||
+ (b.sessions ?? 0) - (a.sessions ?? 0) ||
+ a.path.localeCompare(b.path)
+ );
+}
+
+/**
+ * AI visits per page over the window, from ae_page_traffic_evidence: Google
+ * Analytics where it has the page, else the tracking snippet, never both
+ * added (the snippet counts the visits GA counts), as mergeTrafficPages does.
+ *
+ * @param {{ analytics?: Array<{ page: string, cur_sessions: number }>, snippet?: Array<{ page: string, cur_sessions: number }> }} evidence
+ * @returns {Map<string, number>} by the page string the RPC was asked for
+ */
+export function aiVisitsByPage(evidence) {
+ const sum = (rows) => {
+ const totals = new Map();
+ for (const r of rows ?? []) {
+ if (!r.page) continue;
+ totals.set(r.page, (totals.get(r.page) ?? 0) + Number(r.cur_sessions ?? 0));
+ }
+ return totals;
+ };
+ const visits = sum(evidence?.snippet);
+ for (const [page, sessions] of sum(evidence?.analytics)) visits.set(page, sessions);
+ return visits;
+}
diff --git a/server/src/lib/audit/opportunities.test.js b/server/src/lib/audit/opportunities.test.js
new file mode 100644
index 000000000..ef3cf7cfc
--- /dev/null
+++ b/server/src/lib/audit/opportunities.test.js
@@ -0,0 +1,210 @@
+import { describe, expect, it } from 'vitest';
+import {
+ aiVisitsByPage,
+ buildOpportunities,
+ compareOpportunities,
+ opportunityKey,
+} from './opportunities.js';
+
+const NOW = Date.parse('2026-10-17T12:00:00Z');
+const daysAgo = (n) => new Date(NOW - n * 24 * 60 * 60 * 1000).toISOString();
+
+const audit = (url, score, days, status = 'completed') => ({
+ key: opportunityKey(url),
+ url,
+ score,
+ auditId: `a-${url}`,
+ lastAuditedAt: daysAgo(days),
+ status,
+});
+
+const build = (over = {}) =>
+ buildOpportunities({
+ primaryHost: 'acme.com',
+ staleDays: 90,
+ now: NOW,
+ ...over,
+ });
+
+describe('opportunityKey', () => {
+ it('reads every spelling of a page, in any case, as one page', () => {
+ expect(
+ new Set(
+ [
+ 'https://acme.com/Pricing',
+ 'https://www.acme.com/pricing/',
+ 'http://ACME.com/pricing?utm_source=x',
+ ].map(opportunityKey),
+ ),
+ ).toEqual(new Set(['acme.com/pricing']));
+ expect(opportunityKey('not a url')).toBeNull();
+ });
+});
+
+describe('buildOpportunities', () => {
+ it("lists GA's valuable pages without AI traffic, with their last audit", () => {
+ const { rows } = build({
+ gaPages: [
+ {
+ landing_page: '/pricing',
+ value_signal: 'revenue',
+ value_percentile: '95',
+ sessions: 1200,
+ citation_state: 'targeted_not_cited',
+ citations: 0,
+ },
+ ],
+ auditPages: [audit('https://acme.com/pricing/', 0.63, 3)],
+ });
+ expect(rows).toEqual([
+ expect.objectContaining({
+ key: 'acme.com/pricing',
+ url: 'https://acme.com/pricing',
+ path: '/pricing',
+ pinned: false,
+ running: false,
+ sessions: 1200,
+ reasons: [
+ {
+ type: 'no_ai_traffic',
+ signal: 'revenue',
+ percentile: 95,
+ citationState: 'targeted_not_cited',
+ },
+ ],
+ lastAudit: { at: daysAgo(3), score: 0.63, auditId: 'a-https://acme.com/pricing/' },
+ }),
+ ]);
+ });
+
+ it('lists site pages never audited or audited too long ago, and leaves fresh audits out', () => {
+ const { rows } = build({
+ sitePages: [
+ { url: 'https://acme.com/blog/guide', title: 'Guide', ga_sessions: 40, ai_citations: 3 },
+ { url: 'https://acme.com/compare', title: 'Compare', ga_sessions: 90, ai_citations: 0 },
+ { url: 'https://acme.com/about', title: 'About', ga_sessions: 10, ai_citations: 0 },
+ // A failed audit doesn't count as one.
+ { url: 'https://acme.com/team', title: 'Team', ga_sessions: 5, ai_citations: 0 },
+ ],
+ auditPages: [
+ audit('https://acme.com/compare', 0.7, 120),
+ audit('https://acme.com/about', 0.8, 10),
+ audit('https://acme.com/team', null, 2, 'failed'),
+ ],
+ });
+ expect(rows.map((r) => [r.path, r.reasons])).toEqual([
+ ['/blog/guide', [{ type: 'never_audited' }]],
+ ['/team', [{ type: 'never_audited' }]],
+ ['/compare', [{ type: 'stale_audit', days: 120 }]],
+ ]);
+ expect(rows[0]).toMatchObject({ title: 'Guide', citations: 3, sessions: 40, lastAudit: null });
+ });
+
+ it('merges one page from both sources and keeps checkout-like pages out', () => {
+ const { rows } = build({
+ gaPages: [
+ {
+ landing_page: '/pricing',
+ value_signal: 'key_events',
+ value_percentile: 80,
+ sessions: 50,
+ },
+ ],
+ sitePages: [
+ { url: 'https://acme.com/Pricing/', title: 'Pricing', ga_sessions: 48, ai_citations: 1 },
+ { url: 'https://acme.com/legal/terms', title: 'Terms', ga_sessions: 2, ai_citations: 0 },
+ { url: 'https://acme.com/cart', title: 'Cart', ga_sessions: 30, ai_citations: 0 },
+ ],
+ });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].reasons.map((r) => r.type)).toEqual(['no_ai_traffic', 'never_audited']);
+ expect(rows[0]).toMatchObject({ title: 'Pricing', sessions: 50 });
+ });
+
+ it('puts pinned pages first, even with nothing to fix, and lists excluded ones apart', () => {
+ const { rows, excluded } = build({
+ gaPages: [
+ { landing_page: '/pricing', value_signal: 'revenue', value_percentile: 99, sessions: 10 },
+ ],
+ sitePages: [
+ { url: 'https://acme.com/blog', title: 'Blog', ga_sessions: 1, ai_citations: 0 },
+ { url: 'https://acme.com/about', title: 'About', ga_sessions: 1, ai_citations: 0 },
+ ],
+ auditPages: [audit('https://acme.com/about', 0.9, 5)],
+ prefs: [
+ { page_key: 'acme.com/about', url: 'https://acme.com/about', state: 'pinned' },
+ { page_key: 'acme.com/blog', url: 'https://acme.com/blog', state: 'excluded' },
+ { page_key: 'acme.com/old', url: 'https://acme.com/old', state: 'excluded' },
+ ],
+ });
+ expect(rows.map((r) => [r.path, r.pinned])).toEqual([
+ ['/about', true],
+ ['/pricing', false],
+ ]);
+ expect(excluded.map((e) => [e.path, e.title])).toEqual([
+ ['/blog', 'Blog'],
+ ['/old', null],
+ ]);
+ });
+
+ it('marks a page being audited, and lists GA pages only with a primary host', () => {
+ const { rows } = build({
+ sitePages: [{ url: 'https://acme.com/new', title: null, ga_sessions: 0, ai_citations: 0 }],
+ auditPages: [audit('https://acme.com/new', null, 0, 'running')],
+ });
+ expect(rows[0]).toMatchObject({ path: '/new', running: true, lastAudit: null });
+
+ expect(
+ build({
+ primaryHost: null,
+ gaPages: [
+ { landing_page: '/pricing', value_signal: 'revenue', value_percentile: 90, sessions: 5 },
+ ],
+ }).rows,
+ ).toEqual([]);
+ });
+});
+
+describe('compareOpportunities', () => {
+ const row = (path, over = {}) => ({ path, pinned: false, reasons: [], ...over });
+
+ it('orders pinned, then GA value, then never audited, then citations and visits', () => {
+ const rows = [
+ row('/stale', { reasons: [{ type: 'stale_audit', days: 100 }], citations: 9 }),
+ row('/never-quiet', { reasons: [{ type: 'never_audited' }], citations: 0, sessions: 1 }),
+ row('/never-cited', { reasons: [{ type: 'never_audited' }], citations: 4 }),
+ row('/ga-80', { reasons: [{ type: 'no_ai_traffic', percentile: 80 }] }),
+ row('/ga-95', { reasons: [{ type: 'no_ai_traffic', percentile: 95 }] }),
+ row('/pinned', { pinned: true }),
+ ];
+ expect(rows.sort(compareOpportunities).map((r) => r.path)).toEqual([
+ '/pinned',
+ '/ga-95',
+ '/ga-80',
+ '/never-cited',
+ '/never-quiet',
+ '/stale',
+ ]);
+ });
+});
+
+describe('aiVisitsByPage', () => {
+ it('takes Google Analytics where it has the page, else the snippet, never both', () => {
+ const visits = aiVisitsByPage({
+ analytics: [
+ { page: 'https://acme.com/a', platform: 'chatgpt', cur_sessions: 4 },
+ { page: 'https://acme.com/a', platform: 'perplexity', cur_sessions: 2 },
+ ],
+ snippet: [
+ { page: 'https://acme.com/a', platform: 'chatgpt', cur_sessions: 9 },
+ { page: 'https://acme.com/b', platform: 'chatgpt', cur_sessions: 3 },
+ { page: null, platform: 'chatgpt', cur_sessions: 50 },
+ ],
+ });
+ expect([...visits]).toEqual([
+ ['https://acme.com/a', 6],
+ ['https://acme.com/b', 3],
+ ]);
+ expect(aiVisitsByPage(null).size).toBe(0);
+ });
+});
diff --git a/server/src/routes/audits-opportunities.test.js b/server/src/routes/audits-opportunities.test.js
new file mode 100644
index 000000000..74f382f1e
--- /dev/null
+++ b/server/src/routes/audits-opportunities.test.js
@@ -0,0 +1,263 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * Route-level tests for the Opportunities inbox: GET /api/audits/opportunities
+ * reads the GA page opportunities, site pages, audits and pins/exclusions,
+ * adds each page's AI visits, and PUT /api/audits/opportunities/prefs pins,
+ * excludes or clears pages.
+ */
+
+let tables;
+let rpcCalls;
+let writes;
+let server;
+let baseUrl;
+
+function query(table) {
+ const filters = {};
+ let write = null;
+ const builder = {
+ select: () => builder,
+ eq: (col, val) => {
+ filters[col] = val;
+ return builder;
+ },
+ is: () => builder,
+ in: (col, vals) => {
+ filters[col] = vals;
+ return builder;
+ },
+ order: () => builder,
+ range: (from, to) => {
+ filters.range = [from, to];
+ return builder;
+ },
+ limit: () => builder,
+ maybeSingle: () => {
+ builder.single = true;
+ return builder;
+ },
+ upsert: (rows, opts) => {
+ write = { op: 'upsert', rows, opts };
+ return builder;
+ },
+ delete: () => {
+ write = { op: 'delete' };
+ return builder;
+ },
+ then: (resolve) => {
+ if (write) {
+ writes.push({ table, ...write, filters: { ...filters } });
+ return resolve({ data: null, error: null });
+ }
+ let data = (tables[table] ?? []).filter(
+ (r) => !r.brand_id || r.brand_id === filters.brand_id,
+ );
+ // PostgREST's max_rows: a read without a range stops at 1000 rows.
+ data = filters.range
+ ? data.slice(filters.range[0], filters.range[1] + 1)
+ : data.slice(0, 1000);
+ if (table === 'brands') data = (tables.brands ?? []).find((b) => b.id === filters.id) ?? null;
+ else if (builder.single) data = data[0] ?? null;
+ return resolve({ data, error: null });
+ },
+ };
+ return builder;
+}
+
+async function startApp() {
+ vi.resetModules();
+ vi.doMock('../config/supabase.js', () => ({
+ default: {
+ from: (t) => query(t),
+ rpc: async (name, args) => {
+ rpcCalls.push({ name, args });
+ return {
+ data: {
+ analytics: [{ page: args.p_pages[0], platform: 'chatgpt', cur_sessions: 7 }],
+ snippet: [],
+ },
+ error: null,
+ };
+ },
+ },
+ }));
+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess: async () => ({ orgId: 'org-1' }) }));
+ vi.doMock('../lib/plan-guard.js', () => ({
+ requireFeature: () => (req, res, next) => next(),
+ enforceSiteAuditQuota: vi.fn(),
+ getSiteAuditQuotaStatus: vi.fn(),
+ getOrgIdForUser: vi.fn(),
+ PlanLimitError: class PlanLimitError extends Error {},
+ }));
+ vi.doMock('../lib/audit/context.js', () => ({ buildAuditContext: vi.fn() }));
+ vi.doMock('../lib/audit/engine.js', () => ({ runSignals: vi.fn() }));
+ vi.doMock('../lib/audit/llm-signals.js', () => ({ evaluateLlmSignals: vi.fn() }));
+ vi.doMock('../lib/audit/external-signals.js', () => ({ evaluateBrandEntity: vi.fn() }));
+ vi.doMock('../lib/audit/recommendations.js', () => ({
+ brandFactsFor: vi.fn(),
+ generateRecommendations: vi.fn(),
+ }));
+ vi.doMock('../lib/logger.js', () => {
+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
+ return { default: logger, logger };
+ });
+
+ const { default: router } = await import('./audits.js');
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn(), info: vi.fn() };
+ next();
+ });
+ app.use('/api/audits', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/audits`;
+}
+
+const brandId = '33333333-3333-3333-3333-333333333333';
+
+beforeEach(async () => {
+ rpcCalls = [];
+ writes = [];
+ tables = {
+ brands: [{ id: brandId, ga_property_id: 'properties/1' }],
+ brand_domains: [{ brand_id: brandId, domain: 'www.acme.com', is_primary: true }],
+ page_opportunities: [
+ {
+ brand_id: brandId,
+ landing_page: '/pricing',
+ value_signal: 'revenue',
+ value_percentile: 96,
+ sessions: 800,
+ citation_state: 'not_targeted',
+ citations: 0,
+ },
+ ],
+ site_pages: [
+ {
+ brand_id: brandId,
+ url: 'https://acme.com/blog',
+ title: 'Blog',
+ ga_sessions: 30,
+ ai_citations: 2,
+ },
+ ],
+ site_audits: [],
+ ai_traffic_logs: [],
+ site_audit_page_prefs: [
+ {
+ brand_id: brandId,
+ page_key: 'acme.com/blog',
+ url: 'https://acme.com/blog',
+ state: 'excluded',
+ },
+ ],
+ };
+ await startApp();
+});
+
+afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve));
+ vi.doUnmock('../config/supabase.js');
+});
+
+describe('GET /api/audits/opportunities', () => {
+ it("lists the brand's opportunities with their AI visits, and the excluded pages apart", async () => {
+ const res = await fetch(`${baseUrl}/opportunities?brandId=${brandId}`);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.opportunities).toEqual([
+ expect.objectContaining({
+ url: 'https://acme.com/pricing',
+ path: '/pricing',
+ aiVisits: 7,
+ reasons: [expect.objectContaining({ type: 'no_ai_traffic', percentile: 96 })],
+ }),
+ ]);
+ expect(body.excluded.map((e) => e.path)).toEqual(['/blog']);
+ expect(body.staleDays).toBe(90);
+
+ // AI visits over the last 30 days, for the listed pages.
+ const [{ name, args }] = rpcCalls;
+ expect(name).toBe('ae_page_traffic_evidence');
+ expect(args.p_pages).toEqual(['https://acme.com/pricing']);
+ });
+
+ it('reads every GA page past the first 1000', async () => {
+ tables.page_opportunities = Array.from({ length: 1200 }, (_, i) => ({
+ brand_id: brandId,
+ landing_page: `/p${i}`,
+ value_signal: 'engagement',
+ value_percentile: 75,
+ sessions: 20,
+ citation_state: null,
+ citations: 0,
+ }));
+ const body = await (await fetch(`${baseUrl}/opportunities?brandId=${brandId}`)).json();
+ expect(body.opportunities).toHaveLength(1200);
+ });
+
+ it('leaves AI visits unknown for a brand with neither Analytics nor the snippet', async () => {
+ tables.brands = [{ id: brandId, ga_property_id: null }];
+ const body = await (await fetch(`${baseUrl}/opportunities?brandId=${brandId}`)).json();
+ expect(body.opportunities[0].aiVisits).toBeNull();
+ expect(rpcCalls).toEqual([]);
+ });
+
+ it('needs a brand', async () => {
+ expect((await fetch(`${baseUrl}/opportunities`)).status).toBe(400);
+ });
+});
+
+describe('PUT /api/audits/opportunities/prefs', () => {
+ const put = (body) =>
+ fetch(`${baseUrl}/opportunities/prefs`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+ it('pins or excludes pages once per page, by their page key', async () => {
+ const res = await put({
+ brandId,
+ urls: ['https://www.acme.com/Pricing/', 'https://acme.com/pricing', 'https://acme.com/blog'],
+ state: 'pinned',
+ });
+ expect(res.status).toBe(200);
+ const [write] = writes;
+ expect(write).toMatchObject({
+ table: 'site_audit_page_prefs',
+ op: 'upsert',
+ opts: { onConflict: 'brand_id,page_key' },
+ });
+ expect(write.rows.map((r) => [r.page_key, r.url, r.state, r.created_by])).toEqual([
+ ['acme.com/pricing', 'https://acme.com/pricing', 'pinned', 'u1'],
+ ['acme.com/blog', 'https://acme.com/blog', 'pinned', 'u1'],
+ ]);
+ });
+
+ it('clears pages with a null state', async () => {
+ await put({ brandId, urls: ['https://acme.com/blog'], state: null });
+ expect(writes).toEqual([
+ expect.objectContaining({
+ op: 'delete',
+ filters: { brand_id: brandId, page_key: ['acme.com/blog'] },
+ }),
+ ]);
+ });
+
+ it('refuses an unknown state, no URLs or something that is not a URL', async () => {
+ expect((await put({ brandId, urls: ['https://acme.com/'], state: 'starred' })).status).toBe(
+ 400,
+ );
+ expect((await put({ brandId, urls: [], state: 'pinned' })).status).toBe(400);
+ expect((await put({ brandId, urls: ['nope'], state: 'pinned' })).status).toBe(400);
+ expect(writes).toEqual([]);
+ });
+});
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
index 01bd46daf..a007a8e27 100644
--- a/server/src/routes/audits.js
+++ b/server/src/routes/audits.js
@@ -34,6 +34,8 @@ import {
} from '../lib/audit/history.js';
import { readAllRpcRows } from '../lib/rpc-pages.js';
import { AUTHORITY_CATEGORIES, buildOverview, primaryPages } from '../lib/audit/overview.js';
+import { aiVisitsByPage, buildOpportunities, opportunityKey } from '../lib/audit/opportunities.js';
+import { ENGINE_THRESHOLDS } from '../config/action-engine.js';
import { runSignals } from '../lib/audit/engine.js';
import { evaluateLlmSignals } from '../lib/audit/llm-signals.js';
import { evaluateBrandEntity } from '../lib/audit/external-signals.js';
@@ -551,6 +553,169 @@ router.get('/overview', async (req, res) => {
}
});
+/** The window the Opportunities inbox counts AI visits over. */
+const OPPORTUNITY_VISITS_DAYS = 30;
+
+const isoDay = (ms) => new Date(ms).toISOString().slice(0, 10);
+
+/**
+ * AI visits per page over the last 30 days (null when the brand has neither
+ * Google Analytics nor the tracking snippet, so 0 would be a guess).
+ */
+async function opportunityAiVisits(brandId, urls) {
+ if (urls.length === 0) return new Map();
+ const [{ data: brand }, { data: logs }] = await Promise.all([
+ supabaseAdmin.from('brands').select('ga_property_id').eq('id', brandId).maybeSingle(),
+ supabaseAdmin.from('ai_traffic_logs').select('id').eq('brand_id', brandId).limit(1),
+ ]);
+ if (!brand?.ga_property_id && (logs ?? []).length === 0) return null;
+
+ const now = Date.now();
+ const from = isoDay(now - OPPORTUNITY_VISITS_DAYS * 24 * 60 * 60 * 1000);
+ const { data, error } = await supabaseAdmin.rpc('ae_page_traffic_evidence', {
+ p_brand_id: brandId,
+ p_pages: urls,
+ p_cur_from: from,
+ p_cur_to: isoDay(now),
+ // No comparison window: the previous one is left empty.
+ p_prev_from: from,
+ p_prev_to: isoDay(now - (OPPORTUNITY_VISITS_DAYS + 1) * 24 * 60 * 60 * 1000),
+ });
+ if (error) throw error;
+ return aiVisitsByPage(data);
+}
+
+// GET /api/audits/opportunities?brandId=… — the Opportunities inbox (SA-004):
+// the brand's pages worth auditing, each with why (Google Analytics pages
+// without AI traffic, pages never audited or audited long ago), pinned pages
+// first, plus the excluded pages to put back.
+// Registered before /:id so "opportunities" isn't matched as an audit id.
+router.get('/opportunities', async (req, res) => {
+ const userId = req.user?.id;
+ const { brandId } = req.query;
+ if (!brandId) {
+ return res.status(400).json({ success: false, message: 'brandId is required' });
+ }
+
+ try {
+ await assertBrandAccess(brandId, userId);
+
+ const [primary, gaPages, sitePages, audits, prefs] = await Promise.all([
+ primaryDomainOf(brandId),
+ // Up to 30% of GA's 5,000 pages a day: past PostgREST's 1000-row page.
+ readAllRpcRows('page_opportunities', (from, to) =>
+ supabaseAdmin
+ .from('page_opportunities')
+ .select(
+ 'landing_page, value_signal, value_percentile, sessions, citation_state, citations',
+ )
+ .eq('brand_id', brandId)
+ .eq('kind', 'no_ai_traffic')
+ .is('resolved_at', null)
+ .order('landing_page', { ascending: true })
+ .range(from, to),
+ ),
+ supabaseAdmin
+ .from('site_pages')
+ .select('url, title, ga_sessions, ai_citations')
+ .eq('brand_id', brandId),
+ readBrandAudits(brandId),
+ supabaseAdmin
+ .from('site_audit_page_prefs')
+ .select('page_key, url, state')
+ .eq('brand_id', brandId),
+ ]);
+ for (const read of [gaPages, sitePages, audits, prefs]) if (read.error) throw read.error;
+
+ const { rows, excluded } = buildOpportunities({
+ primaryHost: normStoredDomain(primary),
+ gaPages: gaPages.data ?? [],
+ sitePages: sitePages.data ?? [],
+ auditPages: buildAuditPages(audits.data),
+ prefs: prefs.data ?? [],
+ staleDays: ENGINE_THRESHOLDS.detection.auditMaxAgeDays,
+ });
+ const visits = await opportunityAiVisits(
+ brandId,
+ rows.map((r) => r.url),
+ );
+
+ return res.json({
+ success: true,
+ opportunities: rows.map((r) => ({
+ ...r,
+ aiVisits: visits === null ? null : (visits.get(r.url) ?? 0),
+ })),
+ excluded,
+ staleDays: ENGINE_THRESHOLDS.detection.auditMaxAgeDays,
+ });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ req.log.error({ err }, 'audit opportunities failed');
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+const prefsSchema = z.object({
+ brandId: z.guid(),
+ urls: z
+ .array(z.string().trim().min(1).max(2048))
+ .min(1)
+ .max(BULK_AUDIT_MAX)
+ .refine((urls) => urls.every((url) => opportunityKey(url)), 'Every URL must be a full URL'),
+ // null clears the page's pin or exclusion.
+ state: z.enum(['pinned', 'excluded']).nullable(),
+});
+
+// PUT /api/audits/opportunities/prefs — pin, exclude or clear pages of the
+// Opportunities inbox ({ brandId, urls, state }).
+router.put('/opportunities/prefs', async (req, res) => {
+ const userId = req.user?.id;
+ const parsed = prefsSchema.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ return res.status(400).json({
+ success: false,
+ message: parsed.error.issues[0]?.message ?? 'Invalid request',
+ });
+ }
+ const { brandId, urls, state } = parsed.data;
+
+ try {
+ await assertBrandAccess(brandId, userId);
+
+ const byKey = new Map(urls.map((url) => [opportunityKey(url), url]));
+ const { error } =
+ state === null
+ ? await supabaseAdmin
+ .from('site_audit_page_prefs')
+ .delete()
+ .eq('brand_id', brandId)
+ .in('page_key', [...byKey.keys()])
+ : await supabaseAdmin.from('site_audit_page_prefs').upsert(
+ [...byKey].map(([pageKeyValue, url]) => ({
+ brand_id: brandId,
+ page_key: pageKeyValue,
+ url,
+ state,
+ created_by: userId ?? null,
+ updated_at: new Date().toISOString(),
+ })),
+ { onConflict: 'brand_id,page_key' },
+ );
+ if (error) throw error;
+
+ return res.json({ success: true, pages: byKey.size, state });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ req.log.error({ err }, 'audit opportunity prefs failed');
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
// GET /api/audits/:id — fetch one stored audit with its signals
router.get('/:id', async (req, res) => {
const userId = req.user?.id;
diff --git a/supabase/migrations/00165_site_audit_page_prefs.sql b/supabase/migrations/00165_site_audit_page_prefs.sql
new file mode 100644
index 000000000..ef544036b
--- /dev/null
+++ b/supabase/migrations/00165_site_audit_page_prefs.sql
@@ -0,0 +1,38 @@
+-- Site Audit Opportunities (SA-004): pages a team pins or excludes.
+--
+-- The Opportunities inbox lists a brand's pages worth auditing. A team can
+-- pin a page (kept at the top, and always in the auto-audit runs of SA-006)
+-- or exclude it (left out of the inbox and the runs). One row per page; no
+-- row means neither.
+--
+-- page_key is the page as the Pages list groups audits (history.js pageKey):
+-- the host without "www." and the path without a trailing slash, lowercased,
+-- so every spelling of a page shares its row. url keeps one full URL of the
+-- page, to audit it and to show it.
+
+create table if not exists public.site_audit_page_prefs (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ page_key text not null,
+ url text not null,
+ state text not null check (state in ('pinned', 'excluded')),
+ created_by uuid references auth.users(id) on delete set null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (brand_id, page_key)
+);
+
+alter table public.site_audit_page_prefs enable row level security;
+
+-- Org members, as for site_audits (00017). The server writes with the
+-- service role; members may read.
+create policy site_audit_page_prefs_member_select on public.site_audit_page_prefs
+ for select using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 68133d6cf..8a7bc8483 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -22300,3 +22300,45 @@ comment on function public.insights_platform_compare_daily(
-- PostgREST caches function signatures; make it see the new ones now.
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00165_site_audit_page_prefs.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Site Audit Opportunities (SA-004): pages a team pins or excludes.
+--
+-- The Opportunities inbox lists a brand's pages worth auditing. A team can
+-- pin a page (kept at the top, and always in the auto-audit runs of SA-006)
+-- or exclude it (left out of the inbox and the runs). One row per page; no
+-- row means neither.
+--
+-- page_key is the page as the Pages list groups audits (history.js pageKey):
+-- the host without "www." and the path without a trailing slash, lowercased,
+-- so every spelling of a page shares its row. url keeps one full URL of the
+-- page, to audit it and to show it.
+
+create table if not exists public.site_audit_page_prefs (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ page_key text not null,
+ url text not null,
+ state text not null check (state in ('pinned', 'excluded')),
+ created_by uuid references auth.users(id) on delete set null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (brand_id, page_key)
+);
+
+alter table public.site_audit_page_prefs enable row level security;
+
+-- Org members, as for site_audits (00017). The server writes with the
+-- service role; members may read.
+create policy site_audit_page_prefs_member_select on public.site_audit_page_prefs
+ for select using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 3a598cf42..1a19e819a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -2107,6 +2107,53 @@
"failed": "Failed"
}
},
+ "lists": {
+ "label": "Site Audit lists",
+ "opportunities": "Opportunities",
+ "pages": "Pages",
+ "noPages": "No pages audited yet. Audit an opportunity or enter a URL above."
+ },
+ "opportunities": {
+ "page": "Page",
+ "why": "Why",
+ "aiVisits": "AI visits",
+ "lastAudit": "Last audit",
+ "never": "never",
+ "lastAuditValue": "{date} · {score}",
+ "running": "Running",
+ "select": "Select {page}",
+ "selectAll": "Select all opportunities shown",
+ "reasons": {
+ "noAiTraffic": "No AI traffic",
+ "topValue": "Top {share}% by {signal}",
+ "signals": {
+ "revenue": "revenue",
+ "transactions": "transactions",
+ "key_events": "key events",
+ "engagement": "engagement"
+ },
+ "targetedNotCited": "Targeted, not cited",
+ "neverAudited": "Never audited",
+ "staleAudit": "Audited {days} days ago",
+ "pinned": "Pinned"
+ },
+ "auditSelected": "Audit selected",
+ "pin": "Pin",
+ "unpin": "Unpin",
+ "exclude": "Exclude",
+ "pinnedToast": "{count, plural, one {# page pinned} other {# pages pinned}}",
+ "unpinnedToast": "{count, plural, one {# page unpinned} other {# pages unpinned}}",
+ "excludedToast": "{count, plural, one {# page excluded} other {# pages excluded}}",
+ "undo": "Undo",
+ "excluded": "{count, plural, one {# excluded page} other {# excluded pages}}",
+ "showExcluded": "Show",
+ "hideExcluded": "Hide",
+ "restore": "Restore",
+ "restoredToast": "{count, plural, one {# page restored} other {# pages restored}}",
+ "empty": "No pages to audit right now. Opportunities come from Google Analytics (valuable pages without AI traffic) and from your site's pages that were never audited or not in {days} days.",
+ "showMore": "Show more",
+ "prefsFailed": "Couldn't update the pages"
+ },
"overview": {
"yourDomain": "your domain",
"siteScore": "Site score",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
index 36ef1d69f..461494d8e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
@@ -26,7 +26,7 @@ function render(count: number, quota: AuditQuota | null, starting = false) {
count={count}
quota={quota}
starting={starting}
- onReaudit={onReaudit}
+ onAudit={onReaudit}
onExport={onExport}
onClear={onClear}
/>
@@ -83,6 +83,28 @@ describe('AuditBulkBar', () => {
expect(button('Re-audit').disabled).toBe(false);
});
+ it("takes the table's own audit label and actions, and leaves Export out without one", () => {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <AuditBulkBar
+ count={2}
+ quota={{ used: 0, limit: 500, remaining: 500 }}
+ starting={false}
+ auditLabel="Audit selected"
+ onAudit={onReaudit}
+ onClear={onClear}
+ >
+ <button type="button">Pin</button>
+ </AuditBulkBar>
+ </NextIntlClientProvider>,
+ );
+ });
+ expect(button('Audit selected')).toBeDefined();
+ expect(button('Pin')).toBeDefined();
+ expect(button('Export')).toBeUndefined();
+ });
+
it('waits while a bulk start is on its way', () => {
render(3, { used: 0, limit: 500, remaining: 500 }, true);
expect(button('Re-audit').disabled).toBe(true);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
index 953e77f1f..d74b6cbfc 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { Download, FileDown, FileSpreadsheet, Loader2, RefreshCw, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -55,25 +56,32 @@ export function ExportMenu({
}
/**
- * The Pages table's bulk bar (SA-003), shown while pages are selected: how
- * many of the month's audits a re-audit would use, Re-audit, Export and
- * Clear. Re-audit stays off when the selection is over what's left, so a
- * bulk run never goes past the quota.
+ * The bulk bar of the Pages (SA-003) and Opportunities (SA-004) tables, shown
+ * while pages are selected: how many of the month's audits an audit of them
+ * would use, the audit button (Re-audit, Audit selected), the table's own
+ * actions, Export and Clear. The audit stays off when the selection is over
+ * what's left, so a bulk run never goes past the quota.
*/
export function AuditBulkBar({
count,
quota,
starting,
- onReaudit,
+ auditLabel,
+ onAudit,
onExport,
onClear,
+ children,
}: {
count: number;
quota: AuditQuota | null;
starting: boolean;
- onReaudit: () => void;
- onExport: (format: ExportFormat) => void;
+ auditLabel?: string;
+ onAudit: () => void;
+ /** Export of the selected pages; left out when the table has none. */
+ onExport?: (format: ExportFormat) => void;
onClear: () => void;
+ /** The table's own actions, after the audit button (Pin, Exclude). */
+ children?: ReactNode;
}) {
const t = useTranslations('audit.bulk');
const limited = quota !== null && quota.limit !== -1;
@@ -101,7 +109,7 @@ export function AuditBulkBar({
variant="outline"
size="sm"
className="h-7 gap-1.5 text-xs"
- onClick={onReaudit}
+ onClick={onAudit}
disabled={starting || over}
>
{starting ? (
@@ -109,9 +117,10 @@ export function AuditBulkBar({
) : (
<RefreshCw className="h-3 w-3" />
)}
- {t('reaudit')}
+ {auditLabel ?? t('reaudit')}
</Button>
- <ExportMenu onExport={onExport} />
+ {children}
+ {onExport && <ExportMenu onExport={onExport} />}
<Button
variant="ghost"
size="sm"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.test.tsx
new file mode 100644
index 000000000..f299587ce
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.test.tsx
@@ -0,0 +1,170 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import type { AuditOpportunity, ExcludedPage } from '@/lib/actions/audits';
+import { OPPORTUNITIES_STEP, OpportunitiesTable } from './_opportunities-table';
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ children, ...props }: React.ComponentProps<'a'>) => <a {...props}>{children}</a>,
+}));
+
+const opportunity = (over: Partial<AuditOpportunity> = {}): AuditOpportunity => ({
+ key: 'acme.com/pricing',
+ url: 'https://acme.com/pricing',
+ path: '/pricing',
+ title: 'Pricing',
+ reasons: [
+ {
+ type: 'no_ai_traffic',
+ signal: 'revenue',
+ percentile: 95.4,
+ citationState: 'targeted_not_cited',
+ },
+ ],
+ pinned: false,
+ running: false,
+ aiVisits: 0,
+ lastAudit: { at: '2026-10-14T12:00:00.000Z', score: 0.63, auditId: 'a1' },
+ ...over,
+});
+
+const blog = opportunity({
+ key: 'acme.com/blog',
+ url: 'https://acme.com/blog',
+ path: '/blog',
+ reasons: [{ type: 'never_audited' }],
+ pinned: true,
+ aiVisits: 12,
+ lastAudit: null,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+const onSelect = vi.fn();
+const onRestore = vi.fn();
+
+function render(
+ opportunities: AuditOpportunity[],
+ {
+ excluded = [] as ExcludedPage[],
+ selected = new Set<string>(),
+ toolbar = null as React.ReactNode,
+ } = {},
+) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <OpportunitiesTable
+ opportunities={opportunities}
+ excluded={excluded}
+ staleDays={90}
+ selected={selected}
+ onSelect={onSelect}
+ onRestore={onRestore}
+ toolbar={toolbar}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const rows = () => [...container.querySelectorAll('tbody > tr')];
+const cells = (row: Element) => [...row.querySelectorAll('td')].map((td) => td.textContent?.trim());
+const box = (label: string) =>
+ container.querySelector(`[aria-label="${label}"]`) as HTMLButtonElement;
+const button = (text: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === text);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('OpportunitiesTable', () => {
+ it('shows each page with why, its AI visits and its last audit', () => {
+ render([
+ blog,
+ opportunity(),
+ opportunity({
+ key: 'k3',
+ path: '/compare',
+ aiVisits: null,
+ reasons: [{ type: 'stale_audit', days: 120 }],
+ }),
+ ]);
+
+ expect(rows().map(cells)).toEqual([
+ ['', '/blog', 'PinnedNever audited', '12', 'never'],
+ ['', '/pricing', 'No AI trafficTop 5% by revenueTargeted, not cited', '0', 'Oct 14 · 63'],
+ ['', '/compare', 'Audited 120 days ago', '—', 'Oct 14 · 63'],
+ ]);
+ // The page opens the live page; the last audit its report.
+ const [pageLink] = rows()[1].querySelectorAll('a');
+ expect(pageLink.getAttribute('href')).toBe('https://acme.com/pricing');
+ expect(pageLink.getAttribute('target')).toBe('_blank');
+ expect(rows()[1].querySelectorAll('a')[1].getAttribute('href')).toBe('/dashboard/audit/a1');
+ });
+
+ it('selects pages not being audited, one by one or all shown', () => {
+ const running = opportunity({ key: 'run', path: '/run', running: true, lastAudit: null });
+ render([opportunity(), blog, running], {
+ selected: new Set(['acme.com/blog']),
+ toolbar: <div role="toolbar">bulk</div>,
+ });
+
+ expect(rows()[2].textContent).toContain('Running');
+ expect(box('Select /run').disabled).toBe(true);
+ expect(box('Select all opportunities shown').getAttribute('data-state')).toBe('indeterminate');
+ expect(container.querySelector('[role=toolbar]')?.textContent).toBe('bulk');
+
+ act(() => box('Select /pricing').click());
+ expect(onSelect).toHaveBeenLastCalledWith(['acme.com/pricing'], true);
+ act(() => box('Select all opportunities shown').click());
+ expect(onSelect).toHaveBeenLastCalledWith(['acme.com/pricing', 'acme.com/blog'], true);
+ });
+
+ it('shows 50 pages at a time', () => {
+ const many = Array.from({ length: OPPORTUNITIES_STEP + 5 }, (_, i) =>
+ opportunity({ key: `p${i}`, path: `/p${i}` }),
+ );
+ render(many);
+ expect(rows()).toHaveLength(OPPORTUNITIES_STEP);
+ act(() => button('Show more')!.click());
+ expect(rows()).toHaveLength(OPPORTUNITIES_STEP + 5);
+ expect(button('Show more')).toBeUndefined();
+ });
+
+ it('lists the excluded pages on demand, each to restore', () => {
+ render([opportunity()], {
+ excluded: [
+ { key: 'acme.com/legal', url: 'https://acme.com/legal', path: '/legal', title: null },
+ ],
+ });
+ expect(container.textContent).toContain('1 excluded page');
+ act(() => button('Show')!.click());
+ act(() => button('Restore')!.click());
+ expect(onRestore).toHaveBeenCalledWith(['https://acme.com/legal']);
+ });
+
+ it('says where opportunities come from when there are none', () => {
+ render([]);
+ expect(container.textContent).toContain('No pages to audit right now.');
+ expect(container.textContent).toContain('not in 90 days');
+ expect(container.querySelector('table')).toBeNull();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.tsx
new file mode 100644
index 000000000..d48461371
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.tsx
@@ -0,0 +1,247 @@
+'use client';
+
+import { useState, type ReactNode } from 'react';
+import { useTranslations } from 'next-intl';
+import { ExternalLink, Loader2, Pin } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Card, CardContent } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { pct } from '@/components/audit/audit-report';
+import type { AuditOpportunity, ExcludedPage, OpportunityReason } from '@/lib/actions/audits';
+import { formatMonthDay, formatNumber } from '@/lib/format';
+
+/** Rows shown at first, and added by Show more. */
+export const OPPORTUNITIES_STEP = 50;
+
+function Chip({ children }: { children: ReactNode }) {
+ return (
+ <span className="inline-flex items-center gap-1 whitespace-nowrap rounded-full border bg-background px-2 py-0.5 text-xs text-muted-foreground">
+ {children}
+ </span>
+ );
+}
+
+/** Why a page is listed, as the mockup's chips: "No AI traffic", "Top 5% by revenue"… */
+function ReasonChips({ row }: { row: AuditOpportunity }) {
+ const t = useTranslations('audit.opportunities.reasons');
+ const chip = (reason: OpportunityReason) => {
+ switch (reason.type) {
+ case 'no_ai_traffic':
+ return [
+ <Chip key="ai">{t('noAiTraffic')}</Chip>,
+ <Chip key="value">
+ {t('topValue', {
+ share: Math.max(1, Math.round(100 - reason.percentile)),
+ signal: t(`signals.${reason.signal}`),
+ })}
+ </Chip>,
+ reason.citationState === 'targeted_not_cited' && (
+ <Chip key="cited">{t('targetedNotCited')}</Chip>
+ ),
+ ];
+ case 'never_audited':
+ return <Chip key="never">{t('neverAudited')}</Chip>;
+ case 'stale_audit':
+ return <Chip key="stale">{t('staleAudit', { days: reason.days })}</Chip>;
+ }
+ };
+ return (
+ <div className="flex flex-wrap gap-1">
+ {row.pinned && (
+ <Chip>
+ <Pin className="h-3 w-3" />
+ {t('pinned')}
+ </Chip>
+ )}
+ {row.reasons.flatMap(chip)}
+ </div>
+ );
+}
+
+function ExcludedList({
+ excluded,
+ onRestore,
+}: {
+ excluded: ExcludedPage[];
+ onRestore: (urls: string[]) => void;
+}) {
+ const t = useTranslations('audit.opportunities');
+ const [open, setOpen] = useState(false);
+ if (excluded.length === 0) return null;
+ return (
+ <div className="pt-3 text-xs text-muted-foreground">
+ <span>{t('excluded', { count: excluded.length })}</span>
+ {' · '}
+ <button
+ type="button"
+ className="font-medium text-foreground hover:underline"
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ >
+ {open ? t('hideExcluded') : t('showExcluded')}
+ </button>
+ {open && (
+ <ul className="mt-2 divide-y rounded-md border">
+ {excluded.map((page) => (
+ <li key={page.key} className="flex items-center gap-3 px-3 py-1.5">
+ <span className="min-w-0 flex-1 truncate text-foreground" title={page.url}>
+ {page.path}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 text-xs"
+ onClick={() => onRestore([page.url])}
+ >
+ {t('restore')}
+ </Button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The Opportunities inbox (SA-004): the brand's pages worth auditing, each
+ * with why, pinned pages first. Pages not being audited can be selected for
+ * the bulk bar (`toolbar`): Audit selected, Pin, Exclude.
+ */
+export function OpportunitiesTable({
+ opportunities,
+ excluded,
+ staleDays,
+ selected,
+ onSelect,
+ onRestore,
+ toolbar,
+}: {
+ opportunities: AuditOpportunity[];
+ excluded: ExcludedPage[];
+ staleDays: number;
+ selected: Set<string>;
+ onSelect: (keys: string[], on: boolean) => void;
+ onRestore: (urls: string[]) => void;
+ toolbar?: ReactNode;
+}) {
+ const t = useTranslations('audit.opportunities');
+ const [shown, setShown] = useState(OPPORTUNITIES_STEP);
+ const rows = opportunities.slice(0, shown);
+ const selectable = rows.filter((r) => !r.running).map((r) => r.key);
+ const ticked = selectable.filter((key) => selected.has(key)).length;
+
+ return (
+ <Card>
+ <CardContent className="py-4">
+ {opportunities.length === 0 ? (
+ <p className="py-6 text-center text-sm text-muted-foreground">
+ {t('empty', { days: staleDays })}
+ </p>
+ ) : (
+ <>
+ {toolbar}
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8 pr-0">
+ <Checkbox
+ aria-label={t('selectAll')}
+ disabled={selectable.length === 0}
+ checked={
+ ticked === 0 ? false : ticked === selectable.length ? true : 'indeterminate'
+ }
+ onCheckedChange={(on) => onSelect(selectable, on === true)}
+ />
+ </TableHead>
+ {/* The page column takes the room left, and long paths truncate in it. */}
+ <TableHead className="w-full">{t('page')}</TableHead>
+ <TableHead>{t('why')}</TableHead>
+ <TableHead className="text-right">{t('aiVisits')}</TableHead>
+ <TableHead>{t('lastAudit')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => (
+ <TableRow
+ key={row.key}
+ data-state={selected.has(row.key) ? 'selected' : undefined}
+ >
+ <TableCell className="w-8 pr-0">
+ <Checkbox
+ aria-label={t('select', { page: row.path })}
+ disabled={row.running}
+ checked={selected.has(row.key)}
+ onCheckedChange={(on) => onSelect([row.key], on === true)}
+ />
+ </TableCell>
+ <TableCell className="max-w-0">
+ <a
+ href={row.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={row.title ?? row.url}
+ className="group inline-flex max-w-full items-center gap-1 font-medium hover:underline"
+ >
+ <span className="truncate">{row.path}</span>
+ <ExternalLink className="h-3 w-3 shrink-0 text-muted-foreground opacity-0 group-hover:opacity-100" />
+ </a>
+ </TableCell>
+ {/* Wide enough for a row of chips; more wrap onto a second line. */}
+ <TableCell className="min-w-[18rem] whitespace-normal">
+ <ReasonChips row={row} />
+ </TableCell>
+ <TableCell className="text-right tabular-nums">
+ {row.aiVisits === null ? '—' : formatNumber(row.aiVisits)}
+ </TableCell>
+ <TableCell className="text-muted-foreground">
+ {row.running ? (
+ <span className="inline-flex items-center gap-1">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {t('running')}
+ </span>
+ ) : row.lastAudit ? (
+ <Link
+ href={`/dashboard/audit/${row.lastAudit.auditId}`}
+ className="hover:underline"
+ >
+ {t('lastAuditValue', {
+ date: formatMonthDay(row.lastAudit.at),
+ score: pct(row.lastAudit.score) ?? '—',
+ })}
+ </Link>
+ ) : (
+ t('never')
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ {opportunities.length > shown && (
+ <div className="flex justify-center pt-3">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShown((n) => n + OPPORTUNITIES_STEP)}
+ >
+ {t('showMore')}
+ </Button>
+ </div>
+ )}
+ </>
+ )}
+ <ExcludedList excluded={excluded} onRestore={onRestore} />
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx
index c8a64c461..fdb37e643 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx
@@ -154,6 +154,7 @@ export function AuditPagesTable({
onSelect,
headerAction,
toolbar,
+ showTitle = true,
}: {
pages: AuditedPage[];
total: number;
@@ -167,6 +168,8 @@ export function AuditPagesTable({
/** Beside the title, e.g. Export. */
headerAction?: ReactNode;
toolbar?: ReactNode;
+ /** Off inside the Pages tab, whose trigger already names the list. */
+ showTitle?: boolean;
}) {
const t = useTranslations('audit');
const router = useRouter();
@@ -188,10 +191,14 @@ export function AuditPagesTable({
return (
<Card>
<CardHeader className="flex flex-row items-center gap-2 space-y-0">
- <CardTitle className="text-base">{t('pages.title')}</CardTitle>
- <span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums text-muted-foreground">
- {formatNumber(total)}
- </span>
+ {showTitle && (
+ <>
+ <CardTitle className="text-base">{t('pages.title')}</CardTitle>
+ <span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums text-muted-foreground">
+ {formatNumber(total)}
+ </span>
+ </>
+ )}
{headerAction && <div className="ml-auto">{headerAction}</div>}
</CardHeader>
<CardContent className="pt-0">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
index fe2552123..f97f2c562 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
@@ -11,32 +11,39 @@ import {
TrendingDown,
AlertCircle,
RefreshCw,
+ Pin,
+ EyeOff,
} from 'lucide-react';
import { useRouter } from '@/i18n/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useBrandStore } from '@/stores/use-brand-store';
import {
runAudit,
runAuditsBulk,
getAuditPages,
getAuditOverview,
+ getAuditOpportunities,
+ setOpportunityPrefs,
getAuditQuota,
getAuditTrend,
deleteAudit,
type AuditedPage,
type AuditOverview,
+ type AuditOpportunities,
type AuditQuota,
type AuditTrend,
} from '@/lib/actions/audits';
import { pct, scoreColor, CATEGORY_META } from '@/components/audit/audit-report';
-import { formatMonthDay } from '@/lib/format';
+import { formatMonthDay, formatNumber } from '@/lib/format';
import { ScoreTrendChart } from './_charts';
import { AuditPagesTable } from './_pages-table';
import { AuditBulkBar, ExportMenu } from './_bulk-bar';
import { AuditOverviewCards } from './_overview-cards';
+import { OpportunitiesTable } from './_opportunities-table';
import { usePagesExport } from './_use-pages-export';
import { cn } from '@/lib/utils';
@@ -53,6 +60,27 @@ async function readOverview(brandId: string): Promise<AuditOverview | null> {
}
}
+/** The Opportunities inbox; its tab is left out when it can't be read. */
+async function readOpportunities(brandId: string): Promise<AuditOpportunities | null> {
+ try {
+ return await getAuditOpportunities(brandId);
+ } catch (err) {
+ console.error('Failed to load the Site Audit opportunities:', err);
+ return null;
+ }
+}
+
+type ListTab = 'opportunities' | 'pages';
+
+/** A tab's count, as the mockup's grey pill. */
+function TabCount({ count }: { count: number }) {
+ return (
+ <span className="rounded-full bg-muted px-1.5 text-[11px] font-medium tabular-nums text-muted-foreground">
+ {formatNumber(count)}
+ </span>
+ );
+}
+
/** While audits run, the Pages list and the quota are read again this often. */
const RUNNING_POLL_MS = 10_000;
@@ -88,6 +116,10 @@ export default function SiteAuditPage() {
const [overview, setOverview] = useState<AuditOverview | null>(null);
const [range, setRange] = useState<RangePreset>('30d');
const [selected, setSelected] = useState<Set<string>>(() => new Set());
+ const [opps, setOpps] = useState<AuditOpportunities | null>(null);
+ const [oppSelected, setOppSelected] = useState<Set<string>>(() => new Set());
+ // Opportunities when it lists pages, else Pages; chosen once per brand.
+ const [tab, setTab] = useState<ListTab | null>(null);
const [startingBulk, setStartingBulk] = useState(false);
const { exporting, exportAll, exportPages } = usePagesExport(activeBrandId);
// Capture "now" once (impure call belongs in a lazy initializer, not render).
@@ -101,15 +133,18 @@ export default function SiteAuditPage() {
let cancelled = false;
setLoading(true);
setError(null);
- // A selection belongs to the brand it was made on.
+ // A selection, and the tab, belong to the brand they were made on.
setSelected(new Set());
+ setOppSelected(new Set());
+ setTab(null);
(async () => {
try {
- const [data, q, tr, ov] = await Promise.all([
+ const [data, q, tr, ov, op] = await Promise.all([
getAuditPages(activeBrandId),
getAuditQuota(),
getAuditTrend(activeBrandId),
readOverview(activeBrandId),
+ readOpportunities(activeBrandId),
]);
if (!cancelled) {
setPages(data.pages);
@@ -118,6 +153,11 @@ export default function SiteAuditPage() {
setQuota(q);
setTrend(tr);
setOverview(ov);
+ setOpps(op);
+ setTab(
+ (current) =>
+ current ?? ((op?.opportunities.length ?? 0) > 0 ? 'opportunities' : 'pages'),
+ );
}
} catch (err) {
console.error('Failed to load audit hub data:', err);
@@ -228,11 +268,12 @@ export default function SiteAuditPage() {
shownRef.current = pages.length;
}, [pages.length]);
const reloadInPlace = async (brandId: string) => {
- const [data, q, tr, ov] = await Promise.all([
+ const [data, q, tr, ov, op] = await Promise.all([
getAuditPages(brandId, 0, Math.min(Math.max(shownRef.current, 50), 100)),
getAuditQuota(),
getAuditTrend(brandId),
readOverview(brandId),
+ readOpportunities(brandId),
]);
setPages(data.pages);
setPagesTotal(data.total);
@@ -240,6 +281,11 @@ export default function SiteAuditPage() {
setQuota(q);
setTrend(tr);
setOverview(ov);
+ setOpps(op);
+ const oppSelectable = new Set(
+ (op?.opportunities ?? []).filter((o) => !o.running).map((o) => o.key),
+ );
+ setOppSelected((prev) => new Set([...prev].filter((key) => oppSelectable.has(key))));
const selectable = new Set(data.pages.filter((p) => p.status !== 'running').map((p) => p.key));
setSelected((prev) => new Set([...prev].filter((key) => selectable.has(key))));
};
@@ -287,7 +333,80 @@ export default function SiteAuditPage() {
};
// While any page is being audited, follow it until its run ends.
- const anyRunning = pages.some((p) => p.status === 'running');
+ const handleOppSelect = (keys: string[], on: boolean) =>
+ setOppSelected((prev) => {
+ const next = new Set(prev);
+ for (const key of keys) {
+ if (on) next.add(key);
+ else next.delete(key);
+ }
+ return next;
+ });
+
+ const selectedOpps = (opps?.opportunities ?? []).filter((o) => oppSelected.has(o.key));
+
+ const handleAuditOpps = async () => {
+ if (!activeBrandId || selectedOpps.length === 0) return;
+ setStartingBulk(true);
+ try {
+ const { started } = await runAuditsBulk(
+ activeBrandId,
+ selectedOpps.map((o) => o.url),
+ );
+ toast.success(t('bulk.started', { count: started }));
+ setOppSelected(new Set());
+ await reloadInPlace(activeBrandId);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : t('failed'));
+ } finally {
+ setStartingBulk(false);
+ }
+ };
+
+ // Pin, exclude or restore pages, then read the inbox again. Excluding can
+ // be undone from its toast.
+ const savePrefs = async (
+ urls: string[],
+ state: 'pinned' | 'excluded' | null,
+ message: string,
+ undo?: () => void,
+ ) => {
+ if (!activeBrandId || urls.length === 0) return;
+ try {
+ await setOpportunityPrefs(activeBrandId, urls, state);
+ setOppSelected(new Set());
+ toast.success(
+ message,
+ undo ? { action: { label: t('opportunities.undo'), onClick: undo } } : undefined,
+ );
+ await reloadInPlace(activeBrandId);
+ } catch (err) {
+ console.error('Failed to update the opportunities:', err);
+ toast.error(t('opportunities.prefsFailed'));
+ }
+ };
+
+ const allPinned = selectedOpps.length > 0 && selectedOpps.every((o) => o.pinned);
+ const handlePin = () => {
+ const urls = selectedOpps.map((o) => o.url);
+ return allPinned
+ ? savePrefs(urls, null, t('opportunities.unpinnedToast', { count: urls.length }))
+ : savePrefs(urls, 'pinned', t('opportunities.pinnedToast', { count: urls.length }));
+ };
+ const handleExclude = () => {
+ const urls = selectedOpps.map((o) => o.url);
+ return savePrefs(
+ urls,
+ 'excluded',
+ t('opportunities.excludedToast', { count: urls.length }),
+ () => void savePrefs(urls, null, t('opportunities.restoredToast', { count: urls.length })),
+ );
+ };
+ const handleRestore = (urls: string[]) =>
+ savePrefs(urls, null, t('opportunities.restoredToast', { count: urls.length }));
+
+ const anyRunning =
+ pages.some((p) => p.status === 'running') || (opps?.opportunities ?? []).some((o) => o.running);
useEffect(() => {
if (!anyRunning || !activeBrandId) return;
const timer = setInterval(() => {
@@ -486,7 +605,9 @@ export default function SiteAuditPage() {
</Button>
</CardContent>
</Card>
- ) : pages.length === 0 ? (
+ ) : pages.length === 0 &&
+ (opps?.opportunities.length ?? 0) === 0 &&
+ (opps?.excluded.length ?? 0) === 0 ? (
<Card>
<CardContent className="flex flex-col items-center gap-2 py-12 text-center">
<Sparkles className="h-7 w-7 text-primary" />
@@ -495,29 +616,97 @@ export default function SiteAuditPage() {
</CardContent>
</Card>
) : (
- <AuditPagesTable
- pages={pages}
- total={pagesTotal}
- primaryHost={primaryHost}
- loadingMore={loadingMore}
- onLoadMore={handleLoadMore}
- onDeleteRun={handleDelete}
- selected={selected}
- onSelect={handleSelect}
- headerAction={<ExportMenu busy={exporting} onExport={exportAll} />}
- toolbar={
- selectedPages.length > 0 && (
- <AuditBulkBar
- count={selectedPages.length}
- quota={quota}
- starting={startingBulk}
- onReaudit={handleBulkReaudit}
- onExport={(format) => exportPages(selectedPages, format)}
- onClear={() => setSelected(new Set())}
+ <Tabs value={tab ?? 'pages'} onValueChange={(v) => setTab(v as ListTab)}>
+ <TabsList variant="line" aria-label={t('lists.label')}>
+ {opps && (
+ <TabsTrigger value="opportunities">
+ {t('lists.opportunities')}
+ <TabCount count={opps.opportunities.length} />
+ </TabsTrigger>
+ )}
+ <TabsTrigger value="pages">
+ {t('lists.pages')}
+ <TabCount count={pagesTotal} />
+ </TabsTrigger>
+ </TabsList>
+ {opps && (
+ <TabsContent value="opportunities" className="mt-3">
+ <OpportunitiesTable
+ opportunities={opps.opportunities}
+ excluded={opps.excluded}
+ staleDays={opps.staleDays}
+ selected={oppSelected}
+ onSelect={handleOppSelect}
+ onRestore={(urls) => void handleRestore(urls)}
+ toolbar={
+ selectedOpps.length > 0 && (
+ <AuditBulkBar
+ count={selectedOpps.length}
+ quota={quota}
+ starting={startingBulk}
+ auditLabel={t('opportunities.auditSelected')}
+ onAudit={handleAuditOpps}
+ onClear={() => setOppSelected(new Set())}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ onClick={() => void handlePin()}
+ >
+ <Pin className="h-3 w-3" />
+ {allPinned ? t('opportunities.unpin') : t('opportunities.pin')}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ onClick={() => void handleExclude()}
+ >
+ <EyeOff className="h-3 w-3" />
+ {t('opportunities.exclude')}
+ </Button>
+ </AuditBulkBar>
+ )
+ }
+ />
+ </TabsContent>
+ )}
+ <TabsContent value="pages" className="mt-3">
+ {pages.length === 0 ? (
+ <Card>
+ <CardContent className="py-8 text-center text-sm text-muted-foreground">
+ {t('lists.noPages')}
+ </CardContent>
+ </Card>
+ ) : (
+ <AuditPagesTable
+ showTitle={false}
+ pages={pages}
+ total={pagesTotal}
+ primaryHost={primaryHost}
+ loadingMore={loadingMore}
+ onLoadMore={handleLoadMore}
+ onDeleteRun={handleDelete}
+ selected={selected}
+ onSelect={handleSelect}
+ headerAction={<ExportMenu busy={exporting} onExport={exportAll} />}
+ toolbar={
+ selectedPages.length > 0 && (
+ <AuditBulkBar
+ count={selectedPages.length}
+ quota={quota}
+ starting={startingBulk}
+ onAudit={handleBulkReaudit}
+ onExport={(format) => exportPages(selectedPages, format)}
+ onClear={() => setSelected(new Set())}
+ />
+ )
+ }
/>
- )
- }
- />
+ )}
+ </TabsContent>
+ </Tabs>
)}
</div>
);
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index a1ae25610..36a26ef2d 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -274,6 +274,91 @@ export async function getAuditOverview(brandId: string): Promise<AuditOverview>
return data.overview;
}
+/** Why a page is in the Opportunities inbox. */
+export type OpportunityReason =
+ | {
+ type: 'no_ai_traffic';
+ signal: 'revenue' | 'transactions' | 'key_events' | 'engagement';
+ /** The page's value percentile within its site (0–100). */
+ percentile: number;
+ citationState: 'cited' | 'targeted_not_cited' | 'not_targeted' | null;
+ }
+ | { type: 'never_audited' }
+ | { type: 'stale_audit'; days: number };
+
+/** A page worth auditing (SA-004). */
+export interface AuditOpportunity {
+ key: string;
+ url: string;
+ path: string;
+ title: string | null;
+ reasons: OpportunityReason[];
+ pinned: boolean;
+ /** An audit of the page is running. */
+ running: boolean;
+ /** AI visits over the last 30 days; null without Analytics or the snippet. */
+ aiVisits: number | null;
+ lastAudit: { at: string; score: number; auditId: string } | null;
+}
+
+export interface ExcludedPage {
+ key: string;
+ url: string;
+ path: string;
+ title: string | null;
+}
+
+export interface AuditOpportunities {
+ opportunities: AuditOpportunity[];
+ excluded: ExcludedPage[];
+ /** An audit older than this many days no longer counts. */
+ staleDays: number;
+}
+
+export async function getAuditOpportunities(brandId: string): Promise<AuditOpportunities> {
+ const session = await getSession();
+
+ const res = await fetch(
+ `${AEO_SERVER_URL}/api/audits/opportunities?brandId=${encodeURIComponent(brandId)}`,
+ { headers: { Authorization: `Bearer ${session.access_token}` } },
+ );
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.message || `Server error: ${res.status}`);
+ }
+
+ const data = await res.json();
+ return {
+ opportunities: data.opportunities ?? [],
+ excluded: data.excluded ?? [],
+ staleDays: data.staleDays ?? 90,
+ };
+}
+
+/** Pin, exclude or (null) clear pages of the Opportunities inbox. */
+export async function setOpportunityPrefs(
+ brandId: string,
+ urls: string[],
+ state: 'pinned' | 'excluded' | null,
+): Promise<void> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/audits/opportunities/prefs`, {
+ method: 'PUT',
+ headers: {
+ Authorization: `Bearer ${session.access_token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ brandId, urls, state }),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.message || `Server error: ${res.status}`);
+ }
+}
+
export interface AuditedPages {
pages: AuditedPage[];
/** Pages audited for the brand, across all pages of the list. */