2 Commits

Author SHA1 Message Date
c29e39df13 完善首页接口 2026-10-15 17:04:37 +08:00
Eamon
ba9451b634 添加首页请求接口更新首页数据 2026-09-04 17:26:59 +08:00
9 changed files with 366 additions and 248 deletions

23
src/actions/dashboard.ts Normal file
View File

@@ -0,0 +1,23 @@
"use server"
import type {
DashboardExtractable,
DashboardOverview,
DashboardTrendItem,
} from "@/models/dashboard"
import { callByUser } from "./base"
export async function getOverview() {
return callByUser<DashboardOverview>("/api/admin/home/overview", {})
}
export async function getTrend(params: {
date_start: string
date_end: string
}) {
return callByUser<DashboardTrendItem[]>("/api/admin/home/trend", params)
}
export async function getExtractable() {
return callByUser<DashboardExtractable>("/api/admin/home/extractable", {})
}

View File

@@ -0,0 +1,68 @@
import { useCallback, useEffect, useRef, useState } from "react"
import type { ApiResponse } from "@/lib/api"
export function useData<T>(load: () => Promise<ApiResponse<T>>) {
const request = useRef(0)
const [state, setState] = useState<{
source: typeof load
data: T | null
loading: boolean
error: string | null
updatedAt: Date | null
}>({ source: load, data: null, loading: true, error: null, updatedAt: null })
const reload = useCallback(async () => {
const id = ++request.current
setState(prev => ({
source: load,
data: prev.source === load ? prev.data : null,
updatedAt: prev.source === load ? prev.updatedAt : null,
loading: true,
error: null,
}))
try {
const resp = await load()
if (id !== request.current) return
if (resp.success) {
setState({
source: load,
data: resp.data,
loading: false,
error: null,
updatedAt: new Date(),
})
} else {
setState(prev => ({
...prev,
loading: false,
error: resp.message || "请求失败,请重试",
}))
}
} catch {
if (id !== request.current) return
setState(prev => ({
...prev,
loading: false,
error: "请求失败,请重试",
}))
}
}, [load])
useEffect(() => {
void reload()
return () => {
request.current++
}
}, [reload])
const current = state.source === load
return {
data: current ? state.data : null,
loading: !current || state.loading,
error: current ? state.error : null,
updatedAt: current ? state.updatedAt : null,
reload,
}
}

View File

@@ -1,12 +1,15 @@
"use client"
import { format, subDays } from "date-fns"
import {
differenceInCalendarDays,
format,
isValid,
parseISO,
subDays,
} from "date-fns"
import {
Activity,
ArrowDownRight,
ArrowUpRight,
BarChart3,
Calendar,
DoorOpenIcon,
Server,
TrendingUp,
@@ -14,13 +17,11 @@ import {
Users,
} from "lucide-react"
import Link from "next/link"
import { useMemo, useState } from "react"
import {
SimpleBarChart,
SimpleHorizontalBarChart,
SimpleLineChart,
} from "@/components/charts"
import { useCallback, useMemo, useState } from "react"
import { getExtractable, getOverview, getTrend } from "@/actions/dashboard"
import { SimpleBarChart, SimpleLineChart } from "@/components/charts"
import { Page } from "@/components/page"
import { useData } from "./data"
type TimeRange = "today" | "7d" | "30d" | "90d" | "custom"
@@ -32,97 +33,99 @@ const timeRangeLabels: Record<TimeRange, string> = {
custom: "自定义",
}
function mulberry32(seed: number) {
let t = seed
return () => {
t |= 0
t = (t + 0x6d2b79f5) | 0
let n = Math.imul(t ^ (t >>> 15), 1 | t)
n = (n + Math.imul(n ^ (n >>> 7), 61 | n)) ^ n
return ((n ^ (n >>> 14)) >>> 0) / 4294967296
function getDateRange(range: Exclude<TimeRange, "custom">) {
const now = new Date()
const days = { today: 0, "7d": 6, "30d": 29, "90d": 89 }
return {
date_start: format(subDays(now, days[range]), "yyyy-MM-dd"),
date_end: format(now, "yyyy-MM-dd"),
}
}
export default function DashboardPage() {
const [timeRange, setTimeRange] = useState<TimeRange>("7d")
const [period, setPeriod] = useState(() => ({
key: "7d" as TimeRange,
...getDateRange("7d"),
}))
const [showCustomPicker, setShowCustomPicker] = useState(false)
const [startDate, setStartDate] = useState("")
const [endDate, setEndDate] = useState("")
const [dateError, setDateError] = useState<string | null>(null)
const chartData = useMemo(() => {
const days = 14
const seed = 42
const rng = mulberry32(seed)
const proxyData = []
const tradeData = []
const customerData = []
const extractData = []
const overviewState = useData(getOverview)
const extractableState = useData(getExtractable)
const loadTrend = useCallback(
() =>
getTrend({ date_start: period.date_start, date_end: period.date_end }),
[period.date_start, period.date_end],
)
const trendState = useData(loadTrend)
const overview = overviewState.data
const extractable = extractableState.data
for (let i = days - 1; i >= 0; i--) {
const date = subDays(new Date(), i)
const dateStr = format(date, "MM-dd")
proxyData.push({
date: dateStr,
value: Math.floor(rng() * 50) + 80,
})
tradeData.push({
date: dateStr,
value: Math.floor(rng() * 3000) + 5000,
})
customerData.push({
date: dateStr,
value: Math.floor(rng() * 20) + 5,
})
extractData.push({
date: dateStr,
value: Math.floor(rng() * 800) + 1200,
})
}
const userData = [
{ name: "张三", activity: 287 },
{ name: "李四", activity: 245 },
{ name: "王五", activity: 198 },
{ name: "赵六", activity: 156 },
{ name: "孙七", activity: 132 },
{ name: "周八", activity: 98 },
{ name: "吴九", activity: 76 },
]
return { proxyData, tradeData, customerData, extractData, userData }
}, [])
// 处理自定义日期按钮点击
const handleCustomClick = () => {
setShowCustomPicker(true)
setTimeRange("custom")
// 清空之前的日期
setStartDate("")
setEndDate("")
}
// 处理日期确认
const handleDateConfirm = () => {
if (startDate && endDate) {
console.log("自定义日期范围:", startDate, "~", endDate)
const handleTimeRangeChange = (key: TimeRange) => {
setDateError(null)
if (key === "custom") {
setStartDate(period.date_start)
setEndDate(period.date_end)
setShowCustomPicker(true)
} else {
setPeriod({ key, ...getDateRange(key) })
setShowCustomPicker(false)
}
}
// 处理取消
const handleDateConfirm = () => {
const start = parseISO(startDate)
const end = parseISO(endDate)
if (!isValid(start) || !isValid(end)) {
setDateError("请选择有效的开始和结束日期")
return
}
const days = differenceInCalendarDays(end, start) + 1
if (days < 1) {
setDateError("结束日期不能早于开始日期")
return
}
if (days > 366) {
setDateError("日期范围不能超过 366 天")
return
}
setDateError(null)
setPeriod({ key: "custom", date_start: startDate, date_end: endDate })
setShowCustomPicker(false)
}
const handleCancel = () => {
setShowCustomPicker(false)
setTimeRange("7d")
setDateError(null)
}
const chartData = useMemo(() => {
const trendData = trendState.data ?? []
const proxyData = trendData.map(item => ({
date: item.date.slice(5),
value: item.active_channel_count,
}))
const tradeData = trendData.map(item => ({
date: item.date.slice(5),
value: Number.parseFloat(item.trade_amount) || 0,
}))
const customerData = trendData.map(item => ({
date: item.date.slice(5),
value: item.new_customer_count,
}))
const extractData = trendData.map(item => ({
date: item.date.slice(5),
value: item.extract_count,
}))
return { proxyData, tradeData, customerData, extractData }
}, [trendState.data])
return (
<Page className="overflow-auto">
{/* 欢迎栏 */}
<div className="bg-card rounded-lg border p-2 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div>
<h1 className="text-lg font-bold">IP代理管理控制台</h1>
<p className="text-sm text-muted-foreground mt-1">上次更新: --</p>
</div>
<h1 className="text-lg font-bold">IP代理管理控制台</h1>
<div className="flex gap-2 flex-wrap">
<Link
href="/cust"
@@ -149,58 +152,51 @@ export default function DashboardPage() {
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
{/* 指标卡片 */}
<div className="lg:col-span-2 space-y-4">
<div className="space-y-3">
<DataStatus {...overviewState} />
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
<StatCard
title="待认领客户数量"
value="--"
change="--"
trend="up"
value={
overview ? String(overview.pending_customer_count) : "--"
}
icon={Users}
iconColor="text-cyan-600"
iconBg="bg-cyan-50 border-cyan-100"
/>
<StatCard
title="活跃代理数"
value="--"
change="--"
trend="up"
value={overview ? String(overview.active_channel_count) : "--"}
icon={Server}
iconColor="text-blue-600"
iconBg="bg-blue-50 border-blue-100"
/>
<StatCard
title="今日交易额"
value="--"
change="--"
trend="up"
value={overview ? `¥${overview.today_trade_amount}` : "--"}
icon={TrendingUp}
iconColor="text-amber-600"
iconBg="bg-amber-50 border-amber-100"
/>
<StatCard
title="今日提取数量"
value="--"
change="--"
trend="up"
value={overview ? String(overview.today_extract_count) : "--"}
icon={BarChart3}
iconColor="text-rose-600"
iconBg="bg-rose-50 border-rose-100"
/>
<StatCard
title="今日新增客户"
value="--"
change="--"
trend="up"
value={
overview ? String(overview.today_new_customer_count) : "--"
}
icon={UserPlus}
iconColor="text-blue-600"
iconBg="bg-blue-50 border-blue-100"
/>
</div>
{/* 时间筛选栏 */}
<div className="flex flex-col sm:flex-row sm:items-center justify-end gap-3">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">数据周期</span>
@@ -209,16 +205,11 @@ export default function DashboardPage() {
{(Object.keys(timeRangeLabels) as TimeRange[]).map(key => (
<button
key={key}
onClick={() => {
if (key === "custom") {
handleCustomClick()
} else {
setTimeRange(key)
setShowCustomPicker(false)
}
}}
type="button"
onClick={() => handleTimeRangeChange(key)}
aria-pressed={period.key === key}
className={`px-3 py-1.5 text-xs font-medium transition-colors ${
timeRange === key && !showCustomPicker
period.key === key
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-accent"
}`}
@@ -229,23 +220,31 @@ export default function DashboardPage() {
</div>
</div>
{/* 点击自定义时显示 */}
{showCustomPicker && (
<div className="flex gap-2 items-center p-1 rounded-md">
<input
type="date"
aria-label="开始日期"
className="px-2 py-1 border rounded text-sm bg-background"
value={startDate}
onChange={e => setStartDate(e.target.value)}
onChange={e => {
setStartDate(e.target.value)
setDateError(null)
}}
/>
<span className="text-muted-foreground">~</span>
<input
type="date"
aria-label="结束日期"
className="px-2 py-1 border rounded text-sm bg-background"
value={endDate}
onChange={e => setEndDate(e.target.value)}
onChange={e => {
setEndDate(e.target.value)
setDateError(null)
}}
/>
<button
type="button"
onClick={handleDateConfirm}
disabled={!startDate || !endDate}
className="px-3 py-1 bg-primary text-primary-foreground rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed"
@@ -253,6 +252,7 @@ export default function DashboardPage() {
确定
</button>
<button
type="button"
onClick={handleCancel}
className="px-3 py-1 border rounded text-sm hover:bg-accent"
>
@@ -261,103 +261,98 @@ export default function DashboardPage() {
</div>
)}
</div>
</div>
{/* 图表区域 */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* 每日活跃代理 */}
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日活跃代理</h3>
<SimpleLineChart
data={chartData.proxyData}
dataKey="value"
xAxisKey="date"
stroke="#3b82f6"
height={250}
/>
</div>
{/* 每日交易额 */}
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日交易额</h3>
<SimpleBarChart
data={chartData.tradeData}
dataKey="value"
xAxisKey="date"
fill="#f59e0b"
height={250}
/>
</div>
{/* 每日新增客户 */}
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日新增客户</h3>
<SimpleLineChart
data={chartData.customerData}
dataKey="value"
xAxisKey="date"
stroke="#10b981"
height={250}
/>
</div>
{/* 每日提取量 */}
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日提取量</h3>
<SimpleBarChart
data={chartData.extractData}
dataKey="value"
xAxisKey="date"
fill="#ef4444"
height={250}
/>
{dateError && (
<p role="alert" className="text-sm text-destructive">
{dateError}
</p>
)}
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-sm text-muted-foreground">
{period.date_start} ~ {period.date_end}
</span>
<DataStatus {...trendState} showStale={false} />
</div>
</div>
{trendState.loading || trendState.error ? (
<div className="bg-card rounded-lg border p-4 h-64 flex items-center justify-center text-sm text-muted-foreground">
{trendState.loading
? "正在加载趋势数据…"
: "趋势数据加载失败,请重试"}
</div>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日活跃代理</h3>
<SimpleLineChart
data={chartData.proxyData}
dataKey="value"
xAxisKey="date"
stroke="#3b82f6"
height={250}
/>
</div>
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日交易额</h3>
<SimpleBarChart
data={chartData.tradeData}
dataKey="value"
xAxisKey="date"
fill="#f59e0b"
height={250}
/>
</div>
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日新增客户</h3>
<SimpleLineChart
data={chartData.customerData}
dataKey="value"
xAxisKey="date"
stroke="#10b981"
height={250}
/>
</div>
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日提取量</h3>
<SimpleBarChart
data={chartData.extractData}
dataKey="value"
xAxisKey="date"
fill="#ef4444"
height={250}
/>
</div>
</div>
)}
</div>
{/*套餐统计 */}
<div className="lg:col-span-1 space-y-4">
<div className="bg-card rounded-lg border">
<div className="p-5 border-b">
<h2 className="font-semibold">套餐统计</h2>
</div>
<div className="p-5">
<div className="mb-4">
<DataStatus {...extractableState} />
</div>
<div className="flex flex-col gap-4">
<ResourceItem
label="长效套餐"
active="--"
total="--"
color="bg-blue-500"
total={extractable ? String(extractable.long) : "--"}
/>
<ResourceItem
label="短效套餐"
active="--"
total="--"
color="bg-emerald-500"
total={extractable ? String(extractable.short) : "--"}
/>
<div className="pt-3 border-t flex justify-between text-sm">
<span className="text-muted-foreground">总可用IP</span>
<span className="font-semibold">--</span>
<span className="text-muted-foreground">总可提取量</span>
<span className="font-semibold">
{extractable ? extractable.long + extractable.short : "--"}
</span>
</div>
</div>
</div>
</div>
{/* 最近活跃用户 */}
<div className="bg-card rounded-lg border">
<div className="p-5 border-b">
<h2 className="font-semibold">最近活跃用户</h2>
</div>
<div className="p-4">
<SimpleHorizontalBarChart
data={chartData.userData}
dataKey="activity"
labelKey="name"
fill="#6366f1"
width={300}
/>
</div>
</div>
</div>
</div>
</Page>
@@ -367,16 +362,12 @@ export default function DashboardPage() {
function StatCard({
title,
value,
change,
trend,
icon: Icon,
iconColor,
iconBg,
}: {
title: string
value: string
change: string
trend: "up" | "down"
icon: React.ComponentType<{ className?: string }>
iconColor: string
iconBg: string
@@ -387,19 +378,6 @@ function StatCard({
<div className="flex-1 min-w-0">
<p className="text-xs text-muted-foreground truncate">{title}</p>
<p className="text-xl font-bold mt-1 truncate">{value}</p>
<div className="flex items-center gap-1 mt-1.5">
{trend === "up" ? (
<ArrowUpRight className="h-3 w-3 text-green-600 shrink-0" />
) : (
<ArrowDownRight className="h-3 w-3 text-red-600 shrink-0" />
)}
<span
className={`text-xs font-medium ${trend === "up" ? "text-green-600" : "text-red-600"}`}
>
{change}
</span>
<span className="text-xs text-muted-foreground">较昨日</span>
</div>
</div>
<div className={`p-2 rounded-md border shrink-0 ${iconBg}`}>
<Icon className={`h-5 w-5 ${iconColor}`} />
@@ -409,31 +387,56 @@ function StatCard({
)
}
function ResourceItem({
label,
active,
total,
color,
}: {
label: string
active: string
total: string
color: string
}) {
function ResourceItem({ label, total }: { label: string; total: string }) {
return (
<div>
<div className="flex justify-between text-sm mb-1.5">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium">
{active} / {total}
</span>
</div>
<div className="w-full h-2 bg-muted rounded-full overflow-hidden">
<div
className={`h-full ${color} rounded-full transition-all`}
style={{ width: "0%" }}
/>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium">{total}</span>
</div>
)
}
function DataStatus({
data,
loading,
error,
updatedAt,
reload,
showStale = true,
}: {
data: unknown
loading: boolean
error: string | null
updatedAt: Date | null
reload: () => Promise<void>
showStale?: boolean
}) {
return (
<div
className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"
aria-live="polite"
>
{loading ? (
<span>
{data && showStale ? "正在更新,当前显示上次数据…" : "正在加载…"}
</span>
) : error ? (
<span role="alert" className="text-destructive">
{error}
{data && showStale ? ",当前显示上次数据" : ""}
</span>
) : null}
{updatedAt && (showStale || (!loading && !error)) && (
<span>更新时间:{format(updatedAt, "yyyy-MM-dd HH:mm:ss")}</span>
)}
<button
type="button"
disabled={loading}
onClick={() => void reload()}
className="underline underline-offset-2 hover:text-foreground disabled:opacity-50 disabled:cursor-not-allowed"
>
{error ? "重试" : "刷新"}
</button>
</div>
)
}

View File

@@ -87,6 +87,20 @@ export default function BalancePage() {
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex items-end gap-4">
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel>过期时间</FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="phone"
control={control}
@@ -115,21 +129,8 @@ export default function BalancePage() {
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel>开始时间</FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
{/* <Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
@@ -142,7 +143,7 @@ export default function BalancePage() {
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
/> */}
<Button type="submit">搜索</Button>
<Button

View File

@@ -209,7 +209,10 @@ export default function ResourcesPage() {
>
<ResourceList resourceType="short" />
</TabsContent>
<TabsContent value="long" className="flex flex-col gap-4 overflow-hidden">
<TabsContent
value="long"
className="flex flex-col gap-4 overflow-hidden"
>
<ResourceList resourceType="long" />
</TabsContent>
</Tabs>

View File

@@ -93,8 +93,8 @@ export function SimpleBarChart({
className="w-full h-full"
preserveAspectRatio="xMidYMid meet"
>
{yLabels.map(yl => (
<g key={yl.label}>
{yLabels.map((yl, i) => (
<g key={i}>
<line
x1={padding.left}
y1={yl.y}

View File

@@ -100,8 +100,8 @@ export function SimpleLineChart({
</linearGradient>
</defs>
{yLabels.map(yl => (
<g key={yl.label}>
{yLabels.map((yl, i) => (
<g key={i}>
<line
x1={padding.left}
y1={yl.y}

20
src/models/dashboard.ts Normal file
View File

@@ -0,0 +1,20 @@
export type DashboardOverview = {
active_channel_count: number
pending_customer_count: number
today_extract_count: number
today_new_customer_count: number
today_trade_amount: string
}
export type DashboardTrendItem = {
date: string
active_channel_count: number
trade_amount: string
new_customer_count: number
extract_count: number
}
export type DashboardExtractable = {
short: number
long: number
}

View File

@@ -16,5 +16,5 @@ export type Trade = {
updated_at: Date
user?: User
remark: string
amount:string
amount: string
}