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): follow an opportunity through its Action Center work (#952)
Gökhan Geyik136e8587d6db
diff --git a/server/src/lib/action-center/from-opportunity.js b/server/src/lib/action-center/from-opportunity.jsindex 80143d855..d40c940c2 100644--- a/server/src/lib/action-center/from-opportunity.js+++ b/server/src/lib/action-center/from-opportunity.js@@ -94,7 +94,7 @@ export function initialTaskStatus(taskKey, opportunity) {/*** Creates the action, or returns the open one if this opportunity or asset- * was already sent. Records the action on the opportunity and marks it sent.+ * was already sent, and records the action on the opportunity.** @param {object} opportunity - the content_opportunities row* @param {{ assetKey?: string|null, userId: string }} opts@@ -195,8 +195,8 @@ export async function sendToActionCenter(opportunity, { assetKey = null, userIdconst { error: oppErr } = await supabaseAdmin.from('content_opportunities').update({+ // Status follows the action through a trigger (00106).source_data: { ...sd, actions: { ...(sd.actions || {}), [key]: action.id } },- ...(opportunity.status === 'new' ? { status: 'sent' } : {}),updated_at: new Date().toISOString(),}).eq('id', opportunity.id);diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex d5e435693..fee95cd91 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -414,7 +414,7 @@ router.post('/bulk/status', async (req, res) => {return res.status(400).json({ error: 'ids must be a non-empty array' });}- const validStatuses = ['new', 'sent', 'in_progress', 'done', 'dismissed'];+ const validStatuses = ['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed'];if (!validStatuses.includes(status)) {return res.status(400)@@ -622,7 +622,7 @@ router.patch('/:id/status', async (req, res) => {const { id } = req.params;const { status } = req.body;- const validStatuses = ['new', 'sent', 'in_progress', 'done', 'dismissed'];+ const validStatuses = ['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed'];if (!validStatuses.includes(status)) {return res.status(400)diff --git a/supabase/migrations/00106_opportunity_lifecycle.sql b/supabase/migrations/00106_opportunity_lifecycle.sqlnew file mode 100644index 000000000..196d11ac6--- /dev/null+++ b/supabase/migrations/00106_opportunity_lifecycle.sql@@ -0,0 +1,64 @@+-- An opportunity's status follows the Action Center work sent from it (#857,+-- Phase 4).+--+-- The lifecycle is New → Reviewed → Sent → In Progress → Done. Reviewed is+-- set by a person on the opportunity. The rest follow the actions sent from+-- it (#943), whatever changes them — the Action Center, MCP or anything+-- later — so this is a trigger rather than code in each of those paths:+--+-- every action dismissed → reviewed (the work was called off)+-- every live action completed → done+-- any action started or completed → in_progress+-- otherwise (all still new) → sent+--+-- Only an opportunity somewhere on that path is moved. One a person has+-- dismissed or that was archived stays where it is.++create or replace function public.sync_opportunity_status()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ opp uuid := nullif(new.payload->>'opportunityId', '')::uuid;+ next_status text;+begin+ if opp is null then+ return new;+ end if;++ select case+ when count(*) filter (where a.status <> 'dismissed') = 0 then 'reviewed'+ when count(*) filter (where a.status not in ('completed', 'dismissed')) = 0 then 'done'+ when count(*) filter (where a.status in ('in_progress', 'on_hold', 'completed')) > 0+ then 'in_progress'+ else 'sent'+ end+ into next_status+ from actions a+ where a.kind = 'content_opportunity'+ and a.brand_id = new.brand_id+ and a.payload->>'opportunityId' = opp::text;++ update content_opportunities+ set status = next_status, updated_at = now()+ where id = opp+ and brand_id = new.brand_id+ and status in ('new', 'reviewed', 'sent', 'in_progress', 'done')+ and status <> next_status;++ return new;+end;+$$;++revoke all on function public.sync_opportunity_status() from public, anon, authenticated;++create trigger actions_sync_opportunity_status+ after insert or update of status on public.actions+ for each row+ when (new.kind = 'content_opportunity')+ execute function public.sync_opportunity_status();++-- Bring opportunities already sent into line.+update public.actions set status = status where kind = 'content_opportunity';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 7627a6aaf..3ec789d53 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -12242,6 +12242,74 @@ alter table public.content_opportunitiesadd column decision textcheck (decision in ('create', 'optimize', 'expand', 'refresh', 'consolidate', 'defend'));+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00106_opportunity_lifecycle.sql+-- ─────────────────────────────────────────────────────────────────────────+-- An opportunity's status follows the Action Center work sent from it (#857,+-- Phase 4).+--+-- The lifecycle is New → Reviewed → Sent → In Progress → Done. Reviewed is+-- set by a person on the opportunity. The rest follow the actions sent from+-- it (#943), whatever changes them — the Action Center, MCP or anything+-- later — so this is a trigger rather than code in each of those paths:+--+-- every action dismissed → reviewed (the work was called off)+-- every live action completed → done+-- any action started or completed → in_progress+-- otherwise (all still new) → sent+--+-- Only an opportunity somewhere on that path is moved. One a person has+-- dismissed or that was archived stays where it is.++create or replace function public.sync_opportunity_status()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ opp uuid := nullif(new.payload->>'opportunityId', '')::uuid;+ next_status text;+begin+ if opp is null then+ return new;+ end if;++ select case+ when count(*) filter (where a.status <> 'dismissed') = 0 then 'reviewed'+ when count(*) filter (where a.status not in ('completed', 'dismissed')) = 0 then 'done'+ when count(*) filter (where a.status in ('in_progress', 'on_hold', 'completed')) > 0+ then 'in_progress'+ else 'sent'+ end+ into next_status+ from actions a+ where a.kind = 'content_opportunity'+ and a.brand_id = new.brand_id+ and a.payload->>'opportunityId' = opp::text;++ update content_opportunities+ set status = next_status, updated_at = now()+ where id = opp+ and brand_id = new.brand_id+ and status in ('new', 'reviewed', 'sent', 'in_progress', 'done')+ and status <> next_status;++ return new;+end;+$$;++revoke all on function public.sync_opportunity_status() from public, anon, authenticated;++create trigger actions_sync_opportunity_status+ after insert or update of status on public.actions+ for each row+ when (new.kind = 'content_opportunity')+ execute function public.sync_opportunity_status();++-- Bring opportunities already sent into line.+update public.actions set status = status where kind = 'content_opportunity';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00107_citations_domains_fast.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 9850fc03f..7b6d9b040 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1654,7 +1654,8 @@"in_progress": "In Progress","done": "Done","dismissed": "Dismissed",- "archived": "Archived"+ "archived": "Archived",+ "reviewed": "Reviewed"},"impact": {"high": "High",@@ -1734,7 +1735,10 @@"targetTitle": "Your Site","targetStats": "{citations, plural, one {# AI citation} other {# AI citations}} · {sessions, plural, one {# session} other {# sessions}} in the last 30 days","assetsTitle": "Recommended Assets",- "primaryAsset": "Primary"+ "primaryAsset": "Primary",+ "resultsTitle": "Results",+ "resultsPending": "Completed. Measured from {date}, once a full window has passed.",+ "resultsUnavailable": "The actions sent from this opportunity are no longer available."},"webhook": {"title": "Webhook Settings",@@ -1813,7 +1817,9 @@"openInActionCenter": "Open in Action Center","sentToActionCenter": "Sent to the Action Center","alreadyInActionCenter": "Already in the Action Center",- "sendToActionCenterError": "Failed to send to the Action Center"+ "sendToActionCenterError": "Failed to send to the Action Center",+ "markReviewed": "Mark as reviewed",+ "reviewedError": "Failed to mark as reviewed"},"traffic": {"title": "AI Traffic Analytics",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsxindex 07092beb8..0690fc547 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx@@ -23,6 +23,7 @@ import {ListOrdered,Crown,RotateCcw,+ CheckCheck,} from 'lucide-react';import { cn } from '@/lib/utils';import { Link } from '@/i18n/navigation';@@ -39,6 +40,7 @@ import type { ContentBrief, ContentOpportunity } from '@/types';import { getPromptFanout, type FanoutSubQuery } from '@/lib/actions/fanout';import {AssetsCard,+ OpportunityResultsCard,OpportunityBasketCard,ScoreBreakdown,TargetPagesCard,@@ -53,6 +55,7 @@ const IMPACT_COLORS: Record<string, string> = {const STATUS_COLORS: Record<string, string> = {new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',+ reviewed: 'border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400',sent: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',@@ -150,6 +153,15 @@ export default function ContentDetailPage() {}};+ const handleReviewed = async () => {+ try {+ await updateOpportunityStatus(id, 'reviewed');+ setOpportunity(await getOpportunity(id));+ } catch {+ toast.error(t('reviewedError'));+ }+ };+const handleDismiss = async () => {try {await updateOpportunityStatus(id, 'dismissed');@@ -291,6 +303,12 @@ export default function ContentDetailPage() {{t('restore')}</Button>)}+ {opportunity.status === 'new' && (+ <Button variant="outline" size="sm" onClick={handleReviewed} className="gap-2">+ <CheckCheck className="h-4 w-4" />+ {t('markReviewed')}+ </Button>+ )}{opportunity.status === 'new' && (<><Button@@ -351,7 +369,12 @@ export default function ContentDetailPage() {/><OpportunityBasketCard opportunityId={opportunity.id} /></div>- <ScoreBreakdown sourceData={sd} />+ <div className="space-y-4">+ {sd.actions && Object.keys(sd.actions).length > 0 && (+ <OpportunityResultsCard actionIds={Object.values(sd.actions)} />+ )}+ <ScoreBreakdown sourceData={sd} />+ </div></div>)}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 96cf90c13..bdb3c3f71 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -124,6 +124,7 @@ const IMPACT_COLORS: Record<string, string> = {const STATUS_COLORS: Record<string, string> = {new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',+ reviewed: 'border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400',sent: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',@@ -733,6 +734,7 @@ export default function ContentPage() {<SelectContent><SelectItem value="all">{t('filters.allStatuses')}</SelectItem><SelectItem value="new">{t('status.new')}</SelectItem>+ <SelectItem value="reviewed">{t('status.reviewed')}</SelectItem><SelectItem value="sent">{t('status.sent')}</SelectItem><SelectItem value="in_progress">{t('status.in_progress')}</SelectItem><SelectItem value="done">{t('status.done')}</SelectItem>diff --git a/web/src/components/content/opportunity-basket.tsx b/web/src/components/content/opportunity-basket.tsxindex cee8b74a0..a338d9a2e 100644--- a/web/src/components/content/opportunity-basket.tsx+++ b/web/src/components/content/opportunity-basket.tsx@@ -2,13 +2,17 @@import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';-import { Boxes, ExternalLink, FileText, Layers, Loader2, Search } from 'lucide-react';+import { Boxes, ExternalLink, FileText, Gauge, Layers, Loader2, Search } from 'lucide-react';import { Link } from '@/i18n/navigation';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 { getOpportunityBasket } from '@/lib/actions/content';+import {+ getOpportunityActions,+ getOpportunityBasket,+ type OpportunityActionResult,+} from '@/lib/actions/content';import type {ContentOpportunityDecision,ContentOpportunitySourceData,@@ -321,3 +325,91 @@ export function AssetsCard({</Card>);}++/** Days after an action closes before its "after" window can be read (validate.js). */+const MEASURE_AFTER_DAYS = 31;++const formatMetric = (value: number | null, unit: string) =>+ value === null ? '—' : unit === 'percent' ? `${Math.round(value * 10) / 10}%` : String(value);++/**+ * Where the work sent from this opportunity stands, and what it moved once+ * measured (#857, Phase 4). The measurement is the Action Center's own.+ */+export function OpportunityResultsCard({ actionIds }: { actionIds: string[] }) {+ const t = useTranslations('content.detail');+ const tStatus = useTranslations('actionCenter.actionsPage.status');+ const tOutcome = useTranslations('actionCenter.actionOutcome');+ const tKpi = useTranslations('actionCenter.registry');+ const [actions, setActions] = useState<OpportunityActionResult[] | null>(null);+ const key = actionIds.join(',');++ useEffect(() => {+ let cancelled = false;+ getOpportunityActions(key.split(','))+ .then((rows) => !cancelled && setActions(rows))+ .catch(() => !cancelled && setActions([]));+ return () => {+ cancelled = true;+ };+ }, [key]);++ return (+ <Card>+ <CardHeader className="pb-2">+ <div className="flex items-center gap-2">+ <Gauge className="h-4 w-4 text-primary" />+ <CardTitle className="text-sm font-medium">{t('resultsTitle')}</CardTitle>+ </div>+ </CardHeader>+ <CardContent className="space-y-3">+ {!actions ? (+ <Skeleton className="h-16 w-full" />+ ) : actions.length === 0 ? (+ <p className="text-xs text-muted-foreground">{t('resultsUnavailable')}</p>+ ) : (+ actions.map((a) => {+ const measureFrom =+ a.completedAt &&+ new Date(Date.parse(a.completedAt) + MEASURE_AFTER_DAYS * 86_400_000);+ return (+ <div key={a.id} className="space-y-1.5 rounded-md border p-2.5">+ <div className="flex items-center justify-between gap-2">+ <Link+ href={`/dashboard/action-center/actions?action=${a.id}`}+ className="text-xs font-medium hover:underline"+ >+ AC-{a.actionNo}+ </Link>+ <Badge variant="outline" className="text-[10px]">+ {tStatus(a.status)}+ </Badge>+ </div>+ {a.title && <p className="text-xs text-muted-foreground line-clamp-2">{a.title}</p>}+ {a.status === 'completed' && a.outcome === 'pending_measurement' && measureFrom ? (+ <p className="text-xs text-muted-foreground">+ {t('resultsPending', { date: measureFrom.toLocaleDateString() })}+ </p>+ ) : a.status === 'completed' ? (+ <div className="space-y-1">+ <Badge variant="secondary" className="text-[10px]">+ {tOutcome(a.outcome)}+ </Badge>+ {a.metrics.map((m) => (+ <div key={m.metric} className="flex justify-between text-xs">+ <span className="text-muted-foreground">{tKpi(`${m.metric}.name`)}</span>+ <span className="tabular-nums">+ {formatMetric(m.before, m.unit)} → {formatMetric(m.after, m.unit)}+ </span>+ </div>+ ))}+ </div>+ ) : null}+ </div>+ );+ })+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex 82004ca45..7f5e85211 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -176,6 +176,48 @@ export async function sendOpportunityToActionCenter(return res.json();}+export interface OpportunityActionResult {+ id: string;+ actionNo: number;+ title: string | null;+ status: string;+ outcome: string;+ completedAt: string | null;+ validatedAt: string | null;+ metrics: { metric: string; unit: string; before: number | null; after: number | null }[];+}++/**+ * The Action Center actions sent from an opportunity, with what they measured.+ * Read with the user's session, so RLS keeps it to their organization.+ */+export async function getOpportunityActions(ids: string[]): Promise<OpportunityActionResult[]> {+ if (!ids.length) return [];+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('actions')+ .select('id, action_no, status, outcome, completed_at, validated_at, validation, payload')+ .in('id', ids)+ .order('created_at');+ if (error) throw new Error(error.message);+ return (data ?? []).map((row) => {+ const payload = (row.payload ?? {}) as { title?: string };+ const validation = (row.validation ?? null) as {+ metrics?: OpportunityActionResult['metrics'];+ } | null;+ return {+ id: row.id,+ actionNo: Number(row.action_no),+ title: payload.title ?? null,+ status: row.status,+ outcome: row.outcome,+ completedAt: row.completed_at,+ validatedAt: row.validated_at,+ metrics: validation?.metrics ?? [],+ };+ });+}+export interface OpportunityTopic {topicId: string;name: string;diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex 570d5d4fb..9847aa4b7 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -607,7 +607,7 @@ export interface ContentOpportunityRow {export interface ListContentOpportunitiesParams {brandId: string;- status?: 'new' | 'sent' | 'in_progress' | 'done' | 'dismissed' | 'archived';+ status?: 'new' | 'reviewed' | 'sent' | 'in_progress' | 'done' | 'dismissed' | 'archived';impact?: 'high' | 'medium' | 'low';type?: 'owned' | 'earned';limit?: number;@@ -1064,6 +1064,7 @@ export async function getContentOpportunityFor(export const CONTENT_OPPORTUNITY_STATUSES = ['new',+ 'reviewed','sent','in_progress','done',diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex ccc7766f3..810c975a0 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -267,7 +267,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),status: z- .enum(['new', 'sent', 'in_progress', 'done', 'dismissed', 'archived'])+ .enum(['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed', 'archived']).optional().describe('Filter by progress status of the opportunity. Archived ones (an older per-prompt backlog) are left out unless asked for.',diff --git a/web/src/types/index.ts b/web/src/types/index.tsindex 497a236f3..09b8b7206 100644--- a/web/src/types/index.ts+++ b/web/src/types/index.ts@@ -176,6 +176,7 @@ export interface PromptVolume {export type ContentOpportunityStatus =| 'new'+ | 'reviewed'| 'sent'| 'in_progress'| 'done'