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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(reports): templates with section picker, four new modules, deltas and change-story summary (#419)
Gökhan Geyik7d64ed9cbf6a
diff --git a/server/src/routes/reports.js b/server/src/routes/reports.jsindex b2b70e443..24beecc52 100644--- a/server/src/routes/reports.js+++ b/server/src/routes/reports.js@@ -1,7 +1,7 @@/*** Reports routes (Simple Reports MVP).*- * POST /api/reports/summary { brandId, snapshot, dateFrom, dateTo, model? }+ * POST /api/reports/summary { brandId, snapshot, dateFrom, dateTo, template?, model? }* → { success, summary }** Generates the AI executive summary for a report from the metric snapshot the@@ -22,18 +22,34 @@ const router = Router();const SUMMARY_SYSTEM_PROMPT = `You are an AI search visibility analyst writing the executive summary of a brand's AI visibility report.-You will receive a JSON snapshot of the brand's metrics for the report period: overall visibility KPIs (with deltas vs the previous period), share of voice, a competitor comparison, and a citations overview.+You will receive a JSON snapshot of the brand's metrics for the report period. Depending on the report's sections it may include: overall visibility KPIs (with deltas vs the previous period), a daily visibility trend, share of voice, a competitor comparison, per-topic performance, best/weakest prompts, observed query fan-outs, AI-referred traffic, shopping visibility, a site audit score, and a citations overview. Every delta in the snapshot compares against the previous period of equal length.-Write a 1-2 paragraph executive summary in English for a marketing executive:-- Lead with the overall picture (visibility, mentions, citations) and how it changed.-- Call out the most notable competitor dynamics (who leads, who moved).-- Mention citation reach (domains/URLs) only if it adds signal.+Write a 1-2 paragraph executive summary in English for a marketing executive. It must tell the CHANGE STORY of the period, not describe a static snapshot:+- Open with the headline movement as an arc — e.g. "Visibility climbed from 42 to 48" — using the trend's first/last points or the KPI deltas.+- Name the DRIVER behind that movement when the data shows one: the platform, topic or prompt that moved most (share-of-voice shifts, best/weakest prompts, topic deltas).+- Name the biggest RISK when the data shows one: a competitor gaining ground, a topic or platform sliding, or citation share concentrating away from the brand.+- Close with the single most consequential implication or next focus, in one sentence.- Be concrete: use the numbers from the snapshot. Never invent metrics that are not present.+- Cover only what the snapshot contains — reports include different sections, so skip anything absent. If no previous-period data exists, say the period sets the baseline instead of inventing a change.- No headings, no bullet points, no markdown — plain prose only.`;+/**+ * Per-template flavor appended to the system prompt. The snapshot already+ * contains only that template's sections; this just steers the prose focus.+ */+const TEMPLATE_FLAVOR = {+ weekly_visibility:+ 'This is a WEEKLY visibility summary: keep it to one tight paragraph focused on week-over-week movement in visibility, mentions and share of voice.',+ executive_summary: '',+ competitor_benchmark:+ 'This is a COMPETITOR BENCHMARK report: lead with where the brand stands versus each competitor, who gained and who lost, and where the largest gaps are.',+ citation_sources:+ 'This is a CITATION & SOURCES report: focus on citation reach, which domains and source types dominate, and notable concentration or gaps in the source mix.',+};+router.post('/summary', async (req, res) => {const userId = req.user?.id;- const { brandId, snapshot, dateFrom, dateTo, model } = req.body || {};+ const { brandId, snapshot, dateFrom, dateTo, template, model } = req.body || {};if (!brandId || !snapshot || typeof snapshot !== 'object') {return res.status(400).json({ success: false, message: 'brandId and snapshot are required' });@@ -57,9 +73,10 @@ ${JSON.stringify(snapshot, null, 2)}Write the executive summary.`;+ const flavor = TEMPLATE_FLAVOR[template] || '';const { text: summary } = await generateText({model: resolveModel(model),- system: SUMMARY_SYSTEM_PROMPT,+ system: flavor ? `${SUMMARY_SYSTEM_PROMPT}\n\n${flavor}` : SUMMARY_SYSTEM_PROMPT,prompt: userPrompt,});diff --git a/web/messages/en.json b/web/messages/en.jsonindex d73579237..555d17ee5 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -407,6 +407,41 @@"deleteConfirm": "Delete this report?","deleteFailed": "Failed to delete report","selectDates": "Pick a start and end date",+ "templateLabel": "Template",+ "templates": {+ "weekly_visibility": {+ "name": "Weekly Visibility Summary",+ "description": "A tight weekly pulse: visibility KPIs, trend and share of voice."+ },+ "executive_summary": {+ "name": "Monthly Executive Report",+ "description": "The full picture: every section, ready for a monthly review."+ },+ "competitor_benchmark": {+ "name": "Competitor Benchmark",+ "description": "Where you stand against each competitor, and who moved."+ },+ "citation_sources": {+ "name": "Citation & Sources Report",+ "description": "Which domains and source types AI engines cite around your brand."+ }+ },+ "sections": {+ "kpis": "KPIs",+ "trend": "Trend",+ "shareOfVoice": "Share of Voice",+ "competitors": "Competitors",+ "topicPerformance": "Topics",+ "promptPerformance": "Prompts",+ "queryFanout": "Fan-out",+ "aiTraffic": "AI Traffic",+ "shoppingVisibility": "Shopping",+ "auditScore": "Audit Score",+ "citations": "Citations"+ },+ "brandLabel": "Brand",+ "sectionsLabel": "Sections",+ "selectSections": "Pick at least one section","dialogTitle": "Generate Report","dialogDescription": "Snapshot your brand's AI visibility for a period, with an AI-written executive summary.","reportTitleLabel": "Title (optional)",@@ -431,7 +466,22 @@"runs": "Runs","query": "Query","engines": "Engines",- "timesSearched": "Times Searched"+ "timesSearched": "Times Searched",+ "topic": "Topic",+ "results": "Results",+ "platform": "Platform",+ "topPages": "Top Pages"+ },+ "topicPerformance": "Topic Performance",+ "aiTraffic": "AI Traffic",+ "shoppingVisibility": "Shopping Visibility",+ "auditScore": "Site Audit Score",+ "auditedOn": "Audited on",+ "shopping": {+ "sov": "Shopping SoV",+ "products": "Products Surfaced",+ "cardRate": "Card Rate",+ "topMerchant": "Top Merchant"},"visibilityTrend": "Visibility Trend","bestPrompts": "Best Performing Prompts",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsxindex 41bbb8236..9ab4f1812 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx@@ -228,7 +228,9 @@ function formatDate(iso: string) {export function ReportPdfDocument({ report }: { report: Report }) {const { payload } = report;- const maxSov = Math.max(...payload.shareOfVoice.byPlatform.map((p) => p.sov), 1);+ // Every metric field is optional — templates only gather their own+ // sections, so each block below guards on its payload field.+ const maxSov = Math.max(...(payload.shareOfVoice?.byPlatform.map((p) => p.sov) ?? []), 1);const trend = payload.visibilityTrend ?? [];const hasCompetitorTrend = trend.some((d) => d.competitors !== null);@@ -250,36 +252,42 @@ export function ReportPdfDocument({ report }: { report: Report }) {</View>{/* KPI row */}- <View style={[styles.section, styles.kpiRow]} wrap={false}>- {(- [+ {payload.insights && (+ <View style={[styles.section, styles.kpiRow]} wrap={false}>+ {([- 'Visibility',- `${payload.insights.avgVisibilityScore}%`,- payload.insights.visibilityChange,- ],- ['Mentions', String(payload.insights.totalMentions), payload.insights.mentionsChange],- [- 'Citations',- String(payload.insights.totalCitations),- payload.insights.citationsChange,- ],- [- 'Positive Sentiment',- `${payload.insights.positiveSentimentPct}%`,- payload.insights.sentimentChange,- ],- ] as const- ).map(([label, value, change]) => (- <View key={label} style={styles.kpiBox}>- <Text style={styles.kpiLabel}>{label}</Text>- <View style={styles.kpiValueRow}>- <Text style={styles.kpiValue}>{value}</Text>- <DeltaText value={change} />+ [+ 'Visibility',+ `${payload.insights.avgVisibilityScore}%`,+ payload.insights.visibilityChange,+ ],+ [+ 'Mentions',+ String(payload.insights.totalMentions),+ payload.insights.mentionsChange,+ ],+ [+ 'Citations',+ String(payload.insights.totalCitations),+ payload.insights.citationsChange,+ ],+ [+ 'Positive Sentiment',+ `${payload.insights.positiveSentimentPct}%`,+ payload.insights.sentimentChange,+ ],+ ] as const+ ).map(([label, value, change]) => (+ <View key={label} style={styles.kpiBox}>+ <Text style={styles.kpiLabel}>{label}</Text>+ <View style={styles.kpiValueRow}>+ <Text style={styles.kpiValue}>{value}</Text>+ <DeltaText value={change} />+ </View></View>- </View>- ))}- </View>+ ))}+ </View>+ )}{/* Visibility trend */}{trend.length > 1 && (@@ -306,22 +314,24 @@ export function ReportPdfDocument({ report }: { report: Report }) {)}{/* Share of Voice */}- <View style={styles.section} wrap={false}>- <Text style={styles.sectionTitle}>- Share of Voice — {payload.shareOfVoice.overallSov}%- </Text>- {payload.shareOfVoice.byPlatform.map((p) => (- <HBar- key={p.provider}- label={p.provider}- pct={(p.sov / maxSov) * 100}- value={`${p.sov}%`}- />- ))}- </View>+ {payload.shareOfVoice && (+ <View style={styles.section} wrap={false}>+ <Text style={styles.sectionTitle}>+ Share of Voice — {payload.shareOfVoice.overallSov}%+ </Text>+ {payload.shareOfVoice.byPlatform.map((p) => (+ <HBar+ key={p.provider}+ label={p.provider}+ pct={(p.sov / maxSov) * 100}+ value={`${p.sov}%`}+ />+ ))}+ </View>+ )}{/* Competitor leaderboard */}- {payload.competitors.length > 0 && (+ {payload.competitors && payload.competitors.length > 0 && (<View style={styles.section} wrap={false}><Text style={styles.sectionTitle}>Competitor Leaderboard</Text><View style={styles.tableHeader}>@@ -368,6 +378,39 @@ export function ReportPdfDocument({ report }: { report: Report }) {</View>)}+ {/* Topic performance */}+ {payload.topicPerformance && payload.topicPerformance.length > 0 && (+ <View style={styles.section} wrap={false}>+ <Text style={styles.sectionTitle}>Topic Performance</Text>+ <View style={styles.tableHeader}>+ <Text style={[styles.tableHeaderCell, { flex: 1 }]}>Topic</Text>+ <Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>+ Visibility+ </Text>+ <Text style={[styles.tableHeaderCell, { width: 50, textAlign: 'right' }]}>+ Change+ </Text>+ <Text style={[styles.tableHeaderCell, { width: 50, textAlign: 'right' }]}>+ Results+ </Text>+ </View>+ {payload.topicPerformance.map((tp) => (+ <View key={tp.name} style={styles.tableRow}>+ <Text style={[styles.cell, { flex: 1, paddingRight: 8 }]}>{tp.name}</Text>+ <Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>+ {tp.avgVisibility}%+ </Text>+ <View style={{ width: 50, alignItems: 'flex-end' }}>+ <DeltaText value={tp.change} />+ </View>+ <Text style={[styles.cell, { width: 50, textAlign: 'right', color: MUTED }]}>+ {tp.results}+ </Text>+ </View>+ ))}+ </View>+ )}+{/* Best / worst prompts */}{payload.promptPerformance && payload.promptPerformance.best.length > 0 && (<PromptTable title="Best Performing Prompts" prompts={payload.promptPerformance.best} />@@ -401,39 +444,134 @@ export function ReportPdfDocument({ report }: { report: Report }) {</View>)}- {/* Citations */}- <View style={styles.section} wrap={false}>- <Text style={styles.sectionTitle}>- Top Citation Sources — {payload.citations.totals.domains} domains ·{' '}- {payload.citations.totals.citations} citations- </Text>- {payload.citations.topDomains.length > 0 && (- <View style={{ marginTop: 8 }}>- <View style={styles.tableHeader}>- <Text style={[styles.tableHeaderCell, { flex: 1 }]}>Domain</Text>- <Text style={[styles.tableHeaderCell, { width: 80 }]}>Source Type</Text>- <Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>- Citations- </Text>- <Text style={[styles.tableHeaderCell, { width: 50, textAlign: 'right' }]}>- Usage+ {/* AI traffic */}+ {payload.aiTraffic && (+ <View style={styles.section} wrap={false}>+ <View style={{ flexDirection: 'row', alignItems: 'flex-end', gap: 6 }}>+ <Text style={styles.sectionTitle}>+ AI Traffic — {payload.aiTraffic.totalVisits} visits+ </Text>+ <View style={{ marginBottom: 6 }}>+ <DeltaText value={payload.aiTraffic.change} />+ </View>+ </View>+ {payload.aiTraffic.platformBreakdown.map((p) => (+ <View key={p.platform} style={styles.tableRow}>+ <Text style={[styles.cell, { flex: 1 }]}>{p.platform}</Text>+ <Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>{p.visits}</Text>+ </View>+ ))}+ {payload.aiTraffic.topPages.length > 0 && (+ <View style={{ marginTop: 6 }}>+ <View style={styles.tableHeader}>+ <Text style={[styles.tableHeaderCell, { flex: 1 }]}>Top Page</Text>+ <Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>+ Visits+ </Text>+ </View>+ {payload.aiTraffic.topPages.map((p) => (+ <View key={p.url} style={styles.tableRow}>+ <Text style={[styles.cell, { flex: 1, paddingRight: 8 }]}>{p.url}</Text>+ <Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>{p.visits}</Text>+ </View>+ ))}+ </View>+ )}+ </View>+ )}++ {/* Shopping visibility */}+ {payload.shoppingVisibility && (+ <View style={styles.section} wrap={false}>+ <Text style={styles.sectionTitle}>Shopping Visibility</Text>+ <View style={styles.kpiRow}>+ <View style={styles.kpiBox}>+ <Text style={styles.kpiLabel}>Shopping SoV</Text>+ <View style={styles.kpiValueRow}>+ <Text style={styles.kpiValue}>{payload.shoppingVisibility.shoppingSovPct}%</Text>+ <DeltaText value={payload.shoppingVisibility.sovChange} />+ </View>+ </View>+ <View style={styles.kpiBox}>+ <Text style={styles.kpiLabel}>Products Surfaced</Text>+ <Text style={styles.kpiValue}>{payload.shoppingVisibility.productsSurfaced}</Text>+ </View>+ <View style={styles.kpiBox}>+ <Text style={styles.kpiLabel}>Card Rate</Text>+ <Text style={styles.kpiValue}>{payload.shoppingVisibility.cardRatePct}%</Text>+ </View>+ <View style={styles.kpiBox}>+ <Text style={styles.kpiLabel}>Top Merchant</Text>+ <Text style={[styles.cell, { fontWeight: 700 }]}>+ {payload.shoppingVisibility.topMerchant ?? '—'}</Text></View>- {payload.citations.topDomains.map((d) => (- <View key={d.domain} style={styles.tableRow}>- <Text style={[styles.cell, { flex: 1, paddingRight: 8 }]}>{d.domain}</Text>- <Text style={[styles.cell, { width: 80, color: MUTED }]}>{d.category}</Text>- <Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>- {d.totalCitations}+ </View>+ </View>+ )}++ {/* Site audit score */}+ {payload.auditScore && (+ <View style={styles.section} wrap={false}>+ <Text style={styles.sectionTitle}>Site Audit Score</Text>+ <View style={{ flexDirection: 'row', alignItems: 'flex-end', gap: 8 }}>+ <Text style={{ fontSize: 18, fontWeight: 700 }}>+ {payload.auditScore.totalScore ?? '—'}+ </Text>+ {payload.auditScore.totalScore !== null &&+ payload.auditScore.previousScore !== null && (+ <View style={{ marginBottom: 2 }}>+ <DeltaText+ value={+ Math.round(+ (payload.auditScore.totalScore - payload.auditScore.previousScore) * 10,+ ) / 10+ }+ />+ </View>+ )}+ <Text style={[styles.cell, { color: MUTED, marginBottom: 2 }]}>+ {payload.auditScore.url} · audited {formatDate(payload.auditScore.auditedAt)}+ </Text>+ </View>+ </View>+ )}++ {/* Citations */}+ {payload.citations && (+ <View style={styles.section} wrap={false}>+ <Text style={styles.sectionTitle}>+ Top Citation Sources — {payload.citations.totals.domains} domains ·{' '}+ {payload.citations.totals.citations} citations+ </Text>+ {payload.citations.topDomains.length > 0 && (+ <View style={{ marginTop: 8 }}>+ <View style={styles.tableHeader}>+ <Text style={[styles.tableHeaderCell, { flex: 1 }]}>Domain</Text>+ <Text style={[styles.tableHeaderCell, { width: 80 }]}>Source Type</Text>+ <Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>+ Citations</Text>- <Text style={[styles.cell, { width: 50, textAlign: 'right' }]}>- {d.usagePct}%+ <Text style={[styles.tableHeaderCell, { width: 50, textAlign: 'right' }]}>+ Usage</Text></View>- ))}- </View>- )}- </View>+ {payload.citations.topDomains.map((d) => (+ <View key={d.domain} style={styles.tableRow}>+ <Text style={[styles.cell, { flex: 1, paddingRight: 8 }]}>{d.domain}</Text>+ <Text style={[styles.cell, { width: 80, color: MUTED }]}>{d.category}</Text>+ <Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>+ {d.totalCitations}+ </Text>+ <Text style={[styles.cell, { width: 50, textAlign: 'right' }]}>+ {d.usagePct}%+ </Text>+ </View>+ ))}+ </View>+ )}+ </View>+ )}{/* Footer */}<View style={styles.footer} fixed>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsxindex 0973688d0..5b0bdffe7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx@@ -28,6 +28,9 @@ import {import { ArrowLeft, FileDown, Loader2 } from 'lucide-react';import { cn } from '@/lib/utils';import { PLATFORM_LABELS } from '@/config/platform-labels';+import { REPORT_TEMPLATES } from '@/lib/reports/templates';++const KNOWN_TEMPLATE_IDS = new Set<string>(REPORT_TEMPLATES.map((tpl) => tpl.id));function formatDate(iso: string) {return new Date(iso).toLocaleDateString('en-US', {@@ -121,7 +124,7 @@ export default function ReportDetailPage() {}const { payload } = report;- const maxSov = Math.max(...payload.shareOfVoice.byPlatform.map((p) => p.sov), 1);+ const maxSov = Math.max(...(payload.shareOfVoice?.byPlatform.map((p) => p.sov) ?? []), 1);// Render a true vector PDF from the saved payload with @react-pdf/renderer// (selectable text, exact layout — no screenshot artifacts). The renderer@@ -168,6 +171,9 @@ export default function ReportDetailPage() {</Link><h1 className="text-2xl font-bold tracking-tight">{report.title}</h1><p className="text-sm text-muted-foreground">+ {KNOWN_TEMPLATE_IDS.has(report.template) && (+ <>{t(`templates.${report.template}.name`)} · </>+ )}{formatDate(report.dateFrom)} — {formatDate(report.dateTo)} · {t('generatedOn')}{' '}{formatDate(report.createdAt)}</p>@@ -196,31 +202,33 @@ export default function ReportDetailPage() {</CardContent></Card>- <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">- <KpiCard- label={t('kpi.visibility')}- value={`${payload.insights.avgVisibilityScore}%`}- change={payload.insights.visibilityChange}- />- <KpiCard- label={t('kpi.mentions')}- value={String(payload.insights.totalMentions)}- change={payload.insights.mentionsChange}- />- <KpiCard- label={t('kpi.citations')}- value={String(payload.insights.totalCitations)}- change={payload.insights.citationsChange}- />- <KpiCard- label={t('kpi.sentiment')}- value={`${payload.insights.positiveSentimentPct}%`}- change={payload.insights.sentimentChange}- />- </div>-- {/* Optional sections below guard on their payload field: reports- generated before a section shipped simply don't render it. */}+ {/* Every metric section guards on its payload field: templates only+ gather their own sections, and older (immutable) reports may+ predate a field entirely. */}+ {payload.insights && (+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">+ <KpiCard+ label={t('kpi.visibility')}+ value={`${payload.insights.avgVisibilityScore}%`}+ change={payload.insights.visibilityChange}+ />+ <KpiCard+ label={t('kpi.mentions')}+ value={String(payload.insights.totalMentions)}+ change={payload.insights.mentionsChange}+ />+ <KpiCard+ label={t('kpi.citations')}+ value={String(payload.insights.totalCitations)}+ change={payload.insights.citationsChange}+ />+ <KpiCard+ label={t('kpi.sentiment')}+ value={`${payload.insights.positiveSentimentPct}%`}+ change={payload.insights.sentimentChange}+ />+ </div>+ )}{payload.visibilityTrend && payload.visibilityTrend.length > 0 && (<Card><CardHeader>@@ -232,74 +240,114 @@ export default function ReportDetailPage() {</Card>)}- <Card>- <CardHeader>- <CardTitle className="flex items-baseline gap-2 text-base">- {t('shareOfVoice')}- <span className="text-2xl font-bold">{payload.shareOfVoice.overallSov}%</span>- <Delta value={payload.shareOfVoice.overallSovChange} />- </CardTitle>- </CardHeader>- <CardContent className="space-y-3">- {payload.shareOfVoice.byPlatform.length === 0 ? (- <p className="text-sm text-muted-foreground">{t('noData')}</p>- ) : (- payload.shareOfVoice.byPlatform.map((p) => (- <div key={p.provider} className="flex items-center gap-3">- <span className="w-32 shrink-0 truncate text-sm">{p.provider}</span>- <div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">- <div- className="h-full rounded-full bg-primary"- style={{ width: `${Math.min((p.sov / maxSov) * 100, 100)}%` }}- />+ {payload.shareOfVoice && (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-baseline gap-2 text-base">+ {t('shareOfVoice')}+ <span className="text-2xl font-bold">{payload.shareOfVoice.overallSov}%</span>+ <Delta value={payload.shareOfVoice.overallSovChange} />+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-3">+ {payload.shareOfVoice.byPlatform.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('noData')}</p>+ ) : (+ payload.shareOfVoice.byPlatform.map((p) => (+ <div key={p.provider} className="flex items-center gap-3">+ <span className="w-32 shrink-0 truncate text-sm">{p.provider}</span>+ <div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">+ <div+ className="h-full rounded-full bg-primary"+ style={{ width: `${Math.min((p.sov / maxSov) * 100, 100)}%` }}+ />+ </div>+ <span className="w-14 shrink-0 text-right text-sm font-medium">{p.sov}%</span></div>- <span className="w-14 shrink-0 text-right text-sm font-medium">{p.sov}%</span>- </div>- ))- )}- </CardContent>- </Card>+ ))+ )}+ </CardContent>+ </Card>+ )}- <Card>- <CardHeader>- <CardTitle className="text-base">{t('competitorLeaderboard')}</CardTitle>- </CardHeader>- <CardContent>- {payload.competitors.length === 0 ? (- <p className="text-sm text-muted-foreground">{t('noData')}</p>- ) : (+ {payload.competitors && (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">{t('competitorLeaderboard')}</CardTitle>+ </CardHeader>+ <CardContent>+ {payload.competitors.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('noData')}</p>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('columns.brand')}</TableHead>+ <TableHead className="text-right">{t('kpi.visibility')}</TableHead>+ <TableHead className="text-right">{t('columns.change')}</TableHead>+ <TableHead className="text-right">{t('kpi.mentions')}</TableHead>+ <TableHead className="text-right">{t('kpi.citations')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {payload.competitors.map((c) => (+ <TableRow key={c.name} className={cn(c.isOwnBrand && 'bg-primary/5')}>+ <TableCell className={cn('font-medium', c.isOwnBrand && 'text-primary')}>+ {c.name}+ {c.isOwnBrand && (+ <span className="ml-2 text-xs text-muted-foreground">{t('you')}</span>+ )}+ </TableCell>+ <TableCell className="text-right">{c.avgVisibilityScore}%</TableCell>+ <TableCell className="text-right">+ <Delta value={c.change} />+ </TableCell>+ <TableCell className="text-right">{c.totalMentions}</TableCell>+ <TableCell className="text-right">{c.totalCitations}</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </CardContent>+ </Card>+ )}++ {payload.topicPerformance && payload.topicPerformance.length > 0 && (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">{t('topicPerformance')}</CardTitle>+ </CardHeader>+ <CardContent><Table><TableHeader><TableRow>- <TableHead>{t('columns.brand')}</TableHead>- <TableHead className="text-right">{t('kpi.visibility')}</TableHead>- <TableHead className="text-right">{t('columns.change')}</TableHead>- <TableHead className="text-right">{t('kpi.mentions')}</TableHead>- <TableHead className="text-right">{t('kpi.citations')}</TableHead>+ <TableHead>{t('columns.topic')}</TableHead>+ <TableHead className="w-28 text-right">{t('kpi.visibility')}</TableHead>+ <TableHead className="w-24 text-right">{t('columns.change')}</TableHead>+ <TableHead className="w-24 text-right">{t('columns.results')}</TableHead></TableRow></TableHeader><TableBody>- {payload.competitors.map((c) => (- <TableRow key={c.name} className={cn(c.isOwnBrand && 'bg-primary/5')}>- <TableCell className={cn('font-medium', c.isOwnBrand && 'text-primary')}>- {c.name}- {c.isOwnBrand && (- <span className="ml-2 text-xs text-muted-foreground">{t('you')}</span>- )}+ {payload.topicPerformance.map((tp) => (+ <TableRow key={tp.name}>+ <TableCell className="max-w-[280px] truncate font-medium">+ {tp.name}</TableCell>- <TableCell className="text-right">{c.avgVisibilityScore}%</TableCell>+ <TableCell className="text-right">{tp.avgVisibility}%</TableCell><TableCell className="text-right">- <Delta value={c.change} />+ <Delta value={tp.change} />+ </TableCell>+ <TableCell className="text-right text-muted-foreground">+ {tp.results}</TableCell>- <TableCell className="text-right">{c.totalMentions}</TableCell>- <TableCell className="text-right">{c.totalCitations}</TableCell></TableRow>))}</TableBody></Table>- )}- </CardContent>- </Card>+ </CardContent>+ </Card>+ )}{payload.promptPerformance &&(payload.promptPerformance.best.length > 0 ||@@ -382,45 +430,163 @@ export default function ReportDetailPage() {</Card>)}- <Card>- <CardHeader>- <CardTitle className="text-base">{t('topCitationSources')}</CardTitle>- <p className="text-sm text-muted-foreground">- {t('citationTotals', {- domains: payload.citations.totals.domains,- citations: payload.citations.totals.citations,- })}- </p>- </CardHeader>- <CardContent className="space-y-4">- {payload.citations.topDomains.length === 0 ? (- <p className="text-sm text-muted-foreground">{t('noData')}</p>- ) : (- <Table>- <TableHeader>- <TableRow>- <TableHead>{t('columns.domain')}</TableHead>- <TableHead>{t('columns.sourceType')}</TableHead>- <TableHead className="text-right">{t('kpi.citations')}</TableHead>- <TableHead className="text-right">{t('columns.usage')}</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {payload.citations.topDomains.map((d) => (- <TableRow key={d.domain}>- <TableCell className="font-medium">{d.domain}</TableCell>- <TableCell className="capitalize text-muted-foreground">- {d.category}- </TableCell>- <TableCell className="text-right">{d.totalCitations}</TableCell>- <TableCell className="text-right">{d.usagePct}%</TableCell>+ {payload.aiTraffic && (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-baseline gap-2 text-base">+ {t('aiTraffic')}+ <span className="text-2xl font-bold">{payload.aiTraffic.totalVisits}</span>+ <Delta value={payload.aiTraffic.change} />+ </CardTitle>+ </CardHeader>+ <CardContent className="grid gap-6 sm:grid-cols-2">+ <div className="space-y-2">+ <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t('columns.platform')}+ </p>+ {payload.aiTraffic.platformBreakdown.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('noData')}</p>+ ) : (+ payload.aiTraffic.platformBreakdown.map((p) => (+ <div key={p.platform} className="flex items-center justify-between text-sm">+ <span className="truncate">{PLATFORM_LABELS[p.platform] ?? p.platform}</span>+ <span className="font-medium tabular-nums">{p.visits}</span>+ </div>+ ))+ )}+ </div>+ <div className="space-y-2">+ <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t('columns.topPages')}+ </p>+ {payload.aiTraffic.topPages.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('noData')}</p>+ ) : (+ payload.aiTraffic.topPages.map((p) => (+ <div key={p.url} className="flex items-center justify-between gap-3 text-sm">+ <span className="min-w-0 truncate text-muted-foreground">{p.url}</span>+ <span className="shrink-0 font-medium tabular-nums">{p.visits}</span>+ </div>+ ))+ )}+ </div>+ </CardContent>+ </Card>+ )}++ {payload.shoppingVisibility && (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">{t('shoppingVisibility')}</CardTitle>+ </CardHeader>+ <CardContent className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">+ <div>+ <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t('shopping.sov')}+ </p>+ <div className="mt-1 flex items-baseline gap-2">+ <span className="text-2xl font-bold">+ {payload.shoppingVisibility.shoppingSovPct}%+ </span>+ <Delta value={payload.shoppingVisibility.sovChange} />+ </div>+ </div>+ <div>+ <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t('shopping.products')}+ </p>+ <p className="mt-1 text-2xl font-bold">+ {payload.shoppingVisibility.productsSurfaced}+ </p>+ </div>+ <div>+ <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t('shopping.cardRate')}+ </p>+ <p className="mt-1 text-2xl font-bold">{payload.shoppingVisibility.cardRatePct}%</p>+ </div>+ <div>+ <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t('shopping.topMerchant')}+ </p>+ <p className="mt-1 truncate text-sm font-medium">+ {payload.shoppingVisibility.topMerchant ?? '—'}+ </p>+ </div>+ </CardContent>+ </Card>+ )}++ {payload.auditScore && (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">{t('auditScore')}</CardTitle>+ </CardHeader>+ <CardContent className="flex items-center gap-6">+ <div className="flex items-baseline gap-2">+ <span className="text-3xl font-bold">{payload.auditScore.totalScore ?? '—'}</span>+ {payload.auditScore.totalScore !== null &&+ payload.auditScore.previousScore !== null && (+ <Delta+ value={+ Math.round(+ (payload.auditScore.totalScore - payload.auditScore.previousScore) * 10,+ ) / 10+ }+ />+ )}+ </div>+ <div className="min-w-0">+ <p className="truncate text-sm font-medium">{payload.auditScore.url}</p>+ <p className="text-xs text-muted-foreground">+ {t('auditedOn')} {formatDate(payload.auditScore.auditedAt)}+ </p>+ </div>+ </CardContent>+ </Card>+ )}++ {payload.citations && (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">{t('topCitationSources')}</CardTitle>+ <p className="text-sm text-muted-foreground">+ {t('citationTotals', {+ domains: payload.citations.totals.domains,+ citations: payload.citations.totals.citations,+ })}+ </p>+ </CardHeader>+ <CardContent className="space-y-4">+ {payload.citations.topDomains.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('noData')}</p>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('columns.domain')}</TableHead>+ <TableHead>{t('columns.sourceType')}</TableHead>+ <TableHead className="text-right">{t('kpi.citations')}</TableHead>+ <TableHead className="text-right">{t('columns.usage')}</TableHead></TableRow>- ))}- </TableBody>- </Table>- )}- </CardContent>- </Card>+ </TableHeader>+ <TableBody>+ {payload.citations.topDomains.map((d) => (+ <TableRow key={d.domain}>+ <TableCell className="font-medium">{d.domain}</TableCell>+ <TableCell className="capitalize text-muted-foreground">+ {d.category}+ </TableCell>+ <TableCell className="text-right">{d.totalCitations}</TableCell>+ <TableCell className="text-right">{d.usagePct}%</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </CardContent>+ </Card>+ )}</div></div>);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsxindex 29b27ec34..6db3b7350 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx@@ -25,11 +25,26 @@ import {TableHeader,TableRow,} from '@/components/ui/table';-import { FileBarChart, Loader2, Plus, Trash2 } from 'lucide-react';+import { Check, FileBarChart, Loader2, Plus, Trash2 } from 'lucide-react';import { cn } from '@/lib/utils';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import {+ REPORT_TEMPLATES,+ ALL_REPORT_SECTIONS,+ type ReportSection,+ type ReportTemplateId,+} from '@/lib/reports/templates';type DatePreset = '7d' | '30d' | '90d' | 'custom';+const KNOWN_TEMPLATE_IDS = new Set<string>(REPORT_TEMPLATES.map((tpl) => tpl.id));+/** Resolve a preset into the concrete [from, to] ISO range a report snapshots. */function getDateRange(preset: DatePreset, custom: { from: string; to: string }) {if (preset === 'custom') {@@ -58,6 +73,7 @@ export default function ReportsPage() {const tc = useTranslations('common');const router = useRouter();const activeBrandId = useBrandStore((s) => s.activeBrandId);+ const brands = useBrandStore((s) => s.brands);const [reports, setReports] = useState<ReportListItem[]>([]);const [loading, setLoading] = useState(true);@@ -65,9 +81,48 @@ export default function ReportsPage() {const [generating, setGenerating] = useState(false);const [deletingId, setDeletingId] = useState<string | null>(null);+ const [template, setTemplate] = useState<ReportTemplateId>('executive_summary');const [preset, setPreset] = useState<DatePreset>('30d');const [customRange, setCustomRange] = useState({ from: '', to: '' });const [reportTitle, setReportTitle] = useState('');+ // US-1.1: the dialog can generate for any brand, defaulting to the active one.+ const [reportBrandId, setReportBrandId] = useState<string | null>(activeBrandId);+ // US-1.3: templates only pre-select; the user adjusts the module set freely.+ const [sections, setSections] = useState<Set<ReportSection>>(+ () => new Set(REPORT_TEMPLATES.find((tpl) => tpl.id === 'executive_summary')!.sections),+ );++ const reportBrand = brands.find((b) => b.id === (reportBrandId ?? activeBrandId));+ // Shopping is brand-pref-gated: hidden here exactly like the sidebar hides+ // the Shopping nav item (and the server refuses to gather it regardless).+ const pickableSections = ALL_REPORT_SECTIONS.filter(+ (s) => s !== 'shoppingVisibility' || reportBrand?.shoppingModeEnabled,+ );++ const selectTemplate = (id: ReportTemplateId) => {+ setTemplate(id);+ // Templates carry a sensible default window (weekly → 7d) and a default+ // module set; the user can still override both below.+ const def = REPORT_TEMPLATES.find((tpl) => tpl.id === id);+ if (def) {+ setPreset(def.defaultPreset);+ setSections(new Set(def.sections));+ }+ };++ const toggleSection = (s: ReportSection) => {+ setSections((prev) => {+ const next = new Set(prev);+ if (next.has(s)) next.delete(s);+ else next.add(s);+ return next;+ });+ };++ const openDialog = () => {+ setReportBrandId(activeBrandId);+ setDialogOpen(true);+ };const load = useCallback(async () => {if (!activeBrandId) return;@@ -87,18 +142,25 @@ export default function ReportsPage() {}, [load]);const handleGenerate = async () => {- if (!activeBrandId) return;+ const targetBrandId = reportBrandId ?? activeBrandId;+ if (!targetBrandId) return;const { dateFrom, dateTo } = getDateRange(preset, customRange);if (!dateFrom || !dateTo) {toast.error(t('selectDates'));return;}+ if (sections.size === 0) {+ toast.error(t('selectSections'));+ return;+ }setGenerating(true);try {- const { id } = await createReport(activeBrandId, {+ const { id } = await createReport(targetBrandId, {dateFrom,dateTo,title: reportTitle || undefined,+ template,+ sections: pickableSections.filter((s) => sections.has(s)),});toast.success(t('generated'));setDialogOpen(false);@@ -132,7 +194,7 @@ export default function ReportsPage() {<h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1><p className="text-muted-foreground">{t('description')}</p></div>- <Button className="gap-2" onClick={() => setDialogOpen(true)} disabled={!activeBrandId}>+ <Button className="gap-2" onClick={openDialog} disabled={!activeBrandId}><Plus className="h-4 w-4" />{t('generateReport')}</Button>@@ -166,7 +228,14 @@ export default function ReportsPage() {<TableBody>{reports.map((report) => (<TableRow key={report.id}>- <TableCell className="font-medium">{report.title}</TableCell>+ <TableCell>+ <span className="font-medium">{report.title}</span>+ {KNOWN_TEMPLATE_IDS.has(report.template) && (+ <span className="mt-0.5 block text-xs text-muted-foreground">+ {t(`templates.${report.template}.name`)}+ </span>+ )}+ </TableCell><TableCell className="text-muted-foreground">{formatDate(report.dateFrom)} — {formatDate(report.dateTo)}</TableCell>@@ -206,13 +275,108 @@ export default function ReportsPage() {</Card><Dialog open={dialogOpen} onOpenChange={(open) => !generating && setDialogOpen(open)}>- <DialogContent className="sm:max-w-md">+ <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-xl"><DialogHeader><DialogTitle>{t('dialogTitle')}</DialogTitle><DialogDescription>{t('dialogDescription')}</DialogDescription></DialogHeader><div className="space-y-4 py-2">+ <div className="space-y-2">+ <p className="text-sm font-medium">{t('templateLabel')}</p>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {REPORT_TEMPLATES.map((tpl) => (+ <button+ key={tpl.id}+ type="button"+ onClick={() => selectTemplate(tpl.id)}+ disabled={generating}+ className={cn(+ 'rounded-lg border p-3 text-left transition-colors',+ template === tpl.id+ ? 'border-primary bg-primary/5'+ : 'border-border hover:border-muted-foreground/40',+ )}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-medium">{t(`templates.${tpl.id}.name`)}</span>+ <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">+ {t(`presets.${tpl.defaultPreset}`)}+ </span>+ </div>+ <p className="mt-1 text-xs text-muted-foreground">+ {t(`templates.${tpl.id}.description`)}+ </p>+ <div className="mt-2 flex flex-wrap gap-1">+ {tpl.sections.map((s) => (+ <span+ key={s}+ className="rounded-full border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground"+ >+ {t(`sections.${s}`)}+ </span>+ ))}+ </div>+ </button>+ ))}+ </div>+ </div>++ {brands.length > 1 && (+ <div className="space-y-2">+ <p className="text-sm font-medium">{t('brandLabel')}</p>+ <Select value={reportBrandId ?? ''} onValueChange={(v) => v && setReportBrandId(v)}>+ <SelectTrigger className="w-full" disabled={generating}>+ <SelectValue>+ {(v: string) => brands.find((b) => b.id === v)?.name ?? t('brandLabel')}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {brands.map((b) => (+ <SelectItem key={b.id} value={b.id}>+ {b.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}++ <div className="space-y-2">+ <p className="text-sm font-medium">{t('sectionsLabel')}</p>+ <div className="grid grid-cols-2 gap-1.5 sm:grid-cols-3">+ {pickableSections.map((s) => {+ const on = sections.has(s);+ return (+ <button+ key={s}+ type="button"+ onClick={() => toggleSection(s)}+ disabled={generating}+ className={cn(+ 'flex items-center gap-2 rounded-md border px-2.5 py-1.5 text-left text-xs transition-colors',+ on+ ? 'border-primary bg-primary/5'+ : 'border-border text-muted-foreground hover:border-muted-foreground/40',+ )}+ >+ <span+ className={cn(+ 'flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border',+ on+ ? 'border-primary bg-primary text-primary-foreground'+ : 'border-muted-foreground/30',+ )}+ >+ {on && <Check className="h-2.5 w-2.5" />}+ </span>+ {t(`sections.${s}`)}+ </button>+ );+ })}+ </div>+ </div>+<div className="space-y-2"><p className="text-sm font-medium">{t('reportTitleLabel')}</p><Inputdiff --git a/web/src/lib/actions/reports.ts b/web/src/lib/actions/reports.tsindex 2773958a8..1328e21eb 100644--- a/web/src/lib/actions/reports.ts+++ b/web/src/lib/actions/reports.ts@@ -15,7 +15,14 @@ import {type VisibilityTrendPoint,} from '@/lib/actions/tracking';import { getCitationsOverview, type CitationsSourceBreakdown } from '@/lib/actions/citations';+import { getShoppingKpis } from '@/lib/actions/shopping';import type { SourceCategory } from '@/lib/citations/classify';+import {+ getReportTemplate,+ ALL_REPORT_SECTIONS,+ type ReportSection,+ type ReportTemplateId,+} from '@/lib/reports/templates';/*** Simple Reports MVP — generate, list and delete immutable report snapshots.@@ -50,32 +57,77 @@ export interface ReportFanoutQuery {timesSearched: number;}+export interface ReportTopicPerf {+ name: string;+ avgVisibility: number;+ /** Points change vs the previous window of equal length; null when no prior data. */+ change: number | null;+ results: number;+}++export interface ReportAiTraffic {+ totalVisits: number;+ /** Percent change vs the previous window; null when the previous window had no visits. */+ change: number | null;+ platformBreakdown: { platform: string; visits: number }[];+ topPages: { url: string; visits: number }[];+}++export interface ReportShoppingVisibility {+ /** Own share of all shopping cards in the window, as a percentage. */+ shoppingSovPct: number;+ /** Points change vs the previous window; null when no prior shopping data. */+ sovChange: number | null;+ productsSurfaced: number;+ /** Share of tracked answers that produced shopping cards, as a percentage. */+ cardRatePct: number;+ topMerchant: string | null;+}++export interface ReportAuditScore {+ url: string;+ totalScore: number | null;+ /** The prior completed audit's score, for the delta; null when first audit. */+ previousScore: number | null;+ auditedAt: string;+}++/**+ * All metric fields are optional: a template only gathers its own sections+ * (see lib/reports/templates.ts), and the detail page + PDF render purely by+ * field presence. Reports generated before a field shipped simply don't have+ * it — the payload is immutable.+ */export interface ReportPayload {brandName: string;/** AI-generated executive summary (plain prose). */summaryText: string;- insights: InsightsSummary;- /**- * Daily visibility trend over the report period. Optional: reports- * generated before this field shipped simply don't have it (the payload is- * immutable), and the detail page hides the section.- */+ insights?: InsightsSummary;+ /** Daily visibility trend over the report period. */visibilityTrend?: VisibilityTrendPoint[];- /** Best/worst performing prompts in the period (also optional, see above). */+ /** Best/worst performing prompts in the period. */promptPerformance?: {best: ReportPromptPerf[];worst: ReportPromptPerf[];};- /** Most-run observed fan-out sub-queries in the period (optional, see above). */+ /** Most-run observed fan-out sub-queries in the period. */queryFanout?: ReportFanoutQuery[];- shareOfVoice: {+ /** Per-topic visibility with deltas vs the previous window. */+ topicPerformance?: ReportTopicPerf[];+ /** Real AI-referred visits in the period. */+ aiTraffic?: ReportAiTraffic;+ /** Shopping card presence (only gathered when the brand's shopping mode is on). */+ shoppingVisibility?: ReportShoppingVisibility;+ /** Latest completed Site Audit as of the period end. */+ auditScore?: ReportAuditScore;+ shareOfVoice?: {overallSov: number;overallSovChange: number | null;byPlatform: SoVByPlatform[];};/** Own brand + competitors, as returned by getCompetitorComparison. */- competitors: CompetitorComparisonEntry[];- citations: {+ competitors?: CompetitorComparisonEntry[];+ citations?: {totals: {domains: number;urls: number;@@ -222,11 +274,223 @@ async function getFanoutSnapshot(.map((a) => ({ query: a.display, engines: [...a.engines].sort(), timesSearched: a.count }));}+const round1 = (n: number) => Math.round(n * 10) / 10;++/** The window of equal length immediately before [dateFrom, dateTo] — every+ * report delta (US-1.4) compares against this. */+function previousWindow(dateFrom: string, dateTo: string): { from: string; to: string } {+ const from = new Date(dateFrom).getTime();+ const to = new Date(dateTo).getTime();+ return { from: new Date(from - (to - from)).toISOString(), to: dateFrom };+}++/** How many topics a report keeps. */+const REPORT_TOPIC_COUNT = 8;++/**+ * Per-topic average visibility WITHIN the report period, with a points delta+ * vs the previous window. Same two-step pattern as getPromptPerformance:+ * one prompt_results scan spanning both windows, then resolve topic names.+ */+async function getTopicPerformance(+ brandId: string,+ dateFrom: string,+ dateTo: string,+): Promise<ReportTopicPerf[]> {+ const supabase = await createClient();+ const prev = previousWindow(dateFrom, dateTo);++ const { data, error } = await supabase+ .from('prompt_results')+ .select('prompt_id, visibility_score, created_at')+ .eq('brand_id', brandId)+ .neq('platform', 'chatgpt-shopping')+ .gte('created_at', prev.from)+ .lte('created_at', dateTo);+ if (error) throw new Error(error.message);+ if (!data || data.length === 0) return [];++ const promptIds = [...new Set(data.map((r) => r.prompt_id as string).filter(Boolean))];+ const { data: promptRows } = await supabase+ .from('prompts')+ .select('id, topic_id')+ .in('id', promptIds);+ const topicByPrompt = new Map(+ (promptRows ?? []).filter((p) => p.topic_id).map((p) => [p.id as string, p.topic_id as string]),+ );+ if (topicByPrompt.size === 0) return [];++ interface Acc {+ sumVis: number;+ n: number;+ prevSumVis: number;+ prevN: number;+ }+ const byTopic = new Map<string, Acc>();+ for (const r of data) {+ const topicId = topicByPrompt.get(r.prompt_id as string);+ if (!topicId) continue;+ const acc = byTopic.get(topicId) ?? { sumVis: 0, n: 0, prevSumVis: 0, prevN: 0 };+ const vis = (r.visibility_score as number) ?? 0;+ if ((r.created_at as string) >= dateFrom) {+ acc.sumVis += vis;+ acc.n += 1;+ } else {+ acc.prevSumVis += vis;+ acc.prevN += 1;+ }+ byTopic.set(topicId, acc);+ }++ const { data: topicRows } = await supabase+ .from('topics')+ .select('id, name')+ .in('id', [...byTopic.keys()]);+ const nameById = new Map((topicRows ?? []).map((t) => [t.id as string, t.name as string]));++ return [...byTopic.entries()]+ .filter(([id, acc]) => acc.n > 0 && nameById.has(id))+ .map(([id, acc]) => {+ const avg = round1(acc.sumVis / acc.n);+ const prevAvg = acc.prevN > 0 ? acc.prevSumVis / acc.prevN : null;+ return {+ name: nameById.get(id)!,+ avgVisibility: avg,+ change: prevAvg === null ? null : round1(avg - prevAvg),+ results: acc.n,+ };+ })+ .sort((a, b) => b.results - a.results || b.avgVisibility - a.avgVisibility)+ .slice(0, REPORT_TOPIC_COUNT);+}++/**+ * Real AI-referred visits WITHIN the report period, with a percent delta vs+ * the previous window. Windowed here (getTrafficSummary anchors to "now").+ */+async function getTrafficSnapshot(+ brandId: string,+ dateFrom: string,+ dateTo: string,+): Promise<ReportAiTraffic> {+ const supabase = await createClient();+ const prev = previousWindow(dateFrom, dateTo);++ const [{ data: cur, error }, { data: prevRows }] = await Promise.all([+ supabase+ .from('ai_traffic_logs')+ .select('source_platform, url')+ .eq('brand_id', brandId)+ .gte('created_at', dateFrom)+ .lte('created_at', dateTo),+ supabase+ .from('ai_traffic_logs')+ .select('id')+ .eq('brand_id', brandId)+ .gte('created_at', prev.from)+ .lt('created_at', prev.to),+ ]);+ if (error) throw new Error(error.message);++ const byPlatform = new Map<string, number>();+ const byPage = new Map<string, number>();+ for (const r of cur ?? []) {+ const p = (r.source_platform as string) || 'unknown';+ byPlatform.set(p, (byPlatform.get(p) ?? 0) + 1);+ const u = (r.url as string) || '';+ if (u) byPage.set(u, (byPage.get(u) ?? 0) + 1);+ }++ const totalVisits = cur?.length ?? 0;+ const prevVisits = prevRows?.length ?? 0;+ return {+ totalVisits,+ change: prevVisits > 0 ? round1(((totalVisits - prevVisits) / prevVisits) * 100) : null,+ platformBreakdown: [...byPlatform.entries()]+ .map(([platform, visits]) => ({ platform, visits }))+ .sort((a, b) => b.visits - a.visits)+ .slice(0, 5),+ topPages: [...byPage.entries()]+ .map(([url, visits]) => ({ url, visits }))+ .sort((a, b) => b.visits - a.visits)+ .slice(0, 5),+ };+}++/**+ * Shopping card presence WITHIN the report period (reuses getShoppingKpis+ * with an explicit window), plus a points delta on shopping SoV vs the+ * previous window. Callers gate on the brand's shopping mode.+ */+async function getShoppingSnapshot(+ brandId: string,+ dateFrom: string,+ dateTo: string,+): Promise<ReportShoppingVisibility> {+ const prev = previousWindow(dateFrom, dateTo);+ const [cur, prior] = await Promise.all([+ getShoppingKpis(brandId, { datePreset: 'all', dateFrom, dateTo }),+ getShoppingKpis(brandId, { datePreset: 'all', dateFrom: prev.from, dateTo: prev.to }),+ ]);++ const sovPct = round1(cur.shoppingSov * 100);+ const priorHasData = prior.shoppingCardRateSampleSize > 0;+ return {+ shoppingSovPct: sovPct,+ sovChange: priorHasData ? round1(sovPct - prior.shoppingSov * 100) : null,+ productsSurfaced: cur.productsSurfaced,+ cardRatePct: round1(cur.shoppingCardRate * 100),+ topMerchant: cur.topMerchant?.domain ?? null,+ };+}++/**+ * Latest completed Site Audit as of the period end, with the prior audit's+ * score for the delta. Audits aren't period-bound like the other metrics, so+ * "as of dateTo" keeps historical reports honest.+ */+async function getAuditSnapshot(brandId: string, dateTo: string): Promise<ReportAuditScore | null> {+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('site_audits')+ .select('url, total_score, created_at')+ .eq('brand_id', brandId)+ .eq('status', 'completed')+ .lte('created_at', dateTo)+ .order('created_at', { ascending: false })+ .limit(2);+ if (error) throw new Error(error.message);+ if (!data || data.length === 0) return null;++ const [latest, prior] = data;+ return {+ url: latest.url as string,+ totalScore: latest.total_score === null ? null : round1(Number(latest.total_score)),+ previousScore: prior && prior.total_score !== null ? round1(Number(prior.total_score)) : null,+ auditedAt: latest.created_at as string,+ };+}+// ─── Actions ─────────────────────────────────────────────────────────────────+/** English display names used in stored (immutable) report titles. */+const TEMPLATE_TITLES: Record<ReportTemplateId, string> = {+ weekly_visibility: 'Weekly Visibility Summary',+ executive_summary: 'Executive Summary',+ competitor_benchmark: 'Competitor Benchmark',+ citation_sources: 'Citation & Sources Report',+};+export async function createReport(brandId: string,- opts: { dateFrom: string; dateTo: string; title?: string },+ opts: {+ dateFrom: string;+ dateTo: string;+ title?: string;+ template?: ReportTemplateId;+ /** Explicit section picks (US-1.3); falls back to the template's defaults. */+ sections?: ReportSection[];+ },): Promise<{ id: string }> {const supabase = await createClient();const {@@ -236,54 +500,101 @@ export async function createReport(const { dateFrom, dateTo } = opts;const range = { dateFrom, dateTo };-- // 1. Gather the metric snapshot through the existing analytics actions.- const [brandRow, insights, sov, comparison, citations, trend, promptPerformance, queryFanout] =- await Promise.all([- supabase.from('brands').select('name').eq('id', brandId).single(),- getInsightsSummary(brandId, range),- getShareOfVoiceData(brandId, range),- getCompetitorComparison(brandId, range),- getCitationsOverview(brandId, { datePreset: 'custom', dateFrom, dateTo }),- getVisibilityTrend(brandId, range),- getPromptPerformance(brandId, dateFrom, dateTo),- getFanoutSnapshot(brandId, dateFrom, dateTo),- ]);- const brandName = (brandRow.data?.name as string) ?? 'Brand';-- const snapshot: Omit<ReportPayload, 'summaryText'> = {- brandName,+ const template = getReportTemplate(opts.template);++ // The brand row gates the shopping section server-side: even if a caller+ // sends `shoppingVisibility`, a brand with shopping mode off never gathers+ // it (mirrors the sidebar's requiresBrandPref rule).+ const { data: brand } = await supabase+ .from('brands')+ .select('name, shopping_mode_enabled')+ .eq('id', brandId)+ .single();+ const brandName = (brand?.name as string) ?? 'Brand';++ const picked = (opts.sections ?? template.sections).filter((s) =>+ ALL_REPORT_SECTIONS.includes(s),+ );+ const sectionSet = new Set<ReportSection>(picked);+ if (!brand?.shopping_mode_enabled) sectionSet.delete('shoppingVisibility');+ const has = (s: ReportSection) => sectionSet.has(s);++ // 1. Gather the metric snapshot through the existing analytics actions —+ // only the picked sections (null = section not gathered).+ const [insights,- visibilityTrend: trend,+ sov,+ comparison,+ citations,+ trend,promptPerformance,queryFanout,- shareOfVoice: {- overallSov: sov.overallSov,- overallSovChange: sov.overallSovChange,- byPlatform: sov.byPlatform,- },- competitors: comparison.brands,- citations: {- totals: citations.totals,- sourceTypeBreakdown: citations.sourceTypeBreakdown,- topDomains: citations.rows.slice(0, REPORT_TOP_DOMAINS).map((r) => ({- domain: r.domain,- category: r.category,- totalCitations: r.totalCitations,- resultsCiting: r.resultsCiting,- usagePct: r.usagePct,- })),- },+ topicPerformance,+ aiTraffic,+ shoppingVisibility,+ auditScore,+ ] = await Promise.all([+ has('kpis') ? getInsightsSummary(brandId, range) : null,+ has('shareOfVoice') ? getShareOfVoiceData(brandId, range) : null,+ has('competitors') ? getCompetitorComparison(brandId, range) : null,+ has('citations')+ ? getCitationsOverview(brandId, { datePreset: 'custom', dateFrom, dateTo })+ : null,+ has('trend') ? getVisibilityTrend(brandId, range) : null,+ has('promptPerformance') ? getPromptPerformance(brandId, dateFrom, dateTo) : null,+ has('queryFanout') ? getFanoutSnapshot(brandId, dateFrom, dateTo) : null,+ has('topicPerformance') ? getTopicPerformance(brandId, dateFrom, dateTo) : null,+ has('aiTraffic') ? getTrafficSnapshot(brandId, dateFrom, dateTo) : null,+ has('shoppingVisibility') ? getShoppingSnapshot(brandId, dateFrom, dateTo) : null,+ has('auditScore') ? getAuditSnapshot(brandId, dateTo) : null,+ ]);++ const snapshot: Omit<ReportPayload, 'summaryText'> = {+ brandName,+ ...(insights ? { insights } : {}),+ ...(trend ? { visibilityTrend: trend } : {}),+ ...(promptPerformance ? { promptPerformance } : {}),+ ...(queryFanout ? { queryFanout } : {}),+ ...(topicPerformance && topicPerformance.length > 0 ? { topicPerformance } : {}),+ ...(aiTraffic ? { aiTraffic } : {}),+ ...(shoppingVisibility ? { shoppingVisibility } : {}),+ ...(auditScore ? { auditScore } : {}),+ ...(sov+ ? {+ shareOfVoice: {+ overallSov: sov.overallSov,+ overallSovChange: sov.overallSovChange,+ byPlatform: sov.byPlatform,+ },+ }+ : {}),+ ...(comparison ? { competitors: comparison.brands } : {}),+ ...(citations+ ? {+ citations: {+ totals: citations.totals,+ sourceTypeBreakdown: citations.sourceTypeBreakdown,+ topDomains: citations.rows.slice(0, REPORT_TOP_DOMAINS).map((r) => ({+ domain: r.domain,+ category: r.category,+ totalCitations: r.totalCitations,+ resultsCiting: r.resultsCiting,+ usagePct: r.usagePct,+ })),+ },+ }+ : {}),};// 2. AI executive summary from the server (content.js-style single call).+ // The template id lets the server flavor the prose for the report type.const res = await fetch(`${API_BASE_URL}/api/reports/summary`, {method: 'POST',headers: {'Content-Type': 'application/json',Authorization: `Bearer ${session.access_token}`,},- body: JSON.stringify({ brandId, snapshot, dateFrom, dateTo }),+ body: JSON.stringify({ brandId, snapshot, dateFrom, dateTo, template: template.id }),});if (!res.ok) {const body = await res.json().catch(() => ({}));@@ -296,14 +607,14 @@ export async function createReport(// 3. Persist the immutable snapshot (RLS scopes the insert to org members).const title =opts.title?.trim() ||- `${brandName} — Executive Summary (${dateFrom.slice(0, 10)} → ${dateTo.slice(0, 10)})`;+ `${brandName} — ${TEMPLATE_TITLES[template.id]} (${dateFrom.slice(0, 10)} → ${dateTo.slice(0, 10)})`;const { data: created, error } = await supabase.from('reports').insert({brand_id: brandId,title,- template: 'executive_summary',+ template: template.id,date_from: dateFrom,date_to: dateTo,payload: payload as unknown as Json,diff --git a/web/src/lib/reports/templates.ts b/web/src/lib/reports/templates.tsnew file mode 100644index 000000000..222154b4f--- /dev/null+++ b/web/src/lib/reports/templates.ts@@ -0,0 +1,103 @@+/**+ * Report template registry (US-1.1/1.3) — ready-made report shapes a user+ * can generate without building anything from scratch. A template is a+ * DEFAULT section set: the generate dialog pre-selects its sections and the+ * user can toggle any module on/off before generating (US-1.3). Since the+ * detail page and the PDF both render by payload-field presence, the chosen+ * sections are exactly what shows up in the output. Names/descriptions live+ * in the `reports` i18n namespace under `templates.<id>.*` / `sections.*`.+ *+ * Template ids are persisted in `reports.template`, so they are part of the+ * data contract: never rename an id, only add new ones. `executive_summary`+ * predates this registry (Simple Reports MVP) and stays the full report.+ */++export type ReportTemplateId =+ | 'weekly_visibility'+ | 'executive_summary'+ | 'competitor_benchmark'+ | 'citation_sources';++export type ReportSection =+ | 'kpis'+ | 'trend'+ | 'shareOfVoice'+ | 'competitors'+ | 'topicPerformance'+ | 'promptPerformance'+ | 'queryFanout'+ | 'aiTraffic'+ | 'shoppingVisibility'+ | 'auditScore'+ | 'citations';++/**+ * Every pickable section, in report render order — drives the section+ * checkboxes in the generate dialog. `shoppingVisibility` is additionally+ * gated on the brand's shopping mode (hidden entirely when off, mirroring+ * the sidebar's `requiresBrandPref` rule).+ */+export const ALL_REPORT_SECTIONS: ReportSection[] = [+ 'kpis',+ 'trend',+ 'shareOfVoice',+ 'competitors',+ 'topicPerformance',+ 'promptPerformance',+ 'queryFanout',+ 'aiTraffic',+ 'shoppingVisibility',+ 'auditScore',+ 'citations',+];++export interface ReportTemplateDef {+ id: ReportTemplateId;+ /** Default payload sections (AI summary is always included); user-adjustable in the dialog. */+ sections: ReportSection[];+ /** Date-range preset the generate dialog starts on (user can still override). */+ defaultPreset: '7d' | '30d' | '90d';+}++export const REPORT_TEMPLATES: ReportTemplateDef[] = [+ {+ id: 'weekly_visibility',+ sections: ['kpis', 'trend', 'shareOfVoice'],+ defaultPreset: '7d',+ },+ {+ id: 'executive_summary',+ sections: [+ 'kpis',+ 'trend',+ 'shareOfVoice',+ 'competitors',+ 'topicPerformance',+ 'promptPerformance',+ 'queryFanout',+ 'aiTraffic',+ 'shoppingVisibility',+ 'auditScore',+ 'citations',+ ],+ defaultPreset: '30d',+ },+ {+ id: 'competitor_benchmark',+ sections: ['kpis', 'shareOfVoice', 'competitors', 'topicPerformance'],+ defaultPreset: '30d',+ },+ {+ id: 'citation_sources',+ sections: ['citations'],+ defaultPreset: '30d',+ },+];++/** Falls back to the full executive summary for unknown/legacy ids. */+export function getReportTemplate(id: string | null | undefined): ReportTemplateDef {+ return (+ REPORT_TEMPLATES.find((t) => t.id === id) ??+ REPORT_TEMPLATES.find((t) => t.id === 'executive_summary')!+ );+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex a855892a8..eb80d98cf 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -899,6 +899,7 @@ export type Database = {prompt_set_id: string;regions: string[];text: string;+ topic_id: string | null;};Insert: {category?: string | null;@@ -983,6 +984,62 @@ export type Database = {},];};+ site_audits: {+ Row: {+ brand_id: string;+ category_scores: Json;+ completed_at: string | null;+ created_at: string;+ error: string | null;+ final_url: string | null;+ id: string;+ rubric_version: string | null;+ signals_evaluated: number | null;+ signals_total: number | null;+ status: string;+ total_score: number | null;+ url: string;+ };+ Insert: {+ brand_id: string;+ category_scores?: Json;+ completed_at?: string | null;+ created_at?: string;+ error?: string | null;+ final_url?: string | null;+ id?: string;+ rubric_version?: string | null;+ signals_evaluated?: number | null;+ signals_total?: number | null;+ status?: string;+ total_score?: number | null;+ url: string;+ };+ Update: {+ brand_id?: string;+ category_scores?: Json;+ completed_at?: string | null;+ created_at?: string;+ error?: string | null;+ final_url?: string | null;+ id?: string;+ rubric_version?: string | null;+ signals_evaluated?: number | null;+ signals_total?: number | null;+ status?: string;+ total_score?: number | null;+ url?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'site_audits_brand_id_fkey';+ columns: ['brand_id'];+ isOneToOne: false;+ referencedRelation: 'brands';+ referencedColumns: ['id'];+ },+ ];+ };topics: {Row: {brand_id: string;