后台数据可视化:Recharts 漏斗图、总览页 KPI 卡片和缓存饼图

This commit is contained in:
2569718930@qq.com
2026-05-18 20:53:27 +08:00
parent e12d935cde
commit a9d71c18aa
7 changed files with 681 additions and 39 deletions
@@ -5,6 +5,16 @@ import { RefreshCcw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { opsApi } from "@/lib/ops-api";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Cell,
} from "recharts";
type FunnelStep = { label: string; count: number; pct_of_prev?: number };
@@ -17,14 +27,19 @@ export function AnalyticsPageClient() {
setLoading(true);
try {
const data = await opsApi.funnel(days);
const steps = (data as unknown as { steps?: FunnelStep[] }).steps ?? [];
setFunnel(steps);
setFunnel((data as unknown as { steps?: FunnelStep[] }).steps ?? []);
} catch { /* */ }
setLoading(false);
};
useEffect(() => { void load(); }, [days]);
const chartData = [...funnel].reverse().map((s) => ({
name: s.label,
count: s.count,
pct: s.pct_of_prev,
}));
const maxCount = Math.max(...funnel.map((s) => s.count), 1);
if (loading) return <div className="text-slate-400 animate-pulse">...</div>;
@@ -50,34 +65,100 @@ export function AnalyticsPageClient() {
</div>
</div>
{/* Summary cards */}
{funnel.length > 0 && (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
<Card>
<CardContent className="p-4">
<div className="text-xs text-slate-500"></div>
<div className="text-xl font-bold text-white">{funnel[0]?.count ?? 0}</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-xs text-slate-500"></div>
<div className="text-xl font-bold text-cyan-400">{funnel[2]?.count ?? 0}</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-xs text-slate-500"></div>
<div className="text-xl font-bold text-amber-400">{funnel[4]?.count ?? 0}</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-xs text-slate-500"></div>
<div className="text-xl font-bold text-emerald-400">{funnel[5]?.count ?? 0}</div>
<div className="text-xs text-slate-500 mt-0.5">
{maxCount > 0 ? `${((funnel[5]?.count ?? 0) / maxCount * 100).toFixed(1)}%` : "—"}
</div>
</CardContent>
</Card>
</div>
)}
{/* Funnel chart */}
<Card>
<CardHeader><CardTitle></CardTitle></CardHeader>
<CardHeader><CardTitle> (Recharts)</CardTitle></CardHeader>
<CardContent>
<div className="space-y-4">
{funnel.map((step, i) => {
const pct = (step.count / maxCount) * 100;
const prevPct = step.pct_of_prev != null ? `${step.pct_of_prev}%` : "—";
return (
<div key={i}>
<div className="flex justify-between text-sm mb-1">
<span className="text-slate-300">{step.label}</span>
<span className="text-slate-400">
<span className="text-white font-bold">{step.count}</span>
<span className="ml-2 text-xs"> {prevPct}</span>
</span>
</div>
<div className="h-6 w-full rounded-full bg-white/5 overflow-hidden">
<div
className="h-full rounded-full bg-gradient-to-r from-cyan-500 to-blue-500 transition-all duration-500"
style={{ width: `${Math.max(pct, 2)}%` }}
/>
</div>
</div>
);
})}
{funnel.length === 0 && (
<p className="text-slate-500 text-sm py-4 text-center"></p>
)}
{chartData.length === 0 ? (
<p className="text-slate-500 text-sm py-8 text-center"></p>
) : (
<ResponsiveContainer width="100%" height={chartData.length * 60 + 40}>
<BarChart
data={chartData}
layout="vertical"
margin={{ top: 5, right: 40, left: 140, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
<XAxis type="number" stroke="rgba(255,255,255,0.3)" tick={{ fill: "#94a3b8", fontSize: 12 }} />
<YAxis type="category" dataKey="name" stroke="rgba(255,255,255,0.3)" tick={{ fill: "#e2e8f0", fontSize: 13 }} width={130} />
<Tooltip
contentStyle={{ background: "#1e293b", border: "1px solid rgba(255,255,255,0.1)", borderRadius: 8, color: "#e2e8f0" }}
formatter={(value) => [`${value}`, "数量"]}
/>
<Bar dataKey="count" radius={[0, 6, 6, 0]}>
{chartData.map((_, i) => {
const colors = ["#06b6d4", "#0ea5e9", "#6366f1", "#f59e0b", "#22c55e", "#10b981"];
return <Cell key={i} fill={colors[i % colors.length]} />;
})}
</Bar>
</BarChart>
</ResponsiveContainer>
)}
</CardContent>
</Card>
{/* Drop-off table */}
<Card>
<CardHeader><CardTitle></CardTitle></CardHeader>
<CardContent>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-white/10 text-left text-slate-400">
<th className="py-2 px-3 font-medium"></th>
<th className="py-2 px-3 font-medium text-right"></th>
<th className="py-2 px-3 font-medium text-right"></th>
<th className="py-2 px-3 font-medium text-right"></th>
</tr>
</thead>
<tbody>
{funnel.map((step, i) => {
const pct = step.pct_of_prev;
const dropPct = pct != null ? 100 - pct : 0;
return (
<tr key={i} className="border-b border-white/5">
<td className="py-2 px-3 text-white">{step.label}</td>
<td className="py-2 px-3 text-right font-mono text-white">{step.count}</td>
<td className="py-2 px-3 text-right text-emerald-400">{pct != null ? `${pct}%` : "—"}</td>
<td className="py-2 px-3 text-right text-amber-400">{i > 0 ? `${dropPct}%` : "—"}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</CardContent>
</Card>
@@ -20,6 +20,7 @@ const navGroups = [
{
label: "监控",
items: [
{ href: "/ops/overview", icon: LayoutDashboard, label: "总览" },
{ href: "/ops/system", icon: Cpu, label: "系统状态" },
{ href: "/ops/training", icon: Database, label: "训练数据" },
{ href: "/ops/analytics", icon: BarChart3, label: "转化分析" },
@@ -0,0 +1,175 @@
"use client";
import { useEffect, useState } from "react";
import { RefreshCcw, TrendingUp, Users, CreditCard, Database, Activity } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { opsApi } from "@/lib/ops-api";
import Link from "next/link";
import type { SystemStatusPayload, MembershipsPayload, FunnelPayload } from "@/types/ops";
import {
PieChart, Pie, Cell, ResponsiveContainer, Tooltip,
} from "recharts";
export function OverviewPageClient() {
const [loading, setLoading] = useState(true);
const [status, setStatus] = useState<SystemStatusPayload | null>(null);
const [memberships, setMemberships] = useState<MembershipsPayload | null>(null);
const [funnel, setFunnel] = useState<FunnelPayload | null>(null);
const load = async () => {
setLoading(true);
try {
const [s, m, f] = await Promise.all([
opsApi.systemStatus() as Promise<SystemStatusPayload>,
opsApi.memberships() as Promise<MembershipsPayload>,
opsApi.funnel(7) as Promise<FunnelPayload>,
]);
setStatus(s);
setMemberships(m);
setFunnel(f);
} catch { /* */ }
setLoading(false);
};
useEffect(() => { void load(); }, []);
if (loading) return <div className="text-slate-400 animate-pulse">...</div>;
const cacheAnalysis = status?.cache?.analysis;
const cacheData = cacheAnalysis ? [
{ name: "命中", value: cacheAnalysis.cache_hits ?? 0, color: "#22c55e" },
{ name: "未命中", value: cacheAnalysis.cache_misses ?? 0, color: "#f59e0b" },
{ name: "强制刷新", value: cacheAnalysis.force_refresh_requests ?? 0, color: "#3b82f6" },
].filter((d) => d.value > 0) : [];
const mems = memberships?.memberships ?? [];
const paid = mems.filter((m) => !(m as Record<string, unknown>).is_trial).length;
const trials = mems.filter((m) => (m as Record<string, unknown>).is_trial).length;
const steps = funnel?.steps ?? [];
const totalUsers = steps[0]?.count ?? 0;
const payingUsers = steps[5]?.count ?? 0;
const convRate = totalUsers > 0 ? ((payingUsers / totalUsers) * 100).toFixed(1) : "—";
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-white"></h1>
<Button variant="outline" size="sm" onClick={load} className="gap-1.5">
<RefreshCcw className="h-3.5 w-3.5" />
</Button>
</div>
{/* KPI cards */}
<div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
<Link href="/ops/system" className="block">
<Card className="hover:bg-white/[0.03] transition-colors cursor-pointer">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<Activity className={`h-4 w-4 ${status?.db?.ok ? "text-emerald-400" : "text-red-400"}`} />
<span className="text-xs text-slate-500"></span>
</div>
<div className="text-lg font-bold text-white">{status?.db?.ok ? "OK" : "—"}</div>
</CardContent>
</Card>
</Link>
<Link href="/ops/memberships" className="block">
<Card className="hover:bg-white/[0.03] transition-colors cursor-pointer">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<Users className="h-4 w-4 text-cyan-400" />
<span className="text-xs text-slate-500"></span>
</div>
<div className="text-lg font-bold text-cyan-400">{paid}</div>
{trials > 0 && <div className="text-xs text-slate-500 mt-0.5"> {trials}</div>}
</CardContent>
</Card>
</Link>
<Link href="/ops/payments" className="block">
<Card className="hover:bg-white/[0.03] transition-colors cursor-pointer">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<CreditCard className="h-4 w-4 text-emerald-400" />
<span className="text-xs text-slate-500"></span>
</div>
<div className="text-lg font-bold text-emerald-400">{payingUsers}</div>
</CardContent>
</Card>
</Link>
<Link href="/ops/analytics" className="block">
<Card className="hover:bg-white/[0.03] transition-colors cursor-pointer">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<TrendingUp className="h-4 w-4 text-blue-400" />
<span className="text-xs text-slate-500"></span>
</div>
<div className="text-lg font-bold text-blue-400">{convRate}%</div>
</CardContent>
</Card>
</Link>
<Link href="/ops/training" className="block">
<Card className="hover:bg-white/[0.03] transition-colors cursor-pointer">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<Database className="h-4 w-4 text-purple-400" />
<span className="text-xs text-slate-500"></span>
</div>
<div className="text-lg font-bold text-purple-400">
{status?.training_data?.truth_records?.row_count ?? "—"}
</div>
</CardContent>
</Card>
</Link>
</div>
{/* Cache pie chart */}
{cacheData.length > 0 && (
<Card>
<CardContent className="p-6">
<h3 className="text-sm font-bold text-white mb-4"></h3>
<div className="flex items-center gap-6">
<div className="w-48 h-48">
<ResponsiveContainer>
<PieChart>
<Pie
data={cacheData}
cx="50%"
cy="50%"
innerRadius={48}
outerRadius={80}
paddingAngle={2}
dataKey="value"
>
{cacheData.map((d, i) => (
<Cell key={i} fill={d.color} />
))}
</Pie>
<Tooltip
contentStyle={{ background: "#1e293b", border: "1px solid rgba(255,255,255,0.1)", borderRadius: 8, color: "#e2e8f0" }}
/>
</PieChart>
</ResponsiveContainer>
</div>
<div className="space-y-2 text-sm">
{cacheData.map((d) => (
<div key={d.name} className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ backgroundColor: d.color }} />
<span className="text-slate-400">{d.name}</span>
<span className="text-white font-bold ml-2">{d.value}</span>
</div>
))}
{cacheAnalysis?.hit_rate != null && (
<div className="pt-2 border-t border-white/10">
<span className="text-slate-400"> </span>
<span className="text-emerald-400 font-bold">{(cacheAnalysis.hit_rate * 100).toFixed(1)}%</span>
</div>
)}
</div>
</div>
</CardContent>
</Card>
)}
</div>
);
}