Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(analytics): Custom date range, API key filter & NULL key enrichment (#1830)
Gi99line929559e9a4a
diff --git a/src/app/api/usage/analytics/route.ts b/src/app/api/usage/analytics/route.tsindex 2c34e593a1..1d14c1e14d 100644--- a/src/app/api/usage/analytics/route.ts+++ b/src/app/api/usage/analytics/route.ts@@ -126,12 +126,128 @@ export async function GET(request: Request) {try {const { searchParams } = new URL(request.url);const range = searchParams.get("range") || "30d";- const sinceIso = getRangeStartIso(range);+ const startDate = searchParams.get("startDate") || undefined;+ const endDate = searchParams.get("endDate") || undefined;+ const apiKeyIdsParam = searchParams.get("apiKeyIds") || "";+ const apiKeyIds = apiKeyIdsParam ? apiKeyIdsParam.split(",").filter(Boolean) : [];++ const sinceIso = startDate || getRangeStartIso(range);+ const untilIso = endDate || null;const presetsParam = searchParams.get("presets");const db = getDbInstance();- const whereClause = sinceIso ? "WHERE timestamp >= @since" : "";- const params = sinceIso ? { since: sinceIso } : {};++ // ── Enrich entries with missing apiKeyName ──────────────────────────+ try {+ // Only run enrichment if there are actually NULL entries+ const hasNull = db.prepare("SELECT 1 FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL LIMIT 1").get();+ if (hasNull) {+ // Step 1: dominant key per connectionId from existing usage data+ db.prepare(`+ UPDATE usage_history+ SET+ api_key_name = (+ SELECT uh2.api_key_name+ FROM usage_history AS uh2+ WHERE uh2.connection_id = usage_history.connection_id+ AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''+ GROUP BY uh2.api_key_name+ ORDER BY COUNT(*) DESC+ LIMIT 1+ ),+ api_key_id = COALESCE(api_key_id, (+ SELECT uh2.api_key_id+ FROM usage_history AS uh2+ WHERE uh2.connection_id = usage_history.connection_id+ AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''+ GROUP BY uh2.api_key_name+ ORDER BY COUNT(*) DESC+ LIMIT 1+ ))+ WHERE (api_key_name IS NULL OR api_key_name = '')+ AND connection_id IS NOT NULL+ AND EXISTS (+ SELECT 1 FROM usage_history AS uh3+ WHERE uh3.connection_id = usage_history.connection_id+ AND uh3.api_key_name IS NOT NULL AND uh3.api_key_name != ''+ )+ `).run();++ // Step 2 & 3: For still unresolved connections, check apiKeys config+ const stillNull = db.prepare("SELECT DISTINCT connection_id FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL").all();+ if (stillNull.length > 0) {+ const { getApiKeys } = await import("@/lib/localDb");+ const apiKeys = (await getApiKeys()) as any[];++ const updateStmt = db.prepare("UPDATE usage_history SET api_key_name = ?, api_key_id = ? WHERE connection_id = ? AND (api_key_name IS NULL OR api_key_name = '')");+ const updateMany = db.transaction((updates: any[]) => {+ for (const u of updates) updateStmt.run(u.name, u.id, u.cid);+ });++ const updates = [];+ const orphanIds = new Set(stillNull.map((r: any) => r.connection_id));++ for (const ak of apiKeys) {+ const allowed = Array.isArray(ak.allowedConnections) ? ak.allowedConnections : [];+ const keyName = ak.name || ak.id;+ const keyId = ak.id || null;+ for (const cid of allowed) {+ if (typeof cid === "string" && orphanIds.has(cid)) {+ updates.push({ name: keyName, id: keyId, cid });+ orphanIds.delete(cid);+ }+ }+ }++ if (orphanIds.size > 0) {+ const unrestrictedKeys = apiKeys.filter(+ (ak: any) => !Array.isArray(ak.allowedConnections) || ak.allowedConnections.length === 0+ );+ if (unrestrictedKeys.length > 0) {+ let bestKey = unrestrictedKeys[0];+ let bestCount = -1;+ for (const uk of unrestrictedKeys) {+ const countRow = db.prepare("SELECT COUNT(*) as c FROM usage_history WHERE api_key_name = ?").get(uk.name || uk.id) as any;+ if (countRow.c > bestCount) { bestCount = countRow.c; bestKey = uk; }+ }+ const fallbackName = bestKey.name || bestKey.id;+ const fallbackId = bestKey.id || null;+ for (const cid of orphanIds) {+ updates.push({ name: fallbackName, id: fallbackId, cid });+ }+ }+ }++ if (updates.length > 0) updateMany(updates);+ }+ }+ } catch(e) {+ console.error("Failed to backfill missing api_key_name:", e);+ }++ const conditions = [];+ const params: Record<string, string> = {};++ if (sinceIso) {+ conditions.push("timestamp >= @since");+ params.since = sinceIso;+ }+ if (untilIso) {+ conditions.push("timestamp <= @until");+ params.until = untilIso;+ }++ let apiKeyWhere = "";+ if (apiKeyIds.length > 0) {+ const placeholders = apiKeyIds.map((_, i) => `@apiKey${i}`);+ apiKeyIds.forEach((key, i) => {+ params[`apiKey${i}`] = key;+ });+ apiKeyWhere = `(api_key_name IN (${placeholders.join(",")}) OR api_key_id IN (${placeholders.join(",")}))`;+ conditions.push(apiKeyWhere);+ }++ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";// Fetch pricing data for cost calculation (no rows loaded)const { getPricing } = await import("@/lib/db/settings");@@ -199,6 +315,22 @@ export async function GET(request: Request) {const heatmapStart = new Date();heatmapStart.setUTCDate(heatmapStart.getUTCDate() - 364);+ // Custom date range might need a wider heatmap window+ if (startDate) {+ const customStart = new Date(startDate);+ if (customStart.getTime() < heatmapStart.getTime()) {+ heatmapStart.setTime(customStart.getTime());+ }+ }++ // Heatmap needs its own whereClause if api keys are filtered+ const heatmapConditions = ["timestamp >= @heatmapStart"];+ if (apiKeyWhere) heatmapConditions.push(apiKeyWhere);+ const heatmapParams: Record<string, string> = { heatmapStart: heatmapStart.toISOString() };+ if (apiKeyIds.length > 0) {+ apiKeyIds.forEach((key, i) => { heatmapParams[`apiKey${i}`] = key; });+ }+const heatmapRows = db.prepare(`@@ -206,12 +338,12 @@ export async function GET(request: Request) {DATE(timestamp) as date,COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokensFROM usage_history- WHERE timestamp >= @heatmapStart+ WHERE ${heatmapConditions.join(" AND ")}GROUP BY DATE(timestamp)ORDER BY date ASC`)- .all({ heatmapStart: heatmapStart.toISOString() }) as Array<Record<string, unknown>>;+ .all(heatmapParams) as Array<Record<string, unknown>>;const modelRows = db.prepare(@@ -403,8 +535,7 @@ export async function GET(request: Request) {): 0,avgLatencyMs: Math.round(Number(summaryRow?.avgLatencyMs || 0)),- // Compute totalCost by summing cost from byModel (calculated later)- totalCost: 0, // Will be updated after byModel is processed+ totalCost: 0,firstRequest: summaryRow?.firstRequest || "",lastRequest: summaryRow?.lastRequest || "",fallbackCount: Number(fallbackRow?.fallbacks || 0),@@ -620,7 +751,7 @@ export async function GET(request: Request) {weeklyTokens,weeklyCounts,range,- };+ } as any;if (presetsParam) {const allowedRanges = new Set(["1d", "7d", "30d", "90d", "ytd", "all"]);@@ -639,8 +770,12 @@ export async function GET(request: Request) {}const presetSinceIso = getRangeStartIso(presetRange);- const presetWhere = presetSinceIso ? "WHERE timestamp >= @presetSince" : "";- const presetParams = presetSinceIso ? { presetSince: presetSinceIso } : {};+ const presetConditions = [];+ const presetParams: Record<string, string> = {};+ if (presetSinceIso) { presetConditions.push("timestamp >= @presetSince"); presetParams.presetSince = presetSinceIso; }+ if (apiKeyWhere) { presetConditions.push(apiKeyWhere); Object.assign(presetParams, params); }++ const presetWhere = presetConditions.length > 0 ? `WHERE ${presetConditions.join(" AND ")}` : "";const presetModelRows = db.prepare(diff --git a/src/lib/usageAnalytics.ts b/src/lib/usageAnalytics.tsindex 5319179c5e..77fd0fc159 100644--- a/src/lib/usageAnalytics.ts+++ b/src/lib/usageAnalytics.ts@@ -12,14 +12,22 @@ import {/*** Compute date range boundaries- * @param {string} range - "1d" | "7d" | "30d" | "90d" | "ytd" | "all"+ * @param {string} range - "1d" | "7d" | "30d" | "90d" | "ytd" | "all" | "custom"+ * @param {string} [startDate] - ISO string for custom range start+ * @param {string} [endDate] - ISO string for custom range end* @returns {{ start: Date, end: Date }}*/-function getDateRange(range: string) {+function getDateRange(range: string, startDate?: string, endDate?: string) {const end = new Date();let start;switch (range) {+ case "custom":+ start = startDate ? new Date(startDate) : new Date(0);+ return {+ start,+ end: endDate ? new Date(endDate) : end,+ };case "1d":start = new Date(end);start.setDate(start.getDate() - 1);@@ -78,9 +86,10 @@ function shortModelName(model: string) {export async function computeAnalytics(history: any[],range = "30d",- connectionMap: Record<string, string> = {}+ connectionMap: Record<string, string> = {},+ options: { startDate?: string; endDate?: string } = {}) {- const { start, end } = getDateRange(range);+ const { start, end } = getDateRange(range, options.startDate, options.endDate);// ---- Filtered entries ----const entries = history.filter((e) => {diff --git a/src/shared/components/UsageAnalytics.tsx b/src/shared/components/UsageAnalytics.tsxindex 0d699358a8..0ab5838dc9 100644--- a/src/shared/components/UsageAnalytics.tsx+++ b/src/shared/components/UsageAnalytics.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, useCallback, useMemo } from "react";+import { useState, useEffect, useCallback, useMemo, useRef } from "react";import Card from "./Card";import { CardSkeleton } from "./Loading";import { fmtCompact as fmt, fmtFull, fmtCost } from "@/shared/utils/formatting";@@ -18,6 +18,8 @@ import {ProviderCostDonut,ModelOverTimeChart,ProviderTable,+ ApiKeyFilterDropdown,+ CustomRangePicker,} from "./analytics";// ============================================================================@@ -30,25 +32,90 @@ export default function UsageAnalytics() {const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);+ // Custom date range state+ const [customStart, setCustomStart] = useState("");+ const [customEnd, setCustomEnd] = useState("");+ const [showCustomPicker, setShowCustomPicker] = useState(false);+ const customPickerAnchorRef = useRef<HTMLDivElement>(null);++ // API key filter state+ const [selectedApiKeys, setSelectedApiKeys] = useState<string[]>([]);+ const [availableApiKeys, setAvailableApiKeys] = useState<{ id: string; name: string }[]>([]);+const fetchAnalytics = useCallback(async () => {try {setLoading(true);- const res = await fetch(`/api/usage/analytics?range=${range}`);+ const params = new URLSearchParams();+ params.set("range", range);+ if (range === "custom" && customStart && customEnd) {+ params.set("startDate", customStart);+ params.set("endDate", customEnd);+ }+ if (selectedApiKeys.length > 0) {+ params.set("apiKeyIds", selectedApiKeys.join(","));+ }+ const res = await fetch(`/api/usage/analytics?${params.toString()}`);if (!res.ok) throw new Error("Failed to fetch");const data = await res.json();setAnalytics(data);setError(null);++ // Update available keys from unfiltered data (only when no filter is active).+ // Use apiKeyName as the stable identifier — it is always populated+ // for every OmniRoute API key regardless of the downstream provider.+ if (selectedApiKeys.length === 0 && data.byApiKey?.length > 0) {+ const seen = new Set<string>();+ const keys: { id: string; name: string }[] = [];+ for (const k of data.byApiKey) {+ const name = k.apiKeyName || k.apiKeyId || "unknown";+ if (seen.has(name)) continue;+ seen.add(name);+ keys.push({ id: name, name });+ }+ setAvailableApiKeys(keys);+ }} catch (err) {setError((err as any).message);} finally {setLoading(false);}- }, [range]);+ }, [range, customStart, customEnd, selectedApiKeys]);useEffect(() => {fetchAnalytics();}, [fetchAnalytics]);+ const handleRangeSelect = useCallback((value: string) => {+ if (value === "custom") {+ setShowCustomPicker(true);+ } else {+ setRange(value);+ setShowCustomPicker(false);+ }+ }, []);++ const handleCustomApply = useCallback((start: string, end: string) => {+ setCustomStart(start);+ setCustomEnd(end);+ setRange("custom");+ setShowCustomPicker(false);+ }, []);++ // Format custom range label for display+ const customRangeLabel = useMemo(() => {+ if (range !== "custom" || !customStart || !customEnd) return null;+ const fmt = (iso: string) => {+ const d = new Date(iso);+ return d.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ });+ };+ return `${fmt(customStart)} — ${fmt(customEnd)}`;+ }, [range, customStart, customEnd]);+const ranges = [{ value: "1d", label: "1D" },{ value: "7d", label: "7D" },@@ -111,26 +178,74 @@ export default function UsageAnalytics() {return (<div className="flex flex-col gap-5 min-w-0">- {/* Header + Time Range */}- <div className="flex items-center justify-between">+ {/* Header + Filters */}+ <div className="flex items-center justify-between flex-wrap gap-3"><h2 className="text-xl font-semibold flex items-center gap-2"><span className="material-symbols-outlined text-primary text-[22px]">analytics</span>Usage Analytics</h2>- <div className="flex items-center gap-1 bg-black/[0.03] dark:bg-white/[0.03] rounded-lg p-1 border border-black/5 dark:border-white/5">- {ranges.map((r) => (+ <div className="flex items-center gap-2.5">+ {/* API Key Filter */}+ <ApiKeyFilterDropdown+ available={availableApiKeys}+ selected={selectedApiKeys}+ onChange={setSelectedApiKeys}+ />++ {/* Period Selector + Custom */}+ <div+ className="relative flex items-center gap-1 bg-black/[0.03] dark:bg-white/[0.03] rounded-lg p-1 border border-black/5 dark:border-white/5"+ ref={customPickerAnchorRef}+ >+ {ranges.map((r) => (+ <button+ key={r.value}+ onClick={() => handleRangeSelect(r.value)}+ className={`px-3 py-1 rounded-md text-xs font-semibold transition-all ${+ range === r.value+ ? "bg-primary text-white shadow-sm"+ : "text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5"+ }`}+ >+ {r.label}+ </button>+ ))}<button- key={r.value}- onClick={() => setRange(r.value)}- className={`px-3 py-1 rounded-md text-xs font-semibold transition-all ${- range === r.value+ onClick={() => handleRangeSelect("custom")}+ className={`px-3 py-1 rounded-md text-xs font-semibold transition-all flex items-center gap-1 ${+ range === "custom"? "bg-primary text-white shadow-sm": "text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5"}`}>- {r.label}+ <span className="material-symbols-outlined text-[13px]">date_range</span>+ {customRangeLabel || "Custom"}+ {range === "custom" && customRangeLabel && (+ <span+ role="button"+ onClick={(e) => {+ e.stopPropagation();+ setRange("30d");+ setCustomStart("");+ setCustomEnd("");+ }}+ className="ml-0.5 opacity-70 hover:opacity-100"+ >+ <span className="material-symbols-outlined text-[11px]">close</span>+ </span>+ )}</button>- ))}++ {/* Custom Range Picker Popover */}+ {showCustomPicker && (+ <CustomRangePicker+ start={customStart}+ end={customEnd}+ onApply={handleCustomApply}+ onClose={() => setShowCustomPicker(false)}+ />+ )}+ </div></div></div>diff --git a/src/shared/components/analytics/ApiKeyFilterDropdown.tsx b/src/shared/components/analytics/ApiKeyFilterDropdown.tsxnew file mode 100644index 0000000000..01e5f5c96c--- /dev/null+++ b/src/shared/components/analytics/ApiKeyFilterDropdown.tsx@@ -0,0 +1,201 @@+"use client";++import { useState, useRef, useEffect, useMemo, useCallback } from "react";++interface ApiKeyInfo {+ id: string;+ name: string;+}++interface ApiKeyFilterDropdownProps {+ available: ApiKeyInfo[];+ selected: string[];+ onChange: (ids: string[]) => void;+}++function maskKeyName(name: string): string {+ if (!name || name.length <= 8) return name || "unknown";+ return `${name.slice(0, 6)}…${name.slice(-4)}`;+}++export default function ApiKeyFilterDropdown({+ available,+ selected,+ onChange,+}: ApiKeyFilterDropdownProps) {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const ref = useRef<HTMLDivElement>(null);++ // Close on click outside+ useEffect(() => {+ if (!open) return;+ function handleClick(e: MouseEvent) {+ if (ref.current && !ref.current.contains(e.target as Node)) {+ setOpen(false);+ }+ }+ document.addEventListener("mousedown", handleClick);+ return () => document.removeEventListener("mousedown", handleClick);+ }, [open]);++ // Close on Escape+ useEffect(() => {+ if (!open) return;+ function handleKey(e: KeyboardEvent) {+ if (e.key === "Escape") setOpen(false);+ }+ document.addEventListener("keydown", handleKey);+ return () => document.removeEventListener("keydown", handleKey);+ }, [open]);++ const filtered = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (!q) return available;+ return available.filter(+ (k) => k.name.toLowerCase().includes(q) || k.id.toLowerCase().includes(q)+ );+ }, [available, query]);++ const isAllSelected = selected.length === 0;++ const toggleKey = useCallback(+ (id: string) => {+ if (selected.includes(id)) {+ const next = selected.filter((s) => s !== id);+ onChange(next);+ } else {+ onChange([...selected, id]);+ }+ },+ [selected, onChange]+ );++ const selectAll = useCallback(() => {+ onChange([]);+ }, [onChange]);++ const buttonLabel = useMemo(() => {+ if (isAllSelected) return "All Keys";+ if (selected.length === 1) {+ const key = available.find((k) => k.id === selected[0]);+ return key ? maskKeyName(key.name) : "1 key";+ }+ return `${selected.length} keys`;+ }, [isAllSelected, selected, available]);++ if (available.length === 0) return null;++ return (+ <div className="relative" ref={ref}>+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className={`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium transition-all ${+ isAllSelected+ ? "border-border/50 bg-black/[0.03] text-text-muted hover:text-text-main dark:bg-white/[0.03]"+ : "border-primary/40 bg-primary/10 text-primary"+ }`}+ >+ <span className="material-symbols-outlined text-[14px]">vpn_key</span>+ {buttonLabel}+ <span+ className={`material-symbols-outlined text-[14px] transition-transform ${+ open ? "rotate-180" : ""+ }`}+ >+ expand_more+ </span>+ </button>++ {open && (+ <div+ className="absolute left-0 top-full z-50 mt-1.5 w-[260px] rounded-xl border border-border/50 bg-surface shadow-xl"+ style={{ backdropFilter: "blur(16px)" }}+ >+ {/* Search */}+ {available.length > 5 && (+ <div className="border-b border-border/30 p-2">+ <input+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search keys…"+ className="w-full rounded-md border border-border/30 bg-black/[0.03] px-2.5 py-1.5 text-xs text-text-main placeholder:text-text-muted focus:outline-none focus:border-primary dark:bg-white/[0.03]"+ autoFocus+ />+ </div>+ )}++ <div className="max-h-[280px] overflow-y-auto p-1.5">+ {/* All Keys option */}+ <button+ type="button"+ onClick={selectAll}+ className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-xs transition-colors ${+ isAllSelected+ ? "bg-primary/10 text-primary font-semibold"+ : "text-text-muted hover:bg-black/[0.04] hover:text-text-main dark:hover:bg-white/[0.04]"+ }`}+ >+ <span+ className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] ${+ isAllSelected+ ? "border-primary bg-primary text-white"+ : "border-border/60 bg-transparent"+ }`}+ >+ {isAllSelected && (+ <span className="material-symbols-outlined text-[12px]">check</span>+ )}+ </span>+ All Keys+ <span className="ml-auto text-[10px] text-text-muted font-normal">+ {available.length}+ </span>+ </button>++ {/* Divider */}+ <div className="my-1 h-px bg-border/20" />++ {/* Individual keys */}+ {filtered.map((key) => {+ const isChecked = selected.includes(key.id);++ return (+ <button+ key={key.id}+ type="button"+ onClick={() => toggleKey(key.id)}+ className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-xs transition-colors ${+ isChecked+ ? "bg-primary/[0.06] text-text-main"+ : "text-text-muted hover:bg-black/[0.04] hover:text-text-main dark:hover:bg-white/[0.04]"+ }`}+ title={key.name || key.id}+ >+ <span+ className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] ${+ isChecked+ ? "border-primary bg-primary text-white"+ : "border-border/60 bg-transparent"+ }`}+ >+ {isChecked && (+ <span className="material-symbols-outlined text-[12px]">check</span>+ )}+ </span>+ <span className="truncate">{maskKeyName(key.name || key.id)}</span>+ </button>+ );+ })}++ {filtered.length === 0 && (+ <p className="px-2.5 py-3 text-center text-[11px] text-text-muted">No keys match</p>+ )}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/src/shared/components/analytics/CustomRangePicker.tsx b/src/shared/components/analytics/CustomRangePicker.tsxnew file mode 100644index 0000000000..0fd1cf5f44--- /dev/null+++ b/src/shared/components/analytics/CustomRangePicker.tsx@@ -0,0 +1,193 @@+"use client";++import { useState, useRef, useEffect, useCallback } from "react";++interface CustomRangePickerProps {+ start: string;+ end: string;+ onApply: (start: string, end: string) => void;+ onClose: () => void;+}++function toLocalDatetime(iso: string): string {+ if (!iso) return "";+ const d = new Date(iso);+ if (isNaN(d.getTime())) return "";+ const pad = (n: number) => String(n).padStart(2, "0");+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;+}++function fromLocalDatetime(local: string): string {+ if (!local) return "";+ return new Date(local).toISOString();+}++function getPresetRange(preset: string): { start: string; end: string } {+ const now = new Date();+ const end = toLocalDatetime(now.toISOString());+ const s = new Date(now);++ switch (preset) {+ case "today":+ s.setHours(0, 0, 0, 0);+ break;+ case "yesterday": {+ s.setDate(s.getDate() - 1);+ s.setHours(0, 0, 0, 0);+ const e = new Date(s);+ e.setHours(23, 59, 59, 999);+ return { start: toLocalDatetime(s.toISOString()), end: toLocalDatetime(e.toISOString()) };+ }+ case "thisWeek":+ s.setDate(s.getDate() - s.getDay());+ s.setHours(0, 0, 0, 0);+ break;+ case "thisMonth":+ s.setDate(1);+ s.setHours(0, 0, 0, 0);+ break;+ case "last3d":+ s.setDate(s.getDate() - 3);+ break;+ case "last14d":+ s.setDate(s.getDate() - 14);+ break;+ default:+ s.setDate(s.getDate() - 7);+ }++ return { start: toLocalDatetime(s.toISOString()), end };+}++export default function CustomRangePicker({+ start,+ end,+ onApply,+ onClose,+}: CustomRangePickerProps) {+ const [localStart, setLocalStart] = useState(toLocalDatetime(start) || "");+ const [localEnd, setLocalEnd] = useState(toLocalDatetime(end) || "");+ const ref = useRef<HTMLDivElement>(null);++ // Close on click outside+ useEffect(() => {+ function handleClick(e: MouseEvent) {+ if (ref.current && !ref.current.contains(e.target as Node)) {+ onClose();+ }+ }+ document.addEventListener("mousedown", handleClick);+ return () => document.removeEventListener("mousedown", handleClick);+ }, [onClose]);++ // Close on Escape+ useEffect(() => {+ function handleKey(e: KeyboardEvent) {+ if (e.key === "Escape") onClose();+ }+ document.addEventListener("keydown", handleKey);+ return () => document.removeEventListener("keydown", handleKey);+ }, [onClose]);++ const handleApply = useCallback(() => {+ if (localStart && localEnd) {+ onApply(fromLocalDatetime(localStart), fromLocalDatetime(localEnd));+ }+ }, [localStart, localEnd, onApply]);++ const handlePreset = useCallback((preset: string) => {+ const { start: s, end: e } = getPresetRange(preset);+ setLocalStart(s);+ setLocalEnd(e);+ }, []);++ const isValid = localStart && localEnd && new Date(localStart) <= new Date(localEnd);++ const presets = [+ { key: "today", label: "Today" },+ { key: "yesterday", label: "Yesterday" },+ { key: "last3d", label: "Last 3 days" },+ { key: "thisWeek", label: "This week" },+ { key: "last14d", label: "Last 14 days" },+ { key: "thisMonth", label: "This month" },+ ];++ return (+ <div+ ref={ref}+ className="absolute right-0 top-full z-50 mt-2 w-[340px] rounded-xl border border-border/50 bg-surface p-4 shadow-xl"+ style={{ backdropFilter: "blur(16px)" }}+ >+ {/* Quick presets */}+ <div className="mb-3">+ <p className="text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5">+ Quick Select+ </p>+ <div className="flex flex-wrap gap-1">+ {presets.map((p) => (+ <button+ key={p.key}+ type="button"+ onClick={() => handlePreset(p.key)}+ className="rounded-md border border-border/30 bg-black/[0.03] px-2.5 py-1 text-[11px] font-medium text-text-muted transition-colors hover:bg-primary/10 hover:text-primary hover:border-primary/30 dark:bg-white/[0.03]"+ >+ {p.label}+ </button>+ ))}+ </div>+ </div>++ <div className="h-px bg-border/30 mb-3" />++ {/* Date inputs */}+ <div className="flex flex-col gap-2.5">+ <div>+ <label className="text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1 block">+ Start+ </label>+ <input+ type="datetime-local"+ value={localStart}+ onChange={(e) => setLocalStart(e.target.value)}+ className="w-full rounded-lg border border-border/50 bg-black/[0.04] px-3 py-2 text-sm text-text-main focus:outline-none focus:border-primary dark:bg-white/[0.04]"+ />+ </div>+ <div>+ <label className="text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1 block">+ End+ </label>+ <input+ type="datetime-local"+ value={localEnd}+ onChange={(e) => setLocalEnd(e.target.value)}+ className="w-full rounded-lg border border-border/50 bg-black/[0.04] px-3 py-2 text-sm text-text-main focus:outline-none focus:border-primary dark:bg-white/[0.04]"+ />+ </div>+ </div>++ {/* Validation hint */}+ {localStart && localEnd && !isValid && (+ <p className="mt-1.5 text-[11px] text-error">Start must be before end</p>+ )}++ {/* Actions */}+ <div className="mt-3 flex items-center justify-end gap-2">+ <button+ type="button"+ onClick={onClose}+ className="rounded-lg px-3 py-1.5 text-xs font-medium text-text-muted hover:text-text-main transition-colors"+ >+ Cancel+ </button>+ <button+ type="button"+ disabled={!isValid}+ onClick={handleApply}+ className="rounded-lg bg-primary px-4 py-1.5 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-primary-hover disabled:opacity-40 disabled:cursor-not-allowed"+ >+ Apply+ </button>+ </div>+ </div>+ );+}diff --git a/src/shared/components/analytics/index.tsx b/src/shared/components/analytics/index.tsxindex ba28edafef..fb14864249 100644--- a/src/shared/components/analytics/index.tsx+++ b/src/shared/components/analytics/index.tsx@@ -26,3 +26,6 @@ export {ModelOverTimeChart,ProviderTable,} from "./charts";++export { default as ApiKeyFilterDropdown } from "./ApiKeyFilterDropdown";+export { default as CustomRangePicker } from "./CustomRangePicker";