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): monthly quota for content brief generation (#224)

Gökhan Geyik5fb12ab8d32a
diff --git a/server/src/config/plans.js b/server/src/config/plans.js
index 41f05e037..38309f50f 100644
--- a/server/src/config/plans.js
+++ b/server/src/config/plans.js
@@ -14,6 +14,7 @@ export const PLANS = {
maxTeamMembers: -1,
maxDomainsPerBrand: -1,
maxVolumeAnalyses: -1,
+ maxBriefGenerations: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
@@ -41,6 +42,7 @@ export const PLANS = {
maxTeamMembers: 1,
maxDomainsPerBrand: 3,
maxVolumeAnalyses: 4,
+ maxBriefGenerations: 10,
maxDailyOnDemand: 3,
onDemandCooldownMinutes: 15,
allowedScrapers: ['chatgpt-web', 'perplexity-web'],
@@ -69,6 +71,7 @@ export const PLANS = {
maxTeamMembers: 3,
maxDomainsPerBrand: 10,
maxVolumeAnalyses: 10,
+ maxBriefGenerations: 50,
maxDailyOnDemand: 10,
onDemandCooldownMinutes: 5,
features: [
@@ -96,6 +99,8 @@ export const PLANS = {
maxTeamMembers: -1,
maxDomainsPerBrand: -1,
maxVolumeAnalyses: -1,
+ // Per-customer: override via organizations.plan_overrides in the DB.
+ maxBriefGenerations: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index 19685f928..80e22121f 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -16,26 +16,27 @@ export class PlanLimitError extends Error {
}
/**
- * Resolve the user's organization plan from the database.
+ * Enterprise orgs can have per-customer limit overrides stored in
+ * organizations.plan_overrides (jsonb) — mirrors web getOrgPlan().
+ */
+function applyPlanOverrides(plan, org) {
+ if (org?.plan === 'enterprise' && org.plan_overrides && typeof org.plan_overrides === 'object') {
+ return { ...plan, limits: { ...plan.limits, ...org.plan_overrides } };
+ }
+ return plan;
+}
+
+/**
+ * Resolve an organization's plan directly by org id.
* Self-hosted → returns self_hosted plan (unlimited).
*/
-async function resolveOrgPlan(userId) {
+async function resolveOrgPlanByOrgId(orgId) {
if (!isCloud()) return getPlan('self_hosted');
- const { data: profile } = await supabaseAdmin
- .from('profiles')
- .select('organization_id')
- .eq('id', userId)
- .single();
-
- if (!profile?.organization_id) {
- throw new PlanLimitError('No organization found for user.', 400);
- }
-
const { data: org } = await supabaseAdmin
.from('organizations')
- .select('plan, subscription_status')
- .eq('id', profile.organization_id)
+ .select('plan, subscription_status, plan_overrides')
+ .eq('id', orgId)
.single();
// Block feature access for orgs without an active or trialing Stripe
@@ -49,7 +50,34 @@ async function resolveOrgPlan(userId) {
);
}
- return getPlan(org.plan);
+ return applyPlanOverrides(getPlan(org.plan), org);
+}
+
+/**
+ * Resolve the user's organization id, or null if none.
+ */
+export async function getOrgIdForUser(userId) {
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('organization_id')
+ .eq('id', userId)
+ .single();
+ return profile?.organization_id || null;
+}
+
+/**
+ * Resolve the user's organization plan from the database.
+ * Self-hosted → returns self_hosted plan (unlimited).
+ */
+async function resolveOrgPlan(userId) {
+ if (!isCloud()) return getPlan('self_hosted');
+
+ const orgId = await getOrgIdForUser(userId);
+ if (!orgId) {
+ throw new PlanLimitError('No organization found for user.', 400);
+ }
+
+ return resolveOrgPlanByOrgId(orgId);
}
/**
@@ -158,6 +186,56 @@ export async function getVolumeQuotaStatus(userId) {
return { used, limit: maxAnalyses, remaining: maxAnalyses - used };
}
+function startOfCurrentMonth() {
+ const start = new Date();
+ start.setUTCDate(1);
+ start.setUTCHours(0, 0, 0, 0);
+ return start;
+}
+
+async function countBriefUsageThisMonth(orgId) {
+ const { count } = await supabaseAdmin
+ .from('brief_usage')
+ .select('*', { count: 'exact', head: true })
+ .eq('organization_id', orgId)
+ .gte('used_at', startOfCurrentMonth().toISOString());
+ return count || 0;
+}
+
+/**
+ * Enforce the monthly content-brief generation quota for an organization.
+ * Org-based (not user-based) so both the dashboard route and the internal
+ * MCP route charge the same pool. Returns { plan, remaining } on success,
+ * throws PlanLimitError when the quota is exhausted.
+ */
+export async function enforceBriefQuota(orgId) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const max = plan.limits.maxBriefGenerations;
+ if (max === -1) return { plan, remaining: -1 };
+
+ const used = await countBriefUsageThisMonth(orgId);
+ if (used >= max) {
+ throw new PlanLimitError(
+ `Monthly content brief limit reached (${used}/${max}) on the ${plan.name} plan. Resets on the 1st of next month — upgrade for more.`,
+ );
+ }
+
+ return { plan, remaining: max - used };
+}
+
+/**
+ * Get current brief quota status without enforcing.
+ * Returns { used, limit, remaining }.
+ */
+export async function getBriefQuotaStatus(orgId) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const max = plan.limits.maxBriefGenerations;
+ if (max === -1) return { used: 0, limit: -1, remaining: -1 };
+
+ const used = await countBriefUsageThisMonth(orgId);
+ return { used, limit: max, remaining: Math.max(0, max - used) };
+}
+
/**
* Express middleware that attaches req.plan from the authenticated user.
* Must run after auth middleware (req.user must exist).
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index 6915a1d94..c0c7e4b03 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -1,7 +1,13 @@
import { Router } from 'express';
import { generateObject } from 'ai';
import { z } from 'zod';
-import { requireFeature } from '../lib/plan-guard.js';
+import {
+ requireFeature,
+ enforceBriefQuota,
+ getBriefQuotaStatus,
+ getOrgIdForUser,
+ PlanLimitError,
+} from '../lib/plan-guard.js';
import { createJob, getJob } from '../lib/job-manager.js';
import { runContentJob } from '../lib/job-runner.js';
import { resolveModel } from '../lib/ai-provider.js';
@@ -566,9 +572,10 @@ Rules:
* Behavior:
* - opportunity not found → throws Error with `.status = 404`
* - opportunity has a brief AND `force` is false → returns the cached
- * brief with `regenerated: false` (no LLM call)
- * - otherwise runs the LLM, writes the result back, returns
- * `{ brief, generated_at, regenerated: true }`
+ * brief with `regenerated: false` (no LLM call, no quota charge)
+ * - quota exhausted → throws PlanLimitError (statusCode 403/402)
+ * - otherwise runs the LLM, records usage, writes the result back,
+ * returns `{ brief, generated_at, regenerated: true }`
*/
export async function generateBriefForOpportunity(opportunityId, { force = false, model } = {}) {
const { data: opportunity, error: oppErr } = await supabaseAdmin
@@ -593,10 +600,18 @@ export async function generateBriefForOpportunity(opportunityId, { force = false
const { data: brand } = await supabaseAdmin
.from('brands')
- .select('name, industry, description')
+ .select('name, industry, description, organization_id')
.eq('id', opportunity.brand_id)
.single();
+ // Quota is charged to the opportunity's org, and enforced here in the
+ // shared core so the dashboard route and the internal MCP route draw
+ // from the same monthly pool. Cached reads above never hit this.
+ const orgId = brand?.organization_id || null;
+ if (orgId) {
+ await enforceBriefQuota(orgId);
+ }
+
const { data: domains } = await supabaseAdmin
.from('brand_domains')
.select('domain')
@@ -675,9 +690,43 @@ Generate a detailed content brief for this opportunity.`;
.update({ brief, updated_at: generatedAt })
.eq('id', opportunityId);
+ if (orgId) {
+ await supabaseAdmin.from('brief_usage').insert({
+ organization_id: orgId,
+ opportunity_id: opportunityId,
+ });
+ }
+
return { brief, generated_at: generatedAt, regenerated: true };
}
+/**
+ * GET /api/content/briefs/quota
+ * Current monthly brief-generation quota for the user's org.
+ * Returns { used, limit, remaining } — limit -1 means unlimited.
+ */
+router.get('/briefs/quota', async (req, res) => {
+ try {
+ const orgId = await getOrgIdForUser(req.user.id);
+ if (!orgId) {
+ // Self-hosted single-user setups may have no org row; no quota applies.
+ return res.json({ used: 0, limit: -1, remaining: -1 });
+ }
+ const quota = await getBriefQuotaStatus(orgId);
+ return res.json(quota);
+ } catch (error) {
+ if (error instanceof PlanLimitError) {
+ return res.status(error.statusCode).json({
+ success: false,
+ error: 'plan_limit',
+ message: error.message,
+ });
+ }
+ console.error('[content] Brief quota status error:', error);
+ return res.status(500).json({ error: 'Failed to get brief quota', details: error.message });
+ }
+});
+
/**
* POST /api/content/:id/brief
* Generate an AI-powered content brief for an opportunity.
@@ -685,14 +734,49 @@ Generate a detailed content brief for this opportunity.`;
* Dashboard-facing route. Preserves the existing cache-on-existing-brief
* behavior — to force a re-generate, the MCP route in server.js calls
* `generateBriefForOpportunity` with `{ force: true }` directly.
+ *
+ * Enforces the monthly brief quota (via the shared core) and returns the
+ * updated quota alongside the brief so the UI can refresh its counter.
*/
router.post('/:id/brief', async (req, res) => {
try {
const { id } = req.params;
const { model } = req.body;
+
+ // Ownership check — the quota is charged to the opportunity's org, so
+ // only members of that org may trigger generation.
+ const { data: opp } = await supabaseAdmin
+ .from('content_opportunities')
+ .select('brand_id')
+ .eq('id', id)
+ .single();
+
+ if (!opp) {
+ return res.status(404).json({ error: 'Opportunity not found' });
+ }
+
+ const { data: brand } = await supabaseAdmin
+ .from('brands')
+ .select('organization_id')
+ .eq('id', opp.brand_id)
+ .single();
+
+ const userOrgId = await getOrgIdForUser(req.user.id);
+ if (!brand || !userOrgId || userOrgId !== brand.organization_id) {
+ return res.status(403).json({ error: 'Unauthorized' });
+ }
+
const result = await generateBriefForOpportunity(id, { model });
- return res.json({ brief: result.brief });
+ const quota = await getBriefQuotaStatus(userOrgId);
+ return res.json({ brief: result.brief, quota, regenerated: result.regenerated });
} catch (error) {
+ if (error instanceof PlanLimitError) {
+ return res.status(error.statusCode).json({
+ success: false,
+ error: 'quota_exceeded',
+ message: error.message,
+ });
+ }
if (error.status === 404) {
return res.status(404).json({ error: error.message });
}
diff --git a/server/src/server.js b/server/src/server.js
index 7ca9cef18..559415c53 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -190,6 +190,13 @@ app.post('/api/internal/content/:id/brief', async (req, res) => {
if (err.status === 404) {
return res.status(404).json({ success: false, message: err.message });
}
+ // PlanLimitError (brief quota exhausted / inactive subscription) carries
+ // a statusCode — surface it so the MCP layer can relay a clear message.
+ if (err.statusCode) {
+ return res
+ .status(err.statusCode)
+ .json({ success: false, error: 'quota_exceeded', message: err.message });
+ }
console.error('[internal] content brief error:', err.message);
return res.status(500).json({ success: false, message: err.message });
}
diff --git a/supabase/migrations/00015_brief_usage.sql b/supabase/migrations/00015_brief_usage.sql
new file mode 100644
index 000000000..71dafda0e
--- /dev/null
+++ b/supabase/migrations/00015_brief_usage.sql
@@ -0,0 +1,34 @@
+-- Content brief generation quota tracking.
+-- Mirrors the volume_usage pattern: one row per generated brief, counted
+-- per organization per calendar month against plan.limits.maxBriefGenerations
+-- (Starter 10, Growth 50, Enterprise via organizations.plan_overrides).
+-- Self-hosted instances bypass quota entirely (IS_CLOUD !== "true").
+
+CREATE TABLE IF NOT EXISTS "public"."brief_usage" (
+ "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
+ "organization_id" "uuid" NOT NULL,
+ "opportunity_id" "uuid",
+ "used_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "created_at" timestamp with time zone DEFAULT "now"()
+);
+
+ALTER TABLE "public"."brief_usage" OWNER TO "postgres";
+
+ALTER TABLE ONLY "public"."brief_usage"
+ ADD CONSTRAINT "brief_usage_pkey" PRIMARY KEY ("id");
+
+ALTER TABLE ONLY "public"."brief_usage"
+ ADD CONSTRAINT "brief_usage_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE CASCADE;
+
+ALTER TABLE ONLY "public"."brief_usage"
+ ADD CONSTRAINT "brief_usage_opportunity_id_fkey" FOREIGN KEY ("opportunity_id") REFERENCES "public"."content_opportunities"("id") ON DELETE SET NULL;
+
+CREATE INDEX "idx_brief_usage_org_month" ON "public"."brief_usage" USING "btree" ("organization_id", "used_at");
+
+-- RLS enabled with no policies: only the service role (aeo-server) writes
+-- and reads usage rows — same posture as volume_usage.
+ALTER TABLE "public"."brief_usage" ENABLE ROW LEVEL SECURITY;
+
+GRANT ALL ON TABLE "public"."brief_usage" TO "anon";
+GRANT ALL ON TABLE "public"."brief_usage" TO "authenticated";
+GRANT ALL ON TABLE "public"."brief_usage" TO "service_role";
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
index 3d4554390..3d3507a0a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
@@ -21,6 +21,7 @@ import {
FileText,
Target,
ListOrdered,
+ Crown,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { Link } from '@/i18n/navigation';
@@ -29,6 +30,8 @@ import {
updateOpportunityStatus,
sendToWebhook,
generateBrief,
+ getBriefQuota,
+ type BriefQuota,
} from '@/lib/actions/content';
import type { ContentBrief, ContentOpportunity } from '@/types';
import { toast } from 'sonner';
@@ -90,6 +93,7 @@ export default function ContentDetailPage() {
const [sending, setSending] = useState(false);
const [generatingBrief, setGeneratingBrief] = useState(false);
const [brief, setBrief] = useState<ContentBrief | null>(null);
+ const [quota, setQuota] = useState<BriefQuota | null>(null);
useEffect(() => {
setLoading(true);
@@ -103,6 +107,11 @@ export default function ContentDetailPage() {
toast.error('Failed to load opportunity');
})
.finally(() => setLoading(false));
+
+ // Quota is informational — don't block the page if it fails.
+ getBriefQuota()
+ .then(setQuota)
+ .catch(() => setQuota(null));
}, [id]);
const handleSend = async () => {
@@ -135,11 +144,16 @@ export default function ContentDetailPage() {
setGeneratingBrief(true);
try {
const result = await generateBrief(id);
- setBrief(result);
+ setBrief(result.brief);
+ if (result.quota) setQuota(result.quota);
toast.success('Content brief generated!');
} catch (err) {
console.error('Brief generation failed:', err);
toast.error(err instanceof Error ? err.message : 'Failed to generate brief');
+ // Refresh the counter — the failure may have been a quota rejection.
+ getBriefQuota()
+ .then(setQuota)
+ .catch(() => {});
} finally {
setGeneratingBrief(false);
}
@@ -162,6 +176,8 @@ export default function ContentDetailPage() {
}
const sd = opportunity.sourceData;
+ const quotaLimited = quota !== null && quota.limit !== -1;
+ const quotaExhausted = quotaLimited && quota.remaining <= 0;
return (
<div className="space-y-6">
@@ -348,20 +364,48 @@ export default function ContentDetailPage() {
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center py-10 text-center">
- <Sparkles className="h-10 w-10 text-muted-foreground/40 mb-3" />
- <h3 className="text-sm font-medium mb-1">No Content Brief Yet</h3>
- <p className="text-xs text-muted-foreground mb-4 max-w-sm">
- Generate an AI-powered content brief with a suggested title, outline, target
- keywords, and competitor insights.
- </p>
- <Button onClick={handleGenerateBrief} disabled={generatingBrief} className="gap-2">
- {generatingBrief ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Sparkles className="h-4 w-4" />
- )}
- {generatingBrief ? 'Generating...' : 'Generate Content Brief'}
- </Button>
+ {quotaExhausted ? (
+ <>
+ <Crown className="h-10 w-10 text-amber-500/60 mb-3" />
+ <h3 className="text-sm font-medium mb-1">Monthly Brief Limit Reached</h3>
+ <p className="text-xs text-muted-foreground mb-4 max-w-sm">
+ You&apos;ve used all {quota.limit} content briefs included in your plan this
+ month. Upgrade for a higher limit, or wait until the 1st when your quota resets.
+ </p>
+ <Link href="/dashboard/settings?tab=billing">
+ <Button className="gap-2">
+ <Crown className="h-4 w-4" />
+ Upgrade Plan
+ </Button>
+ </Link>
+ </>
+ ) : (
+ <>
+ <Sparkles className="h-10 w-10 text-muted-foreground/40 mb-3" />
+ <h3 className="text-sm font-medium mb-1">No Content Brief Yet</h3>
+ <p className="text-xs text-muted-foreground mb-4 max-w-sm">
+ Generate an AI-powered content brief with a suggested title, outline, target
+ keywords, and competitor insights.
+ </p>
+ <Button
+ onClick={handleGenerateBrief}
+ disabled={generatingBrief}
+ className="gap-2"
+ >
+ {generatingBrief ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Sparkles className="h-4 w-4" />
+ )}
+ {generatingBrief ? 'Generating...' : 'Generate Content Brief'}
+ </Button>
+ {quotaLimited && (
+ <p className="text-xs text-muted-foreground mt-3 tabular-nums">
+ {quota.remaining}/{quota.limit} briefs remaining this month
+ </p>
+ )}
+ </>
+ )}
</CardContent>
</Card>
)}
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index a6295407a..44c68636a 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -33,6 +33,12 @@ export interface PlanLimits {
maxTeamMembers: number;
maxDomainsPerBrand: number;
maxVolumeAnalyses: number;
+ /**
+ * Monthly content brief generations (AI brief per opportunity).
+ * -1 = unlimited. Enterprise is -1 by default and set per customer via
+ * organizations.plan_overrides.maxBriefGenerations in the DB.
+ */
+ maxBriefGenerations: number;
maxDailyOnDemand: number;
onDemandCooldownMinutes: number;
features: readonly Feature[];
@@ -68,6 +74,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxTeamMembers: -1,
maxDomainsPerBrand: -1,
maxVolumeAnalyses: -1,
+ maxBriefGenerations: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
@@ -99,6 +106,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxTeamMembers: 1,
maxDomainsPerBrand: 3,
maxVolumeAnalyses: 4,
+ maxBriefGenerations: 10,
maxDailyOnDemand: 3,
onDemandCooldownMinutes: 15,
allowedScrapers: ['chatgpt-web', 'perplexity-web'],
@@ -134,6 +142,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxTeamMembers: 3,
maxDomainsPerBrand: 10,
maxVolumeAnalyses: 10,
+ maxBriefGenerations: 50,
maxDailyOnDemand: 10,
onDemandCooldownMinutes: 5,
features: [
@@ -163,6 +172,8 @@ export const PLANS: Record<PlanId, Plan> = {
maxTeamMembers: -1,
maxDomainsPerBrand: -1,
maxVolumeAnalyses: -1,
+ // Per-customer: override via organizations.plan_overrides in the DB.
+ maxBriefGenerations: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 031db66a0..2043c17c0 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -128,7 +128,31 @@ export async function getOpportunity(id: string): Promise<ContentOpportunity> {
return res.json();
}
-export async function generateBrief(opportunityId: string): Promise<ContentBrief> {
+export interface BriefQuota {
+ used: number;
+ limit: number;
+ remaining: number;
+}
+
+export async function getBriefQuota(): Promise<BriefQuota> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/content/briefs/quota`, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.message || body.error || `Server error: ${res.status}`);
+ }
+
+ return res.json();
+}
+
+export async function generateBrief(
+ opportunityId: string,
+): Promise<{ brief: ContentBrief; quota: BriefQuota | null }> {
const session = await getSession();
const res = await fetch(`${AEO_SERVER_URL}/api/content/${opportunityId}/brief`, {
@@ -142,11 +166,11 @@ export async function generateBrief(opportunityId: string): Promise<ContentBrief
if (!res.ok) {
const body = await res.json().catch(() => ({}));
- throw new Error(body.error || `Server error: ${res.status}`);
+ throw new Error(body.message || body.error || `Server error: ${res.status}`);
}
const data = await res.json();
- return data.brief;
+ return { brief: data.brief, quota: data.quota ?? null };
}
export async function updateOpportunityStatus(