Skip to content

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.

feat(content): add a "+ New" button to generate opportunities on demand (#1023)

Cihandc74b242db3a
diff --git a/server/src/config/plans.js b/server/src/config/plans.js
index d576ff20d..f594996c1 100644
--- a/server/src/config/plans.js
+++ b/server/src/config/plans.js
@@ -17,6 +17,7 @@ export const PLANS = {
maxBriefGenerations: -1,
improveMonthlyBudgetUsd: -1,
maxOpportunitiesPerMonth: -1,
+ maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
@@ -50,6 +51,7 @@ export const PLANS = {
maxBriefGenerations: 10,
improveMonthlyBudgetUsd: 0,
maxOpportunitiesPerMonth: 10,
+ maxOpportunitiesPerRequest: 3,
maxSiteAudits: 100,
maxDailyOnDemand: 3,
onDemandCooldownMinutes: 15,
@@ -84,6 +86,7 @@ export const PLANS = {
// 1% of the $249 price, spent on Improve model calls (PROMPT-003).
improveMonthlyBudgetUsd: 2.49,
maxOpportunitiesPerMonth: 50,
+ maxOpportunitiesPerRequest: 5,
maxSiteAudits: 500,
maxDailyOnDemand: 10,
onDemandCooldownMinutes: 5,
@@ -123,6 +126,7 @@ export const PLANS = {
// of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.
improveMonthlyBudgetUsd: 4.99,
maxOpportunitiesPerMonth: -1,
+ maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
diff --git a/server/src/lib/job-runner.js b/server/src/lib/job-runner.js
index 7d9616d2d..223c26838 100644
--- a/server/src/lib/job-runner.js
+++ b/server/src/lib/job-runner.js
@@ -233,10 +233,10 @@ async function attemptContentJob(jobId, io) {
let retrying = false;
try {
- const { brandId, model } = jobRow.data;
+ const { brandId, model, request } = jobRow.data;
const proxy = createJobProxy(jobId, abortController.signal);
- const result = await processContentJob({ brandId, model, job: proxy });
+ const result = await processContentJob({ brandId, model, job: proxy, request });
await completeJob(jobId, result);
diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.js
index a20eba204..2730d04c9 100644
--- a/server/src/lib/opportunity-generator.js
+++ b/server/src/lib/opportunity-generator.js
@@ -16,6 +16,7 @@ import supabaseAdmin from '../config/supabase.js';
import { selectInChunks } from './chunked-in.js';
import { logger } from './logger.js';
import {
+ OPPORTUNITIES_PER_RUN,
OPPORTUNITY_WINDOW_DAYS,
clusterMetrics,
coveredClusterIds,
@@ -218,12 +219,35 @@ async function loadPromptTexts(promptIds) {
return data || [];
}
+/** Longest idea a "+ New" request may carry into the model prompt. */
+export const IDEA_MAX_LENGTH = 500;
+
/**
* @param {string} brandId
- * @param {{ model?: string, onProgress?: (p: {phase: string, message: string}) => void }} [opts]
- * @returns {Promise<{ generated: number, merged: number, reopened?: number }>}
+ * @param {{
+ * model?: string,
+ * onProgress?: (p: {phase: string, message: string}) => void,
+ * count?: number,
+ * topicId?: string | null,
+ * promptId?: string | null,
+ * idea?: string | null,
+ * source?: 'system' | 'manual' | 'prompt',
+ * }} [opts] - `count`, the focus (`topicId` / `promptId`) and `idea` come from
+ * an on-demand request (CONTENT-003); the nightly run passes none of them.
+ * @returns {Promise<{ generated: number, merged: number, reopened?: number, duplicates?: number, limited?: boolean }>}
*/
-export async function generateContentOpportunities(brandId, { model, onProgress } = {}) {
+export async function generateContentOpportunities(
+ brandId,
+ {
+ model,
+ onProgress,
+ count,
+ topicId = null,
+ promptId = null,
+ idea = null,
+ source = 'system',
+ } = {},
+) {
onProgress?.({ phase: 'collecting_data', message: 'Fetching clusters and metrics...' });
const { data: brand } = await supabaseAdmin
@@ -310,7 +334,11 @@ export async function generateContentOpportunities(brandId, { model, onProgress
// The fan-out baskets of every cluster still open for an opportunity: the
// duplicate check compares them, and the prompt shows the picked ones'.
- const open = candidates.filter((c) => c.metrics.tested > 0 && !covered.has(c.id));
+ // A focused request only considers its topic's clusters or its prompt's.
+ const inFocus = (c) =>
+ (!topicId || c.topicId === topicId) &&
+ (!promptId || clusterById.get(c.id).prompt_ids.includes(promptId));
+ const open = candidates.filter((c) => c.metrics.tested > 0 && !covered.has(c.id) && inFocus(c));
const { data: basketRows, error: basketErr } = await selectInChunks(
open.map((c) => c.id),
(chunk) =>
@@ -332,7 +360,9 @@ export async function generateContentOpportunities(brandId, { model, onProgress
covered,
});
- const wanted = pickClusters(candidates, covered);
+ const wanted = pickClusters(open, covered, count ?? OPPORTUNITIES_PER_RUN, {
+ fill: count !== undefined,
+ });
if (!wanted.length) {
logger.info(
{ brandId, clusters: clusters.length, opportunities: existing.length, reopened, duplicates },
@@ -405,7 +435,11 @@ ${picked.map(clusterLine).join('\n\n')}
Existing opportunities in other topics:
${shown.map((o, i) => `[E${i}] ${o.title} (topic: ${topicName(clusterById.get(o.cluster_id)) || 'none'})`).join('\n') || 'none'}
-Write every title and description in ${getLanguageName(brand.language)}.`;
+${
+ idea
+ ? `The user asked for ideas around: "${idea.slice(0, IDEA_MAX_LENGTH)}". Shape the opportunities toward it wherever the clusters' prompts allow; never invent a need the data doesn't show.\n\n`
+ : ''
+}Write every title and description in ${getLanguageName(brand.language)}.`;
onProgress?.({ phase: 'analyzing', message: 'Generating opportunities with AI...' });
const { object } = await generateObject({
@@ -486,6 +520,7 @@ Write every title and description in ${getLanguageName(brand.language)}.`;
impact: opp.impact,
opportunity_score: cand.score,
status: 'new',
+ source,
decision: primary.decision,
source_data: {
...sourceData({
diff --git a/server/src/lib/opportunity-limits.js b/server/src/lib/opportunity-limits.js
index 3faf354e8..ad55059a0 100644
--- a/server/src/lib/opportunity-limits.js
+++ b/server/src/lib/opportunity-limits.js
@@ -135,19 +135,34 @@ export function coveredClusterIds(rows) {
* The highest-scoring clusters with answers and no opportunity yet, at most
* one per topic, so a run's few suggestions spread across the brand's topics
* instead of all landing in its strongest one. The no-topic scope (null)
- * counts as one topic.
+ * counts as one topic. With `fill`, a request for more than one per topic
+ * is topped up from the best of the rest.
*/
-export function pickClusters(candidates, covered, count = OPPORTUNITIES_PER_RUN) {
+export function pickClusters(
+ candidates,
+ covered,
+ count = OPPORTUNITIES_PER_RUN,
+ { fill = false } = {},
+) {
const topics = new Set();
const picked = [];
- for (const c of [...candidates]
+ const ranked = [...candidates]
.filter((c) => c.metrics.tested > 0 && !covered.has(c.id))
- .sort((a, b) => b.score - a.score)) {
+ .sort((a, b) => b.score - a.score);
+ for (const c of ranked) {
const topic = c.topicId ?? null;
if (topics.has(topic)) continue;
topics.add(topic);
picked.push(c);
- if (picked.length === count) break;
+ if (picked.length === count) return picked;
+ }
+ // A request for more than there are topics (CONTENT-003's "+ New") takes
+ // the next best clusters once every topic has one.
+ if (fill) {
+ for (const c of ranked) {
+ if (picked.length === count) break;
+ if (!picked.includes(c)) picked.push(c);
+ }
}
return picked;
}
diff --git a/server/src/lib/opportunity-limits.test.js b/server/src/lib/opportunity-limits.test.js
index 9e1e13412..784196381 100644
--- a/server/src/lib/opportunity-limits.test.js
+++ b/server/src/lib/opportunity-limits.test.js
@@ -126,6 +126,22 @@ describe('cluster selection', () => {
);
expect(picked.map((c) => c.id)).toEqual(['a1', 'none1', 'b1']);
});
+
+ it('tops up from the best of the rest when asked for more than there are topics', () => {
+ const cand = (id, score, topicId) => ({ id, score, topicId, metrics: { tested: 1 } });
+ const candidates = [
+ cand('a1', 95, 'a'),
+ cand('a2', 90, 'a'),
+ cand('a3', 60, 'a'),
+ cand('b1', 50, 'b'),
+ ];
+ expect(pickClusters(candidates, new Set(), 3).map((c) => c.id)).toEqual(['a1', 'b1']);
+ expect(pickClusters(candidates, new Set(), 3, { fill: true }).map((c) => c.id)).toEqual([
+ 'a1',
+ 'b1',
+ 'a2',
+ ]);
+ });
});
describe('generators', () => {
diff --git a/server/src/lib/opportunity-quota.test.js b/server/src/lib/opportunity-quota.test.js
index ed92f5a85..46914e3ed 100644
--- a/server/src/lib/opportunity-quota.test.js
+++ b/server/src/lib/opportunity-quota.test.js
@@ -12,8 +12,12 @@ vi.mock('../config/supabase.js', () => ({
},
}));
-const { claimOpportunitySlots, getContentUsage, getOpportunityQuotaStatus } =
- await import('./plan-guard.js');
+const {
+ claimOpportunitySlots,
+ getContentUsage,
+ getOpportunityQuotaStatus,
+ getOpportunityRequestAllowance,
+} = await import('./plan-guard.js');
/** A query builder that resolves to `result` however it is chained. */
function chain(result) {
@@ -107,7 +111,7 @@ describe('getContentUsage', () => {
planName: expect.any(String),
periodStart: '2026-10-12T00:00:00.000Z',
periodEnd: '2026-11-12T00:00:00.000Z',
- opportunities: { used: 32, limit: 50, remaining: 18 },
+ opportunities: { used: 32, limit: 50, remaining: 18, perRequest: 5 },
briefs: { used: 5, limit: 50, remaining: 45 },
});
} finally {
@@ -115,3 +119,27 @@ describe('getContentUsage', () => {
}
});
});
+
+describe('getOpportunityRequestAllowance', () => {
+ it('caps a "+ New" request at 3 on Starter and 5 on Growth', async () => {
+ org('starter');
+ used(0);
+ expect(await getOpportunityRequestAllowance('o1')).toMatchObject({ perRequest: 3, max: 3 });
+ org('growth');
+ used(0);
+ expect(await getOpportunityRequestAllowance('o1')).toMatchObject({ perRequest: 5, max: 5 });
+ });
+
+ it('never asks for more than is left of the month', async () => {
+ org('growth');
+ used(48);
+ expect(await getOpportunityRequestAllowance('o1')).toMatchObject({ remaining: 2, max: 2 });
+ used(50);
+ expect(await getOpportunityRequestAllowance('o1')).toMatchObject({ remaining: 0, max: 0 });
+ });
+
+ it('is the per-request cap alone when the month is unlimited', async () => {
+ delete process.env.IS_CLOUD;
+ expect(await getOpportunityRequestAllowance('o1')).toMatchObject({ remaining: -1, max: 5 });
+ });
+});
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index 2fd4b0b67..9b7831fb1 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -382,6 +382,25 @@ export async function claimOpportunitySlots(orgId, count) {
return { unlimited: false, ids };
}
+/**
+ * What one "+ New" request may ask for (CONTENT-003): the plan's per-request
+ * cap and what is left of the month, with the period's end for the message
+ * when nothing is. remaining -1 means unlimited.
+ */
+export async function getOpportunityRequestAllowance(orgId) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const quota = await getOpportunityQuotaStatus(orgId);
+ const perRequest = plan.limits.maxOpportunitiesPerRequest ?? 5;
+ const periodEnd = shiftMonthClamped(await quotaPeriodStart(orgId), 1).toISOString();
+ return {
+ planId: plan.id,
+ perRequest,
+ remaining: quota.remaining,
+ max: quota.remaining === -1 ? perRequest : Math.min(perRequest, quota.remaining),
+ periodEnd,
+ };
+}
+
/** Point each claimed slot at the opportunity it was used for. */
export async function linkOpportunitySlots(pairs) {
for (const { usageId, opportunityId } of pairs) {
@@ -417,7 +436,11 @@ export async function getContentUsage(orgId) {
planName: plan.name,
periodStart: periodStart.toISOString(),
periodEnd: shiftMonthClamped(periodStart, 1).toISOString(),
- opportunities,
+ opportunities: {
+ ...opportunities,
+ // What one "+ New" request may ask for (CONTENT-003).
+ perRequest: plan.limits.maxOpportunitiesPerRequest ?? 5,
+ },
briefs,
};
}
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index b8f967d5b..5a9011d28 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -6,6 +6,7 @@ import {
enforceBriefQuota,
getBriefQuotaStatus,
getContentUsage,
+ getOpportunityRequestAllowance,
getOrgIdForUser,
PlanLimitError,
} from '../lib/plan-guard.js';
@@ -22,6 +23,7 @@ import {
} from '../lib/access.js';
import { loadClusters } from '../lib/prompt-clusters.js';
import { sendToActionCenter } from '../lib/action-center/from-opportunity.js';
+import { IDEA_MAX_LENGTH } from '../lib/opportunity-generator.js';
const router = Router();
@@ -38,6 +40,7 @@ function mapOpportunityRow(row) {
impact: row.impact,
opportunityScore: parseFloat(row.opportunity_score),
status: row.status,
+ source: row.source ?? 'system',
sourceData: row.source_data || {},
brief: row.brief || null,
webhookSentAt: row.webhook_sent_at,
@@ -100,6 +103,98 @@ router.post('/generate', requireFeature('content_optimization'), async (req, res
}
});
+const onDemandSchema = z.object({
+ brandId: z.guid(),
+ count: z.number().int().min(1).max(20),
+ topicId: z.guid().nullish(),
+ promptId: z.guid().nullish(),
+ idea: z.string().trim().max(IDEA_MAX_LENGTH).nullish(),
+ idempotencyKey: z.string().min(8).max(100),
+});
+
+/** How long a repeated idempotency key returns the job it first started. */
+const IDEMPOTENCY_WINDOW_MS = 10 * 60 * 1000;
+
+/**
+ * POST /api/content/opportunities/generate
+ * "+ New" (CONTENT-003): generate opportunities now instead of waiting for
+ * the nightly run, optionally around a topic, a prompt or a free-text idea.
+ * Body: { brandId, count, topicId?, promptId?, idea?, idempotencyKey }.
+ *
+ * The count is capped by the plan (Starter 3, Growth 5 per request) and by
+ * what is left of the month; the generation claims its quota slots
+ * atomically, so neither a double click nor two tabs can overshoot, and it
+ * hands back whatever it doesn't create. A repeated idempotency key returns
+ * the job it already started. Returns { jobId, count } (202), or 429 with
+ * error 'quota_exhausted' and the reset date when nothing is left.
+ */
+router.post('/opportunities/generate', requireFeature('content_optimization'), async (req, res) => {
+ const parsed = onDemandSchema.safeParse(req.body);
+ if (!parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.issues });
+ }
+ const { brandId, count, topicId, promptId, idea, idempotencyKey } = parsed.data;
+
+ try {
+ const { orgId } = await assertBrandAccess(brandId, req.user.id);
+
+ const since = new Date(Date.now() - IDEMPOTENCY_WINDOW_MS).toISOString();
+ const { data: previous } = await supabaseAdmin
+ .from('jobs')
+ .select('id, data')
+ .eq('type', 'content')
+ .eq('brand_id', brandId)
+ .eq('data->request->>idempotencyKey', idempotencyKey)
+ .gte('created_at', since)
+ .limit(1)
+ .maybeSingle();
+ if (previous) {
+ return res.status(202).json({ jobId: previous.id, count: previous.data.request.count });
+ }
+
+ const allowance = orgId
+ ? await getOpportunityRequestAllowance(orgId)
+ : { perRequest: 5, remaining: -1, max: 5, periodEnd: null, planId: 'self_hosted' };
+ if (allowance.max <= 0) {
+ return res.status(429).json({
+ success: false,
+ error: 'quota_exhausted',
+ message: 'Monthly opportunity limit reached.',
+ periodEnd: allowance.periodEnd,
+ plan: allowance.planId,
+ });
+ }
+
+ const request = {
+ count: Math.min(count, allowance.max),
+ topicId: topicId ?? null,
+ promptId: promptId ?? null,
+ idea: idea || null,
+ idempotencyKey,
+ };
+ const job = await createJob({
+ type: 'content',
+ brandId,
+ data: { brandId, model: null, request },
+ maxAttempts: 2,
+ });
+ runContentJob(job.id, req.app.get('io'));
+
+ return res.status(202).json({ jobId: job.id, count: request.count });
+ } catch (error) {
+ if (error instanceof PlanLimitError) {
+ return res.status(error.statusCode).json({
+ success: false,
+ error: 'plan_limit',
+ message: error.message,
+ });
+ }
+ if (error.status) return res.status(error.status).json({ error: error.message });
+ req.log.error({ err: error }, 'on-demand opportunity generation error');
+ return res.status(500).json({ error: 'Failed to start generation' });
+ }
+});
+
/**
* GET /api/content/job/:jobId
* Returns job state and progress for content generation.
@@ -174,6 +269,7 @@ router.get('/brand/:brandId', async (req, res) => {
q,
prompt_id: promptId,
topic_id: topicId,
+ source,
limit = 50,
offset = 0,
sort = 'score',
@@ -201,6 +297,11 @@ router.get('/brand/:brandId', async (req, res) => {
filteredQuery = filteredQuery.eq('type', type);
}
+ // system (nightly), manual ("+ New") or prompt ("Suggest Content").
+ if (source) {
+ filteredQuery = filteredQuery.eq('source', source);
+ }
+
// A prompt matches its cluster's opportunities, own or merged, and any
// older opportunity written for the prompt itself.
if (promptId) {
@@ -250,6 +351,7 @@ router.get('/brand/:brandId', async (req, res) => {
p_q: search,
p_prompt_id: promptId ? String(promptId) : null,
p_topic_id: topicId ? String(topicId) : null,
+ p_source: source ? String(source) : null,
});
const [{ data, error: dataError, count }, { data: aggregateData, error: aggregateError }] =
@@ -1053,7 +1155,7 @@ router.get('/usage', async (req, res) => {
planName: null,
periodStart: null,
periodEnd: null,
- opportunities: unlimited,
+ opportunities: { ...unlimited, perRequest: 5 },
briefs: unlimited,
});
}
diff --git a/server/src/workers/content-worker.js b/server/src/workers/content-worker.js
index 33244f2ee..70ce0b923 100644
--- a/server/src/workers/content-worker.js
+++ b/server/src/workers/content-worker.js
@@ -8,15 +8,15 @@ import { generateContentOpportunities } from '../lib/opportunity-generator.js';
import { refreshPromptClusters } from '../lib/prompt-clusters.js';
/**
- * The Generate button runs the same per-cluster generation as the nightly
- * run. Clusters are refreshed first: a brand whose prompts changed since its
+ * The "+ New" button (CONTENT-003) runs the same per-cluster generation as
+ * the nightly run. Clusters are refreshed first: a brand whose prompts changed since its
* last tracking cycle, or that has never been clustered, would otherwise get
* nothing or work from stale groups. The button adds to the existing list
* (#63); a cluster that already has an opportunity is skipped.
*
- * @param {{ brandId: string, model?: string, job: { progress: function } }} opts
+ * @param {{ brandId: string, model?: string, job: { progress: function }, request?: object | null }} opts
*/
-export async function processContentJob({ brandId, model, job }) {
+export async function processContentJob({ brandId, model, job, request = null }) {
job.progress({ phase: 'collecting_data', message: 'Grouping prompts into clusters...' });
try {
await refreshPromptClusters(brandId);
@@ -24,9 +24,20 @@ export async function processContentJob({ brandId, model, job }) {
logger.error({ err, brandId }, 'prompt cluster refresh failed before generation');
}
+ // A "+ New" request (CONTENT-003) carries its count, focus and idea, and
+ // marks what it creates as manual; the nightly path passes none of it.
const result = await generateContentOpportunities(brandId, {
model,
onProgress: (p) => job.progress(p),
+ ...(request
+ ? {
+ count: request.count,
+ topicId: request.topicId ?? null,
+ promptId: request.promptId ?? null,
+ idea: request.idea ?? null,
+ source: 'manual',
+ }
+ : {}),
});
logger.info({ brandId, ...result }, 'content opportunities generated');
return result;
diff --git a/supabase/migrations/00126_opportunity_source.sql b/supabase/migrations/00126_opportunity_source.sql
new file mode 100644
index 000000000..fd24b24e5
--- /dev/null
+++ b/supabase/migrations/00126_opportunity_source.sql
@@ -0,0 +1,103 @@
+-- Where an opportunity came from (CONTENT-003): the nightly run (system),
+-- the "+ New" button (manual), or a prompt's "Suggest Content" (prompt,
+-- PROMPT-006). The list shows it as a badge and can filter by it, so the
+-- summary figures above the list take the same filter.
+--
+-- Existing rows were all made by the nightly run, hence the default.
+alter table public.content_opportunities
+ add column if not exists source text not null default 'system';
+
+alter table public.content_opportunities
+ drop constraint if exists content_opportunities_source_check;
+alter table public.content_opportunities
+ add constraint content_opportunities_source_check
+ check (source in ('system', 'manual', 'prompt'));
+
+-- content_opportunity_aggregates (00103) with the source filter.
+drop function if exists public.content_opportunity_aggregates(uuid, text, text, text, text, uuid, uuid);
+
+create or replace function public.content_opportunity_aggregates(
+ p_brand_id uuid,
+ p_status text default null,
+ p_impact text default null,
+ p_type text default null,
+ p_q text default null,
+ p_prompt_id uuid default null,
+ p_topic_id uuid default null,
+ p_source text default null
+)
+returns table (
+ avg_score numeric,
+ high_impact_count bigint,
+ sent_count bigint,
+ signal_count bigint
+)
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ select
+ coalesce(avg(co.opportunity_score), 0) as avg_score,
+ count(*) filter (
+ where co.impact = 'high'
+ ) as high_impact_count,
+ count(*) filter (
+ where co.status in ('sent', 'in_progress', 'done')
+ ) as sent_count,
+ (
+ select count(*)
+ from prompt_cluster_members m
+ join prompt_clusters pc on pc.id = m.cluster_id
+ where pc.brand_id = p_brand_id
+ ) + (
+ select count(*)
+ from prompt_cluster_queries q
+ join prompt_clusters pc on pc.id = q.cluster_id
+ where pc.brand_id = p_brand_id
+ ) as signal_count
+ from public.content_opportunities co
+ where co.brand_id = p_brand_id
+ and (
+ (p_status is null and co.status <> 'archived')
+ or co.status = p_status
+ )
+ and (p_impact is null or co.impact = p_impact)
+ and (p_type is null or co.type = p_type)
+ and (p_source is null or co.source = p_source)
+ and (
+ p_prompt_id is null
+ or co.prompt_id = p_prompt_id
+ or exists (
+ select 1
+ from prompt_cluster_members m
+ where m.prompt_id = p_prompt_id
+ and (m.cluster_id = co.cluster_id or m.cluster_id = any(co.related_cluster_ids))
+ )
+ )
+ and (
+ p_topic_id is null
+ or exists (
+ select 1
+ from prompt_clusters pc
+ where pc.topic_id = p_topic_id
+ and (pc.id = co.cluster_id or pc.id = any(co.related_cluster_ids))
+ )
+ )
+ and (
+ p_q is null
+ or co.title ilike '%' || p_q || '%'
+ or co.description ilike '%' || p_q || '%'
+ );
+$$;
+
+grant execute on function public.content_opportunity_aggregates(
+ uuid,
+ text,
+ text,
+ text,
+ text,
+ uuid,
+ uuid,
+ text
+) to authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 018b96e82..a7360c3f2 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -14405,3 +14405,110 @@ grant execute on function public.claim_opportunity_usage(uuid, timestamptz, inte
comment on function public.claim_opportunity_usage(uuid, timestamptz, integer, integer) is
'Atomically claims up to p_count monthly opportunity slots for an organization (CONTENT-001). Returns the claimed opportunity_usage ids.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00126_opportunity_source.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Where an opportunity came from (CONTENT-003): the nightly run (system),
+-- the "+ New" button (manual), or a prompt's "Suggest Content" (prompt,
+-- PROMPT-006). The list shows it as a badge and can filter by it, so the
+-- summary figures above the list take the same filter.
+--
+-- Existing rows were all made by the nightly run, hence the default.
+alter table public.content_opportunities
+ add column if not exists source text not null default 'system';
+
+alter table public.content_opportunities
+ drop constraint if exists content_opportunities_source_check;
+alter table public.content_opportunities
+ add constraint content_opportunities_source_check
+ check (source in ('system', 'manual', 'prompt'));
+
+-- content_opportunity_aggregates (00103) with the source filter.
+drop function if exists public.content_opportunity_aggregates(uuid, text, text, text, text, uuid, uuid);
+
+create or replace function public.content_opportunity_aggregates(
+ p_brand_id uuid,
+ p_status text default null,
+ p_impact text default null,
+ p_type text default null,
+ p_q text default null,
+ p_prompt_id uuid default null,
+ p_topic_id uuid default null,
+ p_source text default null
+)
+returns table (
+ avg_score numeric,
+ high_impact_count bigint,
+ sent_count bigint,
+ signal_count bigint
+)
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ select
+ coalesce(avg(co.opportunity_score), 0) as avg_score,
+ count(*) filter (
+ where co.impact = 'high'
+ ) as high_impact_count,
+ count(*) filter (
+ where co.status in ('sent', 'in_progress', 'done')
+ ) as sent_count,
+ (
+ select count(*)
+ from prompt_cluster_members m
+ join prompt_clusters pc on pc.id = m.cluster_id
+ where pc.brand_id = p_brand_id
+ ) + (
+ select count(*)
+ from prompt_cluster_queries q
+ join prompt_clusters pc on pc.id = q.cluster_id
+ where pc.brand_id = p_brand_id
+ ) as signal_count
+ from public.content_opportunities co
+ where co.brand_id = p_brand_id
+ and (
+ (p_status is null and co.status <> 'archived')
+ or co.status = p_status
+ )
+ and (p_impact is null or co.impact = p_impact)
+ and (p_type is null or co.type = p_type)
+ and (p_source is null or co.source = p_source)
+ and (
+ p_prompt_id is null
+ or co.prompt_id = p_prompt_id
+ or exists (
+ select 1
+ from prompt_cluster_members m
+ where m.prompt_id = p_prompt_id
+ and (m.cluster_id = co.cluster_id or m.cluster_id = any(co.related_cluster_ids))
+ )
+ )
+ and (
+ p_topic_id is null
+ or exists (
+ select 1
+ from prompt_clusters pc
+ where pc.topic_id = p_topic_id
+ and (pc.id = co.cluster_id or pc.id = any(co.related_cluster_ids))
+ )
+ )
+ and (
+ p_q is null
+ or co.title ilike '%' || p_q || '%'
+ or co.description ilike '%' || p_q || '%'
+ );
+$$;
+
+grant execute on function public.content_opportunity_aggregates(
+ uuid,
+ text,
+ text,
+ text,
+ text,
+ uuid,
+ uuid,
+ text
+) to authenticated;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 9c4196925..a05df1bda 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1701,10 +1701,8 @@
"title": "Content Opportunities",
"description": "AI-powered content recommendations to improve your visibility in AI-generated answers.",
"opportunities": "Opportunities",
- "generate": "Generate Opportunities",
"autoGeneratedHint": "Opportunities are generated automatically as your tracking data comes in.",
- "regenerate": "Refresh Opportunities",
- "generating": "Analyzing...",
+ "generating": "Generating…",
"send": "Send",
"sendToWorkflow": "Send to Workflow",
"generateBrief": "Generate Brief",
@@ -1781,7 +1779,49 @@
"allStatuses": "All Statuses",
"allImpacts": "All Impacts",
"allTypes": "All Types",
- "allTopics": "All Topics"
+ "allTopics": "All Topics",
+ "allSources": "All Sources"
+ },
+ "source": {
+ "label": "Source",
+ "system": "System",
+ "manual": "Manual",
+ "prompt": "Prompt"
+ },
+ "sourceHint": {
+ "system": "Suggested automatically as tracking data comes in",
+ "manual": "Created with + New",
+ "prompt": "Suggested from a prompt in the prompts table"
+ },
+ "new": "New",
+ "newDone": "{generated, plural, =0 {No new opportunities} one {1 opportunity created} other {# opportunities created}}{duplicates, plural, =0 {} one { · 1 duplicate skipped (not counted)} other { · # duplicates skipped (not counted)}}",
+ "newNothing": "No new opportunities: every matching need already has one.",
+ "newLimitReached": "Monthly opportunity limit reached.",
+ "newLimitTooltip": "Monthly limit reached. Resets on {date}.",
+ "newRefunded": "Nothing was used from your monthly quota.",
+ "retry": "Retry",
+ "generatingRow": "Generating…",
+ "newDialog": {
+ "title": "New content opportunities",
+ "description": "Generate fresh suggestions now instead of waiting for the next scheduled run.",
+ "focus": "Focus (optional)",
+ "focusOptions": {
+ "auto": "Let Ansvisor choose",
+ "topic": "Topic",
+ "prompt": "Prompt"
+ },
+ "pickTopic": "Choose a topic",
+ "pickPrompt": "Choose a prompt",
+ "idea": "Or describe an idea (optional)",
+ "ideaPlaceholder": "e.g. a comparison page against Profound for agencies",
+ "count": "How many",
+ "fewer": "Fewer",
+ "more": "More",
+ "max": "max {max}",
+ "uses": "Uses {count} of your {remaining} remaining this month → {after} left after this. Duplicates of existing opportunities are skipped and don't count.",
+ "usesUnlimited": "Generates up to {count}. Duplicates of existing opportunities are skipped.",
+ "noneLeft": "You've used this month's opportunities. They reset when your subscription renews.",
+ "generate": "Generate {count}"
},
"sort": {
"label": "Sort",
@@ -1870,7 +1910,6 @@
"loadError": "Failed to load content opportunities",
"exportError": "Failed to export opportunities",
"loadOpportunityError": "Failed to load opportunity",
- "generatedToast": "Generated {count} opportunities",
"generationFailed": "Generation failed — please try again",
"generationTimedOut": "Generation timed out — please try again",
"generateError": "Failed to generate opportunities",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index 537c4e6e2..676448374 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -1,7 +1,7 @@
'use client';
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import { useTranslations } from 'next-intl';
+import { useLocale, useTranslations } from 'next-intl';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -51,18 +51,17 @@ import {
BarChart3,
Search,
Loader2,
- RefreshCw,
ExternalLink,
X,
Settings2,
Trash2,
Download,
+ Plus,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
-import { usePlanContext } from '@/components/providers/plan-provider';
import {
- generateOpportunities,
+ generateOpportunitiesOnDemand,
getGenerationJobStatus,
getContentUsage,
getOpportunities,
@@ -83,7 +82,12 @@ import { WebhookSettingsDialog } from './_webhook-settings';
import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';
import { OpportunityDetail } from '@/components/content/opportunity-detail';
import { ContentUsageCard } from '@/components/content/content-usage-card';
-import { hasContentQuota, type ContentUsage } from '@/lib/content-usage';
+import { hasContentQuota, onDemandMax, type ContentUsage } from '@/lib/content-usage';
+import {
+ NewOpportunitiesDialog,
+ type NewOpportunitiesInput,
+} from '@/components/content/new-opportunities-dialog';
+import { Skeleton } from '@/components/ui/skeleton';
import { PAGE_SIZE, TablePager, usePagination } from '@/components/table-pager';
import { toCsv } from '@/lib/csv';
import { readUrlChoice, writeUrlParams } from '@/lib/url-state';
@@ -103,8 +107,12 @@ const STATUS_VALUES = [
] as const;
const IMPACT_VALUES = ['all', 'high', 'medium', 'low'] as const;
const TYPE_VALUES = ['all', 'owned', 'earned'] as const;
+const SOURCE_VALUES = ['all', 'system', 'manual', 'prompt'] as const;
const SORT_VALUES = ['score', 'newest'] as const;
-const URL_DEFAULTS = { status: 'all', impact: 'all', type: 'all', sort: 'score' };
+const URL_DEFAULTS = { status: 'all', impact: 'all', type: 'all', source: 'all', sort: 'score' };
+
+/** Used when the month's usage couldn't be read; the server still caps it. */
+const FALLBACK_REQUEST_MAX = 3;
const OPPORTUNITY_EXPORT_HEADERS = [
'title',
@@ -125,6 +133,8 @@ interface GenerationJob {
brandId: string;
jobId: string;
startedAt: number;
+ /** How many a "+ New" request asked for: the placeholder rows shown meanwhile. */
+ count?: number;
}
function saveGenerationJob(job: GenerationJob) {
@@ -209,9 +219,9 @@ interface PromptFilterItem {
export default function ContentPage() {
const t = useTranslations('content');
const tCommon = useTranslations('common');
+ const locale = useLocale();
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const activeBrandSlug = useBrandStore((s) => s.getActiveBrand()?.slug);
- const { isCloud } = usePlanContext();
const [opportunities, setOpportunities] = useState<ContentOpportunity[]>([]);
const [total, setTotal] = useState(0);
@@ -224,6 +234,7 @@ export default function ContentPage() {
const [statusFilter, setStatusFilter] = useState<string>('all');
const [impactFilter, setImpactFilter] = useState<string>('all');
const [typeFilter, setTypeFilter] = useState<string>('all');
+ const [sourceFilter, setSourceFilter] = useState<string>('all');
const [sortOrder, setSortOrder] = useState<string>('score');
// The prompt filter (#836) lives in the URL as ?prompt=<id> so a filtered
// view can be linked to. It is read after mount — useSearchParams would need
@@ -243,6 +254,13 @@ export default function ContentPage() {
const [webhookOpen, setWebhookOpen] = useState(false);
// This billing period's content usage (CONTENT-001); null hides the card.
const [contentUsage, setContentUsage] = useState<ContentUsage | null>(null);
+ // Bumped after a "+ New" run, which may use quota without changing the total.
+ const [usageVersion, setUsageVersion] = useState(0);
+ const [newOpen, setNewOpen] = useState(false);
+ // Placeholder rows while a "+ New" request runs (CONTENT-003).
+ const [pendingCount, setPendingCount] = useState(0);
+ const lastRequestRef = useRef<NewOpportunitiesInput | null>(null);
+ const retryRef = useRef<(() => void) | null>(null);
const pollRef = useRef(false);
const [debouncedSearch, setDebouncedSearch] = useState(search);
const [aggregates, setAggregates] = useState({
@@ -257,7 +275,7 @@ export default function ContentPage() {
// pager instead of the length of whatever page happens to be loaded.
const pager = usePagination(
total,
- `${statusFilter}|${impactFilter}|${typeFilter}|${promptFilter}|${topicFilter}|${debouncedSearch}|${sortOrder}`,
+ `${statusFilter}|${impactFilter}|${typeFilter}|${sourceFilter}|${promptFilter}|${topicFilter}|${debouncedSearch}|${sortOrder}`,
);
// The list's filters and search, shared by the page load and the CSV export.
@@ -266,6 +284,7 @@ export default function ContentPage() {
if (statusFilter !== 'all') filters.status = statusFilter;
if (impactFilter !== 'all') filters.impact = impactFilter;
if (typeFilter !== 'all') filters.type = typeFilter;
+ if (sourceFilter !== 'all') filters.source = sourceFilter;
if (promptFilter) filters.promptId = promptFilter;
if (topicFilter) filters.topicId = topicFilter;
if (debouncedSearch.trim()) filters.q = debouncedSearch.trim();
@@ -275,6 +294,7 @@ export default function ContentPage() {
statusFilter,
impactFilter,
typeFilter,
+ sourceFilter,
promptFilter,
topicFilter,
debouncedSearch,
@@ -350,6 +370,7 @@ export default function ContentPage() {
setStatusFilter(readUrlChoice('status', STATUS_VALUES, 'all'));
setImpactFilter(readUrlChoice('impact', IMPACT_VALUES, 'all'));
setTypeFilter(readUrlChoice('type', TYPE_VALUES, 'all'));
+ setSourceFilter(readUrlChoice('source', SOURCE_VALUES, 'all'));
setSortOrder(readUrlChoice('sort', SORT_VALUES, 'score'));
setUrlRead(true);
}, []);
@@ -359,10 +380,16 @@ export default function ContentPage() {
useEffect(() => {
if (!urlRead) return;
writeUrlParams(
- { status: statusFilter, impact: impactFilter, type: typeFilter, sort: sortOrder },
+ {
+ status: statusFilter,
+ impact: impactFilter,
+ type: typeFilter,
+ source: sourceFilter,
+ sort: sortOrder,
+ },
URL_DEFAULTS,
);
- }, [urlRead, statusFilter, impactFilter, typeFilter, sortOrder]);
+ }, [urlRead, statusFilter, impactFilter, typeFilter, sourceFilter, sortOrder]);
const selectOpportunity = useCallback((opportunityId: string | null) => {
setOpenOpportunityId(opportunityId);
@@ -445,7 +472,7 @@ export default function ContentPage() {
return () => {
cancelled = true;
};
- }, [activeBrandId, total]);
+ }, [activeBrandId, total, usageVersion]);
const pollJob = useCallback(
(jobId: string, startedAt: number) => {
@@ -463,25 +490,36 @@ export default function ContentPage() {
pollRef.current = false;
clearGenerationJob();
setGenerating(false);
- toast.success(t('generatedToast', { count: status.result?.generated ?? 0 }));
+ setPendingCount(0);
+ const generated = status.result?.generated ?? 0;
+ const duplicates = status.result?.duplicates ?? 0;
+ if (status.result?.limited) toast.error(t('newLimitReached'));
+ else if (generated === 0 && duplicates === 0) toast(t('newNothing'));
+ else toast.success(t('newDone', { generated, duplicates }));
loadData();
loadPromptOptions();
+ setUsageVersion((v) => v + 1);
break;
}
- if (status.status === 'failed') {
- pollRef.current = false;
- clearGenerationJob();
- setGenerating(false);
- toast.error(status.failedReason || t('generationFailed'));
- break;
- }
-
- if (Date.now() - startedAt > GENERATION_TIMEOUT_MS) {
+ if (status.status === 'failed' || Date.now() - startedAt > GENERATION_TIMEOUT_MS) {
pollRef.current = false;
clearGenerationJob();
setGenerating(false);
- toast.error(t('generationTimedOut'));
+ setPendingCount(0);
+ // Slots it didn't use are handed back on the server; say so.
+ toast.error(
+ status.status === 'failed'
+ ? status.failedReason || t('generationFailed')
+ : t('generationTimedOut'),
+ {
+ description: t('newRefunded'),
+ action: lastRequestRef.current
+ ? { label: t('retry'), onClick: () => retryRef.current?.() }
+ : undefined,
+ },
+ );
+ setUsageVersion((v) => v + 1);
break;
}
} catch {
@@ -500,6 +538,7 @@ export default function ContentPage() {
const saved = loadGenerationJob();
if (!saved || saved.brandId !== activeBrandId) return;
+ setPendingCount(saved.count ?? 0);
pollJob(saved.jobId, saved.startedAt);
return () => {
pollRef.current = false;
@@ -550,19 +589,65 @@ export default function ContentPage() {
}
};
- const handleGenerate = async () => {
- if (!activeBrandId) return;
- try {
- const { jobId } = await generateOpportunities(activeBrandId);
- const startedAt = Date.now();
- saveGenerationJob({ brandId: activeBrandId, jobId, startedAt });
- pollJob(jobId, startedAt);
- } catch (err) {
- console.error('Generate failed:', err);
- toast.error(err instanceof Error ? err.message : t('generateError'));
- setGenerating(false);
+ // "+ New" (CONTENT-003). One idempotency key per submit, so a double click
+ // or a retried request starts one job; returns whether it started.
+ const handleNew = async (input: NewOpportunitiesInput): Promise<boolean> => {
+ if (!activeBrandId) return false;
+ lastRequestRef.current = input;
+ const result = await generateOpportunitiesOnDemand({
+ brandId: activeBrandId,
+ ...input,
+ idempotencyKey: crypto.randomUUID(),
+ }).catch((err: unknown) => ({
+ ok: false as const,
+ error: err instanceof Error ? err.message : t('generateError'),
+ quotaExhausted: false,
+ periodEnd: null,
+ }));
+ if (!result.ok) {
+ toast.error(result.quotaExhausted ? t('newLimitReached') : result.error);
+ setUsageVersion((v) => v + 1);
+ return false;
}
+ const startedAt = Date.now();
+ saveGenerationJob({
+ brandId: activeBrandId,
+ jobId: result.jobId,
+ startedAt,
+ count: result.count,
+ });
+ setPendingCount(result.count);
+ pollJob(result.jobId, startedAt);
+ return true;
};
+ // The failure toast's Retry sends the last request again, with a new key.
+ useEffect(() => {
+ retryRef.current = () => {
+ if (lastRequestRef.current) void handleNew(lastRequestRef.current);
+ };
+ });
+
+ const requestMax = contentUsage ? onDemandMax(contentUsage) : FALLBACK_REQUEST_MAX;
+ const limitReached = hasContentQuota(contentUsage) && requestMax === 0;
+ const resetsOn = contentUsage?.periodEnd
+ ? new Date(contentUsage.periodEnd).toLocaleDateString(locale, {
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC',
+ })
+ : '';
+ const newButton = (
+ <Button
+ onClick={() => setNewOpen(true)}
+ disabled={generating || loading || limitReached}
+ size="sm"
+ className="gap-2"
+ title={limitReached ? t('newLimitTooltip', { date: resetsOn }) : undefined}
+ >
+ {generating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
+ {generating ? t('generating') : t('new')}
+ </Button>
+ );
const handleSendWebhook = async (id: string) => {
setSendingId(id);
@@ -707,6 +792,7 @@ export default function ContentPage() {
statusFilter !== 'all' ||
impactFilter !== 'all' ||
typeFilter !== 'all' ||
+ sourceFilter !== 'all' ||
promptFilter !== '' ||
topicFilter !== '' ||
search.trim() !== '';
@@ -715,6 +801,7 @@ export default function ContentPage() {
setStatusFilter('all');
setImpactFilter('all');
setTypeFilter('all');
+ setSourceFilter('all');
selectPrompt('');
setTopicFilter('');
setSearch('');
@@ -736,6 +823,7 @@ export default function ContentPage() {
<p className="text-muted-foreground text-sm">{t('description')}</p>
</div>
<div className="flex items-center gap-2">
+ {newButton}
<Button
onClick={handleExportCsv}
disabled={exporting || loading || total === 0}
@@ -759,27 +847,6 @@ export default function ContentPage() {
<Settings2 className="h-4 w-4" />
{t('webhook.title')}
</Button>
- {!isCloud && (
- <Button
- onClick={handleGenerate}
- disabled={generating || loading}
- size="sm"
- className="gap-2"
- >
- {generating ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : opportunities.length > 0 ? (
- <RefreshCw className="h-4 w-4" />
- ) : (
- <Lightbulb className="h-4 w-4" />
- )}
- {generating
- ? t('generating')
- : opportunities.length > 0
- ? t('regenerate')
- : t('generate')}
- </Button>
- )}
</div>
</div>
@@ -795,18 +862,8 @@ export default function ContentPage() {
<p className="text-sm font-medium">{t('noOpportunities')}</p>
<p className="text-xs text-muted-foreground">{t('noOpportunitiesHint')}</p>
</div>
- {!isCloud ? (
- <Button onClick={handleGenerate} disabled={generating} size="sm" className="gap-2">
- {generating ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Lightbulb className="h-4 w-4" />
- )}
- {generating ? t('generating') : t('generate')}
- </Button>
- ) : (
- <p className="text-xs text-muted-foreground">{t('autoGeneratedHint')}</p>
- )}
+ {newButton}
+ <p className="text-xs text-muted-foreground">{t('autoGeneratedHint')}</p>
</CardContent>
</Card>
) : (
@@ -985,6 +1042,30 @@ export default function ContentPage() {
<SelectItem value="low">{t('impact.low')}</SelectItem>
</SelectContent>
</Select>
+ <Select value={sourceFilter} onValueChange={(v) => v && setSourceFilter(v)}>
+ <SelectTrigger className="h-8 w-[130px] text-xs" aria-label={t('source.label')}>
+ <SelectValue>
+ {(value) =>
+ value === 'all'
+ ? t('filters.allSources')
+ : t(`source.${value as 'system' | 'manual' | 'prompt'}`)
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t('filters.allSources')}</SelectItem>
+ {(['system', 'manual', 'prompt'] as const).map((value) => (
+ <SelectItem key={value} value={value}>
+ <span className="flex flex-col">
+ <span>{t(`source.${value}`)}</span>
+ <span className="text-[11px] text-muted-foreground">
+ {t(`sourceHint.${value}`)}
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
<Select value={statusFilter} onValueChange={(v) => v && setStatusFilter(v)}>
<SelectTrigger className="h-8 w-[130px] text-xs">
<SelectValue>
@@ -1155,6 +1236,30 @@ export default function ContentPage() {
</TableRow>
</TableHeader>
<TableBody>
+ {Array.from({ length: pendingCount }, (_, i) => (
+ <TableRow key={`pending-${i}`} aria-busy="true">
+ <TableCell className="w-10 pl-4" />
+ <TableCell className="pl-6">
+ <Skeleton className="h-4 w-4/5" />
+ <Skeleton className="mt-1.5 h-3 w-3/5" />
+ </TableCell>
+ <TableCell className="text-center">
+ <Skeleton className="mx-auto h-5 w-14" />
+ </TableCell>
+ <TableCell className="text-center">
+ <Skeleton className="mx-auto h-5 w-14" />
+ </TableCell>
+ <TableCell className="text-center">
+ <Skeleton className="mx-auto h-4 w-6" />
+ </TableCell>
+ <TableCell className="text-center">
+ <Badge variant="outline" className="text-xs text-muted-foreground">
+ {t('generatingRow')}
+ </Badge>
+ </TableCell>
+ <TableCell />
+ </TableRow>
+ ))}
{filtered.map((opp) => (
<TableRow key={opp.id} className="hover:bg-muted/50">
<TableCell className="w-10 pl-4">
@@ -1183,6 +1288,16 @@ export default function ContentPage() {
{t('newSignal')}
</Badge>
)}
+ {/* Before the title, which is clamped to one line. */}
+ {opp.source && opp.source !== 'system' && (
+ <Badge
+ variant="outline"
+ className="mr-1.5 align-middle text-[10px] font-normal text-muted-foreground"
+ title={t(`sourceHint.${opp.source}`)}
+ >
+ {t(`source.${opp.source}`)}
+ </Badge>
+ )}
{opp.title}
</p>
{opp.description && (
@@ -1337,6 +1452,14 @@ export default function ContentPage() {
onOpenChange={setWebhookOpen}
brandId={activeBrandId}
/>
+ <NewOpportunitiesDialog
+ open={newOpen}
+ onOpenChange={setNewOpen}
+ brandId={activeBrandId}
+ max={requestMax}
+ remaining={contentUsage?.opportunities.remaining ?? -1}
+ onSubmit={handleNew}
+ />
</div>
);
}
diff --git a/web/src/components/content/new-opportunities-dialog.tsx b/web/src/components/content/new-opportunities-dialog.tsx
new file mode 100644
index 000000000..1dc67665f
--- /dev/null
+++ b/web/src/components/content/new-opportunities-dialog.tsx
@@ -0,0 +1,290 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Loader2, Minus, Plus, Sparkles } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import {
+ Combobox,
+ ComboboxCollection,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+ ComboboxValue,
+} from '@/components/ui/combobox';
+import { Textarea } from '@/components/ui/textarea';
+import { cn } from '@/lib/utils';
+import { getTopics } from '@/lib/actions/topic';
+import { getBrandPrompts } from '@/lib/actions/tracking';
+
+export type NewOpportunitiesFocus = 'auto' | 'topic' | 'prompt';
+
+export interface NewOpportunitiesInput {
+ count: number;
+ topicId: string | null;
+ promptId: string | null;
+ idea: string | null;
+}
+
+/** Longest idea the server accepts (IDEA_MAX_LENGTH in opportunity-generator.js). */
+const IDEA_MAX_LENGTH = 500;
+
+const DEFAULT_COUNT = 3;
+
+interface Option {
+ value: string;
+ label: string;
+}
+
+/**
+ * "+ New" (CONTENT-003): generate opportunities now, optionally around a
+ * topic, a prompt or a free-text idea. The count is capped by `max` — the
+ * plan's per-request limit, never more than what is left of the month — and
+ * the dialog says what the request will use before it is sent.
+ */
+export function NewOpportunitiesDialog({
+ open,
+ onOpenChange,
+ ...form
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ brandId: string;
+ /** Most this request may ask for. */
+ max: number;
+ /** What is left of the month; -1 when unlimited. */
+ remaining: number;
+ onSubmit: (input: NewOpportunitiesInput) => Promise<boolean>;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ {/* Mounted per opening, so every opening starts from a fresh form. */}
+ {open && <NewOpportunitiesForm {...form} onClose={() => onOpenChange(false)} />}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function NewOpportunitiesForm({
+ brandId,
+ max,
+ remaining,
+ onSubmit,
+ onClose,
+}: {
+ brandId: string;
+ max: number;
+ remaining: number;
+ onSubmit: (input: NewOpportunitiesInput) => Promise<boolean>;
+ onClose: () => void;
+}) {
+ const t = useTranslations('content.newDialog');
+ const tCommon = useTranslations('common');
+ const [focus, setFocus] = useState<NewOpportunitiesFocus>('auto');
+ const [topicId, setTopicId] = useState('');
+ const [prompt, setPrompt] = useState<Option | null>(null);
+ const [idea, setIdea] = useState('');
+ const [count, setCount] = useState(() => Math.max(1, Math.min(DEFAULT_COUNT, max)));
+ const [submitting, setSubmitting] = useState(false);
+ const [topics, setTopics] = useState<Option[]>([]);
+ const [prompts, setPrompts] = useState<Option[]>([]);
+
+ // The brand's topics and prompts, not only the ones that already have
+ // opportunities.
+ useEffect(() => {
+ let cancelled = false;
+ Promise.all([getTopics(brandId), getBrandPrompts(brandId)]).then(
+ ([topicRows, promptRows]) => {
+ if (cancelled) return;
+ setTopics(
+ topicRows.filter((tp) => tp.isActive).map((tp) => ({ value: tp.id, label: tp.name })),
+ );
+ setPrompts(promptRows.map((p) => ({ value: p.id, label: p.text })));
+ },
+ () => undefined,
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId]);
+
+ const focusReady =
+ focus === 'auto' || (focus === 'topic' && !!topicId) || (focus === 'prompt' && !!prompt);
+ const canSubmit = max > 0 && count >= 1 && count <= max && focusReady && !submitting;
+
+ const submit = async () => {
+ if (!canSubmit) return;
+ setSubmitting(true);
+ const ok = await onSubmit({
+ count,
+ topicId: focus === 'topic' ? topicId : null,
+ promptId: focus === 'prompt' ? (prompt?.value ?? null) : null,
+ idea: idea.trim() || null,
+ });
+ setSubmitting(false);
+ if (ok) onClose();
+ };
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t('title')}</DialogTitle>
+ <DialogDescription>{t('description')}</DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ <div className="space-y-1.5">
+ <p className="text-xs font-medium text-muted-foreground">{t('focus')}</p>
+ <div className="flex flex-wrap gap-1.5">
+ {(['auto', 'topic', 'prompt'] as const).map((f) => (
+ <Button
+ key={f}
+ type="button"
+ size="sm"
+ variant={focus === f ? 'default' : 'outline'}
+ className="h-7 text-xs"
+ aria-pressed={focus === f}
+ onClick={() => setFocus(f)}
+ >
+ {t(`focusOptions.${f}`)}
+ </Button>
+ ))}
+ </div>
+ {focus === 'topic' && (
+ <Select value={topicId} onValueChange={(v) => setTopicId((v as string) ?? '')}>
+ <SelectTrigger className="h-8 w-full text-xs">
+ <SelectValue placeholder={t('pickTopic')}>
+ {(value) => topics.find((tp) => tp.value === value)?.label ?? t('pickTopic')}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {topics.map((tp) => (
+ <SelectItem key={tp.value} value={tp.value}>
+ {tp.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ {focus === 'prompt' && (
+ <Combobox
+ items={prompts}
+ value={prompt}
+ onValueChange={(item: Option | null) => setPrompt(item)}
+ >
+ <ComboboxTrigger className="h-8 w-full text-xs" title={prompt?.label}>
+ <ComboboxValue placeholder={t('pickPrompt')} />
+ </ComboboxTrigger>
+ <ComboboxContent>
+ <ComboboxInput placeholder={tCommon('searchPrompts')} />
+ <ComboboxList>
+ <ComboboxEmpty>{tCommon('noPromptsMatch')}</ComboboxEmpty>
+ <ComboboxCollection>
+ {(item: Option) => (
+ <ComboboxItem key={item.value} value={item} title={item.label}>
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
+ </ComboboxItem>
+ )}
+ </ComboboxCollection>
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )}
+ </div>
+
+ <div className="space-y-1.5">
+ <label
+ htmlFor="new-opportunities-idea"
+ className="text-xs font-medium text-muted-foreground"
+ >
+ {t('idea')}
+ </label>
+ <Textarea
+ id="new-opportunities-idea"
+ value={idea}
+ onChange={(e) => setIdea(e.target.value.slice(0, IDEA_MAX_LENGTH))}
+ placeholder={t('ideaPlaceholder')}
+ rows={2}
+ className="text-sm"
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <p className="text-xs font-medium text-muted-foreground">{t('count')}</p>
+ <div className="flex items-center gap-3">
+ <div className="inline-flex items-center rounded-md border">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('fewer')}
+ disabled={count <= 1}
+ onClick={() => setCount((n) => Math.max(1, n - 1))}
+ >
+ <Minus className="h-3.5 w-3.5" />
+ </Button>
+ <span className="w-8 text-center text-sm font-semibold tabular-nums">{count}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('more')}
+ disabled={count >= max}
+ onClick={() => setCount((n) => Math.min(max, n + 1))}
+ >
+ <Plus className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ <span className="text-xs text-muted-foreground">{t('max', { max })}</span>
+ </div>
+ </div>
+
+ <p
+ className={cn(
+ 'rounded-md border bg-muted/40 px-3 py-2 text-xs',
+ max === 0 && 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
+ )}
+ >
+ {max === 0
+ ? t('noneLeft')
+ : remaining === -1
+ ? t('usesUnlimited', { count })
+ : t('uses', { count, remaining, after: Math.max(0, remaining - count) })}
+ </p>
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose} disabled={submitting}>
+ {tCommon('cancel')}
+ </Button>
+ <Button onClick={submit} disabled={!canSubmit} className="gap-2">
+ {submitting ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Sparkles className="h-4 w-4" />
+ )}
+ {t('generate', { count })}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+}
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index 9b2b3d2bd..889285879 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -56,6 +56,11 @@ export interface PlanLimits {
* customer via organizations.plan_overrides.maxOpportunitiesPerMonth.
*/
maxOpportunitiesPerMonth: number;
+ /**
+ * Opportunities one "+ New" request may ask for (CONTENT-003), always capped
+ * by what is left of the month. Starter 3, Growth 5.
+ */
+ maxOpportunitiesPerRequest: number;
/**
* Monthly Site Audit runs. -1 = unlimited (self-hosted / enterprise).
* Starter 100, Growth 500.
@@ -99,6 +104,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxBriefGenerations: -1,
improveMonthlyBudgetUsd: -1,
maxOpportunitiesPerMonth: -1,
+ maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
@@ -136,6 +142,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxBriefGenerations: 10,
improveMonthlyBudgetUsd: 0,
maxOpportunitiesPerMonth: 10,
+ maxOpportunitiesPerRequest: 3,
maxSiteAudits: 100,
maxDailyOnDemand: 3,
onDemandCooldownMinutes: 15,
@@ -177,6 +184,7 @@ export const PLANS: Record<PlanId, Plan> = {
// 1% of the $249 price, spent on Improve model calls (PROMPT-003).
improveMonthlyBudgetUsd: 2.49,
maxOpportunitiesPerMonth: 50,
+ maxOpportunitiesPerRequest: 5,
maxSiteAudits: 500,
maxDailyOnDemand: 10,
onDemandCooldownMinutes: 5,
@@ -218,6 +226,7 @@ export const PLANS: Record<PlanId, Plan> = {
// of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.
improveMonthlyBudgetUsd: 4.99,
maxOpportunitiesPerMonth: -1,
+ maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 4012ed313..d3ed704f2 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -16,31 +16,58 @@ async function getSession() {
return session;
}
-export async function generateOpportunities(brandId: string): Promise<{ jobId: string }> {
+/** What a "+ New" request asks for (CONTENT-003). */
+export interface OnDemandRequest {
+ brandId: string;
+ count: number;
+ topicId?: string | null;
+ promptId?: string | null;
+ idea?: string | null;
+ /** One per submit, so a double click or a retried request starts one job. */
+ idempotencyKey: string;
+}
+
+export type OnDemandResult =
+ | { ok: true; jobId: string; count: number }
+ | { ok: false; error: string; quotaExhausted?: boolean; periodEnd?: string | null };
+
+/** Starts generating opportunities now ("+ New"); errors come back as values. */
+export async function generateOpportunitiesOnDemand(
+ request: OnDemandRequest,
+): Promise<OnDemandResult> {
const session = await getSession();
- const res = await fetch(`${AEO_SERVER_URL}/api/content/generate`, {
+ const res = await fetch(`${AEO_SERVER_URL}/api/content/opportunities/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${session.access_token}`,
},
- body: JSON.stringify({ brandId }),
+ body: JSON.stringify(request),
});
+ const body = await res.json().catch(() => ({}));
if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || `Server error: ${res.status}`);
+ return {
+ ok: false,
+ error: body.message || body.error || `Server error: ${res.status}`,
+ quotaExhausted: body.error === 'quota_exhausted',
+ periodEnd: body.periodEnd ?? null,
+ };
}
-
- const data = await res.json();
- return { jobId: data.jobId };
+ return { ok: true, jobId: body.jobId, count: body.count };
}
export interface GenerationJobStatus {
status: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'not_found';
progress: { phase: string; message: string } | null;
- result: { generated: number } | null;
+ result: {
+ generated: number;
+ /** Skipped as duplicates of existing opportunities (CONTENT-004); not counted. */
+ duplicates?: number;
+ /** The month's quota ran out before anything could be generated. */
+ limited?: boolean;
+ } | null;
failedReason: string | null;
}
@@ -86,6 +113,7 @@ export async function getOpportunities(
type?: string;
promptId?: string;
topicId?: string;
+ source?: string;
limit?: number;
offset?: number;
sort?: string;
@@ -109,6 +137,7 @@ export async function getOpportunities(
if (filters?.type) params.set('type', filters.type);
if (filters?.promptId) params.set('prompt_id', filters.promptId);
if (filters?.topicId) params.set('topic_id', filters.topicId);
+ if (filters?.source) params.set('source', filters.source);
if (filters?.limit) params.set('limit', String(filters.limit));
if (filters?.offset) params.set('offset', String(filters.offset));
if (filters?.sort) params.set('sort', filters.sort);
diff --git a/web/src/lib/content-usage.test.ts b/web/src/lib/content-usage.test.ts
index 5ab90a6a4..b51cc46fa 100644
--- a/web/src/lib/content-usage.test.ts
+++ b/web/src/lib/content-usage.test.ts
@@ -5,7 +5,13 @@
*/
import { describe, expect, test } from 'vitest';
-import { hasContentQuota, usagePercent, usageTone, type ContentUsage } from './content-usage';
+import {
+ hasContentQuota,
+ onDemandMax,
+ usagePercent,
+ usageTone,
+ type ContentUsage,
+} from './content-usage';
const c = (used: number, limit: number) => ({ used, limit, remaining: Math.max(0, limit - used) });
@@ -37,7 +43,7 @@ describe('hasContentQuota', () => {
planName: 'Starter',
periodStart: null,
periodEnd: null,
- opportunities: c(0, o),
+ opportunities: { ...c(0, o), perRequest: 3 },
briefs: c(0, b),
});
@@ -48,3 +54,22 @@ describe('hasContentQuota', () => {
expect(hasContentQuota(null)).toBe(false);
});
});
+
+describe('onDemandMax', () => {
+ const usage = (used: number, limit: number, perRequest: number): ContentUsage => ({
+ plan: 'growth',
+ planName: 'Growth',
+ periodStart: null,
+ periodEnd: null,
+ opportunities: { ...c(used, limit), perRequest },
+ briefs: c(0, 50),
+ });
+
+ test('is the per-request cap, never more than what is left', () => {
+ expect(onDemandMax(usage(10, 50, 5))).toBe(5);
+ expect(onDemandMax(usage(48, 50, 5))).toBe(2);
+ expect(onDemandMax(usage(10, 10, 3))).toBe(0);
+ expect(onDemandMax(usage(0, -1, 5))).toBe(5);
+ expect(onDemandMax(null)).toBe(0);
+ });
+});
diff --git a/web/src/lib/content-usage.ts b/web/src/lib/content-usage.ts
index d29cd81cb..bd3499c7c 100644
--- a/web/src/lib/content-usage.ts
+++ b/web/src/lib/content-usage.ts
@@ -17,10 +17,23 @@ export interface ContentUsage {
planName: string | null;
periodStart: string | null;
periodEnd: string | null;
- opportunities: UsageCounter;
+ opportunities: UsageCounter & {
+ /** Most one "+ New" request may ask for: Starter 3, Growth 5. */
+ perRequest: number;
+ };
briefs: UsageCounter;
}
+/**
+ * How many one "+ New" request may ask for (CONTENT-003): the plan's
+ * per-request cap, never more than is left of the month.
+ */
+export function onDemandMax(usage: ContentUsage | null): number {
+ if (!usage) return 0;
+ const { perRequest, remaining, limit } = usage.opportunities;
+ return limit === -1 ? perRequest : Math.max(0, Math.min(perRequest, remaining));
+}
+
export type UsageTone = 'normal' | 'warning' | 'exhausted' | 'unlimited';
/** Warning from 80% of the limit, exhausted at 100%. */
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index cd88e2ccb..85738f600 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -293,6 +293,8 @@ export interface ContentBrief {
callToAction: string;
}
+export type ContentOpportunitySource = 'system' | 'manual' | 'prompt';
+
export interface ContentOpportunity {
id: string;
brandId: string;
@@ -305,6 +307,8 @@ export interface ContentOpportunity {
impact: ContentOpportunityImpact;
opportunityScore: number;
status: ContentOpportunityStatus;
+ /** Where it came from: the nightly run, "+ New", or a prompt (CONTENT-003). */
+ source?: ContentOpportunitySource;
sourceData: ContentOpportunitySourceData;
brief?: ContentBrief;
webhookSentAt?: string;