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

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,
ArrowUpRight,
BarChart3,
Calendar,
DoorOpenIcon,
Server,
TrendingUp,
@@ -14,13 +13,19 @@ import {
Users,
} from "lucide-react"
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 {
SimpleBarChart,
SimpleHorizontalBarChart,
SimpleLineChart,
} from "@/components/charts"
import { Page } from "@/components/page"
import type {
DashboardExtractable,
DashboardOverview,
DashboardTrendItem,
} from "@/models/dashboard"
type TimeRange = "today" | "7d" | "30d" | "90d" | "custom"
@@ -32,6 +37,35 @@ 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":
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) {
let t = seed
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() {
const [timeRange, setTimeRange] = useState<TimeRange>("7d")
const [showCustomPicker, setShowCustomPicker] = useState(false)
const [startDate, setStartDate] = useState("")
const [endDate, setEndDate] = useState("")
const chartData = useMemo(() => {
const days = 14
const seed = 42
const rng = mulberry32(seed)
const proxyData = []
const tradeData = []
const customerData = []
const extractData = []
const [overview, setOverview] = useState<DashboardOverview | null>(null)
const [trendData, setTrendData] = useState<DashboardTrendItem[]>([])
const [extractable, setExtractable] = useState<DashboardExtractable | null>(
null,
)
const [lastUpdated, setLastUpdated] = useState<string>("--")
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 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")
const userData = [
{ name: "张三", activity: 287 },
{ name: "李四", activity: 245 },
{ name: "王五", activity: 198 },
{ name: "赵六", activity: 156 },
{ name: "孙七", activity: 132 },
{ name: "周八", activity: 98 },
{ name: "吴九", activity: 76 },
]
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"))
},
[],
)
return { proxyData, tradeData, customerData, extractData, userData }
}, [])
useEffect(() => {
fetchData(timeRange, startDate, endDate)
}, [fetchData, timeRange, startDate, endDate])
// 处理自定义日期按钮点击
const handleCustomClick = () => {
const handleTimeRangeChange = useCallback(
(key: TimeRange) => {
if (key === "custom") {
setShowCustomPicker(true)
setTimeRange("custom")
// 清空之前的日期
setStartDate("")
setEndDate("")
} else {
setTimeRange(key)
setShowCustomPicker(false)
fetchData(key, "", "")
}
},
[fetchData],
)
// 处理日期确认
const handleDateConfirm = () => {
if (startDate && endDate) {
console.log("自定义日期范围:", startDate, "~", endDate)
setShowCustomPicker(false)
fetchData("custom", startDate, endDate)
}
}
// 处理取消
const handleCancel = () => {
setShowCustomPicker(false)
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 (
<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>
<p className="text-sm text-muted-foreground mt-1">
上次更新: {lastUpdated}
</p>
</div>
<div className="flex gap-2 flex-wrap">
<Link
@@ -149,13 +211,14 @@ 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">
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
<StatCard
title="待认领客户数量"
value="--"
value={
overview ? String(overview.pending_customer_count) : "--"
}
change="--"
trend="up"
icon={Users}
@@ -164,7 +227,7 @@ export default function DashboardPage() {
/>
<StatCard
title="活跃代理数"
value="--"
value={overview ? String(overview.active_channel_count) : "--"}
change="--"
trend="up"
icon={Server}
@@ -173,7 +236,7 @@ export default function DashboardPage() {
/>
<StatCard
title="今日交易额"
value="--"
value={overview ? `¥${overview.today_trade_amount}` : "--"}
change="--"
trend="up"
icon={TrendingUp}
@@ -182,7 +245,7 @@ export default function DashboardPage() {
/>
<StatCard
title="今日提取数量"
value="--"
value={overview ? String(overview.today_extract_count) : "--"}
change="--"
trend="up"
icon={BarChart3}
@@ -191,7 +254,9 @@ export default function DashboardPage() {
/>
<StatCard
title="今日新增客户"
value="--"
value={
overview ? String(overview.today_new_customer_count) : "--"
}
change="--"
trend="up"
icon={UserPlus}
@@ -200,7 +265,6 @@ export default function DashboardPage() {
/>
</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,14 +273,7 @@ export default function DashboardPage() {
{(Object.keys(timeRangeLabels) as TimeRange[]).map(key => (
<button
key={key}
onClick={() => {
if (key === "custom") {
handleCustomClick()
} else {
setTimeRange(key)
setShowCustomPicker(false)
}
}}
onClick={() => handleTimeRangeChange(key)}
className={`px-3 py-1.5 text-xs font-medium transition-colors ${
timeRange === key && !showCustomPicker
? "bg-primary text-primary-foreground"
@@ -229,7 +286,6 @@ export default function DashboardPage() {
</div>
</div>
{/* 点击自定义时显示 */}
{showCustomPicker && (
<div className="flex gap-2 items-center p-1 rounded-md">
<input
@@ -263,9 +319,7 @@ export default function DashboardPage() {
</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
@@ -277,7 +331,6 @@ export default function DashboardPage() {
/>
</div>
{/* 每日交易额 */}
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日交易额</h3>
<SimpleBarChart
@@ -289,7 +342,6 @@ export default function DashboardPage() {
/>
</div>
{/* 每日新增客户 */}
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日新增客户</h3>
<SimpleLineChart
@@ -301,7 +353,6 @@ export default function DashboardPage() {
/>
</div>
{/* 每日提取量 */}
<div className="bg-card rounded-lg border p-4">
<h3 className="font-semibold text-sm mb-4">每日提取量</h3>
<SimpleBarChart
@@ -315,7 +366,6 @@ export default function DashboardPage() {
</div>
</div>
{/*套餐统计 */}
<div className="lg:col-span-1 space-y-4">
<div className="bg-card rounded-lg border">
<div className="p-5 border-b">
@@ -326,31 +376,32 @@ export default function DashboardPage() {
<ResourceItem
label="长效套餐"
active="--"
total="--"
total={extractable ? String(extractable.long) : "--"}
color="bg-blue-500"
/>
<ResourceItem
label="短效套餐"
active="--"
total="--"
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">总可用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}
data={mockUserData}
dataKey="activity"
labelKey="name"
fill="#6366f1"

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
}