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(prompts): count plan quota by tracked location rather than prompt row (#781)
Gökhan Geyikea8f0a69c5c7
diff --git a/supabase/migrations/00070_org_prompt_location_usage.sql b/supabase/migrations/00070_org_prompt_location_usage.sqlnew file mode 100644index 000000000..df47cb2b6--- /dev/null+++ b/supabase/migrations/00070_org_prompt_location_usage.sql@@ -0,0 +1,45 @@+-- Aggregate the tracked-location quota count in Postgres (#691 part 1).+--+-- The web tier first computed it by selecting every prompt row's `regions`+-- and summing in JavaScript. PostgREST silently caps an un-paginated select+-- at 1000 rows (the #427/#450/#464 trap), and the failure direction is the+-- bad one: a truncated sum UNDER-counts, so the quota guard would let an org+-- past its plan limit without an error anywhere. The largest org holds 552+-- prompt rows today, but part 2 of #691 multiplies rows into locations, so+-- the ceiling was already in reach. Aggregating here means no rows travel at+-- all — and the bulk-add path, which runs one guard check per prompt in+-- parallel, stops downloading the org's whole roster N times over.+--+-- One row per brand rather than a single org total: savePromptSet replaces a+-- brand's whole set, so its cap check and the wizards' capacity endpoint+-- need "the org minus this brand", which the caller derives from these rows.+--+-- A prompt's location count is `greatest(coalesce(array_length(regions,1),0),1)`+-- — one per region entry, minimum one, because the tracking worker runs a+-- prompt with no regions once (`regions or [null]`). This mirrors+-- `promptLocationCount` in web/src/lib/prompt-locations.ts exactly; the two+-- definitions must not drift.+--+-- SECURITY INVOKER on purpose, unlike the citation RPCs (#780): prompts,+-- prompt_sets and brands all carry org-membership select policies, so RLS+-- already scopes the aggregation to the caller's own org — a foreign+-- organization id simply aggregates zero visible rows.+create or replace function public.org_prompt_location_usage(p_organization_id uuid)+returns table (brand_id uuid, locations bigint)+language sql+stable+set search_path to 'public'+as $$+ select b.id, sum(greatest(coalesce(array_length(p.regions, 1), 0), 1))::bigint+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ join public.brands b on b.id = ps.brand_id+ where b.organization_id = p_organization_id+ group by b.id;+$$;++revoke all on function public.org_prompt_location_usage(uuid) from public;+grant execute on function public.org_prompt_location_usage(uuid) to authenticated, service_role;++comment on function public.org_prompt_location_usage(uuid) is+ 'Tracked prompt locations per brand for one org (#691) — the plan-quota unit, one per region entry per prompt, minimum one. Security invoker: RLS scopes it to the caller''s org.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 4f3b34d84..0ec856dd7 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -8395,3 +8395,52 @@ comment on function public.citation_url_candidates(uuid, text) iscomment on function public.citation_url_occurrences(uuid, bigint[], timestamptz, timestamptz, text[], text[], uuid[], uuid[]) is'Answers citing any of the given URL ids (#732) — the per-URL citation detail table, one row per answer. Members of the brand''s organization only (#779): a service-role caller reads empty.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00070_org_prompt_location_usage.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Aggregate the tracked-location quota count in Postgres (#691 part 1).+--+-- The web tier first computed it by selecting every prompt row's `regions`+-- and summing in JavaScript. PostgREST silently caps an un-paginated select+-- at 1000 rows (the #427/#450/#464 trap), and the failure direction is the+-- bad one: a truncated sum UNDER-counts, so the quota guard would let an org+-- past its plan limit without an error anywhere. The largest org holds 552+-- prompt rows today, but part 2 of #691 multiplies rows into locations, so+-- the ceiling was already in reach. Aggregating here means no rows travel at+-- all — and the bulk-add path, which runs one guard check per prompt in+-- parallel, stops downloading the org's whole roster N times over.+--+-- One row per brand rather than a single org total: savePromptSet replaces a+-- brand's whole set, so its cap check and the wizards' capacity endpoint+-- need "the org minus this brand", which the caller derives from these rows.+--+-- A prompt's location count is `greatest(coalesce(array_length(regions,1),0),1)`+-- — one per region entry, minimum one, because the tracking worker runs a+-- prompt with no regions once (`regions or [null]`). This mirrors+-- `promptLocationCount` in web/src/lib/prompt-locations.ts exactly; the two+-- definitions must not drift.+--+-- SECURITY INVOKER on purpose, unlike the citation RPCs (#780): prompts,+-- prompt_sets and brands all carry org-membership select policies, so RLS+-- already scopes the aggregation to the caller's own org — a foreign+-- organization id simply aggregates zero visible rows.+create or replace function public.org_prompt_location_usage(p_organization_id uuid)+returns table (brand_id uuid, locations bigint)+language sql+stable+set search_path to 'public'+as $$+ select b.id, sum(greatest(coalesce(array_length(p.regions, 1), 0), 1))::bigint+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ join public.brands b on b.id = ps.brand_id+ where b.organization_id = p_organization_id+ group by b.id;+$$;++revoke all on function public.org_prompt_location_usage(uuid) from public;+grant execute on function public.org_prompt_location_usage(uuid) to authenticated, service_role;++comment on function public.org_prompt_location_usage(uuid) is+ 'Tracked prompt locations per brand for one org (#691) — the plan-quota unit, one per region entry per prompt, minimum one. Security invoker: RLS scopes it to the caller''s org.';+diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex a6dbb8052..c0576648b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -1517,14 +1517,14 @@ export default function InsightsPage() {/><KpiCardtitle="Tracked Prompts"- tooltip="Distinct prompts that produced tracked results in the selected period and filters. The quota below is current usage across your organization — it does not change with the date range."+ tooltip="Distinct prompts that produced tracked results in the selected period and filters. The quota below is current usage across your organization, counting one per location each prompt targets — it does not change with the date range."icon={Layers}value={trackedPrompts?.activeInPeriod ?? 0}sub={trackedPrompts && trackedPrompts.quotaLimit !== -1 ? (<><span className="tabular-nums">- {trackedPrompts.quotaUsed} / {trackedPrompts.quotaLimit} prompts+ {trackedPrompts.quotaUsed} / {trackedPrompts.quotaLimit} prompt locations</span>{trackedPrompts.quotaUsed >= trackedPrompts.quotaLimit * 0.9 && (<button@@ -1540,7 +1540,7 @@ export default function InsightsPage() {)}</>) : (- `${trackedPrompts?.quotaUsed ?? 0} prompts tracked`+ `${trackedPrompts?.quotaUsed ?? 0} prompt locations tracked`)}onClick={() => router.push('/dashboard/prompts')}diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 9973f6fa2..2a6f7db4d 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -3,8 +3,18 @@import { createClient } from '@/lib/supabase/server';import { revalidatePath } from 'next/cache';import type { PromptSet, Prompt, AIPlatform, PromptVolume } from '@/types';-import { enforceLimit, getOrgPlan, PlanLimitError } from '@/lib/guards/plan-guard';-import { ALL_MODELS, ALL_SCRAPERS, DEFAULT_PROMPT_RANGE_DAYS } from '@/config/prompt-options';+import { getOrgPlan, PlanLimitError } from '@/lib/guards/plan-guard';+import {+ getOrgLocationUsage,+ locationLimitMessage,+ promptLocationCount,+} from '@/lib/prompt-locations';+import {+ ALL_MODELS,+ ALL_SCRAPERS,+ DEFAULT_PROMPT_RANGE_DAYS,+ REGIONS,+} from '@/config/prompt-options';import type { Plan } from '@/config/plans';import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';@@ -74,21 +84,6 @@ function mapPromptSetRow(};}-async function getOrgPromptCount(- supabase: Awaited<ReturnType<typeof createClient>>,- organizationId: string,-): Promise<number> {- const { count } = await supabase- .from('prompts')- .select('id, prompt_sets!inner(brand_id, brands!inner(organization_id))', {- count: 'exact',- head: true,- })- .eq('prompt_sets.brands.organization_id', organizationId);-- return count ?? 0;-}-async function getBrandContext(supabase: Awaited<ReturnType<typeof createClient>>,brandId: string,@@ -155,11 +150,14 @@ interface SavePromptSetInput {export type SavePromptSetResult = { promptSet: PromptSet } | { error: string; code?: 'plan_limit' };/**- * How many prompts a brand's save may total before hitting the org's plan cap.- * `used` counts prompts on the org's OTHER brands only — savePromptSet- * replaces this brand's own set, so its current prompts don't count against a- * re-save. Lets the setup wizards gate the review step inline (counter +- * disabled Continue) instead of failing the save after the fact.+ * How many tracked locations a brand's save may total before hitting the+ * org's plan cap (#691: quota counts prompt × location, not prompt rows —+ * though the wizards only create single-location prompts, so for them one+ * prompt still costs one). `used` counts locations on the org's OTHER brands+ * only — savePromptSet replaces this brand's own set, so its current prompts+ * don't count against a re-save. Lets the setup wizards gate the review step+ * inline (counter + disabled Continue) instead of failing the save after the+ * fact.*/export async function getPromptCapacity(brandId: string,@@ -167,14 +165,10 @@ export async function getPromptCapacity(const supabase = await createClient();const { organizationId: orgId } = await getBrandContext(supabase, brandId);const plan = await getOrgPlan(orgId);- const totalOrgPrompts = await getOrgPromptCount(supabase, orgId);- const { count: brandPromptCount } = await supabase- .from('prompts')- .select('id, prompt_sets!inner(brand_id)', { count: 'exact', head: true })- .eq('prompt_sets.brand_id', brandId);+ const usage = await getOrgLocationUsage(supabase, orgId);return {maxPrompts: plan.limits.maxPrompts,- used: totalOrgPrompts - (brandPromptCount ?? 0),+ used: usage.total - (usage.byBrand.get(brandId) ?? 0),};}@@ -193,28 +187,17 @@ export async function savePromptSet(input: SavePromptSetInput): Promise<SaveProm);const plan = await getOrgPlan(orgId);- // Count existing prompts for this org, excluding prompts that belong- // to this brand (they will be replaced below)- const totalOrgPrompts = await getOrgPromptCount(supabase, orgId);-- const { count: brandPromptCount } = await supabase- .from('prompts')- .select('id, prompt_sets!inner(brand_id)', { count: 'exact', head: true })- .eq('prompt_sets.brand_id', input.brandId);-- const otherPrompts = totalOrgPrompts - (brandPromptCount ?? 0);-- // Inclusive cap: saving exactly maxPrompts is allowed; only reject when the- // resulting total would exceed it. Spell out the counts so the user knows- // exactly how many prompts to remove (onboarding generates 5 per topic, so- // hitting the cap there is a normal, recoverable state).- const maxPrompts = plan.limits.maxPrompts;- const requestedTotal = otherPrompts + input.prompts.length;- if (maxPrompts !== -1 && requestedTotal > maxPrompts) {- return {- code: 'plan_limit',- error: `Your ${plan.name} plan allows up to ${maxPrompts} tracked prompts and this would save ${requestedTotal}. Remove ${requestedTotal - maxPrompts} prompt${requestedTotal - maxPrompts === 1 ? '' : 's'} to continue, or upgrade your plan.`,- };+ // Count existing tracked locations for this org, excluding this brand's own+ // (its whole set is replaced below, so a re-save doesn't compete with+ // itself). Every prompt saved here targets exactly one location — the+ // brand's region — so the request adds one location per prompt. The cap is+ // inclusive: landing exactly on maxPrompts is allowed (onboarding generates+ // 5 per topic, so hitting the cap there is a normal, recoverable state).+ const usage = await getOrgLocationUsage(supabase, orgId);+ const otherLocations = usage.total - (usage.byBrand.get(input.brandId) ?? 0);+ const limitError = locationLimitMessage(plan, otherLocations, input.prompts.length);+ if (limitError) {+ return { code: 'plan_limit', error: limitError };}// Delete existing prompt sets for this brand to avoid duplicates@@ -306,6 +289,7 @@ export async function updatePrompt(category?: string;platforms?: string[];models?: string[];+ regions?: string[];isActive?: boolean;},): Promise<Prompt> {@@ -316,34 +300,49 @@ export async function updatePrompt(if (updates.category !== undefined) payload.category = updates.category || null;if (updates.isActive !== undefined) payload.is_active = updates.isActive;- if (updates.category !== undefined) {- const { data: promptWithBrand } = await supabase+ // Category, platform/model and region updates all need context from the+ // prompt's row (its current regions, brand, org and shopping pref) — one+ // fetch serves every branch below.+ let ctx: {+ regions: string[] | null;+ brandId: string;+ organizationId: string;+ shoppingEnabled: boolean | null;+ } | null = null;+ if (+ updates.category !== undefined ||+ updates.platforms !== undefined ||+ updates.models !== undefined ||+ updates.regions !== undefined+ ) {+ const { data: promptRow } = await supabase.from('prompts')- .select('prompt_sets!inner(brand_id)')+ .select(+ 'regions, prompt_sets!inner(brand_id, brands!inner(organization_id, shopping_mode_enabled))',+ ).eq('id', id).single();- const brandId = (promptWithBrand?.prompt_sets as { brand_id: string })?.brand_id;- if (brandId) {- payload.topic_id = await resolveTopicId(supabase, brandId, updates.category);- }+ const set = promptRow?.prompt_sets as unknown as {+ brand_id: string;+ brands: { organization_id: string; shopping_mode_enabled: boolean | null };+ } | null;+ if (!set?.brands?.organization_id) throw new Error('Prompt not found');+ ctx = {+ regions: (promptRow?.regions as string[] | null) ?? null,+ brandId: set.brand_id,+ organizationId: set.brands.organization_id,+ shoppingEnabled: set.brands.shopping_mode_enabled,+ };}- if (updates.platforms !== undefined || updates.models !== undefined) {- const { data: promptRow } = await supabase- .from('prompts')- .select('prompt_sets!inner(brands!inner(organization_id, shopping_mode_enabled))')- .eq('id', id)- .single();- const brandRow = (- promptRow?.prompt_sets as {- brands: { organization_id: string; shopping_mode_enabled: boolean | null };- }- )?.brands;- if (!brandRow?.organization_id) throw new Error('Prompt not found');+ if (updates.category !== undefined && ctx) {+ payload.topic_id = await resolveTopicId(supabase, ctx.brandId, updates.category);+ }- const plan = await getOrgPlan(brandRow.organization_id);+ if ((updates.platforms !== undefined || updates.models !== undefined) && ctx) {+ const plan = await getOrgPlan(ctx.organizationId);const filtered = filterByPlan(plan, updates.platforms ?? [], updates.models ?? []);- const platforms = stripShoppingWhenDisabled(filtered.platforms, brandRow.shopping_mode_enabled);+ const platforms = stripShoppingWhenDisabled(filtered.platforms, ctx.shoppingEnabled);if (platforms.length === 0 && filtered.models.length === 0) {throw new Error('At least one platform or model must be selected.');}@@ -351,6 +350,39 @@ export async function updatePrompt(if (updates.models !== undefined) payload.models = filtered.models;}+ // Changing a prompt's locations changes what the plan meters (#691): an+ // edit that grows the list from 1 to 3 locations costs exactly what adding+ // two more single-location prompts would, so it passes the same guard with+ // the same message. Only the DELTA is checked — re-saving unchanged at the+ // limit succeeds, and removing locations always frees capacity.+ //+ // Throwing PlanLimitError here follows this function's existing error+ // style; nothing in the UI can send `regions` yet, and the region editor+ // that will (#691 follow-up) must surface this as a value, since+ // production masks thrown server-action messages (#427).+ if (updates.regions !== undefined && ctx) {+ const regions = [...new Set(updates.regions.map((r) => r.trim().toUpperCase()))];+ if (regions.length === 0) {+ throw new Error('Select at least one location.');+ }+ const known = new Set<string>(REGIONS.map((r) => r.code));+ const unknown = regions.filter((r) => !known.has(r));+ if (unknown.length > 0) {+ throw new Error(+ `Unknown location code${unknown.length === 1 ? '' : 's'}: ${unknown.join(', ')}`,+ );+ }++ const delta = regions.length - promptLocationCount(ctx.regions);+ if (delta > 0) {+ const plan = await getOrgPlan(ctx.organizationId);+ const usage = await getOrgLocationUsage(supabase, ctx.organizationId);+ const limitError = locationLimitMessage(plan, usage.total, delta);+ if (limitError) throw new PlanLimitError(limitError, plan.name);+ }+ payload.regions = regions;+ }+const { data, error } = await supabase.from('prompts').update(payload)@@ -396,15 +428,13 @@ export async function addPromptToSet(input: AddPromptInput): Promise<AddPromptTosupabase,ps.brand_id as string,);- const currentCount = await getOrgPromptCount(supabase, orgId);- try {- await enforceLimit(orgId, 'maxPrompts', currentCount);- } catch (err) {- if (err instanceof PlanLimitError) return { error: err.message, code: 'plan_limit' };- throw err;- }-const plan = await getOrgPlan(orgId);++ // A new prompt starts at exactly one location (the brand's region), so the+ // change adds one to the org's tracked-location total (#691).+ const usage = await getOrgLocationUsage(supabase, orgId);+ const limitError = locationLimitMessage(plan, usage.total, 1);+ if (limitError) return { error: limitError, code: 'plan_limit' };const filtered = filterByPlan(plan, input.platforms, input.models ?? []);if (filtered.platforms.length === 0 && filtered.models.length === 0) {return { error: 'At least one platform or model must be selected.' };diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex b52d38ff5..b49aa07c7 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -22,6 +22,7 @@ import {import { normalizeCitationUrl } from '@/lib/citations/normalize';import { getTopicById } from '@/lib/actions/topic';import { getOrgPlan } from '@/lib/guards/plan-guard';+import { getOrgLocationUsage } from '@/lib/prompt-locations';import { getPromptVolumes } from '@/lib/actions/volumes';import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';@@ -525,8 +526,10 @@ export async function getVisibilityRateKpi(* cards (the `tracked_prompt_count` RPC mirrors `insights_aggregates`,* shopping excluded) — because a static account-state number sitting in a* filter-reactive row would read as inconsistent. The quota sub-line is- * deliberately a "now" fact: org-wide usage against the effective plan- * limit, matching what `enforceLimit` counts on write.+ * deliberately a "now" fact: org-wide tracked LOCATIONS against the+ * effective plan limit (#691), from the same counter every write-path guard+ * uses, so the number shown and the number that rejects a save cannot+ * disagree.*/export async function getTrackedPromptsKpi(brandId: string,@@ -549,16 +552,10 @@ export async function getTrackedPromptsKpi(.single();const orgId = (brand?.organization_id as string | undefined) ?? null;- const countOrgPrompts = async (): Promise<number> => {+ const countOrgLocations = async (): Promise<number> => {if (!orgId) return 0;- const { count } = await supabase- .from('prompts')- .select('id, prompt_sets!inner(brand_id, brands!inner(organization_id))', {- count: 'exact',- head: true,- })- .eq('prompt_sets.brands.organization_id', orgId);- return count ?? 0;+ const usage = await getOrgLocationUsage(supabase, orgId);+ return usage.total;};const [rpcResult, plan, quotaUsed] = await Promise.all([@@ -581,7 +578,7 @@ export async function getTrackedPromptsKpi(p_topic_id: opts?.topicId ?? undefined,}),orgId ? getOrgPlan(orgId) : Promise.resolve(null),- countOrgPrompts(),+ countOrgLocations(),]);if (rpcResult.error) throw new Error(rpcResult.error.message);diff --git a/web/src/lib/prompt-locations.test.ts b/web/src/lib/prompt-locations.test.tsnew file mode 100644index 000000000..c805ed9ec--- /dev/null+++ b/web/src/lib/prompt-locations.test.ts@@ -0,0 +1,85 @@+import { describe, it, expect } from 'vitest';+import {+ promptLocationCount,+ summarizeLocationRows,+ locationLimitMessage,+} from './prompt-locations';+import { PLANS } from '@/config/plans';++const starter = PLANS.starter; // maxPrompts: 50+const selfHosted = PLANS.self_hosted; // maxPrompts: -1+const enterprise = PLANS.enterprise; // maxPrompts: -1++describe('promptLocationCount', () => {+ it('counts one location per region entry', () => {+ expect(promptLocationCount(['US'])).toBe(1);+ expect(promptLocationCount(['US', 'DE', 'TR'])).toBe(3);+ });++ it('costs one for prompts with no regions — the worker still runs them once', () => {+ expect(promptLocationCount([])).toBe(1);+ expect(promptLocationCount(null)).toBe(1);+ expect(promptLocationCount(undefined)).toBe(1);+ });+});++describe('summarizeLocationRows', () => {+ it('totals the per-brand rows the RPC returns', () => {+ const usage = summarizeLocationRows([+ { brand_id: 'a', locations: 3 },+ { brand_id: 'b', locations: 1 },+ ]);+ expect(usage.total).toBe(4);+ expect(usage.byBrand.get('a')).toBe(3);+ expect(usage.byBrand.get('b')).toBe(1);+ });++ it('returns zero usage for no rows', () => {+ const usage = summarizeLocationRows([]);+ expect(usage.total).toBe(0);+ expect(usage.byBrand.size).toBe(0);+ });+});++describe('locationLimitMessage', () => {+ it('never rejects on the -1 sentinel (self-host and enterprise stay unmetered)', () => {+ expect(locationLimitMessage(selfHosted, 10_000, 500)).toBeNull();+ expect(locationLimitMessage(enterprise, 10_000, 500)).toBeNull();+ });++ it('allows landing exactly on the limit (inclusive cap)', () => {+ expect(locationLimitMessage(starter, 49, 1)).toBeNull();+ expect(locationLimitMessage(starter, 0, 50)).toBeNull();+ });++ it('rejects the first location past the limit', () => {+ expect(locationLimitMessage(starter, 50, 1)).not.toBeNull();+ expect(locationLimitMessage(starter, 49, 2)).not.toBeNull();+ });++ it('measures the delta, not one: a multi-location add near the limit is rejected', () => {+ // 48 used + a prompt targeting 3 locations = 51 > 50, even though a+ // row-count check (48 < 50) would have let it through.+ expect(locationLimitMessage(starter, 48, 3)).not.toBeNull();+ });++ it('always allows changes that add nothing, even over the limit', () => {+ // Re-saving unchanged at the cap, or after a plan downgrade left the org+ // over its limit, must not brick the existing set.+ expect(locationLimitMessage(starter, 50, 0)).toBeNull();+ expect(locationLimitMessage(starter, 120, 0)).toBeNull();+ expect(locationLimitMessage(starter, 120, -5)).toBeNull();+ });++ it('spells out the location math in the message', () => {+ const msg = locationLimitMessage(starter, 48, 5);+ expect(msg).toContain('50 tracked prompt locations');+ expect(msg).toContain('53');+ expect(msg).toContain('48 in place + 5 added');+ expect(msg).toContain('Remove 3 locations');+ });++ it('uses singular grammar for a single excess location', () => {+ expect(locationLimitMessage(starter, 50, 1)).toContain('Remove 1 location ');+ });+});diff --git a/web/src/lib/prompt-locations.ts b/web/src/lib/prompt-locations.tsnew file mode 100644index 000000000..92a13befe--- /dev/null+++ b/web/src/lib/prompt-locations.ts@@ -0,0 +1,102 @@+import type { createClient } from '@/lib/supabase/server';+import type { Plan } from '@/config/plans';++/**+ * Location-based prompt quota (#691).+ *+ * The billable unit of a plan's `maxPrompts` limit is the tracked LOCATION,+ * not the prompt row: one prompt tracked in three locations produces three+ * times the scraper and model calls of a single-location prompt (the worker+ * expands `prompt × (models + scrapers) × regions`), so it counts three+ * against the cap.+ *+ * This module is the single definition of that count. Enforcement on every+ * write path, the capacity endpoint the setup wizards read, and the Tracked+ * Prompts KPI sub-line all call into here — the number a user sees and the+ * number that rejects a save can never drift apart.+ */++type ServerSupabase = Awaited<ReturnType<typeof createClient>>;++/**+ * Locations one prompt tracks: one per region entry. A prompt with an empty+ * or missing region list still runs once (the worker falls back to a single+ * untargeted pass), so it costs one.+ *+ * Mirrored in SQL by `org_prompt_location_usage` (00070) as+ * `greatest(coalesce(array_length(regions,1),0),1)` — the two definitions+ * must not drift.+ */+export function promptLocationCount(regions: readonly unknown[] | null | undefined): number {+ return Array.isArray(regions) && regions.length > 0 ? regions.length : 1;+}++export interface OrgLocationUsage {+ /** Tracked locations across every prompt in the org. */+ total: number;+ /**+ * Tracked locations per brand — for replace-style saves (savePromptSet+ * swaps a brand's whole set, so that brand's current locations don't count+ * against its own re-save) and for the wizards' capacity display.+ */+ byBrand: Map<string, number>;+}++/** Pure aggregation half of {@link getOrgLocationUsage}, split out for tests. */+export function summarizeLocationRows(+ rows: { brand_id: string; locations: number }[],+): OrgLocationUsage {+ const byBrand = new Map<string, number>();+ let total = 0;+ for (const row of rows) {+ total += row.locations;+ byBrand.set(row.brand_id, row.locations);+ }+ return { total, byBrand };+}++/**+ * The count comes from the `org_prompt_location_usage` RPC — one aggregate+ * per call, no rows travel. Selecting the org's prompt rows and summing here+ * would look equivalent but isn't: PostgREST silently caps an un-paginated+ * select at 1000 rows (the #427/#450/#464 trap), and a truncated sum+ * UNDER-counts — the guard would wave an over-limit org through with no+ * error anywhere. The RPC is security invoker, so RLS scopes it to orgs the+ * caller belongs to.+ */+export async function getOrgLocationUsage(+ supabase: ServerSupabase,+ organizationId: string,+): Promise<OrgLocationUsage> {+ const { data, error } = await supabase.rpc('org_prompt_location_usage', {+ p_organization_id: organizationId,+ });+ if (error) throw new Error(error.message);+ return summarizeLocationRows(data ?? []);+}++/**+ * The one quota decision: may a change that adds `adding` locations proceed+ * when `used` are already tracked? Returns null to allow, or the user-facing+ * rejection message.+ *+ * The rules every caller relies on:+ * - `maxPrompts === -1` (self-host, enterprise) is unlimited — always null.+ * - The cap is inclusive: landing exactly on the limit is allowed.+ * - Only growth is metered: a change that adds no locations (re-saving+ * unchanged, removing locations) always passes, even when the org is+ * already over its limit — e.g. after a plan downgrade.+ */+export function locationLimitMessage(plan: Plan, used: number, adding: number): string | null {+ const max = plan.limits.maxPrompts;+ if (max === -1 || adding <= 0) return null;+ const total = used + adding;+ if (total <= max) return null;+ const over = total - max;+ return (+ `Your ${plan.name} plan allows up to ${max} tracked prompt locations — each prompt ` ++ `counts once per location it targets. This change would use ${total} ` ++ `(${used} in place + ${adding} added). Remove ${over} location${over === 1 ? '' : 's'} ` ++ `to continue, or upgrade your plan.`+ );+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 953efe6d9..d8a2a17a9 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -2687,6 +2687,13 @@ export type Database = {regions: string[]}[]}+ org_prompt_location_usage: {+ Args: { p_organization_id: string }+ Returns: {+ brand_id: string+ locations: number+ }[]+ }prompt_performance_aggregates: {Args: {p_brand_id: string