Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+542
View File
@@ -0,0 +1,542 @@
/*
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 React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import {
Card,
Spin,
Select,
Button,
Tag,
Table,
Empty,
Toast,
} from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
import { VChart } from '@visactor/react-vchart';
import {
Upload,
CheckCircle2,
XCircle,
AlertTriangle,
Users,
Download,
} from 'lucide-react';
import { API, showError } from '../../helpers';
import { exportToCsv, formatTimestampForCsv } from '../../helpers/exportCsv';
// 时间范围选项(小时):与 admin 后台后端 uploadAuditMaxRangeHours=720 保持一致
const RANGE_OPTIONS_BUILDER = (t) => [
{ label: t('最近 1 小时'), value: 1 },
{ label: t('最近 24 小时'), value: 24 },
{ label: t('最近 7 天'), value: 24 * 7 },
{ label: t('最近 30 天'), value: 24 * 30 },
];
// event 大类筛选下拉
const EVENT_FILTER_BUILDER = (t) => [
{ label: t('全部事件'), value: '' },
{ label: t('成功'), value: 'success' },
{ label: t('失败(全部)'), value: 'failed' },
{ label: t('警告'), value: 'warning' },
// 高频精细原因,便于快速定位
{ label: t('体积超限'), value: 'rejected_size' },
{ label: t('格式不支持'), value: 'rejected_unsupported_format' },
{ label: t('策略禁止'), value: 'rejected_by_policy' },
{ label: t('COS 上传失败'), value: 'rejected_cos_upload_failed' },
{ label: t('文件内容伪装'), value: 'rejected_corrupt_image' },
{ label: t('对话期 URL 失效'), value: 'inline_failed' },
];
// event → 中文短描述(i18n key 同名)
const EVENT_LABEL = (t, evt) => {
if (!evt) return '';
const map = {
success: t('成功'),
rejected_disabled: t('功能未启用'),
rejected_cos_unavailable: t('存储未就绪'),
rejected_missing_file: t('未提供文件'),
rejected_size: t('体积超限'),
rejected_unsupported_format: t('格式不支持'),
rejected_by_policy: t('策略禁止'),
rejected_read_failed: t('读取失败'),
rejected_corrupt_image: t('文件内容伪装'),
rejected_cos_upload_failed: t('COS 上传失败'),
warn_presign_failed: t('预签名失败'),
rejected_foreign_url: t('非法 URL'),
inline_failed: t('对话期 URL 失效'),
};
return map[evt] || evt;
};
const eventColor = (evt) => {
if (evt === 'success') return 'green';
if (evt.startsWith('warn_')) return 'orange';
if (evt === 'inline_failed') return 'red';
if (evt.startsWith('rejected_')) return 'red';
return 'grey';
};
const StatCard = ({ icon, label, value, accent }) => (
<Card className='!rounded-2xl !shadow-sm hover:!shadow-md transition-shadow border border-gray-100 dark:border-gray-700'>
<div className='flex items-center gap-3 p-1'>
<div
className={`w-12 h-12 rounded-xl flex items-center justify-center ${accent}`}
>
{icon}
</div>
<div className='flex flex-col min-w-0'>
<span className='text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide'>
{label}
</span>
<span className='text-2xl font-semibold text-gray-800 dark:text-gray-100 tabular-nums'>
{(value || 0).toLocaleString()}
</span>
</div>
</div>
</Card>
);
export const ExperienceCenterAuditPanel = () => {
const { t } = useTranslation();
useEffect(() => {
initVChartSemiTheme({ isWatchingThemeSwitch: true });
}, []);
const RANGE_OPTIONS = useMemo(() => RANGE_OPTIONS_BUILDER(t), [t]);
const EVENT_FILTERS = useMemo(() => EVENT_FILTER_BUILDER(t), [t]);
const [rangeHours, setRangeHours] = useState(24);
const [eventFilter, setEventFilter] = useState('');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [loading, setLoading] = useState(false);
const [summary, setSummary] = useState(null);
const [trend, setTrend] = useState(null);
const [topUsers, setTopUsers] = useState([]);
const [recent, setRecent] = useState({ items: [], total: 0 });
// 用单调递增的 request id 给"过期请求"的回写打钩。用户快速切 range/filter 时,多次
// loadAll 会并行飞,只有最后一次的结果应该落到 state — 否则慢响应回来会覆盖新数据,
// 出现"下拉显示 7d 但卡片是 1h 数据"的诡异 UI。
const requestIdRef = useRef(0);
// 单次刷新拉全部四块数据(并行)。任何子接口失败不阻塞其他块,避免一处出错全屏白屏
const loadAll = useCallback(async () => {
const myId = ++requestIdRef.current;
setLoading(true);
const errors = [];
const [summaryRes, trendRes, topUsersRes, recentRes] = await Promise.all([
API.get(
`/api/admin/playground/upload-audit/summary?range_hours=${rangeHours}`,
).catch((e) => {
errors.push(['summary', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/trend?range_hours=${rangeHours}&bucket=${rangeHours > 48 ? 'day' : 'hour'}`,
).catch((e) => {
errors.push(['trend', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/top-failing-users?range_hours=${rangeHours}&limit=10`,
).catch((e) => {
errors.push(['top-users', e]);
return null;
}),
API.get(
`/api/admin/playground/upload-audit/recent?range_hours=${rangeHours}&event=${encodeURIComponent(eventFilter)}&page=${page}&page_size=${pageSize}`,
).catch((e) => {
errors.push(['recent', e]);
return null;
}),
]);
// 过期响应直接丢弃:myId 落后于最新 id 说明用户已经发起新请求了
if (myId !== requestIdRef.current) {
return;
}
if (summaryRes?.data?.success) setSummary(summaryRes.data.data);
if (trendRes?.data?.success) setTrend(trendRes.data.data);
if (topUsersRes?.data?.success)
setTopUsers(topUsersRes.data.data?.items || []);
if (recentRes?.data?.success) {
setRecent({
items: recentRes.data.data?.items || [],
total: recentRes.data.data?.total || 0,
});
}
// 多块同时失败时,单独把每一块的错误都告诉用户;showError 内部会去重处理(如果 message 一致)
if (errors.length > 0) {
// 把 4 块名字翻成可读:summary/trend/top-users/recent → 数据看板加载(部分失败)
Toast.warning({
content: t('数据加载部分失败:{{names}}', {
names: errors.map((e) => e[0]).join(', '),
}),
duration: 4,
});
// 同时把第一个 axios 错误细节也打到 Toast,方便定位(401/500 等)
showError(errors[0][1]);
}
setLoading(false);
}, [rangeHours, eventFilter, page, pageSize, t]);
useEffect(() => {
loadAll();
}, [loadAll]);
// ----- 趋势图 spec -----
const chartSpec = useMemo(() => {
const buckets = trend?.buckets || [];
if (buckets.length === 0) return null;
// 转成 vchart 长表
const formatTs = (ts) => {
const d = new Date(ts * 1000);
if (trend?.bucket === 'day') {
return `${d.getMonth() + 1}/${d.getDate()}`;
}
const pad = (n) => ('0' + n).slice(-2);
return `${d.getMonth() + 1}/${d.getDate()} ${pad(d.getHours())}:00`;
};
const chartData = buckets.flatMap((b) => [
{ ts: formatTs(b.ts), type: t('成功'), value: b.success || 0 },
{ ts: formatTs(b.ts), type: t('失败'), value: b.failed || 0 },
{ ts: formatTs(b.ts), type: t('警告'), value: b.warning || 0 },
]);
return {
type: 'bar',
data: [{ id: 'trend', values: chartData }],
xField: 'ts',
yField: 'value',
seriesField: 'type',
stack: true,
bar: { style: { cornerRadius: [3, 3, 0, 0] } },
legends: {
visible: true,
orient: 'top',
position: 'middle',
padding: { top: 0, bottom: 16 },
},
tooltip: {
visible: true,
mark: {
visible: true,
content: [
{
key: (d) => d?.type,
value: (d) => `${(d?.value || 0).toLocaleString()} ${t('次')}`,
},
],
},
dimension: { visible: true },
},
axes: [
{ orient: 'bottom', label: { autoLimit: true, autoRotate: true } },
{ orient: 'left', label: { formatMethod: (v) => v.toLocaleString() } },
],
color: ['#10b981', '#ef4444', '#f59e0b'],
};
}, [trend, t]);
// ----- Recent events table 列定义 -----
const recentColumns = useMemo(
() => [
{
title: t('时间'),
dataIndex: 'created_at',
width: 170,
render: (ts) => formatTimestampForCsv(ts),
},
{
title: t('用户'),
dataIndex: 'username',
width: 160,
render: (v, row) => v || `(${t('用户')} ${row.user_id})`,
},
{
title: t('事件'),
dataIndex: 'event',
width: 160,
render: (evt) => (
<Tag color={eventColor(evt)} size='small' shape='circle'>
{EVENT_LABEL(t, evt)}
</Tag>
),
},
{
title: t('详情'),
dataIndex: 'detail',
ellipsis: { showTitle: true },
render: (v) => (
<span className='text-xs text-gray-600 dark:text-gray-300 font-mono break-all'>
{v || '-'}
</span>
),
},
],
[t],
);
// ----- 导出 CSV:导出当前已加载的 recent 列表 -----
const handleExport = useCallback(() => {
if (!recent.items.length) {
Toast.info({ content: t('没有可导出的记录'), duration: 2 });
return;
}
const cols = [
{
key: 'created_at',
title: t('时间'),
format: (r) => formatTimestampForCsv(r.created_at),
},
{ key: 'user_id', title: 'user_id' },
{ key: 'username', title: t('用户') },
{
key: 'event',
title: t('事件'),
format: (r) => EVENT_LABEL(t, r.event),
},
{ key: 'event_raw', title: t('原始事件 key'), format: (r) => r.event },
{ key: 'detail', title: t('详情') },
];
const filename = `experience_center_upload_audit_${new Date().toISOString().slice(0, 10)}.csv`;
exportToCsv(cols, recent.items, filename);
Toast.success({
content: t('已导出 {{n}} 条', { n: recent.items.length }),
duration: 2,
});
}, [recent.items, t]);
// ----- Top failing users 列定义 -----
const topUsersColumns = useMemo(
() => [
{
title: t('用户'),
dataIndex: 'username',
render: (v, row) => v || `(${t('用户')} ${row.user_id})`,
},
{
title: t('失败次数'),
dataIndex: 'failure_count',
width: 110,
render: (v) => (
<span className='font-mono font-medium text-red-500 tabular-nums'>
{v}
</span>
),
},
{
title: t('主要原因'),
dataIndex: 'top_reason',
render: (evt) => (
<Tag color={eventColor(evt)} size='small' shape='circle'>
{EVENT_LABEL(t, evt)}
</Tag>
),
},
],
[t],
);
const total = summary?.total || 0;
const successRate =
total > 0 ? Math.round(((summary?.success || 0) / total) * 1000) / 10 : 0;
return (
<div className='space-y-5'>
{/* 工具栏:时间范围 + 刷新(标题由父 Tab 提供,不重复展示) */}
<div className='flex flex-wrap items-center justify-end gap-2'>
<Select
value={rangeHours}
onChange={(v) => {
setPage(1);
setRangeHours(v);
}}
optionList={RANGE_OPTIONS}
className='min-w-[140px]'
/>
<Button
theme='light'
icon={<IconRefresh />}
onClick={loadAll}
loading={loading}
>
{t('刷新')}
</Button>
</div>
<Spin spinning={loading} tip={t('加载中…')}>
{/* 四张概览卡 */}
<div className='grid grid-cols-2 md:grid-cols-4 gap-3'>
<StatCard
icon={<Upload className='text-brand' size={22} />}
label={t('总事件数')}
value={total}
accent='bg-brand/5 dark:bg-brand-deep/30'
/>
<StatCard
icon={<CheckCircle2 className='text-emerald-500' size={22} />}
label={t('成功 (率)')}
value={summary?.success}
accent='bg-emerald-50 dark:bg-emerald-900/30'
/>
<StatCard
icon={<XCircle className='text-red-500' size={22} />}
label={t('失败')}
value={summary?.failed}
accent='bg-red-50 dark:bg-red-900/30'
/>
<StatCard
icon={<Users className='text-blue-500' size={22} />}
label={t('涉及用户数')}
value={summary?.distinct_users}
accent='bg-blue-50 dark:bg-blue-900/30'
/>
</div>
{total > 0 && (
<div className='text-xs text-gray-500 dark:text-gray-400 px-1 mt-1'>
{t('成功率 {{rate}}% · 警告 {{w}} · 默认按 {{bucket}} 聚合', {
rate: successRate,
w: (summary?.warning || 0).toLocaleString(),
bucket: rangeHours > 48 ? t('天') : t('小时'),
})}
</div>
)}
{/* 趋势图 */}
<Card
className='!rounded-2xl !shadow-sm border border-gray-100 dark:border-gray-700 mt-4'
title={
<span className='flex items-center gap-2'>
<AlertTriangle size={16} className='text-brand' />
{t('事件趋势')}
</span>
}
>
{chartSpec ? (
<div style={{ height: 320 }}>
<VChart spec={chartSpec} />
</div>
) : (
<Empty description={t('此区间内暂无事件')} />
)}
</Card>
{/* 失败用户 + 最近事件 双列布局(移动端堆叠) */}
<div className='grid grid-cols-1 xl:grid-cols-5 gap-4 mt-4'>
<Card
className='xl:col-span-2 !rounded-2xl !shadow-sm border border-gray-100 dark:border-gray-700'
title={
<span className='flex items-center gap-2'>
<Users size={16} className='text-red-500' />
{t('失败 Top 10 用户')}
</span>
}
>
{topUsers.length === 0 ? (
<Empty description={t('此区间内无失败用户')} />
) : (
<Table
columns={topUsersColumns}
dataSource={topUsers}
pagination={false}
size='small'
rowKey='user_id'
/>
)}
</Card>
<Card
className='xl:col-span-3 !rounded-2xl !shadow-sm border border-gray-100 dark:border-gray-700'
title={
<span className='flex items-center gap-2'>
<Upload size={16} className='text-brand' />
{t('最近事件')}
</span>
}
headerExtraContent={
// Semi 的 .semi-card-header-wrapper 是 row-reverse 且不换行,
// .semi-card 又是 overflow:hidden:160px 的 Select 加导出按钮共约 410px,
// 塞进 358px 的卡片头时「导出本页 CSV」被裁掉且点不到
<div className='flex flex-wrap items-center justify-end gap-2'>
<Select
value={eventFilter}
onChange={(v) => {
setPage(1);
setEventFilter(v);
}}
optionList={EVENT_FILTERS}
className='min-w-[160px]'
size='small'
/>
<Button
theme='borderless'
icon={<Download size={14} />}
onClick={handleExport}
size='small'
>
{t('导出本页 CSV')}
</Button>
</div>
}
>
<Table
columns={recentColumns}
dataSource={recent.items}
size='small'
rowKey='id'
pagination={{
currentPage: page,
pageSize,
total: recent.total,
onPageChange: (p) => setPage(p),
onPageSizeChange: (s) => {
setPage(1);
setPageSize(s);
},
showSizeChanger: true,
pageSizeOpts: [20, 50, 100],
showTotal: true,
}}
empty={<Empty description={t('此区间内暂无事件')} />}
/>
</Card>
</div>
</Spin>
</div>
);
};
export default ExperienceCenterAuditPanel;