/* 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 . For commercial licensing, please contact support@quantumnous.com */ import { Download as ActionDownload } from '@/components/common/icons/ActionIcons'; import React, { useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { useTranslation } from 'react-i18next'; import { Card, Spin, Select, Button, Tag, Table, Empty, Toast, } from '@/components/ui'; import { IconRefresh } from '@/components/ui/icons'; import { initVChartTheme } from '@/components/ui/chartTheme'; import { VChart } from '@visactor/react-vchart'; import { Upload, CheckCircle2, XCircle, AlertTriangle, Users, } 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 }) => (
{icon}
{label} {(value || 0).toLocaleString()}
); export const ExperienceCenterAuditPanel = () => { const { t } = useTranslation(); useEffect(() => { initVChartTheme({ 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) => t('{{n}} 次', { n: (d?.value || 0).toLocaleString(), count: d?.value || 0, }), }, ], }, 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('用户 {{id}}', { id: row.user_id })})`, }, { title: t('事件'), dataIndex: 'event', width: 160, render: (evt) => ( {EVENT_LABEL(t, evt)} ), }, { title: t('详情'), dataIndex: 'detail', ellipsis: { showTitle: true }, render: (v) => ( {v || '-'} ), }, ], [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, count: recent.items.length, }), duration: 2, }); }, [recent.items, t]); // ----- Top failing users 列定义 ----- const topUsersColumns = useMemo( () => [ { title: t('用户'), dataIndex: 'username', render: (v, row) => v || `(${t('用户 {{id}}', { id: row.user_id })})`, }, { title: t('失败次数'), dataIndex: 'failure_count', width: 110, render: (v) => ( {v} ), }, { title: t('主要原因'), dataIndex: 'top_reason', render: (evt) => ( {EVENT_LABEL(t, evt)} ), }, ], [t], ); const total = summary?.total || 0; const successRate = total > 0 ? Math.round(((summary?.success || 0) / total) * 1000) / 10 : 0; return (
{/* 工具栏:时间范围 + 刷新(标题由父 Tab 提供,不重复展示) */}
{ setPage(1); setEventFilter(v); }} optionList={EVENT_FILTERS} className='min-w-[160px]' size='small' />
} > setPage(p), onPageSizeChange: (s) => { setPage(1); setPageSize(s); }, showSizeChanger: true, pageSizeOpts: [20, 50, 100], showTotal: true, }} empty={} /> ); }; export default ExperienceCenterAuditPanel;