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): filter opportunities by prompt (#854)

Gökhan Geyik844624085dc0
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index 28d0fb44d..8cbc350f7 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -13,6 +13,7 @@ import { runContentJob } from '../lib/job-runner.js';
import { resolveModel } from '../lib/ai-provider.js';
import { getLanguageName } from '../lib/languages.js';
import supabaseAdmin from '../config/supabase.js';
+import { selectInChunks } from '../lib/chunked-in.js';
import {
assertBrandAccess,
assertOpportunitiesAccess,
@@ -129,7 +130,17 @@ router.get('/job/:jobId', async (req, res) => {
router.get('/brand/:brandId', async (req, res) => {
try {
const { brandId } = req.params;
- const { status, impact, type, q, limit = 50, offset = 0, sort = 'score' } = req.query;
+ await assertBrandAccess(brandId, req.user.id);
+ const {
+ status,
+ impact,
+ type,
+ q,
+ prompt_id: promptId,
+ limit = 50,
+ offset = 0,
+ sort = 'score',
+ } = req.query;
const search = q ? String(q).replace(/[,()]/g, ' ') : null;
const applyFilters = (query) => {
@@ -147,6 +158,10 @@ router.get('/brand/:brandId', async (req, res) => {
filteredQuery = filteredQuery.eq('type', type);
}
+ if (promptId) {
+ filteredQuery = filteredQuery.eq('prompt_id', promptId);
+ }
+
if (q) {
filteredQuery = filteredQuery.or(`title.ilike.%${search}%,description.ilike.%${search}%`);
}
@@ -176,6 +191,7 @@ router.get('/brand/:brandId', async (req, res) => {
p_impact: impact ? String(impact) : null,
p_type: type ? String(type) : null,
p_q: search,
+ p_prompt_id: promptId ? String(promptId) : null,
});
const [{ data, error: dataError, count }, { data: aggregateData, error: aggregateError }] =
@@ -209,13 +225,62 @@ router.get('/brand/:brandId', async (req, res) => {
} catch (error) {
req.log.error({ err: error }, 'list opportunities error');
- return res.status(500).json({
+ return res.status(error.status || 500).json({
error: 'Failed to list opportunities',
details: error.message,
});
}
});
+const FACET_PAGE_SIZE = 1000;
+
+/**
+ * GET /api/content/brand/:brandId/prompts
+ * The prompts this brand's opportunities belong to, with how many each has,
+ * most first — the options for the Content page's prompt filter (#836).
+ * Opportunities whose prompt was deleted are left out: there is nothing to
+ * name them by.
+ */
+router.get('/brand/:brandId/prompts', async (req, res) => {
+ try {
+ const { brandId } = req.params;
+ await assertBrandAccess(brandId, req.user.id);
+
+ // Paged: PostgREST caps a response at 1,000 rows and a large brand holds
+ // more opportunities than that.
+ const counts = new Map();
+ for (let from = 0; ; from += FACET_PAGE_SIZE) {
+ const { data, error } = await supabaseAdmin
+ .from('content_opportunities')
+ .select('prompt_id')
+ .eq('brand_id', brandId)
+ .not('prompt_id', 'is', null)
+ .order('id')
+ .range(from, from + FACET_PAGE_SIZE - 1);
+ if (error) throw new Error(error.message);
+ for (const row of data || []) {
+ counts.set(row.prompt_id, (counts.get(row.prompt_id) || 0) + 1);
+ }
+ if (!data || data.length < FACET_PAGE_SIZE) break;
+ }
+
+ const { data: prompts, error: promptError } = await selectInChunks(
+ [...counts.keys()],
+ (chunk) => supabaseAdmin.from('prompts').select('id, text').in('id', chunk),
+ );
+ if (promptError) throw new Error(promptError.message);
+
+ return res.json({
+ prompts: (prompts || [])
+ .map((p) => ({ promptId: p.id, text: p.text, count: counts.get(p.id) || 0 }))
+ .sort((a, b) => b.count - a.count || a.text.localeCompare(b.text)),
+ });
+ } catch (error) {
+ req.log.error({ err: error }, 'list opportunity prompts error');
+ return res.status(error.status || 500).json({ error: 'Failed to list opportunity prompts' });
+ }
+});
+
/**
* POST /api/content/bulk/status
* Update the status of multiple opportunities at once.
diff --git a/supabase/migrations/00099_content_aggregates_prompt_filter.sql b/supabase/migrations/00099_content_aggregates_prompt_filter.sql
new file mode 100644
index 000000000..b3a86d67a
--- /dev/null
+++ b/supabase/migrations/00099_content_aggregates_prompt_filter.sql
@@ -0,0 +1,59 @@
+-- Content opportunities can be filtered by prompt (#836).
+--
+-- The list query takes the new filter directly; the summary cards above it
+-- come from this aggregate, which has to take the same filter or it would
+-- keep describing the whole brand while the list shows one prompt.
+--
+-- The old five-argument version is dropped rather than overloaded: PostgREST
+-- resolves RPCs by argument names, and two candidates that both accept the
+-- same five names would be ambiguous.
+
+drop function if exists public.content_opportunity_aggregates(uuid, text, text, text, text);
+
+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
+)
+returns table (
+ avg_score numeric,
+ high_impact_count bigint,
+ sent_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
+ from public.content_opportunities co
+ where co.brand_id = p_brand_id
+ and (p_status is null 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_prompt_id is null or co.prompt_id = p_prompt_id)
+ 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
+) to authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index b820f6d86..69d57584c 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -11621,3 +11621,66 @@ $$;
GRANT EXECUTE ON FUNCTION public.topics_overview_aggregates(uuid) TO authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00099_content_aggregates_prompt_filter.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Content opportunities can be filtered by prompt (#836).
+--
+-- The list query takes the new filter directly; the summary cards above it
+-- come from this aggregate, which has to take the same filter or it would
+-- keep describing the whole brand while the list shows one prompt.
+--
+-- The old five-argument version is dropped rather than overloaded: PostgREST
+-- resolves RPCs by argument names, and two candidates that both accept the
+-- same five names would be ambiguous.
+
+drop function if exists public.content_opportunity_aggregates(uuid, text, text, text, text);
+
+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
+)
+returns table (
+ avg_score numeric,
+ high_impact_count bigint,
+ sent_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
+ from public.content_opportunities co
+ where co.brand_id = p_brand_id
+ and (p_status is null 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_prompt_id is null or co.prompt_id = p_prompt_id)
+ 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
+) to authenticated;
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index b1a177d2c..216776150 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useState, useEffect, useCallback, useRef } from 'react';
+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useTranslations } from 'next-intl';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -14,6 +14,17 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
+import {
+ Combobox,
+ ComboboxCollection,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+ ComboboxValue,
+} from '@/components/ui/combobox';
import {
Dialog,
DialogClose,
@@ -53,6 +64,8 @@ import {
generateOpportunities,
getGenerationJobStatus,
getOpportunities,
+ getOpportunityPrompts,
+ type OpportunityPrompt,
updateOpportunityStatus,
sendToWebhook,
bulkSendToWebhook,
@@ -142,6 +155,15 @@ function KpiCard({
);
}
+const ALL_PROMPTS = '__all__';
+
+interface PromptFilterItem {
+ value: string;
+ label: string;
+ /** Opportunities for this prompt; null on the "All prompts" row. */
+ count: number | null;
+}
+
export default function ContentPage() {
const t = useTranslations('content');
const tCommon = useTranslations('common');
@@ -158,6 +180,14 @@ export default function ContentPage() {
const [statusFilter, setStatusFilter] = useState<string>('all');
const [impactFilter, setImpactFilter] = useState<string>('all');
const [typeFilter, setTypeFilter] = useState<string>('all');
+ // 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
+ // a Suspense boundary around the page — and loading waits for it, so a
+ // linked view never flashes the unfiltered list first.
+ const [promptFilter, setPromptFilter] = useState('');
+ const [urlRead, setUrlRead] = useState(false);
+ // null until loaded for the current brand.
+ const [promptOptions, setPromptOptions] = useState<OpportunityPrompt[] | null>(null);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [bulkSending, setBulkSending] = useState(false);
@@ -176,11 +206,12 @@ export default function ContentPage() {
// pager instead of the length of whatever page happens to be loaded.
const pager = usePagination(
total,
- `${statusFilter}|${impactFilter}|${typeFilter}|${debouncedSearch}`,
+ `${statusFilter}|${impactFilter}|${typeFilter}|${promptFilter}|${debouncedSearch}`,
);
const loadData = useCallback(
async (silent = false, isCancelled?: () => boolean) => {
+ if (!urlRead) return;
if (!activeBrandId) {
setOpportunities([]);
setTotal(0);
@@ -200,6 +231,7 @@ export default function ContentPage() {
if (statusFilter !== 'all') filters.status = statusFilter;
if (impactFilter !== 'all') filters.impact = impactFilter;
if (typeFilter !== 'all') filters.type = typeFilter;
+ if (promptFilter) filters.promptId = promptFilter;
if (debouncedSearch.trim()) {
filters.q = debouncedSearch.trim();
}
@@ -231,7 +263,17 @@ export default function ContentPage() {
}
}
},
- [activeBrandId, statusFilter, impactFilter, typeFilter, pager.start, debouncedSearch, t],
+ [
+ urlRead,
+ activeBrandId,
+ statusFilter,
+ impactFilter,
+ typeFilter,
+ promptFilter,
+ pager.start,
+ debouncedSearch,
+ t,
+ ],
);
useEffect(() => {
@@ -242,6 +284,49 @@ export default function ContentPage() {
return () => clearTimeout(timer);
}, [search]);
+ useEffect(() => {
+ setPromptFilter(new URLSearchParams(window.location.search).get('prompt') ?? '');
+ setUrlRead(true);
+ }, []);
+
+ const selectPrompt = useCallback((promptId: string) => {
+ setPromptFilter(promptId);
+ const url = new URL(window.location.href);
+ if (promptId) url.searchParams.set('prompt', promptId);
+ else url.searchParams.delete('prompt');
+ window.history.replaceState(window.history.state, '', url);
+ }, []);
+
+ const loadPromptOptions = useCallback(
+ async (isCancelled?: () => boolean) => {
+ if (!activeBrandId) return;
+ try {
+ const options = await getOpportunityPrompts(activeBrandId);
+ if (!isCancelled?.()) setPromptOptions(options);
+ } catch {
+ // The filter is a convenience; without its options it just stays hidden.
+ if (!isCancelled?.()) setPromptOptions([]);
+ }
+ },
+ [activeBrandId],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ setPromptOptions(null);
+ loadPromptOptions(() => cancelled);
+ return () => {
+ cancelled = true;
+ };
+ }, [loadPromptOptions]);
+
+ // A prompt id from another brand, or one whose prompt was deleted, would
+ // filter to nothing while the picker shows "All prompts". Drop it.
+ useEffect(() => {
+ if (!promptFilter || promptOptions === null) return;
+ if (!promptOptions.some((o) => o.promptId === promptFilter)) selectPrompt('');
+ }, [promptFilter, promptOptions, selectPrompt]);
+
useEffect(() => {
let cancelled = false;
@@ -270,6 +355,7 @@ export default function ContentPage() {
setGenerating(false);
toast.success(t('generatedToast', { count: status.result?.generated ?? 0 }));
loadData();
+ loadPromptOptions();
break;
}
@@ -296,7 +382,7 @@ export default function ContentPage() {
poll();
},
- [loadData, t],
+ [loadData, loadPromptOptions, t],
);
// Restore generation state from localStorage on mount
useEffect(() => {
@@ -440,6 +526,19 @@ export default function ContentPage() {
(o.description || '').toLowerCase().includes(search.toLowerCase()),
);
+ // `{ value, label }` items let the Combobox filter and display on its own.
+ // One prompt has nothing to narrow, so the picker only appears for two or
+ // more — or while a filter is set, so it can still be cleared.
+ const promptItems = useMemo<PromptFilterItem[]>(
+ () => [
+ { value: ALL_PROMPTS, label: tCommon('allPrompts'), count: null },
+ ...(promptOptions ?? []).map((o) => ({ value: o.promptId, label: o.text, count: o.count })),
+ ],
+ [promptOptions, tCommon],
+ );
+ const showPromptFilter = (promptOptions?.length ?? 0) >= 2 || promptFilter !== '';
+ const promptFilterTitle = promptItems.find((item) => item.value === promptFilter)?.label;
+
/** How many of the selected rows would lose a generated brief (#731). */
const selectedWithBrief = opportunities.filter(
(o) => selectedIds.has(o.id) && Boolean(o.brief),
@@ -454,12 +553,14 @@ export default function ContentPage() {
statusFilter !== 'all' ||
impactFilter !== 'all' ||
typeFilter !== 'all' ||
+ promptFilter !== '' ||
search.trim() !== '';
const clearFilters = () => {
setStatusFilter('all');
setImpactFilter('all');
setTypeFilter('all');
+ selectPrompt('');
setSearch('');
};
@@ -634,6 +735,40 @@ export default function ContentPage() {
<SelectItem value="earned">{t('type.earned')}</SelectItem>
</SelectContent>
</Select>
+ {showPromptFilter && (
+ <Combobox
+ items={promptItems}
+ value={
+ promptItems.find((item) => item.value === (promptFilter || ALL_PROMPTS)) ??
+ null
+ }
+ onValueChange={(item: PromptFilterItem | null) =>
+ selectPrompt(!item || item.value === ALL_PROMPTS ? '' : item.value)
+ }
+ >
+ <ComboboxTrigger className="h-8 w-56 text-xs" title={promptFilterTitle}>
+ <ComboboxValue placeholder={tCommon('allPrompts')} />
+ </ComboboxTrigger>
+ <ComboboxContent>
+ <ComboboxInput placeholder={tCommon('searchPrompts')} />
+ <ComboboxList>
+ <ComboboxEmpty>{tCommon('noPromptsMatch')}</ComboboxEmpty>
+ <ComboboxCollection>
+ {(item: PromptFilterItem) => (
+ <ComboboxItem key={item.value} value={item} title={item.label}>
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
+ {item.count !== null && (
+ <span className="ml-2 shrink-0 tabular-nums text-muted-foreground">
+ {item.count}
+ </span>
+ )}
+ </ComboboxItem>
+ )}
+ </ComboboxCollection>
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )}
</div>
</div>
</CardHeader>
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 505fa35f8..08d0fec8e 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -83,6 +83,7 @@ export async function getOpportunities(
impact?: string;
q?: string;
type?: string;
+ promptId?: string;
limit?: number;
offset?: number;
sort?: string;
@@ -103,6 +104,7 @@ export async function getOpportunities(
if (filters?.impact) params.set('impact', filters.impact);
if (filters?.q) params.set('q', filters.q);
if (filters?.type) params.set('type', filters.type);
+ if (filters?.promptId) params.set('prompt_id', filters.promptId);
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);
@@ -123,6 +125,31 @@ export async function getOpportunities(
return res.json();
}
+export interface OpportunityPrompt {
+ promptId: string;
+ text: string;
+ /** Opportunities generated for this prompt, across every status. */
+ count: number;
+}
+
+/** The prompts a brand's opportunities belong to, most opportunities first (#836). */
+export async function getOpportunityPrompts(brandId: string): Promise<OpportunityPrompt[]> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/content/brand/${brandId}/prompts`, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.error || `Server error: ${res.status}`);
+ }
+
+ const body = (await res.json()) as { prompts: OpportunityPrompt[] };
+ return body.prompts;
+}
+
export async function getOpportunity(id: string): Promise<ContentOpportunity> {
const session = await getSession();