feat: 管理后台数据看板
新增 /admin/dashboard 页面,提供充值订单统计与分析: - 汇总统计卡片(今日/累计充值金额、订单数、成功率、平均充值) - 每日充值趋势折线图(recharts,支持 7/30/90 天切换) - 充值排行榜(Top 10 用户) - 支付方式分布(水平条形图) - 与 /admin 订单管理页面互相导航 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
155
src/app/admin/dashboard/page.tsx
Normal file
155
src/app/admin/dashboard/page.tsx
Normal file
@@ -0,0 +1,155 @@
|
||||
'use client';
|
||||
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useState, useEffect, useCallback, Suspense } from 'react';
|
||||
import PayPageLayout from '@/components/PayPageLayout';
|
||||
import DashboardStats from '@/components/admin/DashboardStats';
|
||||
import DailyChart from '@/components/admin/DailyChart';
|
||||
import Leaderboard from '@/components/admin/Leaderboard';
|
||||
import PaymentMethodChart from '@/components/admin/PaymentMethodChart';
|
||||
|
||||
interface DashboardData {
|
||||
summary: {
|
||||
today: { amount: number; orderCount: number; paidCount: number };
|
||||
total: { amount: number; orderCount: number; paidCount: number };
|
||||
successRate: number;
|
||||
avgAmount: number;
|
||||
};
|
||||
dailySeries: { date: string; amount: number; count: number }[];
|
||||
leaderboard: { userId: number; userName: string | null; userEmail: string | null; totalAmount: number; orderCount: number }[];
|
||||
paymentMethods: { paymentType: string; amount: number; count: number; percentage: number }[];
|
||||
meta: { days: number; generatedAt: string };
|
||||
}
|
||||
|
||||
const DAYS_OPTIONS = [7, 30, 90] as const;
|
||||
|
||||
function DashboardContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams.get('token');
|
||||
const theme = searchParams.get('theme') === 'dark' ? 'dark' : 'light';
|
||||
const uiMode = searchParams.get('ui_mode') || 'standalone';
|
||||
const isDark = theme === 'dark';
|
||||
const isEmbedded = uiMode === 'embedded';
|
||||
|
||||
const [days, setDays] = useState<number>(30);
|
||||
const [data, setData] = useState<DashboardData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!token) return;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await fetch(`/api/admin/dashboard?token=${encodeURIComponent(token)}&days=${days}`);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
setError('管理员凭证无效');
|
||||
return;
|
||||
}
|
||||
throw new Error('请求失败');
|
||||
}
|
||||
setData(await res.json());
|
||||
} catch {
|
||||
setError('加载数据失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [token, days]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
if (!token) {
|
||||
return (
|
||||
<div className={`flex min-h-screen items-center justify-center p-4 ${isDark ? 'bg-slate-950' : 'bg-slate-50'}`}>
|
||||
<div className="text-center text-red-500">
|
||||
<p className="text-lg font-medium">缺少管理员凭证</p>
|
||||
<p className="mt-2 text-sm text-gray-500">请从 Sub2API 平台正确访问管理页面</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const navParams = new URLSearchParams();
|
||||
navParams.set('token', token);
|
||||
if (theme === 'dark') navParams.set('theme', 'dark');
|
||||
if (isEmbedded) navParams.set('ui_mode', 'embedded');
|
||||
|
||||
const btnBase = [
|
||||
'inline-flex items-center rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors',
|
||||
isDark ? 'border-slate-600 text-slate-200 hover:bg-slate-800' : 'border-slate-300 text-slate-700 hover:bg-slate-100',
|
||||
].join(' ');
|
||||
|
||||
const btnActive = [
|
||||
'inline-flex items-center rounded-lg px-3 py-1.5 text-xs font-medium',
|
||||
isDark ? 'bg-indigo-500/30 text-indigo-200 ring-1 ring-indigo-400/40' : 'bg-blue-600 text-white',
|
||||
].join(' ');
|
||||
|
||||
return (
|
||||
<PayPageLayout
|
||||
isDark={isDark}
|
||||
isEmbedded={isEmbedded}
|
||||
maxWidth="full"
|
||||
title="数据概览"
|
||||
subtitle="充值订单统计与分析"
|
||||
actions={
|
||||
<>
|
||||
{DAYS_OPTIONS.map((d) => (
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
onClick={() => setDays(d)}
|
||||
className={days === d ? btnActive : btnBase}
|
||||
>
|
||||
{d}天
|
||||
</button>
|
||||
))}
|
||||
<a href={`/admin?${navParams}`} className={btnBase}>
|
||||
订单管理
|
||||
</a>
|
||||
<button type="button" onClick={fetchData} className={btnBase}>
|
||||
刷新
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{error && (
|
||||
<div className={`mb-4 rounded-lg border p-3 text-sm ${isDark ? 'border-red-800 bg-red-950/50 text-red-400' : 'border-red-200 bg-red-50 text-red-600'}`}>
|
||||
{error}
|
||||
<button onClick={() => setError('')} className="ml-2 opacity-60 hover:opacity-100">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className={`py-24 text-center ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>加载中...</div>
|
||||
) : data ? (
|
||||
<div className="space-y-6">
|
||||
<DashboardStats summary={data.summary} dark={isDark} />
|
||||
<DailyChart data={data.dailySeries} dark={isDark} />
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Leaderboard data={data.leaderboard} dark={isDark} />
|
||||
<PaymentMethodChart data={data.paymentMethods} dark={isDark} />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</PayPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-gray-500">加载中...</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<DashboardContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -162,6 +162,16 @@ function AdminContent() {
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
const navParams = new URLSearchParams();
|
||||
if (token) navParams.set('token', token);
|
||||
if (isDark) navParams.set('theme', 'dark');
|
||||
if (isEmbedded) navParams.set('ui_mode', 'embedded');
|
||||
|
||||
const btnBase = [
|
||||
'inline-flex items-center rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors',
|
||||
isDark ? 'border-slate-600 text-slate-200 hover:bg-slate-800' : 'border-slate-300 text-slate-700 hover:bg-slate-100',
|
||||
].join(' ');
|
||||
|
||||
return (
|
||||
<PayPageLayout
|
||||
isDark={isDark}
|
||||
@@ -170,16 +180,14 @@ function AdminContent() {
|
||||
title="订单管理"
|
||||
subtitle="查看和管理所有充值订单"
|
||||
actions={
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchOrders}
|
||||
className={[
|
||||
'inline-flex items-center rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors',
|
||||
isDark ? 'border-slate-600 text-slate-200 hover:bg-slate-800' : 'border-slate-300 text-slate-700 hover:bg-slate-100',
|
||||
].join(' ')}
|
||||
>
|
||||
刷新
|
||||
</button>
|
||||
<>
|
||||
<a href={`/admin/dashboard?${navParams}`} className={btnBase}>
|
||||
数据概览
|
||||
</a>
|
||||
<button type="button" onClick={fetchOrders} className={btnBase}>
|
||||
刷新
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{error && (
|
||||
|
||||
139
src/app/api/admin/dashboard/route.ts
Normal file
139
src/app/api/admin/dashboard/route.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
|
||||
import { OrderStatus } from '@prisma/client';
|
||||
|
||||
/** 格式化 Date 为 YYYY-MM-DD(使用本地时区,与 PostgreSQL DATE() 一致) */
|
||||
function toDateStr(d: Date): string {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
if (!(await verifyAdminToken(request))) return unauthorizedResponse();
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const days = Math.min(365, Math.max(1, Number(searchParams.get('days') || '30')));
|
||||
|
||||
const now = new Date();
|
||||
const startDate = new Date(now);
|
||||
startDate.setDate(startDate.getDate() - days);
|
||||
startDate.setHours(0, 0, 0, 0);
|
||||
|
||||
const todayStart = new Date(now);
|
||||
todayStart.setHours(0, 0, 0, 0);
|
||||
|
||||
const paidStatuses: OrderStatus[] = [
|
||||
OrderStatus.PAID,
|
||||
OrderStatus.RECHARGING,
|
||||
OrderStatus.COMPLETED,
|
||||
OrderStatus.REFUNDING,
|
||||
OrderStatus.REFUNDED,
|
||||
OrderStatus.REFUND_FAILED,
|
||||
];
|
||||
|
||||
const [todayStats, totalStats, todayOrders, totalOrders, dailyRaw, leaderboardRaw, paymentMethodStats] =
|
||||
await Promise.all([
|
||||
// Today paid aggregate
|
||||
prisma.order.aggregate({
|
||||
where: { status: { in: paidStatuses }, paidAt: { gte: todayStart } },
|
||||
_sum: { amount: true },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
// Total paid aggregate
|
||||
prisma.order.aggregate({
|
||||
where: { status: { in: paidStatuses } },
|
||||
_sum: { amount: true },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
// Today total orders
|
||||
prisma.order.count({ where: { createdAt: { gte: todayStart } } }),
|
||||
// Total orders
|
||||
prisma.order.count(),
|
||||
// Daily series (raw query for DATE truncation)
|
||||
prisma.$queryRaw<{ date: string; amount: string; count: bigint }[]>`
|
||||
SELECT DATE(paid_at) as date, SUM(amount)::text as amount, COUNT(*) as count
|
||||
FROM orders
|
||||
WHERE status IN ('PAID', 'RECHARGING', 'COMPLETED', 'REFUNDING', 'REFUNDED', 'REFUND_FAILED')
|
||||
AND paid_at >= ${startDate}
|
||||
GROUP BY DATE(paid_at)
|
||||
ORDER BY date
|
||||
`,
|
||||
// Leaderboard: GROUP BY user_id only, MAX() for name/email to avoid splitting rows on name changes
|
||||
prisma.$queryRaw<
|
||||
{ user_id: number; user_name: string | null; user_email: string | null; total_amount: string; order_count: bigint }[]
|
||||
>`
|
||||
SELECT user_id, MAX(user_name) as user_name, MAX(user_email) as user_email,
|
||||
SUM(amount)::text as total_amount, COUNT(*) as order_count
|
||||
FROM orders
|
||||
WHERE status IN ('PAID', 'RECHARGING', 'COMPLETED', 'REFUNDING', 'REFUNDED', 'REFUND_FAILED')
|
||||
AND paid_at >= ${startDate}
|
||||
GROUP BY user_id
|
||||
ORDER BY SUM(amount) DESC
|
||||
LIMIT 10
|
||||
`,
|
||||
// Payment method distribution (within time range)
|
||||
prisma.order.groupBy({
|
||||
by: ['paymentType'],
|
||||
where: { status: { in: paidStatuses }, paidAt: { gte: startDate } },
|
||||
_sum: { amount: true },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
// Fill missing dates for continuous line chart (use local timezone consistently)
|
||||
const dailyMap = new Map<string, { amount: number; count: number }>();
|
||||
for (const row of dailyRaw) {
|
||||
const dateStr = typeof row.date === 'string' ? row.date : toDateStr(new Date(row.date));
|
||||
dailyMap.set(dateStr, { amount: Number(row.amount), count: Number(row.count) });
|
||||
}
|
||||
|
||||
const dailySeries: { date: string; amount: number; count: number }[] = [];
|
||||
const cursor = new Date(startDate);
|
||||
while (cursor <= now) {
|
||||
const dateStr = toDateStr(cursor);
|
||||
const entry = dailyMap.get(dateStr);
|
||||
dailySeries.push({ date: dateStr, amount: entry?.amount ?? 0, count: entry?.count ?? 0 });
|
||||
cursor.setDate(cursor.getDate() + 1);
|
||||
}
|
||||
|
||||
// Calculate summary
|
||||
const todayPaidAmount = Number(todayStats._sum?.amount || 0);
|
||||
const todayPaidCount = todayStats._count._all;
|
||||
const totalPaidAmount = Number(totalStats._sum?.amount || 0);
|
||||
const totalPaidCount = totalStats._count._all;
|
||||
const successRate = totalOrders > 0 ? (totalPaidCount / totalOrders) * 100 : 0;
|
||||
const avgAmount = totalPaidCount > 0 ? totalPaidAmount / totalPaidCount : 0;
|
||||
|
||||
// Payment method total for percentage calc
|
||||
const paymentTotal = paymentMethodStats.reduce((sum, m) => sum + Number(m._sum?.amount || 0), 0);
|
||||
|
||||
return NextResponse.json({
|
||||
summary: {
|
||||
today: { amount: todayPaidAmount, orderCount: todayOrders, paidCount: todayPaidCount },
|
||||
total: { amount: totalPaidAmount, orderCount: totalOrders, paidCount: totalPaidCount },
|
||||
successRate: Math.round(successRate * 10) / 10,
|
||||
avgAmount: Math.round(avgAmount * 100) / 100,
|
||||
},
|
||||
dailySeries,
|
||||
leaderboard: leaderboardRaw.map((row) => ({
|
||||
userId: row.user_id,
|
||||
userName: row.user_name,
|
||||
userEmail: row.user_email,
|
||||
totalAmount: Number(row.total_amount),
|
||||
orderCount: Number(row.order_count),
|
||||
})),
|
||||
paymentMethods: paymentMethodStats.map((m) => {
|
||||
const amount = Number(m._sum?.amount || 0);
|
||||
return {
|
||||
paymentType: m.paymentType,
|
||||
amount,
|
||||
count: m._count._all,
|
||||
percentage: paymentTotal > 0 ? Math.round((amount / paymentTotal) * 1000) / 10 : 0,
|
||||
};
|
||||
}),
|
||||
meta: { days, generatedAt: now.toISOString() },
|
||||
});
|
||||
}
|
||||
110
src/components/admin/DailyChart.tsx
Normal file
110
src/components/admin/DailyChart.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
'use client';
|
||||
|
||||
import { ResponsiveContainer, LineChart, Line, XAxis, YAxis, Tooltip, CartesianGrid } from 'recharts';
|
||||
|
||||
interface DailyData {
|
||||
date: string;
|
||||
amount: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface DailyChartProps {
|
||||
data: DailyData[];
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string) {
|
||||
const [, m, d] = dateStr.split('-');
|
||||
return `${m}/${d}`;
|
||||
}
|
||||
|
||||
function formatAmount(value: number) {
|
||||
if (value >= 10000) return `¥${(value / 10000).toFixed(1)}w`;
|
||||
if (value >= 1000) return `¥${(value / 1000).toFixed(1)}k`;
|
||||
return `¥${value}`;
|
||||
}
|
||||
|
||||
interface TooltipPayload {
|
||||
value: number;
|
||||
dataKey: string;
|
||||
}
|
||||
|
||||
function CustomTooltip({
|
||||
active,
|
||||
payload,
|
||||
label,
|
||||
dark,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: TooltipPayload[];
|
||||
label?: string;
|
||||
dark?: boolean;
|
||||
}) {
|
||||
if (!active || !payload?.length) return null;
|
||||
return (
|
||||
<div
|
||||
className={[
|
||||
'rounded-lg border px-3 py-2 text-sm shadow-lg',
|
||||
dark ? 'border-slate-600 bg-slate-800 text-slate-200' : 'border-slate-200 bg-white text-slate-800',
|
||||
].join(' ')}
|
||||
>
|
||||
<p className={['mb-1 text-xs', dark ? 'text-slate-400' : 'text-slate-500'].join(' ')}>{label}</p>
|
||||
{payload.map((p) => (
|
||||
<p key={p.dataKey}>
|
||||
{p.dataKey === 'amount' ? '金额' : '笔数'}: {p.dataKey === 'amount' ? `¥${p.value.toLocaleString()}` : p.value}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DailyChart({ data, dark }: DailyChartProps) {
|
||||
// Auto-calculate tick interval: show ~10-15 labels max
|
||||
const tickInterval = data.length > 30 ? Math.ceil(data.length / 12) - 1 : 0;
|
||||
if (data.length === 0) {
|
||||
return (
|
||||
<div className={['rounded-xl border p-6', dark ? 'border-slate-700 bg-slate-800/60' : 'border-slate-200 bg-white shadow-sm'].join(' ')}>
|
||||
<h3 className={['mb-4 text-sm font-semibold', dark ? 'text-slate-200' : 'text-slate-800'].join(' ')}>每日充值趋势</h3>
|
||||
<p className={['text-center text-sm py-16', dark ? 'text-slate-500' : 'text-gray-400'].join(' ')}>暂无数据</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const axisColor = dark ? '#64748b' : '#94a3b8';
|
||||
const gridColor = dark ? '#334155' : '#e2e8f0';
|
||||
|
||||
return (
|
||||
<div className={['rounded-xl border p-6', dark ? 'border-slate-700 bg-slate-800/60' : 'border-slate-200 bg-white shadow-sm'].join(' ')}>
|
||||
<h3 className={['mb-4 text-sm font-semibold', dark ? 'text-slate-200' : 'text-slate-800'].join(' ')}>每日充值趋势</h3>
|
||||
<ResponsiveContainer width="100%" height={320}>
|
||||
<LineChart data={data} margin={{ top: 5, right: 20, bottom: 5, left: 10 }}>
|
||||
<CartesianGrid stroke={gridColor} strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={formatDate}
|
||||
tick={{ fill: axisColor, fontSize: 12 }}
|
||||
axisLine={{ stroke: gridColor }}
|
||||
tickLine={false}
|
||||
interval={tickInterval}
|
||||
/>
|
||||
<YAxis
|
||||
tickFormatter={formatAmount}
|
||||
tick={{ fill: axisColor, fontSize: 12 }}
|
||||
axisLine={{ stroke: gridColor }}
|
||||
tickLine={false}
|
||||
width={60}
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip dark={dark} />} />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="amount"
|
||||
stroke={dark ? '#818cf8' : '#4f46e5'}
|
||||
strokeWidth={2}
|
||||
dot={{ r: 3, fill: dark ? '#818cf8' : '#4f46e5' }}
|
||||
activeDot={{ r: 5 }}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
src/components/admin/DashboardStats.tsx
Normal file
58
src/components/admin/DashboardStats.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'use client';
|
||||
|
||||
interface Summary {
|
||||
today: { amount: number; orderCount: number; paidCount: number };
|
||||
total: { amount: number; orderCount: number; paidCount: number };
|
||||
successRate: number;
|
||||
avgAmount: number;
|
||||
}
|
||||
|
||||
interface DashboardStatsProps {
|
||||
summary: Summary;
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
export default function DashboardStats({ summary, dark }: DashboardStatsProps) {
|
||||
const cards = [
|
||||
{ label: '今日充值', value: `¥${summary.today.amount.toLocaleString()}`, accent: true },
|
||||
{ label: '今日订单', value: `${summary.today.paidCount}/${summary.today.orderCount}` },
|
||||
{ label: '累计充值', value: `¥${summary.total.amount.toLocaleString()}`, accent: true },
|
||||
{ label: '累计订单', value: String(summary.total.paidCount) },
|
||||
{ label: '成功率', value: `${summary.successRate}%` },
|
||||
{ label: '平均充值', value: `¥${summary.avgAmount.toFixed(2)}` },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
|
||||
{cards.map((card) => (
|
||||
<div
|
||||
key={card.label}
|
||||
className={[
|
||||
'rounded-xl border p-4',
|
||||
dark
|
||||
? 'border-slate-700 bg-slate-800/60'
|
||||
: 'border-slate-200 bg-white shadow-sm',
|
||||
].join(' ')}
|
||||
>
|
||||
<p className={['text-xs font-medium', dark ? 'text-slate-400' : 'text-slate-500'].join(' ')}>
|
||||
{card.label}
|
||||
</p>
|
||||
<p
|
||||
className={[
|
||||
'mt-1 text-xl font-semibold tracking-tight',
|
||||
card.accent
|
||||
? dark
|
||||
? 'text-indigo-400'
|
||||
: 'text-indigo-600'
|
||||
: dark
|
||||
? 'text-slate-100'
|
||||
: 'text-slate-900',
|
||||
].join(' ')}
|
||||
>
|
||||
{card.value}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
src/components/admin/Leaderboard.tsx
Normal file
86
src/components/admin/Leaderboard.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
'use client';
|
||||
|
||||
interface LeaderboardEntry {
|
||||
userId: number;
|
||||
userName: string | null;
|
||||
userEmail: string | null;
|
||||
totalAmount: number;
|
||||
orderCount: number;
|
||||
}
|
||||
|
||||
interface LeaderboardProps {
|
||||
data: LeaderboardEntry[];
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
const RANK_STYLES: Record<number, { light: string; dark: string }> = {
|
||||
1: { light: 'bg-amber-100 text-amber-700', dark: 'bg-amber-500/20 text-amber-300' },
|
||||
2: { light: 'bg-slate-200 text-slate-600', dark: 'bg-slate-500/20 text-slate-300' },
|
||||
3: { light: 'bg-orange-100 text-orange-700', dark: 'bg-orange-500/20 text-orange-300' },
|
||||
};
|
||||
|
||||
export default function Leaderboard({ data, dark }: LeaderboardProps) {
|
||||
const thCls = `px-4 py-3 text-left text-xs font-medium uppercase ${dark ? 'text-slate-400' : 'text-gray-500'}`;
|
||||
const tdCls = `whitespace-nowrap px-4 py-3 text-sm ${dark ? 'text-slate-300' : 'text-slate-700'}`;
|
||||
const tdMuted = `whitespace-nowrap px-4 py-3 text-sm ${dark ? 'text-slate-400' : 'text-gray-500'}`;
|
||||
|
||||
if (data.length === 0) {
|
||||
return (
|
||||
<div className={['rounded-xl border p-6', dark ? 'border-slate-700 bg-slate-800/60' : 'border-slate-200 bg-white shadow-sm'].join(' ')}>
|
||||
<h3 className={['mb-4 text-sm font-semibold', dark ? 'text-slate-200' : 'text-slate-800'].join(' ')}>充值排行榜 (Top 10)</h3>
|
||||
<p className={['text-center text-sm py-8', dark ? 'text-slate-500' : 'text-gray-400'].join(' ')}>暂无数据</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={['rounded-xl border', dark ? 'border-slate-700 bg-slate-800/60' : 'border-slate-200 bg-white shadow-sm'].join(' ')}>
|
||||
<h3 className={['px-6 pt-5 pb-2 text-sm font-semibold', dark ? 'text-slate-200' : 'text-slate-800'].join(' ')}>
|
||||
充值排行榜 (Top 10)
|
||||
</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<table className={`min-w-full divide-y ${dark ? 'divide-slate-700' : 'divide-gray-200'}`}>
|
||||
<thead className={dark ? 'bg-slate-800/50' : 'bg-gray-50'}>
|
||||
<tr>
|
||||
<th className={thCls}>#</th>
|
||||
<th className={thCls}>用户</th>
|
||||
<th className={thCls}>累计金额</th>
|
||||
<th className={thCls}>订单数</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className={`divide-y ${dark ? 'divide-slate-700/60' : 'divide-gray-200'}`}>
|
||||
{data.map((entry, i) => {
|
||||
const rank = i + 1;
|
||||
const rankStyle = RANK_STYLES[rank];
|
||||
return (
|
||||
<tr key={entry.userId} className={dark ? 'hover:bg-slate-700/40' : 'hover:bg-gray-50'}>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm">
|
||||
{rankStyle ? (
|
||||
<span className={`inline-flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold ${dark ? rankStyle.dark : rankStyle.light}`}>
|
||||
{rank}
|
||||
</span>
|
||||
) : (
|
||||
<span className={dark ? 'text-slate-500' : 'text-gray-400'}>{rank}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={tdCls}>
|
||||
<div>{entry.userName || `#${entry.userId}`}</div>
|
||||
{entry.userEmail && (
|
||||
<div className={['text-xs', dark ? 'text-slate-500' : 'text-gray-400'].join(' ')}>
|
||||
{entry.userEmail}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className={`whitespace-nowrap px-4 py-3 text-sm font-medium ${dark ? 'text-slate-200' : 'text-slate-900'}`}>
|
||||
¥{entry.totalAmount.toLocaleString()}
|
||||
</td>
|
||||
<td className={tdMuted}>{entry.orderCount}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
61
src/components/admin/PaymentMethodChart.tsx
Normal file
61
src/components/admin/PaymentMethodChart.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
'use client';
|
||||
|
||||
interface PaymentMethod {
|
||||
paymentType: string;
|
||||
amount: number;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
interface PaymentMethodChartProps {
|
||||
data: PaymentMethod[];
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
const TYPE_CONFIG: Record<string, { label: string; light: string; dark: string }> = {
|
||||
alipay: { label: '支付宝', light: 'bg-blue-500', dark: 'bg-blue-400' },
|
||||
wechat: { label: '微信支付', light: 'bg-green-500', dark: 'bg-green-400' },
|
||||
stripe: { label: 'Stripe', light: 'bg-purple-500', dark: 'bg-purple-400' },
|
||||
};
|
||||
|
||||
export default function PaymentMethodChart({ data, dark }: PaymentMethodChartProps) {
|
||||
if (data.length === 0) {
|
||||
return (
|
||||
<div className={['rounded-xl border p-6', dark ? 'border-slate-700 bg-slate-800/60' : 'border-slate-200 bg-white shadow-sm'].join(' ')}>
|
||||
<h3 className={['mb-4 text-sm font-semibold', dark ? 'text-slate-200' : 'text-slate-800'].join(' ')}>支付方式分布</h3>
|
||||
<p className={['text-center text-sm py-8', dark ? 'text-slate-500' : 'text-gray-400'].join(' ')}>暂无数据</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={['rounded-xl border p-6', dark ? 'border-slate-700 bg-slate-800/60' : 'border-slate-200 bg-white shadow-sm'].join(' ')}>
|
||||
<h3 className={['mb-4 text-sm font-semibold', dark ? 'text-slate-200' : 'text-slate-800'].join(' ')}>支付方式分布</h3>
|
||||
<div className="space-y-4">
|
||||
{data.map((method) => {
|
||||
const config = TYPE_CONFIG[method.paymentType] || {
|
||||
label: method.paymentType,
|
||||
light: 'bg-gray-500',
|
||||
dark: 'bg-gray-400',
|
||||
};
|
||||
return (
|
||||
<div key={method.paymentType}>
|
||||
<div className="mb-1.5 flex items-center justify-between text-sm">
|
||||
<span className={dark ? 'text-slate-300' : 'text-slate-700'}>{config.label}</span>
|
||||
<span className={dark ? 'text-slate-400' : 'text-slate-500'}>
|
||||
¥{method.amount.toLocaleString()} · {method.percentage}%
|
||||
</span>
|
||||
</div>
|
||||
<div className={['h-3 w-full overflow-hidden rounded-full', dark ? 'bg-slate-700' : 'bg-slate-100'].join(' ')}>
|
||||
<div
|
||||
className={['h-full rounded-full transition-all', dark ? config.dark : config.light].join(' ')}
|
||||
style={{ width: `${method.percentage}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user