Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): show and enforce the monthly content opportunity quota (#1019)
Cihan7a1c9b8f9060
diff --git a/server/src/config/plans.js b/server/src/config/plans.jsindex eaa9d07f2..d576ff20d 100644--- a/server/src/config/plans.js+++ b/server/src/config/plans.js@@ -16,6 +16,7 @@ export const PLANS = {maxVolumeAnalyses: -1,maxBriefGenerations: -1,improveMonthlyBudgetUsd: -1,+ maxOpportunitiesPerMonth: -1,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,@@ -48,6 +49,7 @@ export const PLANS = {maxVolumeAnalyses: 4,maxBriefGenerations: 10,improveMonthlyBudgetUsd: 0,+ maxOpportunitiesPerMonth: 10,maxSiteAudits: 100,maxDailyOnDemand: 3,onDemandCooldownMinutes: 15,@@ -81,6 +83,7 @@ export const PLANS = {maxBriefGenerations: 50,// 1% of the $249 price, spent on Improve model calls (PROMPT-003).improveMonthlyBudgetUsd: 2.49,+ maxOpportunitiesPerMonth: 50,maxSiteAudits: 500,maxDailyOnDemand: 10,onDemandCooldownMinutes: 5,@@ -119,6 +122,7 @@ export const PLANS = {// 1% of the $499 floor. plan_overrides.contractMonthlyUsd raises it to 1%// of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.improveMonthlyBudgetUsd: 4.99,+ maxOpportunitiesPerMonth: -1,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.jsindex 5620f21c2..43e327865 100644--- a/server/src/lib/opportunity-generator.js+++ b/server/src/lib/opportunity-generator.js@@ -26,6 +26,11 @@ import {import { loadClusterOpportunities } from './open-opportunities.js';import { loadClusters } from './prompt-clusters.js';import { reopenStrengthened } from './opportunity-reopen.js';+import {+ claimOpportunitySlots,+ linkOpportunitySlots,+ releaseOpportunitySlots,+} from './plan-guard.js';import {ASSET_TYPES,DECISIONS,@@ -161,7 +166,7 @@ export async function generateContentOpportunities(brandId, { model, onProgressconst { data: brand } = await supabaseAdmin.from('brands')- .select('id, name, industry, language')+ .select('id, name, industry, language, organization_id').eq('id', brandId).single();if (!brand) return { generated: 0, merged: 0 };@@ -239,8 +244,8 @@ export async function generateContentOpportunities(brandId, { model, onProgress}const candidates = clusters.map((c) => ({ id: c.id, topicId: c.topic_id, ...measure([c.id]) }));- const picked = pickClusters(candidates, coveredClusterIds(existing));- if (!picked.length) {+ const wanted = pickClusters(candidates, coveredClusterIds(existing));+ if (!wanted.length) {logger.info({ brandId, clusters: clusters.length, opportunities: existing.length, reopened },'[opportunities] every cluster with answers already has an opportunity',@@ -248,6 +253,20 @@ export async function generateContentOpportunities(brandId, { model, onProgressreturn { generated: 0, merged: 0, reopened };}+ // Each new opportunity takes one of the organization's monthly slots+ // (CONTENT-001). They are claimed before the model call, so two runs at+ // once can't overshoot; whatever this run doesn't use is handed back.+ const slots = await claimOpportunitySlots(brand.organization_id, wanted.length);+ const picked = slots.unlimited ? wanted : wanted.slice(0, slots.ids.length);+ if (!picked.length) {+ logger.info({ brandId }, '[opportunities] monthly opportunity limit reached');+ return { generated: 0, merged: 0, reopened, limited: true };+ }+ const releaseAll = () =>+ releaseOpportunitySlots(slots.ids).catch((err) =>+ logger.error({ err, brandId }, '[opportunities] handing back slots failed'),+ );+const { data: basketRows, error: basketErr } = await supabaseAdmin.from('prompt_cluster_queries').select('cluster_id, query, times_searched, included')@@ -255,7 +274,10 @@ export async function generateContentOpportunities(brandId, { model, onProgress'cluster_id',picked.map((c) => c.id),);- if (basketErr) throw new Error(basketErr.message);+ if (basketErr) {+ await releaseAll();+ throw new Error(basketErr.message);+ }const shown = existing.filter(@@ -315,6 +337,10 @@ Write every title and description in ${getLanguageName(brand.language)}.`;schema: buildSchema(picked.length),system: SYSTEM_PROMPT,prompt: userPrompt,+ }).catch(async (err) => {+ // A failed generation creates nothing, so it uses none of the quota.+ await releaseAll();+ throw err;});onProgress?.({ phase: 'saving', message: 'Saving opportunities...' });@@ -399,9 +425,24 @@ Write every title and description in ${getLanguageName(brand.language)}.`;});}+ let created = [];if (inserts.length) {- const { error } = await supabaseAdmin.from('content_opportunities').insert(inserts);- if (error) throw new Error(error.message);+ const { data, error } = await supabaseAdmin+ .from('content_opportunities')+ .insert(inserts)+ .select('id');+ if (error) {+ await releaseAll();+ throw new Error(error.message);+ }+ created = data || [];+ }+ if (!slots.unlimited) {+ await linkOpportunitySlots(+ created.map((row, i) => ({ usageId: slots.ids[i], opportunityId: row.id })),+ );+ // Merged or skipped clusters created nothing: their slots go back.+ await releaseOpportunitySlots(slots.ids.slice(created.length));}logger.info({ brandId, generated: inserts.length, merged, reopened, clusters: clusters.length },diff --git a/server/src/lib/opportunity-quota.test.js b/server/src/lib/opportunity-quota.test.jsnew file mode 100644index 000000000..ed92f5a85--- /dev/null+++ b/server/src/lib/opportunity-quota.test.js@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// The monthly content opportunity quota (CONTENT-001) in plan-guard.js:+// claiming slots, the counters and the period they belong to.++const rpc = vi.fn();+const tables = {};+vi.mock('../config/supabase.js', () => ({+ default: {+ rpc: (...a) => rpc(...a),+ from: (table) => tables[table](),+ },+}));++const { claimOpportunitySlots, getContentUsage, getOpportunityQuotaStatus } =+ await import('./plan-guard.js');++/** A query builder that resolves to `result` however it is chained. */+function chain(result) {+ const b = {+ select: () => b,+ eq: () => b,+ gte: () => b,+ single: () => Promise.resolve(result),+ maybeSingle: () => Promise.resolve(result),+ then: (resolve) => resolve(result),+ };+ return b;+}++function org(plan, endsAt = '2026-11-12T00:00:00.000Z') {+ tables.organizations = () =>+ chain({+ data: {+ plan,+ subscription_status: 'active',+ subscription_ends_at: endsAt,+ plan_overrides: null,+ },+ });+}++function used(opportunities, briefs = 0) {+ tables.opportunity_usage = () => chain({ count: opportunities });+ tables.brief_usage = () => chain({ count: briefs });+}++beforeEach(() => {+ process.env.IS_CLOUD = 'true';+ rpc.mockReset();+});++afterEach(() => {+ delete process.env.IS_CLOUD;+});++describe('getOpportunityQuotaStatus', () => {+ it('counts against 10 on Starter and 50 on Growth', async () => {+ org('starter');+ used(4);+ expect(await getOpportunityQuotaStatus('o1')).toEqual({ used: 4, limit: 10, remaining: 6 });+ org('growth');+ used(43);+ expect(await getOpportunityQuotaStatus('o1')).toEqual({ used: 43, limit: 50, remaining: 7 });+ });++ it('never reports negative remaining', async () => {+ org('starter');+ used(12);+ expect((await getOpportunityQuotaStatus('o1')).remaining).toBe(0);+ });++ it('is unlimited when self-hosted', async () => {+ delete process.env.IS_CLOUD;+ expect(await getOpportunityQuotaStatus('o1')).toEqual({ used: 0, limit: -1, remaining: -1 });+ });+});++describe('claimOpportunitySlots', () => {+ it('claims through the atomic function, from the start of the billing period', async () => {+ org('starter');+ rpc.mockResolvedValue({ data: ['u1', { claim_opportunity_usage: 'u2' }], error: null });+ expect(await claimOpportunitySlots('o1', 3)).toEqual({ unlimited: false, ids: ['u1', 'u2'] });+ const [name, args] = rpc.mock.calls[0];+ expect(name).toBe('claim_opportunity_usage');+ expect(args).toMatchObject({ p_organization_id: 'o1', p_limit: 10, p_count: 3 });+ // Anchored to the billing day (the 12th), not the 1st of the month.+ expect(new Date(args.p_since).getUTCDate()).toBe(12);+ });++ it('claims nothing when unlimited', async () => {+ delete process.env.IS_CLOUD;+ expect(await claimOpportunitySlots('o1', 3)).toEqual({ unlimited: true, ids: [] });+ expect(rpc).not.toHaveBeenCalled();+ });+});++describe('getContentUsage', () => {+ it('reports both counters and the period they renew with', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-10-20T00:00:00.000Z'));+ try {+ org('growth');+ used(32, 5);+ expect(await getContentUsage('o1')).toEqual({+ plan: 'growth',+ 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 },+ briefs: { used: 5, limit: 50, remaining: 45 },+ });+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.jsindex c6c246925..2fd4b0b67 100644--- a/server/src/lib/plan-guard.js+++ b/server/src/lib/plan-guard.js@@ -6,7 +6,7 @@ import {isCloud,isSubscriptionActive,} from '../config/plans.js';-import { anchoredPeriodStart } from './quota-period.js';+import { anchoredPeriodStart, shiftMonthClamped } from './quota-period.js';import {IMPROVE_BUDGET_SHARE,estimateGenerationsLeft,@@ -336,6 +336,92 @@ export async function enforceImproveQuota(orgId, modelId) {return quota;}+async function countOpportunityUsage(orgId, since) {+ const { count } = await supabaseAdmin+ .from('opportunity_usage')+ .select('*', { count: 'exact', head: true })+ .eq('organization_id', orgId)+ .gte('used_at', since.toISOString());+ return count || 0;+}++/**+ * Get the monthly content opportunity quota without enforcing (CONTENT-001).+ * Returns { used, limit, remaining }; limit -1 is unlimited.+ */+export async function getOpportunityQuotaStatus(orgId) {+ const plan = await resolveOrgPlanByOrgId(orgId);+ const max = plan.limits.maxOpportunitiesPerMonth ?? -1;+ if (max === -1) return { used: 0, limit: -1, remaining: -1 };++ const used = await countOpportunityUsage(orgId, await quotaPeriodStart(orgId));+ return { used, limit: max, remaining: Math.max(0, max - used) };+}++/**+ * Claim up to `count` of this period's opportunity slots before generating.+ * Atomic per organization (claim_opportunity_usage), so concurrent runs can't+ * overshoot. Returns { unlimited, ids }: link each id to the opportunity it+ * becomes (linkOpportunitySlots) and hand back the rest (releaseOpportunitySlots).+ */+export async function claimOpportunitySlots(orgId, count) {+ const plan = await resolveOrgPlanByOrgId(orgId);+ const max = plan.limits.maxOpportunitiesPerMonth ?? -1;+ if (max === -1) return { unlimited: true, ids: [] };+ if (count <= 0) return { unlimited: false, ids: [] };++ const { data, error } = await supabaseAdmin.rpc('claim_opportunity_usage', {+ p_organization_id: orgId,+ p_since: (await quotaPeriodStart(orgId)).toISOString(),+ p_limit: max,+ p_count: count,+ });+ if (error) throw new Error(error.message);+ // A setof uuid comes back as bare ids or as one-key rows, by client version.+ const ids = (data ?? []).map((r) => (typeof r === 'string' ? r : Object.values(r)[0]));+ return { unlimited: false, ids };+}++/** Point each claimed slot at the opportunity it was used for. */+export async function linkOpportunitySlots(pairs) {+ for (const { usageId, opportunityId } of pairs) {+ const { error } = await supabaseAdmin+ .from('opportunity_usage')+ .update({ opportunity_id: opportunityId })+ .eq('id', usageId);+ if (error) throw new Error(error.message);+ }+}++/** Hand back slots that were claimed but not used (merged, skipped or failed). */+export async function releaseOpportunitySlots(ids) {+ if (!ids.length) return;+ const { error } = await supabaseAdmin.from('opportunity_usage').delete().in('id', ids);+ if (error) throw new Error(error.message);+}++/**+ * Both monthly content counters with the period they belong to, for the+ * Content page and GET /content/usage (CONTENT-001). Opportunities and briefs+ * are separate pools that renew together with the subscription.+ */+export async function getContentUsage(orgId) {+ const plan = await resolveOrgPlanByOrgId(orgId);+ const periodStart = await quotaPeriodStart(orgId);+ const [opportunities, briefs] = await Promise.all([+ getOpportunityQuotaStatus(orgId),+ getBriefQuotaStatus(orgId),+ ]);+ return {+ plan: plan.id,+ planName: plan.name,+ periodStart: periodStart.toISOString(),+ periodEnd: shiftMonthClamped(periodStart, 1).toISOString(),+ opportunities,+ briefs,+ };+}+async function countSiteAuditUsageThisMonth(orgId) {const periodStart = await quotaPeriodStart(orgId);const { count } = await supabaseAdmindiff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex fee95cd91..b8f967d5b 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -5,6 +5,7 @@ import {requireFeature,enforceBriefQuota,getBriefQuotaStatus,+ getContentUsage,getOrgIdForUser,PlanLimitError,} from '../lib/plan-guard.js';@@ -1034,6 +1035,42 @@ router.get('/briefs/quota', async (req, res) => {}});+/**+ * GET /api/content/usage+ * Both monthly content counters for the user's org (CONTENT-001), so the+ * Content page, the MCP server and agents read the same figures:+ * { plan, planName, periodStart, periodEnd, opportunities, briefs }, each+ * counter { used, limit, remaining } with limit -1 meaning unlimited.+ */+router.get('/usage', 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.+ const unlimited = { used: 0, limit: -1, remaining: -1 };+ return res.json({+ plan: 'self_hosted',+ planName: null,+ periodStart: null,+ periodEnd: null,+ opportunities: unlimited,+ briefs: unlimited,+ });+ }+ return res.json(await getContentUsage(orgId));+ } catch (error) {+ if (error instanceof PlanLimitError) {+ return res.status(error.statusCode).json({+ success: false,+ error: 'plan_limit',+ message: error.message,+ });+ }+ req.log.error({ err: error }, 'content usage error');+ return res.status(500).json({ error: 'Failed to get content usage', details: error.message });+ }+});+/*** POST /api/content/:id/brief* Generate an AI-powered content brief for an opportunity.diff --git a/supabase/migrations/00125_opportunity_usage.sql b/supabase/migrations/00125_opportunity_usage.sqlnew file mode 100644index 000000000..f8e08dd70--- /dev/null+++ b/supabase/migrations/00125_opportunity_usage.sql@@ -0,0 +1,71 @@+-- Monthly content opportunity quota (CONTENT-001).+--+-- One row per opportunity created, counted per organization per billing+-- period against plan.limits.maxOpportunitiesPerMonth (Starter 10, Growth 50,+-- Enterprise via organizations.plan_overrides). Separate from brief_usage:+-- creating an opportunity and generating its brief are two counters.+--+-- A row outlives its opportunity (ON DELETE SET NULL), so deleting or+-- dismissing an opportunity never hands its slot back. Self-hosted instances+-- bypass the quota entirely (IS_CLOUD !== "true").++create table if not exists public.opportunity_usage (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ opportunity_id uuid references public.content_opportunities(id) on delete set null,+ used_at timestamptz not null default now(),+ created_at timestamptz default now()+);++create index if not exists idx_opportunity_usage_org_period+ on public.opportunity_usage (organization_id, used_at);++-- RLS enabled with no policies: only the service role (aeo-server) reads and+-- writes usage rows, the same posture as brief_usage.+alter table public.opportunity_usage enable row level security;++grant all on table public.opportunity_usage to service_role;++-- Claims up to p_count slots in one transaction, under a per-organization+-- lock, so two generations running at once (several brands of one org, or a+-- double click) can never take the organization past its limit. Returns the+-- claimed usage row ids; the caller links each to the opportunity it creates+-- and deletes the ones it ends up not using, which hands those slots back.+create or replace function public.claim_opportunity_usage(+ p_organization_id uuid,+ p_since timestamptz,+ p_limit integer,+ p_count integer+)+returns setof uuid+language plpgsql+security definer+set search_path = public+as $$+declare+ v_used integer;+ v_take integer;+begin+ perform pg_advisory_xact_lock(hashtext('opportunity_usage:' || p_organization_id::text));++ select count(*) into v_used+ from public.opportunity_usage+ where organization_id = p_organization_id+ and used_at >= p_since;++ v_take := greatest(0, least(p_count, p_limit - v_used));++ return query+ insert into public.opportunity_usage (organization_id)+ select p_organization_id from generate_series(1, v_take)+ returning id;+end;+$$;++revoke all on function public.claim_opportunity_usage(uuid, timestamptz, integer, integer)+ from public, anon, authenticated;+grant execute on function public.claim_opportunity_usage(uuid, timestamptz, integer, integer)+ to service_role;++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.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex e730dfc58..018b96e82 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -14330,3 +14330,78 @@ comment on column public.action_tasks.details isalter table public.prompt_improve_suggestionsadd column if not exists sent_actions jsonb not null default '[]'::jsonb;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00125_opportunity_usage.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Monthly content opportunity quota (CONTENT-001).+--+-- One row per opportunity created, counted per organization per billing+-- period against plan.limits.maxOpportunitiesPerMonth (Starter 10, Growth 50,+-- Enterprise via organizations.plan_overrides). Separate from brief_usage:+-- creating an opportunity and generating its brief are two counters.+--+-- A row outlives its opportunity (ON DELETE SET NULL), so deleting or+-- dismissing an opportunity never hands its slot back. Self-hosted instances+-- bypass the quota entirely (IS_CLOUD !== "true").++create table if not exists public.opportunity_usage (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ opportunity_id uuid references public.content_opportunities(id) on delete set null,+ used_at timestamptz not null default now(),+ created_at timestamptz default now()+);++create index if not exists idx_opportunity_usage_org_period+ on public.opportunity_usage (organization_id, used_at);++-- RLS enabled with no policies: only the service role (aeo-server) reads and+-- writes usage rows, the same posture as brief_usage.+alter table public.opportunity_usage enable row level security;++grant all on table public.opportunity_usage to service_role;++-- Claims up to p_count slots in one transaction, under a per-organization+-- lock, so two generations running at once (several brands of one org, or a+-- double click) can never take the organization past its limit. Returns the+-- claimed usage row ids; the caller links each to the opportunity it creates+-- and deletes the ones it ends up not using, which hands those slots back.+create or replace function public.claim_opportunity_usage(+ p_organization_id uuid,+ p_since timestamptz,+ p_limit integer,+ p_count integer+)+returns setof uuid+language plpgsql+security definer+set search_path = public+as $$+declare+ v_used integer;+ v_take integer;+begin+ perform pg_advisory_xact_lock(hashtext('opportunity_usage:' || p_organization_id::text));++ select count(*) into v_used+ from public.opportunity_usage+ where organization_id = p_organization_id+ and used_at >= p_since;++ v_take := greatest(0, least(p_count, p_limit - v_used));++ return query+ insert into public.opportunity_usage (organization_id)+ select p_organization_id from generate_series(1, v_take)+ returning id;+end;+$$;++revoke all on function public.claim_opportunity_usage(uuid, timestamptz, integer, integer)+ from public, anon, authenticated;+grant execute on function public.claim_opportunity_usage(uuid, timestamptz, integer, integer)+ to service_role;++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.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 5b2fb820b..ca2cb6c86 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1754,6 +1754,18 @@"owned": "Content on your own site","earned": "Coverage on other sites: articles, reviews, links"},+ "usage": {+ "title": "This billing period",+ "opportunities": "New opportunities",+ "briefs": "Content briefs",+ "remaining": "{count, plural, one {# remaining} other {# remaining}}",+ "limitReached": "Limit reached",+ "unlimited": "Unlimited",+ "plan": "{plan} plan",+ "resets": "Resets {date}",+ "upgrade": "Upgrade plan",+ "tooltip": "Every new opportunity counts once, whether Ansvisor suggested it or you asked for it; dismissed and deleted ones still count, merged duplicates don't. Generating a brief counts separately. Unused allowance doesn't carry over. Both reset on {date}, when your subscription renews."+ },"kpi": {"total": "Total Opportunities","highImpact": "High Impact",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex d2d39f258..537c4e6e2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -64,6 +64,7 @@ import { usePlanContext } from '@/components/providers/plan-provider';import {generateOpportunities,getGenerationJobStatus,+ getContentUsage,getOpportunities,getOpportunityPrompts,getOpportunityTopics,@@ -81,6 +82,8 @@ import { Link } from '@/i18n/navigation';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 { PAGE_SIZE, TablePager, usePagination } from '@/components/table-pager';import { toCsv } from '@/lib/csv';import { readUrlChoice, writeUrlParams } from '@/lib/url-state';@@ -238,6 +241,8 @@ export default function ContentPage() {const [bulkSending, setBulkSending] = useState(false);const [webhookOpen, setWebhookOpen] = useState(false);+ // This billing period's content usage (CONTENT-001); null hides the card.+ const [contentUsage, setContentUsage] = useState<ContentUsage | null>(null);const pollRef = useRef(false);const [debouncedSearch, setDebouncedSearch] = useState(search);const [aggregates, setAggregates] = useState({@@ -429,6 +434,19 @@ export default function ContentPage() {};}, [loadData]);+ // Reloaded when the list's size changes, since that is when something may+ // have used the quota. A failure only hides the card.+ useEffect(() => {+ let cancelled = false;+ getContentUsage().then(+ (usage) => !cancelled && setContentUsage(usage),+ () => !cancelled && setContentUsage(null),+ );+ return () => {+ cancelled = true;+ };+ }, [activeBrandId, total]);+const pollJob = useCallback((jobId: string, startedAt: number) => {pollRef.current = true;@@ -793,7 +811,16 @@ export default function ContentPage() {</Card>) : (<>- <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">+ <div+ className={cn(+ 'grid grid-cols-2 gap-4 sm:grid-cols-4',+ hasContentQuota(contentUsage) && 'xl:grid-cols-[1.4fr_repeat(4,minmax(0,1fr))]',+ )}+ >+ <ContentUsageCard+ usage={contentUsage}+ className="col-span-2 sm:col-span-4 xl:col-span-1"+ /><KpiCardtitle={t('kpi.total')}icon={Lightbulb}diff --git a/web/src/components/content/content-usage-card.tsx b/web/src/components/content/content-usage-card.tsxnew file mode 100644index 000000000..1f0af6fac--- /dev/null+++ b/web/src/components/content/content-usage-card.tsx@@ -0,0 +1,133 @@+'use client';++import { useLocale, useTranslations } from 'next-intl';+import { Gauge, Info } from 'lucide-react';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Link } from '@/i18n/navigation';+import { cn } from '@/lib/utils';+import {+ hasContentQuota,+ usagePercent,+ usageTone,+ type ContentUsage,+ type UsageCounter,+ type UsageTone,+} from '@/lib/content-usage';++const BAR_CLASS: Record<UsageTone, string> = {+ normal: 'bg-emerald-500',+ warning: 'bg-amber-500',+ exhausted: 'bg-red-500',+ unlimited: 'bg-muted-foreground/30',+};++const LEFT_CLASS: Record<UsageTone, string> = {+ normal: 'text-muted-foreground',+ warning: 'text-amber-600 dark:text-amber-400',+ exhausted: 'text-red-600 dark:text-red-400',+ unlimited: 'text-muted-foreground',+};++/**+ * This billing period's content usage (CONTENT-001): new opportunities and+ * briefs against the plan's two monthly limits, and when they renew. Renders+ * nothing on plans that limit neither (self-hosted, unlimited Enterprise).+ */+export function ContentUsageCard({+ usage,+ className,+}: {+ usage: ContentUsage | null;+ className?: string;+}) {+ const t = useTranslations('content.usage');+ const locale = useLocale();++ if (!hasContentQuota(usage)) return null;++ const resets = usage.periodEnd+ ? new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(+ new Date(usage.periodEnd),+ )+ : null;+ const exhausted =+ usageTone(usage.opportunities) === 'exhausted' || usageTone(usage.briefs) === 'exhausted';++ return (+ <Card className={className}>+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-1">+ <CardTitle className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ {t('title')}+ </CardTitle>+ <span className="inline-flex items-center gap-1.5 text-muted-foreground">+ <span+ className="inline-flex cursor-help"+ title={t('tooltip', { date: resets ?? '' })}+ aria-label={t('tooltip', { date: resets ?? '' })}+ >+ <Info className="h-3.5 w-3.5" />+ </span>+ <Gauge className="h-3.5 w-3.5" />+ </span>+ </CardHeader>+ <CardContent className="space-y-2">+ <Counter label={t('opportunities')} counter={usage.opportunities} />+ <Counter label={t('briefs')} counter={usage.briefs} />+ <p className="text-xs text-muted-foreground">+ {[+ usage.planName && t('plan', { plan: usage.planName }),+ resets && t('resets', { date: resets }),+ ]+ .filter(Boolean)+ .join(' · ')}+ {exhausted && usage.plan === 'starter' && (+ <>+ {' · '}+ <Link+ href="/dashboard/settings?tab=billing"+ className="font-medium text-foreground underline underline-offset-2"+ >+ {t('upgrade')}+ </Link>+ </>+ )}+ </p>+ </CardContent>+ </Card>+ );+}++function Counter({ label, counter }: { label: string; counter: UsageCounter }) {+ const t = useTranslations('content.usage');+ const tone = usageTone(counter);+ return (+ <div>+ <div className="flex items-baseline justify-between gap-2 text-xs">+ <span className="font-medium">{label}</span>+ {tone === 'unlimited' ? (+ <span className="text-muted-foreground">{t('unlimited')}</span>+ ) : (+ <span className="tabular-nums">+ <span className="text-sm font-semibold">{counter.used}</span>+ <span className="text-muted-foreground"> / {counter.limit}</span>+ </span>+ )}+ </div>+ {tone !== 'unlimited' && (+ <>+ <div className="mt-1 h-1.5 overflow-hidden rounded-full bg-muted">+ <div+ className={cn('h-full rounded-full', BAR_CLASS[tone])}+ style={{ width: `${usagePercent(counter)}%` }}+ />+ </div>+ <p className={cn('mt-0.5 text-[11px] tabular-nums', LEFT_CLASS[tone])}>+ {tone === 'exhausted'+ ? t('limitReached')+ : t('remaining', { count: counter.remaining })}+ </p>+ </>+ )}+ </div>+ );+}diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex b532ea7f0..5f1b17c2c 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -632,7 +632,8 @@ export function OpportunityDetail({<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'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.+ billing period. Upgrade for a higher limit, or wait until your subscription+ renews and the quota resets.</p><Link href="/dashboard/settings?tab=billing"><Button className="gap-2">@@ -663,7 +664,7 @@ export function OpportunityDetail({</Button>{quotaLimited && (<p className="text-xs text-muted-foreground mt-3 tabular-nums">- {quota.remaining}/{quota.limit} briefs remaining this month+ {quota.remaining}/{quota.limit} briefs remaining this billing period</p>)}</>diff --git a/web/src/config/plans.ts b/web/src/config/plans.tsindex ad07dc756..9b2b3d2bd 100644--- a/web/src/config/plans.ts+++ b/web/src/config/plans.ts@@ -50,6 +50,12 @@ export interface PlanLimits {* -1 = unlimited (self-host).*/improveMonthlyBudgetUsd: number;+ /**+ * New content opportunities per month (CONTENT-001), counted separately+ * from briefs. -1 = unlimited. Enterprise is -1 by default and set per+ * customer via organizations.plan_overrides.maxOpportunitiesPerMonth.+ */+ maxOpportunitiesPerMonth: number;/*** Monthly Site Audit runs. -1 = unlimited (self-hosted / enterprise).* Starter 100, Growth 500.@@ -92,6 +98,7 @@ export const PLANS: Record<PlanId, Plan> = {maxVolumeAnalyses: -1,maxBriefGenerations: -1,improveMonthlyBudgetUsd: -1,+ maxOpportunitiesPerMonth: -1,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,@@ -128,6 +135,7 @@ export const PLANS: Record<PlanId, Plan> = {maxVolumeAnalyses: 4,maxBriefGenerations: 10,improveMonthlyBudgetUsd: 0,+ maxOpportunitiesPerMonth: 10,maxSiteAudits: 100,maxDailyOnDemand: 3,onDemandCooldownMinutes: 15,@@ -168,6 +176,7 @@ export const PLANS: Record<PlanId, Plan> = {maxBriefGenerations: 50,// 1% of the $249 price, spent on Improve model calls (PROMPT-003).improveMonthlyBudgetUsd: 2.49,+ maxOpportunitiesPerMonth: 50,maxSiteAudits: 500,maxDailyOnDemand: 10,onDemandCooldownMinutes: 5,@@ -208,6 +217,7 @@ export const PLANS: Record<PlanId, Plan> = {// 1% of the $499 floor. plan_overrides.contractMonthlyUsd raises it to 1%// of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.improveMonthlyBudgetUsd: 4.99,+ maxOpportunitiesPerMonth: -1,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex 7f5e85211..4012ed313 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -3,6 +3,7 @@import { createClient } from '@/lib/supabase/server';import type { ContentBrief, ContentOpportunity, OpportunityBasket, WebhookConfig } from '@/types';import { API_BASE_URL } from '@/config/api';+import type { ContentUsage } from '@/lib/content-usage';const AEO_SERVER_URL = API_BASE_URL;@@ -295,6 +296,24 @@ export async function getBriefQuota(): Promise<BriefQuota> {return res.json();}+/** Both monthly content counters and their period (CONTENT-001). */+export async function getContentUsage(): Promise<ContentUsage> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/content/usage`, {+ method: 'GET',+ headers: { Authorization: `Bearer ${session.access_token}` },+ cache: 'no-store',+ });++ 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 }> {diff --git a/web/src/lib/content-usage.test.ts b/web/src/lib/content-usage.test.tsnew file mode 100644index 000000000..5ab90a6a4--- /dev/null+++ b/web/src/lib/content-usage.test.ts@@ -0,0 +1,50 @@+/**+ * content-usage.test.ts (CONTENT-001)+ *+ * How the monthly content counters read on the usage card.+ */++import { describe, expect, test } from 'vitest';+import { hasContentQuota, usagePercent, usageTone, type ContentUsage } from './content-usage';++const c = (used: number, limit: number) => ({ used, limit, remaining: Math.max(0, limit - used) });++describe('usageTone', () => {+ test('normal under 80%, warning from 80%, exhausted at the limit', () => {+ expect(usageTone(c(7, 10))).toBe('normal');+ expect(usageTone(c(8, 10))).toBe('warning');+ expect(usageTone(c(43, 50))).toBe('warning');+ expect(usageTone(c(10, 10))).toBe('exhausted');+ expect(usageTone(c(12, 10))).toBe('exhausted');+ });++ test('unlimited plans have no tone', () => {+ expect(usageTone(c(0, -1))).toBe('unlimited');+ });+});++describe('usagePercent', () => {+ test('is capped at 100 and empty when unlimited', () => {+ expect(usagePercent(c(32, 50))).toBe(64);+ expect(usagePercent(c(12, 10))).toBe(100);+ expect(usagePercent(c(0, -1))).toBe(0);+ });+});++describe('hasContentQuota', () => {+ const usage = (o: number, b: number): ContentUsage => ({+ plan: 'starter',+ planName: 'Starter',+ periodStart: null,+ periodEnd: null,+ opportunities: c(0, o),+ briefs: c(0, b),+ });++ test('shows the card when either counter is limited', () => {+ expect(hasContentQuota(usage(10, 10))).toBe(true);+ expect(hasContentQuota(usage(-1, 10))).toBe(true);+ expect(hasContentQuota(usage(-1, -1))).toBe(false);+ expect(hasContentQuota(null)).toBe(false);+ });+});diff --git a/web/src/lib/content-usage.ts b/web/src/lib/content-usage.tsnew file mode 100644index 000000000..d29cd81cb--- /dev/null+++ b/web/src/lib/content-usage.ts@@ -0,0 +1,44 @@+/**+ * The Content page's monthly usage card (CONTENT-001): new opportunities and+ * briefs are two counters from the plan, renewing together with the+ * subscription. The figures come from GET /api/content/usage; this only+ * decides how they read.+ */++export interface UsageCounter {+ used: number;+ /** -1 means unlimited. */+ limit: number;+ remaining: number;+}++export interface ContentUsage {+ plan: string;+ planName: string | null;+ periodStart: string | null;+ periodEnd: string | null;+ opportunities: UsageCounter;+ briefs: UsageCounter;+}++export type UsageTone = 'normal' | 'warning' | 'exhausted' | 'unlimited';++/** Warning from 80% of the limit, exhausted at 100%. */+export const USAGE_WARNING_RATIO = 0.8;++export function usageTone(counter: UsageCounter): UsageTone {+ if (counter.limit === -1) return 'unlimited';+ if (counter.limit <= 0 || counter.used >= counter.limit) return 'exhausted';+ return counter.used / counter.limit >= USAGE_WARNING_RATIO ? 'warning' : 'normal';+}++/** Bar width, 0–100. */+export function usagePercent(counter: UsageCounter): number {+ if (counter.limit <= 0) return counter.limit === -1 ? 0 : 100;+ return Math.min(100, Math.round((counter.used / counter.limit) * 100));+}++/** The card is only worth showing when the plan limits at least one counter. */+export function hasContentQuota(usage: ContentUsage | null): usage is ContentUsage {+ return !!usage && (usage.opportunities.limit !== -1 || usage.briefs.limit !== -1);+}