Skip to content

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

feat(traffic): e-mail a weekly AI Traffic digest with the summary line and the top three changes (#1196)

Cihan28a153c92982
diff --git a/server/src/lib/email.js b/server/src/lib/email.js
index 164a99d4a..2444d1e70 100644
--- a/server/src/lib/email.js
+++ b/server/src/lib/email.js
@@ -2,13 +2,18 @@ import { logger } from './logger.js';
/**
* Send one email through the Resend HTTP API (RESEND_API_KEY,
- * RESEND_FROM_EMAIL). Returns true when accepted. Missing config is a silent
- * no-op, so self-host and misconfigured environments never fail a caller.
+ * RESEND_FROM_EMAIL) and say what became of it:
+ * - 'sent': Resend accepted it;
+ * - 'refused': Resend answered with an error, so nothing went out;
+ * - 'unknown': no answer (the 15 s timeout, a dropped connection), and
+ * Resend may have sent it all the same;
+ * - 'skipped': not configured or no recipients. Missing config is a silent
+ * no-op, so self-host and misconfigured environments never fail a caller.
*/
-export async function sendEmail({ to, subject, html, headers }) {
+export async function deliverEmail({ to, subject, html, headers }) {
const apiKey = process.env.RESEND_API_KEY;
const from = process.env.RESEND_FROM_EMAIL;
- if (!apiKey || !from || !to.length) return false;
+ if (!apiKey || !from || !to.length) return 'skipped';
try {
const res = await fetch('https://api.resend.com/emails', {
@@ -23,11 +28,16 @@ export async function sendEmail({ to, subject, html, headers }) {
if (!res.ok) {
const body = await res.text().catch(() => '');
logger.warn({ status: res.status, body: body.slice(0, 500) }, 'resend send failed');
- return false;
+ return 'refused';
}
- return true;
+ return 'sent';
} catch (err) {
logger.warn({ err }, 'resend send errored');
- return false;
+ return 'unknown';
}
}
+
+/** deliverEmail as a yes or no: true when Resend accepted it. */
+export async function sendEmail(message) {
+ return (await deliverEmail(message)) === 'sent';
+}
diff --git a/server/src/lib/email.test.js b/server/src/lib/email.test.js
new file mode 100644
index 000000000..5119b46e2
--- /dev/null
+++ b/server/src/lib/email.test.js
@@ -0,0 +1,56 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Resend's answer, told apart: accepted, refused (nothing went out), or no
+ * answer at all (it may have gone out), and nothing to do without config.
+ */
+
+vi.mock('./logger.js', () => ({ logger: { warn: vi.fn() } }));
+
+const { deliverEmail, sendEmail } = await import('./email.js');
+
+const message = { to: ['[email protected]'], subject: 'Hi', html: '<p>Hi</p>' };
+const answer = (status, body = '{}') => ({ ok: status < 300, status, text: async () => body });
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ vi.stubEnv('RESEND_API_KEY', 're_test');
+ vi.stubEnv('RESEND_FROM_EMAIL', 'Ansvisor <[email protected]>');
+ vi.stubGlobal('fetch', fetchMock);
+ fetchMock.mockReset();
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+});
+
+describe('deliverEmail', () => {
+ it('says sent when Resend accepts it, and refused when it answers with an error', async () => {
+ fetchMock.mockResolvedValueOnce(answer(200, '{"id":"e1"}'));
+ expect(await deliverEmail(message)).toBe('sent');
+ fetchMock.mockResolvedValueOnce(answer(422, '{"message":"invalid"}'));
+ expect(await deliverEmail(message)).toBe('refused');
+ });
+
+ it('says unknown when no answer came: a timeout or a dropped connection', async () => {
+ fetchMock.mockRejectedValueOnce(Object.assign(new Error('aborted'), { name: 'TimeoutError' }));
+ expect(await deliverEmail(message)).toBe('unknown');
+ });
+
+ it('skips without config or recipients', async () => {
+ expect(await deliverEmail({ ...message, to: [] })).toBe('skipped');
+ vi.stubEnv('RESEND_API_KEY', '');
+ expect(await deliverEmail(message)).toBe('skipped');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('sendEmail', () => {
+ it('is true only when Resend accepted it', async () => {
+ fetchMock.mockResolvedValueOnce(answer(200));
+ expect(await sendEmail(message)).toBe(true);
+ fetchMock.mockRejectedValueOnce(new Error('socket hang up'));
+ expect(await sendEmail(message)).toBe(false);
+ });
+});
diff --git a/server/src/lib/pulse/engine.js b/server/src/lib/pulse/engine.js
index bd9c32b4f..f4af37111 100644
--- a/server/src/lib/pulse/engine.js
+++ b/server/src/lib/pulse/engine.js
@@ -22,7 +22,7 @@ const WEEKLY_SEND_UTC_DAY = 1; // Monday
let warnedAppUrlPath = false;
-function appUrl() {
+export function appUrl() {
const raw = process.env.PUBLIC_APP_URL || 'http://localhost:3000';
try {
const url = new URL(raw);
@@ -39,8 +39,9 @@ function appUrl() {
}
}
-/** Recipient emails: explicit list from settings, else every org member. */
-async function resolveRecipients(organizationId, settings) {
+/** Recipient emails: explicit list from settings, else every org member.
+ * The AI Traffic weekly digest (AT-013) sends to the same people. */
+export async function resolveRecipients(organizationId, settings) {
if (settings?.recipients?.length) return settings.recipients;
const { data: members } = await supabaseAdmin
diff --git a/server/src/lib/traffic-digest/email.js b/server/src/lib/traffic-digest/email.js
new file mode 100644
index 000000000..8a3c87ac5
--- /dev/null
+++ b/server/src/lib/traffic-digest/email.js
@@ -0,0 +1,249 @@
+import { deliverEmail } from '../email.js';
+import { changeText, platformName } from './summary.js';
+
+/**
+ * The AI Traffic weekly digest as an e-mail (AT-013, spec §3.8): the week's
+ * summary line and its top three changes, laid out with the page's numbers
+ * — three cards, the visits by day, the platforms — and a way to the AI
+ * Traffic page and to the notification settings. English, like the Daily
+ * Pulse.
+ *
+ * Built for mail clients: tables and inline styles only, no images or
+ * scripts, so it reads the same in Gmail, Apple Mail and Outlook. A full
+ * document that declares UTF-8 itself, whatever the client assumes.
+ *
+ * In the brand's colors and type (the style guide the product follows):
+ * warm neutrals, Geist where the client loads it, pill buttons. Red, green
+ * and amber only say what a change was.
+ */
+
+const INK = '#1C1A17';
+const MUTED = '#464442';
+const SAND = '#F0EEEA';
+const LINE = '#EBE6DE';
+const WHITE = '#FFFFFF';
+// What a change was: up, down, needs a fix — each on a tint of itself.
+const UP = '#067647';
+const UP_TINT = '#ECFDF3';
+const DOWN = '#B42318';
+const DOWN_TINT = '#FEF3F2';
+const WARN = '#B54708';
+const WARN_TINT = '#FFFAEB';
+const FONT = "Geist,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";
+
+function escapeHtml(value) {
+ return String(value ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+const formatNumber = (value) => Math.round(value).toLocaleString('en-US');
+
+/** "Oct 12", or "Mon": calendar days in UTC, so written in UTC. */
+function day(isoDay, options = { month: 'short', day: 'numeric' }) {
+ return new Date(`${isoDay}T00:00:00Z`).toLocaleDateString('en-US', {
+ ...options,
+ timeZone: 'UTC',
+ });
+}
+
+/** Each change's mark: a broken link, a first, a rise or a fall. */
+function changeMark(change) {
+ if (change.type === 'broken') return { symbol: '!', color: WARN, background: WARN_TINT };
+ if (change.before === 0) return { symbol: '✦', color: UP, background: UP_TINT };
+ return change.now > change.before
+ ? { symbol: '▲', color: UP, background: UP_TINT }
+ : { symbol: '▼', color: DOWN, background: DOWN_TINT };
+}
+
+function card(label, value, sub, subColor = MUTED) {
+ return `<td class="stack" width="33%" valign="top" style="padding:0 4px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid ${LINE};border-radius:12px;">
+ <tr><td style="padding:14px 14px 12px 14px;">
+ <div style="font-size:11px;font-weight:500;letter-spacing:0.06em;text-transform:uppercase;color:${MUTED};">${escapeHtml(label)}</div>
+ <div style="font-size:26px;font-weight:500;letter-spacing:-0.03em;color:${INK};margin:6px 0 2px 0;line-height:1.2;">${escapeHtml(value)}</div>
+ <div style="font-size:12px;color:${subColor};">${escapeHtml(sub)}</div>
+ </td></tr>
+ </table>
+ </td>`;
+}
+
+function cards({ visits, prevVisits, change, platforms, share, citedNotClicked }) {
+ const visitsSub =
+ change !== null
+ ? `${change > 0 ? '▲' : '▼'} ${Math.abs(change)}% on the week before`
+ : prevVisits > 0
+ ? `${formatNumber(prevVisits)} the week before`
+ : 'none the week before';
+ const visitsColor = change === null ? MUTED : change > 0 ? UP : DOWN;
+ const top = platforms[0];
+ const third = share
+ ? card('Share of traffic', share, 'of all sessions in Analytics')
+ : card(
+ 'Cited, not clicked',
+ formatNumber(citedNotClicked),
+ citedNotClicked === 1 ? 'page AI answers cite' : 'pages AI answers cite',
+ );
+ return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 -4px 20px -4px;">
+ <tr>
+ ${card('AI visits', formatNumber(visits), visitsSub, visitsColor)}
+ ${card(
+ 'Top platform',
+ top ? platformName(top.platform) : '—',
+ top
+ ? `${formatNumber(top.visits)} ${top.visits === 1 ? 'visit' : 'visits'}`
+ : 'no AI visits',
+ )}
+ ${third}
+ </tr>
+ </table>`;
+}
+
+function section(title, body) {
+ return `<div style="font-size:15px;font-weight:500;letter-spacing:-0.01em;color:${INK};margin:26px 0 10px 0;">${escapeHtml(title)}</div>${body}`;
+}
+
+/** Seven columns, one a day, as tall as its share of the busiest day. */
+function dayBars(days) {
+ const max = Math.max(1, ...days.map((d) => d.visits));
+ const height = 72;
+ const columns = days
+ .map((d) => {
+ const bar = d.visits > 0 ? Math.max(4, Math.round((d.visits / max) * height)) : 3;
+ return `<td align="center" valign="bottom" style="padding:0 3px;">
+ <div style="font-size:11px;color:${MUTED};margin-bottom:4px;">${d.visits > 0 ? formatNumber(d.visits) : ''}</div>
+ <div style="width:70%;max-width:28px;height:${bar}px;line-height:${bar}px;font-size:0;background:${d.visits > 0 ? INK : LINE};border-radius:6px 6px 0 0;margin:0 auto;">&nbsp;</div>
+ </td>`;
+ })
+ .join('');
+ const labels = days
+ .map(
+ (d) =>
+ `<td align="center" style="padding:6px 3px 0 3px;font-size:11px;color:${MUTED};">${escapeHtml(day(d.day, { weekday: 'short' }))}</td>`,
+ )
+ .join('');
+ return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-bottom:1px solid ${LINE};">
+ <tr style="height:${height + 20}px;">${columns}</tr>
+ </table>
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr>${labels}</tr></table>`;
+}
+
+/** A row a platform: its name, a bar as long as its share of the top one, its visits. */
+function platformBars(platforms) {
+ const max = Math.max(1, ...platforms.map((p) => p.visits));
+ return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0">${platforms
+ .map((p) => {
+ const pct = Math.max(2, Math.round((p.visits / max) * 100));
+ return `<tr>
+ <td width="110" style="padding:5px 10px 5px 0;font-size:13px;color:${INK};white-space:nowrap;">
+ ${escapeHtml(platformName(p.platform))}
+ </td>
+ <td style="padding:5px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${SAND};border-radius:4px;">
+ <tr><td width="${pct}%" style="height:8px;line-height:8px;font-size:0;background:${INK};border-radius:4px;">&nbsp;</td><td style="font-size:0;">&nbsp;</td></tr>
+ </table>
+ </td>
+ <td width="48" align="right" style="padding:5px 0 5px 10px;font-size:13px;font-weight:600;color:${INK};">${formatNumber(p.visits)}</td>
+ </tr>`;
+ })
+ .join('')}</table>`;
+}
+
+function changeRows(changes) {
+ return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0">${changes
+ .map((c) => {
+ const mark = changeMark(c);
+ return `<tr>
+ <td width="34" valign="top" style="padding:6px 0;">
+ <div style="width:24px;height:24px;line-height:24px;border-radius:12px;text-align:center;font-size:12px;font-weight:600;color:${mark.color};background:${mark.background};">${mark.symbol}</div>
+ </td>
+ <td valign="top" style="padding:8px 0 6px 0;font-size:14px;line-height:1.5;color:${INK};">${escapeHtml(changeText(c))}</td>
+ </tr>`;
+ })
+ .join('')}</table>`;
+}
+
+/**
+ * @param {{ brandName: string, week: { firstDay: string, lastDay: string },
+ * visits: number, prevVisits?: number, change: number | null, sentences: string[],
+ * changes: object[], share?: string | null, citedNotClicked?: number,
+ * platforms?: { platform: string, visits: number }[], days?: { day: string, visits: number }[],
+ * trafficUrl: string, settingsUrl: string }} digest
+ * @returns {{ subject: string, html: string }}
+ */
+export function renderTrafficDigestEmail({
+ brandName,
+ week,
+ visits,
+ prevVisits = 0,
+ change,
+ sentences,
+ changes,
+ share = null,
+ citedNotClicked = 0,
+ platforms = [],
+ days = [],
+ trafficUrl,
+ settingsUrl,
+}) {
+ const range = `${day(week.firstDay)} – ${day(week.lastDay)}`;
+ const count = `${formatNumber(visits)} AI ${visits === 1 ? 'visit' : 'visits'}`;
+ const pct = change === null ? '' : ` (${change > 0 ? '+' : '−'}${Math.abs(change)}%)`;
+ const subject = `${brandName} AI traffic last week: ${count}${pct}`;
+
+ const html = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>${escapeHtml(subject)}</title>
+<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600&display=swap" rel="stylesheet">
+<style>
+ /* Phones: the cards stack and the margins narrow. Clients that ignore
+ this (Outlook) keep the three columns. */
+ @media (max-width: 480px) {
+ .stack { display: block !important; width: 100% !important; padding: 0 0 8px 0 !important; }
+ .pad { padding-left: 18px !important; padding-right: 18px !important; }
+ }
+</style>
+</head>
+<body style="margin:0;padding:0;background:${SAND};">
+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${SAND};">
+<tr><td align="center" style="padding:24px 12px;">
+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;background:${WHITE};border:1px solid ${LINE};border-radius:16px;overflow:hidden;font-family:${FONT};">
+ <tr><td class="pad" style="background:${INK};padding:26px 28px;">
+ <div style="font-size:11px;font-weight:500;letter-spacing:0.14em;text-transform:uppercase;color:${LINE};">Ansvisor · AI Traffic weekly</div>
+ <div style="font-size:26px;font-weight:500;letter-spacing:-0.03em;color:${WHITE};margin:8px 0 4px 0;">${escapeHtml(brandName)}</div>
+ <div style="font-size:14px;color:${SAND};opacity:0.8;">Visits from AI assistants to your site, ${escapeHtml(range)}</div>
+ </td></tr>
+ <tr><td class="pad" style="padding:24px 28px 8px 28px;">
+ ${cards({ visits, prevVisits, change, platforms, share, citedNotClicked })}
+ <div style="background:${SAND};border-radius:12px;padding:16px 18px;font-size:15px;line-height:1.6;color:${INK};">${escapeHtml(sentences.join(' '))}</div>
+ ${days.length ? section('AI visits by day', dayBars(days)) : ''}
+ ${platforms.length ? section('By platform', platformBars(platforms)) : ''}
+ ${changes.length ? section('Top changes', changeRows(changes)) : ''}
+ <table role="presentation" cellpadding="0" cellspacing="0" style="margin:28px 0 8px 0;">
+ <tr><td style="background:${INK};border-radius:100px;">
+ <a href="${escapeHtml(trafficUrl)}" style="display:inline-block;padding:12px 28px;font-size:15px;font-weight:500;color:${WHITE};text-decoration:none;border-radius:100px;">Open AI Traffic →</a>
+ </td></tr>
+ </table>
+ </td></tr>
+ <tr><td class="pad" style="padding:18px 28px 24px 28px;border-top:1px solid ${LINE};font-size:12px;line-height:1.6;color:${MUTED};">
+ You're receiving this because the AI Traffic weekly digest is on for ${escapeHtml(brandName)}.
+ <a href="${escapeHtml(settingsUrl)}" style="color:${INK};">Manage notification settings</a>
+ </td></tr>
+</table>
+</td></tr>
+</table>
+</body>
+</html>`;
+
+ return { subject, html };
+}
+
+/** Sends through the Resend HTTP API: 'sent', 'refused', 'unknown' or 'skipped' (deliverEmail). */
+export function sendTrafficDigestEmail({ to, subject, html, settingsUrl }) {
+ return deliverEmail({ to, subject, html, headers: { 'List-Unsubscribe': `<${settingsUrl}>` } });
+}
diff --git a/server/src/lib/traffic-digest/email.test.js b/server/src/lib/traffic-digest/email.test.js
new file mode 100644
index 000000000..56254e088
--- /dev/null
+++ b/server/src/lib/traffic-digest/email.test.js
@@ -0,0 +1,100 @@
+import { describe, expect, it } from 'vitest';
+import { renderTrafficDigestEmail } from './email.js';
+
+/** The AI Traffic weekly digest's e-mail (AT-013). */
+
+const digest = (over = {}) =>
+ renderTrafficDigestEmail({
+ brandName: 'Acme <Coffee>',
+ week: { firstDay: '2026-10-12', lastDay: '2026-10-18' },
+ visits: 42,
+ change: -30,
+ sentences: ['Last week: 42 AI-referred visits, down 30% on the week before.'],
+ changes: [{ type: 'platform', name: 'chatgpt.com', before: 30, now: 12 }],
+ prevVisits: 60,
+ share: null,
+ citedNotClicked: 3,
+ platforms: [
+ { platform: 'chatgpt.com', visits: 30 },
+ { platform: 'perplexity.ai', visits: 12 },
+ ],
+ days: [
+ { day: '2026-10-12', visits: 4 },
+ { day: '2026-10-13', visits: 0 },
+ { day: '2026-10-14', visits: 8 },
+ { day: '2026-10-15', visits: 6 },
+ { day: '2026-10-16', visits: 6 },
+ { day: '2026-10-17', visits: 10 },
+ { day: '2026-10-18', visits: 8 },
+ ],
+ trafficUrl: 'https://app.example.com/dashboard/traffic',
+ settingsUrl: 'https://app.example.com/dashboard/settings?tab=notifications',
+ ...over,
+ });
+
+describe('renderTrafficDigestEmail', () => {
+ it('leads with the visits and their change, then the summary line and the top changes', () => {
+ const { subject, html } = digest();
+ expect(subject).toBe('Acme <Coffee> AI traffic last week: 42 AI visits (−30%)');
+ // A whole document that says its own charset, whatever the client assumes.
+ expect(html.startsWith('<!doctype html>')).toBe(true);
+ expect(html).toContain('<meta charset="utf-8">');
+ expect(html).toContain('Acme &lt;Coffee&gt;');
+ expect(html).toContain('Oct 12 – Oct 18');
+ expect(html).toContain('Last week: 42 AI-referred visits, down 30% on the week before.');
+ expect(html).toContain('Top changes');
+ expect(html).toContain('ChatGPT sent 12 AI visits, down from 30.');
+ expect(html).toContain('href="https://app.example.com/dashboard/traffic"');
+ expect(html).toContain('href="https://app.example.com/dashboard/settings?tab=notifications"');
+ // Nothing the brand typed reaches the HTML unescaped.
+ expect(html).not.toContain('<Coffee>');
+ });
+
+ it('shows the cards, the visits by day and the platforms, in the brand colors', () => {
+ const { html } = digest();
+ // AI visits with its change; the top platform; cited-not-clicked without Analytics.
+ expect(html).toContain('▼ 30% on the week before');
+ expect(html).toContain('>ChatGPT</div>');
+ expect(html).toContain('Cited, not clicked');
+ expect(html).not.toContain('Share of traffic');
+ // Seven day columns, Monday first; the busiest day is the tallest bar.
+ expect(html).toContain('AI visits by day');
+ expect(html.match(/>(Mon|Tue|Wed|Thu|Fri|Sat|Sun)</g)).toEqual([
+ '>Mon<',
+ '>Tue<',
+ '>Wed<',
+ '>Thu<',
+ '>Fri<',
+ '>Sat<',
+ '>Sun<',
+ ]);
+ expect(html).toContain('height:72px;');
+ // The platforms by name, their bars as long as their share of the top one.
+ expect(html).toContain('ChatGPT');
+ expect(html).toContain('Perplexity');
+ expect(html).toContain(
+ '<td width="40%" style="height:8px;line-height:8px;font-size:0;background:#1C1A17;',
+ );
+ // Only the brand's neutrals, and red, green and amber for what changed.
+ const palette = ['#1C1A17', '#464442', '#F0EEEA', '#EBE6DE', '#FFFFFF'];
+ const status = ['#067647', '#ECFDF3', '#B42318', '#FEF3F2', '#B54708', '#FFFAEB'];
+ for (const color of new Set(html.match(/#[0-9a-fA-F]{6}\b/g))) {
+ expect([...palette, ...status]).toContain(color);
+ }
+ // A fall is marked red.
+ expect(html).toContain('color:#B42318;background:#FEF3F2;">▼</div>');
+ });
+
+ it('names the share of traffic when Analytics gives one', () => {
+ const { html } = digest({ share: '0.8%' });
+ expect(html).toContain('Share of traffic');
+ expect(html).toContain('0.8%');
+ });
+
+ it('leaves out a change it cannot state, and the list when nothing moved', () => {
+ const { subject, html } = digest({ visits: 1, prevVisits: 0, change: null, changes: [] });
+ expect(subject).toBe('Acme <Coffee> AI traffic last week: 1 AI visit');
+ expect(html).toContain('none the week before');
+ expect(html).not.toContain('Top changes');
+ });
+});
diff --git a/server/src/lib/traffic-digest/engine.js b/server/src/lib/traffic-digest/engine.js
new file mode 100644
index 000000000..cf635293c
--- /dev/null
+++ b/server/src/lib/traffic-digest/engine.js
@@ -0,0 +1,340 @@
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { readAllRpcRows } from '../rpc-pages.js';
+import { isCloud, isSubscriptionActive } from '../../config/plans.js';
+import { appUrl, resolveRecipients } from '../pulse/engine.js';
+import { untrackedGoogleQueries } from '../untracked-queries.js';
+import {
+ dailyVisits,
+ digestWeek,
+ formatShare,
+ summarySentences,
+ topChanges,
+ topPlatforms,
+ visitChangePct,
+} from './summary.js';
+import { renderTrafficDigestEmail, sendTrafficDigestEmail } from './email.js';
+
+/**
+ * The AI Traffic weekly digest (AT-013, spec §3.8): every Monday, for the
+ * week before, "the summary line and the top three changes" to the Daily
+ * Pulse's recipients (00036), unless Settings › Notifications turned it off
+ * for the brand (00187) or the brand's pulse is off.
+ *
+ * A brand with no AI visits in either week gets nothing. A week is claimed in
+ * ai_traffic_digests before anything is sent, so two sweeps can't mail it
+ * twice, and marked sent (sent_at) just before the e-mail goes, so a stop
+ * after the send can't leave a claim a later sweep takes over and sends
+ * again. The sweep runs Monday to Wednesday: a week a failure left unsent (a
+ * read that kept failing, an e-mail Resend refused, a restart between the
+ * claim and the send) is tried again the next day, and one already sent is
+ * skipped. An e-mail Resend gave no answer for may have gone out, so its
+ * week isn't sent again: Resend's idempotency keys don't last to the next
+ * day. Cloud only, like the pulse's e-mail. Best effort: one brand's failure
+ * is logged and the sweep moves on.
+ */
+
+/** Monday, as the weekly pulse; then Tuesday and Wednesday for a week left unsent. */
+const SEND_UTC_DAYS = [1, 2, 3];
+
+/** A claim this old without a send was left by a sweep that stopped; it's taken over. */
+const STALE_CLAIM_MS = 60 * 60 * 1000;
+
+/** A read is tried this many times before the brand's week waits for the next sweep. */
+const READ_ATTEMPTS = 3;
+
+async function withRetries(read, waitMs) {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return await read();
+ } catch (err) {
+ if (attempt >= READ_ATTEMPTS) throw err;
+ await new Promise((resolve) => setTimeout(resolve, waitMs * attempt));
+ }
+ }
+}
+
+/** Writes to the week's row, tried again as the reads are; throws when it still fails. */
+function updateDigest(id, patch, waitMs) {
+ return withRetries(async () => {
+ const { error } = await supabaseAdmin.from('ai_traffic_digests').update(patch).eq('id', id);
+ if (error) throw new Error(`ai_traffic_digests: ${error.message}`);
+ }, waitMs);
+}
+
+async function rpc(name, params) {
+ const { data, error } = await supabaseAdmin.rpc(name, params);
+ if (error) throw new Error(`${name}: ${error.message}`);
+ return data;
+}
+
+/** The last second of the week: the reads that take an inclusive end stop on its Sunday. */
+const lastSecond = (end) => new Date(Date.parse(end) - 1000).toISOString();
+
+/**
+ * The numbers behind one brand's digest, read as the AI Traffic page reads
+ * them for a 7-day range.
+ */
+export async function readDigestData(brandId, week) {
+ // To each week's last second, inclusive: ai_traffic_merged keeps Analytics
+ // rows through p_to's day (00176), so a midnight end would count the
+ // Monday between the weeks in both.
+ const merged = (from, to) =>
+ rpc('ai_traffic_merged', {
+ p_brand_id: brandId,
+ p_from: from,
+ p_to: lastSecond(to),
+ p_to_inclusive: true,
+ p_analytics: true,
+ });
+ const [cur, prev] = await Promise.all([
+ merged(week.start, week.end),
+ merged(week.prevStart, week.start),
+ ]);
+ const data = { cur: cur ?? {}, prev: prev ?? {} };
+ if ((Number(data.cur.visits) || 0) + (Number(data.prev.visits) || 0) === 0) return data;
+
+ const until = lastSecond(week.end);
+ const [totals, pages, broken, untracked] = await Promise.all([
+ supabaseAdmin
+ .rpc('ga_traffic_totals', {
+ p_brand_id: brandId,
+ p_since: week.firstDay,
+ p_until: week.lastDay,
+ })
+ .maybeSingle()
+ .then(({ data: row, error }) => {
+ if (error) throw new Error(`ga_traffic_totals: ${error.message}`);
+ return row;
+ }),
+ rpc('ai_traffic_pages', {
+ p_brand_id: brandId,
+ p_from: week.start,
+ p_to: until,
+ p_tab: 'cited_not_clicked',
+ p_limit: 0,
+ p_offset: 0,
+ }),
+ rpc('ai_traffic_broken_links', {
+ p_brand_id: brandId,
+ p_from: week.start,
+ p_to: until,
+ p_limit: 1,
+ p_offset: 0,
+ }),
+ untrackedGoogleQueries(brandId, {
+ since: week.firstDay,
+ until: week.lastDay,
+ latest: true,
+ limit: 0,
+ }),
+ ]);
+ // Share and conversions only from a connected Analytics (§3.8b rule 5).
+ const gaSessions = (Number(totals?.sessions) || 0) > 0 ? Number(totals.sessions) : null;
+ const platformValue =
+ gaSessions === null
+ ? null
+ : await rpc('ga_platform_value', {
+ p_brand_id: brandId,
+ p_since: week.firstDay,
+ p_until: week.lastDay,
+ });
+ return {
+ ...data,
+ gaSessions,
+ platformValue: platformValue ?? null,
+ citedNotClicked: Number(pages?.counts?.cited_not_clicked) || 0,
+ broken: broken ?? null,
+ untrackedQueries: untracked?.count ?? 0,
+ };
+}
+
+/** What the e-mail says and shows, from the numbers. */
+export function digestContent(data, week) {
+ const visits = Number(data.cur.visits) || 0;
+ const prevVisits = Number(data.prev.visits) || 0;
+ const platforms = topPlatforms(data.cur.platforms ?? []);
+ return {
+ visits,
+ prevVisits,
+ change: visitChangePct(visits, prevVisits),
+ // The cards and charts (the summary line says the same in words).
+ share: data.gaSessions ? formatShare(visits, data.gaSessions) : null,
+ citedNotClicked: data.citedNotClicked ?? 0,
+ platforms,
+ days: dailyVisits(week, data.cur.days ?? []),
+ sentences: summarySentences({
+ visits,
+ prevVisits,
+ platforms: data.cur.platforms ?? [],
+ gaSessions: data.gaSessions ?? null,
+ platformValue: data.platformValue ?? null,
+ citedNotClicked: data.citedNotClicked ?? 0,
+ untrackedQueries: data.untrackedQueries ?? 0,
+ }),
+ changes: topChanges(data),
+ };
+}
+
+/**
+ * One brand's digest for the week before `now`'s.
+ *
+ * @returns {Promise<object>} what happened: `{ sent, emailSent, recipients }` or `{ skipped }`
+ */
+export async function sendTrafficDigestForBrand(
+ brandId,
+ { now = new Date(), retryWaitMs = 2000 } = {},
+) {
+ const { data: brand } = await supabaseAdmin
+ .from('brands')
+ .select('id, name, organization_id, is_active')
+ .eq('id', brandId)
+ .single();
+ if (!brand?.is_active) return { skipped: 'brand_inactive' };
+
+ const { data: org } = await supabaseAdmin
+ .from('organizations')
+ .select('subscription_status')
+ .eq('id', brand.organization_id)
+ .single();
+ if (!isSubscriptionActive(org?.subscription_status)) return { skipped: 'subscription_inactive' };
+
+ const { data: settings } = await supabaseAdmin
+ .from('pulse_settings')
+ .select('recipients, traffic_digest, frequency')
+ .eq('brand_id', brandId)
+ .maybeSingle();
+ // On by default, but not where the brand's pulse is off. No settings row: on.
+ if (settings?.traffic_digest === false || settings?.frequency === 'off') {
+ return { skipped: 'off' };
+ }
+
+ const week = digestWeek(now);
+ const { data: existing } = await supabaseAdmin
+ .from('ai_traffic_digests')
+ .select('id, sent_at, created_at')
+ .eq('brand_id', brandId)
+ .eq('week_start', week.firstDay)
+ .maybeSingle();
+ if (existing?.sent_at) return { skipped: 'already_sent' };
+ if (existing) {
+ if (now.getTime() - Date.parse(existing.created_at) < STALE_CLAIM_MS) {
+ return { skipped: 'in_progress' };
+ }
+ // Claimed by a sweep that stopped before sending (a deploy, a restart).
+ await releaseClaim(existing.id);
+ }
+
+ const data = await withRetries(() => readDigestData(brandId, week), retryWaitMs);
+ const content = digestContent(data, week);
+ if (content.visits === 0 && content.prevVisits === 0) return { skipped: 'no_traffic' };
+
+ // Claim the week first: the unique (brand_id, week_start) is the race-safe
+ // guard against a second sweep.
+ const { data: row, error: claimError } = await supabaseAdmin
+ .from('ai_traffic_digests')
+ .insert({ brand_id: brandId, week_start: week.firstDay, payload: { week, ...content } })
+ .select('id')
+ .single();
+ if (claimError) {
+ if (claimError.code === '23505') return { skipped: 'already_sent' };
+ throw new Error(claimError.message);
+ }
+
+ let recipients;
+ // Nothing to send to, or Resend isn't set up: the week is done all the same.
+ let outcome = 'skipped';
+ try {
+ recipients = await resolveRecipients(brand.organization_id, settings);
+ if (recipients.length) {
+ const settingsUrl = `${appUrl()}/dashboard/settings?tab=notifications`;
+ const { subject, html } = renderTrafficDigestEmail({
+ brandName: brand.name,
+ week,
+ ...content,
+ trafficUrl: `${appUrl()}/dashboard/traffic`,
+ settingsUrl,
+ });
+ // Marked sent before it goes. When this fails, nothing went out.
+ await updateDigest(row.id, { sent_at: new Date().toISOString() }, retryWaitMs);
+ outcome = await sendTrafficDigestEmail({ to: recipients, subject, html, settingsUrl });
+ // Resend answered with an error: nothing went out.
+ if (outcome === 'refused') throw new Error('Resend refused the digest');
+ }
+ } catch (err) {
+ // Give the week back, so the next sweep (through Wednesday) tries again.
+ await releaseClaim(row.id);
+ throw err;
+ }
+ if (outcome === 'unknown') {
+ logger.warn(
+ { brandId, week: week.firstDay },
+ '[traffic-digest] no answer from Resend; the week is not sent again',
+ );
+ }
+ const emailSent = outcome === 'sent';
+ try {
+ await updateDigest(
+ row.id,
+ {
+ email_sent: emailSent,
+ email_recipient_count: emailSent ? recipients.length : 0,
+ sent_at: new Date().toISOString(),
+ },
+ retryWaitMs,
+ );
+ } catch (err) {
+ // The claim stays, marked sent before the e-mail went (or with nothing to
+ // send): only the record of what went out is missing.
+ logger.error(
+ { err, brandId, week: week.firstDay },
+ '[traffic-digest] recording the send failed',
+ );
+ }
+
+ logger.info(
+ { brandId, week: week.firstDay, emailSent, recipients: recipients.length },
+ '[traffic-digest] sent',
+ );
+ return { sent: true, emailSent, recipients: recipients.length };
+}
+
+/** Take back a claim, so a later sweep sends the week. */
+async function releaseClaim(id) {
+ const { error } = await supabaseAdmin.from('ai_traffic_digests').delete().eq('id', id);
+ if (error) logger.warn({ err: error, id }, '[traffic-digest] claim release failed');
+}
+
+/**
+ * The sweep, Monday to Wednesday: every active brand's digest for the week
+ * before that isn't sent yet. Called from the daily cycle after the
+ * Analytics sync, so Sunday's numbers are in.
+ */
+export async function sendTrafficDigests({ now = new Date() } = {}) {
+ if (!isCloud()) return { skipped: 'self_hosted' };
+ if (!SEND_UTC_DAYS.includes(now.getUTCDay())) return { skipped: 'not_send_day' };
+
+ // Read past PostgREST's 1000-row page.
+ const { data: brands, error } = await readAllRpcRows('brands', (from, to) =>
+ supabaseAdmin
+ .from('brands')
+ .select('id')
+ .eq('is_active', true)
+ .order('id', { ascending: true })
+ .range(from, to),
+ );
+ if (error) throw new Error(error.message);
+
+ let sent = 0;
+ // A slice boundary can repeat a row (rpc-pages.js).
+ for (const id of new Set((brands ?? []).map((b) => b.id))) {
+ try {
+ const result = await sendTrafficDigestForBrand(id, { now });
+ if (result.sent) sent += 1;
+ } catch (err) {
+ logger.error({ err, brandId: id }, '[traffic-digest] brand failed');
+ }
+ }
+ logger.info({ sent, brands: (brands ?? []).length }, '[traffic-digest] weekly sweep done');
+ return { sent };
+}
diff --git a/server/src/lib/traffic-digest/engine.test.js b/server/src/lib/traffic-digest/engine.test.js
new file mode 100644
index 000000000..8d1d8cf41
--- /dev/null
+++ b/server/src/lib/traffic-digest/engine.test.js
@@ -0,0 +1,323 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Sending the AI Traffic weekly digest (AT-013): Mondays, cloud only, once a
+ * week per brand, to the pulse's recipients, unless turned off.
+ */
+
+const state = vi.hoisted(() => ({
+ brand: { id: 'b1', name: 'Acme', organization_id: 'o1', is_active: true },
+ settings: null,
+ existing: null,
+ claimError: null,
+ inserted: [],
+ updated: [],
+ deleted: [],
+ rpcCalls: [],
+ rpcFailures: 0,
+ updateFailures: 0,
+ rpc: {},
+}));
+
+vi.mock('../../config/supabase.js', () => {
+ const single = (data) => ({
+ single: async () => ({ data }),
+ maybeSingle: async () => ({ data }),
+ });
+ return {
+ default: {
+ from: (table) => ({
+ select: () => {
+ const chain = {
+ eq: () => chain,
+ single: async () => ({
+ data:
+ table === 'brands'
+ ? state.brand
+ : table === 'organizations'
+ ? { subscription_status: 'active' }
+ : null,
+ }),
+ maybeSingle: async () => ({
+ data: table === 'pulse_settings' ? state.settings : state.existing,
+ }),
+ };
+ // The sweep reads the active brands a page at a time.
+ if (table === 'brands') {
+ chain.order = () => chain;
+ chain.range = async () => ({ data: state.listBrands ?? [], error: null });
+ }
+ return chain;
+ },
+ insert: (row) => {
+ state.inserted.push({ table, row });
+ return {
+ select: () => ({
+ single: async () =>
+ state.claimError ? { error: state.claimError } : { data: { id: 'd1' } },
+ }),
+ };
+ },
+ update: (patch) => ({
+ eq: async () => {
+ // A test may fail the writes, as a dropped connection would.
+ if (state.updateFailures > 0) {
+ state.updateFailures -= 1;
+ return { error: { message: 'connection reset' } };
+ }
+ state.updated.push({ table, patch });
+ return { error: null };
+ },
+ }),
+ delete: () => ({
+ eq: async (_col, id) => {
+ state.deleted.push({ table, id });
+ return { error: null };
+ },
+ }),
+ }),
+ rpc: (name, params) => {
+ state.rpcCalls.push({ name, params });
+ // A test may fail the first reads, as a transient error would.
+ if (state.rpcFailures > 0) {
+ state.rpcFailures -= 1;
+ const failed = { data: null, error: { message: 'connection reset' } };
+ return Object.assign(Promise.resolve(failed), single(null));
+ }
+ const answer = { data: state.rpc[name]?.(params) ?? null, error: null };
+ return Object.assign(Promise.resolve(answer), single(answer.data));
+ },
+ },
+ };
+});
+const logger = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }));
+vi.mock('../logger.js', () => ({ logger }));
+// 'sent', 'refused', 'unknown' or 'skipped', as deliverEmail says.
+const deliverEmail = vi.fn(async () => 'sent');
+vi.mock('../email.js', () => ({ deliverEmail: (...args) => deliverEmail(...args) }));
+vi.mock('../pulse/engine.js', () => ({
+ appUrl: () => 'https://app.example.com',
+ resolveRecipients: async (_org, settings) => settings?.recipients ?? ['[email protected]'],
+}));
+vi.mock('../untracked-queries.js', () => ({ untrackedGoogleQueries: async () => ({ count: 0 }) }));
+let cloud = true;
+vi.mock('../../config/plans.js', () => ({
+ isCloud: () => cloud,
+ isSubscriptionActive: () => true,
+}));
+
+const { sendTrafficDigestForBrand, sendTrafficDigests } = await import('./engine.js');
+
+const MONDAY = new Date('2026-10-19T03:00:00Z');
+
+beforeEach(() => {
+ Object.assign(state, {
+ settings: null,
+ existing: null,
+ claimError: null,
+ inserted: [],
+ updated: [],
+ deleted: [],
+ rpcCalls: [],
+ rpcFailures: 0,
+ updateFailures: 0,
+ listBrands: null,
+ rpc: {
+ ai_traffic_merged: (p) =>
+ p.p_from === '2026-10-12T00:00:00.000Z'
+ ? { visits: 36, platforms: [{ platform: 'chatgpt.com', visits: 36 }], pages: [] }
+ : { visits: 60, platforms: [{ platform: 'chatgpt.com', visits: 60 }], pages: [] },
+ ga_traffic_totals: () => null,
+ ai_traffic_pages: () => ({ counts: { cited_not_clicked: 2 } }),
+ ai_traffic_broken_links: () => ({ count: 0, rows: [] }),
+ },
+ });
+ deliverEmail.mockReset().mockResolvedValue('sent');
+ logger.warn.mockReset();
+ logger.error.mockReset();
+ cloud = true;
+});
+
+describe('sendTrafficDigestForBrand', () => {
+ it("claims the week, then mails last week's line and changes to the pulse's recipients", async () => {
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toEqual({
+ sent: true,
+ emailSent: true,
+ recipients: 1,
+ });
+ expect(state.inserted[0]).toMatchObject({
+ table: 'ai_traffic_digests',
+ row: { brand_id: 'b1', week_start: '2026-10-12' },
+ });
+ const [mail] = deliverEmail.mock.calls[0];
+ expect(mail.to).toEqual(['[email protected]']);
+ expect(mail.subject).toBe('Acme AI traffic last week: 36 AI visits (−40%)');
+ expect(mail.html).toContain('2 pages are cited in AI answers but get no clicks.');
+ expect(mail.html).toContain('ChatGPT sent 36 AI visits, down from 60.');
+ expect(mail.headers).toEqual({
+ 'List-Unsubscribe': '<https://app.example.com/dashboard/settings?tab=notifications>',
+ });
+ // Marked sent before it went, then what went out.
+ expect(state.updated.map((u) => u.patch)).toEqual([
+ { sent_at: expect.any(String) },
+ { email_sent: true, email_recipient_count: 1, sent_at: expect.any(String) },
+ ]);
+ });
+
+ it("reads each week to its Sunday's last second, so the Monday between them counts once", async () => {
+ await sendTrafficDigestForBrand('b1', { now: MONDAY });
+ const merged = state.rpcCalls.filter((c) => c.name === 'ai_traffic_merged');
+ expect(merged.map((c) => [c.params.p_from, c.params.p_to, c.params.p_to_inclusive])).toEqual([
+ ['2026-10-12T00:00:00.000Z', '2026-10-18T23:59:59.000Z', true],
+ ['2026-10-05T00:00:00.000Z', '2026-10-11T23:59:59.000Z', true],
+ ]);
+ });
+
+ it('tries a failing read again before giving the week up', async () => {
+ state.rpcFailures = 2;
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY, retryWaitMs: 0 })).toMatchObject({
+ sent: true,
+ });
+ state.rpcFailures = 9;
+ state.inserted = [];
+ await expect(sendTrafficDigestForBrand('b1', { now: MONDAY, retryWaitMs: 0 })).rejects.toThrow(
+ 'connection reset',
+ );
+ // Nothing was claimed: Tuesday's sweep tries the week again.
+ expect(state.inserted).toEqual([]);
+ });
+
+ it('gives the week back when Resend refuses the e-mail', async () => {
+ deliverEmail.mockResolvedValue('refused');
+ await expect(sendTrafficDigestForBrand('b1', { now: MONDAY })).rejects.toThrow(
+ 'Resend refused the digest',
+ );
+ expect(state.deleted).toEqual([{ table: 'ai_traffic_digests', id: 'd1' }]);
+
+ // Without Resend set up, nothing could go out: the week is done.
+ deliverEmail.mockResolvedValue('skipped');
+ state.deleted = [];
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toMatchObject({
+ sent: true,
+ emailSent: false,
+ });
+ expect(state.deleted).toEqual([]);
+ });
+
+ it("keeps the week when Resend gave no answer: it may have gone, and isn't sent twice", async () => {
+ deliverEmail.mockResolvedValue('unknown');
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toMatchObject({
+ sent: true,
+ emailSent: false,
+ });
+ expect(state.deleted).toEqual([]);
+ expect(state.updated.at(-1).patch).toMatchObject({ sent_at: expect.any(String) });
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.objectContaining({ brandId: 'b1', week: '2026-10-12' }),
+ '[traffic-digest] no answer from Resend; the week is not sent again',
+ );
+ });
+
+ it('tries a failing write again; a send it cannot record keeps its claim', async () => {
+ // The mark before the send fails twice, then holds.
+ state.updateFailures = 2;
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY, retryWaitMs: 0 })).toMatchObject({
+ sent: true,
+ emailSent: true,
+ });
+ expect(state.updated).toHaveLength(2);
+
+ // The mark never holds: nothing is sent, and the week is given back.
+ state.updated = [];
+ state.updateFailures = 3;
+ deliverEmail.mockClear();
+ await expect(sendTrafficDigestForBrand('b1', { now: MONDAY, retryWaitMs: 0 })).rejects.toThrow(
+ 'connection reset',
+ );
+ expect(deliverEmail).not.toHaveBeenCalled();
+ expect(state.deleted).toEqual([{ table: 'ai_traffic_digests', id: 'd1' }]);
+
+ // The record after the send never holds: the claim, marked sent, stays.
+ state.deleted = [];
+ state.updated = [];
+ deliverEmail.mockImplementation(async () => {
+ state.updateFailures = 3;
+ return 'sent';
+ });
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY, retryWaitMs: 0 })).toMatchObject({
+ sent: true,
+ emailSent: true,
+ });
+ expect(state.updated.map((u) => u.patch)).toEqual([{ sent_at: expect.any(String) }]);
+ expect(state.deleted).toEqual([]);
+ expect(logger.error).toHaveBeenCalledWith(
+ expect.objectContaining({ brandId: 'b1', week: '2026-10-12' }),
+ '[traffic-digest] recording the send failed',
+ );
+ });
+
+ it('takes over a claim a stopped sweep left, and leaves one still in progress', async () => {
+ state.existing = { id: 'd0', sent_at: null, created_at: '2026-10-19T02:50:00Z' };
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toEqual({
+ skipped: 'in_progress',
+ });
+ state.existing = { id: 'd0', sent_at: null, created_at: '2026-10-19T01:00:00Z' };
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toMatchObject({ sent: true });
+ expect(state.deleted).toEqual([{ table: 'ai_traffic_digests', id: 'd0' }]);
+ });
+
+ it('sends nothing when turned off, already sent, or without AI visits', async () => {
+ state.settings = { recipients: null, traffic_digest: false };
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toEqual({ skipped: 'off' });
+
+ // Nor where the brand's pulse is off.
+ state.settings = { recipients: null, traffic_digest: true, frequency: 'off' };
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toEqual({ skipped: 'off' });
+
+ state.settings = null;
+ state.existing = {
+ id: 'd0',
+ sent_at: '2026-10-19T03:01:00Z',
+ created_at: '2026-10-19T03:00:00Z',
+ };
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toEqual({
+ skipped: 'already_sent',
+ });
+
+ state.existing = null;
+ state.rpc.ai_traffic_merged = () => ({ visits: 0, platforms: [], pages: [] });
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toEqual({
+ skipped: 'no_traffic',
+ });
+ expect(deliverEmail).not.toHaveBeenCalled();
+ expect(state.inserted).toEqual([]);
+ });
+
+ it('loses a race for the week quietly', async () => {
+ state.claimError = { code: '23505', message: 'duplicate key' };
+ expect(await sendTrafficDigestForBrand('b1', { now: MONDAY })).toEqual({
+ skipped: 'already_sent',
+ });
+ expect(deliverEmail).not.toHaveBeenCalled();
+ });
+});
+
+describe('sendTrafficDigests', () => {
+ it('runs Monday to Wednesday, for a week left unsent, in the cloud only', async () => {
+ state.listBrands = [];
+ expect(await sendTrafficDigests({ now: new Date('2026-10-21T03:00:00Z') })).toEqual({
+ sent: 0,
+ });
+ expect(await sendTrafficDigests({ now: new Date('2026-10-22T03:00:00Z') })).toEqual({
+ skipped: 'not_send_day',
+ });
+ cloud = false;
+ expect(await sendTrafficDigests({ now: MONDAY })).toEqual({ skipped: 'self_hosted' });
+ });
+
+ it("sends every active brand's digest and counts them", async () => {
+ state.listBrands = [{ id: 'b1' }];
+ const result = await sendTrafficDigests({ now: MONDAY });
+ expect(result).toEqual({ sent: 1 });
+ });
+});
diff --git a/server/src/lib/traffic-digest/platform-names.json b/server/src/lib/traffic-digest/platform-names.json
new file mode 100644
index 000000000..41b3e6d20
--- /dev/null
+++ b/server/src/lib/traffic-digest/platform-names.json
@@ -0,0 +1,18 @@
+{
+ "chatgpt.com": "ChatGPT",
+ "chat.openai.com": "ChatGPT",
+ "search.chatgpt.com": "ChatGPT",
+ "perplexity.ai": "Perplexity",
+ "claude.ai": "Claude",
+ "gemini.google.com": "Gemini",
+ "copilot.microsoft.com": "Copilot",
+ "you.com": "You.com",
+ "phind.com": "Phind",
+ "meta.ai": "Meta AI",
+ "poe.com": "Poe",
+ "labs.google": "Google Labs",
+ "bing.com": "Bing",
+ "grok.com": "Grok",
+ "deepseek.com": "DeepSeek",
+ "unknown": "Unknown"
+}
diff --git a/server/src/lib/traffic-digest/summary.js b/server/src/lib/traffic-digest/summary.js
new file mode 100644
index 000000000..370b3d18c
--- /dev/null
+++ b/server/src/lib/traffic-digest/summary.js
@@ -0,0 +1,248 @@
+/**
+ * What the AI Traffic weekly digest says (AT-013, spec §3.8): "the summary
+ * line and the top three changes". Pure: the engine reads the numbers, the
+ * e-mail lays them out.
+ *
+ * The summary line is the AI Traffic page's (AT-007), with the same rules,
+ * written here because the server can't import the web's TypeScript
+ * (web/src/lib/traffic-summary-line.ts and its copy in en.json
+ * traffic.summaryLine):
+ *
+ * - the change on the week before only when both weeks have 30 visits;
+ * - the share of all traffic and the best-converting platform only from
+ * Google Analytics, the latter when two platforms have 30 visits and 5
+ * key events;
+ * - the cited pages nobody clicks, and the Google queries no prompt tracks.
+ */
+
+import { createRequire } from 'module';
+
+// The AI Traffic page's names (web/src/lib/traffic-platforms.ts); a web test
+// keeps the two the same.
+const require = createRequire(import.meta.url);
+const PLATFORM_NAMES = require('./platform-names.json');
+
+const DAY_MS = 86_400_000;
+
+/** Below this many visits in either week, no % change (the page's Low sample). */
+export const LOW_SAMPLE_VISITS = 30;
+/** Key events a platform needs before its conversions are compared (§5.4). */
+export const MIN_COMPARED_KEY_EVENTS = 5;
+/** A platform or page has to move by this many visits to be a change worth naming. */
+export const MIN_CHANGE_VISITS = 3;
+/** "The top three changes." */
+export const TOP_CHANGES = 3;
+
+export const platformName = (key) => PLATFORM_NAMES[key] ?? key;
+
+const n = (value) => Number(value) || 0;
+const formatNumber = (value) => Math.round(value).toLocaleString('en-US');
+const plural = (count, one, other) => (count === 1 ? one : other);
+
+/**
+ * The week a digest reports: the last whole Monday-to-Sunday week (UTC)
+ * before `now`'s. `end` is the next Monday, excluded.
+ */
+export function digestWeek(now) {
+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
+ const sinceMonday = (now.getUTCDay() + 6) % 7;
+ const end = new Date(today - sinceMonday * DAY_MS);
+ const start = new Date(end.getTime() - 7 * DAY_MS);
+ const prevStart = new Date(start.getTime() - 7 * DAY_MS);
+ const day = (d) => d.toISOString().slice(0, 10);
+ return {
+ start: start.toISOString(),
+ end: end.toISOString(),
+ prevStart: prevStart.toISOString(),
+ firstDay: day(start),
+ lastDay: day(new Date(end.getTime() - DAY_MS)),
+ prevFirstDay: day(prevStart),
+ prevLastDay: day(new Date(start.getTime() - DAY_MS)),
+ };
+}
+
+/** AI visits on each day of the week, Monday first, from ai_traffic_merged's days. */
+export function dailyVisits(week, days = []) {
+ const totals = new Map();
+ for (const d of days) {
+ const day = String(d.day).slice(0, 10);
+ totals.set(day, (totals.get(day) ?? 0) + n(d.visits));
+ }
+ return Array.from({ length: 7 }, (_, i) => {
+ const day = new Date(Date.parse(week.start) + i * DAY_MS).toISOString().slice(0, 10);
+ return { day, visits: totals.get(day) ?? 0 };
+ });
+}
+
+/** The week's platforms with visits, most first, at most `limit`. */
+export function topPlatforms(platforms = [], limit = 5) {
+ return platforms
+ .map((p) => ({ platform: String(p.platform ?? ''), visits: n(p.visits) }))
+ .filter((p) => p.visits > 0 && p.platform)
+ .sort((a, b) => b.visits - a.visits || a.platform.localeCompare(b.platform))
+ .slice(0, limit);
+}
+
+/** The page's change rule (web/src/lib/traffic-change.ts): a % only on 30 visits each. */
+export function visitChangePct(current, previous) {
+ if (previous === 0 || current < LOW_SAMPLE_VISITS || previous < LOW_SAMPLE_VISITS) return null;
+ const pct = Math.round(((current - previous) / previous) * 100);
+ return pct === 0 ? null : pct;
+}
+
+/** "0.8%" of all traffic, as the page's KPI writes it. */
+export function formatShare(part, whole) {
+ if (whole <= 0) return null;
+ const pct = (part / whole) * 100;
+ if (pct > 0 && pct < 0.1) return '<0.1%';
+ const rounded = pct < 10 ? Math.round(pct * 10) / 10 : Math.round(pct);
+ return `${rounded.toLocaleString('en-US')}%`;
+}
+
+/** The platform whose visitors convert best, when two or more can be compared. */
+export function bestConvertingPlatform(value = []) {
+ const compared = value.flatMap((p) => {
+ const sessions = n(p.sessions);
+ if (sessions < LOW_SAMPLE_VISITS || n(p.key_events) < MIN_COMPARED_KEY_EVENTS) return [];
+ if (n(p.key_event_sessions) <= 0) return [];
+ return [{ platform: p.platform, rate: n(p.key_event_sessions) / sessions }];
+ });
+ if (compared.length < 2) return null;
+ const best = compared.reduce((a, b) => (b.rate > a.rate ? b : a));
+ return { platform: best.platform, rate: Math.round(best.rate * 1000) / 10 };
+}
+
+/**
+ * The summary line's sentences, in the page's words.
+ *
+ * @param {{ visits: number, prevVisits: number, platforms: {platform: string, visits: number}[],
+ * gaSessions: number | null, platformValue: object[] | null, citedNotClicked: number,
+ * untrackedQueries: number }} input
+ */
+export function summarySentences(input) {
+ const visits = n(input.visits);
+ if (visits === 0) return ['Last week: no AI-referred visits.'];
+
+ const sentences = [];
+ const first = [
+ `Last week: ${formatNumber(visits)} ${plural(visits, 'AI-referred visit', 'AI-referred visits')}`,
+ ];
+ const share = input.gaSessions !== null ? formatShare(visits, n(input.gaSessions)) : null;
+ if (share) first.push(`${share} of all traffic`);
+ const change = visitChangePct(visits, n(input.prevVisits));
+ if (change !== null) {
+ first.push(`${change > 0 ? 'up' : 'down'} ${Math.abs(change)}% on the week before`);
+ }
+ sentences.push(`${first.join(', ')}.`);
+
+ const top = [...(input.platforms ?? [])]
+ .filter((p) => n(p.visits) > 0)
+ .sort((a, b) => n(b.visits) - n(a.visits))[0];
+ const best = input.gaSessions !== null ? bestConvertingPlatform(input.platformValue ?? []) : null;
+ const rate = best ? `${best.rate.toLocaleString('en-US')}%` : '';
+ if (top && best && best.platform === top.platform) {
+ sentences.push(
+ `${platformName(top.platform)} sent the most (${formatNumber(n(top.visits))}), and its visitors convert best (${rate} of their visits had a key event).`,
+ );
+ } else {
+ const second = [];
+ if (top)
+ second.push(`${platformName(top.platform)} sent the most (${formatNumber(n(top.visits))})`);
+ if (best) {
+ second.push(
+ `${platformName(best.platform)} visitors convert best (${rate} of their visits had a key event)`,
+ );
+ }
+ if (second.length) sentences.push(`${second.join('; ')}.`);
+ }
+
+ const cited = n(input.citedNotClicked);
+ if (cited > 0) {
+ sentences.push(
+ cited === 1
+ ? '1 page is cited in AI answers but gets no clicks.'
+ : `${formatNumber(cited)} pages are cited in AI answers but get no clicks.`,
+ );
+ }
+ const untracked = n(input.untrackedQueries);
+ if (untracked > 0) {
+ sentences.push(
+ `${formatNumber(untracked)} Google ${plural(untracked, 'query', 'queries')} with clicks ${plural(untracked, "isn't", "aren't")} tracked as prompts.`,
+ );
+ }
+ return sentences;
+}
+
+function movers(cur = [], prev = [], keyOf, type) {
+ const before = new Map();
+ const now = new Map();
+ const names = new Map();
+ for (const [list, into] of [
+ [prev, before],
+ [cur, now],
+ ]) {
+ for (const row of list) {
+ const raw = keyOf(row);
+ if (!raw || raw === 'unknown') continue;
+ const key = type === 'page' ? raw.toLowerCase() : raw;
+ if (!names.has(key)) names.set(key, raw);
+ into.set(key, (into.get(key) ?? 0) + n(row.visits));
+ }
+ }
+ return [...names.entries()].map(([key, name]) => ({
+ type,
+ name,
+ before: before.get(key) ?? 0,
+ now: now.get(key) ?? 0,
+ }));
+}
+
+/**
+ * The week's top changes: broken AI links first — visitors are landing on
+ * missing pages every day until someone adds a redirect — then the platforms
+ * and pages whose AI visits moved most, by at least MIN_CHANGE_VISITS.
+ */
+export function topChanges({ cur, prev, broken }, limit = TOP_CHANGES) {
+ const changes = [];
+ const brokenRows = Array.isArray(broken?.rows) ? broken.rows : [];
+ if (brokenRows.length > 0) {
+ changes.push({
+ type: 'broken',
+ count: n(broken.count) || brokenRows.length,
+ page: brokenRows[0].page,
+ target: brokenRows[0].target ?? null,
+ });
+ }
+ const moved = [
+ ...movers(cur?.platforms, prev?.platforms, (r) => r.platform, 'platform'),
+ ...movers(cur?.pages, prev?.pages, (r) => r.page, 'page'),
+ ]
+ .filter((m) => Math.abs(m.now - m.before) >= MIN_CHANGE_VISITS)
+ .sort(
+ (a, b) =>
+ Math.abs(b.now - b.before) - Math.abs(a.now - a.before) ||
+ b.now - a.now ||
+ a.name.localeCompare(b.name),
+ );
+ return [...changes, ...moved].slice(0, limit);
+}
+
+/** One change as the e-mail says it. */
+export function changeText(change) {
+ if (change.type === 'broken') {
+ const pages =
+ change.count === 1
+ ? '1 page AI visitors landed on doesn’t exist'
+ : `${formatNumber(change.count)} pages AI visitors landed on don’t exist`;
+ const redirect = change.target ? `, redirect to ${change.target}` : '';
+ return `${pages}: ${change.page}${redirect}.`;
+ }
+ const subject = change.type === 'platform' ? platformName(change.name) : change.name;
+ const verb = change.type === 'platform' ? 'sent' : 'got';
+ if (change.before === 0) {
+ // Not "its first": a page or platform may be coming back after a quiet week.
+ return `${subject} ${verb} ${formatNumber(change.now)} AI ${plural(change.now, 'visit', 'visits')}, none the week before.`;
+ }
+ const direction = change.now > change.before ? 'up' : 'down';
+ return `${subject} ${verb} ${formatNumber(change.now)} AI ${plural(change.now, 'visit', 'visits')}, ${direction} from ${formatNumber(change.before)}.`;
+}
diff --git a/server/src/lib/traffic-digest/summary.test.js b/server/src/lib/traffic-digest/summary.test.js
new file mode 100644
index 000000000..a05d8de11
--- /dev/null
+++ b/server/src/lib/traffic-digest/summary.test.js
@@ -0,0 +1,199 @@
+import { describe, expect, it } from 'vitest';
+import {
+ bestConvertingPlatform,
+ changeText,
+ dailyVisits,
+ digestWeek,
+ summarySentences,
+ topChanges,
+ topPlatforms,
+ visitChangePct,
+} from './summary.js';
+
+/**
+ * The AI Traffic weekly digest's words (AT-013, spec §3.8): the page's
+ * summary line (AT-007), with its rules, and the week's top three changes.
+ */
+
+describe('digestWeek', () => {
+ it('reports the last whole Monday-to-Sunday week, whatever day it runs', () => {
+ // A Monday morning: the week that ended last night.
+ expect(digestWeek(new Date('2026-10-19T02:00:00Z'))).toEqual({
+ start: '2026-10-12T00:00:00.000Z',
+ end: '2026-10-19T00:00:00.000Z',
+ prevStart: '2026-10-05T00:00:00.000Z',
+ firstDay: '2026-10-12',
+ lastDay: '2026-10-18',
+ prevFirstDay: '2026-10-05',
+ prevLastDay: '2026-10-11',
+ });
+ // A Sunday still reports the week before this one.
+ expect(digestWeek(new Date('2026-10-25T23:00:00Z')).firstDay).toBe('2026-10-12');
+ });
+});
+
+describe('the charts', () => {
+ const week = digestWeek(new Date('2026-10-19T02:00:00Z'));
+
+ it('gives every day of the week its visits, Monday first, quiet days included', () => {
+ expect(
+ dailyVisits(week, [
+ { day: '2026-10-13', platform: 'chatgpt.com', visits: 3 },
+ { day: '2026-10-13', platform: 'grok.com', visits: 1 },
+ { day: '2026-10-18', platform: 'chatgpt.com', visits: 2 },
+ ]),
+ ).toEqual([
+ { day: '2026-10-12', visits: 0 },
+ { day: '2026-10-13', visits: 4 },
+ { day: '2026-10-14', visits: 0 },
+ { day: '2026-10-15', visits: 0 },
+ { day: '2026-10-16', visits: 0 },
+ { day: '2026-10-17', visits: 0 },
+ { day: '2026-10-18', visits: 2 },
+ ]);
+ });
+
+ it('lists the platforms with visits, most first', () => {
+ expect(
+ topPlatforms([
+ { platform: 'perplexity.ai', visits: 11 },
+ { platform: 'claude.ai', visits: 0 },
+ { platform: 'chatgpt.com', visits: '21' },
+ ]),
+ ).toEqual([
+ { platform: 'chatgpt.com', visits: 21 },
+ { platform: 'perplexity.ai', visits: 11 },
+ ]);
+ });
+});
+
+describe('the summary line', () => {
+ it('states a change only when both weeks have 30 visits', () => {
+ expect(visitChangePct(42, 60)).toBe(-30);
+ expect(visitChangePct(29, 60)).toBeNull();
+ expect(visitChangePct(60, 29)).toBeNull();
+ expect(visitChangePct(5, 0)).toBeNull();
+ expect(visitChangePct(40, 40)).toBeNull();
+ });
+
+ it("says what the page says, from Analytics only where it's connected", () => {
+ expect(
+ summarySentences({
+ visits: 42,
+ prevVisits: 60,
+ platforms: [
+ { platform: 'perplexity.ai', visits: 12 },
+ { platform: 'chatgpt.com', visits: 30 },
+ ],
+ gaSessions: 5250,
+ platformValue: [
+ { platform: 'chatgpt.com', sessions: 30, key_events: 6, key_event_sessions: 6 },
+ { platform: 'perplexity.ai', sessions: 31, key_events: 9, key_event_sessions: 9 },
+ ],
+ citedNotClicked: 3,
+ untrackedQueries: 12,
+ }),
+ ).toEqual([
+ 'Last week: 42 AI-referred visits, 0.8% of all traffic, down 30% on the week before.',
+ 'ChatGPT sent the most (30); Perplexity visitors convert best (29% of their visits had a key event).',
+ '3 pages are cited in AI answers but get no clicks.',
+ "12 Google queries with clicks aren't tracked as prompts.",
+ ]);
+ });
+
+ it('joins the top and best platform when they are the same, and says nothing it cannot', () => {
+ expect(
+ summarySentences({
+ visits: 1,
+ prevVisits: 0,
+ platforms: [{ platform: 'grok.com', visits: 1 }],
+ gaSessions: null,
+ platformValue: null,
+ citedNotClicked: 1,
+ untrackedQueries: 1,
+ }),
+ ).toEqual([
+ 'Last week: 1 AI-referred visit.',
+ 'Grok sent the most (1).',
+ '1 page is cited in AI answers but gets no clicks.',
+ "1 Google query with clicks isn't tracked as prompts.",
+ ]);
+ expect(
+ bestConvertingPlatform([
+ { platform: 'chatgpt.com', sessions: 40, key_events: 8, key_event_sessions: 8 },
+ { platform: 'perplexity.ai', sessions: 30, key_events: 5, key_event_sessions: 3 },
+ ]),
+ ).toEqual({ platform: 'chatgpt.com', rate: 20 });
+ expect(summarySentences({ visits: 0, prevVisits: 4, platforms: [] })).toEqual([
+ 'Last week: no AI-referred visits.',
+ ]);
+ });
+});
+
+describe('topChanges', () => {
+ const week = (platforms, pages) => ({ platforms, pages });
+
+ it('puts broken AI links first, then the biggest moves of 3 visits or more', () => {
+ const changes = topChanges({
+ prev: week(
+ [
+ { platform: 'chatgpt.com', visits: 30 },
+ { platform: 'perplexity.ai', visits: 10 },
+ { platform: 'unknown', visits: 40 },
+ ],
+ [
+ { page: '/menu', visits: 25 },
+ { page: '/Gifts', visits: 6 },
+ ],
+ ),
+ cur: week(
+ [
+ { platform: 'chatgpt.com', visits: 12 },
+ { platform: 'perplexity.ai', visits: 11 },
+ { platform: 'grok.com', visits: 3 },
+ ],
+ [
+ { page: '/menu', visits: 8 },
+ { page: '/gifts', visits: 6 },
+ ],
+ ),
+ broken: { count: 2, rows: [{ page: '/old-menu', target: '/menu' }] },
+ });
+ expect(changes).toEqual([
+ { type: 'broken', count: 2, page: '/old-menu', target: '/menu' },
+ { type: 'platform', name: 'chatgpt.com', before: 30, now: 12 },
+ { type: 'page', name: '/menu', before: 25, now: 8 },
+ ]);
+ });
+
+ it('names nothing that moved by less than 3 visits', () => {
+ expect(
+ topChanges({
+ prev: week([{ platform: 'chatgpt.com', visits: 10 }], []),
+ cur: week([{ platform: 'chatgpt.com', visits: 12 }], []),
+ broken: { count: 0, rows: [] },
+ }),
+ ).toEqual([]);
+ });
+
+ it('writes each change in plain words', () => {
+ expect(changeText({ type: 'broken', count: 2, page: '/old-menu', target: '/menu' })).toBe(
+ '2 pages AI visitors landed on don’t exist: /old-menu, redirect to /menu.',
+ );
+ expect(changeText({ type: 'broken', count: 1, page: '/', target: null })).toBe(
+ '1 page AI visitors landed on doesn’t exist: /.',
+ );
+ expect(changeText({ type: 'platform', name: 'chatgpt.com', before: 30, now: 12 })).toBe(
+ 'ChatGPT sent 12 AI visits, down from 30.',
+ );
+ expect(changeText({ type: 'platform', name: 'grok.com', before: 0, now: 3 })).toBe(
+ 'Grok sent 3 AI visits, none the week before.',
+ );
+ expect(changeText({ type: 'page', name: '/new', before: 0, now: 1 })).toBe(
+ '/new got 1 AI visit, none the week before.',
+ );
+ expect(changeText({ type: 'page', name: '/blog/beans', before: 2, now: 14 })).toBe(
+ '/blog/beans got 14 AI visits, up from 2.',
+ );
+ });
+});
diff --git a/server/src/scripts/test-traffic-digest.js b/server/src/scripts/test-traffic-digest.js
new file mode 100644
index 000000000..4f0b70679
--- /dev/null
+++ b/server/src/scripts/test-traffic-digest.js
@@ -0,0 +1,38 @@
+/**
+ * One-off manual test for the AI Traffic weekly digest (AT-013).
+ *
+ * node src/scripts/test-traffic-digest.js <brandId> [out.html]
+ *
+ * Reads the brand's last whole week and writes the e-mail it would get to
+ * out.html (default traffic-digest.html) without sending or recording it.
+ */
+import 'dotenv/config';
+import { writeFileSync } from 'fs';
+import supabaseAdmin from '../config/supabase.js';
+import { digestWeek } from '../lib/traffic-digest/summary.js';
+import { digestContent, readDigestData } from '../lib/traffic-digest/engine.js';
+import { renderTrafficDigestEmail } from '../lib/traffic-digest/email.js';
+
+const [brandId, out = 'traffic-digest.html'] = process.argv.slice(2);
+if (!brandId) {
+ console.error('Usage: node src/scripts/test-traffic-digest.js <brandId> [out.html]');
+ process.exit(1);
+}
+
+const { data: brand } = await supabaseAdmin
+ .from('brands')
+ .select('name')
+ .eq('id', brandId)
+ .single();
+const week = digestWeek(new Date());
+const content = digestContent(await readDigestData(brandId, week), week);
+const { subject, html } = renderTrafficDigestEmail({
+ brandName: brand?.name ?? brandId,
+ week,
+ ...content,
+ trafficUrl: 'http://localhost:3000/dashboard/traffic',
+ settingsUrl: 'http://localhost:3000/dashboard/settings?tab=notifications',
+});
+writeFileSync(out, html);
+console.log(JSON.stringify({ week, subject, ...content }, null, 2));
+process.exit(0);
diff --git a/server/src/server.js b/server/src/server.js
index e2193a844..242884bac 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -40,6 +40,7 @@ import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/pla
import { analyzeBrandVolumes } from './lib/volume-analysis.js';
import { runGscSync } from './lib/gsc-sync.js';
import { runGaSync } from './lib/ga-sync.js';
+import { sendTrafficDigests } from './lib/traffic-digest/engine.js';
import { runPageOpportunityDetection } from './lib/page-opportunities.js';
import { runPulseCatchUp } from './lib/pulse/engine.js';
import { runSignalCatchUp } from './lib/signals/pass.js';
@@ -287,13 +288,19 @@ async function runDailyTracking() {
.catch((err) => {
logger.error({ err }, '[ga-sync] daily run failed');
})
- .finally(() =>
- sweepAutoAudits({ readInbox: readOpportunityInbox, startAudits: startAutoAudits }).catch(
- (err) => {
- logger.error({ err }, '[auto-audit] daily sweep crashed');
- },
- ),
- );
+ .finally(() => {
+ // The AI Traffic weekly digest (AT-013): Mondays, after the sync, so
+ // last Sunday's Analytics numbers are in. Cloud only, like the pulse.
+ sendTrafficDigests().catch((err) => {
+ logger.error({ err }, '[traffic-digest] weekly sweep crashed');
+ });
+ return sweepAutoAudits({
+ readInbox: readOpportunityInbox,
+ startAudits: startAutoAudits,
+ }).catch((err) => {
+ logger.error({ err }, '[auto-audit] daily sweep crashed');
+ });
+ });
return { triggered, total: brands.length };
}
diff --git a/supabase/migrations/00187_ai_traffic_digest.sql b/supabase/migrations/00187_ai_traffic_digest.sql
new file mode 100644
index 000000000..bcff0f54d
--- /dev/null
+++ b/supabase/migrations/00187_ai_traffic_digest.sql
@@ -0,0 +1,53 @@
+-- ============================================================================
+-- 00187: the AI Traffic weekly digest (AT-013)
+-- ============================================================================
+-- Spec §3.8: "A weekly e-mail digest with the summary line and the top three
+-- changes." Sent on Mondays for the week before, per brand, to the Daily
+-- Pulse's recipients (00036), unless the pulse is off (frequency 'off').
+--
+-- * pulse_settings.traffic_digest — on unless an admin or manager turns it
+-- off in Settings › Notifications. A brand with no settings row gets it.
+-- * ai_traffic_digests — one row per brand and week: the claim that stops
+-- a second send, what went out, and when (sent_at, set just before the
+-- e-mail goes, so a stop after the send never mails the week twice). A
+-- claim with no sent_at was left by a sweep that stopped before sending;
+-- the next one (through Wednesday) takes it over.
+--
+-- Written by the Express server's service-role client; members read their
+-- brands' rows, as with sent_pulses.
+
+alter table public.pulse_settings
+ add column if not exists traffic_digest boolean not null default true;
+
+comment on column public.pulse_settings.traffic_digest is
+ 'Whether the AI Traffic weekly digest (AT-013) is e-mailed for the brand, to the pulse''s recipients.';
+
+create table if not exists public.ai_traffic_digests (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands (id) on delete cascade,
+ -- The Monday the reported week starts on (UTC).
+ week_start date not null,
+ payload jsonb not null default '{}'::jsonb,
+ email_sent boolean not null default false,
+ email_recipient_count integer not null default 0,
+ created_at timestamptz not null default now(),
+ sent_at timestamptz,
+ unique (brand_id, week_start)
+);
+
+alter table public.ai_traffic_digests enable row level security;
+
+grant select on public.ai_traffic_digests to authenticated;
+
+create policy "ai_traffic_digests: member select" on public.ai_traffic_digests
+ 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()
+ )
+ );
+
+comment on table public.ai_traffic_digests is
+ 'AI Traffic weekly digests sent (AT-013): one per brand and week, claimed before sending so a week is never mailed twice.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 17e561fcc..0b034329b 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -26147,3 +26147,60 @@ comment on function public.ai_traffic_pages(uuid, timestamptz, timestamptz, text
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00187_ai_traffic_digest.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00187: the AI Traffic weekly digest (AT-013)
+-- ============================================================================
+-- Spec §3.8: "A weekly e-mail digest with the summary line and the top three
+-- changes." Sent on Mondays for the week before, per brand, to the Daily
+-- Pulse's recipients (00036), unless the pulse is off (frequency 'off').
+--
+-- * pulse_settings.traffic_digest — on unless an admin or manager turns it
+-- off in Settings › Notifications. A brand with no settings row gets it.
+-- * ai_traffic_digests — one row per brand and week: the claim that stops
+-- a second send, what went out, and when (sent_at, set just before the
+-- e-mail goes, so a stop after the send never mails the week twice). A
+-- claim with no sent_at was left by a sweep that stopped before sending;
+-- the next one (through Wednesday) takes it over.
+--
+-- Written by the Express server's service-role client; members read their
+-- brands' rows, as with sent_pulses.
+
+alter table public.pulse_settings
+ add column if not exists traffic_digest boolean not null default true;
+
+comment on column public.pulse_settings.traffic_digest is
+ 'Whether the AI Traffic weekly digest (AT-013) is e-mailed for the brand, to the pulse''s recipients.';
+
+create table if not exists public.ai_traffic_digests (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands (id) on delete cascade,
+ -- The Monday the reported week starts on (UTC).
+ week_start date not null,
+ payload jsonb not null default '{}'::jsonb,
+ email_sent boolean not null default false,
+ email_recipient_count integer not null default 0,
+ created_at timestamptz not null default now(),
+ sent_at timestamptz,
+ unique (brand_id, week_start)
+);
+
+alter table public.ai_traffic_digests enable row level security;
+
+grant select on public.ai_traffic_digests to authenticated;
+
+create policy "ai_traffic_digests: member select" on public.ai_traffic_digests
+ 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()
+ )
+ );
+
+comment on table public.ai_traffic_digests is
+ 'AI Traffic weekly digests sent (AT-013): one per brand and week, claimed before sending so a week is never mailed twice.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 997e4c9f8..7fbf68f17 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -4500,6 +4500,9 @@
"pulseRecipientsPlaceholder": "[email protected], [email protected]",
"pulseRecipientsHint": "Comma-separated email addresses. Leave empty to send to every organization member.",
"pulseRecipientsInvalid": "Not a valid email address: {emails}. Fix or remove it before saving.",
+ "trafficDigest": "AI Traffic weekly digest",
+ "trafficDigestHint": "Every Monday: last week's AI visits in one summary line, with the top three changes. Sent to the recipients above.",
+ "trafficDigestPulseOff": "Not sent while the Daily Pulse is off. Turn the pulse back on to get it again.",
"pulseSaved": "Notification settings saved",
"pulseSaveFailed": "Could not save notification settings. Please try again.",
"pulseLoadFailed": "Could not load notification settings.",
diff --git a/web/src/app/api/settings/pulse/route.test.ts b/web/src/app/api/settings/pulse/route.test.ts
new file mode 100644
index 000000000..141ca1f7c
--- /dev/null
+++ b/web/src/app/api/settings/pulse/route.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * /api/settings/pulse: the Daily Pulse's delivery per brand, and whether the
+ * AI Traffic weekly digest (AT-013) is on — on unless an admin or manager
+ * turned it off.
+ */
+
+const state = vi.hoisted(() => ({
+ role: 'admin',
+ settings: [] as Record<string, unknown>[],
+ upserts: [] as Record<string, unknown>[],
+}));
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({
+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
+ from: () => ({
+ select: () => ({
+ eq: () => ({
+ single: async () => ({
+ data: { id: 'u1', role: state.role, organization_id: 'o1' },
+ }),
+ }),
+ }),
+ }),
+ }),
+}));
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: (table: string) => {
+ if (table === 'pulse_settings') {
+ return {
+ select: () => ({ in: async () => ({ data: state.settings }) }),
+ upsert: async (row: Record<string, unknown>) => {
+ state.upserts.push(row);
+ return { error: null };
+ },
+ };
+ }
+ // brands: the org's active list, or one brand by id.
+ const list = { data: [{ id: 'b1', name: 'Acme' }], error: null };
+ const chain = {
+ eq: () => chain,
+ order: async () => list,
+ single: async () => ({ data: { id: 'b1', organization_id: 'o1' } }),
+ };
+ return { select: () => chain };
+ },
+ },
+}));
+
+const { GET, PUT } = await import('./route');
+
+const put = (body: Record<string, unknown>) =>
+ PUT(
+ new Request('http://localhost/api/settings/pulse', {
+ method: 'PUT',
+ body: JSON.stringify(body),
+ }),
+ );
+
+beforeEach(() => {
+ state.role = 'admin';
+ state.settings = [];
+ state.upserts = [];
+});
+
+describe('GET /api/settings/pulse', () => {
+ it('has the weekly digest on for a brand nobody configured, and as saved otherwise', async () => {
+ expect((await (await GET()).json()).brands).toEqual([
+ { brandId: 'b1', brandName: 'Acme', frequency: 'daily', recipients: [], trafficDigest: true },
+ ]);
+ state.settings = [
+ {
+ brand_id: 'b1',
+ frequency: 'weekly',
+ recipients: ['[email protected]'],
+ traffic_digest: false,
+ },
+ ];
+ expect((await (await GET()).json()).brands[0]).toMatchObject({
+ frequency: 'weekly',
+ trafficDigest: false,
+ });
+ });
+});
+
+describe('PUT /api/settings/pulse', () => {
+ it('saves the digest switch with the pulse, and leaves it alone when not sent', async () => {
+ expect((await put({ brandId: 'b1', frequency: 'off', trafficDigest: false })).status).toBe(200);
+ expect(state.upserts[0]).toMatchObject({
+ brand_id: 'b1',
+ frequency: 'off',
+ traffic_digest: false,
+ });
+
+ await put({ brandId: 'b1', frequency: 'daily' });
+ expect(state.upserts[1]).not.toHaveProperty('traffic_digest');
+ });
+
+ it('refuses a switch that is not true or false, and members who are not admins or managers', async () => {
+ expect((await put({ brandId: 'b1', frequency: 'daily', trafficDigest: 'no' })).status).toBe(
+ 400,
+ );
+ state.role = 'analyst';
+ expect((await put({ brandId: 'b1', frequency: 'daily', trafficDigest: true })).status).toBe(
+ 403,
+ );
+ expect(state.upserts).toEqual([]);
+ });
+});
diff --git a/web/src/app/api/settings/pulse/route.ts b/web/src/app/api/settings/pulse/route.ts
index c4753656b..b7f8796da 100644
--- a/web/src/app/api/settings/pulse/route.ts
+++ b/web/src/app/api/settings/pulse/route.ts
@@ -6,7 +6,8 @@ import { parseRecipients } from '@/lib/pulse-recipients';
/**
* GET / PUT /api/settings/pulse
*
- * Daily Pulse delivery preferences (#540), per brand.
+ * Daily Pulse delivery preferences (#540), per brand, and whether the AI
+ * Traffic weekly digest (AT-013) goes to the same recipients.
*
* Auth model (same bar as the webhook config RLS):
* - GET: any signed-in org member sees each brand's frequency/recipients.
@@ -60,7 +61,7 @@ export async function GET() {
const { data: settings } = brandIds.length
? await supabaseAdmin
.from('pulse_settings')
- .select('brand_id, frequency, recipients')
+ .select('brand_id, frequency, recipients, traffic_digest')
.in('brand_id', brandIds)
: { data: [] };
@@ -74,6 +75,8 @@ export async function GET() {
brandName: brand.name,
frequency: s?.frequency ?? 'daily',
recipients: s?.recipients ?? [],
+ // On unless turned off (00187).
+ trafficDigest: s?.traffic_digest ?? true,
};
}),
});
@@ -91,7 +94,12 @@ export async function PUT(request: Request) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
- let body: { brandId?: string; frequency?: string; recipients?: unknown };
+ let body: {
+ brandId?: string;
+ frequency?: string;
+ recipients?: unknown;
+ trafficDigest?: unknown;
+ };
try {
body = await request.json();
} catch {
@@ -111,6 +119,9 @@ export async function PUT(request: Request) {
return NextResponse.json({ error: 'Invalid recipient email', invalid }, { status: 400 });
}
const recipients = valid.slice(0, 50);
+ if (body.trafficDigest !== undefined && typeof body.trafficDigest !== 'boolean') {
+ return NextResponse.json({ error: 'trafficDigest must be true or false' }, { status: 400 });
+ }
// The brand must belong to the caller's org.
const { data: brand } = await supabaseAdmin
@@ -127,6 +138,8 @@ export async function PUT(request: Request) {
brand_id: brandId,
frequency,
recipients: recipients.length ? recipients : null,
+ // Left as it is when the caller doesn't say.
+ ...(typeof body.trafficDigest === 'boolean' ? { traffic_digest: body.trafficDigest } : {}),
updated_at: new Date().toISOString(),
},
{ onConflict: 'brand_id' },
diff --git a/web/src/components/settings/notifications-section.test.tsx b/web/src/components/settings/notifications-section.test.tsx
new file mode 100644
index 000000000..2f2e62f86
--- /dev/null
+++ b/web/src/components/settings/notifications-section.test.tsx
@@ -0,0 +1,121 @@
+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';
+
+/**
+ * Settings › Notifications: the AI Traffic weekly digest (AT-013) is turned
+ * on or off per brand beside its Daily Pulse, and saved with it.
+ */
+
+let canManage = true;
+vi.mock('@/hooks/use-user-role', () => ({
+ useUserRole: () => ({ role: canManage ? 'admin' : 'analyst', canManage, canAdmin: canManage }),
+}));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+const { NotificationsSection } = await import('./notifications-section');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const fetchMock = vi.fn();
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ canManage = true;
+ fetchMock.mockReset().mockImplementation(async (_url: string, init?: RequestInit) =>
+ init?.method === 'PUT'
+ ? { ok: true, json: async () => ({ success: true }) }
+ : {
+ ok: true,
+ json: async () => ({
+ brands: [
+ {
+ brandId: 'b1',
+ brandName: 'Acme',
+ frequency: 'daily',
+ recipients: [],
+ trafficDigest: true,
+ },
+ ],
+ }),
+ },
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <NotificationsSection />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const checkbox = () => container.querySelector<HTMLButtonElement>('#traffic-digest-b1')!;
+
+describe('NotificationsSection', () => {
+ it('shows the weekly digest on, and saves it off with the pulse', async () => {
+ await render();
+ expect(container.textContent).toContain('AI Traffic weekly digest');
+ expect(checkbox().getAttribute('data-state')).toBe('checked');
+
+ await act(async () => checkbox().click());
+ expect(checkbox().getAttribute('data-state')).toBe('unchecked');
+ const save = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Save changes',
+ )!;
+ await act(async () => save.click());
+
+ const [, init] = fetchMock.mock.calls.find(([, i]) => i?.method === 'PUT')!;
+ expect(JSON.parse(init.body)).toEqual({
+ brandId: 'b1',
+ frequency: 'daily',
+ recipients: [],
+ trafficDigest: false,
+ });
+ });
+
+ it("shows it off, and can't be turned on, while the brand's pulse is off", async () => {
+ fetchMock.mockImplementation(async () => ({
+ ok: true,
+ json: async () => ({
+ brands: [
+ {
+ brandId: 'b1',
+ brandName: 'Acme',
+ frequency: 'off',
+ recipients: [],
+ trafficDigest: true,
+ },
+ ],
+ }),
+ }));
+ await render();
+ expect(checkbox().getAttribute('data-state')).toBe('unchecked');
+ expect(
+ checkbox().hasAttribute('disabled') || checkbox().getAttribute('data-disabled') !== null,
+ ).toBe(true);
+ expect(container.textContent).toContain('Not sent while the Daily Pulse is off');
+ });
+
+ it('lets members see it but not change it', async () => {
+ canManage = false;
+ await render();
+ expect(checkbox().disabled).toBe(true);
+ });
+});
diff --git a/web/src/components/settings/notifications-section.tsx b/web/src/components/settings/notifications-section.tsx
index daade6645..ca197c8da 100644
--- a/web/src/components/settings/notifications-section.tsx
+++ b/web/src/components/settings/notifications-section.tsx
@@ -6,6 +6,7 @@ import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
@@ -22,7 +23,8 @@ import { parseRecipients } from '@/lib/pulse-recipients';
/**
* Settings → Notifications: Daily Pulse delivery preferences per brand
* (#540). Frequency + optional explicit recipient list; an empty list
- * means every organization member receives the pulse.
+ * means every organization member receives the pulse. The AI Traffic weekly
+ * digest (AT-013) goes to the same recipients, and can be turned off here.
*/
interface BrandPulseSettings {
@@ -30,6 +32,7 @@ interface BrandPulseSettings {
brandName: string;
frequency: string;
recipients: string[];
+ trafficDigest: boolean;
}
const FREQUENCIES = ['daily', 'weekly', 'notable', 'off'] as const;
@@ -69,7 +72,7 @@ export function NotificationsSection() {
void load();
}, [load]);
- async function save(brandId: string, frequency: string) {
+ async function save(brandId: string, frequency: string, trafficDigest: boolean) {
if (savingBrand) return;
const { valid: recipients, invalid } = parseRecipients(
(recipientDrafts[brandId] ?? '').split(','),
@@ -81,7 +84,7 @@ export function NotificationsSection() {
const res = await fetch('/api/settings/pulse', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ brandId, frequency, recipients }),
+ body: JSON.stringify({ brandId, frequency, recipients, trafficDigest }),
});
const body = (await res.json().catch(() => ({}))) as { error?: string; invalid?: string[] };
if (body.invalid?.length) {
@@ -90,7 +93,9 @@ export function NotificationsSection() {
}
if (!res.ok) throw new Error(body.error || 'Save failed');
setBrands((prev) =>
- prev.map((b) => (b.brandId === brandId ? { ...b, frequency, recipients } : b)),
+ prev.map((b) =>
+ b.brandId === brandId ? { ...b, frequency, recipients, trafficDigest } : b,
+ ),
);
setRecipientDrafts((prev) => ({ ...prev, [brandId]: recipients.join(', ') }));
toast.success(t('pulseSaved'));
@@ -167,10 +172,34 @@ export function NotificationsSection() {
<p className="text-xs text-muted-foreground">{t('pulseRecipientsHint')}</p>
)}
</div>
+ <div className="flex items-start gap-2.5">
+ {/* Not sent while the pulse is off; the brand's own choice is kept for when it's back. */}
+ <Checkbox
+ id={`traffic-digest-${brand.brandId}`}
+ className="mt-0.5"
+ checked={brand.trafficDigest && brand.frequency !== 'off'}
+ onCheckedChange={(on) =>
+ setBrands((prev) =>
+ prev.map((b) =>
+ b.brandId === brand.brandId ? { ...b, trafficDigest: on === true } : b,
+ ),
+ )
+ }
+ disabled={!canManage || brand.frequency === 'off'}
+ />
+ <div className="space-y-0.5">
+ <Label htmlFor={`traffic-digest-${brand.brandId}`}>{t('trafficDigest')}</Label>
+ <p className="text-xs text-muted-foreground">
+ {brand.frequency === 'off'
+ ? t('trafficDigestPulseOff')
+ : t('trafficDigestHint')}
+ </p>
+ </div>
+ </div>
{canManage && (
<Button
size="sm"
- onClick={() => save(brand.brandId, brand.frequency)}
+ onClick={() => save(brand.brandId, brand.frequency, brand.trafficDigest)}
disabled={savingBrand !== null}
className="gap-2"
>
diff --git a/web/src/lib/traffic-platforms.test.ts b/web/src/lib/traffic-platforms.test.ts
index 429c1e90a..02abf30d0 100644
--- a/web/src/lib/traffic-platforms.test.ts
+++ b/web/src/lib/traffic-platforms.test.ts
@@ -21,6 +21,21 @@ describe('the AI source list on the page', () => {
}
});
+ it('names every platform in the weekly digest e-mail as the page names it (AT-013)', () => {
+ const digestNames = JSON.parse(
+ readFileSync(
+ join(__dirname, '../../../server/src/lib/traffic-digest/platform-names.json'),
+ 'utf8',
+ ),
+ ) as Record<string, string>;
+ for (const { key } of list.sources) {
+ expect(digestNames[key], key).toBe(getPlatformName(key));
+ }
+ for (const [key, name] of Object.entries(digestNames)) {
+ expect(getPlatformName(key), key).toBe(name);
+ }
+ });
+
it('colors every engine on the list', () => {
const fallback = getColor('not-an-engine.example');
for (const { key } of list.sources) {