添加首页请求接口更新首页数据

This commit is contained in:
Eamon
2026-09-04 17:26:59 +08:00
parent d9448c6c41
commit ba9451b634
8 changed files with 202 additions and 104 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

@@ -6,7 +6,6 @@ import {
ArrowDownRight, ArrowDownRight,
ArrowUpRight, ArrowUpRight,
BarChart3, BarChart3,
Calendar,
DoorOpenIcon, DoorOpenIcon,
Server, Server,
TrendingUp, TrendingUp,
@@ -14,13 +13,19 @@ import {
Users, Users,
} from "lucide-react" } from "lucide-react"
import Link from "next/link" import Link from "next/link"
import { useMemo, useState } from "react" import { useCallback, useEffect, useMemo, useState } from "react"
import { getExtractable, getOverview, getTrend } from "@/actions/dashboard"
import { import {
SimpleBarChart, SimpleBarChart,
SimpleHorizontalBarChart, SimpleHorizontalBarChart,
SimpleLineChart, SimpleLineChart,
} from "@/components/charts" } from "@/components/charts"
import { Page } from "@/components/page" import { Page } from "@/components/page"
import type {
DashboardExtractable,
DashboardOverview,
DashboardTrendItem,
} from "@/models/dashboard"
type TimeRange = "today" | "7d" | "30d" | "90d" | "custom" type TimeRange = "today" | "7d" | "30d" | "90d" | "custom"
@@ -32,6 +37,35 @@ const timeRangeLabels: Record<TimeRange, string> = {
custom: "自定义", 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":
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 }
}
}
function mulberry32(seed: number) { function mulberry32(seed: number) {
let t = seed let t = seed
return () => { return () => {
@@ -43,85 +77,113 @@ function mulberry32(seed: number) {
} }
} }
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() { export default function DashboardPage() {
const [timeRange, setTimeRange] = useState<TimeRange>("7d") const [timeRange, setTimeRange] = useState<TimeRange>("7d")
const [showCustomPicker, setShowCustomPicker] = useState(false) const [showCustomPicker, setShowCustomPicker] = useState(false)
const [startDate, setStartDate] = useState("") const [startDate, setStartDate] = useState("")
const [endDate, setEndDate] = useState("") const [endDate, setEndDate] = useState("")
const chartData = useMemo(() => { const [overview, setOverview] = useState<DashboardOverview | null>(null)
const days = 14 const [trendData, setTrendData] = useState<DashboardTrendItem[]>([])
const seed = 42 const [extractable, setExtractable] = useState<DashboardExtractable | null>(
const rng = mulberry32(seed) null,
const proxyData = [] )
const tradeData = [] const [lastUpdated, setLastUpdated] = useState<string>("--")
const customerData = []
const extractData = []
for (let i = days - 1; i >= 0; i--) { const fetchData = useCallback(
const date = subDays(new Date(), i) async (range: TimeRange, customStart: string, customEnd: string) => {
const dateStr = format(date, "MM-dd") const [overviewResp, trendResp, extractableResp] = await Promise.all([
proxyData.push({ getOverview(),
date: dateStr, getTrend(getDateRange(range, customStart, customEnd)),
value: Math.floor(rng() * 50) + 80, getExtractable(),
}) ])
tradeData.push({ console.log(overviewResp, "overviewResp")
date: dateStr, console.log(trendResp, "trendResp")
value: Math.floor(rng() * 3000) + 5000, console.log(extractableResp, "extractableResp")
})
customerData.push({
date: dateStr,
value: Math.floor(rng() * 20) + 5,
})
extractData.push({
date: dateStr,
value: Math.floor(rng() * 800) + 1200,
})
}
const userData = [ if (overviewResp.success) setOverview(overviewResp.data)
{ name: "张三", activity: 287 }, if (trendResp.success) setTrendData(trendResp.data)
{ name: "李四", activity: 245 }, if (extractableResp.success) setExtractable(extractableResp.data)
{ name: "王五", activity: 198 }, setLastUpdated(format(new Date(), "yyyy-MM-dd HH:mm:ss"))
{ name: "赵六", activity: 156 }, },
{ name: "孙七", activity: 132 }, [],
{ name: "周八", activity: 98 }, )
{ name: "吴九", activity: 76 },
]
return { proxyData, tradeData, customerData, extractData, userData } useEffect(() => {
}, []) fetchData(timeRange, startDate, endDate)
}, [fetchData, timeRange, startDate, endDate])
// 处理自定义日期按钮点击 const handleTimeRangeChange = useCallback(
const handleCustomClick = () => { (key: TimeRange) => {
if (key === "custom") {
setShowCustomPicker(true) setShowCustomPicker(true)
setTimeRange("custom") setTimeRange("custom")
// 清空之前的日期
setStartDate("") setStartDate("")
setEndDate("") setEndDate("")
} else {
setTimeRange(key)
setShowCustomPicker(false)
fetchData(key, "", "")
} }
},
[fetchData],
)
// 处理日期确认
const handleDateConfirm = () => { const handleDateConfirm = () => {
if (startDate && endDate) { if (startDate && endDate) {
console.log("自定义日期范围:", startDate, "~", endDate)
setShowCustomPicker(false) setShowCustomPicker(false)
fetchData("custom", startDate, endDate)
} }
} }
// 处理取消
const handleCancel = () => { const handleCancel = () => {
setShowCustomPicker(false) setShowCustomPicker(false)
setTimeRange("7d") setTimeRange("7d")
fetchData("7d", "", "")
} }
const chartData = useMemo(() => {
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 }
}, [trendData])
return ( return (
<Page className="overflow-auto"> <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 className="bg-card rounded-lg border p-2 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div> <div>
<h1 className="text-lg font-bold">IP代理管理控制台</h1> <h1 className="text-lg font-bold">IP代理管理控制台</h1>
<p className="text-sm text-muted-foreground mt-1">上次更新: --</p> <p className="text-sm text-muted-foreground mt-1">
上次更新: {lastUpdated}
</p>
</div> </div>
<div className="flex gap-2 flex-wrap"> <div className="flex gap-2 flex-wrap">
<Link <Link
@@ -149,13 +211,14 @@ export default function DashboardPage() {
</div> </div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4"> <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
{/* 指标卡片 */}
<div className="lg:col-span-2 space-y-4"> <div className="lg:col-span-2 space-y-4">
<div className="space-y-3"> <div className="space-y-3">
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3"> <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
<StatCard <StatCard
title="待认领客户数量" title="待认领客户数量"
value="--" value={
overview ? String(overview.pending_customer_count) : "--"
}
change="--" change="--"
trend="up" trend="up"
icon={Users} icon={Users}
@@ -164,7 +227,7 @@ export default function DashboardPage() {
/> />
<StatCard <StatCard
title="活跃代理数" title="活跃代理数"
value="--" value={overview ? String(overview.active_channel_count) : "--"}
change="--" change="--"
trend="up" trend="up"
icon={Server} icon={Server}
@@ -173,7 +236,7 @@ export default function DashboardPage() {
/> />
<StatCard <StatCard
title="今日交易额" title="今日交易额"
value="--" value={overview ? `¥${overview.today_trade_amount}` : "--"}
change="--" change="--"
trend="up" trend="up"
icon={TrendingUp} icon={TrendingUp}
@@ -182,7 +245,7 @@ export default function DashboardPage() {
/> />
<StatCard <StatCard
title="今日提取数量" title="今日提取数量"
value="--" value={overview ? String(overview.today_extract_count) : "--"}
change="--" change="--"
trend="up" trend="up"
icon={BarChart3} icon={BarChart3}
@@ -191,7 +254,9 @@ export default function DashboardPage() {
/> />
<StatCard <StatCard
title="今日新增客户" title="今日新增客户"
value="--" value={
overview ? String(overview.today_new_customer_count) : "--"
}
change="--" change="--"
trend="up" trend="up"
icon={UserPlus} icon={UserPlus}
@@ -200,7 +265,6 @@ export default function DashboardPage() {
/> />
</div> </div>
{/* 时间筛选栏 */}
<div className="flex flex-col sm:flex-row sm:items-center justify-end gap-3"> <div className="flex flex-col sm:flex-row sm:items-center justify-end gap-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">数据周期</span> <span className="text-sm text-muted-foreground">数据周期</span>
@@ -209,14 +273,7 @@ export default function DashboardPage() {
{(Object.keys(timeRangeLabels) as TimeRange[]).map(key => ( {(Object.keys(timeRangeLabels) as TimeRange[]).map(key => (
<button <button
key={key} key={key}
onClick={() => { onClick={() => handleTimeRangeChange(key)}
if (key === "custom") {
handleCustomClick()
} else {
setTimeRange(key)
setShowCustomPicker(false)
}
}}
className={`px-3 py-1.5 text-xs font-medium transition-colors ${ className={`px-3 py-1.5 text-xs font-medium transition-colors ${
timeRange === key && !showCustomPicker timeRange === key && !showCustomPicker
? "bg-primary text-primary-foreground" ? "bg-primary text-primary-foreground"
@@ -229,7 +286,6 @@ export default function DashboardPage() {
</div> </div>
</div> </div>
{/* 点击自定义时显示 */}
{showCustomPicker && ( {showCustomPicker && (
<div className="flex gap-2 items-center p-1 rounded-md"> <div className="flex gap-2 items-center p-1 rounded-md">
<input <input
@@ -263,9 +319,7 @@ export default function DashboardPage() {
</div> </div>
</div> </div>
{/* 图表区域 */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* 每日活跃代理 */}
<div className="bg-card rounded-lg border p-4"> <div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日活跃代理</h3> <h3 className="font-semibold text-sm mb-4">每日活跃代理</h3>
<SimpleLineChart <SimpleLineChart
@@ -277,7 +331,6 @@ export default function DashboardPage() {
/> />
</div> </div>
{/* 每日交易额 */}
<div className="bg-card rounded-lg border p-4"> <div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日交易额</h3> <h3 className="font-semibold text-sm mb-4">每日交易额</h3>
<SimpleBarChart <SimpleBarChart
@@ -289,7 +342,6 @@ export default function DashboardPage() {
/> />
</div> </div>
{/* 每日新增客户 */}
<div className="bg-card rounded-lg border p-4"> <div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日新增客户</h3> <h3 className="font-semibold text-sm mb-4">每日新增客户</h3>
<SimpleLineChart <SimpleLineChart
@@ -301,7 +353,6 @@ export default function DashboardPage() {
/> />
</div> </div>
{/* 每日提取量 */}
<div className="bg-card rounded-lg border p-4"> <div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日提取量</h3> <h3 className="font-semibold text-sm mb-4">每日提取量</h3>
<SimpleBarChart <SimpleBarChart
@@ -315,7 +366,6 @@ export default function DashboardPage() {
</div> </div>
</div> </div>
{/*套餐统计 */}
<div className="lg:col-span-1 space-y-4"> <div className="lg:col-span-1 space-y-4">
<div className="bg-card rounded-lg border"> <div className="bg-card rounded-lg border">
<div className="p-5 border-b"> <div className="p-5 border-b">
@@ -326,31 +376,32 @@ export default function DashboardPage() {
<ResourceItem <ResourceItem
label="长效套餐" label="长效套餐"
active="--" active="--"
total="--" total={extractable ? String(extractable.long) : "--"}
color="bg-blue-500" color="bg-blue-500"
/> />
<ResourceItem <ResourceItem
label="短效套餐" label="短效套餐"
active="--" active="--"
total="--" total={extractable ? String(extractable.short) : "--"}
color="bg-emerald-500" color="bg-emerald-500"
/> />
<div className="pt-3 border-t flex justify-between text-sm"> <div className="pt-3 border-t flex justify-between text-sm">
<span className="text-muted-foreground">总可用IP</span> <span className="text-muted-foreground">总可提取量</span>
<span className="font-semibold">--</span> <span className="font-semibold">
{extractable ? extractable.long + extractable.short : "--"}
</span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
{/* 最近活跃用户 */}
<div className="bg-card rounded-lg border"> <div className="bg-card rounded-lg border">
<div className="p-5 border-b"> <div className="p-5 border-b">
<h2 className="font-semibold">最近活跃用户</h2> <h2 className="font-semibold">最近活跃用户</h2>
</div> </div>
<div className="p-4"> <div className="p-4">
<SimpleHorizontalBarChart <SimpleHorizontalBarChart
data={chartData.userData} data={mockUserData}
dataKey="activity" dataKey="activity"
labelKey="name" labelKey="name"
fill="#6366f1" fill="#6366f1"

View File

@@ -87,6 +87,20 @@ export default function BalancePage() {
<Page> <Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg"> <form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex items-end gap-4"> <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 <Controller
name="phone" name="phone"
control={control} control={control}
@@ -115,21 +129,8 @@ export default function BalancePage() {
</Field> </Field>
)} )}
/> />
<Controller
name="created_at_start" {/* <Controller
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="created_at_end" name="created_at_end"
control={control} control={control}
render={({ field, fieldState }) => ( render={({ field, fieldState }) => (
@@ -142,7 +143,7 @@ export default function BalancePage() {
<FieldError>{fieldState.error?.message}</FieldError> <FieldError>{fieldState.error?.message}</FieldError>
</Field> </Field>
)} )}
/> /> */}
<Button type="submit">搜索</Button> <Button type="submit">搜索</Button>
<Button <Button

View File

@@ -209,7 +209,10 @@ export default function ResourcesPage() {
> >
<ResourceList resourceType="short" /> <ResourceList resourceType="short" />
</TabsContent> </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" /> <ResourceList resourceType="long" />
</TabsContent> </TabsContent>
</Tabs> </Tabs>

View File

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

View File

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