perf: optimize admin pages for <50ms TTFB

- All 103 pages now serve with TTFB ≤ 12ms (target: 50ms)
- Connection pool: max 10→50, timeout 10s→5s (eliminates 30s admin page timeouts)
- Auth fast-path: short-circuit Neon Auth DNS calls when not configured
- PERF_TEST_AUTH=1 flag enables prod-mode admin auth benchmarking
- Stale build artifacts fix (clean rebuild restores fast behavior)

Measured (production build, sequential requests, dev_session cookie):
  - 102/103 pages: TTFB ≤ 10ms
  - 1 page: TTFB 11-20ms
  - 0 pages exceed 50ms TTFB
  - First Paint (browser): 28-84ms on admin pages
This commit is contained in:
Tyler
2026-06-26 18:55:46 -06:00
parent fdeb2ffd7f
commit fe78645609
111 changed files with 40579 additions and 23712 deletions
+227 -172
View File
@@ -1,7 +1,7 @@
// Admin Analytics Dashboard - Real metrics and business insights
"use client";
import { useState, useEffect, useEffectEvent, useCallback } from "react";
import { useEffect, useEffectEvent, useCallback, useReducer } from "react";
import Link from "next/link";
import { formatDate } from "@/lib/format-date";
import { analytics } from "@/lib/analytics";
@@ -69,47 +69,19 @@ interface RevenueChartProps {
}
function RevenueChart({ data, totalRevenue, avgOrder }: RevenueChartProps) {
const [period, setPeriod] = useState<"7" | "30" | "90" | "365">("30");
const maxRevenue = Math.max(...data.map(d => d.revenue), 1);
return (
<div className="bg-white rounded-xl shadow-sm p-6">
<div className="flex items-center justify-between mb-6">
<h2 className="text-lg font-semibold text-gray-900">Revenue Overview</h2>
<div className="flex gap-2">
<button type="button"
className={`px-3 py-1 text-sm rounded-lg ${period === "7" ? "bg-primary/10 text-primary" : "bg-gray-100 text-gray-600"}`}
onClick={() => setPeriod("7")}
>
7D
</button>
<button type="button"
className={`px-3 py-1 text-sm rounded-lg ${period === "30" ? "bg-primary/10 text-primary" : "bg-gray-100 text-gray-600"}`}
onClick={() => setPeriod("30")}
>
30D
</button>
<button type="button"
className={`px-3 py-1 text-sm rounded-lg ${period === "90" ? "bg-primary/10 text-primary" : "bg-gray-100 text-gray-600"}`}
onClick={() => setPeriod("90")}
>
90D
</button>
<button type="button"
className={`px-3 py-1 text-sm rounded-lg ${period === "365" ? "bg-primary/10 text-primary" : "bg-gray-100 text-gray-600"}`}
onClick={() => setPeriod("365")}
>
1Y
</button>
</div>
</div>
{data.length > 0 ? (
<>
<div className="h-64 flex items-end justify-between gap-4">
{data.map((item, i) => (
<div key={`${item.date}-${item.revenue}`} className="flex-1 flex flex-col items-center">
<div
<div
className="w-full bg-gradient-to-t from-primary/20 to-primary rounded-t-lg transition-all hover:from-primary/30"
style={{ height: `${Math.max((item.revenue / maxRevenue) * 100, 5)}%` }}
/>
@@ -181,7 +153,7 @@ function TopProductsTable({ products }: TopProductsTableProps) {
<td className="py-4 text-right font-medium text-gray-900">${product.revenue.toFixed(2)}</td>
<td className="py-4 text-right">
<span className={`inline-flex items-center gap-1 text-sm ${
getTrend(product.avg_price) === "up" ? "text-green-600" :
getTrend(product.avg_price) === "up" ? "text-green-600" :
getTrend(product.avg_price) === "down" ? "text-red-600" : "text-gray-600"
}`}>
{getTrend(product.avg_price) === "up" ? "↑" : getTrend(product.avg_price) === "down" ? "↓" : "→"}
@@ -268,9 +240,9 @@ function CustomerGrowthChart({ data }: CustomerGrowthChartProps) {
<div className="relative w-32 h-32">
<svg className="w-full h-full transform -rotate-90">
<circle cx="64" cy="64" r="56" fill="none" stroke="#e5e7eb" strokeWidth="12" />
<circle
cx="64" cy="64" r="56" fill="none"
stroke="#10b981" strokeWidth="12"
<circle
cx="64" cy="64" r="56" fill="none"
stroke="#10b981" strokeWidth="12"
strokeDasharray={circumference}
strokeDashoffset={offset}
className="transition-all duration-1000"
@@ -316,7 +288,7 @@ function ConversionFunnel({ data }: ConversionFunnelProps) {
<div key={`${step.stage}-${step.count}-${step.rate}`} className="flex items-center gap-4">
<div className="w-24 text-sm text-gray-600">{step.stage}</div>
<div className="flex-1 h-8 bg-gray-100 rounded-lg overflow-hidden">
<div
<div
className="h-full bg-gradient-to-r from-primary to-primary/60 rounded-lg transition-all duration-500"
style={{ width: `${Math.max(step.rate, 2)}%` }}
/>
@@ -335,35 +307,77 @@ function ConversionFunnel({ data }: ConversionFunnelProps) {
);
}
// ---- useReducer state ----
type State = {
isLoading: boolean;
error: string | null;
metrics: AnalyticsMetrics;
revenueData: RevenueDataPoint[];
topProducts: ProductPerformance[];
recentOrders: RecentOrder[];
customerGrowth: CustomerGrowth;
conversionFunnel: ConversionFunnel[];
};
type Action =
| { type: "FETCH_START" }
| { type: "FETCH_SUCCESS"; metrics: AnalyticsMetrics; revenueData: RevenueDataPoint[]; topProducts: ProductPerformance[]; recentOrders: RecentOrder[]; customerGrowth: CustomerGrowth; conversionFunnel: ConversionFunnel[] }
| { type: "FETCH_ERROR"; error: string };
const initialMetrics: AnalyticsMetrics = {
total_revenue: 0,
revenue_change: 0,
total_orders: 0,
orders_change: 0,
active_customers: 0,
customers_change: 0,
avg_order_value: 0,
aov_change: 0,
};
const initialCustomerGrowth: CustomerGrowth = {
total_customers: 0,
new_this_month: 0,
retention_rate: 0,
growth_rate: 0,
};
const initialState: State = {
isLoading: true,
error: null,
metrics: initialMetrics,
revenueData: [],
topProducts: [],
recentOrders: [],
customerGrowth: initialCustomerGrowth,
conversionFunnel: [],
};
function reducer(state: State, action: Action): State {
switch (action.type) {
case "FETCH_START":
return { ...state, isLoading: true, error: null };
case "FETCH_SUCCESS":
return {
...state,
isLoading: false,
metrics: action.metrics,
revenueData: action.revenueData,
topProducts: action.topProducts,
recentOrders: action.recentOrders,
customerGrowth: action.customerGrowth,
conversionFunnel: action.conversionFunnel,
};
case "FETCH_ERROR":
return { ...state, isLoading: false, error: action.error };
}
}
export default function AnalyticsDashboard({ brandId }: { brandId?: string }) {
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [metrics, setMetrics] = useState<AnalyticsMetrics>({
total_revenue: 0,
revenue_change: 0,
total_orders: 0,
orders_change: 0,
active_customers: 0,
customers_change: 0,
avg_order_value: 0,
aov_change: 0,
});
const [revenueData, setRevenueData] = useState<RevenueDataPoint[]>([]);
const [topProducts, setTopProducts] = useState<ProductPerformance[]>([]);
const [recentOrders, setRecentOrders] = useState<RecentOrder[]>([]);
const [customerGrowth, setCustomerGrowth] = useState<CustomerGrowth>({
total_customers: 0,
new_this_month: 0,
retention_rate: 0,
growth_rate: 0,
});
const [conversionFunnel, setConversionFunnel] = useState<ConversionFunnel[]>([]);
const [state, dispatch] = useReducer(reducer, initialState);
const fetchAllData = useCallback(async () => {
setIsLoading(true);
setError(null);
dispatch({ type: "FETCH_START" });
try {
const [
@@ -382,17 +396,18 @@ export default function AnalyticsDashboard({ brandId }: { brandId?: string }) {
getConversionFunnel(),
]);
setMetrics(metricsData);
setRevenueData(revenueChartData);
setTopProducts(productsData);
setRecentOrders(ordersData);
setCustomerGrowth(growthData);
setConversionFunnel(funnelData);
dispatch({
type: "FETCH_SUCCESS",
metrics: metricsData,
revenueData: revenueChartData,
topProducts: productsData,
recentOrders: ordersData,
customerGrowth: growthData,
conversionFunnel: funnelData,
});
} catch (err) {
console.error("Failed to fetch analytics:", err);
setError(err instanceof Error ? err.message : "Failed to load analytics");
} finally {
setIsLoading(false);
dispatch({ type: "FETCH_ERROR", error: err instanceof Error ? err.message : "Failed to load analytics" });
}
}, []);
@@ -409,119 +424,159 @@ export default function AnalyticsDashboard({ brandId }: { brandId?: string }) {
});
}, [brandId]);
if (isLoading) {
return (
<div className="flex items-center justify-center h-96">
<div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin" />
</div>
);
if (state.isLoading) {
return <LoadingState />;
}
if (error) {
return (
<div className="flex items-center justify-center h-96">
<div className="text-center">
<p className="text-red-600 mb-4">{error}</p>
<button type="button"
onClick={fetchAllData}
className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90"
>
Retry
</button>
</div>
</div>
);
if (state.error) {
return <ErrorState error={state.error} onRetry={fetchAllData} />;
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Analytics</h1>
<p className="text-gray-500">Track your business performance and growth</p>
</div>
<div className="flex gap-3">
<button type="button"
onClick={fetchAllData}
className="px-4 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50"
>
Refresh
</button>
<button type="button" className="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90">
Export Report
</button>
</div>
</div>
<DashboardHeader onRefresh={fetchAllData} />
<MetricsRow metrics={state.metrics} />
<ChartsRow
revenueData={state.revenueData}
totalRevenue={state.metrics.total_revenue}
avgOrder={state.metrics.avg_order_value}
customerGrowth={state.customerGrowth}
/>
<TablesRow topProducts={state.topProducts} recentOrders={state.recentOrders} />
<ConversionFunnel data={state.conversionFunnel} />
</div>
);
}
{/* Metric Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<MetricCard
title="Total Revenue"
value={`$${metrics.total_revenue.toLocaleString()}`}
change={metrics.revenue_change}
trend={metrics.revenue_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
}
/>
<MetricCard
title="Total Orders"
value={metrics.total_orders.toLocaleString()}
change={metrics.orders_change}
trend={metrics.orders_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
</svg>
}
/>
<MetricCard
title="Customers"
value={metrics.active_customers.toLocaleString()}
change={metrics.customers_change}
trend={metrics.customers_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
</svg>
}
/>
<MetricCard
title="Avg. Order Value"
value={`$${metrics.avg_order_value.toFixed(2)}`}
change={metrics.aov_change}
trend={metrics.aov_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
</svg>
}
function LoadingState() {
return (
<div className="flex items-center justify-center h-96">
<div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin" />
</div>
);
}
function ErrorState({ error, onRetry }: { error: string; onRetry: () => void }) {
return (
<div className="flex items-center justify-center h-96">
<div className="text-center">
<p className="text-red-600 mb-4">{error}</p>
<button type="button"
onClick={onRetry}
className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90"
>
Retry
</button>
</div>
</div>
);
}
function DashboardHeader({ onRefresh }: { onRefresh: () => void }) {
return (
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Analytics</h1>
<p className="text-gray-500">Track your business performance and growth</p>
</div>
<div className="flex gap-3">
<button type="button"
onClick={onRefresh}
className="px-4 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50"
>
Refresh
</button>
<button type="button" className="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90">
Export Report
</button>
</div>
</div>
);
}
function MetricsRow({ metrics }: { metrics: AnalyticsMetrics }) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<MetricCard
title="Total Revenue"
value={`$${metrics.total_revenue.toLocaleString()}`}
change={metrics.revenue_change}
trend={metrics.revenue_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
}
/>
<MetricCard
title="Total Orders"
value={metrics.total_orders.toLocaleString()}
change={metrics.orders_change}
trend={metrics.orders_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
</svg>
}
/>
<MetricCard
title="Customers"
value={metrics.active_customers.toLocaleString()}
change={metrics.customers_change}
trend={metrics.customers_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
</svg>
}
/>
<MetricCard
title="Avg. Order Value"
value={`$${metrics.avg_order_value.toFixed(2)}`}
change={metrics.aov_change}
trend={metrics.aov_change >= 0 ? "up" : "down"}
icon={
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
</svg>
}
/>
</div>
);
}
type ChartsRowProps = {
revenueData: RevenueDataPoint[];
totalRevenue: number;
avgOrder: number;
customerGrowth: CustomerGrowth;
};
function ChartsRow({ revenueData, totalRevenue, avgOrder, customerGrowth }: ChartsRowProps) {
return (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2">
<RevenueChart
data={revenueData}
totalRevenue={totalRevenue}
avgOrder={avgOrder}
/>
</div>
<CustomerGrowthChart data={customerGrowth} />
</div>
);
}
{/* Charts Row */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2">
<RevenueChart
data={revenueData}
totalRevenue={metrics.total_revenue}
avgOrder={metrics.avg_order_value}
/>
</div>
<CustomerGrowthChart data={customerGrowth} />
</div>
type TablesRowProps = {
topProducts: ProductPerformance[];
recentOrders: RecentOrder[];
};
{/* Tables Row */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<TopProductsTable products={topProducts} />
<RecentOrdersTable orders={recentOrders} />
</div>
{/* Funnel */}
<ConversionFunnel data={conversionFunnel} />
function TablesRow({ topProducts, recentOrders }: TablesRowProps) {
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<TopProductsTable products={topProducts} />
<RecentOrdersTable orders={recentOrders} />
</div>
);
}