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(web): one date range control across Visibility, Citations and Prompts (#722)
Gökhan Geyik9b9e2fdba948
diff --git a/supabase/migrations/00055_prompt_visibility_summaries_date_to.sql b/supabase/migrations/00055_prompt_visibility_summaries_date_to.sqlnew file mode 100644index 000000000..f0bab056e--- /dev/null+++ b/supabase/migrations/00055_prompt_visibility_summaries_date_to.sql@@ -0,0 +1,75 @@+-- prompt_visibility_summaries gains an upper bound (#713).+--+-- The Prompts page previously offered only whole-window presets (7/30/90+-- days), so a start date was the entire filter. Matching the date range+-- control the other surfaces use means supporting a custom from/to range,+-- which needs an end bound the function never had.+--+-- Dropped and recreated rather than overloaded: an added parameter with a+-- default makes the two-argument call ambiguous, and Postgres rejects it as+-- "function is not unique". Migrations 00034 and 00040 replaced this same+-- function the same way.+--+-- Both bounds stay optional and NULL keeps meaning "unbounded on that side",+-- so every existing caller behaves exactly as before.+--+-- Both signatures are dropped conditionally rather than the two-argument one+-- unconditionally: the hosted database already carries a three-argument+-- version that no migration in this repo produced, so a plain DROP of the+-- two-argument form fails there while succeeding on a fresh install. This+-- also makes the file the single definition of the function again — the+-- drift is what it exists to close.++DROP FUNCTION IF EXISTS public.prompt_visibility_summaries(uuid, timestamptz);+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+)+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)+ GROUP BY pr.prompt_id+$$;++GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz, timestamptz)+ TO authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 01a0ce83b..6aaed7c73 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -5451,3 +5451,82 @@ ALTER TABLE public.prompt_suggestions DROP CONSTRAINT prompt_suggestions_source_ALTER TABLE public.prompt_suggestions ADD CONSTRAINT prompt_suggestions_source_checkCHECK (source = ANY (ARRAY['llm'::text, 'heuristic'::text, 'gsc'::text, 'ga'::text]));+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00055_prompt_visibility_summaries_date_to.sql+-- ─────────────────────────────────────────────────────────────────────────+-- prompt_visibility_summaries gains an upper bound (#713).+--+-- The Prompts page previously offered only whole-window presets (7/30/90+-- days), so a start date was the entire filter. Matching the date range+-- control the other surfaces use means supporting a custom from/to range,+-- which needs an end bound the function never had.+--+-- Dropped and recreated rather than overloaded: an added parameter with a+-- default makes the two-argument call ambiguous, and Postgres rejects it as+-- "function is not unique". Migrations 00034 and 00040 replaced this same+-- function the same way.+--+-- Both bounds stay optional and NULL keeps meaning "unbounded on that side",+-- so every existing caller behaves exactly as before.+--+-- Both signatures are dropped conditionally rather than the two-argument one+-- unconditionally: the hosted database already carries a three-argument+-- version that no migration in this repo produced, so a plain DROP of the+-- two-argument form fails there while succeeding on a fresh install. This+-- also makes the file the single definition of the function again — the+-- drift is what it exists to close.++DROP FUNCTION IF EXISTS public.prompt_visibility_summaries(uuid, timestamptz);+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+)+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)+ GROUP BY pr.prompt_id+$$;++GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz, timestamptz)+ TO authenticated;+diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 06d276108..93c9d06a2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -65,6 +65,11 @@ import { getTopics } from '@/lib/actions/topic';import { MODEL_PROVIDER_LABELS, PLATFORM_LABELS } from '@/config/platform-labels';import { formatRegionDisplay } from '@/lib/region';import type { Topic } from '@/types';+import {+ ALL_DATE_PRESETS,+ DateRangeFilter,+ type DateRangePreset,+} from '@/components/filters/date-range-filter';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -102,7 +107,6 @@ import {SelectTrigger,SelectValue,} from '@/components/ui/select';-import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';import { usePlanContext } from '@/components/providers/plan-provider';@@ -111,7 +115,9 @@ import { toast } from 'sonner';// ─── Filter Types ─────────────────────────────────────────────────────────────-type DatePreset = '24h' | '7d' | '30d' | '90d' | 'all' | 'custom';+// The preset vocabulary is shared with the control that renders it (#713), so+// a page cannot drift from the options it actually offers.+type DatePreset = DateRangePreset;interface InsightsFilters {datePreset: DatePreset;@@ -467,51 +473,15 @@ function FilterBar({return (<div className="flex flex-wrap items-end gap-3">- {/* Date presets */}- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Date Range</label>- <div className="flex rounded-md border overflow-hidden">- {(['24h', '7d', '30d', '90d', 'all', 'custom'] as DatePreset[]).map((p) => (- <button- key={p}- type="button"- onClick={() => set({ datePreset: p })}- className={cn(- 'px-3 py-1.5 text-xs font-medium transition-colors',- filters.datePreset === p- ? 'bg-primary text-primary-foreground'- : 'bg-card hover:bg-muted text-foreground',- )}- >- {p === 'custom' ? 'Custom' : p === 'all' ? 'All' : p}- </button>- ))}- </div>- </div>-- {/* Custom date inputs */}- {filters.datePreset === 'custom' && (- <>- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">From</label>- <Input- type="date"- value={filters.dateFrom}- onChange={(e) => set({ dateFrom: e.target.value })}- className="h-8 w-36 text-xs"- />- </div>- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">To</label>- <Input- type="date"- value={filters.dateTo}- onChange={(e) => set({ dateTo: e.target.value })}- className="h-8 w-36 text-xs"- />- </div>- </>- )}+ <DateRangeFilter+ value={filters.datePreset}+ presets={ALL_DATE_PRESETS as readonly DatePreset[]}+ onChange={(datePreset) => set({ datePreset })}+ from={filters.dateFrom}+ to={filters.dateTo}+ onFromChange={(dateFrom) => set({ dateFrom })}+ onToChange={(dateTo) => set({ dateTo })}+ />{/* Topic filter */}{availableTopics.length > 0 && (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsxindex 112303ef2..007133242 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx@@ -11,7 +11,7 @@ import {type FanoutSubQuery,} from '@/lib/actions/fanout';import { INTENT_LABELS, INTENT_COLORS } from '@/config/intent-labels';-import type { PromptRangeDays } from '@/config/prompt-options';+import type { PromptRange } from '@/config/prompt-options';import { PlatformsCell } from '@/components/citations/source-cells';import { cn } from '@/lib/utils';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';@@ -44,7 +44,8 @@ interface PromptGroup {type QueryFanoutTabProps = {brandId: string;/** Window shared with the rest of the Prompts page (#686). */- days: PromptRangeDays;+ range: PromptRange | null;+ rangeLabel: string;onTracked?: () => void | Promise<void>;};@@ -76,7 +77,7 @@ function userErrorMessage(err: unknown, fallback: string): string {return fallback;}-export function QueryFanoutTab({ brandId, days, onTracked }: QueryFanoutTabProps) {+export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryFanoutTabProps) {const [data, setData] = useState<QueryFanoutData | null>(null);const [loading, setLoading] = useState(true);const [addingKey, setAddingKey] = useState<string | null>(null);@@ -143,7 +144,11 @@ export function QueryFanoutTab({ brandId, days, onTracked }: QueryFanoutTabPropssetLoading(true);}try {- const result = await getQueryFanout(brandId, { days });+ const result = await getQueryFanout(brandId, {+ days: range?.days,+ from: range?.from,+ to: range?.to,+ });setData(result);void classifyProgressively(result.subQueries.map((s) => s.query));} catch (err) {@@ -156,7 +161,7 @@ export function QueryFanoutTab({ brandId, days, onTracked }: QueryFanoutTabProps}}},- [brandId, days, classifyProgressively],+ [brandId, range, classifyProgressively],);useEffect(() => {@@ -169,7 +174,7 @@ export function QueryFanoutTab({ brandId, days, onTracked }: QueryFanoutTabPropsuseEffect(() => {setSearchText('');- }, [brandId, days]);+ }, [brandId, range]);useEffect(() => {setSearchText('');@@ -300,7 +305,7 @@ export function QueryFanoutTab({ brandId, days, onTracked }: QueryFanoutTabProps<p className="text-xs text-muted-foreground">{view === 'by-prompt'? 'Your tracked prompts grouped by the sub-queries their answers actually triggered — expand a prompt to see its observed fan-out. "Answers with fan-out" is how many of that prompt’s tracked answers ran a live search at all.'- : `The sub-queries answer engines actually ran while building your answers (last ${days} days) — observed, never predicted. Sorted by how often they were searched. Track any of them with the + to measure its own visibility.`}+ : `The sub-queries answer engines actually ran while building your answers (${rangeLabel}) — observed, never predicted. Sorted by how often they were searched. Track any of them with the + to measure its own visibility.`}</p></CardHeader><CardContent>@@ -328,7 +333,7 @@ export function QueryFanoutTab({ brandId, days, onTracked }: QueryFanoutTabPropsintents={intents}addingKey={addingKey}pager={byPromptPager}- days={days}+ rangeLabel={rangeLabel}onTrack={handleTrack}searchText={searchText}onSearchChange={setSearchText}@@ -481,7 +486,7 @@ function ByPromptView({intents,addingKey,pager,- days,+ rangeLabel,onTrack,searchText,onSearchChange,@@ -490,7 +495,7 @@ function ByPromptView({intents: Record<string, string>;addingKey: string | null;pager: ReturnType<typeof usePagination>;- days: PromptRangeDays;+ rangeLabel: string;onTrack: (query: string) => void;searchText: string;onSearchChange: (text: string) => void;@@ -518,7 +523,7 @@ function ByPromptView({searchText ? (<NoMatches label="No prompts match your search" />) : (- <NoMatches label={`No tracked answers in the last ${days} days`} />+ <NoMatches label={`No tracked answers in the ${rangeLabel}`} />)) : (<>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 5d34e0339..09c9fe4aa 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -81,11 +81,14 @@ import {ALL_MODELS,SCRAPER_GROUPS,ALL_SCRAPERS,- PROMPT_RANGE_DAYS,- DEFAULT_PROMPT_RANGE_DAYS,- isPromptRangeDays,- type PromptRangeDays,+ PROMPT_RANGE_PRESETS,+ DEFAULT_PROMPT_RANGE_PRESET,+ isPromptRangePreset,+ promptRangeLabel,+ resolvePromptRange,+ type PromptRangePreset,} from '@/config/prompt-options';+import { DateRangeFilter } from '@/components/filters/date-range-filter';import { PLANS } from '@/config/plans';import { getTopics } from '@/lib/actions/topic';import { type PromptVisibilitySummary } from '@/lib/actions/tracking';@@ -222,11 +225,12 @@ function SortableHead({/*** CSV headers. The window-scoped columns carry the selected range in their- * name (`runs_7d`, `runs_90d`, …) rather than a hardcoded `_30d`, so an export- * taken at a different range can't be misread as 30-day data. At the default- * range the header row is byte-identical to what it has always been.+ * name (`runs_7d`, `runs_90d`, `runs_24h`, `runs_custom`) rather than a+ * hardcoded `_30d`, so an export taken at a different range can't be misread+ * as 30-day data. At the default range the header row is byte-identical to+ * what it has always been.*/-const promptExportHeaders = (days: number) => [+const promptExportHeaders = (suffix: string) => ['text','topic_id','category',@@ -238,13 +242,13 @@ const promptExportHeaders = (days: number) => ['est_ai_volume','total_google_volume','intent',- `ai_visibility_score_${days}d`,- `visibility_rate_${days}d`,- `visible_runs_${days}d`,- `avg_visibility_${days}d`,- `total_mentions_${days}d`,- `total_citations_${days}d`,- `runs_${days}d`,+ `ai_visibility_score_${suffix}`,+ `visibility_rate_${suffix}`,+ `visible_runs_${suffix}`,+ `avg_visibility_${suffix}`,+ `total_mentions_${suffix}`,+ `total_citations_${suffix}`,+ `runs_${suffix}`,'last_run_at',];@@ -920,11 +924,29 @@ export default function PromptsPage() {})();const [tab, setTab] = useState<TabId>(initialTab);- const initialRange: PromptRangeDays = (() => {+ const initialRange: PromptRangePreset = (() => {const raw = searchParams.get('range');- return isPromptRangeDays(raw) ? (Number(raw) as PromptRangeDays) : DEFAULT_PROMPT_RANGE_DAYS;+ // Older links carry a bare day count (`range=7`); keep them working rather+ // than silently dropping them back to the default.+ if (isPromptRangePreset(raw)) return raw;+ if (raw && isPromptRangePreset(`${raw}d`)) return `${raw}d` as PromptRangePreset;+ return DEFAULT_PROMPT_RANGE_PRESET;})();- const [rangeDays, setRangeDays] = useState<PromptRangeDays>(initialRange);+ const [rangePreset, setRangePreset] = useState<PromptRangePreset>(initialRange);+ const [customFrom, setCustomFrom] = useState(() => searchParams.get('from') ?? '');+ const [customTo, setCustomTo] = useState(() => searchParams.get('to') ?? '');++ // A custom range only becomes a real window once a bound is entered; until+ // then the resolver's clamp would silently mean "the last 90 days", which is+ // not what an empty form is asking for.+ const range = useMemo(+ () =>+ rangePreset === 'custom' && !customFrom && !customTo+ ? null+ : resolvePromptRange(rangePreset, { from: customFrom, to: customTo }),+ [rangePreset, customFrom, customTo],+ );+ const rangeLabel = promptRangeLabel(rangePreset);// Keep the URL in sync with the active tab so deep links / refreshes land// back on the same view. Shallow history update on purpose: the tab is pure@@ -938,16 +960,29 @@ export default function PromptsPage() {const currentRange = searchParams.get('range');// The default range stays out of the URL so shared links keep their// existing shape unless the user actually picked a different window.- const wantRange = rangeDays === DEFAULT_PROMPT_RANGE_DAYS ? null : String(rangeDays);- if (currentTab === tab && currentRange === wantRange) return;+ const wantRange = rangePreset === DEFAULT_PROMPT_RANGE_PRESET ? null : rangePreset;+ const wantFrom = rangePreset === 'custom' && customFrom ? customFrom : null;+ const wantTo = rangePreset === 'custom' && customTo ? customTo : null;+ if (+ currentTab === tab &&+ currentRange === wantRange &&+ searchParams.get('from') === wantFrom &&+ searchParams.get('to') === wantTo+ ) {+ return;+ }const params = new URLSearchParams(Array.from(searchParams.entries()));params.set('tab', tab);if (wantRange) params.set('range', wantRange);else params.delete('range');+ if (wantFrom) params.set('from', wantFrom);+ else params.delete('from');+ if (wantTo) params.set('to', wantTo);+ else params.delete('to');// Keep the hash: deep links like #prompt-opportunities arrive without a// tab param, and this sync must not strip their anchor from the URL.window.history.replaceState(null, '', `?${params.toString()}${window.location.hash}`);- }, [tab, rangeDays, searchParams]);+ }, [tab, rangePreset, customFrom, customTo, searchParams]);// Deep link from the Insights Recommendations row (#459): the target card// only exists once the Insights tab's volume data has rendered, so a bare@@ -975,7 +1010,11 @@ export default function PromptsPage() {// One consolidated server action: Next.js queues client-fired server// actions sequentially, so the old three separate calls cost their// SUM on a cold load — the main culprit behind the slow first paint.- const page = await getPromptsPageData(activeBrandId, { days: rangeDays });+ const page = await getPromptsPageData(activeBrandId, {+ days: range?.days,+ from: range?.from,+ to: range?.to,+ });if (isCancelled?.()) return;setVolumes(page.volumes);if (page.quota) setQuota(page.quota);@@ -993,7 +1032,7 @@ export default function PromptsPage() {if (!isCancelled?.()) setLoading(false);}},- [activeBrandId, rangeDays],+ [activeBrandId, range],);useEffect(() => {@@ -1145,6 +1184,7 @@ export default function PromptsPage() {const handleExportCsv = useCallback(() => {if (!canExport) return;+ const rangeSuffix = rangePreset;const rows = allPrompts.map((p) => ({text: p.text,topic_id: p.topicId ?? '',@@ -1157,17 +1197,17 @@ export default function PromptsPage() {est_ai_volume: volumeByPromptId.get(p.id)?.estAiVolume ?? '',total_google_volume: volumeByPromptId.get(p.id)?.totalGoogleVolume ?? '',intent: volumeByPromptId.get(p.id)?.intent ?? '',- [`ai_visibility_score_${rangeDays}d`]: visibility[p.id]?.score ?? '',- [`visibility_rate_${rangeDays}d`]: visibility[p.id]?.visibilityRate ?? '',- [`visible_runs_${rangeDays}d`]: visibility[p.id]?.visibleRuns ?? '',- [`avg_visibility_${rangeDays}d`]: visibility[p.id]?.avgVisibility ?? '',- [`total_mentions_${rangeDays}d`]: visibility[p.id]?.totalMentions ?? '',- [`total_citations_${rangeDays}d`]: visibility[p.id]?.totalCitations ?? '',- [`runs_${rangeDays}d`]: visibility[p.id]?.runs ?? '',+ [`ai_visibility_score_${rangeSuffix}`]: visibility[p.id]?.score ?? '',+ [`visibility_rate_${rangeSuffix}`]: visibility[p.id]?.visibilityRate ?? '',+ [`visible_runs_${rangeSuffix}`]: visibility[p.id]?.visibleRuns ?? '',+ [`avg_visibility_${rangeSuffix}`]: visibility[p.id]?.avgVisibility ?? '',+ [`total_mentions_${rangeSuffix}`]: visibility[p.id]?.totalMentions ?? '',+ [`total_citations_${rangeSuffix}`]: visibility[p.id]?.totalCitations ?? '',+ [`runs_${rangeSuffix}`]: visibility[p.id]?.runs ?? '',last_run_at: visibility[p.id]?.lastRunAt ?? '',}));- const csv = toCsv(rows, promptExportHeaders(rangeDays));+ const csv = toCsv(rows, promptExportHeaders(rangeSuffix));const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });const url = URL.createObjectURL(blob);const link = document.createElement('a');@@ -1179,7 +1219,7 @@ export default function PromptsPage() {link.click();URL.revokeObjectURL(url);- }, [activeBrand?.slug, canExport, allPrompts, visibility, volumeByPromptId, rangeDays]);+ }, [activeBrand?.slug, canExport, allPrompts, visibility, volumeByPromptId, rangePreset]);if (!activeBrandId) {return (@@ -1213,29 +1253,6 @@ export default function PromptsPage() {<TabsTrigger value="insights">Insights</TabsTrigger></TabsList><div className="flex items-center gap-2">- {/* Hidden on Insights: that tab shows keyword volume estimates,- which carry no date dimension, so a range there would be a- control that changes nothing. */}- {tab !== 'insights' && (- <div className="flex items-center rounded-md border p-0.5" role="group">- {PROMPT_RANGE_DAYS.map((days) => (- <button- key={days}- type="button"- onClick={() => setRangeDays(days)}- aria-pressed={rangeDays === days}- className={cn(- 'rounded-sm px-2.5 py-1 text-xs font-medium transition-colors',- rangeDays === days- ? 'bg-primary text-primary-foreground'- : 'text-muted-foreground hover:text-foreground',- )}- >- {days}d- </button>- ))}- </div>- )}{tab === 'all' && canManage && (<Buttontype="button"@@ -1273,6 +1290,25 @@ export default function PromptsPage() {</div></div>+ {/* Filter bar — same shape and position as Visibility and Citations+ (#713). Hidden on Insights: that tab shows keyword volume+ estimates, which carry no date dimension, so a range there would be+ a control that changes nothing. It sits outside the tab panels+ because the range governs both All Prompts and Query Fan-out. */}+ {tab !== 'insights' && (+ <div className="mt-4 flex flex-wrap items-end gap-3">+ <DateRangeFilter+ value={rangePreset}+ presets={PROMPT_RANGE_PRESETS}+ onChange={setRangePreset}+ from={customFrom}+ to={customTo}+ onFromChange={setCustomFrom}+ onToChange={setCustomTo}+ />+ </div>+ )}+{/* ─── All Prompts tab ─────────────────────────────────────────── */}<TabsContent value="all" className="mt-4 space-y-4">{activeBrandId && <SuggestionsCard brandId={activeBrandId} onAccepted={loadData} />}@@ -1319,7 +1355,7 @@ export default function PromptsPage() {activeBrandId={activeBrandId}volumeByPromptId={volumeByPromptId}visibility={visibility}- days={rangeDays}+ rangeLabel={rangeLabel}onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}onEditPrompt={canManage ? setEditingPrompt : undefined}/>@@ -1328,7 +1364,12 @@ export default function PromptsPage() {{/* ─── Query Fan-out tab ───────────────────────────────────────── */}<TabsContent value="fanout" className="mt-4">{activeBrandId && (- <QueryFanoutTab brandId={activeBrandId} days={rangeDays} onTracked={loadData} />+ <QueryFanoutTab+ brandId={activeBrandId}+ range={range}+ rangeLabel={rangeLabel}+ onTracked={loadData}+ />)}</TabsContent>@@ -1715,7 +1756,7 @@ function AllPromptsTab({activeBrandId,volumeByPromptId,visibility,- days,+ rangeLabel,onAddPrompt,onEditPrompt,}: {@@ -1725,7 +1766,7 @@ function AllPromptsTab({volumeByPromptId: Map<string, PromptVolume>;visibility: Record<string, PromptVisibilitySummary>;/** Selected window, so the column tooltips describe the data on screen. */- days: PromptRangeDays;+ rangeLabel: string;/** Opens the Add Prompt dialog; undefined when the user can't write (member role). */onAddPrompt?: () => void;/** Opens the Edit Prompt dialog for a row; undefined hides the pencil (member role). */@@ -1919,7 +1960,7 @@ function AllPromptsTab({</ColHead><SortableHeadclassName="text-right"- tooltip={`AI Visibility Score (0-100) for this prompt over the last ${days} days: how often answers mention the brand (60%), cite its site (25%) and how early it's named (15%). Hover a value for the components.`}+ tooltip={`AI Visibility Score (0-100) for this prompt over the ${rangeLabel}: how often answers mention the brand (60%), cite its site (25%) and how early it's named (15%). Hover a value for the components.`}sortKey="visibility"activeSort={activeSort}dir={dir}@@ -1929,7 +1970,7 @@ function AllPromptsTab({</SortableHead><SortableHeadclassName="text-right"- tooltip={`Total times the brand was mentioned across AI answers for this prompt over the last ${days} days.`}+ tooltip={`Total times the brand was mentioned across AI answers for this prompt over the ${rangeLabel}.`}sortKey="mentions"activeSort={activeSort}dir={dir}@@ -1939,7 +1980,7 @@ function AllPromptsTab({</SortableHead><SortableHeadclassName="text-right"- tooltip={`Total times your pages were cited in AI answers for this prompt over the last ${days} days.`}+ tooltip={`Total times your pages were cited in AI answers for this prompt over the ${rangeLabel}.`}sortKey="citations"activeSort={activeSort}dir={dir}@@ -1965,7 +2006,7 @@ function AllPromptsTab({</ColHead><SortableHeadclassName="text-right"- tooltip={`Number of tracking runs for this prompt over the last ${days} days (one per platform per day).`}+ tooltip={`Number of tracking runs for this prompt over the ${rangeLabel} (one per platform per day).`}sortKey="runs"activeSort={activeSort}dir={dir}@@ -2043,7 +2084,7 @@ function AllPromptsTab({{vis ? (<divclassName="inline-flex items-center gap-2 justify-end min-w-[110px]"- title={`Mentioned in ${vis.mentionAnswers} of ${vis.runs} answers (${days}d) · cited in ${vis.citationAnswers}${+ title={`Mentioned in ${vis.mentionAnswers} of ${vis.runs} answers (${rangeLabel}) · cited in ${vis.citationAnswers}${vis.positionFactor !== null? ` · position factor ${vis.positionFactor.toFixed(2)}`: ''diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex 451871e49..2b620fff3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -28,6 +28,11 @@ import {type TrafficLog,type TrafficDateWindow,} from '@/lib/actions/traffic';+import {+ ALL_DATE_PRESETS,+ DateRangeFilter,+ type DateRangePreset,+} from '@/components/filters/date-range-filter';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import {@@ -373,9 +378,10 @@ function NoTrafficForPeriod({ rangeLabel, onReset }: { rangeLabel: string; onRes// ─── Date range ─────────────-type DatePreset = '24h' | '7d' | '30d' | '90d' | 'all' | 'custom';+// The preset vocabulary is shared with the control that renders it (#713).+type DatePreset = DateRangePreset;-const DATE_PRESETS: DatePreset[] = ['24h', '7d', '30d', '90d', 'all', 'custom'];+const DATE_PRESETS = ALL_DATE_PRESETS;function getDateRange(preset: DatePreset, custom: { from: string; to: string }): TrafficDateWindow {if (preset === 'all') return {};@@ -434,69 +440,6 @@ function getTrendTitle(preset: DatePreset, custom: { from: string; to: string })}}-function DateRangePicker({- preset,- customFrom,- customTo,- onPreset,- onCustomFrom,- onCustomTo,-}: {- preset: DatePreset;- customFrom: string;- customTo: string;- onPreset: (p: DatePreset) => void;- onCustomFrom: (v: string) => void;- onCustomTo: (v: string) => void;-}) {- return (- <div className="flex flex-wrap items-end gap-3">- <div>- <label className="block mb-1.5 font-medium text-muted-foreground text-xs">Date Range</label>- <div className="flex border rounded-md overflow-hidden">- {DATE_PRESETS.map((p) => (- <button- key={p}- type="button"- className={cn(- 'px-3 py-1.5 font-medium text-xs transition-colors',- preset === p- ? 'bg-primary text-primary-foreground'- : 'bg-card hover:bg-muted text-foreground',- )}- onClick={() => onPreset(p)}- >- {p === 'custom' ? 'Custom' : p === 'all' ? 'All' : p}- </button>- ))}- </div>- </div>- {preset === 'custom' && (- <>- <div>- <label className="block mb-1.5 font-medium text-muted-foreground text-xs">From</label>- <Input- type="date"- value={customFrom}- onChange={(e) => onCustomFrom(e.target.value)}- className="w-36 h-8 text-xs"- />- </div>- <div>- <label className="block mb-1.5 font-medium text-muted-foreground text-xs">To</label>- <Input- type="date"- value={customTo}- onChange={(e) => onCustomTo(e.target.value)}- className="w-36 h-8 text-xs"- />- </div>- </>- )}- </div>- );-}-// ─── Main Page ────────────────────────────────────────────────────────────────export default function TrafficPage() {@@ -695,7 +638,19 @@ function TrafficPageContent({ brand }: { brand: Brand }) {{primaryDomain ? `${primaryDomain} · ` : ''}AI-referred visits to your website</p></div>- <div className="flex items-center gap-2">+ {/* items-end, not items-center: the range control is two rows tall+ (its label sits above the buttons), so centring left the Export+ button floating above the segmented control's baseline. */}+ <div className="flex flex-wrap items-end gap-3">+ <DateRangeFilter+ value={datePreset}+ presets={DATE_PRESETS}+ onChange={handleDatePresetChange}+ from={customFrom}+ to={customTo}+ onFromChange={handleCustomFromChange}+ onToChange={handleCustomToChange}+ /><Buttonvariant="outline"className="gap-2"@@ -709,14 +664,6 @@ function TrafficPageContent({ brand }: { brand: Brand }) {)}{isExporting ? 'Exporting...' : 'Export CSV'}</Button>- <DateRangePicker- preset={datePreset}- customFrom={customFrom}- customTo={customTo}- onPreset={handleDatePresetChange}- onCustomFrom={handleCustomFromChange}- onCustomTo={handleCustomToChange}- /></div></div>diff --git a/web/src/components/citations/filter-bar.tsx b/web/src/components/citations/filter-bar.tsxindex ef81a459a..0a775dc34 100644--- a/web/src/components/citations/filter-bar.tsx+++ b/web/src/components/citations/filter-bar.tsx@@ -8,13 +8,12 @@*/import { useMemo } from 'react';-import { cn } from '@/lib/utils';import type { Topic } from '@/types';import type { CitationsDatePreset } from '@/lib/actions/citations';import { MODEL_PROVIDER_LABELS, PLATFORM_LABELS } from '@/config/platform-labels';import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';+import { DateRangeFilter } from '@/components/filters/date-range-filter';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';import {Select,SelectContent,@@ -204,49 +203,15 @@ export function CitationsFilterBar({return (<div className="flex flex-wrap items-end gap-3">- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Date Range</label>- <div className="flex rounded-md border overflow-hidden">- {DATE_PRESETS.map((p) => (- <button- key={p}- type="button"- onClick={() => onChange({ datePreset: p })}- className={cn(- 'px-3 py-1.5 text-xs font-medium transition-colors',- filters.datePreset === p- ? 'bg-primary text-primary-foreground'- : 'bg-card hover:bg-muted text-foreground',- )}- >- {p === 'custom' ? 'Custom' : p === 'all' ? 'All' : p}- </button>- ))}- </div>- </div>-- {filters.datePreset === 'custom' && (- <>- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">From</label>- <Input- type="date"- value={filters.dateFrom}- onChange={(e) => onChange({ dateFrom: e.target.value })}- className="h-8 w-36 text-xs"- />- </div>- <div>- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">To</label>- <Input- type="date"- value={filters.dateTo}- onChange={(e) => onChange({ dateTo: e.target.value })}- className="h-8 w-36 text-xs"- />- </div>- </>- )}+ <DateRangeFilter+ value={filters.datePreset}+ presets={DATE_PRESETS}+ onChange={(datePreset) => onChange({ datePreset })}+ from={filters.dateFrom}+ to={filters.dateTo}+ onFromChange={(dateFrom) => onChange({ dateFrom })}+ onToChange={(dateTo) => onChange({ dateTo })}+ />{topics.length > 0 && (<div>diff --git a/web/src/components/filters/date-range-filter.tsx b/web/src/components/filters/date-range-filter.tsxnew file mode 100644index 000000000..90a2b48c4--- /dev/null+++ b/web/src/components/filters/date-range-filter.tsx@@ -0,0 +1,117 @@+'use client';++import { Input } from '@/components/ui/input';+import { cn } from '@/lib/utils';++/**+ * The one date range control (#713).+ *+ * Visibility and Citations carried byte-identical copies of this markup and+ * Prompts a third, divergent one — same concept, three shapes, three places.+ * Extracting it is what stops the next page from adding a fourth.+ *+ * Which presets a page offers stays the page's decision. Prompts deliberately+ * omits 24h and All: its table scores each prompt over the window, and a+ * single day yields one or two runs per prompt, so the column would read zero+ * for most rows (#686). Parity here means the same shape, label and position —+ * not pretending every page answers the same question.+ */++export type DateRangePreset = '24h' | '7d' | '30d' | '90d' | 'all' | 'custom';++export const ALL_DATE_PRESETS: readonly DateRangePreset[] = [+ '24h',+ '7d',+ '30d',+ '90d',+ 'all',+ 'custom',+];++export function dateRangePresetLabel(preset: DateRangePreset): string {+ if (preset === 'custom') return 'Custom';+ if (preset === 'all') return 'All';+ return preset;+}++interface DateRangeFilterProps<P extends string = DateRangePreset> {+ value: P;+ onChange: (preset: P) => void;+ /** Presets this page offers, in display order. */+ presets: readonly P[];+ label?: string;+ /** Custom-range inputs render only when both the value and handlers are present. */+ from?: string;+ to?: string;+ onFromChange?: (value: string) => void;+ onToChange?: (value: string) => void;+ className?: string;+}++/**+ * Renders as sibling blocks rather than one wrapper, so it drops into the+ * `flex flex-wrap items-end gap-3` filter bars the pages already use and the+ * custom-range inputs sit alongside the other filters instead of under them.+ */+export function DateRangeFilter<P extends string = DateRangePreset>({+ value,+ onChange,+ presets,+ label = 'Date Range',+ from,+ to,+ onFromChange,+ onToChange,+ className,+}: DateRangeFilterProps<P>) {+ const showCustom = value === 'custom' && onFromChange && onToChange;++ return (+ <>+ <div className={className}>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">{label}</label>+ <div className="flex rounded-md border overflow-hidden" role="group" aria-label={label}>+ {presets.map((preset) => (+ <button+ key={preset}+ type="button"+ onClick={() => onChange(preset)}+ aria-pressed={value === preset}+ className={cn(+ 'px-3 py-1.5 text-xs font-medium transition-colors',+ value === preset+ ? 'bg-primary text-primary-foreground'+ : 'bg-card hover:bg-muted text-foreground',+ )}+ >+ {dateRangePresetLabel(preset as DateRangePreset)}+ </button>+ ))}+ </div>+ </div>++ {showCustom && (+ <>+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">From</label>+ <Input+ type="date"+ value={from ?? ''}+ onChange={(e) => onFromChange(e.target.value)}+ className="h-8 w-36 text-xs"+ />+ </div>+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">To</label>+ <Input+ type="date"+ value={to ?? ''}+ onChange={(e) => onToChange(e.target.value)}+ className="h-8 w-36 text-xs"+ />+ </div>+ </>+ )}+ </>+ );+}diff --git a/web/src/config/prompt-options.ts b/web/src/config/prompt-options.tsindex a4a787080..79af33735 100644--- a/web/src/config/prompt-options.ts+++ b/web/src/config/prompt-options.ts@@ -133,19 +133,79 @@ export const ALL_SCRAPERS = SCRAPER_GROUPS.flatMap((g) =>);/**- * Date-range presets for the Prompts page (#686).+ * Fallback window for `getPromptsPageData` when a caller passes no range at+ * all. The page always passes one; this only covers direct calls.+ */+export const DEFAULT_PROMPT_RANGE_DAYS = 30;++/**+ * The windows the Prompts page offers, in the shared date-range control's+ * vocabulary (#713).*- * No 24h option: a single day gives one or two runs per prompt, so the scores- * would be noise and most of the table would read zero. No "all time" either —- * the visibility summaries scan every result row in the window, so an- * unbounded range has unbounded cost, and 90 days matches the fan-out cap.+ * Matches Visibility and Citations except for `all`, which is deliberately+ * absent: the Query Fan-out tab aggregates raw rows in the client and is hard+ * capped at 90 days and 50,000 rows, so an unbounded option would silently+ * mean "90 days" there — the same silent truncation filed as #721. A custom+ * range is clamped to the same 90 days for the same reason, so both tabs+ * always describe the window they actually read.+ */+export const PROMPT_RANGE_PRESETS = ['24h', '7d', '30d', '90d', 'custom'] as const;++export type PromptRangePreset = (typeof PROMPT_RANGE_PRESETS)[number];++/** Matches Visibility and Citations, which both open on 24h. */+export const DEFAULT_PROMPT_RANGE_PRESET: PromptRangePreset = '24h';++/** The furthest back either tab can honestly report. */+export const PROMPT_RANGE_MAX_DAYS = 90;++export function isPromptRangePreset(value: unknown): value is PromptRangePreset {+ return PROMPT_RANGE_PRESETS.includes(value as PromptRangePreset);+}++export interface PromptRange {+ /** ISO lower bound. */+ from: string;+ /** ISO upper bound, or undefined for "up to now". */+ to?: string;+ /** Whole days the window spans — the fan-out path still thinks in days. */+ days: number;+}++/**+ * Resolve a preset (plus the custom inputs) into the bounds both data paths+ * take. A custom range is clamped to PROMPT_RANGE_MAX_DAYS and never extends+ * into the future, so the two tabs cannot disagree about what they read.*/-export const PROMPT_RANGE_DAYS = [7, 30, 90] as const;+export function resolvePromptRange(+ preset: PromptRangePreset,+ custom?: { from?: string; to?: string },+): PromptRange {+ const now = Date.now();+ const dayMs = 86_400_000;-export type PromptRangeDays = (typeof PROMPT_RANGE_DAYS)[number];+ if (preset === 'custom') {+ const parsedTo = custom?.to ? Date.parse(`${custom.to}T23:59:59.999Z`) : NaN;+ const parsedFrom = custom?.from ? Date.parse(custom.from) : NaN;+ const to = Number.isFinite(parsedTo) ? Math.min(parsedTo, now) : now;+ const earliest = to - PROMPT_RANGE_MAX_DAYS * dayMs;+ const from = Number.isFinite(parsedFrom)+ ? Math.min(Math.max(parsedFrom, earliest), to)+ : earliest;+ return {+ from: new Date(from).toISOString(),+ to: new Date(to).toISOString(),+ days: Math.max(1, Math.ceil((to - from) / dayMs)),+ };+ }-export const DEFAULT_PROMPT_RANGE_DAYS: PromptRangeDays = 30;+ const days = preset === '24h' ? 1 : Number(preset.slice(0, -1));+ return { from: new Date(now - days * dayMs).toISOString(), days };+}-export function isPromptRangeDays(value: unknown): value is PromptRangeDays {- return PROMPT_RANGE_DAYS.includes(Number(value) as PromptRangeDays);+/** Human label for the resolved window, used in table tooltips and exports. */+export function promptRangeLabel(preset: PromptRangePreset): string {+ if (preset === '24h') return 'last 24 hours';+ if (preset === 'custom') return 'the selected range';+ return `last ${preset.slice(0, -1)} days`;}diff --git a/web/src/lib/actions/fanout.ts b/web/src/lib/actions/fanout.tsindex fc45397ce..d7b1762d5 100644--- a/web/src/lib/actions/fanout.ts+++ b/web/src/lib/actions/fanout.ts@@ -111,6 +111,7 @@ async function fetchFanoutRows(brandId: string,since: string,promptId?: string,+ until?: string,): Promise<{ rows: FanoutResultRow[]; truncated: boolean }> {const rows: FanoutResultRow[] = [];for (let from = 0; from < FANOUT_MAX_ROWS; from += FANOUT_PAGE_SIZE) {@@ -123,6 +124,7 @@ async function fetchFanoutRows(.order('created_at', { ascending: true }).order('id', { ascending: true }).range(from, from + FANOUT_PAGE_SIZE - 1);+ if (until) query = query.lte('created_at', until);if (promptId) query = query.eq('prompt_id', promptId);const { data, error } = await query;@@ -203,19 +205,25 @@ function normalizeQuery(raw: string): string {*/export async function getQueryFanout(brandId: string,- opts?: { days?: number },+ opts?: { days?: number; from?: string; to?: string },): Promise<QueryFanoutData> {const supabase = await createClient();// Clamp the window to a sane range so a crafted call can't force an- // unbounded prompt_results scan + in-memory aggregation.+ // unbounded prompt_results scan + in-memory aggregation. The custom range+ // (#713) is clamped by the caller to the same ceiling, and re-clamped here+ // because this action is reachable on its own.const days = Math.min(Math.max(Math.trunc(opts?.days ?? 30) || 30, 1), MAX_FANOUT_DAYS);- const since = new Date(Date.now() - days * 86_400_000).toISOString();+ const earliest = Date.now() - MAX_FANOUT_DAYS * 86_400_000;+ const requested = opts?.from ? Date.parse(opts.from) : NaN;+ const since = Number.isFinite(requested)+ ? new Date(Math.max(requested, earliest)).toISOString()+ : new Date(Date.now() - days * 86_400_000).toISOString();// No server-side "non-empty" filter: comparing a jsonb column to '[]' through// PostgREST is unreliable, and rows with an empty fan-out contribute nothing// to the sub-query aggregation below (the item loop skips them) — but they do// count toward coverage, which is the whole point of the denominator.- const { rows, truncated } = await fetchFanoutRows(supabase, brandId, since);+ const { rows, truncated } = await fetchFanoutRows(supabase, brandId, since, undefined, opts?.to);interface Acc {display: string;diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex ac659e820..9973f6fa2 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -549,7 +549,7 @@ export interface PromptsPageData {*/export async function getPromptsPageData(brandId: string,- opts?: { days?: number },+ opts?: { days?: number; from?: string; to?: 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@@ -557,7 +557,7 @@ export async function getPromptsPageData(const days = opts?.days ?? DEFAULT_PROMPT_RANGE_DAYS;const [promptSets, visibility, volumesResult] = await Promise.all([getPromptSets(brandId),- getPromptVisibilitySummaries(brandId, { days }),+ getPromptVisibilitySummaries(brandId, { days, from: opts?.from, to: opts?.to }),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 dd4ccea1a..f4abe5c9c 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -1440,11 +1440,13 @@ export interface PromptVisibilitySummary {*/export async function getPromptVisibilitySummaries(brandId: string,- opts?: { days?: number },+ opts?: { days?: number; from?: string; to?: string },): Promise<Record<string, PromptVisibilitySummary>> {const supabase = await createClient();+ // `from`/`to` win when given (the custom range, #713); otherwise the day+ // count keeps every existing caller on its previous behaviour.const days = opts?.days ?? 30;- const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();+ const since = opts?.from ?? new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();// One GROUP BY in Postgres (migration 00025) instead of pulling the raw// result window into JS: the old un-paginated select silently capped at@@ -1454,6 +1456,7 @@ export async function getPromptVisibilitySummaries(const { data, error } = await supabase.rpc('prompt_visibility_summaries', {p_brand_id: brandId,p_date_from: since,+ p_date_to: opts?.to ?? null,});if (error) throw new Error(error.message);