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(insights): send opportunities to the Action Center and suggest content (#1047)
Cihanfda6d5eb842f
diff --git a/server/src/lib/action-center/basket-metrics.js b/server/src/lib/action-center/basket-metrics.jsindex d12e01917..1f5279c0e 100644--- a/server/src/lib/action-center/basket-metrics.js+++ b/server/src/lib/action-center/basket-metrics.js@@ -76,7 +76,9 @@ export function basketValues(raw, { pageCount }) {/*** The prompts and pages an action covers. Actions sent before the payload* carried prompt ids take them from the opportunity's clusters as they are- * now, or, without clusters, from the one prompt it was written for.+ * now, or, without clusters, from the one prompt it was written for. A topic+ * sent before any of its prompts was tracked (VIS-011) takes the prompts it+ * has now: the ones tracked from its suggestions.*/export async function basketScope(action) {const payload = action.payload || {};@@ -98,6 +100,15 @@ export async function basketScope(action) {}if (!promptIds.length && opp?.prompt_id) promptIds = [opp.prompt_id];}+ if (!promptIds.length && payload.topicId) {+ const { data: prompts, error } = await supabaseAdmin+ .from('prompts')+ .select('id, prompt_sets!inner(brand_id)')+ .eq('topic_id', payload.topicId)+ .eq('prompt_sets.brand_id', action.brand_id);+ if (error) throw new Error(error.message);+ promptIds = (prompts || []).map((p) => p.id);+ }return { promptIds, pages: Array.isArray(payload.pages) ? payload.pages : [] };}diff --git a/server/src/lib/action-center/basket-metrics.test.js b/server/src/lib/action-center/basket-metrics.test.jsindex 7cb9b195e..c180bfb38 100644--- a/server/src/lib/action-center/basket-metrics.test.js+++ b/server/src/lib/action-center/basket-metrics.test.js@@ -14,6 +14,7 @@ function chain(result) {eq: () => b,in: () => Promise.resolve(result),maybeSingle: () => Promise.resolve(result),+ then: (resolve) => resolve(result),};return b;}@@ -100,4 +101,16 @@ describe('basketScope', () => {chain({ data: { cluster_id: null, related_cluster_ids: [], prompt_id: 'p9' } });expect((await basketScope({ payload: { opportunityId: 'o1' } })).promptIds).toEqual(['p9']);});++ it('takes the prompts a topic has now when none were tracked when it was sent', async () => {+ tables.prompts = () => chain({ data: [{ id: 'p3' }, { id: 'p4' }], error: null });+ expect(+ (await basketScope({ brand_id: 'b1', payload: { topicId: 't1', promptIds: [] } })).promptIds,+ ).toEqual(['p3', 'p4']);+ // Prompt ids it was sent with are kept, so the basket doesn't move.+ expect(+ (await basketScope({ brand_id: 'b1', payload: { topicId: 't1', promptIds: ['p1'] } }))+ .promptIds,+ ).toEqual(['p1']);+ });});diff --git a/server/src/lib/action-center/from-topic-opportunity.js b/server/src/lib/action-center/from-topic-opportunity.jsnew file mode 100644index 000000000..8bf930922--- /dev/null+++ b/server/src/lib/action-center/from-topic-opportunity.js@@ -0,0 +1,177 @@+/**+ * "Send action" on an Insights Opportunities topic (VIS-011): a topic's+ * suggested prompts, with their demand, sent as a Growth action.+ *+ * The person picks the topic and its suggestions; which suggestions count is+ * read again here (the brand's, in this topic, relevant, and still open or+ * tracked from the card, not dismissed), so the+ * action states the demand as Ansvisor has it, not as a client says it is.+ * The work follows a library plan chosen by how far the brand already is in+ * the topic: G16 (create_content_for_topics) when none of its prompts track+ * the topic yet, G05 (expand_topic_visibility) when some do. It is measured+ * afterwards on the topic's prompts (basket-metrics.js).+ */++import supabaseAdmin from '../../config/supabase.js';+import { RELEVANCE_THRESHOLD } from '../suggestion-relevance.js';+import expandTopicVisibility from './definitions/g05-expand-topic-visibility.js';+import createContentForTopics from './definitions/g16-create-content-for-topics.js';+import { resolveBrandSources } from './sources.js';+import { planTasks } from './tasks/plan.js';++export const TOPIC_OPPORTUNITY_ACTION_KIND = 'topic_opportunity';++const ACTIVE = ['new', 'in_progress', 'on_hold'];+const KPI_KEYS = ['ai_visibility', 'share_of_voice'];++function httpError(message, status) {+ const err = new Error(message);+ err.status = status;+ return err;+}++/** G16 for a topic none of the brand's prompts track yet, G05 once some do. */+export function topicOpportunityPlan(trackedPrompts) {+ return trackedPrompts > 0 ? expandTopicVisibility : createContentForTopics;+}++/** How much the demand matters: 50k+ AI searches a month is high, 10k+ medium. */+export function topicOpportunityImpact(volume) {+ if (volume >= 50_000) return 'high';+ if (volume >= 10_000) return 'medium';+ return 'low';+}++/**+ * Creates the Growth action, or returns the open one if this topic was+ * already sent: one opportunity action per topic at a time.+ *+ * @param {{ id: string, name: string, brand_id: string }} topic - checked against the caller's org+ * @param {{ suggestionIds: string[], userId: string }} opts - the item's suggestions+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}+ */+export async function sendTopicOpportunityToActionCenter(topic, { suggestionIds, userId }) {+ const brandId = topic.brand_id;++ const dedupKey = `topic_opportunity:${topic.id}`;+ const openAction = async () => {+ const { data } = await supabaseAdmin+ .from('actions')+ .select('id, action_no')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .in('status', ACTIVE)+ .maybeSingle();+ return data;+ };+ const open = await openAction();+ if (open) return { actionId: open.id, actionNo: Number(open.action_no), created: false };++ // The card's rule, kept here too: in this topic and relevant. Tracked+ // ('added') counts: Track takes the topic off the card, and its toast+ // offers Send action for what it just tracked.+ const { data: rows, error: rowsErr } = await supabaseAdmin+ .from('prompt_suggestions')+ .select('id, suggested_text, est_volume, relevance')+ .in('id', suggestionIds)+ .eq('brand_id', brandId)+ .eq('topic_id', topic.id)+ .in('status', ['new', 'added']);+ if (rowsErr) throw new Error(rowsErr.message);+ const suggestions = (rows || [])+ .filter((r) => r.relevance !== null && Number(r.relevance) >= RELEVANCE_THRESHOLD)+ .sort((a, b) => Number(b.est_volume ?? 0) - Number(a.est_volume ?? 0));+ if (!suggestions.length) throw httpError('No open suggestions for this topic', 409);+ const demand = suggestions.reduce((sum, s) => sum + Number(s.est_volume ?? 0), 0);++ // The topic's tracked prompts, fixed at send time like a topic gap's; a+ // topic with none is measured on the prompts it has later (basket-metrics.js).+ const { data: prompts, error: promptsErr } = await supabaseAdmin+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .eq('topic_id', topic.id)+ .eq('is_active', true)+ .eq('prompt_sets.brand_id', brandId);+ if (promptsErr) throw new Error(promptsErr.message);+ const tracked = prompts || [];+ const definition = topicOpportunityPlan(tracked.length);++ const payload = {+ source: TOPIC_OPPORTUNITY_ACTION_KIND,+ topicId: topic.id,+ topicName: topic.name,+ plan: definition.code,+ demand,+ suggestions: suggestions.map((s) => ({+ id: s.id,+ text: s.suggested_text,+ volume: Number(s.est_volume ?? 0),+ })),+ trackedPrompts: tracked.length,+ promptIds: tracked.map((p) => p.id),+ targetEntity: 'prompts',+ targetCount: suggestions.length,+ targets: suggestions.slice(0, 50).map((s) => s.suggested_text),+ };++ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: brandId,+ category: 'growth',+ kind: TOPIC_OPPORTUNITY_ACTION_KIND,+ definition_version: 1,+ impact: topicOpportunityImpact(demand),+ payload,+ kpi_keys: KPI_KEYS,+ baseline: { demand, trackedPrompts: tracked.length },+ dedup_key: dedupKey,+ })+ .select('id, action_no')+ .single();+ if (error) {+ // Two sends at once: the other one opened it (the open-action dedup index, 00084).+ if (error.code === '23505') {+ const winner = await openAction();+ if (winner) {+ return { actionId: winner.id, actionNo: Number(winner.action_no), created: false };+ }+ }+ throw new Error(error.message);+ }++ const sources = await resolveBrandSources(brandId);+ const plan = planTasks(+ { id: TOPIC_OPPORTUNITY_ACTION_KIND, tasks: definition.tasks },+ { sources, payload },+ );+ const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(+ plan.map((item) => ({+ action_id: action.id,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,+ status: 'todo',+ })),+ );+ if (tasksErr) throw new Error(tasksErr.message);++ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: userId,+ data: {+ source: TOPIC_OPPORTUNITY_ACTION_KIND,+ topicId: topic.id,+ plan: definition.code,+ demand,+ taskCount: plan.length,+ },+ });++ return { actionId: action.id, actionNo: Number(action.action_no), created: true };+}diff --git a/server/src/lib/action-center/from-topic-opportunity.test.js b/server/src/lib/action-center/from-topic-opportunity.test.jsnew file mode 100644index 000000000..09489b4b2--- /dev/null+++ b/server/src/lib/action-center/from-topic-opportunity.test.js@@ -0,0 +1,201 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * sendTopicOpportunityToActionCenter (VIS-011): an Opportunities topic as a+ * Growth action. These pin that the suggestions are read again on the+ * server, that the plan follows how far the brand is in the topic (G16 / G05),+ * that a topic already sent returns the open action, and that the action+ * carries a person's "created" event.+ */++let db;++function table(name) {+ const state = { name, filters: {}, op: 'select', row: null };+ const result = () => {+ if (state.op === 'insert') {+ db.inserts.push({ table: name, row: state.row });+ if (name === 'actions') {+ return db.insertError+ ? { data: null, error: db.insertError }+ : { data: { id: 'act-1', action_no: 62 }, error: null };+ }+ return { data: null, error: null };+ }+ return { data: db.rows[name]?.(state.filters) ?? null, error: null };+ };+ const chain = {+ select: () => chain,+ insert: (row) => {+ state.op = 'insert';+ state.row = row;+ return chain;+ },+ eq: (col, val) => {+ state.filters[col] = val;+ return chain;+ },+ in: (col, val) => {+ state.filters[col] = val;+ return chain;+ },+ maybeSingle: async () => result(),+ single: async () => result(),+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),+ };+ return chain;+}++vi.mock('../../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));+vi.mock('./sources.js', () => ({+ resolveBrandSources: async () => new Set(['tracking', 'topics', 'site', 'content']),+}));++const { sendTopicOpportunityToActionCenter, topicOpportunityImpact, topicOpportunityPlan } =+ await import('./from-topic-opportunity.js');++const topic = { id: 't1', name: 'GEO tools for agencies', brand_id: 'b1' };++const suggestionRow = (id, volume, relevance = 0.8) => ({+ id,+ suggested_text: `prompt ${id}`,+ est_volume: volume,+ relevance,+});++beforeEach(() => {+ db = {+ inserts: [],+ insertError: null,+ rows: {+ actions: () => null,+ // The query filters on brand, topic and status (open or tracked from the+ // card, never dismissed); the mock returns what matched.+ prompt_suggestions: (f) =>+ f.brand_id === 'b1' &&+ f.topic_id === 't1' &&+ JSON.stringify(f.status) === JSON.stringify(['new', 'added'])+ ? [suggestionRow('s1', 30_000), suggestionRow('s2', 62_000)].filter((r) =>+ f.id.includes(r.id),+ )+ : [],+ prompts: () => [],+ },+ };+});++const send = (suggestionIds = ['s1', 's2']) =>+ sendTopicOpportunityToActionCenter(topic, { suggestionIds, userId: 'u1' });++describe('topicOpportunityPlan', () => {+ it('writes new content for an untracked topic and grows a tracked one', () => {+ expect(topicOpportunityPlan(0).code).toBe('G16');+ expect(topicOpportunityPlan(3).code).toBe('G05');+ });+});++describe('topicOpportunityImpact', () => {+ it('is high from 50k a month, medium from 10k', () => {+ expect([92_000, 50_000, 12_000, 10_000, 900].map(topicOpportunityImpact)).toEqual([+ 'high',+ 'high',+ 'medium',+ 'medium',+ 'low',+ ]);+ });+});++describe('sendTopicOpportunityToActionCenter', () => {+ it('opens a Growth action with the suggestions read on the server', async () => {+ expect(await send()).toEqual({ actionId: 'act-1', actionNo: 62, created: true });++ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action).toMatchObject({+ brand_id: 'b1',+ category: 'growth',+ kind: 'topic_opportunity',+ impact: 'high',+ dedup_key: 'topic_opportunity:t1',+ kpi_keys: ['ai_visibility', 'share_of_voice'],+ baseline: { demand: 92_000, trackedPrompts: 0 },+ });+ expect(action.payload).toMatchObject({+ topicId: 't1',+ topicName: 'GEO tools for agencies',+ plan: 'G16',+ demand: 92_000,+ // Highest volume first.+ suggestions: [+ { id: 's2', text: 'prompt s2', volume: 62_000 },+ { id: 's1', text: 'prompt s1', volume: 30_000 },+ ],+ promptIds: [],+ targetEntity: 'prompts',+ targetCount: 2,+ });+ });++ it('plans G16’s tasks for an untracked topic and records who sent it', async () => {+ await send();++ const tasks = db.inserts.find((i) => i.table === 'action_tasks').row;+ expect(tasks.map((t) => t.task_key)).toContain('identify_new_content_need');+ expect(tasks.every((t) => t.action_id === 'act-1' && t.status === 'todo')).toBe(true);+ expect(db.inserts.find((i) => i.table === 'action_events').row).toMatchObject({+ action_id: 'act-1',+ event: 'created',+ actor_id: 'u1',+ data: { plan: 'G16', demand: 92_000 },+ });+ });++ it('plans G05’s tasks and keeps the tracked prompts for a topic you track', async () => {+ db.rows.prompts = (f) =>+ f.topic_id === 't1' && f.is_active === true ? [{ id: 'p1', text: 'tracked prompt' }] : [];++ await send();++ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action.payload).toMatchObject({ plan: 'G05', trackedPrompts: 1, promptIds: ['p1'] });+ const tasks = db.inserts.find((i) => i.table === 'action_tasks').row;+ expect(tasks.map((t) => t.task_key)).toContain('map_prompts_to_content');+ expect(tasks.map((t) => t.task_key)).not.toContain('identify_new_content_need');+ });++ it('returns the open action for a topic already sent', async () => {+ db.rows.actions = (f) =>+ f.dedup_key === 'topic_opportunity:t1' ? { id: 'act-0', action_no: 59 } : null;++ expect(await send()).toEqual({ actionId: 'act-0', actionNo: 59, created: false });+ expect(db.inserts).toEqual([]);+ });++ it('leaves out suggestions under the relevance threshold or not rated', async () => {+ db.rows.prompt_suggestions = () => [+ suggestionRow('s1', 30_000),+ suggestionRow('s2', 62_000, 0.5),+ suggestionRow('s3', 9_000, null),+ ];++ await send(['s1', 's2', 's3']);++ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action.payload.suggestions.map((s) => s.id)).toEqual(['s1']);+ expect(action.payload.demand).toBe(30_000);+ });++ it('refuses when none of the suggestions is still open in this topic', async () => {+ db.rows.prompt_suggestions = () => [];+ await expect(send()).rejects.toMatchObject({ status: 409 });+ expect(db.inserts).toEqual([]);+ });++ it('returns the winner when another send opened it at the same moment', async () => {+ let reads = 0;+ db.rows.actions = () => (reads++ === 0 ? null : { id: 'act-9', action_no: 63 });+ db.insertError = { code: '23505', message: 'duplicate key' };++ expect(await send()).toEqual({ actionId: 'act-9', actionNo: 63, created: false });+ });+});diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex c3b38ea15..86820c3c1 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -237,11 +237,13 @@ export async function validateAction(action, { now = new Date() } = {}) {// An action sent from a content opportunity is measured on its own prompts// and pages; the brand-wide numbers would bury a single piece of content.// An Improve action (PROMPT-004) likewise, on its one prompt, and a topic- // gap sent from Insights (VIS-010) on the topic's prompts.+ // gap (VIS-010) or opportunity (VIS-011) sent from Insights on the topic's+ // prompts.if (action.kind === 'content_opportunity' ||action.kind === 'prompt_improve' ||- action.kind === 'topic_competitor_gap'+ action.kind === 'topic_competitor_gap' ||+ action.kind === 'topic_opportunity') {const scope = await basketScope(action);const [before, after] = await Promise.all([diff --git a/server/src/lib/suggestion-relevance.js b/server/src/lib/suggestion-relevance.jsindex ee5242bda..6b3185725 100644--- a/server/src/lib/suggestion-relevance.js+++ b/server/src/lib/suggestion-relevance.js@@ -9,6 +9,12 @@ import { generationCostUsd } from './improve-cost.js';*/export const RELEVANCE_SCALE = 10;+/**+ * Below this a suggestion is never offered as an opportunity (Visibility spec+ * v2, fixed). Mirrors web/src/lib/insights-opportunities.ts.+ */+export const RELEVANCE_THRESHOLD = 0.6;+/*** Share of the plan price that rating relevance may add to suggestion* refreshes each month (plan.limits.relevanceMonthlyBudgetUsd).diff --git a/server/src/routes/topics-opportunity-action.test.js b/server/src/routes/topics-opportunity-action.test.jsnew file mode 100644index 000000000..43ba29b79--- /dev/null+++ b/server/src/routes/topics-opportunity-action.test.js@@ -0,0 +1,142 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for an Opportunities topic's "Send action" (VIS-011):+ * POST /api/topics/:id/opportunity-action. The action itself is tested in+ * from-topic-opportunity.test.js; what shows up only here is what the route+ * lets through: ids in the format seeded data uses, a body that matches, a+ * topic that exists, and a caller from the topic's organization.+ */++const assertBrandAccess = vi.fn();+const sendTopicOpportunityToActionCenter = vi.fn();+let topicRow = null;++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));+ vi.doMock('../lib/action-center/from-topic-opportunity.js', () => ({+ sendTopicOpportunityToActionCenter,+ }));+ vi.doMock('../lib/action-center/from-topic-gap.js', () => ({+ sendTopicGapToActionCenter: vi.fn(),+ }));+ vi.doMock('../lib/plan-guard.js', () => ({ requireFeature: () => (req, res, next) => next() }));+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));+ vi.doMock('../lib/web-research.js', () => ({ webResearch: vi.fn() }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ return { default: logger, logger };+ });+ // The topic lookup is the only table the route reads.+ vi.doMock('../config/supabase.js', () => {+ const chain = new Proxy(+ {},+ {+ get: (_t, op) =>+ op === 'maybeSingle' ? async () => ({ data: topicRow, error: null }) : () => chain,+ },+ );+ return { default: { from: () => chain } };+ });++ const { default: router } = await import('./topics.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/topics', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/topics`;+}++// Seeded ids aren't RFC 4122 versions; the route must still take them.+const TOPIC = '77777777-7777-7777-7777-777777777701';+const SUGGESTION = '88888888-8888-8888-8888-888888888801';++const post = (topicId, body) =>+ fetch(`${baseUrl}/${topicId}/opportunity-action`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ vi.clearAllMocks();+ topicRow = { id: TOPIC, name: 'GEO tools for agencies', brand_id: 'b1' };+ assertBrandAccess.mockResolvedValue({});+ sendTopicOpportunityToActionCenter.mockResolvedValue({+ actionId: 'a1',+ actionNo: 62,+ created: true,+ });+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/topics/:id/opportunity-action', () => {+ it('sends the topic with its suggestions', async () => {+ const res = await post(TOPIC, { suggestionIds: [SUGGESTION] });++ expect(res.status).toBe(201);+ expect(await res.json()).toEqual({ actionId: 'a1', actionNo: 62, created: true });+ expect(assertBrandAccess).toHaveBeenCalledWith('b1', 'u1');+ expect(sendTopicOpportunityToActionCenter).toHaveBeenCalledWith(topicRow, {+ suggestionIds: [SUGGESTION],+ userId: 'u1',+ });+ });++ it('answers 200 with the open action when it was already sent', async () => {+ sendTopicOpportunityToActionCenter.mockResolvedValue({+ actionId: 'a0',+ actionNo: 59,+ created: false,+ });+ expect((await post(TOPIC, { suggestionIds: [SUGGESTION] })).status).toBe(200);+ });++ it('rejects a malformed topic id or body before reading anything', async () => {+ const tooMany = Array.from({ length: 26 }, () => SUGGESTION);+ expect((await post('not-an-id', { suggestionIds: [SUGGESTION] })).status).toBe(400);+ expect((await post(TOPIC, { suggestionIds: [] })).status).toBe(400);+ expect((await post(TOPIC, { suggestionIds: ['nope'] })).status).toBe(400);+ expect((await post(TOPIC, { suggestionIds: tooMany })).status).toBe(400);+ expect(assertBrandAccess).not.toHaveBeenCalled();+ expect(sendTopicOpportunityToActionCenter).not.toHaveBeenCalled();+ });++ it('answers 404 for a topic that does not exist', async () => {+ topicRow = null;+ expect((await post(TOPIC, { suggestionIds: [SUGGESTION] })).status).toBe(404);+ expect(sendTopicOpportunityToActionCenter).not.toHaveBeenCalled();+ });++ it('refuses a caller from another organization', async () => {+ assertBrandAccess.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 403 }));+ expect((await post(TOPIC, { suggestionIds: [SUGGESTION] })).status).toBe(403);+ expect(sendTopicOpportunityToActionCenter).not.toHaveBeenCalled();+ });++ it('passes the action’s own status through, e.g. suggestions already handled', async () => {+ sendTopicOpportunityToActionCenter.mockRejectedValue(+ Object.assign(new Error('No open suggestions for this topic'), { status: 409 }),+ );+ const res = await post(TOPIC, { suggestionIds: [SUGGESTION] });+ expect(res.status).toBe(409);+ expect((await res.json()).details).toBe('No open suggestions for this topic');+ });+});diff --git a/server/src/routes/topics.js b/server/src/routes/topics.jsindex 5b092dc99..02672e5d8 100644--- a/server/src/routes/topics.js+++ b/server/src/routes/topics.js@@ -10,6 +10,7 @@ import { webResearch } from '../lib/web-research.js';import logger from '../lib/logger.js';import { getLanguageName } from '../lib/languages.js';import { sendTopicGapToActionCenter } from '../lib/action-center/from-topic-gap.js';+import { sendTopicOpportunityToActionCenter } from '../lib/action-center/from-topic-opportunity.js';const router = Router();@@ -466,4 +467,49 @@ router.post('/:id/gap-action', async (req, res) => {}});+const opportunityActionSchema = z.object({+ // A refresh makes 25 suggestions; guid for seeded ids, as above.+ suggestionIds: z.array(z.guid()).min(1).max(25),+});++/**+ * POST /api/topics/:id/opportunity-action+ * Body: { suggestionIds }+ *+ * "Send action" on an Insights Opportunities topic (VIS-011): a Growth+ * action to capture the demand of the topic's suggested prompts. Sending the+ * same topic again returns the action already open.+ */+router.post('/:id/opportunity-action', async (req, res) => {+ try {+ if (!z.guid().safeParse(req.params.id).success) {+ return res.status(400).json({ error: 'Invalid topic id' });+ }+ const parsed = opportunityActionSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ const { data: topic } = await supabaseAdmin+ .from('topics')+ .select('id, name, brand_id')+ .eq('id', req.params.id)+ .maybeSingle();+ if (!topic) return res.status(404).json({ error: 'Topic not found' });+ await assertBrandAccess(topic.brand_id, req.user.id);++ const result = await sendTopicOpportunityToActionCenter(topic, {+ suggestionIds: parsed.data.suggestionIds,+ userId: req.user.id,+ });+ return res.status(result.created ? 201 : 200).json(result);+ } catch (error) {+ const status = error.status || 500;+ req.log.error({ err: error }, 'topic opportunity action error');+ return res.status(status).json({+ error: 'Failed to send to the Action Center',+ details: error.message,+ });+ }+});+export default router;diff --git a/web/messages/en.json b/web/messages/en.jsonindex 91cb793a4..d4e80b82d 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -786,6 +786,19 @@"scores": "Visibility when sent","you": "You","gap": "{gap} pts behind"+ },+ "noSignalsTopicOpportunity": "This action was sent from Insights' Opportunities, so it has no detection signals. Its evidence is the topic and suggested prompts on the Overview tab.",+ "topicOpportunity": {+ "source": "Source",+ "sourceValue": "Insights › Opportunities",+ "topic": "Topic",+ "openTopic": "Open topic",+ "plan": "Plan",+ "planNew": "Write new content: none of your prompts tracked this topic when it was sent",+ "planExpand": "Grow what covers it: your prompts tracked this topic when it was sent",+ "demand": "Suggested prompts when sent",+ "demandValue": "{count, plural, one {# prompt} other {# prompts}} · ~{volume}/mo",+ "volume": "~{volume}/mo"}}},@@ -1193,6 +1206,12 @@"titleGeneric": "Close a topic gap with a competitor","description": "Sent from Insights: a competitor leads one of your topics on Visibility.","goal": "Lead the topic, or close most of the gap."+ },+ "topic_opportunity": {+ "title": "Capture ~{demand}/mo of AI demand in {topic}",+ "titleGeneric": "Capture the AI demand in a topic",+ "description": "Sent from Insights: prompts suggested for one of your topics, with the monthly AI demand behind them.",+ "goal": "Get the brand into AI answers for the topic's suggested prompts."}},"actionTasks": {@@ -1870,7 +1889,29 @@"noneRelevant": "No suggestion fits your brand closely enough right now. Refresh for new ideas.","allTracked": "You're tracking every suggestion that fits. Refresh suggestions for more ideas.","alreadyHandled": "These suggestions were already accepted or dismissed.",- "openSuggestions": "Open suggestions"+ "openSuggestions": "Open suggestions",+ "sendAction": "Send action",+ "sendActionHint": "Open a Growth action for {topic} in the Action Center",+ "sendNeedsTopic": "This topic isn't saved yet. Refresh suggestions to send it.",+ "sent": "AC-{no} sent to the Action Center",+ "alreadySent": "Already in the Action Center as AC-{no}",+ "sendStale": "These suggestions changed since the page loaded. Refresh to see the latest.",+ "sendFailed": "Couldn't send to the Action Center.",+ "openAction": "Open",+ "suggestContent": "Suggest content",+ "suggestHint": "Write a content suggestion for this topic, steered by this prompt.",+ "suggestHintQuota": "Uses one of the month's content suggestions.",+ "suggestTrackFirst": "Track the topic first: content is written from the answers your tracked prompts get.",+ "contentLimit": "Monthly content limit reached",+ "contentLimitResets": "Monthly content limit reached · resets {date}",+ "writing": "Writing a content suggestion…",+ "written": "Content suggestion created",+ "openContent": "Open",+ "notWritten": "Couldn't write a new suggestion for this topic yet",+ "notWrittenWhy": "Its tracked prompts are already covered by open suggestions, or have no answers yet. Nothing was used from your content quota.",+ "writeFailed": "Couldn't write a content suggestion",+ "stillWriting": "Still writing the content suggestion",+ "stillWritingWhy": "It will appear in Content when it's done."}},"topics": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsxindex 6a8f37cd4..e6cca9421 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx@@ -1,7 +1,7 @@'use client';import { useMemo, useState } from 'react';-import { useTranslations } from 'next-intl';+import { useFormatter, useTranslations } from 'next-intl';import { ArrowRight, Loader2, MessageCircle, Tag } from 'lucide-react';import { toast } from 'sonner';import { Link, useRouter } from '@/i18n/navigation';@@ -9,8 +9,14 @@ import { Button } from '@/components/ui/button';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { formatCompactNumber } from '@/lib/format';import { trackSuggestions } from '@/lib/actions/prompt-suggestions';+import { sendTopicOpportunityToActionCenter } from '@/lib/actions/topic';+import { generateOpportunitiesOnDemand, getGenerationJobStatus } from '@/lib/actions/content';+import { waitForContentJob } from '@/lib/content-job';+import type { ContentUsage } from '@/lib/content-usage';import {+ contentLeft,opportunities,+ secondaryBlock,topicStandings,type Opportunity,type OpportunitySuggestion,@@ -27,16 +33,21 @@ const SUGGESTIONS_HREF = '/dashboard/prompts/suggestions';* stored prompt suggestions. A topic item tracks all its suggested prompts* (Track 23), a prompt item the one. Both stay within the plan's prompt* locations: the server checks every prompt and stops when they're full.+ * Beside Track, a topic item sends a Growth action to the Action Center, and+ * a prompt item has content written for its topic (the Content quota).*/export function Opportunities({+ brandId,suggestions,trackedTopicIds,topics,entities,slotsLeft,+ contentUsage,onTracked,className,}: {+ brandId: string;suggestions: OpportunitySuggestion[];trackedTopicIds: string[] | null;/** The heat map's data, for who leads each topic; null where it isn't loaded. */@@ -45,13 +56,19 @@ export function Opportunities({entities: { key: string; name: string; isOwnBrand: boolean }[] | null;/** Prompt locations left on the plan; null when unlimited. */slotsLeft: number | null;+ /** The month's content quota (CONTENT-001); null when it couldn't be read. */+ contentUsage: ContentUsage | null;onTracked: (count: number) => void;className?: string;}) {const t = useTranslations('insights.opportunities');+ const format = useFormatter();const router = useRouter();const [trackedIds, setTrackedIds] = useState<ReadonlySet<string>>(new Set());const [busy, setBusy] = useState<string | null>(null);+ // Send action and Suggest content run on their own: writing content takes a while.+ const [working, setWorking] = useState<ReadonlySet<string>>(new Set());+ const [contentSpent, setContentSpent] = useState(0);const result = useMemo(() => {const names = Object.fromEntries(@@ -63,6 +80,121 @@ export function Opportunities({);}, [suggestions, trackedIds, topics, entities, trackedTopicIds]);const planFull = slotsLeft !== null && slotsLeft <= 0;+ const left = contentLeft(contentUsage?.opportunities, contentSpent);+ const contentFullHint = contentUsage?.periodEnd+ ? t('contentLimitResets', {+ date: format.dateTime(new Date(contentUsage.periodEnd), {+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC',+ }),+ })+ : t('contentLimit');++ const run = async (key: string, work: () => Promise<void>) => {+ setWorking((prev) => new Set(prev).add(key));+ try {+ await work();+ } finally {+ setWorking((prev) => {+ const next = new Set(prev);+ next.delete(key);+ return next;+ });+ }+ };++ const sendAction = (item: Opportunity) =>+ run(item.key, async () => {+ if (!item.topicId) return;+ try {+ const result = await sendTopicOpportunityToActionCenter(item.topicId, item.suggestionIds);+ if ('error' in result) {+ // The suggestions can be older than the server's: refreshed or handled since.+ if (result.code === 'stale') toast.error(t('sendStale'));+ else toast.error(t('sendFailed'), { description: result.error });+ return;+ }+ toast.success(+ result.created+ ? t('sent', { no: result.actionNo })+ : t('alreadySent', { no: result.actionNo }),+ {+ action: {+ label: t('openAction'),+ onClick: () =>+ router.push(`/dashboard/action-center/actions?action=${result.actionId}`),+ },+ },+ );+ } catch {+ toast.error(t('sendFailed'));+ }+ });++ const suggestContent = (item: Opportunity) =>+ run(item.key, async () => {+ const description = item.title;+ const toastId = toast.loading(t('writing'), { description });+ const open = (label: string, id: string) => ({+ label,+ onClick: () => router.push(`/dashboard/content?opportunity=${id}`),+ });+ try {+ // "+ New" for the prompt's topic, steered by the prompt (CONTENT-003).+ const started = await generateOpportunitiesOnDemand({+ brandId,+ count: 1,+ topicId: item.topicId,+ idea: item.title,+ idempotencyKey: crypto.randomUUID(),+ });+ if (!started.ok) {+ toast.error(started.quotaExhausted ? t('contentLimit') : started.error, {+ id: toastId,+ description,+ });+ return;+ }+ const outcome = await waitForContentJob(started.jobId, {+ getStatus: getGenerationJobStatus,+ });+ if (outcome.kind === 'completed') {+ const createdId = outcome.result.opportunityIds?.[0];+ if (createdId) {+ setContentSpent((n) => n + 1);+ toast.success(t('written'), {+ id: toastId,+ description,+ duration: 10_000,+ action: open(t('openContent'), createdId),+ });+ } else if (outcome.result.limited) {+ toast.error(t('contentLimit'), { id: toastId, description });+ } else {+ toast.info(t('notWritten'), { id: toastId, description: t('notWrittenWhy') });+ }+ } else if (outcome.kind === 'failed') {+ toast.error(t('writeFailed'), { id: toastId, description });+ } else {+ toast.info(t('stillWriting'), { id: toastId, description: t('stillWritingWhy') });+ }+ } catch {+ // Nothing may be left spinning, whatever went wrong on the way.+ toast.error(t('writeFailed'), { id: toastId, description });+ }+ });++ /** Why an item's second button is off, as its hint, or null when it can be used. */+ const secondaryBlocked = (item: Opportunity): string | null => {+ const block = secondaryBlock(item, left);+ if (block === 'needsTopic') return t('sendNeedsTopic');+ if (block === 'trackFirst') return t('suggestTrackFirst');+ return block === 'contentLimit' ? contentFullHint : null;+ };+ // Only a plan with a monthly limit has a quota to mention.+ const suggestHint =+ left === null ? t('suggestHint') : `${t('suggestHint')} ${t('suggestHintQuota')}`;const track = async (item: Opportunity) => {setBusy(item.key);@@ -81,6 +213,15 @@ export function Opportunities({const open = { label: t('openPrompts'), onClick: () => router.push('/dashboard/prompts') };if (!error && done.length === 0) {toast.info(t('alreadyHandled'));+ } else if (!error && item.kind === 'topic' && item.topicId) {+ // Tracking takes the topic off the card; Send action stays one click away.+ toast.success(t('tracked', { count: done.length }), {+ duration: 10_000,+ action: {+ label: t('sendAction'),+ onClick: () => sendAction({ ...item, suggestionIds: done }),+ },+ });} else if (!error) {toast.success(t('tracked', { count: done.length }), { action: open });} else if (code === 'plan_limit' && done.length > 0) {@@ -141,6 +282,7 @@ export function Opportunities({const isTopic = item.kind === 'topic';const Icon = isTopic ? Tag : MessageCircle;const count = item.suggestionIds.length;+ const blocked = secondaryBlocked(item);return (<likey={item.key}@@ -158,29 +300,49 @@ export function Opportunities({{meta(item)}</span></span>- {/* The hint sits on a wrapper: a disabled button shows no tooltip. */}- <span- className="shrink-0"- title={- planFull- ? t('planFull')- : isTopic- ? t('trackCountHint', { count, topic: item.title })- : t('trackHint')- }- >- <Button- size="sm"- className="h-7 gap-1.5 px-2.5 text-xs"- disabled={planFull || busy !== null}- onClick={() => track(item)}+ <span className="flex shrink-0 items-center gap-1.5">+ {/* The hints sit on wrappers: a disabled button shows no tooltip. */}+ <span+ title={+ planFull+ ? t('planFull')+ : isTopic+ ? t('trackCountHint', { count, topic: item.title })+ : t('trackHint')+ }>- {/* Track N adds one prompt at a time, so a big topic takes a moment. */}- {busy === item.key && (- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />- )}- {isTopic ? t('trackCount', { count }) : t('track')}- </Button>+ <Button+ size="sm"+ className="h-7 gap-1.5 px-2.5 text-xs"+ disabled={planFull || busy !== null}+ onClick={() => track(item)}+ >+ {/* Track N adds one prompt at a time, so a big topic takes a moment. */}+ {busy === item.key && (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ )}+ {isTopic ? t('trackCount', { count }) : t('track')}+ </Button>+ </span>+ <span+ title={+ blocked ??+ (isTopic ? t('sendActionHint', { topic: item.title }) : suggestHint)+ }+ >+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 px-2.5 text-xs"+ disabled={blocked !== null || working.has(item.key)}+ onClick={() => (isTopic ? sendAction(item) : suggestContent(item))}+ >+ {working.has(item.key) && (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ )}+ {isTopic ? t('sendAction') : t('suggestContent')}+ </Button>+ </span></span></li>);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex afcb9eb0f..a7cad0e1e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -1364,6 +1364,7 @@ export default function InsightsPage() {{/* Opportunities (VIS-011), under the map: stored suggestions, not period-scoped. */}{opportunities && (<Opportunities+ brandId={brand.id}suggestions={opportunities.suggestions}trackedTopicIds={opportunities.trackedTopicIds}topics={topicCompetitors}@@ -1373,6 +1374,7 @@ export default function InsightsPage() {? null: Math.max(0, trackedPrompts.quotaLimit - trackedPrompts.quotaUsed)}+ contentUsage={opportunities.contentUsage}onTracked={(count) =>setTrackedPrompts((current) => current && { ...current, quotaUsed: current.quotaUsed + count },diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex 80901bf3d..bab0ffe04 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -61,6 +61,7 @@ import { ActionIcon } from './action-table';import { OpportunityContext } from './opportunity-context';import { ImproveContext } from './improve-context';import { TopicGapContext } from './topic-gap-context';+import { TopicOpportunityContext } from './topic-opportunity-context';import { ImproveOutcomeCard } from './improve-outcome-card';import { improvePlatformLabels } from '@/lib/improve-outcome';import { cn } from '@/lib/utils';@@ -266,6 +267,8 @@ export function ActionDrawer({</>) : action.kind === 'topic_competitor_gap' ? (<TopicGapContext payload={action.payload ?? {}} />+ ) : action.kind === 'topic_opportunity' ? (+ <TopicOpportunityContext payload={action.payload ?? {}} />) : opportunityId ? (<OpportunityContextopportunityId={opportunityId}@@ -345,9 +348,11 @@ export function ActionDrawer({? t('drawer.noSignalsImprove'): action.kind === 'topic_competitor_gap'? t('drawer.noSignalsTopicGap')- : opportunityId- ? t('drawer.noSignalsOpportunity')- : t('drawer.noSignals')}+ : action.kind === 'topic_opportunity'+ ? t('drawer.noSignalsTopicOpportunity')+ : opportunityId+ ? t('drawer.noSignalsOpportunity')+ : t('drawer.noSignals')}</p>)}{detail.signals.map((signal) => {diff --git a/web/src/components/action-center/topic-opportunity-context.tsx b/web/src/components/action-center/topic-opportunity-context.tsxnew file mode 100644index 000000000..d680b2e19--- /dev/null+++ b/web/src/components/action-center/topic-opportunity-context.tsx@@ -0,0 +1,85 @@+'use client';++import { useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { formatCompactNumber } from '@/lib/format';++interface SuggestedPrompt {+ text: string;+ volume: number;+}++/**+ * What an Opportunities topic sent from Insights is about (VIS-011): its+ * source, the topic with a link to it, the plan it follows and the suggested+ * prompts with their demand when it was sent. Copied onto the action at send+ * time, so it still reads after the suggestions are refreshed.+ */+export function TopicOpportunityContext({ payload }: { payload: Record<string, unknown> }) {+ const t = useTranslations('actionCenter.actionsPage.drawer.topicOpportunity');+ const topicId = typeof payload.topicId === 'string' ? payload.topicId : null;+ const topicName = typeof payload.topicName === 'string' ? payload.topicName : null;+ const demand = typeof payload.demand === 'number' ? payload.demand : null;+ const plan = payload.plan === 'G05' ? 'planExpand' : payload.plan === 'G16' ? 'planNew' : null;+ const suggestions: SuggestedPrompt[] = Array.isArray(payload.suggestions)+ ? (payload.suggestions as Record<string, unknown>[]).flatMap((s) =>+ typeof s?.text === 'string' ? [{ text: s.text, volume: Number(s.volume) || 0 }] : [],+ )+ : [];++ return (+ <section className="space-y-3">+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>+ <p className="mt-1">{t('sourceValue')}</p>+ </div>+ {topicName && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('topic')}</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span>{topicName}</span>+ {topicId && (+ <Link+ href={`/dashboard/topics/${topicId}`}+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('openTopic')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ )}+ </div>+ </div>+ )}+ {plan && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('plan')}</p>+ <p className="mt-1">{t(plan)}</p>+ </div>+ )}+ {suggestions.length > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('demand')}</p>+ {demand !== null && (+ <p className="mt-1 tabular-nums">+ {t('demandValue', {+ count: suggestions.length,+ volume: formatCompactNumber(demand),+ })}+ </p>+ )}+ <ul className="mt-1.5 space-y-1 text-xs">+ {suggestions.map((s) => (+ <li key={s.text} className="flex items-baseline justify-between gap-3">+ <span className="min-w-0">{s.text}</span>+ <span className="shrink-0 tabular-nums text-muted-foreground">+ {t('volume', { volume: formatCompactNumber(s.volume) })}+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}+ </section>+ );+}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex 4d28c4b90..3b0577bcb 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -47,8 +47,20 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions, opportunity, Improve and topic gap actions', () => {- expect(ACTION_KINDS).toHaveLength(65);+ it('holds copy for all sixty-two definitions and the four person-sent kinds', () => {+ expect(ACTION_KINDS).toHaveLength(66);+ });++ it('names a topic opportunity after its topic and demand (VIS-011)', () => {+ const payload = { topicName: 'GEO tools for agencies', demand: 92_000 };+ expect(actionTexts(action({ kind: 'topic_opportunity', payload }), t).title).toBe(+ 'Capture ~92k/mo of AI demand in GEO tools for agencies',+ );+ const tags = actionContextTags(+ action({ kind: 'topic_opportunity', payload, signalCount: 0 }),+ (key: string) => key,+ );+ expect(tags).not.toContain('tags.signals');});it('names a topic gap after its topic, competitor and gap (VIS-010)', () => {diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 5e5b78ec4..4209125cd 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -1,5 +1,6 @@import type { ActionItem } from '@/lib/actions/action-center';import { isActionKind } from '@/lib/action-center/registry';+import { formatCompactNumber } from '@/lib/format';/*** Composes what an action row shows from `kind` + `payload`, mirroring the@@ -95,6 +96,21 @@ export function actionTexts(description: t(`${action.kind}.description`),};}+ // An Opportunities topic sent from Insights (VIS-011) names the topic and+ // the demand it was sent with.+ if (+ action.kind === 'topic_opportunity' &&+ typeof p.topicName === 'string' &&+ typeof p.demand === 'number'+ ) {+ return {+ title: t(`${action.kind}.title`, {+ demand: formatCompactNumber(p.demand),+ topic: p.topicName,+ }),+ description: t(`${action.kind}.description`),+ };+ }const targets = targetLabel(p, t);return {title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),@@ -143,13 +159,14 @@ const PERSON_SENT_KINDS: string[] = ['content_opportunity','prompt_improve','topic_competitor_gap',+ 'topic_opportunity',];/** Compact evidence chips under the title: signal count plus the kind's own* count (pages, prompts, competitors). */export function actionContextTags(action: ActionItem, t: Translator): string[] {// Actions a person sent (a content opportunity, an Improve set, a topic- // gap) have no detection signals by design; "0 signals" would read as+ // gap or opportunity) have no detection signals by design; "0 signals" would read as// missing evidence.const tags = PERSON_SENT_KINDS.includes(action.kind)? []diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex 8c4b83f4a..b71a8a98e 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -106,7 +106,9 @@ export type ActionKind =// Sent by a person from the Prompts Positions panel's Improve tab (PROMPT-004).| 'prompt_improve'// Sent by a person from Insights' Topics vs competitors (VIS-010).- | 'topic_competitor_gap';+ | 'topic_competitor_gap'+ // Sent by a person from an Insights Opportunities topic (VIS-011).+ | 'topic_opportunity';export type TaskStatus =| 'todo'@@ -223,6 +225,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['content_opportunity','prompt_improve','topic_competitor_gap',+ 'topic_opportunity',];/**diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.tsindex 58421e198..a9bb6dd3c 100644--- a/web/src/lib/actions/topic.ts+++ b/web/src/lib/actions/topic.ts@@ -465,3 +465,41 @@ export async function sendTopicGapToActionCenter(}return res.json();}++/**+ * "Send action" on an Insights Opportunities topic (VIS-011): a Growth+ * action to capture the demand of the topic's suggested prompts. The server+ * reads the suggestions again; the same topic sent again returns the open+ * action.+ */+export async function sendTopicOpportunityToActionCenter(+ topicId: string,+ suggestionIds: string[],+): Promise<+ | { actionId: string; actionNo: number; created: boolean }+ // 'stale': none of the suggestions is still open in the topic (409).+ | { error: string; code?: 'stale' }+> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };++ const res = await fetch(`${API_BASE_URL}/api/topics/${topicId}/opportunity-action`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ suggestionIds }),+ });++ // Returned, not thrown: a thrown error's message is masked in production.+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ const error = body.details || body.error || `Server error: ${res.status}`;+ return res.status === 409 ? { error, code: 'stale' } : { error };+ }+ return res.json();+}diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 1fd3e7491..345cd3aa3 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -42,6 +42,8 @@ import { getTopicById } from '@/lib/actions/topic';import { getOrgPlan } from '@/lib/guards/plan-guard';import { getOrgLocationUsage } from '@/lib/prompt-locations';import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';+import { getContentUsage } from '@/lib/actions/content';+import type { ContentUsage } from '@/lib/content-usage';import { percentageChange } from '@/lib/metrics';import { parseChangeDrivers, whyChanged, type WhyChanged } from '@/lib/insights-drivers';import { parseTrendMarkers, type TrendMarkerData } from '@/lib/insights-trend';@@ -634,6 +636,8 @@ export interface InsightsOpportunities {suggestions: OpportunitySuggestion[];/** The suggestions' topics with at least one active tracked prompt; null when unknown. */trackedTopicIds: string[] | null;+ /** The month's content quota, for Suggest content (CONTENT-001); null when unread. */+ contentUsage: ContentUsage | null;}/** PostgREST's default row cap: a read that fills it may have been cut short. */@@ -650,8 +654,8 @@ async function getInsightsOpportunities(brandId: string): Promise<InsightsOpporttry {const { suggestions } = await getPromptSuggestions(brandId);const topicIds = [...new Set(suggestions.flatMap((s) => (s.topicId ? [s.topicId] : [])))];- let trackedTopicIds: string[] | null = [];- if (topicIds.length > 0) {+ const readTrackedTopics = async (): Promise<string[] | null> => {+ if (topicIds.length === 0) return [];const supabase = await dbClient();const { data, error } = await supabase.from('prompts')@@ -660,11 +664,16 @@ async function getInsightsOpportunities(brandId: string): Promise<InsightsOpport.eq('is_active', true).limit(TRACKED_TOPIC_ROWS);// Unknown, not "none": a failed or cut-off read would call tracked topics untracked.- trackedTopicIds =- error || (data?.length ?? 0) >= TRACKED_TOPIC_ROWS- ? null- : [...new Set((data ?? []).map((r) => r.topic_id as string))];- }+ return error || (data?.length ?? 0) >= TRACKED_TOPIC_ROWS+ ? null+ : [...new Set((data ?? []).map((r) => r.topic_id as string))];+ };+ const [trackedTopicIds, contentUsage] = await Promise.all([+ readTrackedTopics(),+ // Only Suggest content uses it. The server still enforces the quota; an+ // unread one only leaves the button enabled.+ suggestions.length > 0 ? getContentUsage().catch(() => null) : Promise.resolve(null),+ ]);return {suggestions: suggestions.map((s) => ({id: s.id,@@ -675,9 +684,10 @@ async function getInsightsOpportunities(brandId: string): Promise<InsightsOpportrelevance: s.relevance,})),trackedTopicIds,+ contentUsage,};} catch {- return { suggestions: [], trackedTopicIds: [] };+ return { suggestions: [], trackedTopicIds: [], contentUsage: null };}}diff --git a/web/src/lib/insights-opportunities.test.ts b/web/src/lib/insights-opportunities.test.tsindex aba502d91..5f8d91874 100644--- a/web/src/lib/insights-opportunities.test.ts+++ b/web/src/lib/insights-opportunities.test.ts@@ -1,10 +1,13 @@import { describe, expect, it } from 'vitest';import type { TopicCompetitors } from './insights-topics';import {+ contentLeft,gapWeight,opportunities,RELEVANCE_THRESHOLD,+ secondaryBlock,topicStandings,+ type Opportunity,type OpportunityStanding,type OpportunitySuggestion,} from './insights-opportunities';@@ -188,3 +191,40 @@ describe('gapWeight', () => {expect(gapWeight({ kind: 'notTracked' })).toBe(1);});});++describe('contentLeft', () => {+ it('takes what this page wrote off the month’s remaining suggestions', () => {+ expect(contentLeft({ limit: 10, remaining: 3 }, 1)).toBe(2);+ });++ it('is null without a monthly limit or a quota read', () => {+ expect(contentLeft({ limit: -1, remaining: 0 }, 4)).toBeNull();+ expect(contentLeft(null, 0)).toBeNull();+ });+});++describe('secondaryBlock', () => {+ const item = (over: Partial<Opportunity>): Opportunity => ({+ kind: 'prompt',+ key: 'k',+ title: 'prompt',+ topicId: 't1',+ suggestionIds: ['s1'],+ volume: 1000,+ standing: { kind: 'unknown' },+ ...over,+ });++ it('sends a topic once it is saved', () => {+ expect(secondaryBlock(item({ kind: 'topic' }), 0)).toBeNull();+ expect(secondaryBlock(item({ kind: 'topic', topicId: null }), null)).toBe('needsTopic');+ });++ it('writes content only for a topic you track, within the month’s quota', () => {+ expect(secondaryBlock(item({}), 2)).toBeNull();+ expect(secondaryBlock(item({}), null)).toBeNull();+ expect(secondaryBlock(item({ standing: { kind: 'notTracked' } }), 2)).toBe('trackFirst');+ expect(secondaryBlock(item({ topicId: null }), 2)).toBe('trackFirst');+ expect(secondaryBlock(item({}), 0)).toBe('contentLimit');+ });+});diff --git a/web/src/lib/insights-opportunities.ts b/web/src/lib/insights-opportunities.tsindex defe63d1c..3924071b8 100644--- a/web/src/lib/insights-opportunities.ts+++ b/web/src/lib/insights-opportunities.ts@@ -145,3 +145,27 @@ export function opportunities();return { status: 'ready', items: ranked.map((r) => r.item) };}++/**+ * Content suggestions left this month, less the ones this page has written+ * since it loaded (CONTENT-001). Null when the plan has no monthly limit or+ * the quota couldn't be read: the server still enforces it.+ */+export function contentLeft(+ quota: { limit: number; remaining: number } | null | undefined,+ spent: number,+): number | null {+ if (!quota || quota.limit === -1) return null;+ return quota.remaining - spent;+}++/** Why an item's second button (Send action / Suggest content) is off; null when it can be used. */+export type SecondaryBlock = 'needsTopic' | 'trackFirst' | 'contentLimit' | null;++export function secondaryBlock(item: Opportunity, left: number | null): SecondaryBlock {+ if (item.kind === 'topic') return item.topicId ? null : 'needsTopic';+ // Content is written from the answers of the topic's tracked prompts+ // (the server's opportunity generator), so an untracked topic has none.+ if (!item.topicId || item.standing.kind === 'notTracked') return 'trackFirst';+ return left !== null && left <= 0 ? 'contentLimit' : null;+}