Files
monkey-ai-web/src/pages/ServiceDashboard/GroupMonitorAdmin.jsx
T
zhanjunhao e7a7541b2b fix(i18n): 补齐九语翻译并修复国际化检查
补齐历史缺译并统一整句插值。九语覆盖 100%,静态检查及 713 项单测通过。
2026-11-17 14:10:25 +08:00

894 lines
30 KiB
React

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useCallback } from 'react';
import {
Card,
Row,
Col,
Empty,
Spin,
Tag,
Table,
Progress,
Button,
DatePicker,
Space,
} from '@/components/ui';
import {
Activity,
Clock,
Server,
Zap,
AlertTriangle,
CheckCircle,
XCircle,
ChevronDown,
ChevronUp,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, showError } from '../../helpers';
const GroupMonitorAdmin = () => {
const { t, i18n } = useTranslation();
const [groups, setGroups] = useState([]);
const [overview, setOverview] = useState(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [expandedGroups, setExpandedGroups] = useState({});
const [historyData, setHistoryData] = useState({});
const [historyLoading, setHistoryLoading] = useState({});
const [dateRange, setDateRange] = useState({});
// 获取分组监控数据
const fetchGroupData = useCallback(
async (showRefreshIndicator = false) => {
if (showRefreshIndicator) {
setRefreshing(true);
} else {
setLoading(true);
}
try {
const [groupsRes, overviewRes] = await Promise.all([
API.get('/api/monitor/groups/admin'),
API.get('/api/monitor/groups/overview'),
]);
if (groupsRes.data.success) {
setGroups(groupsRes.data.data || []);
} else {
showError(groupsRes.data.message || t('获取分组数据失败'));
}
if (overviewRes.data.success) {
setOverview(overviewRes.data.data);
}
} catch (error) {
showError(error.message || t('网络请求失败'));
} finally {
setLoading(false);
setRefreshing(false);
}
},
[t],
);
// 获取历史趋势数据
const fetchHistoryData = useCallback(
async (groupName, startTime, endTime) => {
setHistoryLoading((prev) => ({ ...prev, [groupName]: true }));
try {
let url = `/api/monitor/groups/${encodeURIComponent(groupName)}/history`;
if (startTime && endTime) {
url += `?start_time=${Math.floor(startTime.getTime() / 1000)}&end_time=${Math.floor(endTime.getTime() / 1000)}`;
} else {
url += '?period=24h';
}
const res = await API.get(url);
if (res.data.success) {
setHistoryData((prev) => ({ ...prev, [groupName]: res.data.data }));
}
} catch (error) {
console.error('获取历史数据失败:', error);
} finally {
setHistoryLoading((prev) => ({ ...prev, [groupName]: false }));
}
},
[],
);
useEffect(() => {
fetchGroupData();
// 每30秒刷新一次数据
const interval = setInterval(() => {
fetchGroupData(true);
}, 30000);
return () => clearInterval(interval);
}, [fetchGroupData]);
// 切换分组展开状态
const toggleGroupExpand = (groupName) => {
setExpandedGroups((prev) => {
const newState = { ...prev, [groupName]: !prev[groupName] };
if (newState[groupName] && !historyData[groupName]) {
fetchHistoryData(groupName);
}
return newState;
});
};
// 处理日期范围变更
const handleDateRangeChange = (groupName, dates) => {
setDateRange((prev) => ({ ...prev, [groupName]: dates }));
if (dates && dates.length === 2) {
fetchHistoryData(groupName, dates[0], dates[1]);
}
};
// 格式化时间戳
const formatTime = (timestamp) => {
if (!timestamp) return '-';
const date = new Date(timestamp * 1000);
return date.toLocaleString(i18n.language, {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
};
// 格式化相对时间
const formatRelativeTime = (timestamp) => {
if (!timestamp) return '-';
const now = Date.now() / 1000;
const diff = now - timestamp;
if (diff < 60) return t('刚刚');
if (diff < 3600) return t('{{n}} 分钟前', { n: Math.floor(diff / 60) });
if (diff < 86400) return t('{{n}} 小时前', { n: Math.floor(diff / 3600) });
return t('{{n}} 天前', { n: Math.floor(diff / 86400) });
};
// 获取健康度颜色
const getHealthColor = (score) => {
if (score >= 90) return 'var(--ui-color-success)';
if (score >= 70) return 'var(--ui-color-warning)';
return 'var(--ui-color-danger)';
};
// 获取状态配置
const getStatusConfig = (status) => {
switch (status) {
case 'healthy':
return {
color: 'green',
icon: <CheckCircle className='w-4 h-4' />,
text: t('健康'),
};
case 'warning':
return {
color: 'orange',
icon: <AlertTriangle className='w-4 h-4' />,
text: t('警告'),
};
case 'critical':
return {
color: 'red',
icon: <XCircle className='w-4 h-4' />,
text: t('严重'),
};
default:
return { color: 'grey', icon: null, text: t('未知') };
}
};
// 获取渠道状态配置
const getChannelStatusConfig = (status) => {
switch (status) {
case 1:
return { color: 'green', text: t('启用') };
case 2:
return { color: 'grey', text: t('手动禁用') };
case 3:
return { color: 'orange', text: t('自动禁用') };
default:
return { color: 'grey', text: t('未知') };
}
};
// 渲染趋势图
const renderTrendChart = (dataPoints, height = 80) => {
if (!dataPoints || dataPoints.length === 0) return null;
const uptimeData = dataPoints.map((p) => p.uptime_percent);
const max = Math.max(...uptimeData, 100);
const min = Math.min(...uptimeData, 0);
const range = max - min || 1;
const points = uptimeData
.map((value, index) => {
const x = (index / (uptimeData.length - 1)) * 100;
const y = 100 - ((value - min) / range) * 100;
return `${x},${y}`;
})
.join(' ');
const avgUptime = uptimeData.reduce((a, b) => a + b, 0) / uptimeData.length;
const lineColor = getHealthColor(avgUptime);
return (
<svg
width='100%'
height={height}
viewBox='0 0 100 100'
preserveAspectRatio='none'
style={{ display: 'block' }}
>
<defs>
<linearGradient
id={`admin-gradient-${avgUptime}`}
x1='0%'
y1='0%'
x2='0%'
y2='100%'
>
<stop
offset='0%'
style={{ stopColor: lineColor, stopOpacity: 0.3 }}
/>
<stop
offset='100%'
style={{ stopColor: lineColor, stopOpacity: 0.05 }}
/>
</linearGradient>
</defs>
<polyline
fill={`url(#admin-gradient-${avgUptime})`}
stroke='none'
points={`0,100 ${points} 100,100`}
/>
<polyline
fill='none'
stroke={lineColor}
strokeWidth='2'
points={points}
/>
</svg>
);
};
// 渠道列定义
const channelColumns = [
{
title: t('渠道名称'),
dataIndex: 'name',
key: 'name',
render: (text, record) => (
<div className='flex items-center gap-2'>
<Server className='w-4 h-4 text-gray-400' />
<span className='font-medium'>{text}</span>
{record.priority > 0 && (
<Tag size='small' color='blue'>
P{record.priority}
</Tag>
)}
</div>
),
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
width: 100,
render: (status) => {
const config = getChannelStatusConfig(status);
return <Tag color={config.color}>{config.text}</Tag>;
},
},
{
title: t('响应时间'),
dataIndex: 'response_time',
key: 'response_time',
width: 120,
render: (time) => {
if (!time) return '-';
let color = 'green';
if (time > 3000) color = 'red';
else if (time > 1000) color = 'orange';
return (
<span
style={{
color:
color === 'green'
? 'var(--ui-color-success)'
: color === 'orange'
? 'var(--ui-color-warning)'
: 'var(--ui-color-danger)',
}}
>
<Zap className='w-3 h-3 inline mr-1' />
{time}
{I18N_TECHNICAL_TEXT.MILLISECONDS}
</span>
);
},
},
{
title: t('最后测试'),
dataIndex: 'test_time',
key: 'test_time',
width: 120,
render: (time) => (
<span className='text-gray-500 text-sm'>
{formatRelativeTime(time)}
</span>
),
},
{
title: t('支持模型'),
dataIndex: 'models',
key: 'models',
render: (models) => (
<div className='flex flex-wrap gap-1'>
{models?.slice(0, 3).map((m, i) => (
<Tag key={i} size='small'>
{m}
</Tag>
))}
{models?.length > 3 && (
<Tag size='small' color='grey'>
+{models.length - 3}
</Tag>
)}
</div>
),
},
];
// 模型统计列定义
const modelColumns = [
{
title: t('模型'),
dataIndex: 'model',
key: 'model',
render: (text) => <Tag>{text}</Tag>,
},
{
title: t('可用率'),
dataIndex: 'uptime_percent',
key: 'uptime_percent',
render: (value) => (
<Progress
percent={value}
size='small'
style={{ width: 100 }}
stroke={getHealthColor(value)}
/>
),
},
{
title: t('可用/总数'),
key: 'count',
render: (_, record) => `${record.available_count}/${record.total_count}`,
},
{
title: t('平均响应'),
dataIndex: 'avg_response_time',
key: 'avg_response_time',
render: (value) => (value > 0 ? `${value}ms` : '-'),
},
];
if (loading) {
return (
<div style={{ textAlign: 'center', padding: '60px 0' }}>
<Spin size='large' />
</div>
);
}
return (
<div className='group-monitor-admin'>
<style>
{`
.overview-card {
transition: all 0.3s;
border-radius: 12px;
}
.overview-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}
.group-admin-card {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
border: 1px solid var(--ui-color-border);
border-radius: 12px;
overflow: hidden;
}
.group-admin-card:hover {
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}
.health-ring {
position: relative;
width: 80px;
height: 80px;
}
.health-ring-bg {
fill: none;
stroke: var(--ui-color-fill-1);
stroke-width: 8;
}
.health-ring-progress {
fill: none;
stroke-width: 8;
stroke-linecap: round;
transform: rotate(-90deg);
transform-origin: 50% 50%;
transition: stroke-dasharray 0.5s ease;
}
.health-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 18px;
font-weight: 600;
}
.stat-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
gap: 12px;
}
.stat-box {
padding: 12px;
background: var(--ui-color-fill-0);
border-radius: 8px;
text-align: center;
}
.stat-box-value {
font-size: 20px;
font-weight: 600;
color: var(--ui-color-text-0);
}
.stat-box-label {
font-size: 12px;
color: var(--ui-color-text-2);
margin-top: 4px;
}
.trend-section {
background: var(--ui-color-fill-0);
border-radius: 8px;
padding: 16px;
margin-top: 16px;
}
`}
</style>
{/* 概览卡片 */}
{overview && (
<Row gutter={[16, 16]} className='mb-6'>
<Col xs={12} sm={6}>
<Card
className='overview-card'
styles={{ body: { padding: '20px', textAlign: 'center' } }}
>
<div className='text-3xl font-bold text-blue-500'>
{overview.total_groups}
</div>
<div className='text-gray-500 mt-1'>{t('分组总数')}</div>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card
className='overview-card'
styles={{ body: { padding: '20px', textAlign: 'center' } }}
>
<div className='text-3xl font-bold text-green-500'>
{overview.healthy_groups}
</div>
<div className='text-gray-500 mt-1'>{t('健康分组')}</div>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card
className='overview-card'
styles={{ body: { padding: '20px', textAlign: 'center' } }}
>
<div className='text-3xl font-bold text-orange-500'>
{overview.warning_groups}
</div>
<div className='text-gray-500 mt-1'>{t('警告分组')}</div>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card
className='overview-card'
styles={{ body: { padding: '20px', textAlign: 'center' } }}
>
<div
className='text-3xl font-bold'
style={{ color: getHealthColor(overview.average_uptime) }}
>
{overview.average_uptime.toFixed(1)}%
</div>
<div className='text-gray-500 mt-1'>{t('平均可用率')}</div>
</Card>
</Col>
</Row>
)}
{/* 刷新按钮 */}
<div className='flex justify-end mb-4'>
<Button
icon={
<ActionRefreshCw
className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`}
/>
}
onClick={() => fetchGroupData(true)}
loading={refreshing}
>
{t('刷新')}
</Button>
</div>
{groups.length === 0 ? (
<Empty description={t('暂无分组数据')} />
) : (
<Row gutter={[16, 16]}>
{groups.map((group) => {
const isExpanded = expandedGroups[group.name];
const statusConfig = getStatusConfig(group.status);
const groupHistory = historyData[group.name];
const isHistoryLoading = historyLoading[group.name];
return (
<Col key={group.name} xs={24}>
<Card
className='group-admin-card'
styles={{ body: { padding: 0 } }}
>
{/* 分组头部 */}
<div
className='p-4 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors'
onClick={() => toggleGroupExpand(group.name)}
>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-4'>
{/* 健康度环形图 */}
<div className='health-ring'>
<svg viewBox='0 0 100 100'>
<circle
className='health-ring-bg'
cx='50'
cy='50'
r='40'
/>
<circle
className='health-ring-progress'
cx='50'
cy='50'
r='40'
stroke={getHealthColor(group.health_score)}
strokeDasharray={`${group.health_score * 2.51} 251`}
/>
</svg>
<span
className='health-text'
style={{
color: getHealthColor(group.health_score),
}}
>
{Math.round(group.health_score)}
</span>
</div>
<div>
<div className='flex items-center gap-2'>
<h3 className='text-xl font-semibold m-0'>
{group.name}
</h3>
<Tag color={statusConfig.color}>
{statusConfig.icon}
<span className='ml-1'>{statusConfig.text}</span>
</Tag>
</div>
<div className='flex items-center gap-4 mt-2 text-sm text-gray-500'>
<span>
<Clock className='w-4 h-4 inline mr-1' />
{t('最后测试')}:{' '}
{formatRelativeTime(group.last_test_time)}
</span>
<span>
<Server className='w-4 h-4 inline mr-1' />
{group.available_count}/{group.total_channels}{' '}
{t('可用')}
</span>
{group.auto_disabled_count > 0 && (
<span className='text-orange-500'>
<AlertTriangle className='w-4 h-4 inline mr-1' />
{group.auto_disabled_count} {t('自动禁用')}
</span>
)}
</div>
</div>
</div>
<div className='flex items-center gap-6'>
{/* 快速统计 */}
<div className='hidden md:flex items-center gap-6'>
<div className='text-center'>
<div
className='text-2xl font-bold'
style={{
color: getHealthColor(group.uptime_percent),
}}
>
{group.uptime_percent.toFixed(1)}%
</div>
<div className='text-xs text-gray-500'>
{t('可用率')}
</div>
</div>
<div className='text-center'>
<div className='text-2xl font-bold text-blue-500'>
{group.avg_response_time || '-'}
<span className='text-sm font-normal'>
{I18N_TECHNICAL_TEXT.MILLISECONDS}
</span>
</div>
<div className='text-xs text-gray-500'>
{t('平均响应')}
</div>
</div>
<div className='text-center'>
<div className='text-2xl font-bold text-brand'>
{group.models?.length || 0}
</div>
<div className='text-xs text-gray-500'>
{t('模型数')}
</div>
</div>
</div>
{isExpanded ? (
<ChevronUp className='w-6 h-6 text-gray-400' />
) : (
<ChevronDown className='w-6 h-6 text-gray-400' />
)}
</div>
</div>
</div>
{/* 展开详情 */}
{isExpanded && (
<div className='border-t border-gray-200 dark:border-gray-700'>
{/* 详细统计 */}
<div className='p-4 bg-gray-50 dark:bg-gray-800'>
<div className='stat-grid'>
<div className='stat-box'>
<div
className='stat-box-value'
style={{
color: getHealthColor(group.uptime_percent),
}}
>
{group.uptime_percent.toFixed(1)}%
</div>
<div className='stat-box-label'>{t('可用率')}</div>
</div>
<div className='stat-box'>
<div className='stat-box-value text-green-500'>
{group.available_count}
</div>
<div className='stat-box-label'>
{t('可用渠道')}
</div>
</div>
<div className='stat-box'>
<div className='stat-box-value text-gray-500'>
{group.disabled_count}
</div>
<div className='stat-box-label'>
{t('禁用渠道')}
</div>
</div>
<div className='stat-box'>
<div className='stat-box-value text-orange-500'>
{group.auto_disabled_count}
</div>
<div className='stat-box-label'>
{t('自动禁用')}
</div>
</div>
<div className='stat-box'>
<div className='stat-box-value text-blue-500'>
{group.avg_response_time || '-'}
{I18N_TECHNICAL_TEXT.MILLISECONDS}
</div>
<div className='stat-box-label'>
{t('平均响应')}
</div>
</div>
<div className='stat-box'>
<div className='stat-box-value text-red-500'>
{group.max_response_time || '-'}
{I18N_TECHNICAL_TEXT.MILLISECONDS}
</div>
<div className='stat-box-label'>
{t('最慢响应')}
</div>
</div>
<div className='stat-box'>
<div className='stat-box-value text-green-500'>
{group.min_response_time || '-'}
{I18N_TECHNICAL_TEXT.MILLISECONDS}
</div>
<div className='stat-box-label'>
{t('最快响应')}
</div>
</div>
<div className='stat-box'>
<div className='stat-box-value text-brand'>
{group.models?.length || 0}
</div>
<div className='stat-box-label'>
{t('支持模型')}
</div>
</div>
</div>
{/* 时间选择器 */}
<div className='flex items-center gap-4 mt-4'>
<span className='text-sm font-medium'>
{t('趋势时间范围')}:
</span>
<DatePicker
type='dateTimeRange'
style={{ width: 320 }}
value={dateRange[group.name]}
onChange={(dates) =>
handleDateRangeChange(group.name, dates)
}
placeholder={[t('开始时间'), t('结束时间')]}
/>
<Space>
<Button
size='small'
onClick={() => {
const now = new Date();
const start = new Date(
now.getTime() - 24 * 60 * 60 * 1000,
);
handleDateRangeChange(group.name, [start, now]);
}}
>
{I18N_TECHNICAL_TEXT.LAST_24_HOURS}
</Button>
<Button
size='small'
onClick={() => {
const now = new Date();
const start = new Date(
now.getTime() - 7 * 24 * 60 * 60 * 1000,
);
handleDateRangeChange(group.name, [start, now]);
}}
>
{I18N_TECHNICAL_TEXT.LAST_7_DAYS}
</Button>
<Button
size='small'
onClick={() => {
const now = new Date();
const start = new Date(
now.getTime() - 30 * 24 * 60 * 60 * 1000,
);
handleDateRangeChange(group.name, [start, now]);
}}
>
{I18N_TECHNICAL_TEXT.LAST_30_DAYS}
</Button>
</Space>
</div>
{/* 趋势图 */}
{isHistoryLoading ? (
<div className='text-center py-4'>
<Spin />
</div>
) : (
groupHistory?.data_points && (
<div className='trend-section'>
<div className='flex items-center justify-between mb-2'>
<span className='text-sm font-medium'>
<Activity className='w-4 h-4 inline mr-1' />
{t('可用率趋势')}
</span>
<span className='text-xs text-gray-500'>
{formatTime(groupHistory.start_time)} -{' '}
{formatTime(groupHistory.end_time)}
</span>
</div>
{renderTrendChart(groupHistory.data_points, 100)}
</div>
)
)}
</div>
{/* 模型统计 */}
<div className='p-4 border-t border-gray-200 dark:border-gray-700'>
<h4 className='text-sm font-semibold mb-3'>
{t('模型可用性统计')}
</h4>
<Table
columns={modelColumns}
dataSource={group.model_stats || []}
pagination={false}
size='small'
rowKey='model'
/>
</div>
{/* 渠道列表 */}
<div className='p-4 border-t border-gray-200 dark:border-gray-700'>
<h4 className='text-sm font-semibold mb-3'>
{t('渠道详情')}
</h4>
<Table
columns={channelColumns}
dataSource={group.channels || []}
pagination={{ pageSize: 10 }}
size='small'
rowKey='id'
/>
</div>
</div>
)}
</Card>
</Col>
);
})}
</Row>
)}
</div>
);
};
export default GroupMonitorAdmin;