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): break the per-prompt health columns down by location (#784)
Gökhan Geyik385df84d6a34
diff --git a/supabase/migrations/00072_prompt_visibility_summaries_region.sql b/supabase/migrations/00072_prompt_visibility_summaries_region.sqlnew file mode 100644index 000000000..3e446983a--- /dev/null+++ b/supabase/migrations/00072_prompt_visibility_summaries_region.sql@@ -0,0 +1,77 @@+-- Let the per-prompt health column answer "…in which location?" (#691).+--+-- Prompts can now be tracked in several places at once, so a single blended+-- number per prompt hides the thing multi-location tracking was bought for:+-- a prompt can be strong at home and invisible in Germany, and the All+-- Prompts table averaged the two into one figure with no way to split them.+-- Every other analytical surface already takes a region — Insights, the+-- citation RPCs, the KPI cards — this one was the gap.+--+-- The parameter is appended with a NULL default, and NULL keeps the previous+-- whole-brand behaviour exactly, so callers that don't pass it are unchanged.+--+-- The 3-argument signature is dropped rather than left in place: with both+-- installed, a 3-argument call would match the old function AND the new one+-- through its default, which Postgres rejects as ambiguous. Dropping it is+-- safe across the deploy window because PostgREST passes arguments by name —+-- the running app's 3-name call binds to the new function and takes the+-- default.+DROP FUNCTION IF EXISTS public.prompt_visibility_summaries(uuid, timestamptz, timestamptz);++CREATE FUNCTION public.prompt_visibility_summaries(+ p_brand_id uuid,+ p_date_from timestamptz DEFAULT NULL,+ p_date_to timestamptz DEFAULT NULL,+ p_region text DEFAULT NULL+)+RETURNS TABLE (+ prompt_id uuid,+ avg_visibility double precision,+ avg_visibility_visible double precision,+ total_mentions bigint,+ total_citations bigint,+ runs bigint,+ visible_runs bigint,+ mention_answers bigint,+ citation_answers bigint,+ position_factor double precision,+ last_run_at timestamptz+)+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ SELECT pr.prompt_id,+ AVG(COALESCE(pr.visibility_score, 0))::double precision AS avg_visibility,+ AVG(COALESCE(pr.visibility_score, 0))+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)+ ::double precision AS avg_visibility_visible,+ COALESCE(SUM(pr.mention_count), 0)::bigint AS total_mentions,+ COALESCE(SUM(pr.citation_count), 0)::bigint AS total_citations,+ COUNT(*)::bigint AS runs,+ COUNT(*) FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)::bigint+ AS visible_runs,+ COUNT(*) FILTER (WHERE pr.mention_count > 0)::bigint AS mention_answers,+ COUNT(*) FILTER (WHERE pr.citation_count > 0)::bigint AS citation_answers,+ AVG(1.0 / pr.mention_position)+ FILTER (WHERE pr.mention_position IS NOT NULL)+ ::double precision AS position_factor,+ MAX(pr.created_at) AS last_run_at+ FROM public.prompt_results pr+ WHERE pr.brand_id = p_brand_id+ AND pr.prompt_id IS NOT NULL+ AND pr.platform <> 'chatgpt-shopping' -- #155 - isolate from analytics+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)+ AND (p_region IS NULL OR pr.region = p_region)+ GROUP BY pr.prompt_id+$$;++GRANT EXECUTE ON FUNCTION+ public.prompt_visibility_summaries(uuid, timestamptz, timestamptz, text)+ TO authenticated;++COMMENT ON FUNCTION+ public.prompt_visibility_summaries(uuid, timestamptz, timestamptz, text) IS+ 'Per-prompt visibility/mention aggregates for the All Prompts table. p_region scopes to one tracked location (#691); NULL blends every location, as before.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex ecf416b5b..21b5bcaff 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -8491,3 +8491,84 @@ where ps.id = p.prompt_set_idcomment on column public.brands.state is'Default US state for prompts created for this brand (#691). Targeting itself lives in prompts.regions as location codes (US-CA); the tracking worker does not read this column.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00072_prompt_visibility_summaries_region.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Let the per-prompt health column answer "…in which location?" (#691).+--+-- Prompts can now be tracked in several places at once, so a single blended+-- number per prompt hides the thing multi-location tracking was bought for:+-- a prompt can be strong at home and invisible in Germany, and the All+-- Prompts table averaged the two into one figure with no way to split them.+-- Every other analytical surface already takes a region — Insights, the+-- citation RPCs, the KPI cards — this one was the gap.+--+-- The parameter is appended with a NULL default, and NULL keeps the previous+-- whole-brand behaviour exactly, so callers that don't pass it are unchanged.+--+-- The 3-argument signature is dropped rather than left in place: with both+-- installed, a 3-argument call would match the old function AND the new one+-- through its default, which Postgres rejects as ambiguous. Dropping it is+-- safe across the deploy window because PostgREST passes arguments by name —+-- the running app's 3-name call binds to the new function and takes the+-- default.+DROP FUNCTION IF EXISTS public.prompt_visibility_summaries(uuid, timestamptz, timestamptz);++CREATE FUNCTION public.prompt_visibility_summaries(+ p_brand_id uuid,+ p_date_from timestamptz DEFAULT NULL,+ p_date_to timestamptz DEFAULT NULL,+ p_region text DEFAULT NULL+)+RETURNS TABLE (+ prompt_id uuid,+ avg_visibility double precision,+ avg_visibility_visible double precision,+ total_mentions bigint,+ total_citations bigint,+ runs bigint,+ visible_runs bigint,+ mention_answers bigint,+ citation_answers bigint,+ position_factor double precision,+ last_run_at timestamptz+)+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ SELECT pr.prompt_id,+ AVG(COALESCE(pr.visibility_score, 0))::double precision AS avg_visibility,+ AVG(COALESCE(pr.visibility_score, 0))+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)+ ::double precision AS avg_visibility_visible,+ COALESCE(SUM(pr.mention_count), 0)::bigint AS total_mentions,+ COALESCE(SUM(pr.citation_count), 0)::bigint AS total_citations,+ COUNT(*)::bigint AS runs,+ COUNT(*) FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)::bigint+ AS visible_runs,+ COUNT(*) FILTER (WHERE pr.mention_count > 0)::bigint AS mention_answers,+ COUNT(*) FILTER (WHERE pr.citation_count > 0)::bigint AS citation_answers,+ AVG(1.0 / pr.mention_position)+ FILTER (WHERE pr.mention_position IS NOT NULL)+ ::double precision AS position_factor,+ MAX(pr.created_at) AS last_run_at+ FROM public.prompt_results pr+ WHERE pr.brand_id = p_brand_id+ AND pr.prompt_id IS NOT NULL+ AND pr.platform <> 'chatgpt-shopping' -- #155 - isolate from analytics+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)+ AND (p_region IS NULL OR pr.region = p_region)+ GROUP BY pr.prompt_id+$$;++GRANT EXECUTE ON FUNCTION+ public.prompt_visibility_summaries(uuid, timestamptz, timestamptz, text)+ TO authenticated;++COMMENT ON FUNCTION+ public.prompt_visibility_summaries(uuid, timestamptz, timestamptz, text) IS+ 'Per-prompt visibility/mention aggregates for the All Prompts table. p_region scopes to one tracked location (#691); NULL blends every location, as before.';+diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsxindex 890dd9c6e..4604de026 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx@@ -38,6 +38,7 @@ import {RotateCw,} from 'lucide-react';import { cn } from '@/lib/utils';+import { formatRegionDisplay } from '@/lib/region';import { toast } from 'sonner';import { useUserRole } from '@/hooks/use-user-role';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';@@ -486,7 +487,7 @@ function PlatformResultGroup({<ModelBadge model={group.modelUsed ?? group.platform} platform={group.platform} />{group.region && (<Badge variant="outline" className="text-[10px]">- {group.region}+ {formatRegionDisplay(group.region)}</Badge>)}<span className="text-[11px] text-muted-foreground">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex c0fad1d31..58d37d159 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -98,6 +98,8 @@ import {type PromptRangePreset,} from '@/config/prompt-options';import { DateRangeFilter } from '@/components/filters/date-range-filter';+import { getBrandFilterOptions } from '@/lib/actions/tracking';+import { formatRegionDisplay } from '@/lib/region';import { DataSourcesPanel } from './_data-sources-panel';import { PLANS } from '@/config/plans';import { getTopics } from '@/lib/actions/topic';@@ -995,6 +997,10 @@ export default function PromptsPage() {return DEFAULT_PROMPT_RANGE_PRESET;})();const [rangePreset, setRangePreset] = useState<PromptRangePreset>(initialRange);+ // Which tracked location the health columns describe. Empty = every+ // location blended, which is what the table has always shown (#691).+ const [regionFilter, setRegionFilter] = useState('');+ const [availableRegions, setAvailableRegions] = useState<string[]>([]);const [customFrom, setCustomFrom] = useState(() => searchParams.get('from') ?? '');const [customTo, setCustomTo] = useState(() => searchParams.get('to') ?? '');@@ -1080,6 +1086,7 @@ export default function PromptsPage() {days: range?.days,from: range?.from,to: range?.to,+ region: regionFilter || undefined,});if (isCancelled?.()) return;setVolumes(page.volumes);@@ -1098,7 +1105,7 @@ export default function PromptsPage() {if (!isCancelled?.()) setLoading(false);}},- [activeBrandId, range],+ [activeBrandId, range, regionFilter],);useEffect(() => {@@ -1109,6 +1116,35 @@ export default function PromptsPage() {};}, [loadData]);+ // Locations the brand has actually produced results in — the same+ // whole-brand list the Visibility page offers, so the two pages never+ // disagree about where this brand is tracked. A brand tracked in one place+ // gets no control at all: a filter with a single option is noise.+ useEffect(() => {+ if (!activeBrandId) {+ setAvailableRegions([]);+ return;+ }+ let cancelled = false;+ getBrandFilterOptions(activeBrandId)+ .then((options) => {+ if (cancelled) return;+ setAvailableRegions([...options.regions].sort((a, b) => a.localeCompare(b)));+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [activeBrandId]);++ // A location that stops producing results must not keep filtering the+ // table to nothing — fall back to the blended view.+ useEffect(() => {+ if (regionFilter && availableRegions.length > 0 && !availableRegions.includes(regionFilter)) {+ setRegionFilter('');+ }+ }, [availableRegions, regionFilter]);+// loadData changes identity whenever the date range does. The watch below// must not restart for that, so it reaches the current one through a ref.const loadDataRef = useRef(loadData);@@ -1465,6 +1501,36 @@ export default function PromptsPage() {onFromChange={setCustomFrom}onToChange={setCustomTo}/>++ {availableRegions.length > 1 && (+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">+ Location+ </label>+ <Select+ value={regionFilter || null}+ onValueChange={(v) => setRegionFilter(!v || v === '__all__' ? '' : String(v))}+ >+ <SelectTrigger className="h-8 w-48 text-xs">+ <SelectValue placeholder="All Locations">+ {(value) =>+ value && value !== '__all__'+ ? formatRegionDisplay(String(value))+ : 'All Locations'+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="__all__">All Locations</SelectItem>+ {availableRegions.map((r) => (+ <SelectItem key={r} value={r}>+ {formatRegionDisplay(r)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}</div>)}diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 5981fb545..ca26b63d0 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -630,15 +630,21 @@ export interface PromptsPageData {*/export async function getPromptsPageData(brandId: string,- opts?: { days?: number; from?: string; to?: string },+ opts?: { days?: number; from?: string; to?: string; region?: string },): Promise<PromptsPageData> {- // Only the visibility summaries are window-scoped. Prompt sets are the- // roster itself, and volumes are keyword-level estimates with no date- // dimension, so neither changes with the selected range.+ // Only the visibility summaries are window- and location-scoped. Prompt+ // sets are the roster itself, and volumes are keyword-level estimates with+ // no date dimension, so neither changes with the selected range or the+ // selected location.const days = opts?.days ?? DEFAULT_PROMPT_RANGE_DAYS;const [promptSets, visibility, volumesResult] = await Promise.all([getPromptSets(brandId),- getPromptVisibilitySummaries(brandId, { days, from: opts?.from, to: opts?.to }),+ getPromptVisibilitySummaries(brandId, {+ days,+ from: opts?.from,+ to: opts?.to,+ region: opts?.region,+ }),getPromptVolumes(brandId).then((r) => ({ volumes: r.volumes, quota: r.quota ?? null, degraded: false }),(err) => {diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex b49aa07c7..f88118a2d 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -603,6 +603,10 @@ export interface InsightsFilterOptions {* Deliberately unfiltered (whole-brand): the dropdowns must keep offering* every value the brand has ever produced, not just the current window's.*/+export async function getBrandFilterOptions(brandId: string): Promise<InsightsFilterOptions> {+ return getInsightsFilterOptions(brandId);+}+async function getInsightsFilterOptions(brandId: string): Promise<InsightsFilterOptions> {const supabase = await createClient();const { data, error } = await supabase.rpc('insights_filter_options', { p_brand_id: brandId });@@ -1631,12 +1635,17 @@ export interface PromptVisibilitySummary {* last N days (default 30). Used by the All Prompts tab to show a quick* health column next to each prompt.*+ * `region` scopes the aggregate to one tracked location (#691). Without it+ * a multi-location prompt's figures are the blend of everywhere it runs,+ * which hides exactly what tracking several locations was meant to reveal —+ * a prompt can be strong at home and invisible abroad.+ ** Returns a map keyed by prompt_id. Prompts without any runs in the window* simply won't appear in the map (callers should render "—").*/export async function getPromptVisibilitySummaries(brandId: string,- opts?: { days?: number; from?: string; to?: string },+ opts?: { days?: number; from?: string; to?: string; region?: string },): Promise<Record<string, PromptVisibilitySummary>> {const supabase = await createClient();// `from`/`to` win when given (the custom range, #713); otherwise the day@@ -1653,6 +1662,8 @@ export async function getPromptVisibilitySummaries(p_brand_id: brandId,p_date_from: since,p_date_to: opts?.to ?? undefined,+ // One tracked location, or every location blended when absent (#691).+ p_region: opts?.region ?? undefined,});if (error) throw new Error(error.message);diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex d8a2a17a9..1187486fc 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -2706,7 +2706,12 @@ export type Database = {Returns: Json}prompt_visibility_summaries: {- Args: { p_brand_id: string; p_date_from?: string; p_date_to?: string }+ Args: {+ p_brand_id: string+ p_date_from?: string+ p_date_to?: string+ p_region?: string+ }Returns: {avg_visibility: numberavg_visibility_visible: number