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.

fix: calculate content metrics across all opportunities (#700)

Bharadwajjjjj6c7ba4b0640c
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index 6e9fd16e5..ddf4a7167 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -131,38 +131,84 @@ router.get('/brand/:brandId', async (req, res) => {
const { brandId } = req.params;
const { status, impact, type, q, limit = 50, offset = 0, sort = 'score' } = req.query;
- let query = supabaseAdmin
- .from('content_opportunities')
- .select('*', { count: 'exact' })
- .eq('brand_id', brandId);
+ const search = q ? String(q).replace(/[,()]/g, ' ') : null;
+ const applyFilters = (query) => {
+ let filteredQuery = query.eq('brand_id', brandId);
- if (status) query = query.eq('status', status);
- if (impact) query = query.eq('impact', impact);
- if (type) query = query.eq('type', type);
+ if (status) {
+ filteredQuery = filteredQuery.eq('status', status);
+ }
- if (q) {
- const search = String(q).replace(/[,()]/g, ' ');
- query = query.or(`title.ilike.%${search}%,description.ilike.%${search}%`);
- }
+ if (impact) {
+ filteredQuery = filteredQuery.eq('impact', impact);
+ }
+
+ if (type) {
+ filteredQuery = filteredQuery.eq('type', type);
+ }
+
+ if (q) {
+ filteredQuery = filteredQuery.or(`title.ilike.%${search}%,description.ilike.%${search}%`);
+ }
+
+ return filteredQuery;
+ };
+
+ let dataQuery = supabaseAdmin.from('content_opportunities').select('*', { count: 'exact' });
+
+ dataQuery = applyFilters(dataQuery);
if (sort === 'score') {
- query = query.order('opportunity_score', { ascending: false });
+ dataQuery = dataQuery.order('opportunity_score', {
+ ascending: false,
+ });
} else if (sort === 'newest') {
- query = query.order('created_at', { ascending: false });
+ dataQuery = dataQuery.order('created_at', {
+ ascending: false,
+ });
}
- query = query.range(Number(offset), Number(offset) + Number(limit) - 1);
+ dataQuery = dataQuery.range(Number(offset), Number(offset) + Number(limit) - 1);
+
+ const aggregateQuery = supabaseAdmin.rpc('content_opportunity_aggregates', {
+ p_brand_id: brandId,
+ p_status: status ? String(status) : null,
+ p_impact: impact ? String(impact) : null,
+ p_type: type ? String(type) : null,
+ p_q: search,
+ });
- const { data, error, count } = await query;
+ const [{ data, error: dataError, count }, { data: aggregateData, error: aggregateError }] =
+ await Promise.all([dataQuery, aggregateQuery]);
- if (error) throw new Error(error.message);
+ if (dataError) {
+ throw new Error(dataError.message);
+ }
+
+ if (aggregateError) {
+ throw new Error(aggregateError.message);
+ }
+
+ const aggregates = aggregateData?.[0] ?? {
+ avg_score: 0,
+ high_impact_count: 0,
+ sent_count: 0,
+ };
return res.json({
opportunities: (data || []).map(mapOpportunityRow),
+
total: count || 0,
+
+ aggregates: {
+ avgScore: Math.round(Number(aggregates.avg_score) || 0),
+ highImpactCount: Number(aggregates.high_impact_count) || 0,
+ sentCount: Number(aggregates.sent_count) || 0,
+ },
});
} catch (error) {
req.log.error({ err: error }, 'list opportunities error');
+
return res.status(500).json({
error: 'Failed to list opportunities',
details: error.message,
diff --git a/supabase/migrations/00050_content_opportunity_aggregates.sql b/supabase/migrations/00050_content_opportunity_aggregates.sql
new file mode 100644
index 000000000..bc541f003
--- /dev/null
+++ b/supabase/migrations/00050_content_opportunity_aggregates.sql
@@ -0,0 +1,44 @@
+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
+)
+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_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
+) TO authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index e3684a78b..94961d9e2 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -5101,3 +5101,51 @@ CREATE INDEX IF NOT EXISTS idx_cloro_pending_tasks_submitted_at
-- nothing, which is the intent — task ids are provider-side handles.
ALTER TABLE public.cloro_pending_tasks ENABLE ROW LEVEL SECURITY;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00050_content_opportunity_aggregates.sql
+-- ─────────────────────────────────────────────────────────────────────────
+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
+)
+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_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
+) 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 ecb975cf3..13ab1c338 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -163,6 +163,11 @@ export default function ContentPage() {
const [webhookOpen, setWebhookOpen] = useState(false);
const pollRef = useRef(false);
const [debouncedSearch, setDebouncedSearch] = useState(search);
+ const [aggregates, setAggregates] = useState({
+ avgScore: 0,
+ highImpactCount: 0,
+ sentCount: 0,
+ });
// Server-side paging (#610) — the list can hold far more than one page's
// worth of opportunities, so `total` (the exact server count) drives the
@@ -177,6 +182,11 @@ export default function ContentPage() {
if (!activeBrandId) {
setOpportunities([]);
setTotal(0);
+ setAggregates({
+ avgScore: 0,
+ highImpactCount: 0,
+ sentCount: 0,
+ });
setLoading(false);
return;
}
@@ -201,6 +211,13 @@ export default function ContentPage() {
if (isCancelled?.()) return;
setOpportunities(data.opportunities);
setTotal(data.total);
+ setAggregates(
+ data.aggregates ?? {
+ avgScore: 0,
+ highImpactCount: 0,
+ sentCount: 0,
+ },
+ );
return data.total;
} catch (err) {
console.error('Failed to load opportunities:', err);
@@ -408,15 +425,6 @@ export default function ContentPage() {
(o.description || '').toLowerCase().includes(search.toLowerCase()),
);
- const highImpact = opportunities.filter((o) => o.impact === 'high').length;
- const sentCount = opportunities.filter(
- (o) => o.status === 'sent' || o.status === 'in_progress' || o.status === 'done',
- ).length;
- const avgScore =
- opportunities.length > 0
- ? Math.round(opportunities.reduce((s, o) => s + o.opportunityScore, 0) / opportunities.length)
- : 0;
-
if (!activeBrandId) {
return (
<div className="flex items-center justify-center min-h-[400px]">
@@ -500,19 +508,19 @@ export default function ContentPage() {
<KpiCard
title={t('kpi.highImpact')}
icon={Zap}
- value={highImpact}
+ value={aggregates.highImpactCount}
sub={t('kpi.opportunities')}
/>
<KpiCard
title={t('kpi.avgScore')}
icon={BarChart3}
- value={avgScore}
+ value={aggregates.avgScore}
sub={t('kpi.outOf100')}
/>
<KpiCard
title={t('kpi.sentToWorkflow')}
icon={Send}
- value={sentCount}
+ value={aggregates.sentCount}
sub={t('kpi.sentOrInProgress')}
/>
</div>
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index ee9caff5e..7a9d2acfc 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -87,7 +87,15 @@ export async function getOpportunities(
offset?: number;
sort?: string;
},
-): Promise<{ opportunities: ContentOpportunity[]; total: number }> {
+): Promise<{
+ opportunities: ContentOpportunity[];
+ total: number;
+ aggregates: {
+ avgScore: number;
+ highImpactCount: number;
+ sentCount: number;
+ };
+}> {
const session = await getSession();
const params = new URLSearchParams();