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(content): export an opportunity as CSV, Excel or Word (#1337)
Cihan6aed20178f92
diff --git a/web/messages/en.json b/web/messages/en.jsonindex cc38fcb45..8f48ca4ee 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4047,6 +4047,13 @@"openPlan": "Open Plan","moreActions": "More actions","rowActions": "Actions for {title}",+ "exportOne": {+ "button": "Export",+ "csv": "Export CSV",+ "excel": "Export Excel",+ "word": "Export Word",+ "failed": "Couldn't export this opportunity. Please try again."+ },"openInActions": "Open in Actions","sendAgain": "Send Again","copyAllData": "Copy All Data",diff --git a/web/package.json b/web/package.jsonindex 84ceb2e62..885fcb2b3 100644--- a/web/package.json+++ b/web/package.json@@ -44,6 +44,7 @@"ai": "^6.0.116","class-variance-authority": "^0.7.1","clsx": "^2.1.1",+ "docx": "9.7.0","dompurify": "3.4.16","fflate": "^0.8.3","lucide-react": "^0.577.0",diff --git a/web/src/components/content/opportunity-actions.test.tsx b/web/src/components/content/opportunity-actions.test.tsxindex c4e108ea5..e8de7e7a0 100644--- a/web/src/components/content/opportunity-actions.test.tsx+++ b/web/src/components/content/opportunity-actions.test.tsx@@ -27,6 +27,7 @@ const handlers = {alternative: vi.fn(),workflow: vi.fn(),copy: vi.fn(),+ export: vi.fn(),reviewed: vi.fn(),dismiss: vi.fn(),};@@ -46,6 +47,7 @@ const props = (over: Partial<Props> = {}): Props => ({alternative: { running: false, onOpen: handlers.alternative },workflow: { sending: false, sentBefore: false, onSend: handlers.workflow },onCopy: handlers.copy,+ onExport: handlers.export,onReviewed: handlers.reviewed,onDismiss: handlers.dismiss,...over,@@ -90,7 +92,7 @@ afterEach(() => {describe('OpportunityActions', () => {it('puts Send to Actions, Generate Brief and Send to Editor in front, in that order', async () => {await render(props());- expect(front()).toEqual(['Send to Actions', 'Generate Brief', 'Send to Editor']);+ expect(front()).toEqual(['Send to Actions', 'Generate Brief', 'Send to Editor', 'Export']);await act(async () => button('Send to Editor').click());expect(handlers.start).toHaveBeenCalled();});@@ -103,7 +105,7 @@ describe('OpportunityActions', () => {content: { ...props().content, draftId: 'd7' },}),);- expect(front()).toEqual(['Open in Actions', 'Brief Generated', 'Open draft']);+ expect(front()).toEqual(['Open in Actions', 'Brief Generated', 'Open draft', 'Export']);expect(container.querySelector('a')!.getAttribute('href')).toBe('/dashboard/action-center/actions?action=a7',);@@ -115,7 +117,24 @@ describe('OpportunityActions', () => {await render(props({ content: { ...props().content, draftId: undefined } }));expect(button('Send to Editor').disabled).toBe(true);await render(props({ content: { ...props().content, canStart: false } }));- expect(front()).toEqual(['Send to Actions', 'Generate Brief']);+ expect(front()).toEqual(['Send to Actions', 'Generate Brief', 'Export']);+ });++ it('offers Export CSV, Excel and Word, one under the other', async () => {+ await render(props());+ const trigger = button('Export');+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ const items = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+ expect(items.map((i) => i.textContent?.trim())).toEqual([+ 'Export CSV',+ 'Export Excel',+ 'Export Word',+ ]);+ await act(async () => items[2].click());+ expect(handlers.export).toHaveBeenCalledWith('docx');});it('offers to check again when the draft lookup failed, never Start', async () => {@@ -126,6 +145,7 @@ describe('OpportunityActions', () => {'Send to Actions','Generate Brief',"Couldn't check for a draft · Retry",+ 'Export',]);await act(async () => button("Couldn't check for a draft · Retry").click());expect(handlers.retry).toHaveBeenCalled();diff --git a/web/src/components/content/opportunity-actions.tsx b/web/src/components/content/opportunity-actions.tsxindex 6d94e5832..725167f50 100644--- a/web/src/components/content/opportunity-actions.tsx+++ b/web/src/components/content/opportunity-actions.tsx@@ -4,6 +4,11 @@ import { useTranslations } from 'next-intl';import {Check,CheckCheck,+ ChevronDown,+ Download,+ FileDown,+ FileSpreadsheet,+ FileType,Copy,ExternalLink,FilePen,@@ -21,6 +26,7 @@ import {} from 'lucide-react';import { Link } from '@/i18n/navigation';import { Button } from '@/components/ui/button';+import type { OpportunityExportFormat } from '@/lib/content/opportunity-export';import {DropdownMenu,DropdownMenuContent,@@ -44,6 +50,7 @@ export function OpportunityActions({alternative,workflow,onCopy,+ onExport,onReviewed,onRestore,onDismiss,@@ -81,6 +88,8 @@ export function OpportunityActions({/** The CMS webhook; null when it isn't offered. */workflow: { sending: boolean; sentBefore: boolean; onSend: () => void } | null;onCopy: () => void;+ /** Export (the user's spec): the write-up as CSV, Excel or Word. */+ onExport: (format: OpportunityExportFormat) => void;onReviewed?: () => void;onRestore?: () => void;onDismiss?: () => void;@@ -167,7 +176,30 @@ export function OpportunityActions({<DropdownMenu><DropdownMenuTrigger- className="ml-auto inline-flex h-8 w-8 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"+ render={<Button variant="outline" size="sm" className="ml-auto gap-2" />}+ >+ <Download className="h-4 w-4" />+ {t('exportOne.button')}+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-44">+ <DropdownMenuItem className="gap-2" onClick={() => onExport('csv')}>+ <FileDown className="h-3.5 w-3.5" />+ {t('exportOne.csv')}+ </DropdownMenuItem>+ <DropdownMenuItem className="gap-2" onClick={() => onExport('xlsx')}>+ <FileSpreadsheet className="h-3.5 w-3.5" />+ {t('exportOne.excel')}+ </DropdownMenuItem>+ <DropdownMenuItem className="gap-2" onClick={() => onExport('docx')}>+ <FileType className="h-3.5 w-3.5" />+ {t('exportOne.word')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <DropdownMenu>+ <DropdownMenuTrigger+ className="inline-flex h-8 w-8 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"aria-label={t('moreActions')}><MoreHorizontal className="h-4 w-4" />diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex 00cf4be00..ca31d9728 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -48,7 +48,16 @@ import {ScoreBreakdown,TargetPagesCard,} from '@/components/content/opportunity-basket';-import { opportunityToMarkdown } from '@/lib/content/opportunity-markdown';+import { opportunityDocument, opportunityToMarkdown } from '@/lib/content/opportunity-markdown';+import {+ opportunityCsv,+ opportunityDocx,+ opportunityExportFileName,+ opportunityWorkbook,+ type OpportunityExportFormat,+} from '@/lib/content/opportunity-export';+import { BYTE_ORDER_MARK } from '@/lib/action-center/export';+import { saveBlob } from '@/lib/download';import { canWriteOpportunity, opportunityStart } from '@/lib/content/opportunity-start';import { contentEditorPath } from '@/lib/content/drafts';import { siteTypeOf } from '@/lib/content/page-types';@@ -421,6 +430,28 @@ export function OpportunityDetail({const actionId = sd.actions?.all ?? Object.values(sd.actions ?? {})[0];const canSendToWorkflow = !['dismissed', 'archived'].includes(opportunity.status);+ // Export (the user's spec): what Copy All Data copies, as a file.+ const handleExport = async (format: OpportunityExportFormat) => {+ const doc = opportunityDocument(opportunity, brief, fanoutQueries, assetTypeLabel);+ const fileName = opportunityExportFileName(doc, format);+ try {+ if (format === 'csv') {+ saveBlob(+ new Blob([BYTE_ORDER_MARK, opportunityCsv(doc)], { type: 'text/csv;charset=utf-8;' }),+ fileName,+ );+ } else if (format === 'xlsx') {+ const { default: writeXlsxFile } = await import('write-excel-file/browser');+ await writeXlsxFile(opportunityWorkbook(doc)).toFile(fileName);+ } else {+ saveBlob(await opportunityDocx(doc), fileName);+ }+ } catch (err) {+ console.error('Export failed:', err);+ toast.error(t('exportOne.failed'));+ }+ };+const handleCopy = async () => {try {await navigator.clipboard.writeText(@@ -554,6 +585,7 @@ export function OpportunityDetail({: null}onCopy={() => void handleCopy()}+ onExport={(format) => void handleExport(format)}onReviewed={opportunity.status === 'new' ? () => void handleReviewed() : undefined}onRestore={opportunity.status === 'archived' ? () => void handleRestore() : undefined}onDismiss={opportunity.status === 'new' ? () => setDismissOpen(true) : undefined}diff --git a/web/src/lib/content/opportunity-export.test.ts b/web/src/lib/content/opportunity-export.test.tsnew file mode 100644index 000000000..b2165c84b--- /dev/null+++ b/web/src/lib/content/opportunity-export.test.ts@@ -0,0 +1,114 @@+import { strFromU8, unzipSync } from 'fflate';+import { describe, expect, it } from 'vitest';+import {+ opportunityCsv,+ opportunityDocx,+ opportunityExportFileName,+ opportunityRows,+ opportunityWorkbook,+} from './opportunity-export';+import type { OpportunityDocument } from './opportunity-markdown';++const doc: OpportunityDocument = {+ title: 'Office coffee subscriptions for teams',+ description: 'Rivals rank first for "office coffee".',+ sections: [+ {+ title: null,+ lines: [+ { kind: 'field', label: 'Type', value: 'Owned' },+ { kind: 'field', label: 'Score', value: '75' },+ ],+ },+ { title: 'Target pages', lines: [{ kind: 'item', text: 'Pricing: https://acme.example/p' }] },+ {+ title: 'Brief outline',+ lines: [{ kind: 'step', n: 1, text: 'Why teams switch', points: ['Cost', 'Choice'] }],+ },+ {+ title: 'Competitor insights',+ lines: [{ kind: 'text', text: 'Rivals list prices, we don’t.' }],+ },+ ],+};++describe('opportunityRows', () => {+ it('puts every line under its section, the opening facts under Overview', () => {+ expect(opportunityRows(doc)).toEqual([+ { section: 'Overview', field: 'Title', value: 'Office coffee subscriptions for teams' },+ {+ section: 'Overview',+ field: 'Description',+ value: 'Rivals rank first for "office coffee".',+ },+ { section: 'Overview', field: 'Type', value: 'Owned' },+ { section: 'Overview', field: 'Score', value: '75' },+ { section: 'Target pages', field: '', value: 'Pricing: https://acme.example/p' },+ { section: 'Brief outline', field: '1', value: 'Why teams switch\n- Cost\n- Choice' },+ { section: 'Competitor insights', field: '', value: 'Rivals list prices, we don’t.' },+ ]);+ });+});++describe('opportunityCsv', () => {+ it('writes the rows under Section, Field and Value, quoting what needs it', () => {+ const lines = opportunityCsv(doc).split('\n');+ // The sheet's header, in the same case.+ expect(lines[0]).toBe('Section,Field,Value');+ expect(lines[2]).toBe('Overview,Description,"Rivals rank first for ""office coffee""."');+ });+});++describe('opportunityWorkbook', () => {+ it('is one sheet: a bold header, then the rows', () => {+ const [sheet] = opportunityWorkbook(doc);+ expect(sheet.sheet).toBe('Opportunity');+ expect(sheet.data[0]).toEqual([+ { value: 'Section', fontWeight: 'bold' },+ { value: 'Field', fontWeight: 'bold' },+ { value: 'Value', fontWeight: 'bold' },+ ]);+ expect(sheet.data).toHaveLength(8);+ expect(sheet.data[3]).toEqual(['Overview', 'Type', 'Owned']);+ // An outline step and its points wrap, so Excel shows them on their lines.+ expect(sheet.data.find((row) => row[0] === 'Brief outline')![2]).toEqual({+ value: 'Why teams switch\n- Cost\n- Choice',+ wrap: true,+ });+ });+});++describe('opportunityDocx', () => {+ it('writes a Word document with the title, headings, fields and lists', async () => {+ const blob = await opportunityDocx(doc);+ // jsdom's Blob has no arrayBuffer(): read it as a browser's FileReader would.+ const bytes = await new Promise<Uint8Array>((resolve) => {+ const reader = new FileReader();+ reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));+ reader.readAsArrayBuffer(blob);+ });+ const xml = strFromU8(unzipSync(bytes)['word/document.xml']);+ for (const text of [+ 'Office coffee subscriptions for teams',+ 'Target pages',+ 'Type: ',+ 'Owned',+ '1. Why teams switch',+ 'Choice',+ 'Rivals list prices, we don’t.',+ ]) {+ expect(xml).toContain(text);+ }+ });+});++describe('opportunityExportFileName', () => {+ it('names the file after the opportunity', () => {+ expect(opportunityExportFileName(doc, 'docx')).toBe(+ 'ansvisor_opportunity_office-coffee-subscriptions-for-teams.docx',+ );+ expect(opportunityExportFileName({ ...doc, title: '—' }, 'csv')).toBe(+ 'ansvisor_opportunity_export.csv',+ );+ });+});diff --git a/web/src/lib/content/opportunity-export.ts b/web/src/lib/content/opportunity-export.tsnew file mode 100644index 000000000..abba09f11--- /dev/null+++ b/web/src/lib/content/opportunity-export.ts@@ -0,0 +1,140 @@+import type { Sheet } from 'write-excel-file/browser';+import { toCsv } from '@/lib/csv';+import { slugify } from '@/lib/slug';+import type { OpportunityDocument, OpportunityLine } from './opportunity-markdown';++/**+ * An opportunity's Export (the user's spec): the write-up Copy All Data+ * copies (opportunityDocument), as CSV, an Excel sheet or a Word document.+ * CSV and Excel hold one row per line, under its section; Word keeps the+ * headings, fields and lists.+ */++export type OpportunityExportFormat = 'csv' | 'xlsx' | 'docx';++/** The CSV's and the sheet's header, in the same case. */+export const OPPORTUNITY_EXPORT_HEADERS = ['Section', 'Field', 'Value'];++/** The opening facts' section, which the write-up leaves unheaded. */+const OVERVIEW = 'Overview';++export interface OpportunityExportRow {+ section: string;+ field: string;+ value: string;+}++function cells(line: OpportunityLine): { field: string; value: string } {+ switch (line.kind) {+ case 'field':+ return { field: line.label, value: line.value };+ case 'step':+ return {+ field: String(line.n),+ value: [line.text, ...line.points.map((p) => `- ${p}`)].join('\n'),+ };+ default:+ return { field: '', value: line.text };+ }+}++export function opportunityRows(doc: OpportunityDocument): OpportunityExportRow[] {+ return [+ { section: OVERVIEW, field: 'Title', value: doc.title },+ ...(doc.description+ ? [{ section: OVERVIEW, field: 'Description', value: doc.description }]+ : []),+ ...doc.sections.flatMap((s) =>+ s.lines.map((line) => ({ section: s.title ?? OVERVIEW, ...cells(line) })),+ ),+ ];+}++/** Export CSV; the caller adds the byte order mark Excel reads UTF-8 by. */+export function opportunityCsv(doc: OpportunityDocument): string {+ return toCsv(+ opportunityRows(doc).map((row) => ({+ Section: row.section,+ Field: row.field,+ Value: row.value,+ })),+ OPPORTUNITY_EXPORT_HEADERS,+ );+}++const bold = (value: string) => ({ value, fontWeight: 'bold' as const });++/**+ * Export Excel: one sheet, the CSV's rows under a bold header. A value on+ * several lines (an outline step and its points) wraps, so Excel shows them.+ */+export function opportunityWorkbook(doc: OpportunityDocument): Sheet<Blob>[] {+ return [+ {+ sheet: 'Opportunity',+ columns: [{ width: 22 }, { width: 22 }, { width: 100 }],+ data: [+ OPPORTUNITY_EXPORT_HEADERS.map(bold),+ ...opportunityRows(doc).map((row) => [+ row.section,+ row.field,+ row.value.includes('\n') ? { value: row.value, wrap: true } : row.value,+ ]),+ ],+ },+ ];+}++/** Export Word: the title, then each section's heading, fields and lists. */+export async function opportunityDocx(doc: OpportunityDocument): Promise<Blob> {+ // Loaded on the click: the library is only needed to write the file.+ const { Document, HeadingLevel, Packer, Paragraph, TextRun } = await import('docx');+ const paragraphs = (line: OpportunityLine) => {+ switch (line.kind) {+ case 'field':+ return [+ new Paragraph({+ bullet: { level: 0 },+ children: [+ new TextRun({ text: `${line.label}: `, bold: true }),+ new TextRun(line.value),+ ],+ }),+ ];+ case 'item':+ return [new Paragraph({ text: line.text, bullet: { level: 0 } })];+ case 'step':+ return [+ new Paragraph({ text: `${line.n}. ${line.text}` }),+ ...line.points.map((p) => new Paragraph({ text: p, bullet: { level: 1 } })),+ ];+ case 'text':+ return [new Paragraph({ text: line.text })];+ }+ };+ const document = new Document({+ title: doc.title,+ sections: [+ {+ children: [+ new Paragraph({ text: doc.title, heading: HeadingLevel.TITLE }),+ ...(doc.description ? [new Paragraph({ text: doc.description })] : []),+ ...doc.sections.flatMap((s) => [+ ...(s.title ? [new Paragraph({ text: s.title, heading: HeadingLevel.HEADING_2 })] : []),+ ...s.lines.flatMap(paragraphs),+ ]),+ ],+ },+ ],+ });+ return Packer.toBlob(document);+}++/** "ansvisor_opportunity_office-coffee-subscriptions.xlsx". */+export function opportunityExportFileName(+ doc: OpportunityDocument,+ extension: OpportunityExportFormat,+): string {+ const slug = slugify(doc.title).slice(0, 60).replace(/-+$/, '') || 'export';+ return `ansvisor_opportunity_${slug}.${extension}`;+}diff --git a/web/src/lib/content/opportunity-markdown.ts b/web/src/lib/content/opportunity-markdown.tsindex 4012ee15e..e14240456 100644--- a/web/src/lib/content/opportunity-markdown.ts+++ b/web/src/lib/content/opportunity-markdown.ts@@ -6,138 +6,197 @@ function humanize(slug: string): string {return words.charAt(0).toUpperCase() + words.slice(1);}-function section(title: string, lines: (string | null | undefined | false)[]): string | null {- const body = lines.filter((l): l is string => typeof l === 'string' && l.length > 0);- return body.length ? `## ${title}\n\n${body.join('\n')}` : null;-}-const fmt = (n: number) => Math.round(n).toLocaleString('en-US');+/** One line of an opportunity's write-up. */+export type OpportunityLine =+ | { kind: 'field'; label: string; value: string }+ | { kind: 'item'; text: string }+ | { kind: 'step'; n: number; text: string; points: string[] }+ | { kind: 'text'; text: string };++/** A part of the write-up; the opening facts have no heading. */+export interface OpportunitySection {+ title: string | null;+ lines: OpportunityLine[];+}+/**- * Everything the opportunity detail shows, as Markdown in page order, for the- * Copy All Data button. Empty sections are left out.+ * Everything the opportunity detail shows, in page order: what Copy All Data+ * writes as Markdown and Export writes as CSV, Excel or Word. Empty sections+ * are left out.*/-export function opportunityToMarkdown(+export interface OpportunityDocument {+ title: string;+ description: string | null;+ sections: OpportunitySection[];+}++type Maybe<T> = T | null | undefined | false | '' | 0;++const field = (label: string, value: Maybe<string | number>): OpportunityLine | null =>+ value || value === 0 ? { kind: 'field', label, value: String(value) } : null;+const item = (text: string): OpportunityLine => ({ kind: 'item', text });++function section(title: string | null, lines: Maybe<OpportunityLine>[]): OpportunitySection {+ return { title, lines: lines.filter((l): l is OpportunityLine => !!l) };+}++export function opportunityDocument(opportunity: ContentOpportunity,brief: ContentBrief | null,fanoutQueries: { query: string }[] = [],/** An asset's type as the page names it (useAssetTypeLabel); else its key, humanized. */assetTypeLabel: (type: string) => string | null = () => null,-): string {+): OpportunityDocument {const sd = opportunity.sourceData;- const parts: (string | null)[] = [];-- parts.push([`# ${opportunity.title}`, opportunity.description].filter(Boolean).join('\n\n'));-- parts.push(- [- `- Type: ${humanize(opportunity.type)}`,- `- Impact: ${humanize(opportunity.impact)}`,- `- Status: ${humanize(opportunity.status)}`,- `- Score: ${Math.round(opportunity.opportunityScore)}`,- `- Created: ${opportunity.createdAt.slice(0, 10)}`,- opportunity.decision && `- Decision: ${humanize(opportunity.decision)}`,- ]- .filter(Boolean)- .join('\n'),+ const sections: OpportunitySection[] = [];++ sections.push(+ section(null, [+ field('Type', humanize(opportunity.type)),+ field('Impact', humanize(opportunity.impact)),+ field('Status', humanize(opportunity.status)),+ field('Score', String(Math.round(opportunity.opportunityScore))),+ field('Created', opportunity.createdAt.slice(0, 10)),+ opportunity.decision && field('Decision', humanize(opportunity.decision)),+ ]),);// Sent from an Action Center task (AC-004): what the task says to do.const task = sd.fromAction?.task;- parts.push(+ sections.push(section(sd.fromAction?.actionNo != null? `From a task in AC-${sd.fromAction.actionNo}`: 'From an Action Center task',[- task?.where && `- Where: ${task.where}`,- task?.why && `- Why: ${task.why}`,- ...(task?.how ?? []).map((step, i) => `${i + 1}. ${step}`),- task?.doneWhen && `- Done when: ${task.doneWhen}`,+ task?.where && field('Where', task.where),+ task?.why && field('Why', task.why),+ ...(task?.how ?? []).map(+ (step, i): OpportunityLine => ({ kind: 'step', n: i + 1, text: step, points: [] }),+ ),+ task?.doneWhen && field('Done when', task.doneWhen),(task?.effort || task?.role) &&- `- Effort: ${[task?.effort, task?.role].filter(Boolean).join(' · ')}`,+ field('Effort', [task?.effort, task?.role].filter(Boolean).join(' · ')),],),);- parts.push(+ sections.push(section('Target pages',- (sd.targetPages ?? []).map((p) => `- ${p.title ? `${p.title}: ` : ''}${p.url}`),+ (sd.targetPages ?? []).map((p) => item(`${p.title ? `${p.title}: ` : ''}${p.url}`)),),);- parts.push(+ sections.push(section('Recommended assets',- (sd.assets ?? []).map(- (a) =>- `- ${a.title} (${assetTypeLabel(a.type) ?? humanize(a.type)}, ${humanize(a.channel)}, ${humanize(a.decision)})`,+ (sd.assets ?? []).map((a) =>+ item(+ `${a.title} (${assetTypeLabel(a.type) ?? humanize(a.type)}, ${humanize(a.channel)}, ${humanize(a.decision)})`,+ ),),),);const sc = sd.scoreComponents;- parts.push(+ sections.push(section('Score breakdown', [- sc && `- Demand: ${Math.round(sc.demand)}`,- sc && `- Visibility gap: ${Math.round(sc.visibilityGap)}`,- sc && `- Competitor gap: ${Math.round(sc.competitorGap)}`,- sc && `- Intent: ${Math.round(sc.intent)}`,+ sc && field('Demand', String(Math.round(sc.demand))),+ sc && field('Visibility gap', String(Math.round(sc.visibilityGap))),+ sc && field('Competitor gap', String(Math.round(sc.competitorGap))),+ sc && field('Intent', String(Math.round(sc.intent))),]),);const queries = sd.queries?.top.map((q) => q.query) ?? fanoutQueries.map((q) => q.query);- parts.push(+ sections.push(section('Source data', [- sd.promptText && `- Related prompt: ${sd.promptText}`,- sd.clusterLabel && `- Cluster: ${sd.clusterLabel}`,- sd.topicName && `- Topic: ${sd.topicName}`,- sd.estAiVolume != null && `- Est. AI volume: ${fmt(sd.estAiVolume)}`,- sd.visibilityScore != null && `- Visibility: ${Math.round(sd.visibilityScore)}%`,- sd.competitorGap != null && `- Competitor gap: ${Math.round(sd.competitorGap)}%`,- sd.intent && `- Intent: ${sd.intent}`,- !!sd.keywords?.length && `- Keywords: ${sd.keywords.join(', ')}`,- !!sd.competitorsCited?.length && `- Competitors cited: ${sd.competitorsCited.join(', ')}`,+ field('Related prompt', sd.promptText),+ field('Cluster', sd.clusterLabel),+ field('Topic', sd.topicName),+ sd.estAiVolume != null && field('Est. AI volume', fmt(sd.estAiVolume)),+ sd.visibilityScore != null && field('Visibility', `${Math.round(sd.visibilityScore)}%`),+ sd.competitorGap != null && field('Competitor gap', `${Math.round(sd.competitorGap)}%`),+ field('Intent', sd.intent),+ !!sd.keywords?.length && field('Keywords', sd.keywords.join(', ')),+ !!sd.competitorsCited?.length && field('Competitors cited', sd.competitorsCited.join(', ')),]),);- parts.push(- section(- 'Prompts',- (sd.prompts ?? []).map((p) => `- ${p}`),- ),- );- parts.push(- section(- 'Fan-out queries',- queries.map((q) => `- ${q}`),- ),- );+ sections.push(section('Prompts', (sd.prompts ?? []).map(item)));+ sections.push(section('Fan-out queries', queries.map(item)));if (brief) {- parts.push(+ sections.push(section('Content brief', [- `- Suggested title: ${brief.suggestedTitle}`,- `- Content type: ${brief.contentType}`,- `- Target word count: ${fmt(brief.targetWordCount)}`,- brief.targetKeywords.length > 0 && `- Keywords: ${brief.targetKeywords.join(', ')}`,- brief.callToAction && `- CTA: ${brief.callToAction}`,+ field('Suggested title', brief.suggestedTitle),+ field('Content type', brief.contentType),+ field('Target word count', fmt(brief.targetWordCount)),+ brief.targetKeywords.length > 0 && field('Keywords', brief.targetKeywords.join(', ')),+ field('CTA', brief.callToAction),]),);- parts.push(- brief.outline.length- ? `## Brief outline\n\n${brief.outline- .map(- (s, i) => `${i + 1}. ${s.heading}${s.keyPoints.map((k) => `\n - ${k}`).join('')}`,- )- .join('\n')}`- : null,+ sections.push(+ section(+ 'Brief outline',+ brief.outline.map(+ (s, i): OpportunityLine => ({+ kind: 'step',+ n: i + 1,+ text: s.heading,+ points: s.keyPoints,+ }),+ ),+ ),);- parts.push(- brief.competitorInsights ? `## Competitor insights\n\n${brief.competitorInsights}` : null,+ sections.push(+ section('Competitor insights', [+ brief.competitorInsights && { kind: 'text', text: brief.competitorInsights },+ ]),);}- return parts.filter((p): p is string => !!p).join('\n\n') + '\n';+ return {+ title: opportunity.title,+ description: opportunity.description || null,+ sections: sections.filter((s) => s.lines.length > 0),+ };+}++function markdownLine(line: OpportunityLine): string {+ switch (line.kind) {+ case 'field':+ return `- ${line.label}: ${line.value}`;+ case 'item':+ return `- ${line.text}`;+ case 'step':+ return `${line.n}. ${line.text}${line.points.map((p) => `\n - ${p}`).join('')}`;+ case 'text':+ return line.text;+ }+}++/**+ * Everything the opportunity detail shows, as Markdown in page order, for the+ * Copy All Data button. Empty sections are left out.+ */+export function opportunityToMarkdown(+ opportunity: ContentOpportunity,+ brief: ContentBrief | null,+ fanoutQueries: { query: string }[] = [],+ /** An asset's type as the page names it (useAssetTypeLabel); else its key, humanized. */+ assetTypeLabel: (type: string) => string | null = () => null,+): string {+ const doc = opportunityDocument(opportunity, brief, fanoutQueries, assetTypeLabel);+ const parts = [+ [`# ${doc.title}`, doc.description].filter(Boolean).join('\n\n'),+ ...doc.sections.map((s) => {+ const body = s.lines.map(markdownLine).join('\n');+ return s.title ? `## ${s.title}\n\n${body}` : body;+ }),+ ];+ return parts.join('\n\n') + '\n';}diff --git a/web/yarn.lock b/web/yarn.lockindex de29a54f1..c07f4fb56 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -2525,7 +2525,7 @@dependencies:undici-types "~7.18.0"-"@types/node@>=13.7.0":+"@types/node@>=13.7.0", "@types/node@^25.2.3":version "25.7.0"resolved "https://registry.yarnpkg.com/@types/node/-/node-25.7.0.tgz#7498f82e90dbdce7c34b75aaaa256c498a0ebe6c"integrity sha512-z+pdZyxE+RTQE9AcboAZCb4otwcrvgHD+GlBpPgn0emDVt0ohrTMhAwlr2Wd9nZ+nihhYFxO2pThz3C5qSu2Eg==@@ -3748,6 +3748,18 @@ doctrine@^2.1.0:dependencies:esutils "^2.0.2"+ version "9.7.0"+ resolved "https://registry.yarnpkg.com/docx/-/docx-9.7.0.tgz#0562eee67917868d20e83c67d840ac3dbb698493"+ integrity sha512-saDn+8rAtW9nPlWxDs31Kbb/hL+AhHQN2gktHkWwkj59u9htUXtpVMN1Z+cSoLGCAaeYpW7Qe9F5sU3aPdiy9w==+ dependencies:+ "@types/node" "^25.2.3"+ hash.js "^1.1.7"+ jszip "^3.10.1"+ nanoid "^5.1.3"+ xml "^1.0.1"+ xml-js "^1.6.8"+dom-serializer@^2.0.0:version "2.0.0"resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-2.0.0.tgz#e41b802e1eedf9f6cae183ce5e622d789d7d8e53"@@ -4811,6 +4823,14 @@ has-tostringtag@^1.0.2:dependencies:has-symbols "^1.0.3"+hash.js@^1.1.7:+ version "1.1.7"+ resolved "https://registry.yarnpkg.com/hash.js/-/hash.js-1.1.7.tgz#0babca538e8d4ee4a0f8988d68866537a003cf42"+ integrity sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==+ dependencies:+ inherits "^2.0.3"+ minimalistic-assert "^1.0.1"+hasown@^2.0.2:version "2.0.2"resolved "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz"@@ -5554,7 +5574,7 @@ jsonfile@^6.0.1:object.assign "^4.1.4"object.values "^1.1.6"-jszip@^3.7.1:+jszip@^3.10.1, jszip@^3.7.1:version "3.10.2"resolved "https://registry.yarnpkg.com/jszip/-/jszip-3.10.2.tgz#9fee8cfaaffb601f6c8796ecc522e4f81cbe88bf"integrity sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==@@ -6320,6 +6340,11 @@ mimic-function@^5.0.0:resolved "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz"integrity sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==+minimalistic-assert@^1.0.1:+ version "1.0.1"+ resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7"+ integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==+minimatch@^10.0.1, minimatch@^10.2.2:version "10.2.4"resolved "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz"@@ -6383,6 +6408,11 @@ nanoid@^3.3.16, nanoid@^3.3.20:resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.20.tgz#dfd4444d85aa10111ef66ba85ed72e08ba0855d8"integrity sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==+nanoid@^5.1.3:+ version "5.1.16"+ resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-5.1.16.tgz#fe345c0a1f9007c32fbb5c139e1208bfd3f41ef7"+ integrity sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==+napi-postinstall@^0.3.0:version "0.3.4"resolved "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz"@@ -7558,6 +7588,11 @@ [email protected]:parse-srcset "^1.0.2"postcss "^8.3.11"+sax@^1.2.4:+ version "1.6.1"+ resolved "https://registry.yarnpkg.com/sax/-/sax-1.6.1.tgz#4c23cf608c0b693ab54b4b5888e92cfe977b9843"+ integrity sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==+saxen@^11.1.0:version "11.2.0"resolved "https://registry.yarnpkg.com/saxen/-/saxen-11.2.0.tgz#fec7492a2606c01dda58b3426be696de36a4952c"@@ -8866,11 +8901,23 @@ wsl-utils@^0.3.0:is-wsl "^3.1.0"powershell-utils "^0.1.0"+xml-js@^1.6.8:+ version "1.6.11"+ resolved "https://registry.yarnpkg.com/xml-js/-/xml-js-1.6.11.tgz#927d2f6947f7f1c19a316dd8eea3614e8b18f8e9"+ integrity sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==+ dependencies:+ sax "^1.2.4"+xml-name-validator@^5.0.0:version "5.0.0"resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz#82be9b957f7afdacf961e5980f1bf227c0bf7673"integrity sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==+xml@^1.0.1:+ version "1.0.1"+ resolved "https://registry.yarnpkg.com/xml/-/xml-1.0.1.tgz#78ba72020029c5bc87b8a81a3cfcd74b4a2fc1e5"+ integrity sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==+xmlbuilder@^10.0.0:version "10.1.1"resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-10.1.1.tgz#8cae6688cc9b38d850b7c8d3c0a4161dcaf475b0"