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): add full date range picker to AI Traffic Analytics (#509)
Utkarsh Singhal7cb5f584a59e
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex c747854ce..8d7a8b8c7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -1,6 +1,6 @@'use client';-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useMemo } from 'react';import { getPlatformName } from './_charts';import dynamic from 'next/dynamic';import { Skeleton } from '@/components/ui/skeleton';@@ -18,6 +18,7 @@ const PlatformBreakdownChart = dynamic(},);import { useBrandStore } from '@/stores/use-brand-store';+import type { Brand } from '@/types';import {getTrafficSummary,getTrafficTrend,@@ -25,6 +26,7 @@ import {type TrafficSummary,type TrafficTrendPoint,type TrafficLog,+ type TrafficDateWindow,} from '@/lib/actions/traffic';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';@@ -339,21 +341,159 @@ function EmptyLogsState({ hasFilters }: { hasFilters: boolean }) {}}-// ─── Main Page ────────────────────────────────────────────────────────────────+// ─── Date range ─────────────++type DatePreset = '24h' | '7d' | '30d' | '90d' | 'all' | 'custom';++const DATE_PRESETS: DatePreset[] = ['24h', '7d', '30d', '90d', 'all', 'custom'];++function getDateRange(preset: DatePreset, custom: { from: string; to: string }): TrafficDateWindow {+ if (preset === 'all') return {};+ if (preset === 'custom') {+ return {+ dateFrom: custom.from || undefined,+ dateTo: custom.to ? `${custom.to}T23:59:59.999Z` : undefined,+ };+ }+ if (preset === '24h') {+ const from = new Date();+ from.setHours(from.getHours() - 24);+ return { dateFrom: from.toISOString() };+ }+ const days = preset === '7d' ? 7 : preset === '30d' ? 30 : 90;+ const from = new Date();+ from.setDate(from.getDate() - days);+ return { dateFrom: from.toISOString() };+}++function getRangeSubLabel(preset: DatePreset, custom: { from: string; to: string }): string {+ switch (preset) {+ case '24h':+ return 'last 24 hours';+ case '7d':+ return 'last 7 days';+ case '30d':+ return 'last 30 days';+ case '90d':+ return 'last 90 days';+ case 'all':+ return 'all time';+ case 'custom':+ if (custom.from && custom.to) return `${custom.from} – ${custom.to}`;+ if (custom.from) return `from ${custom.from}`;+ if (custom.to) return `through ${custom.to}`;+ return 'selected period';+ }+}-const TIME_RANGE_OPTIONS = [- { label: '7d', value: 7 },- { label: '30d', value: 30 },- { label: '90d', value: 90 },-] as const;+function getTrendTitle(preset: DatePreset, custom: { from: string; to: string }): string {+ switch (preset) {+ case '24h':+ return 'AI Referral Trend — Last 24 Hours';+ case '7d':+ return 'AI Referral Trend — Last 7 Days';+ case '30d':+ return 'AI Referral Trend — Last 30 Days';+ case '90d':+ return 'AI Referral Trend — Last 90 Days';+ case 'all':+ return 'AI Referral Trend — All Time';+ case 'custom':+ if (custom.from && custom.to) return `AI Referral Trend — ${custom.from} – ${custom.to}`;+ return 'AI Referral Trend';+ }+}++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>+ );+}-type TimeRangeDays = (typeof TIME_RANGE_OPTIONS)[number]['value'];+// ─── Main Page ────────────────────────────────────────────────────────────────export default function TrafficPage() {- const { getActiveBrand } = useBrandStore();- const brand = getActiveBrand();+ const brand = useBrandStore((s) => s.getActiveBrand());+ if (!brand) {+ return (+ <div className="flex flex-col justify-center items-center py-20 text-center">+ <h2 className="font-semibold text-lg">No brand selected</h2>+ <p className="mt-1 text-muted-foreground text-sm">+ Select a brand to view AI traffic analytics.+ </p>+ </div>+ );+ }+ return <TrafficPageContent key={brand.id} brand={brand} />;+}- const [days, setDays] = useState<TimeRangeDays>(7);+function TrafficPageContent({ brand }: { brand: Brand }) {+ const [datePreset, setDatePreset] = useState<DatePreset>('7d');+ const [customFrom, setCustomFrom] = useState('');+ const [customTo, setCustomTo] = useState('');+ const dateWindow = useMemo(+ () => getDateRange(datePreset, { from: customFrom, to: customTo }),+ [datePreset, customFrom, customTo],+ );+ const rangeSubLabel = getRangeSubLabel(datePreset, { from: customFrom, to: customTo });+ const trendTitle = getTrendTitle(datePreset, { from: customFrom, to: customTo });const [summary, setSummary] = useState<TrafficSummary | null>(null);const [trend, setTrend] = useState<TrafficTrendPoint[]>([]);const [logs, setLogs] = useState<TrafficLog[]>([]);@@ -365,13 +505,6 @@ export default function TrafficPage() {const [searchInput, setSearchInput] = useState(filters.search);const [page, setPage] = useState(0);- useEffect(() => {- setDays(7);- setPage(0);- setSearchInput('');- setFilters({ platform: '', search: '' });- }, [brand?.id]);-useEffect(() => {const id = window.setTimeout(() => {setFilters((prevFilters) => {@@ -390,12 +523,11 @@ export default function TrafficPage() {}, [searchInput]);const loadSummary = useCallback(async () => {- if (!brand) return;setIsLoadingSummary(true);try {const [s, t] = await Promise.all([- getTrafficSummary(brand.id, days),- getTrafficTrend(brand.id, days),+ getTrafficSummary(brand.id, dateWindow),+ getTrafficTrend(brand.id, dateWindow),]);setSummary(s);setTrend(t);@@ -404,10 +536,9 @@ export default function TrafficPage() {} finally {setIsLoadingSummary(false);}- }, [brand, days]);+ }, [brand.id, dateWindow]);const loadLogs = useCallback(async () => {- if (!brand) return;setIsLoadingLogs(true);try {const result = await getTrafficLogs(brand.id, {@@ -415,7 +546,8 @@ export default function TrafficPage() {offset: page * PAGE_SIZE,platform: filters.platform || undefined,search: filters.search || undefined,- days,+ dateFrom: dateWindow.dateFrom,+ dateTo: dateWindow.dateTo,});setLogs(result.logs);setLogsTotal(result.total);@@ -424,40 +556,39 @@ export default function TrafficPage() {} finally {setIsLoadingLogs(false);}- }, [brand, page, filters.platform, filters.search, days]);+ }, [brand.id, page, filters.platform, filters.search, dateWindow]);const handleFiltersChange = useCallback((patch: Partial<TrafficFilters>) => {setPage(0);setFilters((f) => ({ ...f, ...patch }));}, []);- const handleDaysChange = useCallback((d: TimeRangeDays) => {- setDays(d);+ const handleDatePresetChange = useCallback((preset: DatePreset) => {setPage(0);+ setDatePreset(preset);}, []);- useEffect(() => {- loadSummary();- }, [loadSummary]);+ const handleCustomFromChange = useCallback((value: string) => {+ setPage(0);+ setCustomFrom(value);+ }, []);- useEffect(() => {- loadLogs();- }, [loadLogs]);+ const handleCustomToChange = useCallback((value: string) => {+ setPage(0);+ setCustomTo(value);+ }, []);- if (!brand) {- return (- <div className="flex flex-col items-center justify-center py-20 text-center">- <h2 className="text-lg font-semibold">No brand selected</h2>- <p className="text-muted-foreground text-sm mt-1">- Select a brand to view AI traffic analytics.- </p>- </div>- );- }+ useEffect(() => {+ const id = window.setTimeout(() => {+ void loadSummary();+ void loadLogs();+ }, 0);+ return () => window.clearTimeout(id);+ }, [loadSummary, loadLogs]);const primaryDomain = brand.domains.find((d) => d.isPrimary)?.domain ?? brand.domains[0]?.domain;- if (isLoadingSummary) {+ if (isLoadingSummary && summary === null) {return (<div className="space-y-6"><div>@@ -495,22 +626,14 @@ export default function TrafficPage() {{primaryDomain ? `${primaryDomain} · ` : ''}AI-referred visits to your website</p></div>- <div className="flex rounded-md border p-0.5 self-center">- {TIME_RANGE_OPTIONS.map((opt) => (- <button- key={opt.value}- className={cn(- 'rounded px-3 py-1 text-xs font-medium transition-colors',- days === opt.value- ? 'bg-background text-foreground shadow-sm'- : 'text-muted-foreground hover:text-foreground',- )}- onClick={() => handleDaysChange(opt.value)}- >- {opt.label}- </button>- ))}- </div>+ <DateRangePicker+ preset={datePreset}+ customFrom={customFrom}+ customTo={customTo}+ onPreset={handleDatePresetChange}+ onCustomFrom={handleCustomFromChange}+ onCustomTo={handleCustomToChange}+ /></div>{/* Snippet Banner */}@@ -548,7 +671,7 @@ export default function TrafficPage() {{visitsDelta}% vs previous period</>) : (- `last ${days} days`+ rangeSubLabel)}subPositive={visitsDelta > 0 ? true : visitsDelta < 0 ? false : undefined}@@ -571,9 +694,7 @@ export default function TrafficPage() {<div className="grid grid-cols-1 gap-4 lg:grid-cols-3"><Card className="lg:col-span-2"><CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">- AI Referral Trend — Last {days} Days- </CardTitle>+ <CardTitle className="font-medium text-sm">{trendTitle}</CardTitle></CardHeader><CardContent><ReferralTrendChart data={trend} />diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.tsindex ab8450703..f98e6458d 100644--- a/web/src/lib/actions/traffic.ts+++ b/web/src/lib/actions/traffic.ts@@ -1,6 +1,12 @@'use server';import { createClient } from '@/lib/supabase/server';+import { expandDateToEndOfDay } from '@/lib/dates';++export interface TrafficDateWindow {+ dateFrom?: string;+ dateTo?: string;+}export interface TrafficLog {id: string;@@ -40,18 +46,52 @@ function mapLogRow(row: Record<string, unknown>): TrafficLog {};}-function getDateRange(days: number): {- from: string;- to: string;- prevFrom: string;- prevTo: string;+/** Window of equal length immediately before [from, to]. */+function previousWindow(from: string, to: string): { from: string; to: string } {+ const fromMs = new Date(from).getTime();+ const toMs = new Date(to).getTime();+ return { from: new Date(fromMs - (toMs - fromMs)).toISOString(), to: from };+}++function resolveTrafficWindow(window?: TrafficDateWindow): {+ from?: string;+ to?: string;+ prevFrom?: string;+ prevTo?: string;} {- const now = new Date();- const to = now.toISOString();- const from = new Date(now.getTime() - days * 86400000).toISOString();- const prevTo = from;- const prevFrom = new Date(now.getTime() - days * 2 * 86400000).toISOString();- return { from, to, prevFrom, prevTo };+ if (!window?.dateFrom && !window?.dateTo) {+ return {};+ }++ const from = window.dateFrom;+ const to = expandDateToEndOfDay(window.dateTo) ?? new Date().toISOString();++ if (!from) {+ return { to };+ }++ const prev = previousWindow(from, to);+ return { from, to, prevFrom: prev.from, prevTo: prev.to };+}++/** Cap daily trend buckets so an "all time" scan stays chart-friendly. */+const TRAFFIC_TREND_MAX_DAYS = 365;++function listUtcDays(from: string, to: string): string[] {+ const days: string[] = [];+ const start = new Date(from);+ const end = new Date(to);+ const cursor = new Date(+ Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate()),+ );+ const endDay = new Date(Date.UTC(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate()));++ while (cursor <= endDay) {+ days.push(cursor.toISOString().slice(0, 10));+ cursor.setUTCDate(cursor.getUTCDate() + 1);+ }++ return days;}/**@@ -67,7 +107,7 @@ const TRAFFIC_MAX_ROWS = 50_000;async function scanTrafficLogs(supabase: Awaited<ReturnType<typeof createClient>>,brandId: string,- window: { columns: string; from: string; to?: string },+ window: { columns: string; from?: string; to?: string; toInclusive?: boolean },onRow: (row: Record<string, unknown>) => void,): Promise<void> {for (let start = 0; start < TRAFFIC_MAX_ROWS; start += TRAFFIC_PAGE_SIZE) {@@ -75,12 +115,16 @@ async function scanTrafficLogs(.from('ai_traffic_logs').select(window.columns).eq('brand_id', brandId)- .gte('created_at', window.from)// Deterministic order so .range() pages don't shuffle between requests..order('created_at', { ascending: true }).order('id', { ascending: true }).range(start, start + TRAFFIC_PAGE_SIZE - 1);- if (window.to) query = query.lt('created_at', window.to);+ if (window.from) query = query.gte('created_at', window.from);+ if (window.to) {+ query = window.toInclusive+ ? query.lte('created_at', window.to)+ : query.lt('created_at', window.to);+ }const { data, error } = await query;if (error) throw new Error(error.message);@@ -91,18 +135,23 @@ async function scanTrafficLogs(}}-export async function getTrafficSummary(brandId: string, days = 7): Promise<TrafficSummary> {+export async function getTrafficSummary(+ brandId: string,+ window?: TrafficDateWindow,+): Promise<TrafficSummary> {const supabase = await createClient();- const { from, prevFrom, prevTo } = getDateRange(days);+ const { from, to, prevFrom, prevTo } = resolveTrafficWindow(window);// Exact totals — count queries transfer no rows and are immune to the cap.- const countVisits = async (fromTs: string, toTs?: string) => {+ const countVisits = async (fromTs?: string, toTs?: string, toInclusive = false) => {let query = supabase.from('ai_traffic_logs').select('id', { count: 'exact', head: true })- .eq('brand_id', brandId)- .gte('created_at', fromTs);- if (toTs) query = query.lt('created_at', toTs);+ .eq('brand_id', brandId);+ if (fromTs) query = query.gte('created_at', fromTs);+ if (toTs) {+ query = toInclusive ? query.lte('created_at', toTs) : query.lt('created_at', toTs);+ }const { count, error } = await query;if (error) throw new Error(error.message);return count ?? 0;@@ -131,16 +180,24 @@ export async function getTrafficSummary(brandId: string, days = 7): Promise<Traf};const columns = 'source_platform, url, created_at, id';+ const hasPrev = Boolean(prevFrom && prevTo);const [totalVisits, totalVisitsPrev] = await Promise.all([- countVisits(from),- countVisits(prevFrom, prevTo),- scanTrafficLogs(supabase, brandId, { columns, from }, aggregate(platformMap, pageMap)),+ countVisits(from, to, true),+ hasPrev ? countVisits(prevFrom, prevTo) : Promise.resolve(0),scanTrafficLogs(supabase,brandId,- { columns, from: prevFrom, to: prevTo },- aggregate(platformMapPrev, pageMapPrev),+ { columns, from, to, toInclusive: true },+ aggregate(platformMap, pageMap),),+ hasPrev+ ? scanTrafficLogs(+ supabase,+ brandId,+ { columns, from: prevFrom, to: prevTo },+ aggregate(platformMapPrev, pageMapPrev),+ )+ : Promise.resolve(),]);const allPlatforms = new Set([...platformMap.keys(), ...platformMapPrev.keys()]);@@ -169,9 +226,12 @@ export async function getTrafficSummary(brandId: string, days = 7): Promise<Traf};}-export async function getTrafficTrend(brandId: string, days = 7): Promise<TrafficTrendPoint[]> {+export async function getTrafficTrend(+ brandId: string,+ window?: TrafficDateWindow,+): Promise<TrafficTrendPoint[]> {const supabase = await createClient();- const from = new Date(Date.now() - days * 86400000).toISOString();+ const { from, to } = resolveTrafficWindow(window);// Group by day + platform, aggregated per batch (#450).const dayMap = new Map<string, Map<string, number>>();@@ -180,7 +240,7 @@ export async function getTrafficTrend(brandId: string, days = 7): Promise<Traffiawait scanTrafficLogs(supabase,brandId,- { columns: 'source_platform, created_at, id', from },+ { columns: 'source_platform, created_at, id', from, to, toInclusive: true },(r) => {const day = (r.created_at as string).slice(0, 10);const platform = (r.source_platform as string) || 'unknown';@@ -192,20 +252,25 @@ export async function getTrafficTrend(brandId: string, days = 7): Promise<Traffi},);- // Fill missing days- const result: TrafficTrendPoint[] = [];- for (let i = days - 1; i >= 0; i--) {- const d = new Date(Date.now() - i * 86400000);- const day = d.toISOString().slice(0, 10);+ let days: string[];+ if (from && to) {+ days = listUtcDays(from, to);+ } else {+ days = [...dayMap.keys()].sort();+ if (days.length > TRAFFIC_TREND_MAX_DAYS) {+ days = days.slice(-TRAFFIC_TREND_MAX_DAYS);+ }+ if (days.length === 0) days = [new Date().toISOString().slice(0, 10)];+ }++ return days.map((day) => {const dm = dayMap.get(day);const point: TrafficTrendPoint = { date: day };for (const p of allPlatforms) {point[p] = dm?.get(p) ?? 0;}- result.push(point);- }-- return result;+ return point;+ });}export async function getTrafficLogs(@@ -215,7 +280,8 @@ export async function getTrafficLogs(offset?: number;platform?: string;search?: string;- days?: number;+ dateFrom?: string;+ dateTo?: string;},): Promise<{ logs: TrafficLog[]; total: number }> {const supabase = await createClient();@@ -223,7 +289,10 @@ export async function getTrafficLogs(const offset = opts?.offset ?? 0;const platform = opts?.platform;const search = opts?.search;- const days = opts?.days;+ const { from, to } = resolveTrafficWindow({+ dateFrom: opts?.dateFrom,+ dateTo: opts?.dateTo,+ });let query = supabase.from('ai_traffic_logs')@@ -241,10 +310,8 @@ export async function getTrafficLogs(query = query.ilike('url', `%${escaped}%`);}- if (days) {- const from = new Date(Date.now() - days * 86400000).toISOString();- query = query.gte('created_at', from);- }+ if (from) query = query.gte('created_at', from);+ if (to) query = query.lte('created_at', to);const { data, error, count } = await query.order('created_at', { ascending: false })