StatisticsDashboard.tsx
13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import { useEffect, useState, useCallback } from 'react';
import { Card, Row, Col, Statistic, Space, Segmented, DatePicker, Spin, Empty, Button } from 'antd';
import {
ReloadOutlined,
ClockCircleOutlined,
ThunderboltOutlined,
RiseOutlined,
DatabaseOutlined,
AppstoreOutlined,
BarChartOutlined,
} from '@ant-design/icons';
import {
XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
Area, AreaChart, BarChart, Bar, Legend,
} from 'recharts';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { statisticsService } from '../../services/statisticsService';
dayjs.locale('zh-cn');
const { RangePicker } = DatePicker;
type RangeKey = '7d' | '30d' | '90d' | 'custom';
type Granularity = 'hourly' | 'daily';
const RANGE_PRESETS: { key: RangeKey; label: string; days: number }[] = [
{ key: '7d', label: '7天', days: 7 },
{ key: '30d', label: '30天', days: 30 },
{ key: '90d', label: '90天', days: 90 },
];
interface TrendItem {
time: string;
total_calls: number;
success_count: number;
fail_count: number;
success_rate: number;
avg_latency: number;
total_tokens: number;
}
interface ModelStat {
model_name: string;
total_calls: number;
success_rate: number;
total_tokens: number;
}
interface AccountStat {
account_name: string;
total_calls: number;
success_rate: number;
total_tokens: number;
}
export default function StatisticsDashboard() {
const [rangeKey, setRangeKey] = useState<RangeKey>('30d');
const [customRange, setCustomRange] = useState<[string, string] | null>(null);
const [granularity, setGranularity] = useState<Granularity>('daily');
const [loading, setLoading] = useState(false);
const [overview, setOverview] = useState<any>({});
const [trends, setTrends] = useState<TrendItem[]>([]);
const [byModel, setByModel] = useState<ModelStat[]>([]);
const [byAccount, setByAccount] = useState<AccountStat[]>([]);
const getDateRange = useCallback((): [string, string] => {
if (rangeKey === 'custom' && customRange) {
return customRange;
}
const preset = RANGE_PRESETS.find((p) => p.key === rangeKey) || RANGE_PRESETS[0];
return [
dayjs().subtract(preset.days, 'day').startOf('day').toISOString(),
dayjs().endOf('day').toISOString(),
];
}, [rangeKey, customRange]);
// 7天内默认按小时,否则按天
useEffect(() => {
if (rangeKey === '7d' || (rangeKey === 'custom' && customRange)) {
const [s, e] = getDateRange();
const days = dayjs(e).diff(dayjs(s), 'day');
setGranularity(days <= 7 ? 'hourly' : 'daily');
} else if (rangeKey === '30d' || rangeKey === '90d') {
setGranularity('daily');
}
}, [rangeKey, customRange, getDateRange]);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const [startTime, endTime] = getDateRange();
const [ov, tr, md, ac] = await Promise.all([
statisticsService.getSummary(startTime, endTime),
statisticsService.getTrends(startTime, endTime, granularity),
statisticsService.getByModel(startTime, endTime, 10),
statisticsService.getByAccount(startTime, endTime, 10),
]);
setOverview(ov || {});
setTrends(Array.isArray(tr) ? tr : []);
setByModel(Array.isArray(md) ? md : []);
setByAccount(Array.isArray(ac) ? ac : []);
} catch (err) {
console.error('获取统计数据失败', err);
} finally {
setLoading(false);
}
}, [getDateRange, granularity]);
useEffect(() => {
fetchData();
}, [fetchData]);
const formatTrendTime = (t: string) => {
if (granularity === 'hourly') return dayjs(t).format('DD日 HH:mm');
return dayjs(t).format('MM-DD');
};
const successRate = overview?.success_rate ?? 0;
return (
<>
<div className="page-header">
<div className="page-header-left">
<h4 className="page-header-title">调用统计</h4>
<span className="page-header-desc">查看模型调用的统计数据、趋势和分布情况</span>
</div>
<div className="page-header-actions">
<Button icon={<ReloadOutlined />} onClick={fetchData} loading={loading} className="action-btn">刷新</Button>
</div>
</div>
<div style={{ padding: 0 }}>
{/* 时间范围选择器 */}
<Card className="page-card" style={{ marginBottom: 16 }}>
<div style={{ padding: '10px 0' }}>
<Space wrap>
<Segmented
value={rangeKey}
onChange={(v) => {
setRangeKey(v as RangeKey);
if (v !== 'custom') setCustomRange(null);
}}
options={[
...RANGE_PRESETS.map((p) => ({ label: p.label, value: p.key })),
{ label: '自定义', value: 'custom' as RangeKey },
]}
/>
{rangeKey === 'custom' && (
<RangePicker
onChange={(dates) => {
if (dates && dates[0] && dates[1]) {
setCustomRange([dates[0].startOf('day').toISOString(), dates[1].endOf('day').toISOString()]);
}
}}
/>
)}
{loading && <Spin size="small" style={{ marginLeft: 4 }} />}
</Space>
</div>
</Card>
{/* 概览统计卡片 */}
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col xs={12} sm={12} md={6}>
<Card className="page-card" bodyStyle={{ padding: '18px 20px' }}>
<Statistic
title={<span className="stat-label">总调用次数</span>}
value={overview?.total_calls || 0}
prefix={<ThunderboltOutlined className="stat-icon-primary" />}
valueStyle={{ fontWeight: 600, fontSize: 24 }}
/>
</Card>
</Col>
<Col xs={12} sm={12} md={6}>
<Card className="page-card" bodyStyle={{ padding: '18px 20px' }}>
<Statistic
title={<span className="stat-label">成功率</span>}
value={successRate}
precision={1}
suffix="%"
prefix={<RiseOutlined className={successRate >= 95 ? 'stat-icon-success' : 'stat-icon-warning'} />}
valueStyle={{ color: successRate >= 95 ? 'var(--color-success)' : 'var(--color-warning)', fontWeight: 600, fontSize: 24 }}
/>
</Card>
</Col>
<Col xs={12} sm={12} md={6}>
<Card className="page-card" bodyStyle={{ padding: '18px 20px' }}>
<Statistic
title={<span className="stat-label">平均耗时</span>}
value={overview?.avg_duration_ms || 0}
suffix="ms"
precision={0}
prefix={<ClockCircleOutlined className="stat-icon-warning" />}
valueStyle={{ fontWeight: 600, fontSize: 24 }}
/>
</Card>
</Col>
<Col xs={12} sm={12} md={6}>
<Card className="page-card" bodyStyle={{ padding: '18px 20px' }}>
<Statistic
title={<span className="stat-label">Token 消耗</span>}
value={overview?.total_tokens || 0}
prefix={<DatabaseOutlined className="stat-icon-purple" />}
valueStyle={{ fontWeight: 600, fontSize: 24 }}
/>
</Card>
</Col>
</Row>
{/* 趋势折线图 */}
<Card className="page-card" style={{ marginBottom: 16 }}>
<div className="page-card-title-row">
<Space>
<BarChartOutlined />
<span>调用趋势</span>
</Space>
<Segmented
size="small"
value={granularity}
onChange={(v) => setGranularity(v as Granularity)}
options={[
{ label: '按小时', value: 'hourly' },
{ label: '按天', value: 'daily' },
]}
/>
</div>
<div style={{ padding: 16 }}>
{trends.length === 0 ? (
<Empty description="暂无趋势数据" />
) : (
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={trends}>
<defs>
<linearGradient id="colorCalls" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#6366f1" stopOpacity={0.15} />
<stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
</linearGradient>
<linearGradient id="colorSuccess" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#22c55e" stopOpacity={0.15} />
<stop offset="95%" stopColor="#22c55e" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey="time" tickFormatter={formatTrendTime} fontSize={12} stroke="#9ca3af" />
<YAxis fontSize={12} stroke="#9ca3af" />
<Tooltip
labelFormatter={(l) => dayjs(l).format('YYYY-MM-DD HH:mm')}
contentStyle={{ borderRadius: 8, border: '1px solid #e5e7eb', boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}
/>
<Legend />
<Area type="monotone" dataKey="total_calls" name="总调用" stroke="#6366f1" fill="url(#colorCalls)" strokeWidth={2} />
<Area type="monotone" dataKey="success_count" name="成功" stroke="#22c55e" fill="url(#colorSuccess)" strokeWidth={2} />
<Area type="monotone" dataKey="fail_count" name="失败" stroke="#ef4444" fill="none" strokeWidth={2} strokeDasharray="4 4" />
</AreaChart>
</ResponsiveContainer>
)}
</div>
</Card>
{/* 模型分布 + 账号分布 */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<Card className="page-card">
<div className="page-card-title-row">
<Space>
<DatabaseOutlined />
<span>模型调用分布</span>
</Space>
</div>
<div style={{ padding: 16 }}>
{byModel.length === 0 ? (
<Empty description="暂无数据" />
) : (
<ResponsiveContainer width="100%" height={280}>
<BarChart data={byModel} layout="vertical" margin={{ left: 80 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis type="number" fontSize={12} stroke="#9ca3af" />
<YAxis type="category" dataKey="model_name" fontSize={12} stroke="#9ca3af" width={80} tickFormatter={(v) => v.length > 12 ? `${v.slice(0, 12)}...` : v} />
<Tooltip
formatter={(value: number, name: string) => {
if (name === 'success_rate') return [`${value}%`, '成功率'];
return [value, name === 'total_calls' ? '调用次数' : 'Token 总量'];
}}
contentStyle={{ borderRadius: 8, border: '1px solid #e5e7eb' }}
/>
<Legend />
<Bar dataKey="total_calls" name="调用次数" fill="#6366f1" radius={[0, 4, 4, 0]} />
<Bar dataKey="total_tokens" name="Token 总量" fill="#8b5cf6" radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
)}
</div>
</Card>
</Col>
<Col xs={24} md={12}>
<Card className="page-card">
<div className="page-card-title-row">
<Space>
<AppstoreOutlined />
<span>账号调用分布</span>
</Space>
</div>
<div style={{ padding: 16 }}>
{byAccount.length === 0 ? (
<Empty description="暂无数据" />
) : (
<ResponsiveContainer width="100%" height={280}>
<BarChart data={byAccount} layout="vertical" margin={{ left: 80 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis type="number" fontSize={12} stroke="#9ca3af" />
<YAxis type="category" dataKey="account_name" fontSize={12} stroke="#9ca3af" width={80} tickFormatter={(v) => v.length > 12 ? `${v.slice(0, 12)}...` : v} />
<Tooltip
formatter={(value: number, name: string) => {
if (name === 'success_rate') return [`${value}%`, '成功率'];
return [value, name === 'total_calls' ? '调用次数' : 'Token 总量'];
}}
contentStyle={{ borderRadius: 8, border: '1px solid #e5e7eb' }}
/>
<Legend />
<Bar dataKey="total_calls" name="调用次数" fill="#06b6d4" radius={[0, 4, 4, 0]} />
<Bar dataKey="total_tokens" name="Token 总量" fill="#14b8a6" radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
)}
</div>
</Card>
</Col>
</Row>
</div>
</>
);
}