完善首页接口

This commit is contained in:
2026-10-15 17:04:37 +08:00
parent ba9451b634
commit c29e39df13
2 changed files with 259 additions and 239 deletions

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,10 +1,14 @@
"use client"
import { format, subDays } from "date-fns"
import {
differenceInCalendarDays,
format,
isValid,
parseISO,
subDays,
} from "date-fns"
import {
Activity,
ArrowDownRight,
ArrowUpRight,
BarChart3,
DoorOpenIcon,
Server,
@@ -13,19 +17,11 @@ import {
Users,
} from "lucide-react"
import Link from "next/link"
import { useCallback, useEffect, useMemo, useState } from "react"
import { useCallback, useMemo, useState } from "react"
import { getExtractable, getOverview, getTrend } from "@/actions/dashboard"
import {
SimpleBarChart,
SimpleHorizontalBarChart,
SimpleLineChart,
} from "@/components/charts"
import { SimpleBarChart, SimpleLineChart } from "@/components/charts"
import { Page } from "@/components/page"
import type {
DashboardExtractable,
DashboardOverview,
DashboardTrendItem,
} from "@/models/dashboard"
import { useData } from "./data"
type TimeRange = "today" | "7d" | "30d" | "90d" | "custom"
@@ -37,125 +33,76 @@ const timeRangeLabels: Record<TimeRange, string> = {
custom: "自定义",
}
function getDateRange(
range: TimeRange,
customStart: string,
customEnd: string,
) {
const today = format(new Date(), "yyyy-MM-dd")
switch (range) {
case "today":
return { date_start: today, date_end: today }
case "7d":
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(new Date(), 6), "yyyy-MM-dd"),
date_end: today,
}
case "30d":
return {
date_start: format(subDays(new Date(), 29), "yyyy-MM-dd"),
date_end: today,
}
case "90d":
return {
date_start: format(subDays(new Date(), 89), "yyyy-MM-dd"),
date_end: today,
}
case "custom":
return { date_start: customStart, date_end: customEnd }
date_start: format(subDays(now, days[range]), "yyyy-MM-dd"),
date_end: format(now, "yyyy-MM-dd"),
}
}
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
}
}
const mockUserData = (() => {
const rng = mulberry32(42)
return [
{ name: "张三", activity: Math.floor(rng() * 100) + 200 },
{ name: "李四", activity: Math.floor(rng() * 100) + 180 },
{ name: "王五", activity: Math.floor(rng() * 100) + 160 },
{ name: "赵六", activity: Math.floor(rng() * 100) + 140 },
{ name: "孙七", activity: Math.floor(rng() * 100) + 120 },
{ name: "周八", activity: Math.floor(rng() * 100) + 90 },
{ name: "吴九", activity: Math.floor(rng() * 100) + 60 },
]
})()
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 [overview, setOverview] = useState<DashboardOverview | null>(null)
const [trendData, setTrendData] = useState<DashboardTrendItem[]>([])
const [extractable, setExtractable] = useState<DashboardExtractable | null>(
null,
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 [lastUpdated, setLastUpdated] = useState<string>("--")
const trendState = useData(loadTrend)
const overview = overviewState.data
const extractable = extractableState.data
const fetchData = useCallback(
async (range: TimeRange, customStart: string, customEnd: string) => {
const [overviewResp, trendResp, extractableResp] = await Promise.all([
getOverview(),
getTrend(getDateRange(range, customStart, customEnd)),
getExtractable(),
])
console.log(overviewResp, "overviewResp")
console.log(trendResp, "trendResp")
console.log(extractableResp, "extractableResp")
if (overviewResp.success) setOverview(overviewResp.data)
if (trendResp.success) setTrendData(trendResp.data)
if (extractableResp.success) setExtractable(extractableResp.data)
setLastUpdated(format(new Date(), "yyyy-MM-dd HH:mm:ss"))
},
[],
)
useEffect(() => {
fetchData(timeRange, startDate, endDate)
}, [fetchData, timeRange, startDate, endDate])
const handleTimeRangeChange = useCallback(
(key: TimeRange) => {
const handleTimeRangeChange = (key: TimeRange) => {
setDateError(null)
if (key === "custom") {
setStartDate(period.date_start)
setEndDate(period.date_end)
setShowCustomPicker(true)
setTimeRange("custom")
setStartDate("")
setEndDate("")
} else {
setTimeRange(key)
setPeriod({ key, ...getDateRange(key) })
setShowCustomPicker(false)
fetchData(key, "", "")
}
},
[fetchData],
)
}
const handleDateConfirm = () => {
if (startDate && endDate) {
setShowCustomPicker(false)
fetchData("custom", startDate, endDate)
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")
fetchData("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,
@@ -172,19 +119,13 @@ export default function DashboardPage() {
date: item.date.slice(5),
value: item.extract_count,
}))
return { proxyData, tradeData, customerData, extractData }
}, [trendData])
}, [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">
上次更新: {lastUpdated}
</p>
</div>
<div className="flex gap-2 flex-wrap">
<Link
href="/cust"
@@ -213,14 +154,13 @@ export default function DashboardPage() {
<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={
overview ? String(overview.pending_customer_count) : "--"
}
change="--"
trend="up"
icon={Users}
iconColor="text-cyan-600"
iconBg="bg-cyan-50 border-cyan-100"
@@ -228,8 +168,6 @@ export default function DashboardPage() {
<StatCard
title="活跃代理数"
value={overview ? String(overview.active_channel_count) : "--"}
change="--"
trend="up"
icon={Server}
iconColor="text-blue-600"
iconBg="bg-blue-50 border-blue-100"
@@ -237,8 +175,6 @@ export default function DashboardPage() {
<StatCard
title="今日交易额"
value={overview ? `¥${overview.today_trade_amount}` : "--"}
change="--"
trend="up"
icon={TrendingUp}
iconColor="text-amber-600"
iconBg="bg-amber-50 border-amber-100"
@@ -246,8 +182,6 @@ export default function DashboardPage() {
<StatCard
title="今日提取数量"
value={overview ? String(overview.today_extract_count) : "--"}
change="--"
trend="up"
icon={BarChart3}
iconColor="text-rose-600"
iconBg="bg-rose-50 border-rose-100"
@@ -257,8 +191,6 @@ export default function DashboardPage() {
value={
overview ? String(overview.today_new_customer_count) : "--"
}
change="--"
trend="up"
icon={UserPlus}
iconColor="text-blue-600"
iconBg="bg-blue-50 border-blue-100"
@@ -273,9 +205,11 @@ export default function DashboardPage() {
{(Object.keys(timeRangeLabels) as TimeRange[]).map(key => (
<button
key={key}
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"
}`}
@@ -290,18 +224,27 @@ export default function DashboardPage() {
<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"
@@ -309,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"
>
@@ -317,8 +261,26 @@ export default function DashboardPage() {
</div>
)}
</div>
{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>
@@ -330,7 +292,6 @@ export default function DashboardPage() {
height={250}
/>
</div>
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日交易额</h3>
<SimpleBarChart
@@ -341,7 +302,6 @@ export default function DashboardPage() {
height={250}
/>
</div>
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日新增客户</h3>
<SimpleLineChart
@@ -352,7 +312,6 @@ export default function DashboardPage() {
height={250}
/>
</div>
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日提取量</h3>
<SimpleBarChart
@@ -364,6 +323,7 @@ export default function DashboardPage() {
/>
</div>
</div>
)}
</div>
<div className="lg:col-span-1 space-y-4">
@@ -372,18 +332,17 @@ export default function DashboardPage() {
<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={extractable ? String(extractable.long) : "--"}
color="bg-blue-500"
/>
<ResourceItem
label="短效套餐"
active="--"
total={extractable ? String(extractable.short) : "--"}
color="bg-emerald-500"
/>
<div className="pt-3 border-t flex justify-between text-sm">
<span className="text-muted-foreground">总可提取量</span>
@@ -394,21 +353,6 @@ export default function DashboardPage() {
</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={mockUserData}
dataKey="activity"
labelKey="name"
fill="#6366f1"
width={300}
/>
</div>
</div>
</div>
</div>
</Page>
@@ -418,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
@@ -438,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}`} />
@@ -460,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">
<div className="flex justify-between text-sm">
<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>
<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>
)
}