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): show site score, pages, Authority · E-E-A-T and this month's audits as KPI cards (#1135)

Cihanbba2b50c64a6
diff --git a/server/src/lib/audit/overview.js b/server/src/lib/audit/overview.js
new file mode 100644
index 000000000..ecf75c56c
--- /dev/null
+++ b/server/src/lib/audit/overview.js
@@ -0,0 +1,83 @@
+/**
+ * The Site Audit hub's KPI cards (SA-018): site score, pages audited, and the
+ * Authority and E-E-A-T scores with their biggest gaps. Pure, so the route
+ * only reads rows and this decides what they add up to.
+ *
+ * Everything covers the brand's primary domain, like the Score over time
+ * chart, and each page counts once, through its latest completed audit.
+ */
+
+import { signalsByKey } from './rubric.js';
+
+/** The categories the Authority · E-E-A-T card reads. */
+export const AUTHORITY_CATEGORIES = ['authority', 'eeat'];
+
+/** Gaps listed on the card. */
+export const OVERVIEW_GAPS = 3;
+
+const average = (values) =>
+ values.length === 0 ? null : values.reduce((sum, v) => sum + v, 0) / values.length;
+
+const points = (score) => Math.round(score * 100);
+
+/**
+ * @param {Array<{ host: string|null, auditId: string, score: number|null, previousScore: number|null }>} pages
+ * from buildAuditPages
+ * @param {string|null} primaryHost
+ * @returns {{ own: typeof pages, otherPages: number }} the primary domain's audited pages, and how many
+ * audited pages are on other sites
+ */
+export function primaryPages(pages, primaryHost) {
+ const audited = (pages ?? []).filter((p) => p.score !== null);
+ const own = primaryHost ? audited.filter((p) => p.host === primaryHost) : [];
+ return { own, otherPages: audited.length - own.length };
+}
+
+/**
+ * @param {ReturnType<typeof primaryPages>['own']} own
+ * @param {Map<string, object>} categoryScoresById each latest audit's category_scores
+ * @param {Array<{ audit_id: string, signal_key: string }>} failingRows
+ * failed or warning Authority / E-E-A-T signals of those audits
+ */
+export function buildOverview(own, categoryScoresById, failingRows) {
+ const siteScore = average(own.map((p) => p.score));
+ // Against each page's previous audit; a page audited once counts as unchanged.
+ const withPrevious = own.some((p) => p.previousScore !== null);
+ const previous = average(own.map((p) => p.previousScore ?? p.score));
+ const siteScoreChange =
+ siteScore !== null && withPrevious ? points(siteScore) - points(previous) : null;
+
+ const categoryAverage = (key) =>
+ average(
+ own
+ .map((p) => categoryScoresById.get(p.auditId)?.[key]?.score)
+ .filter((s) => typeof s === 'number'),
+ );
+
+ // Pages per failing signal, each page once.
+ const ownIds = new Set(own.map((p) => p.auditId));
+ const pagesBySignal = new Map();
+ for (const row of failingRows ?? []) {
+ if (!ownIds.has(row.audit_id)) continue;
+ if (!pagesBySignal.has(row.signal_key)) pagesBySignal.set(row.signal_key, new Set());
+ pagesBySignal.get(row.signal_key).add(row.audit_id);
+ }
+ const gaps = [...pagesBySignal.entries()]
+ .map(([key, ids]) => ({
+ key,
+ label: signalsByKey[key]?.label ?? key,
+ category: signalsByKey[key]?.category ?? null,
+ pages: ids.size,
+ }))
+ .sort((a, b) => b.pages - a.pages || a.key.localeCompare(b.key))
+ .slice(0, OVERVIEW_GAPS);
+
+ return {
+ pages: own.length,
+ siteScore,
+ siteScoreChange,
+ authority: categoryAverage('authority'),
+ eeat: categoryAverage('eeat'),
+ gaps,
+ };
+}
diff --git a/server/src/lib/audit/overview.test.js b/server/src/lib/audit/overview.test.js
new file mode 100644
index 000000000..734c10625
--- /dev/null
+++ b/server/src/lib/audit/overview.test.js
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+import { buildOverview, primaryPages, OVERVIEW_GAPS } from './overview.js';
+
+const page = (auditId, score, previousScore = null, host = 'acme.com') => ({
+ auditId,
+ host,
+ score,
+ previousScore,
+});
+
+describe('primaryPages', () => {
+ it('keeps the audited pages of the primary domain and counts the other sites', () => {
+ const { own, otherPages } = primaryPages(
+ [
+ page('a', 0.6),
+ page('b', 0.7, null, 'other.com'),
+ page('c', null), // never completed
+ page('d', 0.8),
+ ],
+ 'acme.com',
+ );
+ expect(own.map((p) => p.auditId)).toEqual(['a', 'd']);
+ expect(otherPages).toBe(1);
+ });
+
+ it('has no own pages without a primary domain', () => {
+ expect(primaryPages([page('a', 0.6)], null)).toEqual({ own: [], otherPages: 1 });
+ });
+});
+
+describe('buildOverview', () => {
+ const scores = new Map([
+ ['a', { authority: { score: 0.4 }, eeat: { score: 0.3 } }],
+ ['b', { authority: { score: 0.36 }, eeat: { score: null } }],
+ ['c', {}],
+ ]);
+
+ it("averages each page's latest audit, and compares with each page's previous one", () => {
+ const overview = buildOverview(
+ [page('a', 0.7, 0.6), page('b', 0.6), page('c', 0.74, 0.7)],
+ scores,
+ [],
+ );
+ expect(overview.pages).toBe(3);
+ expect(overview.siteScore).toBeCloseTo(0.68);
+ // Now 68; before, 63 (60, 60 unchanged and 70: 63.3 rounds to 63) → +5.
+ expect(overview.siteScoreChange).toBe(68 - 63);
+ // Pages without a category score are left out of its average.
+ expect(overview.authority).toBeCloseTo(0.38);
+ expect(overview.eeat).toBeCloseTo(0.3);
+ });
+
+ it('has no change when no page was audited twice, and nothing without pages', () => {
+ expect(buildOverview([page('a', 0.7)], scores, []).siteScoreChange).toBeNull();
+ expect(buildOverview([], scores, [])).toEqual({
+ pages: 0,
+ siteScore: null,
+ siteScoreChange: null,
+ authority: null,
+ eeat: null,
+ gaps: [],
+ });
+ });
+
+ it('lists the signals failing on the most pages, each page once', () => {
+ const rows = [
+ { audit_id: 'a', signal_key: 'author-byline' },
+ { audit_id: 'b', signal_key: 'author-byline' },
+ { audit_id: 'c', signal_key: 'author-byline' },
+ { audit_id: 'a', signal_key: 'press-mentions' },
+ { audit_id: 'b', signal_key: 'press-mentions' },
+ { audit_id: 'a', signal_key: 'quotations' },
+ { audit_id: 'b', signal_key: 'case-study-evidence' },
+ { audit_id: 'a', signal_key: 'byline-depth' },
+ // Another site's audit doesn't count.
+ { audit_id: 'z', signal_key: 'quotations' },
+ ];
+ const { gaps } = buildOverview([page('a', 0.7), page('b', 0.6), page('c', 0.5)], scores, rows);
+ expect(gaps).toHaveLength(OVERVIEW_GAPS);
+ expect(gaps).toEqual([
+ { key: 'author-byline', label: 'Author byline', category: 'authority', pages: 3 },
+ { key: 'press-mentions', label: 'Press mentions', category: 'eeat', pages: 2 },
+ // Ties read in key order.
+ { key: 'byline-depth', label: 'Byline depth', category: 'eeat', pages: 1 },
+ ]);
+ });
+});
diff --git a/server/src/routes/audits-pages.test.js b/server/src/routes/audits-pages.test.js
index 033083109..9d2e5c9ff 100644
--- a/server/src/routes/audits-pages.test.js
+++ b/server/src/routes/audits-pages.test.js
@@ -49,7 +49,9 @@ function query(table) {
inserted.push(...rows);
return resolve({ data: rows, error: null });
}
- if (table === 'site_audits') {
+ if (table === 'site_audits' && filters.in.id) {
+ data = audits.filter((a) => filters.in.id.includes(a.id));
+ } else if (table === 'site_audits') {
data = audits.filter((a) => a.brand_id === filters.eq.brand_id);
if (range) data = data.slice(range[0], range[1] + 1);
} else if (table === 'brand_domains') {
@@ -57,7 +59,10 @@ function query(table) {
} else if (table === 'audit_signal_results') {
signalQueries.push(filters.in.audit_id);
data = signals.filter(
- (s) => filters.in.audit_id.includes(s.audit_id) && filters.in.status.includes(s.status),
+ (s) =>
+ filters.in.audit_id.includes(s.audit_id) &&
+ filters.in.status.includes(s.status) &&
+ (!filters.in.category || filters.in.category.includes(s.category)),
);
}
return resolve({ data, error: null });
@@ -251,3 +256,38 @@ describe('POST /api/audits/bulk', () => {
expect(inserted).toEqual([]);
});
});
+
+describe('GET /api/audits/overview', () => {
+ it("adds up the primary domain's latest audits: score, change, categories and gaps", async () => {
+ audits[0].category_scores = { authority: { score: 0.4 }, eeat: { score: 0.3 } };
+ signals = [
+ { audit_id: 'p2', status: 'fail', category: 'authority', signal_key: 'author-byline' },
+ { audit_id: 'p2', status: 'warn', category: 'eeat', signal_key: 'press-mentions' },
+ { audit_id: 'p2', status: 'fail', category: 'structure', signal_key: 'h1-quality' },
+ // The older audit of the page doesn't count.
+ { audit_id: 'p1', status: 'fail', category: 'eeat', signal_key: 'quotations' },
+ ];
+ const res = await fetch(`${baseUrl}/overview?brandId=b1`);
+ const { overview } = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(overview).toMatchObject({
+ primaryHost: 'acme.com',
+ // acme.com/pricing; other.com/ is another site; /broken never completed.
+ pages: 1,
+ otherPages: 1,
+ siteScore: 0.63,
+ siteScoreChange: 5,
+ authority: 0.4,
+ eeat: 0.3,
+ });
+ expect(overview.gaps.map((g) => [g.key, g.pages])).toEqual([
+ ['author-byline', 1],
+ ['press-mentions', 1],
+ ]);
+ });
+
+ it('needs a brand', async () => {
+ expect((await fetch(`${baseUrl}/overview`)).status).toBe(400);
+ });
+});
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
index 17b86c018..01bd46daf 100644
--- a/server/src/routes/audits.js
+++ b/server/src/routes/audits.js
@@ -33,6 +33,7 @@ import {
TREND_LIMIT,
} from '../lib/audit/history.js';
import { readAllRpcRows } from '../lib/rpc-pages.js';
+import { AUTHORITY_CATEGORIES, buildOverview, primaryPages } from '../lib/audit/overview.js';
import { runSignals } from '../lib/audit/engine.js';
import { evaluateLlmSignals } from '../lib/audit/llm-signals.js';
import { evaluateBrandEntity } from '../lib/audit/external-signals.js';
@@ -96,26 +97,43 @@ async function primaryDomainOf(brandId) {
// 20 audits × 47 signals stays under PostgREST's 1000-row page.
const ISSUE_COUNT_CHUNK = 20;
-/** Failed and warning signals per audit id. */
-async function countIssues(auditIds) {
- const counts = new Map();
- const chunks = [];
- for (let i = 0; i < auditIds.length; i += ISSUE_COUNT_CHUNK) {
- chunks.push(auditIds.slice(i, i + ISSUE_COUNT_CHUNK));
- }
- const results = await Promise.all(
- chunks.map((ids) =>
- supabaseAdmin
- .from('audit_signal_results')
- .select('audit_id')
- .in('audit_id', ids)
- .in('status', ['fail', 'warn']),
- ),
+/** Every audit of the brand, newest first, read past PostgREST's 1000-row page. */
+function readBrandAudits(brandId) {
+ return readAllRpcRows('site_audits', (from, to) =>
+ supabaseAdmin
+ .from('site_audits')
+ .select('id, url, final_url, status, total_score, created_at')
+ .eq('brand_id', brandId)
+ .order('created_at', { ascending: false })
+ .order('id', { ascending: false })
+ .range(from, to),
);
+}
+
+/** Rows for the given audit ids, read a chunk of ids at a time by `query`. */
+async function readByAuditIds(ids, chunkSize, query) {
+ const chunks = [];
+ for (let i = 0; i < ids.length; i += chunkSize) chunks.push(ids.slice(i, i + chunkSize));
+ const results = await Promise.all(chunks.map(query));
+ const rows = [];
for (const { data, error } of results) {
if (error) throw error;
- for (const row of data ?? []) counts.set(row.audit_id, (counts.get(row.audit_id) ?? 0) + 1);
+ rows.push(...(data ?? []));
}
+ return rows;
+}
+
+/** Failed and warning signals per audit id. */
+async function countIssues(auditIds) {
+ const rows = await readByAuditIds(auditIds, ISSUE_COUNT_CHUNK, (ids) =>
+ supabaseAdmin
+ .from('audit_signal_results')
+ .select('audit_id')
+ .in('audit_id', ids)
+ .in('status', ['fail', 'warn']),
+ );
+ const counts = new Map();
+ for (const row of rows) counts.set(row.audit_id, (counts.get(row.audit_id) ?? 0) + 1);
return counts;
}
@@ -450,15 +468,7 @@ router.get('/pages', async (req, res) => {
const [primary, { data: rows, error }] = await Promise.all([
primaryDomainOf(brandId),
- readAllRpcRows('site_audits', (from, to) =>
- supabaseAdmin
- .from('site_audits')
- .select('id, url, final_url, status, total_score, created_at')
- .eq('brand_id', brandId)
- .order('created_at', { ascending: false })
- .order('id', { ascending: false })
- .range(from, to),
- ),
+ readBrandAudits(brandId),
]);
if (error) throw error;
@@ -484,6 +494,63 @@ router.get('/pages', async (req, res) => {
}
});
+// GET /api/audits/overview?brandId=… — the hub's KPI cards: site score and
+// its change, pages audited, and the Authority / E-E-A-T scores with their
+// biggest gaps, over the latest audit of each page on the primary domain.
+// Registered before /:id so "overview" isn't matched as an audit id.
+router.get('/overview', 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, { data: rows, error }] = await Promise.all([
+ primaryDomainOf(brandId),
+ readBrandAudits(brandId),
+ ]);
+ if (error) throw error;
+
+ const primaryHost = normStoredDomain(primary);
+ const { own, otherPages } = primaryPages(buildAuditPages(rows), primaryHost);
+ const ids = own.map((p) => p.auditId);
+
+ const [scoreRows, failingRows] = await Promise.all([
+ readByAuditIds(ids, 100, (chunk) =>
+ supabaseAdmin.from('site_audits').select('id, category_scores').in('id', chunk),
+ ),
+ // 50 audits × 16 Authority and E-E-A-T signals stays under 1000 rows.
+ readByAuditIds(ids, 50, (chunk) =>
+ supabaseAdmin
+ .from('audit_signal_results')
+ .select('audit_id, signal_key')
+ .in('audit_id', chunk)
+ .in('category', AUTHORITY_CATEGORIES)
+ .in('status', ['fail', 'warn']),
+ ),
+ ]);
+ const categoryScoresById = new Map(scoreRows.map((r) => [r.id, r.category_scores ?? {}]));
+
+ return res.json({
+ success: true,
+ overview: {
+ primaryHost,
+ otherPages,
+ ...buildOverview(own, categoryScoresById, failingRows),
+ },
+ });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ req.log.error({ err }, 'audit overview 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/web/messages/en.json b/web/messages/en.json
index a30afceee..3a598cf42 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -2107,6 +2107,30 @@
"failed": "Failed"
}
},
+ "overview": {
+ "yourDomain": "your domain",
+ "siteScore": "Site score",
+ "siteScoreTip": "The average score of each page's latest audit on {domain}. The change compares it with each page's previous audit.",
+ "siteScoreSub": "average of latest audits",
+ "pagesAudited": "Pages audited",
+ "pagesAuditedTip": "Pages of {domain} with a completed audit. Audits of other sites are listed under Pages but left out of these cards.",
+ "pagesSub": "on {domain}",
+ "pagesSubOther": "+ {count} on other sites",
+ "authority": "Authority · E-E-A-T",
+ "authorityTip": "The Authority and E-E-A-T scores, averaged over each page's latest audit, and the signals that fail or warn on the most pages.",
+ "gapsSub": "Top gaps",
+ "noGaps": "No Authority or E-E-A-T gaps",
+ "noPages": "No pages audited yet",
+ "gapPages": "{pages} of {total}",
+ "auditsThisMonth": "Audits this month",
+ "auditsTip": "Your plan's audits this billing month. Audits still running already count; failed ones don't.",
+ "ofLeft": "of {limit} left",
+ "used": "{used} used",
+ "usedRunning": "{used} used · {running} running",
+ "quotaBar": "{used} of {limit} audits used",
+ "unlimited": "Unlimited",
+ "unlimitedSub": "no monthly limit"
+ },
"bulk": {
"toolbar": "Actions for the selected pages",
"selected": "{count} selected",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx
new file mode 100644
index 000000000..fcf5090c4
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx
@@ -0,0 +1,128 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import type { AuditOverview, AuditQuota } from '@/lib/actions/audits';
+import { AuditOverviewCards } from './_overview-cards';
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const overview = (over: Partial<AuditOverview> = {}): AuditOverview => ({
+ primaryHost: 'acme.com',
+ pages: 48,
+ otherPages: 0,
+ siteScore: 0.68,
+ siteScoreChange: 4,
+ authority: 0.38,
+ eeat: 0.36,
+ gaps: [
+ { key: 'author-byline', label: 'Author byline', category: 'authority', pages: 31 },
+ { key: 'press-mentions', label: 'Press mentions', category: 'eeat', pages: 22 },
+ { key: 'case-study-evidence', label: 'Case study evidence', category: 'eeat', pages: 9 },
+ ],
+ ...over,
+});
+
+const growth: AuditQuota = { used: 245, running: 5, limit: 500, remaining: 250 };
+
+let container: HTMLDivElement;
+let root: Root;
+
+function render(data: AuditOverview | null, quota: AuditQuota | null = growth) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <AuditOverviewCards overview={data} quota={quota} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+/** Each card's label, value, change and sub-line, as text. */
+const cards = () =>
+ [...container.querySelectorAll('[data-slot=card]')].map((card) => card.textContent ?? '');
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('AuditOverviewCards', () => {
+ it('shows the four cards of the mockup', () => {
+ render(overview());
+ const [site, pages, authority, audits] = cards();
+
+ expect(site).toContain('Site score');
+ expect(site).toContain('68+4');
+ expect(site).toContain('average of latest audits');
+
+ expect(pages).toContain('Pages audited');
+ expect(pages).toContain('48');
+ expect(pages).toContain('on acme.com');
+
+ expect(authority).toContain('Authority · E-E-A-T');
+ expect(authority).toContain('38 · 36');
+ expect(authority).toContain('Top gaps');
+ const gaps = [...container.querySelectorAll('li')].map((li) => li.textContent);
+ expect(gaps).toEqual([
+ 'Author byline31 of 48',
+ 'Press mentions22 of 48',
+ 'Case study evidence9 of 48',
+ ]);
+
+ expect(audits).toContain('Audits this month');
+ expect(audits).toContain('250of 500 left');
+ expect(audits).toContain('245 used · 5 running');
+ // Running audits fill the bar with the used ones.
+ expect(container.querySelector('[role=img][aria-label]')?.getAttribute('aria-label')).toBe(
+ '250 of 500 audits used',
+ );
+ });
+
+ it('counts the pages on other sites apart, and says when there are no gaps or pages', () => {
+ render(overview({ otherPages: 3, gaps: [] }));
+ expect(cards()[1]).toContain('+ 3 on other sites');
+ expect(cards()[2]).toContain('No Authority or E-E-A-T gaps');
+
+ render(
+ overview({
+ primaryHost: null,
+ pages: 0,
+ siteScore: null,
+ siteScoreChange: null,
+ authority: null,
+ eeat: null,
+ gaps: [],
+ }),
+ );
+ expect(cards()[0]).toContain('—');
+ expect(cards()[1]).toContain('on your domain');
+ expect(cards()[2]).toContain('— · —');
+ expect(cards()[2]).toContain('No pages audited yet');
+ });
+
+ it('shows an unlimited plan without a bar', () => {
+ render(overview(), { used: 0, running: 0, limit: -1, remaining: -1 });
+ expect(cards()[3]).toContain('Unlimited');
+ expect(cards()[3]).toContain('no monthly limit');
+ expect(cards()[3]).not.toContain('left');
+ });
+
+ it('holds the cards with placeholders while loading', () => {
+ render(null);
+ expect(container.querySelectorAll('[data-slot=card]')).toHaveLength(4);
+ expect(container.querySelectorAll('[data-slot=skeleton]').length).toBeGreaterThan(0);
+ expect(container.textContent).toBe('');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx
new file mode 100644
index 000000000..b55cad814
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { CalendarDays, FileText, Gauge, ShieldCheck } from 'lucide-react';
+import { Card } from '@/components/ui/card';
+import { Skeleton } from '@/components/ui/skeleton';
+import { pct } from '@/components/audit/audit-report';
+import type { AuditOverview, AuditQuota } from '@/lib/actions/audits';
+import { formatNumber } from '@/lib/format';
+import { MetricCard } from '../insights/_kpi-cards';
+import { upIsGood } from '../insights/kpi-format';
+
+/** The Authority · E-E-A-T card's gaps: the signal, and on how many pages it fails. */
+function GapList({ overview }: { overview: AuditOverview }) {
+ const t = useTranslations('audit.overview');
+ if (overview.gaps.length === 0) return <div className="h-6" aria-hidden />;
+ return (
+ <ul className="space-y-0.5 pb-0.5 text-xs">
+ {overview.gaps.map((gap) => (
+ <li key={gap.key} className="flex items-baseline justify-between gap-2">
+ <span className="truncate">{gap.label}</span>
+ <span className="shrink-0 tabular-nums text-muted-foreground">
+ {t('gapPages', { pages: gap.pages, total: overview.pages })}
+ </span>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+// Four in a row from 1,200px, two below, one on a phone (spec §4.5). In rem,
+// so Tailwind orders it after sm: (a px breakpoint would sort before it).
+const GRID = 'grid grid-cols-1 gap-3 sm:grid-cols-2 min-[75rem]:grid-cols-4';
+
+/**
+ * The Site Audit hub's KPI cards (SA-018), as in the v2 mockup: site score,
+ * pages audited, Authority · E-E-A-T with its biggest gaps, and this month's
+ * audits. The numbers cover the latest audit of each page on the primary
+ * domain.
+ */
+export function AuditOverviewCards({
+ overview,
+ quota,
+}: {
+ overview: AuditOverview | null;
+ quota: AuditQuota | null;
+}) {
+ const t = useTranslations('audit.overview');
+
+ if (!overview) {
+ return (
+ <div className={GRID}>
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Card key={i} className="gap-3 rounded-xl px-4 py-3.5">
+ <Skeleton className="h-3 w-24" />
+ <Skeleton className="h-7 w-16" />
+ <Skeleton className="h-3 w-32" />
+ </Card>
+ ))}
+ </div>
+ );
+ }
+
+ const domain = overview.primaryHost ?? t('yourDomain');
+ const limited = quota !== null && quota.limit !== -1;
+ const running = quota?.running ?? 0;
+ const gapsSub =
+ overview.pages === 0 ? t('noPages') : overview.gaps.length > 0 ? t('gapsSub') : t('noGaps');
+
+ return (
+ <div className={GRID}>
+ <MetricCard
+ label={t('siteScore')}
+ tooltip={t('siteScoreTip', { domain })}
+ icon={Gauge}
+ value={pct(overview.siteScore)?.toString() ?? '—'}
+ delta={upIsGood(overview.siteScoreChange)}
+ sub={t('siteScoreSub')}
+ />
+ <MetricCard
+ label={t('pagesAudited')}
+ tooltip={t('pagesAuditedTip', { domain })}
+ icon={FileText}
+ value={formatNumber(overview.pages)}
+ sub={
+ overview.otherPages > 0
+ ? t('pagesSubOther', { count: overview.otherPages })
+ : t('pagesSub', { domain })
+ }
+ />
+ <MetricCard
+ label={t('authority')}
+ tooltip={t('authorityTip')}
+ icon={ShieldCheck}
+ value={`${pct(overview.authority) ?? '—'} · ${pct(overview.eeat) ?? '—'}`}
+ sub={gapsSub}
+ footer={<GapList overview={overview} />}
+ />
+ <MetricCard
+ label={t('auditsThisMonth')}
+ tooltip={t('auditsTip')}
+ icon={CalendarDays}
+ value={limited ? formatNumber(quota.remaining) : t('unlimited')}
+ delta={
+ limited
+ ? { text: t('ofLeft', { limit: formatNumber(quota.limit) }), tone: 'neutral' }
+ : null
+ }
+ sub={
+ !quota
+ ? ''
+ : !limited
+ ? t('unlimitedSub')
+ : running > 0
+ ? t('usedRunning', { used: quota.used, running })
+ : t('used', { used: quota.used })
+ }
+ quota={
+ limited
+ ? {
+ used: quota.used + running,
+ limit: quota.limit,
+ label: t('quotaBar', { used: quota.used + running, limit: quota.limit }),
+ }
+ : null
+ }
+ />
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
index 8073460ef..fe2552123 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
@@ -22,10 +22,12 @@ import {
runAudit,
runAuditsBulk,
getAuditPages,
+ getAuditOverview,
getAuditQuota,
getAuditTrend,
deleteAudit,
type AuditedPage,
+ type AuditOverview,
type AuditQuota,
type AuditTrend,
} from '@/lib/actions/audits';
@@ -34,12 +36,23 @@ import { formatMonthDay } from '@/lib/format';
import { ScoreTrendChart } from './_charts';
import { AuditPagesTable } from './_pages-table';
import { AuditBulkBar, ExportMenu } from './_bulk-bar';
+import { AuditOverviewCards } from './_overview-cards';
import { usePagesExport } from './_use-pages-export';
import { cn } from '@/lib/utils';
type RangePreset = '7d' | '30d' | '90d' | 'all';
const RANGE_DAYS: Record<RangePreset, number | null> = { '7d': 7, '30d': 30, '90d': 90, all: null };
+/** The KPI cards' numbers; the cards are left out when they can't be read. */
+async function readOverview(brandId: string): Promise<AuditOverview | null> {
+ try {
+ return await getAuditOverview(brandId);
+ } catch (err) {
+ console.error('Failed to load the Site Audit overview:', err);
+ return null;
+ }
+}
+
/** While audits run, the Pages list and the quota are read again this often. */
const RUNNING_POLL_MS = 10_000;
@@ -72,6 +85,7 @@ export default function SiteAuditPage() {
const [loadingMore, setLoadingMore] = useState(false);
const [quota, setQuota] = useState<AuditQuota | null>(null);
const [trend, setTrend] = useState<AuditTrend | null>(null);
+ const [overview, setOverview] = useState<AuditOverview | null>(null);
const [range, setRange] = useState<RangePreset>('30d');
const [selected, setSelected] = useState<Set<string>>(() => new Set());
const [startingBulk, setStartingBulk] = useState(false);
@@ -91,10 +105,11 @@ export default function SiteAuditPage() {
setSelected(new Set());
(async () => {
try {
- const [data, q, tr] = await Promise.all([
+ const [data, q, tr, ov] = await Promise.all([
getAuditPages(activeBrandId),
getAuditQuota(),
getAuditTrend(activeBrandId),
+ readOverview(activeBrandId),
]);
if (!cancelled) {
setPages(data.pages);
@@ -102,6 +117,7 @@ export default function SiteAuditPage() {
setPrimaryHost(data.primaryHost);
setQuota(q);
setTrend(tr);
+ setOverview(ov);
}
} catch (err) {
console.error('Failed to load audit hub data:', err);
@@ -212,16 +228,18 @@ export default function SiteAuditPage() {
shownRef.current = pages.length;
}, [pages.length]);
const reloadInPlace = async (brandId: string) => {
- const [data, q, tr] = await Promise.all([
+ const [data, q, tr, ov] = await Promise.all([
getAuditPages(brandId, 0, Math.min(Math.max(shownRef.current, 50), 100)),
getAuditQuota(),
getAuditTrend(brandId),
+ readOverview(brandId),
]);
setPages(data.pages);
setPagesTotal(data.total);
setPrimaryHost(data.primaryHost);
setQuota(q);
setTrend(tr);
+ setOverview(ov);
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))));
};
@@ -295,6 +313,47 @@ export default function SiteAuditPage() {
<p className="text-sm text-muted-foreground">{t('description')}</p>
</div>
+ {/* Run bar */}
+ <Card>
+ <CardContent className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center">
+ <Input
+ type="url"
+ inputMode="url"
+ placeholder="https://example.com/page"
+ aria-label="Website URL"
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && !running && !quotaExhausted && handleRun()}
+ disabled={running}
+ className="flex-1"
+ />
+ {/* The Audits this month card shows what's left; here only why Run is off. */}
+ {quotaExhausted && (
+ <span className="shrink-0 text-xs tabular-nums text-destructive">
+ {quota.remaining}/{quota.limit} {t('auditsLeft')}
+ </span>
+ )}
+ <Button onClick={handleRun} disabled={running || quotaExhausted} className="shrink-0">
+ {running ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ {t('running')}
+ </>
+ ) : (
+ <>
+ <Search className="mr-2 h-4 w-4" />
+ {t('runAudit')}
+ </>
+ )}
+ </Button>
+ </CardContent>
+ </Card>
+
+ {/* KPI cards, as in the v2 mockup (SA-018) */}
+ {(loading || overview) && (
+ <AuditOverviewCards overview={loading ? null : overview} quota={quota} />
+ )}
+
{/* Primary-domain score trend + category breakdown */}
{trend && trend.points.length > 0 && (
<Card>
@@ -398,46 +457,6 @@ export default function SiteAuditPage() {
</Card>
)}
- {/* Run bar */}
- <Card>
- <CardContent className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center">
- <Input
- type="url"
- inputMode="url"
- placeholder="https://example.com/page"
- aria-label="Website URL"
- value={url}
- onChange={(e) => setUrl(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && !running && !quotaExhausted && handleRun()}
- disabled={running}
- className="flex-1"
- />
- {quota && quota.limit !== -1 && (
- <span
- className={cn(
- 'shrink-0 text-xs tabular-nums',
- quotaExhausted ? 'text-destructive' : 'text-muted-foreground',
- )}
- >
- {quota.remaining}/{quota.limit} {t('auditsLeft')}
- </span>
- )}
- <Button onClick={handleRun} disabled={running || quotaExhausted} className="shrink-0">
- {running ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- {t('running')}
- </>
- ) : (
- <>
- <Search className="mr-2 h-4 w-4" />
- {t('runAudit')}
- </>
- )}
- </Button>
- </CardContent>
- </Card>
-
{loading ? (
<Card>
<CardHeader>
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index d938501cc..a1ae25610 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -233,6 +233,47 @@ export async function runAuditsBulk(brandId: string, urls: string[]): Promise<{
return { started: (data.audits ?? []).length };
}
+/** One of the most common Authority / E-E-A-T gaps across the audited pages. */
+export interface AuditGap {
+ key: string;
+ label: string;
+ category: string | null;
+ /** Pages whose latest audit fails or warns on it. */
+ pages: number;
+}
+
+/** The hub's KPI cards, over the latest audit of each page on the primary domain. */
+export interface AuditOverview {
+ primaryHost: string | null;
+ /** Audited pages on the primary domain. */
+ pages: number;
+ /** Audited pages on other sites, left out of the numbers. */
+ otherPages: number;
+ siteScore: number | null;
+ /** Points against each page's previous audit; null when none was audited twice. */
+ siteScoreChange: number | null;
+ authority: number | null;
+ eeat: number | null;
+ gaps: AuditGap[];
+}
+
+export async function getAuditOverview(brandId: string): Promise<AuditOverview> {
+ const session = await getSession();
+
+ const res = await fetch(
+ `${AEO_SERVER_URL}/api/audits/overview?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 data.overview;
+}
+
export interface AuditedPages {
pages: AuditedPage[];
/** Pages audited for the brand, across all pages of the list. */