feat: API analytics dashboard with i18n and theme support
Next.js full-stack analytics dashboard for new-api. - Direct PostgreSQL readonly queries on logs table - 5 pages: Dashboard, Rankings, Aggregation, Logs, Detail - Dark/Light/System theme with CSS variables - Chinese/English i18n (default Chinese) - Recharts with dual Y-axis for input/output tokens - Lucide icons + Motion animations - Docker + docker-compose with external sinobridge network, port 8019
This commit is contained in:
140
app/aggregation/page.tsx
Normal file
140
app/aggregation/page.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { motion } from "motion/react";
|
||||
import { Users, Calendar, Hash, Zap, ArrowUpDown, ArrowDown, ArrowUp } from "lucide-react";
|
||||
import { TimeRangeSelector } from "@/components/TimeRangeSelector";
|
||||
import { type TimeRange, getTimeRange, buildQuery, formatNumber, formatTokens } from "@/lib/utils";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
interface AggItem {
|
||||
rank: number; name: string; calls: number;
|
||||
prompt_tokens: number; completion_tokens: number; total_tokens: number;
|
||||
}
|
||||
|
||||
type SortKey = "total_tokens" | "calls" | "prompt_tokens" | "completion_tokens";
|
||||
|
||||
export default function AggregationPage() {
|
||||
const { t } = useI18n();
|
||||
const [range, setRange] = useState<TimeRange>("30d");
|
||||
const [data, setData] = useState<AggItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sortKey, setSortKey] = useState<SortKey>("total_tokens");
|
||||
const [sortAsc, setSortAsc] = useState(false);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const { start, end } = getTimeRange(range);
|
||||
const res = await fetch(buildQuery("/api/aggregation", { start, end }));
|
||||
setData(await res.json());
|
||||
setLoading(false);
|
||||
}, [range]);
|
||||
|
||||
useEffect(() => { fetchData(); }, [fetchData]);
|
||||
|
||||
const sorted = [...data].sort((a, b) => {
|
||||
const diff = (a[sortKey] as number) - (b[sortKey] as number);
|
||||
return sortAsc ? diff : -diff;
|
||||
});
|
||||
|
||||
const totals = data.reduce(
|
||||
(acc, d) => ({ calls: acc.calls + d.calls, tokens: acc.tokens + d.total_tokens }),
|
||||
{ calls: 0, tokens: 0 }
|
||||
);
|
||||
|
||||
function handleSort(key: SortKey) {
|
||||
if (sortKey === key) setSortAsc(!sortAsc);
|
||||
else { setSortKey(key); setSortAsc(false); }
|
||||
}
|
||||
|
||||
function SortIcon({ col }: { col: SortKey }) {
|
||||
if (sortKey !== col) return <ArrowUpDown className="h-3 w-3" style={{ color: "var(--text-muted)", opacity: 0.5 }} />;
|
||||
return sortAsc
|
||||
? <ArrowUp className="h-3 w-3" style={{ color: "var(--accent)" }} />
|
||||
: <ArrowDown className="h-3 w-3" style={{ color: "var(--accent)" }} />;
|
||||
}
|
||||
|
||||
const sortHeaders: { key: SortKey; label: string }[] = [
|
||||
{ key: "calls", label: t("th.calls") },
|
||||
{ key: "prompt_tokens", label: t("th.input") },
|
||||
{ key: "completion_tokens", label: t("th.output") },
|
||||
{ key: "total_tokens", label: t("th.totalToken") },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} className="flex items-center gap-3">
|
||||
<Users className="h-5 w-5" style={{ color: "var(--accent)", opacity: 0.6 }} />
|
||||
<h1 className="text-2xl font-bold gradient-text">{t("agg.title")}</h1>
|
||||
</motion.div>
|
||||
<TimeRangeSelector value={range} onChange={setRange} />
|
||||
</div>
|
||||
|
||||
{!loading && data.length > 0 && (
|
||||
<motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="glass p-4 flex items-center gap-8 text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-3.5 w-3.5" style={{ color: "var(--accent)", opacity: 0.5 }} />
|
||||
<span style={{ color: "var(--text-muted)" }}>{t("agg.userCount")}</span>
|
||||
<span className="font-semibold font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-primary)" }}>{data.length}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Hash className="h-3.5 w-3.5" style={{ color: "var(--accent)", opacity: 0.5 }} />
|
||||
<span style={{ color: "var(--text-muted)" }}>{t("agg.totalCalls")}</span>
|
||||
<span className="font-semibold font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-primary)" }}>{formatNumber(totals.calls)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-3.5 w-3.5" style={{ color: "var(--accent)", opacity: 0.5 }} />
|
||||
<span style={{ color: "var(--text-muted)" }}>{t("agg.totalToken")}</span>
|
||||
<span className="font-semibold font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-primary)" }}>{formatTokens(totals.tokens)}</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="glass overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr style={{ borderBottom: "1px solid var(--surface-border)" }}>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>#</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>{t("th.user")}</th>
|
||||
{sortHeaders.map(h => (
|
||||
<th key={h.key} className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider cursor-pointer select-none transition-colors"
|
||||
style={{ color: "var(--text-muted)" }} onClick={() => handleSort(h.key)}>
|
||||
<span className="inline-flex items-center gap-1">{h.label} <SortIcon col={h.key} /></span>
|
||||
</th>
|
||||
))}
|
||||
<th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>{t("common.share")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr><td colSpan={7} className="px-4 py-16 text-center"><div className="inline-block h-5 w-5 animate-spin rounded-full spinner" /></td></tr>
|
||||
) : sorted.map((item, i) => {
|
||||
const pct = totals.tokens > 0 ? (item.total_tokens / totals.tokens * 100) : 0;
|
||||
return (
|
||||
<tr key={item.name} className="row-glow transition-colors group" style={{ borderBottom: "1px solid var(--surface-border)" }}>
|
||||
<td className="px-4 py-3 font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{i + 1}</td>
|
||||
<td className="px-4 py-3 font-medium transition-colors" style={{ color: "var(--text-accent)" }}>{item.name}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-secondary)" }}>{formatNumber(item.calls)}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{formatTokens(item.prompt_tokens)}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{formatTokens(item.completion_tokens)}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-medium font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-primary)" }}>{formatTokens(item.total_tokens)}</td>
|
||||
<td className="px-4 py-3 text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<div className="w-16 h-1.5 rounded-full overflow-hidden" style={{ background: "var(--progress-bg)" }}>
|
||||
<motion.div className="h-full rounded-full bg-gradient-to-r from-[var(--accent)] to-[var(--accent-purple)]"
|
||||
initial={{ width: 0 }} animate={{ width: `${Math.min(pct, 100)}%` }}
|
||||
transition={{ duration: 0.8, delay: i * 0.02 }} />
|
||||
</div>
|
||||
<span className="text-xs font-[family-name:var(--font-geist-mono)] w-10 text-right" style={{ color: "var(--text-muted)" }}>{pct.toFixed(1)}%</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
12
app/api/aggregation/route.ts
Normal file
12
app/api/aggregation/route.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getUserRanking } from "@/lib/queries";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const sp = req.nextUrl.searchParams;
|
||||
const startTs = sp.get("start") ? Number(sp.get("start")) : undefined;
|
||||
const endTs = sp.get("end") ? Number(sp.get("end")) : undefined;
|
||||
|
||||
// Get ALL users (no limit) for aggregation view
|
||||
const data = await getUserRanking(startTs, endTs, 500);
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
29
app/api/detail/[type]/[id]/route.ts
Normal file
29
app/api/detail/[type]/[id]/route.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getUserDetail, getModelDetail, getChannelDetail } from "@/lib/queries";
|
||||
|
||||
export async function GET(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ type: string; id: string }> }
|
||||
) {
|
||||
const { type, id } = await params;
|
||||
const sp = req.nextUrl.searchParams;
|
||||
const startTs = sp.get("start") ? Number(sp.get("start")) : undefined;
|
||||
const endTs = sp.get("end") ? Number(sp.get("end")) : undefined;
|
||||
|
||||
let data;
|
||||
switch (type) {
|
||||
case "user":
|
||||
data = await getUserDetail(decodeURIComponent(id), startTs, endTs);
|
||||
break;
|
||||
case "model":
|
||||
data = await getModelDetail(decodeURIComponent(id), startTs, endTs);
|
||||
break;
|
||||
case "channel":
|
||||
data = await getChannelDetail(Number(id), startTs, endTs);
|
||||
break;
|
||||
default:
|
||||
return NextResponse.json({ error: "Invalid type" }, { status: 400 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
19
app/api/logs/route.ts
Normal file
19
app/api/logs/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getLogs } from "@/lib/queries";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const sp = req.nextUrl.searchParams;
|
||||
|
||||
const data = await getLogs({
|
||||
page: sp.get("page") ? Number(sp.get("page")) : 1,
|
||||
pageSize: sp.get("page_size") ? Number(sp.get("page_size")) : 100,
|
||||
startTs: sp.get("start") ? Number(sp.get("start")) : undefined,
|
||||
endTs: sp.get("end") ? Number(sp.get("end")) : undefined,
|
||||
username: sp.get("username") || undefined,
|
||||
model: sp.get("model") || undefined,
|
||||
channelId: sp.get("channel_id") ? Number(sp.get("channel_id")) : undefined,
|
||||
tokenName: sp.get("token_name") || undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
11
app/api/overview/route.ts
Normal file
11
app/api/overview/route.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getOverview } from "@/lib/queries";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const sp = req.nextUrl.searchParams;
|
||||
const startTs = sp.get("start") ? Number(sp.get("start")) : undefined;
|
||||
const endTs = sp.get("end") ? Number(sp.get("end")) : undefined;
|
||||
|
||||
const data = await getOverview(startTs, endTs);
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
24
app/api/rankings/route.ts
Normal file
24
app/api/rankings/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getUserRanking, getModelRanking, getChannelRanking } from "@/lib/queries";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const sp = req.nextUrl.searchParams;
|
||||
const type = sp.get("type") || "user";
|
||||
const startTs = sp.get("start") ? Number(sp.get("start")) : undefined;
|
||||
const endTs = sp.get("end") ? Number(sp.get("end")) : undefined;
|
||||
const limit = sp.get("limit") ? Number(sp.get("limit")) : 50;
|
||||
|
||||
let data;
|
||||
switch (type) {
|
||||
case "model":
|
||||
data = await getModelRanking(startTs, endTs, limit);
|
||||
break;
|
||||
case "channel":
|
||||
data = await getChannelRanking(startTs, endTs, limit);
|
||||
break;
|
||||
default:
|
||||
data = await getUserRanking(startTs, endTs, limit);
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
12
app/api/trends/route.ts
Normal file
12
app/api/trends/route.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getTrends } from "@/lib/queries";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const sp = req.nextUrl.searchParams;
|
||||
const granularity = (sp.get("granularity") || "day") as "day" | "week" | "month";
|
||||
const startTs = sp.get("start") ? Number(sp.get("start")) : undefined;
|
||||
const endTs = sp.get("end") ? Number(sp.get("end")) : undefined;
|
||||
|
||||
const data = await getTrends(granularity, startTs, endTs);
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
114
app/detail/[...slug]/page.tsx
Normal file
114
app/detail/[...slug]/page.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { motion } from "motion/react";
|
||||
import { ArrowLeft, Hash, Zap, MessageSquare } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { StatsCard } from "@/components/StatsCard";
|
||||
import { TimeRangeSelector } from "@/components/TimeRangeSelector";
|
||||
import { TrendChart } from "@/components/charts/TrendChart";
|
||||
import { type TimeRange, getTimeRange, buildQuery, formatNumber, formatTokens } from "@/lib/utils";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
interface DetailData {
|
||||
calls: number; prompt_tokens: number; completion_tokens: number;
|
||||
total_tokens: number; quota: number;
|
||||
models?: { name: string; calls: number; total_tokens: number; quota: number }[];
|
||||
users?: { name: string; calls: number; total_tokens: number; quota: number }[];
|
||||
channel_name?: string;
|
||||
}
|
||||
|
||||
export default function DetailPage() {
|
||||
const { t } = useI18n();
|
||||
const params = useParams();
|
||||
const segments = Array.isArray(params.slug) ? params.slug : [];
|
||||
const type = segments[0] || "";
|
||||
const id = segments[1] || "";
|
||||
const decodedId = decodeURIComponent(id);
|
||||
|
||||
const [range, setRange] = useState<TimeRange>("30d");
|
||||
const [data, setData] = useState<DetailData | null>(null);
|
||||
const [trends, setTrends] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const { start, end } = getTimeRange(range);
|
||||
const tp = { start, end };
|
||||
const [detail, tr] = await Promise.all([
|
||||
fetch(buildQuery(`/api/detail/${type}/${encodeURIComponent(decodedId)}`, tp)).then(r => r.json()),
|
||||
fetch(buildQuery("/api/trends", { ...tp, granularity: "day",
|
||||
...(type === "user" ? { username: decodedId } : {}),
|
||||
...(type === "model" ? { model: decodedId } : {}),
|
||||
...(type === "channel" ? { channel_id: decodedId } : {}),
|
||||
})).then(r => r.json()),
|
||||
]);
|
||||
setData(detail); setTrends(tr); setLoading(false);
|
||||
}, [range, type, decodedId]);
|
||||
|
||||
useEffect(() => { fetchData(); }, [fetchData]);
|
||||
|
||||
const title = type === "channel" ? (data?.channel_name || decodedId) : decodedId;
|
||||
const typeLabel = { user: t("detail.user"), model: t("detail.model"), channel: t("detail.channel") }[type] || type;
|
||||
const breakdownItems = data?.models || data?.users || [];
|
||||
const breakdownLabel = data?.models ? t("detail.modelDist") : t("detail.userDist");
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }}>
|
||||
<Link href="/rankings" className="inline-flex items-center gap-1 text-xs transition-colors mb-2" style={{ color: "var(--text-muted)" }}>
|
||||
<ArrowLeft className="h-3 w-3" /> {t("common.backToRankings")}
|
||||
</Link>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs uppercase tracking-wider px-2 py-0.5 rounded" style={{ color: "var(--text-muted)", background: "var(--btn-active-bg)", border: "1px solid var(--surface-border)" }}>{typeLabel}</span>
|
||||
<h1 className="text-2xl font-bold" style={{ color: "var(--text-primary)" }}>{title}</h1>
|
||||
</div>
|
||||
</motion.div>
|
||||
<TimeRangeSelector value={range} onChange={setRange} />
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex h-64 items-center justify-center"><div className="h-6 w-6 animate-spin rounded-full spinner" /></div>
|
||||
) : data ? (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-4 md:grid-cols-3">
|
||||
<StatsCard title={t("dash.totalCalls")} value={data.calls} icon={Hash} delay={0} />
|
||||
<StatsCard title={t("th.totalToken")} value={data.total_tokens} format="tokens" icon={Zap} delay={0.05} />
|
||||
<StatsCard title={t("th.input")} value={data.prompt_tokens} format="tokens" icon={MessageSquare} delay={0.1} />
|
||||
</div>
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }} className="glass p-5">
|
||||
<h2 className="mb-4 text-sm font-semibold" style={{ color: "var(--text-primary)" }}>{t("detail.trend")}</h2>
|
||||
<TrendChart data={trends} />
|
||||
</motion.div>
|
||||
|
||||
{breakdownItems.length > 0 && (
|
||||
<motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }} className="glass overflow-hidden">
|
||||
<h2 className="px-5 pt-5 text-xs font-medium uppercase tracking-widest" style={{ color: "var(--text-muted)" }}>{breakdownLabel}</h2>
|
||||
<table className="w-full text-sm mt-3">
|
||||
<thead>
|
||||
<tr style={{ borderBottom: "1px solid var(--surface-border)" }}>
|
||||
<th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>{t("th.name")}</th>
|
||||
<th className="px-5 py-3 text-right text-xs font-medium uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>{t("th.calls")}</th>
|
||||
<th className="px-5 py-3 text-right text-xs font-medium uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>{t("th.totalToken")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{breakdownItems.map((item) => (
|
||||
<tr key={item.name} className="row-glow transition-colors" style={{ borderBottom: "1px solid var(--surface-border)" }}>
|
||||
<td className="px-5 py-3" style={{ color: "var(--text-accent)", opacity: 0.8 }}>{item.name}</td>
|
||||
<td className="px-5 py-3 text-right tabular-nums font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-secondary)" }}>{formatNumber(item.calls)}</td>
|
||||
<td className="px-5 py-3 text-right tabular-nums font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-primary)" }}>{formatTokens(item.total_tokens)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</motion.div>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
BIN
app/favicon.ico
Normal file
BIN
app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
196
app/globals.css
Normal file
196
app/globals.css
Normal file
@@ -0,0 +1,196 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
/* ═══ DARK THEME ═══ */
|
||||
:root, [data-theme="dark"] {
|
||||
--background: #06080d;
|
||||
--foreground: #c8d6e5;
|
||||
--accent: #00e5ff;
|
||||
--accent-dim: #0097a7;
|
||||
--accent-purple: #7c4dff;
|
||||
--accent-pink: #ff4081;
|
||||
--surface: rgba(12, 18, 30, 0.7);
|
||||
--surface-border: rgba(0, 229, 255, 0.08);
|
||||
--surface-hover: rgba(0, 229, 255, 0.04);
|
||||
--text-primary: #ffffff;
|
||||
--text-secondary: #c8d6e5;
|
||||
--text-muted: #6b7280;
|
||||
--text-accent: #00e5ff;
|
||||
--text-accent-hover: #67edff;
|
||||
--glow-cyan: 0 0 20px rgba(0, 229, 255, 0.15);
|
||||
--grid-color: rgba(0, 229, 255, 0.03);
|
||||
--row-hover: rgba(0, 229, 255, 0.04);
|
||||
--input-bg: rgba(12, 18, 30, 0.6);
|
||||
--input-border: rgba(0, 229, 255, 0.1);
|
||||
--input-focus: rgba(0, 229, 255, 0.4);
|
||||
--chart-grid: rgba(0, 229, 255, 0.06);
|
||||
--btn-active-bg: rgba(0, 229, 255, 0.2);
|
||||
--btn-active-border: rgba(0, 229, 255, 0.5);
|
||||
--progress-bg: rgba(0, 229, 255, 0.08);
|
||||
--spinner-track: rgba(0, 229, 255, 0.3);
|
||||
--spinner-head: #00e5ff;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
/* ═══ LIGHT THEME ═══ */
|
||||
[data-theme="light"] {
|
||||
--background: #f7f8fc;
|
||||
--foreground: #1e293b;
|
||||
--accent: #0284c7;
|
||||
--accent-dim: #0369a1;
|
||||
--accent-purple: #7c3aed;
|
||||
--accent-pink: #db2777;
|
||||
--surface: rgba(255, 255, 255, 0.85);
|
||||
--surface-border: rgba(2, 132, 199, 0.12);
|
||||
--surface-hover: rgba(2, 132, 199, 0.04);
|
||||
--text-primary: #0f172a;
|
||||
--text-secondary: #475569;
|
||||
--text-muted: #94a3b8;
|
||||
--text-accent: #0284c7;
|
||||
--text-accent-hover: #0369a1;
|
||||
--glow-cyan: 0 4px 20px rgba(2, 132, 199, 0.08);
|
||||
--grid-color: rgba(2, 132, 199, 0.04);
|
||||
--row-hover: rgba(2, 132, 199, 0.05);
|
||||
--input-bg: rgba(255, 255, 255, 0.8);
|
||||
--input-border: rgba(2, 132, 199, 0.15);
|
||||
--input-focus: rgba(2, 132, 199, 0.4);
|
||||
--chart-grid: rgba(2, 132, 199, 0.08);
|
||||
--btn-active-bg: rgba(2, 132, 199, 0.12);
|
||||
--btn-active-border: rgba(2, 132, 199, 0.3);
|
||||
--progress-bg: rgba(2, 132, 199, 0.1);
|
||||
--spinner-track: rgba(2, 132, 199, 0.3);
|
||||
--spinner-head: #0284c7;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-sans), system-ui, sans-serif;
|
||||
transition: background 0.3s, color 0.3s;
|
||||
}
|
||||
|
||||
/* Grid background — dark only */
|
||||
[data-theme="dark"] body::before {
|
||||
content: '';
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
background-image:
|
||||
linear-gradient(var(--grid-color) 1px, transparent 1px),
|
||||
linear-gradient(90deg, var(--grid-color) 1px, transparent 1px);
|
||||
background-size: 60px 60px;
|
||||
mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, black 20%, transparent 100%);
|
||||
}
|
||||
|
||||
/* Top ambient glow — dark only */
|
||||
[data-theme="dark"] body::after {
|
||||
content: '';
|
||||
position: fixed;
|
||||
top: -200px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 800px;
|
||||
height: 500px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(ellipse, rgba(0, 229, 255, 0.06) 0%, transparent 70%);
|
||||
z-index: -1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Light theme subtle background */
|
||||
[data-theme="light"] body::before {
|
||||
content: '';
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
background: radial-gradient(ellipse at 50% 0%, rgba(2, 132, 199, 0.03) 0%, transparent 60%);
|
||||
}
|
||||
|
||||
/* Glass card */
|
||||
.glass {
|
||||
background: var(--surface);
|
||||
backdrop-filter: blur(16px);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 12px;
|
||||
transition: border-color 0.2s, background 0.3s;
|
||||
}
|
||||
.glass:hover {
|
||||
border-color: var(--input-border);
|
||||
}
|
||||
|
||||
/* Gradient heading */
|
||||
.gradient-text {
|
||||
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-purple) 50%, var(--accent-pink) 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
/* Table row glow on hover */
|
||||
.row-glow:hover {
|
||||
background: var(--row-hover);
|
||||
}
|
||||
|
||||
/* Accent button */
|
||||
.btn-accent {
|
||||
background: var(--btn-active-bg);
|
||||
border: 1px solid var(--surface-border);
|
||||
color: var(--text-accent);
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-accent:hover {
|
||||
border-color: var(--btn-active-border);
|
||||
box-shadow: var(--glow-cyan);
|
||||
}
|
||||
|
||||
/* Input style */
|
||||
.input-glass {
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--input-border);
|
||||
color: var(--foreground);
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
.input-glass::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.input-glass:focus {
|
||||
outline: none;
|
||||
border-color: var(--input-focus);
|
||||
box-shadow: 0 0 12px rgba(2, 132, 199, 0.1);
|
||||
}
|
||||
|
||||
/* Spinner */
|
||||
.spinner {
|
||||
border: 2px solid var(--spinner-track);
|
||||
border-top-color: var(--spinner-head);
|
||||
}
|
||||
|
||||
/* Themed text utility classes */
|
||||
.text-t-primary { color: var(--text-primary); }
|
||||
.text-t-secondary { color: var(--text-secondary); }
|
||||
.text-t-muted { color: var(--text-muted); }
|
||||
.text-t-accent { color: var(--text-accent); }
|
||||
.text-t-accent:hover { color: var(--text-accent-hover); }
|
||||
.border-t { border-color: var(--surface-border); }
|
||||
|
||||
/* Scrollbar */
|
||||
::-webkit-scrollbar { width: 6px; height: 6px; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
::-webkit-scrollbar-thumb { background: var(--surface-border); border-radius: 3px; }
|
||||
::-webkit-scrollbar-thumb:hover { background: var(--input-border); }
|
||||
|
||||
/* Recharts overrides */
|
||||
.recharts-cartesian-grid-horizontal line,
|
||||
.recharts-cartesian-grid-vertical line {
|
||||
stroke: var(--chart-grid) !important;
|
||||
}
|
||||
.recharts-text {
|
||||
fill: var(--text-muted) !important;
|
||||
}
|
||||
45
app/layout.tsx
Normal file
45
app/layout.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Outfit, JetBrains_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { ClientProviders } from "@/components/ClientProviders";
|
||||
|
||||
const outfit = Outfit({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
weight: ["300", "400", "500", "600", "700", "800"],
|
||||
});
|
||||
|
||||
const jetbrains = JetBrains_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "API Analytics — Neural Pulse",
|
||||
description: "Real-time API usage analytics dashboard",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="zh" className={`${outfit.variable} ${jetbrains.variable} h-full antialiased dark`} suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: `
|
||||
(function(){
|
||||
var t=localStorage.getItem('theme')||'system';
|
||||
var r=t==='system'?window.matchMedia('(prefers-color-scheme:dark)').matches?'dark':'light':t;
|
||||
document.documentElement.classList.add(r);
|
||||
document.documentElement.setAttribute('data-theme',r);
|
||||
})();
|
||||
`}} />
|
||||
</head>
|
||||
<body className="min-h-full">
|
||||
<ClientProviders>{children}</ClientProviders>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
113
app/logs/page.tsx
Normal file
113
app/logs/page.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { motion } from "motion/react";
|
||||
import { ScrollText, Search, ChevronLeft, ChevronRight, Zap } from "lucide-react";
|
||||
import { TimeRangeSelector } from "@/components/TimeRangeSelector";
|
||||
import { type TimeRange, getTimeRange, buildQuery, formatNumber, formatTokens, formatDate } from "@/lib/utils";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
interface LogEntry {
|
||||
id: number; created_at: string; display_name: string;
|
||||
real_model: string; channel_name: string; prompt_tokens: number;
|
||||
completion_tokens: number; total_tokens: number;
|
||||
use_time: number; is_stream: boolean;
|
||||
}
|
||||
|
||||
export default function LogsPage() {
|
||||
const { t } = useI18n();
|
||||
const [range, setRange] = useState<TimeRange>("7d");
|
||||
const [page, setPage] = useState(1);
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filters, setFilters] = useState({ username: "", model: "", token_name: "" });
|
||||
const pageSize = 100;
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const { start, end } = getTimeRange(range);
|
||||
const res = await fetch(buildQuery("/api/logs", { start, end, page, page_size: pageSize, ...filters }));
|
||||
const data = await res.json();
|
||||
setLogs(data.logs); setTotal(data.total); setLoading(false);
|
||||
}, [range, page, filters]);
|
||||
|
||||
useEffect(() => { fetchData(); }, [fetchData]);
|
||||
useEffect(() => { setPage(1); }, [range, filters]);
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
|
||||
const headers = [t("th.time"), t("th.user"), t("th.realModel"), t("th.channel"), t("th.input"), t("th.output"), t("th.totalToken"), t("th.latency"), ""];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} className="flex items-center gap-3">
|
||||
<ScrollText className="h-5 w-5" style={{ color: "var(--accent)", opacity: 0.6 }} />
|
||||
<h1 className="text-2xl font-bold gradient-text">{t("logs.title")}</h1>
|
||||
</motion.div>
|
||||
<TimeRangeSelector value={range} onChange={setRange} />
|
||||
</div>
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="flex items-center gap-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5" style={{ color: "var(--text-muted)" }} />
|
||||
<input type="text" placeholder={t("logs.filterUser")} value={filters.username}
|
||||
onChange={(e) => setFilters({ ...filters, username: e.target.value })}
|
||||
className="input-glass rounded-lg pl-9 pr-3 py-2 text-sm w-36" />
|
||||
</div>
|
||||
<input type="text" placeholder={t("logs.filterModel")} value={filters.model}
|
||||
onChange={(e) => setFilters({ ...filters, model: e.target.value })}
|
||||
className="input-glass rounded-lg px-3 py-2 text-sm w-36" />
|
||||
<input type="text" placeholder={t("logs.filterToken")} value={filters.token_name}
|
||||
onChange={(e) => setFilters({ ...filters, token_name: e.target.value })}
|
||||
className="input-glass rounded-lg px-3 py-2 text-sm w-36" />
|
||||
<span className="text-xs font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-muted)" }}>
|
||||
{formatNumber(total)} {t("common.records")}
|
||||
</span>
|
||||
</motion.div>
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="glass overflow-auto">
|
||||
<table className="w-full text-sm whitespace-nowrap">
|
||||
<thead>
|
||||
<tr style={{ borderBottom: "1px solid var(--surface-border)" }}>
|
||||
{headers.map((h, i) => (
|
||||
<th key={i} className={`px-3 py-3 text-xs font-medium uppercase tracking-wider ${i >= 4 ? "text-right" : "text-left"}`} style={{ color: "var(--text-muted)" }}>{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr><td colSpan={9} className="px-3 py-16 text-center"><div className="inline-block h-5 w-5 animate-spin rounded-full spinner" /></td></tr>
|
||||
) : logs.map((log) => (
|
||||
<tr key={log.id} className="row-glow transition-colors" style={{ borderBottom: "1px solid var(--surface-border)" }}>
|
||||
<td className="px-3 py-2.5 text-xs font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-muted)" }}>{formatDate(log.created_at)}</td>
|
||||
<td className="px-3 py-2.5" style={{ color: "var(--text-secondary)" }}>{log.display_name}</td>
|
||||
<td className="px-3 py-2.5 font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-accent)", opacity: 0.7 }}>{log.real_model}</td>
|
||||
<td className="px-3 py-2.5" style={{ color: "var(--text-muted)" }}>{log.channel_name}</td>
|
||||
<td className="px-3 py-2.5 text-right tabular-nums font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{formatNumber(log.prompt_tokens)}</td>
|
||||
<td className="px-3 py-2.5 text-right tabular-nums font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{formatNumber(log.completion_tokens)}</td>
|
||||
<td className="px-3 py-2.5 text-right tabular-nums font-medium font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-primary)" }}>{formatNumber(log.total_tokens)}</td>
|
||||
<td className="px-3 py-2.5 text-right tabular-nums text-xs" style={{ color: "var(--text-muted)" }}>{log.use_time}ms</td>
|
||||
<td className="px-3 py-2.5 text-center">{log.is_stream ? <Zap className="inline h-3 w-3 text-yellow-500/60" /> : ""}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</motion.div>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button onClick={() => setPage(Math.max(1, page - 1))} disabled={page === 1}
|
||||
className="btn-accent rounded-lg px-3 py-1.5 text-xs disabled:opacity-20 flex items-center gap-1">
|
||||
<ChevronLeft className="h-3 w-3" /> {t("common.prevPage")}
|
||||
</button>
|
||||
<span className="text-xs font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-muted)" }}>{page} / {totalPages}</span>
|
||||
<button onClick={() => setPage(Math.min(totalPages, page + 1))} disabled={page === totalPages}
|
||||
className="btn-accent rounded-lg px-3 py-1.5 text-xs disabled:opacity-20 flex items-center gap-1">
|
||||
{t("common.nextPage")} <ChevronRight className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
117
app/page.tsx
Normal file
117
app/page.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { motion } from "motion/react";
|
||||
import { Zap, Hash, Users, Cpu, TrendingUp, BarChart3 } from "lucide-react";
|
||||
import { StatsCard } from "@/components/StatsCard";
|
||||
import { TimeRangeSelector } from "@/components/TimeRangeSelector";
|
||||
import { TrendChart } from "@/components/charts/TrendChart";
|
||||
import { RankingBar } from "@/components/charts/RankingBar";
|
||||
import { type TimeRange, getTimeRange, buildQuery } from "@/lib/utils";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { t } = useI18n();
|
||||
const [range, setRange] = useState<TimeRange>("30d");
|
||||
const [granularity, setGranularity] = useState<"day" | "week" | "month">("day");
|
||||
const [trendMetric, setTrendMetric] = useState<"total_tokens" | "calls">("total_tokens");
|
||||
const [overview, setOverview] = useState<any>(null);
|
||||
const [trends, setTrends] = useState<any[]>([]);
|
||||
const [userRank, setUserRank] = useState<any[]>([]);
|
||||
const [modelRank, setModelRank] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const { start, end } = getTimeRange(range);
|
||||
const tp = { start, end };
|
||||
const [ov, tr, ur, mr] = await Promise.all([
|
||||
fetch(buildQuery("/api/overview", tp)).then(r => r.json()),
|
||||
fetch(buildQuery("/api/trends", { ...tp, granularity })).then(r => r.json()),
|
||||
fetch(buildQuery("/api/rankings", { ...tp, type: "user", limit: 10 })).then(r => r.json()),
|
||||
fetch(buildQuery("/api/rankings", { ...tp, type: "model", limit: 10 })).then(r => r.json()),
|
||||
]);
|
||||
setOverview(ov); setTrends(tr); setUserRank(ur); setModelRank(mr); setLoading(false);
|
||||
}, [range, granularity]);
|
||||
|
||||
useEffect(() => { fetchData(); }, [fetchData]);
|
||||
|
||||
const grans = [
|
||||
{ key: "day" as const, label: t("gran.day") },
|
||||
{ key: "week" as const, label: t("gran.week") },
|
||||
{ key: "month" as const, label: t("gran.month") },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<motion.h1 initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} className="text-2xl font-bold gradient-text">
|
||||
{t("dash.title")}
|
||||
</motion.h1>
|
||||
<TimeRangeSelector value={range} onChange={setRange} />
|
||||
</div>
|
||||
|
||||
{overview && (
|
||||
<div className="grid grid-cols-2 gap-4 md:grid-cols-4">
|
||||
<StatsCard title={t("dash.totalCalls")} value={overview.total_calls} icon={Hash} delay={0} />
|
||||
<StatsCard title={t("dash.tokenUsage")} value={overview.total_tokens} format="tokens" icon={Zap} delay={0.05} />
|
||||
<StatsCard title={t("dash.activeUsers")} value={overview.active_users} icon={Users} delay={0.1} />
|
||||
<StatsCard title={t("dash.activeModels")} value={overview.active_models} icon={Cpu} delay={0.15} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }} className="glass p-5">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<TrendingUp className="h-4 w-4" style={{ color: "var(--accent)", opacity: 0.6 }} />
|
||||
<h2 className="text-sm font-semibold" style={{ color: "var(--text-primary)" }}>{t("dash.trend")}</h2>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<div className="flex gap-1 rounded-md p-0.5" style={{ background: "var(--row-hover)", border: "1px solid var(--surface-border)" }}>
|
||||
{grans.map(g => (
|
||||
<button key={g.key} onClick={() => setGranularity(g.key)}
|
||||
className="px-2.5 py-1 text-xs rounded transition-colors"
|
||||
style={{
|
||||
background: granularity === g.key ? "var(--btn-active-bg)" : "transparent",
|
||||
color: granularity === g.key ? "var(--text-accent)" : "var(--text-muted)",
|
||||
border: granularity === g.key ? "1px solid var(--surface-border)" : "1px solid transparent",
|
||||
}}
|
||||
>{g.label}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex gap-1 rounded-md p-0.5" style={{ background: "var(--row-hover)", border: "1px solid var(--surface-border)" }}>
|
||||
{([["total_tokens", t("metric.token")], ["calls", t("metric.calls")]] as const).map(([k, l]) => (
|
||||
<button key={k} onClick={() => setTrendMetric(k as any)}
|
||||
className="px-2.5 py-1 text-xs rounded transition-colors"
|
||||
style={{
|
||||
background: trendMetric === k ? "var(--btn-active-bg)" : "transparent",
|
||||
color: trendMetric === k ? "var(--text-accent)" : "var(--text-muted)",
|
||||
border: trendMetric === k ? "1px solid var(--surface-border)" : "1px solid transparent",
|
||||
}}
|
||||
>{l}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{loading ? (
|
||||
<div className="flex h-64 items-center justify-center">
|
||||
<div className="h-5 w-5 animate-spin rounded-full spinner" />
|
||||
</div>
|
||||
) : (
|
||||
<TrendChart data={trends} metric={trendMetric} />
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.25 }} className="glass p-5">
|
||||
<BarChart3 className="h-4 w-4 mb-1" style={{ color: "var(--accent)", opacity: 0.6 }} />
|
||||
<RankingBar data={userRank} title={t("dash.userTop10")} />
|
||||
</motion.div>
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }} className="glass p-5">
|
||||
<BarChart3 className="h-4 w-4 mb-1" style={{ color: "var(--accent-purple)", opacity: 0.6 }} />
|
||||
<RankingBar data={modelRank} title={t("dash.modelTop10")} />
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
109
app/rankings/page.tsx
Normal file
109
app/rankings/page.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import { motion } from "motion/react";
|
||||
import { Trophy, Users, Cpu, Radio } from "lucide-react";
|
||||
import { TimeRangeSelector } from "@/components/TimeRangeSelector";
|
||||
import { type TimeRange, getTimeRange, buildQuery, formatNumber, formatTokens } from "@/lib/utils";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
type Tab = "user" | "model" | "channel";
|
||||
|
||||
interface RankItem {
|
||||
rank: number; name: string; id?: number; calls: number;
|
||||
prompt_tokens: number; completion_tokens: number; total_tokens: number;
|
||||
}
|
||||
|
||||
export default function RankingsPage() {
|
||||
const { t } = useI18n();
|
||||
const [range, setRange] = useState<TimeRange>("30d");
|
||||
const [tab, setTab] = useState<Tab>("user");
|
||||
const [data, setData] = useState<RankItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const tabConfig: Record<Tab, { label: string; icon: typeof Users }> = {
|
||||
user: { label: t("rank.user"), icon: Users },
|
||||
model: { label: t("rank.model"), icon: Cpu },
|
||||
channel: { label: t("rank.channel"), icon: Radio },
|
||||
};
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const { start, end } = getTimeRange(range);
|
||||
const res = await fetch(buildQuery("/api/rankings", { start, end, type: tab, limit: 100 }));
|
||||
setData(await res.json());
|
||||
setLoading(false);
|
||||
}, [range, tab]);
|
||||
|
||||
useEffect(() => { fetchData(); }, [fetchData]);
|
||||
|
||||
function detailHref(item: RankItem): string {
|
||||
if (tab === "channel") return `/detail/channel/${item.id}`;
|
||||
if (tab === "model") return `/detail/model/${encodeURIComponent(item.name)}`;
|
||||
return `/detail/user/${encodeURIComponent(item.name)}`;
|
||||
}
|
||||
|
||||
const headers = [t("th.rank"), t("th.name"), t("th.calls"), t("th.input"), t("th.output"), t("th.totalToken")];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} className="flex items-center gap-3">
|
||||
<Trophy className="h-5 w-5" style={{ color: "var(--accent)", opacity: 0.6 }} />
|
||||
<h1 className="text-2xl font-bold gradient-text">{t("rank.title")}</h1>
|
||||
</motion.div>
|
||||
<TimeRangeSelector value={range} onChange={setRange} />
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 rounded-lg p-1 w-fit" style={{ background: "var(--row-hover)", border: "1px solid var(--surface-border)" }}>
|
||||
{(Object.keys(tabConfig) as Tab[]).map((key) => {
|
||||
const Icon = tabConfig[key].icon;
|
||||
return (
|
||||
<button key={key} onClick={() => setTab(key)}
|
||||
className="relative flex items-center gap-2 px-4 py-2 text-xs font-medium rounded-md transition-colors"
|
||||
style={{ color: tab === key ? "var(--text-accent)" : "var(--text-muted)" }}
|
||||
>
|
||||
{tab === key && (
|
||||
<motion.div layoutId="tab-bg" className="absolute inset-0 rounded-md"
|
||||
style={{ background: "var(--btn-active-bg)", border: "1px solid var(--surface-border)" }}
|
||||
transition={{ type: "spring", stiffness: 400, damping: 30 }} />
|
||||
)}
|
||||
<Icon className="relative z-10 h-3.5 w-3.5" />
|
||||
<span className="relative z-10">{tabConfig[key].label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} className="glass overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr style={{ borderBottom: "1px solid var(--surface-border)" }}>
|
||||
{headers.map((h, i) => (
|
||||
<th key={h} className={`px-4 py-3 text-xs font-medium uppercase tracking-wider ${i >= 2 ? "text-right" : "text-left"}`} style={{ color: "var(--text-muted)" }}>{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr><td colSpan={6} className="px-4 py-16 text-center"><div className="inline-block h-5 w-5 animate-spin rounded-full spinner" /></td></tr>
|
||||
) : data.map((item, i) => (
|
||||
<motion.tr key={item.rank} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: i * 0.02 }}
|
||||
className="row-glow transition-colors" style={{ borderBottom: "1px solid var(--surface-border)", borderBottomWidth: "1px", opacity: 0.01 }}>
|
||||
<td className="px-4 py-3 font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{item.rank}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Link href={detailHref(item)} className="transition-colors" style={{ color: "var(--text-accent)" }}>{item.name}</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums" style={{ color: "var(--text-secondary)" }}>{formatNumber(item.calls)}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{formatTokens(item.prompt_tokens)}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-[family-name:var(--font-geist-mono)] text-xs" style={{ color: "var(--text-muted)" }}>{formatTokens(item.completion_tokens)}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-medium font-[family-name:var(--font-geist-mono)]" style={{ color: "var(--text-primary)" }}>{formatTokens(item.total_tokens)}</td>
|
||||
</motion.tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user