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): open the Content Editor from Content Opportunities (#1334)
Cihandb993ea66356
diff --git a/server/src/lib/content-page-types.js b/server/src/lib/content-page-types.jsindex 57c732334..b1038916f 100644--- a/server/src/lib/content-page-types.js+++ b/server/src/lib/content-page-types.js@@ -34,3 +34,79 @@ export function pageTypeFormat(pageType) {if (!pageType) return 'not set';return Object.hasOwn(PAGE_TYPE_FORMATS, pageType) ? PAGE_TYPE_FORMATS[pageType] : pageType;}++/** Kinds of site (brands.site_type, 00205), as web/src/lib/content/page-types.ts has them. */+export const SITE_TYPES = ['b2b', 'ecommerce', 'b2c'];++/** Each kind of site as Brand settings names it (web/messages/en.json, siteTypes). */+export const SITE_TYPE_NAMES = { b2b: 'B2B SaaS', ecommerce: 'E-commerce', b2c: 'B2C' };++/** The page types each kind of site writes, in the order the editor offers them. */+export const SITE_PAGE_TYPES = {+ b2b: [+ 'feature_page',+ 'solution_page',+ 'comparison',+ 'alternatives',+ 'best_of',+ 'guide',+ 'definition',+ 'integration',+ 'pricing',+ 'docs_faq',+ 'blog_post',+ ],+ ecommerce: [+ 'product_page',+ 'category_page',+ 'collection_page',+ 'buying_guide',+ 'best_of',+ 'comparison',+ 'alternatives',+ 'guide',+ 'definition',+ 'sizing_guide',+ 'help_faq',+ 'policy',+ 'blog_post',+ ],+ b2c: [+ 'destination_page',+ 'itinerary',+ 'guide',+ 'best_of',+ 'comparison',+ 'definition',+ 'help_faq',+ 'blog_post',+ ],+};++/** Industries that point away from B2B, as the editor guesses them. */+const INDUSTRY_SITE_TYPES = {+ 'E-commerce & Retail': 'ecommerce',+ 'Fashion & Apparel': 'ecommerce',+ 'Consumer Goods': 'ecommerce',+ 'Food & Beverage': 'ecommerce',+ Automotive: 'ecommerce',+ 'Travel & Hospitality': 'b2c',+};++/**+ * The brand's kind of site: the one picked in Brand settings, else the+ * editor's guess (a shop when Shopping mode is on, else by industry, and B2B+ * when nothing says otherwise).+ *+ * @param {{ siteType?: string|null, industry?: string|null, shoppingModeEnabled?: boolean|null }} brand+ */+export function siteTypeOf({ siteType, industry, shoppingModeEnabled } = {}) {+ if (SITE_TYPES.includes(siteType)) return siteType;+ if (shoppingModeEnabled) return 'ecommerce';+ return Object.hasOwn(INDUSTRY_SITE_TYPES, industry ?? '') ? INDUSTRY_SITE_TYPES[industry] : 'b2b';+}++/** The page types this kind of site writes, one a line with its format, for a model prompt. */+export function sitePageTypeLines(siteType) {+ return SITE_PAGE_TYPES[siteType].map((type) => `- ${type}: ${pageTypeFormat(type)}`).join('\n');+}diff --git a/server/src/lib/content-page-types.test.js b/server/src/lib/content-page-types.test.jsindex ec761b99e..71e4cc106 100644--- a/server/src/lib/content-page-types.test.js+++ b/server/src/lib/content-page-types.test.js@@ -1,6 +1,13 @@import { readFileSync } from 'node:fs';import { describe, expect, it } from 'vitest';-import { PAGE_TYPE_FORMATS, pageTypeFormat } from './content-page-types.js';+import {+ PAGE_TYPE_FORMATS,+ SITE_PAGE_TYPES,+ SITE_TYPES,+ pageTypeFormat,+ sitePageTypeLines,+ siteTypeOf,+} from './content-page-types.js';describe('pageTypeFormat', () => {it('names a page type as the person picks it, with its format', () => {@@ -34,3 +41,42 @@ describe('pageTypeFormat', () => {}});});++describe('siteTypeOf', () => {+ it('takes the site type picked, else guesses it as the editor does', () => {+ expect(siteTypeOf({ siteType: 'b2c', industry: 'E-commerce & Retail' })).toBe('b2c');+ expect(siteTypeOf({ siteType: null, shoppingModeEnabled: true })).toBe('ecommerce');+ expect(siteTypeOf({ siteType: 'retail', industry: 'Fashion & Apparel' })).toBe('ecommerce');+ expect(siteTypeOf({ industry: 'Travel & Hospitality' })).toBe('b2c');+ expect(siteTypeOf({ industry: 'Technology & Software' })).toBe('b2b');+ expect(siteTypeOf({ industry: 'constructor' })).toBe('b2b');+ expect(siteTypeOf()).toBe('b2b');+ });++ it("keeps the editor's lists and guesses (web/src/lib/content/page-types.ts)", () => {+ const source = readFileSync(+ new URL('../../../web/src/lib/content/page-types.ts', import.meta.url),+ 'utf8',+ );+ const block = (start) => source.slice(source.indexOf(start)).match(/\{([\s\S]*?)\n\};/)[1];+ const sites = block('export const SITE_PAGE_TYPES');+ for (const site of SITE_TYPES) {+ const list = sites.match(new RegExp(`\\b${site}: \\[([\\s\\S]*?)\\]`))[1];+ expect(SITE_PAGE_TYPES[site]).toEqual([...list.matchAll(/'([a-z_]+)'/g)].map((m) => m[1]));+ }+ const industries = block('const INDUSTRY_SITE_TYPES');+ const guesses = [...industries.matchAll(/^\s*'?([^':\n]+)'?: '([a-z0-9]+)',$/gm)];+ expect(guesses).toHaveLength(6);+ for (const [, industry, site] of guesses) expect(siteTypeOf({ industry })).toBe(site);+ });+});++describe('sitePageTypeLines', () => {+ it('lists the site’s page types with their formats', () => {+ const lines = sitePageTypeLines('b2c').split('\n');+ expect(lines).toHaveLength(SITE_PAGE_TYPES.b2c.length);+ expect(lines[0]).toBe(+ '- destination_page: Destination page: a place, what to do there and when to go',+ );+ });+});diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.jsindex 456324c88..6adc84c6e 100644--- a/server/src/lib/opportunity-generator.js+++ b/server/src/lib/opportunity-generator.js@@ -43,12 +43,13 @@ import {releaseOpportunitySlots,} from './plan-guard.js';import {- ASSET_TYPES,DECISIONS,MAX_SUPPORTING_ASSETS,+ assetTypes,buildAssets,candidatePages,} from './page-matching.js';+import { SITE_TYPE_NAMES, sitePageTypeLines, siteTypeOf } from './content-page-types.js';/** Existing opportunities shown to the model for the cross-topic check. */const EXISTING_SHOWN = 60;@@ -77,13 +78,14 @@ Rules:- consolidate: two or more listed pages are each mainly about this same need, close to duplicates, and split its signals. Merge them into one. Pages of different kinds (a head-to-head comparison and a general list, a glossary entry and a guide) are not duplicates: pick the page closest to the need and expand or optimize it instead.- defend: the brand is already visible for this need and a listed page answers it. Keep it ahead of competitors.Set pageIndexes to the bracketed P indexes of the pages the decision is about, and leave it empty for create. The title should say what to do with which page, for example "Expand the AI rank tracker comparison with Google AI Overviews coverage".-- The opportunity is the primary asset above. Set assetType to what that content is.-- Add supporting assets only when the data calls for them, up to ${MAX_SUPPORTING_ASSETS}, each a different piece of work. For example: a comparison page when people compare named products; a glossary or FAQ page for a definition the main content relies on; an earned third-party article when competitors are visible and the brand is not; a backlink when the brand's page exists but is not cited. Give each a short title saying what to make or do. Most opportunities need none or one.+- The opportunity is the primary asset above. Set assetType to what that content is: the content type, of those listed for the brand's site, that answers this need there.+- Add supporting assets only when the data calls for them, up to ${MAX_SUPPORTING_ASSETS}, each a different piece of work. Owned ones are of the brand's content types too. For example: a comparison or alternatives page when people compare named products; a definition or FAQ page for a term the main content relies on; an earned third-party article when competitors are visible and the brand is not; a backlink when the brand's page exists but is not cited. Give each a short title saying what to make or do. Most opportunities need none or one.- Earned assets (third_party_article, backlink) live on other sites: set their channel to "earned", decision to "create" and pageIndexes to empty.- Write for the brand's marketing team: do not use the words "cluster" or "prompt" in titles or descriptions.- Refer to clusters and existing opportunities only through clusterIndex and sameAs. Never mention a bracketed index in a title or description.`;-function buildSchema(count) {+/** @param {string[]} types - what an asset can be on the brand's site (assetTypes) */+function buildSchema(count, types) {return z.object({opportunities: z.array(@@ -103,11 +105,11 @@ function buildSchema(count) {pageIndexes: z.array(z.number()).describe('The P indexes of the existing pages the decision is about'),- assetType: z.enum(ASSET_TYPES).describe('What the primary content is'),+ assetType: z.enum(types).describe('What the primary content is'),supportingAssets: z.array(z.object({- type: z.enum(ASSET_TYPES),+ type: z.enum(types),channel: z.enum(['owned', 'earned']),decision: z.enum(DECISIONS),pageIndexes: z.array(z.number()),@@ -309,7 +311,7 @@ export async function generateContentOpportunities(const { data: brand } = await supabaseAdmin.from('brands')- .select('id, name, industry, language, organization_id')+ .select('id, name, industry, language, organization_id, site_type, shopping_mode_enabled').eq('id', brandId).single();if (!brand) return { generated: 0, merged: 0 };@@ -526,9 +528,22 @@ Brand pages that may cover this need:${pages.map(pageLine).join('\n') || 'none found'}`;};+ // The content types follow the brand's kind of site, as the Content Editor's+ // page types do: a shop gets product pages, a SaaS brand feature pages.+ const siteType = siteTypeOf({+ siteType: brand.site_type,+ industry: brand.industry,+ shoppingModeEnabled: brand.shopping_mode_enabled,+ });+ const types = assetTypes(siteType);+const userPrompt = `Brand: ${brand.name}Industry: ${brand.industry || 'Not specified'}Domain: ${(domainsRes.data || []).map((d) => d.domain).join(', ') || 'N/A'}+Site type: ${SITE_TYPE_NAMES[siteType]}++Content types for the brand's site (owned assets):+${sitePageTypeLines(siteType)}Clusters (highest opportunity first):${picked.map(clusterLine).join('\n\n')}@@ -547,7 +562,7 @@ ${alternativeOf ? `${alternativeInstruction(alternativeOf)}\n\n` : ''}${onProgress?.({ phase: 'analyzing', message: 'Generating opportunities with AI...' });const { object } = await generateObject({model: resolveModel(model),- schema: buildSchema(picked.length),+ schema: buildSchema(picked.length, types),system: SYSTEM_PROMPT,prompt: userPrompt,}).catch(async (err) => {@@ -629,6 +644,7 @@ ${alternativeOf ? `${alternativeInstruction(alternativeOf)}\n\n` : ''}${},opp.supportingAssets,pagesFor.get(cand.id),+ types,);const [primary] = assets;inserts.push({diff --git a/server/src/lib/page-matching.js b/server/src/lib/page-matching.jsindex 3bc396473..4149d927e 100644--- a/server/src/lib/page-matching.js+++ b/server/src/lib/page-matching.js@@ -9,6 +9,8 @@* ignores.*/+import { SITE_PAGE_TYPES } from './content-page-types.js';+/** Candidate pages shown to the model per cluster. */export const CANDIDATES_PER_CLUSTER = 8;@@ -99,19 +101,16 @@ export function resolveDecision(decision, pageIndexes, candidates) {return { decision: valid, pages };}-/** What an asset is. Owned types are pages on the brand's site; earned ones live elsewhere. */-export const ASSET_TYPES = [- 'blog_post',- 'pillar_guide',- 'landing_page',- 'comparison_page',- 'glossary_page',- 'faq_page',- 'product_page',- 'category_page',- 'third_party_article',- 'backlink',-];+/** Assets that live on other sites, whatever the brand's kind of site. */+export const EARNED_ASSET_TYPES = ['third_party_article', 'backlink'];++/**+ * What an asset can be on this kind of site: a page type the Content Editor+ * offers it (content-page-types.js), or an earned asset.+ */+export function assetTypes(siteType) {+ return [...SITE_PAGE_TYPES[siteType], ...EARNED_ASSET_TYPES];+}/** Supporting assets an opportunity may add to its primary one. */export const MAX_SUPPORTING_ASSETS = 3;@@ -128,24 +127,26 @@ const toPage = (p) => ({* An opportunity's assets, primary first, each with a stable key, its type,* channel, decision, title and the existing pages it works on. Earned assets* live off the brand's site, so they are always new and carry no page. A- * supporting asset of an unknown type, or one repeating the primary's type- * and decision, is dropped; so is anything past MAX_SUPPORTING_ASSETS.+ * supporting asset of a type outside `types`, or one repeating the primary's+ * type and decision, is dropped; so is anything past MAX_SUPPORTING_ASSETS.+ * A primary of such a type is a blog post, which every kind of site writes.** @param {{type: string, channel: string, decision: string, title: string, pageIndexes: number[]}} primary* @param {typeof primary[]} supporting* @param {object[]} candidates - the cluster's candidate pages+ * @param {string[]} types - what an asset can be on the brand's site (assetTypes)*/-export function buildAssets(primary, supporting, candidates) {+export function buildAssets(primary, supporting, candidates, types) {const assets = [];const seen = new Set();for (const a of [primary, ...(supporting || []).slice(0, MAX_SUPPORTING_ASSETS)]) {- if (!a || (assets.length && !ASSET_TYPES.includes(a.type))) continue;+ if (!a || (assets.length && !types.includes(a.type))) continue;const channel = a.channel === 'earned' ? 'earned' : 'owned';const { decision, pages } =channel === 'earned'? { decision: 'create', pages: [] }: resolveDecision(a.decision, a.pageIndexes, candidates);- const type = ASSET_TYPES.includes(a.type) ? a.type : 'blog_post';+ const type = types.includes(a.type) ? a.type : 'blog_post';const id = `${type}:${decision}:${pages.map((p) => p.url).join(',')}`;if (seen.has(id)) continue;seen.add(id);diff --git a/server/src/lib/page-matching.test.js b/server/src/lib/page-matching.test.jsindex ca352d407..f0a960def 100644--- a/server/src/lib/page-matching.test.js+++ b/server/src/lib/page-matching.test.js@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest';-import { buildAssets, candidatePages, resolveDecision, tokens } from './page-matching.js';+import {+ assetTypes,+ buildAssets,+ candidatePages,+ resolveDecision,+ tokens,+} from './page-matching.js';describe('tokens', () => {it('keeps meaningful words, folds plain plurals and handles any script', () => {@@ -69,7 +75,18 @@ describe('resolveDecision', () => {});});+describe('assetTypes', () => {+ it("offers the site's page types, then the earned ones", () => {+ expect(assetTypes('ecommerce')).toContain('product_page');+ expect(assetTypes('ecommerce')).not.toContain('feature_page');+ expect(assetTypes('b2b')).toContain('feature_page');+ expect(assetTypes('b2b')).not.toContain('product_page');+ expect(assetTypes('b2c').slice(-2)).toEqual(['third_party_article', 'backlink']);+ });+});+describe('buildAssets', () => {+ const types = assetTypes('b2b');const candidates = [{ url: 'https://example.com/list', title: 'Tool list', ai_citations: 3, ga_sessions: 9 },{ url: 'https://example.com/vs', title: 'A vs B', ai_citations: 0, ga_sessions: 1 },@@ -80,7 +97,7 @@ describe('buildAssets', () => {{ type: 'blog_post', channel: 'owned', decision: 'expand', pageIndexes: [0], title: 'Main' },[{- type: 'comparison_page',+ type: 'comparison',channel: 'owned',decision: 'optimize',pageIndexes: [1],@@ -89,12 +106,13 @@ describe('buildAssets', () => {{ type: 'backlink', channel: 'earned', decision: 'optimize', pageIndexes: [0], title: 'L' },],candidates,+ types,);expect(assets.map((a) => [a.key, a.type, a.channel, a.decision, a.pages.map((p) => p.url)]),).toEqual([['a1', 'blog_post', 'owned', 'expand', ['https://example.com/list']],- ['a2', 'comparison_page', 'owned', 'optimize', ['https://example.com/vs']],+ ['a2', 'comparison', 'owned', 'optimize', ['https://example.com/vs']],// Earned work lives on other sites: always new, no page of ours.['a3', 'backlink', 'earned', 'create', []],]);@@ -107,7 +125,7 @@ describe('buildAssets', () => {});});- it('drops unknown types, repeats of the same work and anything past the cap', () => {+ it("drops types the site doesn't write, repeats of the same work and anything past the cap", () => {const extra = (type) => ({type,channel: 'owned',@@ -116,10 +134,22 @@ describe('buildAssets', () => {title: type,});const assets = buildAssets(- { type: 'faq_page', channel: 'owned', decision: 'create', pageIndexes: [], title: 'FAQ' },- [extra('podcast'), extra('faq_page'), extra('glossary_page'), extra('landing_page')],+ { type: 'docs_faq', channel: 'owned', decision: 'create', pageIndexes: [], title: 'FAQ' },+ [extra('product_page'), extra('docs_faq'), extra('definition'), extra('pricing')],+ candidates,+ types,+ );+ // A shop's product page isn't a B2B page type, and pricing is past the cap.+ expect(assets.map((a) => a.type)).toEqual(['docs_faq', 'definition']);+ });++ it("makes a primary of a type the site doesn't write a blog post", () => {+ const [primary] = buildAssets(+ { type: 'feature_page', channel: 'owned', decision: 'create', pageIndexes: [], title: 'X' },+ [],candidates,+ assetTypes('ecommerce'),);- expect(assets.map((a) => a.type)).toEqual(['faq_page', 'glossary_page']);+ expect(primary.type).toBe('blog_post');});});diff --git a/web/messages/en.json b/web/messages/en.jsonindex 0441d0e3f..f8f3f377e 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3326,6 +3326,7 @@"detectedTitle": "Picked from the title.","detectedContent": "Picked from the content.","detectedPage": "Picked from the page.",+ "detectedOpportunity": "Picked from the opportunity.","openEditor": "Open editor","pageUnread": "Couldn't read {page}: the draft starts with its title.","failed": "Couldn't start the draft. Try again.",@@ -4019,13 +4020,22 @@"opportunities": "Opportunities","autoGeneratedHint": "Opportunities are generated automatically as your tracking data comes in.","generating": "Generating…",- "send": "Send","sendToWorkflow": "Send to Workflow","generateBrief": "Generate Brief","generatingBrief": "Generating...","briefGenerated": "Brief Generated","briefLimitReached": "You've used this month's content briefs","sendToActions": "Send to Actions",+ "draftCheckFailed": "Couldn't check for a draft · Retry",+ "sendToEditor": "Send to Editor",+ "openDraft": "Open draft",+ "sendToPlan": "Send to Plan",+ "openInPlan": "Open in Plan",+ "sentToPlan": "Added to the Plan's priority list",+ "sendToPlanError": "Couldn't add it to the Plan. Please try again.",+ "openPlan": "Open Plan",+ "moreActions": "More actions",+ "rowActions": "Actions for {title}","openInActions": "Open in Actions","sendAgain": "Send Again","copyAllData": "Copy All Data",@@ -4332,14 +4342,6 @@"defend": "You are already visible here. Keep this page ahead of competitors."},"assetType": {- "blog_post": "Blog post",- "pillar_guide": "Pillar guide",- "landing_page": "Landing page",- "comparison_page": "Comparison page",- "glossary_page": "Glossary page",- "faq_page": "FAQ page",- "product_page": "Product page",- "category_page": "Category page","third_party_article": "Third-party article","backlink": "Backlink"},diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 9801edc3f..f97a0dbd5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -51,7 +51,6 @@ import {BarChart3,Search,Loader2,- ExternalLink,X,Settings2,Trash2,@@ -61,6 +60,7 @@ import {} from 'lucide-react';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';+import { useAssetTypeLabel } from '@/hooks/use-asset-type-label';import {generateOpportunitiesOnDemand,getGenerationJobStatus,@@ -78,7 +78,15 @@ import {} from '@/lib/actions/content';import type { ContentOpportunity, ContentOpportunityStatus } from '@/types';import { toast } from 'sonner';-import { Link } from '@/i18n/navigation';+import { useRouter } from '@/i18n/navigation';+import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';+import { getOpportunityDrafts } from '@/lib/actions/content-drafts';+import { getPlanPriorities, setPlanRowPriority } from '@/lib/actions/content-plan';+import { OpportunityRowMenu } from '@/components/content/opportunity-row-menu';+import { useUserRole } from '@/hooks/use-user-role';+import { contentEditorPath } from '@/lib/content/drafts';+import { canWriteOpportunity, opportunityStart } from '@/lib/content/opportunity-start';+import { siteTypeOf } from '@/lib/content/page-types';import { WebhookSettingsDialog } from './_webhook-settings';import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';import {@@ -332,6 +340,7 @@ interface PromptFilterItem {export default function ContentPage() {const t = useTranslations('content');+ const assetTypeLabel = useAssetTypeLabel();const tCommon = useTranslations('common');const locale = useLocale();const activeBrandId = useBrandStore((s) => s.activeBrandId);@@ -488,6 +497,70 @@ export default function ContentPage() {// Action Center's drawers: a refresh or a shared link reopens it, and// opening one never navigates away from the filtered list.const [openOpportunityId, setOpenOpportunityId] = useState<string | null>(null);+ // Send to Editor from a row: Start for its opportunity.+ const router = useRouter();+ const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));+ const [contentPreset, setContentPreset] = useState<DialogPreset | null>(null);+ // The drafts being written for the rows on screen, which open instead. A+ // failed read is not "no draft": the rows offer to check again, so Start+ // never writes a second draft for the same opportunity.+ const shownIds = opportunities.map((o) => o.id).join(',');+ const [drafts, setDrafts] = useState<{+ key: string;+ byOpportunity: Record<string, string>;+ failed: boolean;+ }>({ key: '', byOpportunity: {}, failed: false });+ const [draftsAttempt, setDraftsAttempt] = useState(0);+ useEffect(() => {+ if (!activeBrandId || !shownIds) return;+ let cancelled = false;+ getOpportunityDrafts(activeBrandId, shownIds.split(',')).then(+ (byOpportunity) => !cancelled && setDrafts({ key: shownIds, byOpportunity, failed: false }),+ () => !cancelled && setDrafts({ key: shownIds, byOpportunity: {}, failed: true }),+ );+ return () => {+ cancelled = true;+ };+ }, [activeBrandId, shownIds, draftsAttempt]);+ // Null until the rows' drafts are known: their button waits.+ const draftsShown = drafts.key === shownIds ? drafts : null;+ const retryDrafts = () => {+ setDrafts((d) => ({ ...d, key: '' }));+ setDraftsAttempt((n) => n + 1);+ };+ // Send to Plan: which rows are a priority in the Content plan already.+ const { canManage } = useUserRole();+ const [priorities, setPriorities] = useState<{ key: string; ids: string[] }>({+ key: '',+ ids: [],+ });+ useEffect(() => {+ if (!activeBrandId || !shownIds || !canManage) return;+ let cancelled = false;+ getPlanPriorities(activeBrandId, shownIds.split(',')).then(+ (ids) => !cancelled && setPriorities({ key: shownIds, ids }),+ () => !cancelled && setPriorities({ key: shownIds, ids: [] }),+ );+ return () => {+ cancelled = true;+ };+ }, [activeBrandId, shownIds, canManage]);+ const prioritiesShown = priorities.key === shownIds ? priorities.ids : null;+ // A row marked here or from the panel: its menu says Open in Plan then.+ const markPrioritized = (id: string) =>+ setPriorities((p) => (p.ids.includes(id) ? p : { ...p, ids: [...p.ids, id] }));+ const handleSendToPlan = async (id: string) => {+ if (!activeBrandId) return;+ try {+ await setPlanRowPriority(activeBrandId, `opportunity:${id}`, true);+ markPrioritized(id);+ toast.success(t('sentToPlan'), {+ action: { label: t('openPlan'), onClick: () => router.push('/dashboard/content/plan') },+ });+ } catch {+ toast.error(t('sendToPlanError'));+ }+ };useEffect(() => {const params = new URLSearchParams(window.location.search);@@ -1454,9 +1527,7 @@ export default function ContentPage() {<TableHead className="w-[88px] text-center">{t('table.impact')}</TableHead><TableHead className="w-[72px] text-center">{t('table.score')}</TableHead><TableHead className="w-[136px] text-center">{t('table.status')}</TableHead>- <TableHead className="w-[176px] text-right pr-6">- {t('table.actions')}- </TableHead>+ <TableHead className="w-[96px] text-right pr-6">{t('table.actions')}</TableHead></TableRow></TableHeader><TableBody>@@ -1568,6 +1639,11 @@ export default function ContentPage() {{t(`decision.${opp.decision}`)}</Badge>)}+ {assetTypeLabel(opp.sourceData?.assets?.[0]?.type) && (+ <span className="text-[11px] leading-tight text-muted-foreground">+ {assetTypeLabel(opp.sourceData?.assets?.[0]?.type)}+ </span>+ )}</div></TableCell><TableCell className="text-center">@@ -1597,51 +1673,45 @@ export default function ContentPage() {</Badge></TableCell><TableCell className="text-right pr-6">- <div className="flex items-center justify-end gap-1">- {opp.status === 'new' && (- <>- <Button- variant="ghost"- size="sm"- className="h-7 px-2 text-xs gap-1"- onClick={() => handleSendWebhook(opp.id)}- disabled={sendingId === opp.id}- >- {sendingId === opp.id ? (- <Loader2 className="h-3 w-3 animate-spin" />- ) : (- <Send className="h-3 w-3" />- )}- {t('send')}- </Button>- <Button- variant="ghost"- size="sm"- className="h-7 px-2 text-xs text-muted-foreground"- onClick={() => handleDismiss(opp.id)}- aria-label={t('dismiss')}- >- <X className="h-3 w-3" />- </Button>- </>- )}- {/* The full page, in a new tab so the list stays put. */}- <Link- href={`/dashboard/content/${opp.id}`}- target="_blank"- rel="noopener noreferrer"- >- <Button- variant="ghost"- size="sm"- className="h-7 px-2 text-xs"- aria-label={t('openInNewTab')}- title={t('openInNewTab')}- >- <ExternalLink className="h-3 w-3" />- </Button>- </Link>- </div>+ <OpportunityRowMenu+ title={opp.title}+ editor={{+ draftId:+ draftsShown && !draftsShown.failed+ ? (draftsShown.byOpportunity[opp.id] ?? null)+ : undefined,+ lookupFailed: draftsShown?.failed ?? false,+ onRetry: retryDrafts,+ canStart: canWriteOpportunity(opp),+ onStart: () => setContentPreset(opportunityStart(opp)),+ onOpenDraft: (draftId) => router.push(contentEditorPath(draftId)),+ }}+ // The Plan lists owned work still open; its marks are+ // for admins and managers.+ plan={+ canManage && canWriteOpportunity(opp)+ ? {+ prioritized: prioritiesShown+ ? prioritiesShown.includes(opp.id)+ : undefined,+ onSend: () => void handleSendToPlan(opp.id),+ onOpen: () => router.push('/dashboard/content/plan'),+ }+ : null+ }+ workflow={+ opp.status === 'new'+ ? {+ sending: sendingId === opp.id,+ onSend: () => void handleSendWebhook(opp.id),+ }+ : null+ }+ pageHref={`/dashboard/content/${opp.id}`}+ onDismiss={+ opp.status === 'new' ? () => void handleDismiss(opp.id) : undefined+ }+ /></TableCell></TableRow>))}@@ -1671,6 +1741,15 @@ export default function ContentPage() {</>)}+ {activeBrandId && (+ <NewContentDialog+ open={contentPreset !== null}+ onOpenChange={(open) => !open && setContentPreset(null)}+ brandId={activeBrandId}+ siteType={siteTypeOf(activeBrand ?? {})}+ preset={contentPreset}+ />+ )}<Sheetopen={openOpportunityId !== null}onOpenChange={(open) => {@@ -1686,6 +1765,7 @@ export default function ContentPage() {id={openOpportunityId}inDraweronChanged={() => loadData(true)}+ onPrioritized={markPrioritized}/>)}</div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsxindex f5cee36d1..02097bbad 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx@@ -81,6 +81,7 @@ const opportunity: PlanOpportunity = {competitorsCited: ['Daily Grind Co.', 'Origin Box'],visibility: 6,prompts: 2,+ assetType: null,};const PLAN = {pages: [diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsxindex 40f568dfb..511d80d41 100644--- a/web/src/components/content/new-content-dialog.test.tsx+++ b/web/src/components/content/new-content-dialog.test.tsx@@ -107,12 +107,19 @@ if (!('text' in Blob.prototype)) {const OPTIONS = {opportunities: [- { id: 'o1', title: 'Northwind vs HubSpot', decision: 'create', pageTitle: null },+ {+ id: 'o1',+ title: 'Northwind vs HubSpot',+ decision: 'create',+ pageTitle: null,+ assetType: null,+ },{id: 'o2',title: 'Create a page for realtors',decision: 'create',pageTitle: 'CRM for real estate teams',+ assetType: null,},],prompts: [{ id: 'p1', text: 'best crm for realtors', seen: false }],@@ -451,6 +458,61 @@ describe('New content', () => {});});+ it("picks the opportunity's page type for a new page, and for its page when that shows none", async () => {+ getContentStartOptions.mockResolvedValue({+ ...OPTIONS,+ opportunities: [+ // An older type, read as this B2B site's: Docs / FAQ, not the title's comparison.+ { ...OPTIONS.opportunities[0], id: 'o3', decision: 'expand', assetType: 'faq_page' },+ ],+ });+ await render('b2b', {+ kind: 'opportunity',+ id: 'o3',+ // Nothing in its address or title says what the page is.+ page: { url: 'https://northwind.example/crm-tips', title: 'CRM tips' },+ });+ await act(async () => {});+ expect(document.body.textContent).toContain('Optimize: CRM tips');+ expect(checkedType()).toBe('Docs / FAQ');+ expect(document.body.textContent).toContain('Picked from the opportunity.');++ await click(radio('Create a new page'));+ expect(checkedType()).toBe('Docs / FAQ');+ await click(button('Open editor'));+ expect(createContentDraft.mock.calls[0][1]).toMatchObject({+ method: 'create',+ pageType: 'docs_faq',+ typePicked: false,+ });+ });++ it("types an existing page by its own address first, then by the opportunity's type", async () => {+ getContentStartOptions.mockResolvedValue({+ ...OPTIONS,+ opportunities: [{ ...OPTIONS.opportunities[0], decision: 'expand', assetType: 'faq_page' }],+ });+ await render('b2b', {+ kind: 'opportunity',+ id: 'o1',+ page: { url: 'https://northwind.example/pricing', title: 'Pricing' },+ });+ await act(async () => {});+ // An older opportunity's "FAQ page" doesn't make /pricing anything but pricing.+ expect(checkedType()).toBe('Pricing');+ expect(document.body.textContent).toContain('Picked from the page.');+ });++ it("guesses from the title when the site doesn't write the opportunity's type", async () => {+ getContentStartOptions.mockResolvedValue({+ ...OPTIONS,+ opportunities: [{ ...OPTIONS.opportunities[0], assetType: 'sizing_guide' }],+ });+ await render('b2b', { kind: 'opportunity', id: 'o1' });+ expect(checkedType()).toBe('Comparison');+ expect(document.body.textContent).toContain('Picked from the title.');+ });+it('lets a person write a new page instead of the plan’s page when nothing overlaps', async () => {getContentOverlap.mockResolvedValue({ totalPrompts: 2, pages: [] });await render('b2b', {diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsxindex 7c82c327b..3527ba8e7 100644--- a/web/src/components/content/new-content-dialog.tsx+++ b/web/src/components/content/new-content-dialog.tsx@@ -69,6 +69,7 @@ import {type OverlapChoice,type OverlapOption,} from '@/lib/content/overlap';+import { opportunityPageType } from '@/lib/content/asset-types';import { SITE_PAGE_TYPES, detectPageType, type SiteType } from '@/lib/content/page-types';import {fileTitle,@@ -89,6 +90,8 @@ interface PickerItem {meta?: string;/** The page's title, when it isn't the label (an opportunity's brief title). */pageTitle?: string;+ /** The page type an opportunity names for its page, when the site writes it. */+ pageType?: PageType;}/** Content brought to optimize: cleaned HTML, what it holds, and where it came from. */@@ -105,7 +108,7 @@ interface BroughtContent extends ContentSummary {type ContentFrom = 'url' | 'paste' | 'file';/** Where Start's first page type came from, if it was read from somewhere. */-type DetectedFrom = 'title' | 'content' | 'page' | null;+type DetectedFrom = 'title' | 'content' | 'page' | 'opportunity' | null;/** What Start opens the editor with. */interface StartChoice {@@ -253,11 +256,7 @@ export function NewContentDialog({presetApplied.current = true;const opportunity = options.opportunities.find((o) => o.id === preset.id);if (!opportunity) return;- const item = {- value: opportunity.id,- label: opportunity.title,- pageTitle: opportunity.pageTitle ?? undefined,- };+ const item = opportunityItem(opportunity, siteType);setKind('opportunity');setPicked(item);startFrom(@@ -324,11 +323,7 @@ export function NewContentDialog({const items: PickerItem[] = !options? []: kind === 'opportunity'- ? options.opportunities.map((o) => ({- value: o.id,- label: o.title,- pageTitle: o.pageTitle ?? undefined,- }))+ ? options.opportunities.map((o) => opportunityItem(o, siteType)): kind === 'prompt'? // A prompt the brand is already named in or cited for needs no new page.options.prompts.filter((p) => !p.seen).map((p) => ({ value: p.id, label: p.text }))@@ -408,17 +403,20 @@ export function NewContentDialog({/*** Start for a new page from what was picked: its title, and the page type- * it reads as. With a page (an opportunity for an existing page, from the- * plan), Start optimizes that page, and it stays chosen.+ * its opportunity names, else the one it reads as. With a page (an+ * opportunity for an existing page, from the plan), Start optimizes that+ * page, and it stays chosen.*/const startFrom = (item: PickerItem, from: SourceKind, page?: OverlapPage) => {const title = item.pageTitle ?? item.label;const type = startPageType({ title }, siteType);- const newPageType = {- pageType: type.pageType,- detectedFrom: type.detected ? ('title' as const) : null,- picked: false,- };+ const newPageType = item.pageType+ ? { pageType: item.pageType, detectedFrom: 'opportunity' as const, picked: false }+ : {+ pageType: type.pageType,+ detectedFrom: type.detected ? ('title' as const) : null,+ picked: false,+ };const next: StartChoice = {method: 'create',title,@@ -637,6 +635,7 @@ export function NewContentDialog({title: 'start.detectedTitle',content: 'start.detectedContent',page: 'start.detectedPage',+ opportunity: 'start.detectedOpportunity',}[start.detectedFrom],)}</p>@@ -991,14 +990,34 @@ export function NewContentDialog({);}+/** An opportunity to pick, with the page type it names when the site writes it. */+function opportunityItem(+ opportunity: DraftStartOptions['opportunities'][number],+ siteType: SiteType,+): PickerItem {+ return {+ value: opportunity.id,+ label: opportunity.title,+ pageTitle: opportunity.pageTitle ?? undefined,+ pageType: opportunityPageType(opportunity.assetType, siteType) ?? undefined,+ };+}+function sourceKey(source: Exclude<DraftSource, { kind: 'content' }>) {return `${source.kind}:${source.id}`;}-/** Start with this overlap pick: an existing page brings its own title and type. */+/**+ * Start with this overlap pick: an existing page brings its own title and+ * the type its address or title shows; when they show none, the type its+ * opportunity names, unless the person picked one.+ */function withChoice(start: StartChoice, choice: OverlapChoice, siteType: SiteType): StartChoice {if (choice.kind === 'create') return { ...start, choice, ...start.newPageType };const detected = detectPageType({ url: choice.page.url, title: choice.page.title }, siteType);+ if (!detected && !start.picked && start.newPageType.detectedFrom === 'opportunity') {+ return { ...start, choice, ...start.newPageType };+ }return {...start,choice,diff --git a/web/src/components/content/opportunity-actions.test.tsx b/web/src/components/content/opportunity-actions.test.tsxnew file mode 100644index 000000000..c4e108ea5--- /dev/null+++ b/web/src/components/content/opportunity-actions.test.tsx@@ -0,0 +1,163 @@+import { act, type ComponentProps } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import { OpportunityActions } from './opportunity-actions';++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children }: { href: string; children: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;+const handlers = {+ send: vi.fn(),+ brief: vi.fn(),+ start: vi.fn(),+ retry: vi.fn(),+ openDraft: vi.fn(),+ plan: vi.fn(),+ openPlan: vi.fn(),+ alternative: vi.fn(),+ workflow: vi.fn(),+ copy: vi.fn(),+ reviewed: vi.fn(),+ dismiss: vi.fn(),+};++type Props = ComponentProps<typeof OpportunityActions>;+const props = (over: Partial<Props> = {}): Props => ({+ actionId: null,+ sendToActions: { sending: false, disabled: false, onSend: handlers.send },+ brief: { generated: false, generating: false, blockedReason: null, onGenerate: handlers.brief },+ content: {+ draftId: null,+ canStart: true,+ onStart: handlers.start,+ onOpenDraft: handlers.openDraft,+ },+ plan: { prioritized: false, onSend: handlers.plan, onOpen: handlers.openPlan },+ alternative: { running: false, onOpen: handlers.alternative },+ workflow: { sending: false, sentBefore: false, onSend: handlers.workflow },+ onCopy: handlers.copy,+ onReviewed: handlers.reviewed,+ onDismiss: handlers.dismiss,+ ...over,+});++async function render(p: Props) {+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <OpportunityActions {...p} />+ </NextIntlClientProvider>,+ ),+ );+}+// The buttons in front, before the "…" menu (an icon, with no text).+const front = () =>+ [...container.firstElementChild!.children].map((el) => el.textContent?.trim()).filter(Boolean);+const button = (name: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === name)!;+async function openMenu() {+ const trigger = container.querySelector<HTMLButtonElement>('[aria-label="More actions"]')!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ Object.values(handlers).forEach((h) => h.mockReset());+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.body.replaceChildren();+});++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']);+ await act(async () => button('Send to Editor').click());+ expect(handlers.start).toHaveBeenCalled();+ });++ it('shows each one done in its place', async () => {+ await render(+ props({+ actionId: 'a7',+ brief: { generated: true, generating: false, blockedReason: null, onGenerate: vi.fn() },+ content: { ...props().content, draftId: 'd7' },+ }),+ );+ expect(front()).toEqual(['Open in Actions', 'Brief Generated', 'Open draft']);+ expect(container.querySelector('a')!.getAttribute('href')).toBe(+ '/dashboard/action-center/actions?action=a7',+ );+ await act(async () => button('Open draft').click());+ expect(handlers.openDraft).toHaveBeenCalledWith('d7');+ });++ it('waits for the draft lookup, and offers no Send to Editor where the editor has nothing to write', async () => {+ 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']);+ });++ it('offers to check again when the draft lookup failed, never Start', async () => {+ await render(+ props({ content: { ...props().content, lookupFailed: true, onRetry: handlers.retry } }),+ );+ expect(front()).toEqual([+ 'Send to Actions',+ 'Generate Brief',+ "Couldn't check for a draft · Retry",+ ]);+ await act(async () => button("Couldn't check for a draft · Retry").click());+ expect(handlers.retry).toHaveBeenCalled();+ expect(handlers.start).not.toHaveBeenCalled();+ });++ it('keeps the rest in the "…" menu', async () => {+ await render(props());+ const items = await openMenu();+ expect(items.map((i) => i.textContent?.trim())).toEqual([+ 'Send to Plan',+ 'Another angle',+ 'Send to Workflow',+ 'Copy All Data',+ 'Mark as reviewed',+ 'Dismiss',+ ]);+ // Another angle says what it does on hover.+ expect(items[1].getAttribute('title')).toBe(+ 'Suggest one more opportunity for the same need, with a different angle',+ );+ await act(async () => items[5].click());+ expect(handlers.dismiss).toHaveBeenCalled();+ });++ it('opens the Plan once the opportunity is a priority there', async () => {+ await render(+ props({ plan: { prioritized: true, onSend: handlers.plan, onOpen: handlers.openPlan } }),+ );+ const item = (await openMenu()).find((i) => i.textContent?.trim() === 'Open in Plan')!;+ await act(async () => item.click());+ expect(handlers.openPlan).toHaveBeenCalled();+ expect(handlers.plan).not.toHaveBeenCalled();+ });+});diff --git a/web/src/components/content/opportunity-actions.tsx b/web/src/components/content/opportunity-actions.tsxnew file mode 100644index 000000000..6d94e5832--- /dev/null+++ b/web/src/components/content/opportunity-actions.tsx@@ -0,0 +1,254 @@+'use client';++import { useTranslations } from 'next-intl';+import {+ Check,+ CheckCheck,+ Copy,+ ExternalLink,+ FilePen,+ FileText,+ ListChecks,+ ListPlus,+ Loader2,+ MoreHorizontal,+ RefreshCw,+ RotateCcw,+ Send,+ Sparkles,+ Target,+ X,+} from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';++/**+ * The opportunity panel's actions (the user's spec): three in front, in this+ * order: Send to Actions, Generate Brief, Send to Editor. Each turns into+ * its state in place once done (Open in Actions, Brief generated, Open+ * draft). The rest sit in the "…" menu on the right.+ */+export function OpportunityActions({+ actionId,+ sendToActions,+ brief,+ content,+ plan,+ alternative,+ workflow,+ onCopy,+ onReviewed,+ onRestore,+ onDismiss,+}: {+ /** The Action Center action it was sent to: Open in Actions takes Send's place. */+ actionId: string | null;+ /** Send to Actions, when the opportunity can still go there; `sending` while it does. */+ sendToActions: { sending: boolean; disabled: boolean; onSend: () => void } | null;+ brief: {+ generated: boolean;+ generating: boolean;+ /** Why it can't be generated now (the month's briefs are used up). */+ blockedReason: string | null;+ onGenerate: () => void;+ };+ /**+ * The Content Editor: the draft written for this opportunity (undefined+ * while looked up), or Start for one when `canStart` (earned work lives on+ * other sites; a closed opportunity has nothing to write). A lookup that+ * failed offers to check again instead of Start, so it never turns into a+ * second draft.+ */+ content: {+ draftId: string | null | undefined;+ lookupFailed?: boolean;+ onRetry?: () => void;+ canStart: boolean;+ onStart: () => void;+ onOpenDraft: (draftId: string) => void;+ };+ /** Its Plan row's priority mark (undefined while looked up); null when not offered. */+ plan: { prioritized: boolean | undefined; onSend: () => void; onOpen: () => void } | null;+ /** Another angle (CONTENT-006); null when it isn't offered. */+ alternative: { running: boolean; onOpen: () => void } | null;+ /** The CMS webhook; null when it isn't offered. */+ workflow: { sending: boolean; sentBefore: boolean; onSend: () => void } | null;+ onCopy: () => void;+ onReviewed?: () => void;+ onRestore?: () => void;+ onDismiss?: () => void;+}) {+ const t = useTranslations('content');+ const draftId = content.draftId;+ const showContent = !!draftId || content.canStart || !!content.lookupFailed;++ return (+ <div className="flex flex-wrap items-center gap-2">+ {actionId ? (+ <Link href={`/dashboard/action-center/actions?action=${actionId}`}>+ <Button variant="outline" size="sm" className="gap-2">+ <ExternalLink className="h-4 w-4" />+ {t('openInActions')}+ </Button>+ </Link>+ ) : (+ sendToActions && (+ <Button+ variant="outline"+ size="sm"+ onClick={sendToActions.onSend}+ disabled={sendToActions.disabled}+ className="gap-2"+ >+ {sendToActions.sending ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Target className="h-4 w-4" />+ )}+ {t('sendToActions')}+ </Button>+ )+ )}+ {brief.generated ? (+ <Button variant="outline" size="sm" disabled className="gap-2 disabled:opacity-100">+ <Check className="h-4 w-4" />+ {t('briefGenerated')}+ </Button>+ ) : (+ <Button+ variant="outline"+ size="sm"+ onClick={brief.onGenerate}+ disabled={brief.generating || brief.blockedReason !== null}+ title={brief.blockedReason ?? undefined}+ className="gap-2"+ >+ {brief.generating ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Sparkles className="h-4 w-4" />+ )}+ {brief.generating ? t('generatingBrief') : t('generateBrief')}+ </Button>+ )}+ {showContent &&+ (content.lookupFailed ? (+ <Button size="sm" variant="outline" className="gap-2" onClick={content.onRetry}>+ <RotateCcw className="h-4 w-4" />+ {t('draftCheckFailed')}+ </Button>+ ) : draftId ? (+ <Button size="sm" className="gap-2" onClick={() => content.onOpenDraft(draftId)}>+ <FileText className="h-4 w-4" />+ {t('openDraft')}+ </Button>+ ) : (+ <Button+ size="sm"+ className="gap-2"+ onClick={content.onStart}+ disabled={draftId === undefined}+ >+ {draftId === undefined ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <FilePen className="h-4 w-4" />+ )}+ {t('sendToEditor')}+ </Button>+ ))}++ <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"+ aria-label={t('moreActions')}+ >+ <MoreHorizontal className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ {plan && (+ <DropdownMenuItem+ className="gap-2"+ onClick={plan.prioritized ? plan.onOpen : plan.onSend}+ disabled={plan.prioritized === undefined}+ >+ {plan.prioritized === undefined ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : plan.prioritized ? (+ <ListChecks className="h-3.5 w-3.5" />+ ) : (+ <ListPlus className="h-3.5 w-3.5" />+ )}+ {plan.prioritized ? t('openInPlan') : t('sendToPlan')}+ </DropdownMenuItem>+ )}+ {alternative && (+ <DropdownMenuItem+ className="gap-2"+ onClick={alternative.onOpen}+ disabled={alternative.running}+ title={t('alternative.hint')}+ >+ {alternative.running ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RefreshCw className="h-3.5 w-3.5" />+ )}+ {alternative.running ? t('alternative.running') : t('alternative.button')}+ </DropdownMenuItem>+ )}+ {workflow && (+ <DropdownMenuItem+ className="gap-2"+ onClick={workflow.onSend}+ disabled={workflow.sending}+ >+ {workflow.sending ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Send className="h-3.5 w-3.5" />+ )}+ {workflow.sending+ ? t('sending')+ : workflow.sentBefore+ ? t('sendAgain')+ : t('sendToWorkflow')}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem className="gap-2" onClick={onCopy}>+ <Copy className="h-3.5 w-3.5" />+ {t('copyAllData')}+ </DropdownMenuItem>+ {onReviewed && (+ <DropdownMenuItem className="gap-2" onClick={onReviewed}>+ <CheckCheck className="h-3.5 w-3.5" />+ {t('markReviewed')}+ </DropdownMenuItem>+ )}+ {onRestore && (+ <DropdownMenuItem className="gap-2" onClick={onRestore}>+ <RotateCcw className="h-3.5 w-3.5" />+ {t('restore')}+ </DropdownMenuItem>+ )}+ {onDismiss && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem className="gap-2" variant="destructive" onClick={onDismiss}>+ <X className="h-3.5 w-3.5" />+ {t('dismiss')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/web/src/components/content/opportunity-basket.tsx b/web/src/components/content/opportunity-basket.tsxindex 5e1ef84ff..32d8c9718 100644--- a/web/src/components/content/opportunity-basket.tsx+++ b/web/src/components/content/opportunity-basket.tsx@@ -8,6 +8,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';+import { useAssetTypeLabel } from '@/hooks/use-asset-type-label';import {getOpportunityActions,getOpportunityBasket,@@ -248,6 +249,7 @@ export function AssetsCard({sendingKey?: string | null;}) {const t = useTranslations('content');+ const assetTypeLabel = useAssetTypeLabel();const assets = sourceData.assets ?? [];const actions = sourceData.actions ?? {};if (assets.length < 2) return null;@@ -269,9 +271,11 @@ export function AssetsCard({{t('detail.primaryAsset')}</Badge>)}- <Badge variant="outline" className="text-[10px]">- {t(`assetType.${a.type}`)}- </Badge>+ {assetTypeLabel(a.type) && (+ <Badge variant="outline" className="text-[10px]">+ {assetTypeLabel(a.type)}+ </Badge>+ )}<Badge variant="outline" className="text-[10px]">{t(`type.${a.channel}`)}</Badge>diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex bf05bbd8f..00cf4be00 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -7,7 +7,6 @@ import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import {ArrowLeft,- Send,Loader2,TrendingUp,Eye,@@ -15,22 +14,15 @@ import {Search,Tag,Clock,- X,Sparkles,FileText,Target,ListOrdered,Crown,- RotateCcw,- CheckCheck,- Check,- Copy,- ExternalLink,Info,- RefreshCw,} from 'lucide-react';import { cn } from '@/lib/utils';-import { Link } from '@/i18n/navigation';+import { Link, useRouter } from '@/i18n/navigation';import {getOpportunity,updateOpportunityStatus,@@ -57,6 +49,16 @@ import {TargetPagesCard,} from '@/components/content/opportunity-basket';import { opportunityToMarkdown } from '@/lib/content/opportunity-markdown';+import { canWriteOpportunity, opportunityStart } from '@/lib/content/opportunity-start';+import { contentEditorPath } from '@/lib/content/drafts';+import { siteTypeOf } from '@/lib/content/page-types';+import { getOpportunityDrafts } from '@/lib/actions/content-drafts';+import { getPlanPriorities, setPlanRowPriority } from '@/lib/actions/content-plan';+import { useUserRole } from '@/hooks/use-user-role';+import { useBrandStore } from '@/stores/use-brand-store';+import { OpportunityActions } from '@/components/content/opportunity-actions';+import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';+import { useAssetTypeLabel } from '@/hooks/use-asset-type-label';import { toast } from 'sonner';import { suggestedDate } from '@/lib/suggested-date';@@ -121,14 +123,21 @@ export function OpportunityDetail({id,inDrawer = false,onChanged,+ onPrioritized,}: {id: string;/** In the list's drawer: no back link, and the layout follows the drawer's width. */inDrawer?: boolean;/** Called after any change to the opportunity, so the list can refresh. */onChanged?: () => void;+ /**+ * Called once Send to Plan marked it as a priority: the list keeps its+ * rows' marks (they aren't read again on a refresh), so its menu agrees.+ */+ onPrioritized?: (id: string) => void;}) {const t = useTranslations('content');+ const assetTypeLabel = useAssetTypeLabel();const locale = useLocale();const [opportunity, setOpportunity] = useState<ContentOpportunity | null>(null);@@ -138,6 +147,67 @@ export function OpportunityDetail({const [brief, setBrief] = useState<ContentBrief | null>(null);const [quota, setQuota] = useState<BriefQuota | null>(null);const [fanoutQueries, setFanoutQueries] = useState<FanoutSubQuery[]>([]);+ const router = useRouter();+ // Start's page types are the opportunity's brand's, which may not be the+ // active one (/dashboard/content/[id] opens any of the org's brands).+ const opportunityBrand = useBrandStore((s) =>+ s.brands.find((b) => b.id === (opportunity?.brandId ?? s.activeBrandId)),+ );+ // Send to Editor: Start for this opportunity, over the panel.+ const [contentPreset, setContentPreset] = useState<DialogPreset | null>(null);+ // The draft being written for it, opened instead of starting another. A+ // failed read is not "no draft": it offers to check again.+ const [draft, setDraft] = useState<{+ opportunityId: string;+ id: string | null;+ failed: boolean;+ } | null>(null);+ const [draftAttempt, setDraftAttempt] = useState(0);+ const brandId = opportunity?.brandId;+ useEffect(() => {+ if (!brandId) return;+ let cancelled = false;+ getOpportunityDrafts(brandId, [id]).then(+ (drafts) =>+ !cancelled && setDraft({ opportunityId: id, id: drafts[id] ?? null, failed: false }),+ () => !cancelled && setDraft({ opportunityId: id, id: null, failed: true }),+ );+ return () => {+ cancelled = true;+ };+ }, [brandId, id, draftAttempt]);+ const retryDraft = () => {+ setDraft(null);+ setDraftAttempt((n) => n + 1);+ };+ // Send to Plan: whether its Plan row is a priority already (admins and+ // managers mark Plan rows).+ const { canManage } = useUserRole();+ const [priority, setPriority] = useState<{ opportunityId: string; on: boolean } | null>(null);+ useEffect(() => {+ if (!brandId || !canManage) return;+ let cancelled = false;+ getPlanPriorities(brandId, [id]).then(+ (ids) => !cancelled && setPriority({ opportunityId: id, on: ids.includes(id) }),+ () => !cancelled && setPriority({ opportunityId: id, on: false }),+ );+ return () => {+ cancelled = true;+ };+ }, [brandId, id, canManage]);+ const handleSendToPlan = async () => {+ if (!brandId) return;+ try {+ await setPlanRowPriority(brandId, `opportunity:${id}`, true);+ setPriority({ opportunityId: id, on: true });+ onPrioritized?.(id);+ toast.success(t('sentToPlan'), {+ action: { label: t('openPlan'), onClick: () => router.push('/dashboard/content/plan') },+ });+ } catch {+ toast.error(t('sendToPlanError'));+ }+ };useEffect(() => {setLoading(true);@@ -343,6 +413,8 @@ export function OpportunityDetail({}const sd = opportunity.sourceData;+ // What the opportunity makes: its primary asset's type.+ const primaryType = assetTypeLabel(sd.assets?.[0]?.type);const canSendToActionCenter = !['dismissed', 'archived', 'done'].includes(opportunity.status);const quotaLimited = quota !== null && quota.limit !== -1;const quotaExhausted = quotaLimited && quota.remaining <= 0;@@ -351,7 +423,9 @@ export function OpportunityDetail({const handleCopy = async () => {try {- await navigator.clipboard.writeText(opportunityToMarkdown(opportunity, brief, fanoutQueries));+ await navigator.clipboard.writeText(+ opportunityToMarkdown(opportunity, brief, fanoutQueries, assetTypeLabel),+ );toast.success(t('copiedToast'));} catch {toast.error(t('copyError'));@@ -401,6 +475,11 @@ export function OpportunityDetail({>{t(`type.${opportunity.type}` as 'type.owned' | 'type.earned')}</Badge>+ {primaryType && (+ <Badge variant="outline" className="text-xs">+ {primaryType}+ </Badge>+ )}<Badge variant="outline" className={cn('text-xs', IMPACT_COLORS[opportunity.impact])}>{t(`impact.${opportunity.impact}` as 'impact.high' | 'impact.medium' | 'impact.low')}</Badge>@@ -410,32 +489,9 @@ export function OpportunityDetail({<Badge variant="outline" className="text-xs tabular-nums">Score: {Math.round(opportunity.opportunityScore)}</Badge>- {/* Another angle is written from a cluster or a prompt; a task sent- from the Action Center (AC-004) has neither. */}- {opportunity.source !== 'action' && (- <Button- type="button"- variant="ghost"- size="xs"- className="ml-auto gap-1 text-xs text-muted-foreground"- onClick={() => setAlternativeOpen(true)}- disabled={alternativeRunning}- title={t('alternative.hint')}- >- {alternativeRunning ? (- <Loader2 className="h-3 w-3 animate-spin" />- ) : (- <RefreshCw className="h-3 w-3" />- )}- {alternativeRunning ? t('alternative.running') : t('alternative.button')}- </Button>- )}{/* The UI's language, not the browser's: an English page showed "25 Eyl". */}<span- className={cn(- 'text-xs text-muted-foreground flex items-center gap-1.5',- opportunity.source === 'action' && 'ml-auto',- )}+ className="ml-auto flex items-center gap-1.5 text-xs text-muted-foreground"title={suggestedDate(opportunity.createdAt, locale).full}><Clock className="h-3.5 w-3.5" />@@ -446,103 +502,62 @@ export function OpportunityDetail({})}</span></div>- <div className="flex flex-wrap items-center gap-2">- {brief ? (- <Button variant="outline" size="sm" disabled className="gap-2 disabled:opacity-100">- <Check className="h-4 w-4" />- {t('briefGenerated')}- </Button>- ) : (- <Button- size="sm"- onClick={handleGenerateBrief}- disabled={generatingBrief || quotaExhausted}- title={quotaExhausted ? t('briefLimitReached') : undefined}- className="gap-2"- >- {generatingBrief ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Sparkles className="h-4 w-4" />- )}- {generatingBrief ? t('generatingBrief') : t('generateBrief')}- </Button>- )}- {/* Every opportunity can go to the Action Center, cluster or single prompt. */}- {actionId ? (- <Link href={`/dashboard/action-center/actions?action=${actionId}`}>- <Button variant="outline" size="sm" className="gap-2">- <ExternalLink className="h-4 w-4" />- {t('openInActions')}- </Button>- </Link>- ) : (- canSendToActionCenter && (- <Button- variant="outline"- size="sm"- onClick={() => handleSendToActionCenter()}- disabled={sendingAction !== null}- className="gap-2"- >- {sendingAction === 'all' ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Target className="h-4 w-4" />- )}- {t('sendToActions')}- </Button>- )- )}- {canSendToWorkflow && (- <Button- variant="outline"- size="sm"- onClick={handleSend}- disabled={sending}- className="gap-2"- >- {sending ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Send className="h-4 w-4" />- )}- {sending- ? t('sending')- : opportunity.webhookSentAt- ? t('sendAgain')- : t('sendToWorkflow')}- </Button>- )}- <Button variant="outline" size="sm" onClick={handleCopy} className="gap-2">- <Copy className="h-4 w-4" />- {t('copyAllData')}- </Button>- {/* Status actions sit beside the others: the row has room for them. */}- {opportunity.status === 'new' && (- <Button variant="outline" size="sm" onClick={handleReviewed} className="gap-2">- <CheckCheck className="h-4 w-4" />- {t('markReviewed')}- </Button>- )}- {opportunity.status === 'archived' && (- <Button variant="outline" size="sm" onClick={handleRestore} className="gap-2">- <RotateCcw className="h-4 w-4" />- {t('restore')}- </Button>- )}- {opportunity.status === 'new' && (- <Button- variant="ghost"- size="sm"- onClick={() => setDismissOpen(true)}- className="gap-2 text-muted-foreground hover:text-destructive"- >- <X className="h-4 w-4" />- {t('dismiss')}- </Button>- )}- </div>+ <OpportunityActions+ actionId={actionId ?? null}+ sendToActions={+ canSendToActionCenter+ ? {+ sending: sendingAction === 'all',+ disabled: sendingAction !== null,+ onSend: () => void handleSendToActionCenter(),+ }+ : null+ }+ brief={{+ generated: !!brief,+ generating: generatingBrief,+ blockedReason: quotaExhausted ? t('briefLimitReached') : null,+ onGenerate: () => void handleGenerateBrief(),+ }}+ content={{+ draftId:+ draft?.opportunityId === opportunity.id && !draft.failed ? draft.id : undefined,+ lookupFailed: draft?.opportunityId === opportunity.id && draft.failed,+ onRetry: retryDraft,+ canStart: canWriteOpportunity(opportunity),+ onStart: () => setContentPreset(opportunityStart(opportunity)),+ onOpenDraft: (draftId) => router.push(contentEditorPath(draftId)),+ }}+ plan={+ canManage && canWriteOpportunity(opportunity)+ ? {+ prioritized: priority?.opportunityId === opportunity.id ? priority.on : undefined,+ onSend: () => void handleSendToPlan(),+ onOpen: () => router.push('/dashboard/content/plan'),+ }+ : null+ }+ // Another angle is written from a cluster or a prompt; a task sent+ // from the Action Center (AC-004) has neither.+ alternative={+ opportunity.source !== 'action'+ ? { running: alternativeRunning, onOpen: () => setAlternativeOpen(true) }+ : null+ }+ workflow={+ canSendToWorkflow+ ? {+ sending,+ sentBefore: !!opportunity.webhookSentAt,+ onSend: () => void handleSend(),+ }+ : null+ }+ onCopy={() => void handleCopy()}+ onReviewed={opportunity.status === 'new' ? () => void handleReviewed() : undefined}+ onRestore={opportunity.status === 'archived' ? () => void handleRestore() : undefined}+ onDismiss={opportunity.status === 'new' ? () => setDismissOpen(true) : undefined}+ /></div>{sd.reopened && ['new', 'reviewed'].includes(opportunity.status) && (@@ -851,6 +866,13 @@ export function OpportunityDetail({onOpenChange={setDismissOpen}onChoose={(reason) => void handleDismiss(reason)}/>+ <NewContentDialog+ open={contentPreset !== null}+ onOpenChange={(open) => !open && setContentPreset(null)}+ brandId={opportunity.brandId}+ siteType={siteTypeOf(opportunityBrand ?? {})}+ preset={contentPreset}+ /></div>);}diff --git a/web/src/components/content/opportunity-row-menu.test.tsx b/web/src/components/content/opportunity-row-menu.test.tsxnew file mode 100644index 000000000..29d201a97--- /dev/null+++ b/web/src/components/content/opportunity-row-menu.test.tsx@@ -0,0 +1,141 @@+import { act, type ComponentProps } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import { OpportunityRowMenu } from './opportunity-row-menu';++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children?: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;+const handlers = {+ start: vi.fn(),+ retry: vi.fn(),+ openDraft: vi.fn(),+ plan: vi.fn(),+ openPlan: vi.fn(),+ workflow: vi.fn(),+ dismiss: vi.fn(),+};++type Props = ComponentProps<typeof OpportunityRowMenu>;+const props = (over: Partial<Props> = {}): Props => ({+ title: 'Office coffee page',+ editor: {+ draftId: null,+ canStart: true,+ onStart: handlers.start,+ onOpenDraft: handlers.openDraft,+ },+ plan: { prioritized: false, onSend: handlers.plan, onOpen: handlers.openPlan },+ workflow: { sending: false, onSend: handlers.workflow },+ pageHref: '/dashboard/content/o1',+ onDismiss: handlers.dismiss,+ ...over,+});++async function open(p: Props) {+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <OpportunityRowMenu {...p} />+ </NextIntlClientProvider>,+ ),+ );+ const trigger = container.querySelector<HTMLButtonElement>(+ '[aria-label="Actions for Office coffee page"]',+ )!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+}+const labels = (items: HTMLElement[]) => items.map((i) => i.textContent?.trim());++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ Object.values(handlers).forEach((h) => h.mockReset());+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.body.replaceChildren();+});++describe('OpportunityRowMenu', () => {+ it("keeps a row's actions in one menu, with Send to Editor and Send to Plan", async () => {+ const items = await open(props());+ expect(labels(items)).toEqual([+ 'Send to Editor',+ 'Send to Plan',+ 'Send to Workflow',+ 'Open in new tab',+ 'Dismiss',+ ]);+ expect(items[3].getAttribute('href')).toBe('/dashboard/content/o1');+ expect(items[3].getAttribute('target')).toBe('_blank');+ await act(async () => items[0].click());+ expect(handlers.start).toHaveBeenCalled();+ });++ it('opens what is already there: the draft, and the Plan', async () => {+ const items = await open(+ props({+ editor: { ...props().editor, draftId: 'd7' },+ plan: { prioritized: true, onSend: handlers.plan, onOpen: handlers.openPlan },+ }),+ );+ expect(labels(items).slice(0, 2)).toEqual(['Open draft', 'Open in Plan']);+ await act(async () => items[0].click());+ expect(handlers.openDraft).toHaveBeenCalledWith('d7');+ });++ it('offers to check again when the draft lookup failed, never Start', async () => {+ const items = await open(+ props({ editor: { ...props().editor, lookupFailed: true, onRetry: handlers.retry } }),+ );+ expect(labels(items)[0]).toBe("Couldn't check for a draft · Retry");+ expect(labels(items)).not.toContain('Send to Editor');+ await act(async () => items[0].click());+ expect(handlers.retry).toHaveBeenCalled();+ expect(handlers.start).not.toHaveBeenCalled();+ });++ it('waits for its lookups, and leaves out what the row has no use for', async () => {+ let items = await open(+ props({+ editor: { ...props().editor, draftId: undefined },+ plan: { prioritized: undefined, onSend: handlers.plan, onOpen: handlers.openPlan },+ }),+ );+ expect(items.slice(0, 2).every((i) => i.hasAttribute('data-disabled'))).toBe(true);++ // Earned work, a member, a status past New.+ act(() => root.unmount());+ root = createRoot(container);+ document.querySelectorAll('[role="menu"]').forEach((m) => m.remove());+ items = await open(+ props({+ editor: { ...props().editor, canStart: false },+ plan: null,+ workflow: null,+ onDismiss: undefined,+ }),+ );+ expect(labels(items)).toEqual(['Open in new tab']);+ });+});diff --git a/web/src/components/content/opportunity-row-menu.tsx b/web/src/components/content/opportunity-row-menu.tsxnew file mode 100644index 000000000..662537435--- /dev/null+++ b/web/src/components/content/opportunity-row-menu.tsx@@ -0,0 +1,145 @@+'use client';++import { useTranslations } from 'next-intl';+import {+ ExternalLink,+ FilePen,+ FileText,+ ListChecks,+ ListPlus,+ Loader2,+ MoreHorizontal,+ RotateCcw,+ Send,+ X,+} from 'lucide-react';+import { Link } from '@/i18n/navigation';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';++/**+ * An Opportunities list row's actions, in one "…" menu as the panel keeps+ * its own (the user's spec): Send to Editor (Open draft once one is being+ * written), Send to Plan (Open in Plan once it is a priority there), Send+ * to Workflow, the full page in a new tab, and Dismiss.+ */+export function OpportunityRowMenu({+ title,+ editor,+ plan,+ workflow,+ pageHref,+ onDismiss,+}: {+ /** The opportunity's title, naming the menu for screen readers. */+ title: string;+ /**+ * The draft written for it (undefined while looked up), or Start for one+ * when `canStart`. A lookup that failed offers to check again instead of+ * Start, so it never turns into a second draft.+ */+ editor: {+ draftId: string | null | undefined;+ lookupFailed?: boolean;+ onRetry?: () => void;+ canStart: boolean;+ onStart: () => void;+ onOpenDraft: (draftId: string) => void;+ };+ /** Its Plan row's priority mark (undefined while looked up); null when not offered. */+ plan: { prioritized: boolean | undefined; onSend: () => void; onOpen: () => void } | null;+ /** The CMS webhook; null when not offered. */+ workflow: { sending: boolean; onSend: () => void } | null;+ pageHref: string;+ onDismiss?: () => void;+}) {+ const t = useTranslations('content');+ const draftId = editor.draftId;++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ className="inline-flex h-7 w-7 items-center justify-center rounded-md 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('rowActions', { title })}+ >+ <MoreHorizontal className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ {editor.lookupFailed ? (+ <DropdownMenuItem className="gap-2" onClick={editor.onRetry}>+ <RotateCcw className="h-3.5 w-3.5" />+ {t('draftCheckFailed')}+ </DropdownMenuItem>+ ) : draftId ? (+ <DropdownMenuItem className="gap-2" onClick={() => editor.onOpenDraft(draftId)}>+ <FileText className="h-3.5 w-3.5" />+ {t('openDraft')}+ </DropdownMenuItem>+ ) : (+ editor.canStart && (+ <DropdownMenuItem+ className="gap-2"+ onClick={editor.onStart}+ disabled={draftId === undefined}+ >+ {draftId === undefined ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <FilePen className="h-3.5 w-3.5" />+ )}+ {t('sendToEditor')}+ </DropdownMenuItem>+ )+ )}+ {plan && (+ <DropdownMenuItem+ className="gap-2"+ onClick={plan.prioritized ? plan.onOpen : plan.onSend}+ disabled={plan.prioritized === undefined}+ >+ {plan.prioritized === undefined ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : plan.prioritized ? (+ <ListChecks className="h-3.5 w-3.5" />+ ) : (+ <ListPlus className="h-3.5 w-3.5" />+ )}+ {plan.prioritized ? t('openInPlan') : t('sendToPlan')}+ </DropdownMenuItem>+ )}+ {workflow && (+ <DropdownMenuItem className="gap-2" onClick={workflow.onSend} disabled={workflow.sending}>+ {workflow.sending ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Send className="h-3.5 w-3.5" />+ )}+ {t('sendToWorkflow')}+ </DropdownMenuItem>+ )}+ {/* The full page, in a new tab so the list stays put. */}+ <DropdownMenuItem+ className="gap-2"+ render={<Link href={pageHref} target="_blank" rel="noopener noreferrer" />}+ >+ <ExternalLink className="h-3.5 w-3.5" />+ {t('openInNewTab')}+ </DropdownMenuItem>+ {onDismiss && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem className="gap-2" variant="destructive" onClick={onDismiss}>+ <X className="h-3.5 w-3.5" />+ {t('dismiss')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/web/src/hooks/use-asset-type-label.test.tsx b/web/src/hooks/use-asset-type-label.test.tsxnew file mode 100644index 000000000..b36f8b2b4--- /dev/null+++ b/web/src/hooks/use-asset-type-label.test.tsx@@ -0,0 +1,51 @@+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { describe, expect, it, vi } from 'vitest';+import messages from '../../messages/en.json';+import { useAssetTypeLabel } from './use-asset-type-label';++const brandState = vi.hoisted(() => ({+ activeBrandId: 'brand-1' as string | null,+ brands: [{ id: 'brand-1', siteType: 'ecommerce' as string | undefined, industry: 'Software' }],+}));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const TYPES = ['pillar_guide', 'product_page', 'alternatives', 'backlink', 'podcast'];++function Probe() {+ const label = useAssetTypeLabel();+ return <p>{TYPES.map((type) => label(type) ?? '—').join(' | ')}</p>;+}++function labels() {+ const container = document.createElement('div');+ const root = createRoot(container);+ act(() =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <Probe />+ </NextIntlClientProvider>,+ ),+ );+ const text = container.textContent;+ act(() => root.unmount());+ return text;+}++describe('useAssetTypeLabel', () => {+ it("names each type as the active brand's kind of site reads it", () => {+ expect(labels()).toBe('Buying guide | Product page | Alternatives page | Backlink | —');+ });++ it('reads older types for the site type the brand has, or its guess', () => {+ brandState.brands[0].siteType = undefined;+ // Software guesses B2B: an older product page is a feature page there.+ expect(labels()).toBe('How-to guide | Feature page | Alternatives page | Backlink | —');+ });+});diff --git a/web/src/hooks/use-asset-type-label.ts b/web/src/hooks/use-asset-type-label.tsnew file mode 100644index 000000000..cf01a1587--- /dev/null+++ b/web/src/hooks/use-asset-type-label.ts@@ -0,0 +1,23 @@+'use client';++import { useTranslations } from 'next-intl';+import { assetKind, isEarnedAssetType } from '@/lib/content/asset-types';+import { siteTypeOf } from '@/lib/content/page-types';+import { useBrandStore } from '@/stores/use-brand-store';++/**+ * A Content Opportunity asset's type as the person reads it on the active+ * brand's kind of site ("Feature page", "Backlink"), an older type read as+ * the page type it stands for there; null for a type it doesn't know.+ */+export function useAssetTypeLabel(): (type: string | null | undefined) => string | null {+ const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));+ const siteType = siteTypeOf(activeBrand ?? {});+ const t = useTranslations('content.assetType');+ const tTypes = useTranslations('contentEditor.pageTypes');+ return (type) => {+ const kind = assetKind(type, siteType);+ if (!kind) return null;+ return isEarnedAssetType(kind) ? t(kind) : tTypes(kind);+ };+}diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.tsindex 325400eb9..d474beec2 100644--- a/web/src/lib/actions/content-drafts-start.test.ts+++ b/web/src/lib/actions/content-drafts-start.test.ts@@ -83,6 +83,7 @@ vi.mock('@/lib/supabase/server', () => ({}));const {+ getOpportunityDrafts,createContentDraft,getContentOverlap,getContentStartOptions,@@ -114,8 +115,16 @@ describe('getContentStartOptions', () => {title: 'Create a CRM page for real estate',decision: 'create',brief: { suggestedTitle: ' CRM for real estate teams ' },+ assetType: 'solution_page',+ },+ // Written before opportunities had assets.+ {+ id: 'o2',+ title: 'Refresh the pricing page',+ decision: 'refresh',+ brief: null,+ assetType: null,},- { id: 'o2', title: 'Refresh the pricing page', decision: 'refresh', brief: null },],// Counted in the database: a big brand's topics past the listed prompts too.topics: [@@ -138,8 +147,15 @@ describe('getContentStartOptions', () => {title: 'Create a CRM page for real estate',decision: 'create',pageTitle: 'CRM for real estate teams',+ assetType: 'solution_page',+ },+ {+ id: 'o2',+ title: 'Refresh the pricing page',+ decision: 'refresh',+ pageTitle: null,+ assetType: null,},- { id: 'o2', title: 'Refresh the pricing page', decision: 'refresh', pageTitle: null },],prompts: [{ id: PROMPT, text: 'best crm for realtors', seen: false },@@ -203,6 +219,41 @@ describe('getContentStartOptions', () => {});});+describe('getOpportunityDrafts', () => {+ it('maps each opportunity to the latest draft not yet published started from it', async () => {+ reads = {+ content_drafts: [+ { id: 'd9', opportunity_id: OPPORTUNITY },+ { id: 'd3', opportunity_id: OPPORTUNITY },+ { id: 'd4', opportunity_id: 'o2' },+ ],+ };+ await expect(+ getOpportunityDrafts(BRAND, [OPPORTUNITY, OPPORTUNITY, 'not-an-id']),+ ).resolves.toEqual({+ [OPPORTUNITY]: 'd9',+ o2: 'd4',+ });+ expect(calls).toEqual([+ {+ table: 'content_drafts',+ op: 'select',+ filters: [+ ['eq', 'brand_id', BRAND],+ ['in', 'opportunity_id', [OPPORTUNITY]],+ ['in', 'status', ['draft', 'in_review', 'ready']],+ ],+ },+ ]);+ });++ it('reads nothing without an opportunity to look up', async () => {+ await expect(getOpportunityDrafts(BRAND, [])).resolves.toEqual({});+ await expect(getOpportunityDrafts('x', [OPPORTUNITY])).resolves.toEqual({});+ expect(calls).toEqual([]);+ });+});+describe('createContentDraft', () => {const start = (over: Partial<DraftStart> = {}): DraftStart => ({method: 'create',diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex d1b148ae1..81a62a249 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -294,7 +294,7 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStarconst [opportunities, prompts, topics] = await Promise.all([supabase.from('content_opportunities')- .select('id, title, decision, brief')+ .select('id, title, decision, brief, assetType:source_data->assets->0->>type').eq('brand_id', brandId).in('status', OPEN_OPPORTUNITY_STATUSES).order('opportunity_score', { ascending: false, nullsFirst: false })@@ -321,6 +321,7 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStartitle: o.title,decision: o.decision,pageTitle: typeof suggested === 'string' && suggested.trim() ? suggested.trim() : null,+ assetType: typeof o.assetType === 'string' ? o.assetType : null,};}),prompts: prompts.prompts,@@ -338,6 +339,40 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStar};}+/** How many opportunities one Open draft lookup covers: a page of the list. */+const MAX_DRAFT_LOOKUPS = 200;++/**+ * The draft being written for each opportunity (Generate Content's Open+ * draft): the latest one not yet published started from it, by opportunity+ * id. Opportunities with none, or that the member can't read, are left out.+ */+export async function getOpportunityDrafts(+ brandId: string,+ opportunityIds: string[],+): Promise<Record<string, string>> {+ const ids = [...new Set(opportunityIds)]+ .filter((id) => draftId.safeParse(id).success)+ .slice(0, MAX_DRAFT_LOOKUPS);+ if (!draftId.safeParse(brandId).success || !ids.length) return {};+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_drafts')+ .select('id, opportunity_id')+ .eq('brand_id', brandId)+ .in('opportunity_id', ids)+ .in('status', ['draft', 'in_review', 'ready'])+ .order('updated_at', { ascending: false });+ if (error) throw new Error(error.message);+ const drafts: Record<string, string> = {};+ for (const row of data ?? []) {+ if (row.opportunity_id && !(row.opportunity_id in drafts)) {+ drafts[row.opportunity_id] = row.id;+ }+ }+ return drafts;+}+const startInput = z.object({method: z.enum(['create', 'optimize']),// A prompt's text can run longer than a title: cut to fit, not refused.diff --git a/web/src/lib/actions/content-plan.test.ts b/web/src/lib/actions/content-plan.test.tsindex b4e6115e8..a3a43a623 100644--- a/web/src/lib/actions/content-plan.test.ts+++ b/web/src/lib/actions/content-plan.test.ts@@ -65,8 +65,14 @@ const getSuggestionSourceStates = vi.hoisted(() => vi.fn());vi.mock('@/lib/actions/integrations', () => ({ getSuggestionSourceStates }));const GA_CONNECTED = { configured: true, connected: true, mapped: true, lastDataAt: '2026-10-20' };-const { getContentPlan, getContentPlanInsights, hidePlanRow, setPlanRowPriority, showPlanRow } =- await import('./content-plan');+const {+ getContentPlan,+ getContentPlanInsights,+ getPlanPriorities,+ hidePlanRow,+ setPlanRowPriority,+ showPlanRow,+} = await import('./content-plan');beforeEach(() => {reads = {};@@ -114,6 +120,10 @@ describe('getContentPlan', () => {competitorsCited: ['Daily Grind Co.', '', 'Origin Box'],visibilityScore: 6,prompts: ['p1', 'p2'],+ assets: [+ { key: 'a1', type: 'pillar_guide' },+ { key: 'a2', type: 'backlink' },+ ],},},];@@ -160,6 +170,7 @@ describe('getContentPlan', () => {competitorsCited: ['Daily Grind Co.', 'Origin Box'],visibility: 6,prompts: 2,+ assetType: 'pillar_guide',},],drafts: [@@ -304,6 +315,26 @@ describe('the Plan’s row marks (00229)', () => {});});+describe('getPlanPriorities', () => {+ const O1 = '44444444-4444-4444-4444-444444444441';+ const O2 = '44444444-4444-4444-4444-444444444442';++ it('names the opportunities whose Plan rows are a priority', async () => {+ reads.content_plan_marks = [{ row_key: `opportunity:${O2}` }];+ await expect(getPlanPriorities(BRAND, [O1, O2, O1, 'not-an-id'])).resolves.toEqual([O2]);+ expect(filters).toEqual([+ ['content_plan_marks', 'eq', 'brand_id', BRAND],+ ['content_plan_marks', 'eq', 'priority', true],+ ['content_plan_marks', 'in', 'row_key', [`opportunity:${O1}`, `opportunity:${O2}`]],+ ]);+ });++ it('reads nothing without an opportunity to look up', async () => {+ await expect(getPlanPriorities(BRAND, ['x'])).resolves.toEqual([]);+ expect(filters).toEqual([]);+ });+});+describe('getContentPlanInsights', () => {it('reads what AI cites and what AI visits brought in', async () => {rpcResult = {diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.tsindex 0e2d334bd..f8ce79aa1 100644--- a/web/src/lib/actions/content-plan.ts+++ b/web/src/lib/actions/content-plan.ts@@ -163,6 +163,9 @@ export async function getContentPlan(: [],visibility: typeof sd.visibilityScore === 'number' ? sd.visibilityScore : null,prompts: Array.isArray(sd.prompts) ? sd.prompts.length : 0,+ assetType: Array.isArray(sd.assets)+ ? text((sd.assets as { type?: unknown }[])[0]?.type) || null+ : null,};},);@@ -245,6 +248,34 @@ export async function setPlanRowPriority(if (error) throw new Error(error.message);}+/** How many opportunities one priority lookup covers: a page of the list. */+const MAX_PRIORITY_LOOKUPS = 200;++/**+ * Which of these opportunities' Plan rows are marked as a priority, for the+ * Opportunities list's Send to Plan: their ids. Ids that aren't ids are left+ * out; an empty list when the member can't read the brand's marks.+ */+export async function getPlanPriorities(+ brandId: string,+ opportunityIds: string[],+): Promise<string[]> {+ const keys = [...new Set(opportunityIds)]+ .filter((id) => z.guid().safeParse(id).success)+ .slice(0, MAX_PRIORITY_LOOKUPS)+ .map((id) => `${OPPORTUNITY_KEY}${id}`);+ if (!z.guid().safeParse(brandId).success || !keys.length) return [];+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_plan_marks')+ .select('row_key')+ .eq('brand_id', brandId)+ .eq('priority', true)+ .in('row_key', keys);+ if (error) throw new Error(error.message);+ return (data ?? []).map((m) => m.row_key.slice(OPPORTUNITY_KEY.length));+}+/*** Hide a Plan row until someone shows it again (admins and managers). An* opportunity's row dismisses the opportunity too, so the Opportunities pagediff --git a/web/src/lib/content/asset-types.test.ts b/web/src/lib/content/asset-types.test.tsnew file mode 100644index 000000000..ca76cccb9--- /dev/null+++ b/web/src/lib/content/asset-types.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import { assetKind, opportunityPageType } from './asset-types';+import { SITE_PAGE_TYPES, SITE_TYPES } from './page-types';++describe('assetKind', () => {+ it('reads the older types as page types of each kind of site', () => {+ const older = [+ 'blog_post',+ 'pillar_guide',+ 'landing_page',+ 'comparison_page',+ 'glossary_page',+ 'faq_page',+ 'product_page',+ 'category_page',+ ];+ const read = Object.fromEntries(+ older.map((type) => [type, SITE_TYPES.map((site) => assetKind(type, site))]),+ );+ expect(read).toEqual({+ blog_post: ['blog_post', 'blog_post', 'blog_post'],+ pillar_guide: ['guide', 'buying_guide', 'guide'],+ landing_page: ['solution_page', 'collection_page', 'destination_page'],+ comparison_page: ['comparison', 'comparison', 'comparison'],+ glossary_page: ['definition', 'definition', 'definition'],+ faq_page: ['docs_faq', 'help_faq', 'help_faq'],+ product_page: ['feature_page', 'product_page', 'guide'],+ category_page: ['solution_page', 'category_page', 'guide'],+ });+ // Each one a type that site writes.+ for (const type of older) {+ for (const site of SITE_TYPES) {+ expect(SITE_PAGE_TYPES[site]).toContain(assetKind(type, site));+ }+ }+ });++ it('keeps page types and earned assets, and knows nothing else', () => {+ expect(assetKind('feature_page', 'b2b')).toBe('feature_page');+ expect(assetKind('alternatives', 'ecommerce')).toBe('alternatives');+ expect(assetKind('backlink', 'b2c')).toBe('backlink');+ expect(assetKind('third_party_article', 'b2b')).toBe('third_party_article');+ expect(assetKind('podcast', 'b2b')).toBeNull();+ expect(assetKind('constructor', 'b2b')).toBeNull();+ expect(assetKind(null, 'b2b')).toBeNull();+ expect(assetKind(undefined, 'b2b')).toBeNull();+ });+});++describe('opportunityPageType', () => {+ it("is the opportunity's type when the site writes it", () => {+ expect(opportunityPageType('comparison', 'b2b')).toBe('comparison');+ expect(opportunityPageType('faq_page', 'ecommerce')).toBe('help_faq');+ expect(opportunityPageType('product_page', 'b2b')).toBe('feature_page');+ });++ it('is null for earned work, a type the site no longer writes, or none', () => {+ expect(opportunityPageType('backlink', 'b2b')).toBeNull();+ // The older default: the page or its title tells more.+ expect(opportunityPageType('blog_post', 'b2b')).toBeNull();+ expect(opportunityPageType('pricing', 'ecommerce')).toBeNull();+ expect(opportunityPageType(null, 'b2c')).toBeNull();+ });+});diff --git a/web/src/lib/content/asset-types.ts b/web/src/lib/content/asset-types.tsnew file mode 100644index 000000000..84061c74b--- /dev/null+++ b/web/src/lib/content/asset-types.ts@@ -0,0 +1,64 @@+import { isPageType, type PageType } from './drafts';+import { SITE_PAGE_TYPES, type SiteType } from './page-types';++/**+ * What a Content Opportunity's assets are (#857). Opportunities follow the+ * brand's kind of site: an owned asset is one of the Content Editor's page+ * types for it (SITE_PAGE_TYPES), an earned one lives on another site.+ * Opportunities written before keep their old types, read here as the page+ * type they stand for on the brand's site; the rows aren't rewritten.+ */++export const EARNED_ASSET_TYPES = ['third_party_article', 'backlink'] as const;+export type EarnedAssetType = (typeof EARNED_ASSET_TYPES)[number];+export type AssetKind = PageType | EarnedAssetType;++export function isEarnedAssetType(value: string): value is EarnedAssetType {+ return (EARNED_ASSET_TYPES as readonly string[]).includes(value);+}++const ANY_SITE = (type: PageType): Record<SiteType, PageType> => ({+ b2b: type,+ ecommerce: type,+ b2c: type,+});++/** The types opportunities used before they followed the site, on each kind of site. */+const OLDER_TYPES: Record<string, Record<SiteType, PageType>> = {+ pillar_guide: { b2b: 'guide', ecommerce: 'buying_guide', b2c: 'guide' },+ landing_page: { b2b: 'solution_page', ecommerce: 'collection_page', b2c: 'destination_page' },+ comparison_page: ANY_SITE('comparison'),+ glossary_page: ANY_SITE('definition'),+ faq_page: { b2b: 'docs_faq', ecommerce: 'help_faq', b2c: 'help_faq' },+ // Also page types of a shop's, where they stay what they are.+ product_page: { b2b: 'feature_page', ecommerce: 'product_page', b2c: 'guide' },+ category_page: { b2b: 'solution_page', ecommerce: 'category_page', b2c: 'guide' },+};++/** An asset's type as the brand's site reads it; null when it isn't one. */+export function assetKind(type: string | null | undefined, siteType: SiteType): AssetKind | null {+ if (!type) return null;+ if (isEarnedAssetType(type)) return type;+ if (Object.hasOwn(OLDER_TYPES, type)) return OLDER_TYPES[type][siteType];+ return isPageType(type) ? type : null;+}++/**+ * The page type Start picks for an opportunity: its primary asset's, when+ * the brand's site writes that type; null otherwise (an earned asset, or a+ * type from before the site type changed). A blog post is what opportunities+ * were when nothing more specific fit, so it is null too: what the page or+ * its title shows comes first, and Start falls back to a blog post anyway.+ */+export function opportunityPageType(+ type: string | null | undefined,+ siteType: SiteType,+): PageType | null {+ const kind = assetKind(type, siteType);+ return kind &&+ kind !== 'blog_post' &&+ !isEarnedAssetType(kind) &&+ SITE_PAGE_TYPES[siteType].includes(kind)+ ? kind+ : null;+}diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex efe48778c..4ce0d4026 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -205,8 +205,15 @@ export interface DraftStartOptions {/*** pageTitle: the page title its brief suggests, once one is generated;* the opportunity's own title says what to do, not what to call the page.+ * assetType: its primary asset's type as stored (lib/content/asset-types.ts).*/- opportunities: { id: string; title: string; decision: string | null; pageTitle: string | null }[];+ opportunities: {+ id: string;+ title: string;+ decision: string | null;+ pageTitle: string | null;+ assetType: string | null;+ }[];/*** seen: the brand was named in or cited for it lately, so it needs no new* page (New content leaves it out; Add source keeps it). Not seen first.diff --git a/web/src/lib/content/opportunity-markdown.test.ts b/web/src/lib/content/opportunity-markdown.test.tsindex bd9033a1f..22c8bc198 100644--- a/web/src/lib/content/opportunity-markdown.test.ts+++ b/web/src/lib/content/opportunity-markdown.test.ts@@ -86,6 +86,13 @@ describe('opportunityToMarkdown', () => {expect(md).toContain('1. What flat feet need\n - Arch support\n - Stability\n2. The shoes');});+ it("names each asset's type as the page does", () => {+ const md = opportunityToMarkdown(base, brief, [], (type) =>+ type === 'comparison_page' ? 'Comparison' : null,+ );+ expect(md).toContain('- Flat feet shoe comparison (Comparison, Owned, Expand)');+ });+it('copies the opportunity and its source data before a brief exists', () => {const md = opportunityToMarkdown({ ...base, clusterId: null, decision: null, sourceData: { promptText: 'Best shoes?' } },diff --git a/web/src/lib/content/opportunity-markdown.ts b/web/src/lib/content/opportunity-markdown.tsindex a4fca7512..4012ee15e 100644--- a/web/src/lib/content/opportunity-markdown.ts+++ b/web/src/lib/content/opportunity-markdown.ts@@ -21,6 +21,8 @@ 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 sd = opportunity.sourceData;const parts: (string | null)[] = [];@@ -70,7 +72,7 @@ export function opportunityToMarkdown('Recommended assets',(sd.assets ?? []).map((a) =>- `- ${a.title} (${humanize(a.type)}, ${humanize(a.channel)}, ${humanize(a.decision)})`,+ `- ${a.title} (${assetTypeLabel(a.type) ?? humanize(a.type)}, ${humanize(a.channel)}, ${humanize(a.decision)})`,),),);diff --git a/web/src/lib/content/opportunity-start.test.ts b/web/src/lib/content/opportunity-start.test.tsnew file mode 100644index 000000000..bca74d9a1--- /dev/null+++ b/web/src/lib/content/opportunity-start.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';+import { canWriteOpportunity, opportunityStart } from './opportunity-start';++const page = {+ url: 'https://acme.example/guide',+ title: 'The guide',+ aiCitations: 3,+ gaSessions: 9,+ lastmod: null,+};++describe('opportunityStart', () => {+ it('starts a new page for a create decision, or with no page to work on', () => {+ expect(+ opportunityStart({ id: 'o1', decision: 'create', sourceData: { targetPages: [page] } }),+ ).toEqual({ kind: 'opportunity', id: 'o1', page: null });+ expect(opportunityStart({ id: 'o2', decision: 'optimize', sourceData: {} })).toMatchObject({+ page: null,+ });+ expect(+ opportunityStart({ id: 'o3', decision: null, sourceData: { targetPages: [page] } }),+ ).toMatchObject({ page: null });+ });++ it('starts on the page it works on for every other decision', () => {+ for (const decision of ['optimize', 'expand', 'refresh', 'consolidate', 'defend'] as const) {+ expect(+ opportunityStart({+ id: 'o1',+ decision,+ sourceData: { targetPages: [{ ...page, url: '' }, page] },+ }),+ ).toEqual({ kind: 'opportunity', id: 'o1', page: { url: page.url, title: 'The guide' } });+ }+ expect(+ opportunityStart({+ id: 'o1',+ decision: 'expand',+ sourceData: { targetPages: [{ ...page, title: null }] },+ }).page,+ ).toEqual({ url: page.url, title: null });+ });+});++describe('canWriteOpportunity', () => {+ it('is owned work still open', () => {+ expect(canWriteOpportunity({ type: 'owned', status: 'new' })).toBe(true);+ expect(canWriteOpportunity({ type: 'owned', status: 'in_progress' })).toBe(true);+ expect(canWriteOpportunity({ type: 'earned', status: 'new' })).toBe(false);+ expect(canWriteOpportunity({ type: 'owned', status: 'dismissed' })).toBe(false);+ expect(canWriteOpportunity({ type: 'owned', status: 'done' })).toBe(false);+ });+});diff --git a/web/src/lib/content/opportunity-start.ts b/web/src/lib/content/opportunity-start.tsnew file mode 100644index 000000000..2759cfbe8--- /dev/null+++ b/web/src/lib/content/opportunity-start.ts@@ -0,0 +1,33 @@+import type { ContentOpportunity } from '@/types';++/** Opportunities still open to write for, as New content lists them. */+const OPEN_STATUSES: readonly string[] = ['new', 'reviewed', 'sent', 'in_progress'];++/**+ * Whether Generate Content can start a page for this opportunity: owned+ * work (earned content lives on other sites) that is still open, so New+ * content lists it.+ */+export function canWriteOpportunity(+ opportunity: Pick<ContentOpportunity, 'type' | 'status'>,+): boolean {+ return opportunity.type === 'owned' && OPEN_STATUSES.includes(opportunity.status);+}++/**+ * Start for an opportunity (Generate Content), as the Content plan opens it:+ * a new page when it decided to create one or names no page, else the page+ * it works on (optimize, expand, refresh, consolidate or defend), the first+ * of its target pages.+ */+export function opportunityStart(+ opportunity: Pick<ContentOpportunity, 'id' | 'decision' | 'sourceData'>,+): { kind: 'opportunity'; id: string; page: { url: string; title: string | null } | null } {+ const target = (opportunity.sourceData?.targetPages ?? []).find((p) => p?.url);+ const create = !opportunity.decision || opportunity.decision === 'create' || !target;+ return {+ kind: 'opportunity',+ id: opportunity.id,+ page: create ? null : { url: target.url, title: target.title || null },+ };+}diff --git a/web/src/lib/content/plan.test.ts b/web/src/lib/content/plan.test.tsindex bb11d15ed..f19839a9c 100644--- a/web/src/lib/content/plan.test.ts+++ b/web/src/lib/content/plan.test.ts@@ -37,6 +37,7 @@ const opportunity = (id: string, over: Partial<PlanOpportunity> = {}): PlanOpporcompetitorsCited: [],visibility: null,prompts: 3,+ assetType: null,...over,});const plan = (@@ -77,6 +78,43 @@ describe('buildPlan', () => {expect(counts).toEqual({ create: 1, optimize: 0, protect: 0, priority: 0 });});+ it("types an opportunity's page as the opportunity does, when the site writes that type", () => {+ const { rows } = plan(+ [],+ [+ // An older type, read as this B2B site's page type.+ opportunity('o1', { pageTitle: 'Northwind vs HubSpot', assetType: 'faq_page', score: 90 }),+ opportunity('o2', { pageTitle: 'Northwind vs Pipedrive', assetType: 'alternatives' }),+ // A shop's type, and the older default: the title tells instead.+ opportunity('o3', {+ pageTitle: 'Northwind vs Close',+ assetType: 'sizing_guide',+ score: 50,+ }),+ opportunity('o4', { pageTitle: 'Northwind vs Zoho', assetType: 'blog_post', score: 40 }),+ ],+ );+ expect(rows.map((r) => r.pageType)).toEqual([+ 'docs_faq',+ 'alternatives',+ 'comparison',+ 'comparison',+ ]);+ });++ it('types an existing page by its own address first, then by its opportunity', () => {+ const optimize = (id: string, targetPage: string, assetType: string) =>+ opportunity(id, { decision: 'optimize', targetPage, targetTitle: 'Our page', assetType });+ const { rows } = plan(+ [],+ [optimize('o1', '/shipping', 'landing_page'), optimize('o2', '/crm-tips', 'comparison_page')],+ );+ expect(rows.map((r) => [r.page, r.pageType])).toEqual([+ ['/shipping', 'docs_faq'],+ ['/crm-tips', 'comparison'],+ ]);+ });+it('optimizes a page losing citations, by how much it lost, with the platforms citing it less', () => {const { rows } = plan([page('/features/forecasting', {diff --git a/web/src/lib/content/plan.ts b/web/src/lib/content/plan.tsindex a898231cd..7ee4d0aeb 100644--- a/web/src/lib/content/plan.ts+++ b/web/src/lib/content/plan.ts@@ -11,6 +11,7 @@* with fewer runs, or prompts added or removed, moves no page.*/+import { opportunityPageType } from './asset-types';import { detectPageType, type SiteType } from './page-types';import type { DraftMethod, PageType } from './drafts';import { pageKey } from './sources';@@ -64,6 +65,8 @@ export interface PlanOpportunity {competitorsCited: string[];visibility: number | null;prompts: number;+ /** Its primary asset's type as stored (asset-types.ts): the page type it names. */+ assetType: string | null;}/** A draft still being written, to open rather than start another. */@@ -193,7 +196,11 @@ export function buildPlan({action: create ? 'create' : PROTECT_DECISIONS.has(o.decision ?? '') ? 'protect' : 'optimize',title,page: create ? null : o.targetPage,- pageType: typeOf(title, create ? null : o.targetPage),+ // A new page is what the opportunity names; an existing one is what+ // its address or title shows, else what the opportunity names.+ pageType: create+ ? (opportunityPageType(o.assetType, siteType) ?? typeOf(title, null))+ : (typeOf(title, o.targetPage) ?? opportunityPageType(o.assetType, siteType)),// The period's own signal, when the page is losing ground, says more.why:page && dropdiff --git a/web/src/types/index.ts b/web/src/types/index.tsindex b803e9fc9..d19cc70f8 100644--- a/web/src/types/index.ts+++ b/web/src/types/index.ts@@ -277,17 +277,11 @@ export interface OpportunityPage {lastmod: string | null;}-export type OpportunityAssetType =- | 'blog_post'- | 'pillar_guide'- | 'landing_page'- | 'comparison_page'- | 'glossary_page'- | 'faq_page'- | 'product_page'- | 'category_page'- | 'third_party_article'- | 'backlink';+/**+ * A page type of the brand's kind of site, an earned asset, or a type from+ * before opportunities followed the site; lib/content/asset-types.ts reads it.+ */+export type OpportunityAssetType = string;export interface OpportunityAsset {key: string;