import { useEffectEvent } from '../common/useEffectEvent'; import { useState, useEffect, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { Modal } from '@/components/ui'; import { API, getTodayStartTimestamp, isAdmin, isRoot, showError, showSuccess, timestamp2string, getLogOther, copy, } from '../../helpers'; import { ITEMS_PER_PAGE } from '../../constants'; import { useTableCompactMode } from '../common/useTableCompactMode'; import { EVENTS, subscribe } from '../../helpers/eventBus'; import { resolveColumnVisibility } from '../../helpers/columnVisibility'; export const useLogsData = () => { const { t } = useTranslation(); // Define column keys for selection const COLUMN_KEYS = { TIME: 'time', CHANNEL: 'channel', USERNAME: 'username', TOKEN: 'token', GROUP: 'group', TYPE: 'type', MODEL: 'model', USE_TIME: 'use_time', PROMPT: 'prompt', COMPLETION: 'completion', COST: 'cost', RETRY: 'retry', IP: 'ip', DETAILS: 'details', }; // Basic state const [logs, setLogs] = useState([]); const [expandData, setExpandData] = useState({}); const [showStat, setShowStat] = useState(false); const [loading, setLoading] = useState(false); const [loadingStat, setLoadingStat] = useState(false); const [activePage, setActivePage] = useState(1); const [logCount, setLogCount] = useState(0); const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE); // logType 由表单管理(field='logType'),不再维护独立的 React state —— 避免双真源导致的刷新时机错位 // User and admin const isAdminUser = isAdmin(); const isRootUser = isRoot(); // Role-specific storage key to prevent different roles from overwriting each other const STORAGE_KEY = isAdminUser ? 'logs-table-columns-admin' : 'logs-table-columns-user'; // Statistics state const [stat, setStat] = useState({ quota: 0, rpm: 0, tpm: 0, }); // Form state const [formApi, setFormApi] = useState(null); // 每次调用都返回"此刻"的默认时间范围,避免长时间驻留页面后 // 点击"重置"仍得到页面加载时的"今日"(跨日 bug) const getFreshDateRange = () => [ timestamp2string(getTodayStartTimestamp()), timestamp2string(new Date().getTime() / 1000 + 3600), ]; const getFreshInitValues = () => ({ username: '', token_name: '', model_name: '', channel: '', group: '', user_id: '', dateRange: getFreshDateRange(), logType: '0', }); // URL → 初始表单值:支持分享携带过滤条件的链接 // 与 task-logs 的字段不同前缀/冲突:channel vs channel_id、user_id 两边都会读 const URL_SYNC_FIELDS = [ 'username', 'token_name', 'model_name', 'channel', 'group', 'user_id', 'logType', ]; // 用 ref 锁定挂载时刻的 URL 值,后续 render 不再重读 window.location const initialFormValuesRef = useRef(null); if (initialFormValuesRef.current === null) { const fresh = getFreshInitValues(); if (typeof window !== 'undefined') { const sp = new URLSearchParams(window.location.search); URL_SYNC_FIELDS.forEach((key) => { const v = sp.get(key); if (v != null && v !== '') fresh[key] = v; }); // 错误日志仅管理员可见:非管理员经分享链接携带 logType=5 时归一化回"全部" if (!isAdminUser && fresh.logType === '5') fresh.logType = '0'; } initialFormValuesRef.current = fresh; } const formInitValues = initialFormValuesRef.current; // Column visibility state const [visibleColumns, setVisibleColumns] = useState({}); const [showColumnSelector, setShowColumnSelector] = useState(false); // Compact mode const [compactMode, setCompactMode] = useTableCompactMode('logs'); // User info modal state const [showUserInfo, setShowUserInfoModal] = useState(false); const [userInfoData, setUserInfoData] = useState(null); // 导出弹窗状态 const [showExportModal, setShowExportModal] = useState(false); // 记录「最近一次成功查询」所用的筛选条件,导出「全部筛选结果」时复用, // 确保导出结果与当前表格展示(及统计总数 logCount)严格一致, // 而非读取可能被编辑却未点「查询」的实时表单值 const appliedExportParamsRef = useRef(null); // 按当前已应用筛选条件拉取用于导出的全部日志(不分页,后端最多返回 logExportLimit 条) // 返回 { items, total, limit, truncated } 或 null(失败/尚未查询) const fetchLogsForExport = async () => { const applied = appliedExportParamsRef.current; if (!applied) { showError(t('请先查询后再导出')); return null; } const params = new URLSearchParams({ type: applied.type || 0, token_name: applied.token_name, model_name: applied.model_name, start_timestamp: applied.start_timestamp, end_timestamp: applied.end_timestamp, group: applied.group, }); let url; if (isAdminUser) { params.set('username', applied.username); params.set('channel', applied.channel); params.set('user_id', applied.user_id); url = `/api/log/export?${params.toString()}`; } else { url = `/api/log/self/export?${params.toString()}`; } try { const res = await API.get(url); const { success, message, data } = res.data; if (!success) { showError(message); return null; } return data; } catch (err) { showError(err.message); return null; } }; // Load saved column preferences from localStorage const onMount = useEffectEvent(() => { const savedColumns = localStorage.getItem(STORAGE_KEY); setVisibleColumns( resolveColumnVisibility( getDefaultColumnVisibility(), savedColumns, isAdminUser ? [] : [COLUMN_KEYS.CHANNEL, COLUMN_KEYS.USERNAME, COLUMN_KEYS.RETRY], ), ); }); useEffect(() => onMount(), [onMount]); // Get default column visibility based on user role const getDefaultColumnVisibility = () => { return { [COLUMN_KEYS.TIME]: true, [COLUMN_KEYS.CHANNEL]: isAdminUser, [COLUMN_KEYS.USERNAME]: isAdminUser, [COLUMN_KEYS.TOKEN]: true, [COLUMN_KEYS.GROUP]: true, [COLUMN_KEYS.TYPE]: true, [COLUMN_KEYS.MODEL]: true, [COLUMN_KEYS.USE_TIME]: true, [COLUMN_KEYS.PROMPT]: true, [COLUMN_KEYS.COMPLETION]: true, [COLUMN_KEYS.COST]: true, [COLUMN_KEYS.RETRY]: isAdminUser, [COLUMN_KEYS.IP]: true, [COLUMN_KEYS.DETAILS]: true, }; }; // Initialize default column visibility const initDefaultColumns = () => { const defaults = getDefaultColumnVisibility(); setVisibleColumns(defaults); localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults)); }; // Handle column visibility change const handleColumnVisibilityChange = (columnKey, checked) => { const updatedColumns = { ...visibleColumns, [columnKey]: checked }; setVisibleColumns(updatedColumns); }; // Handle "Select All" checkbox const handleSelectAll = (checked) => { const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]); const updatedColumns = {}; allKeys.forEach((key) => { if ( (key === COLUMN_KEYS.CHANNEL || key === COLUMN_KEYS.USERNAME || key === COLUMN_KEYS.RETRY) && !isAdminUser ) { updatedColumns[key] = false; } else { updatedColumns[key] = checked; } }); setVisibleColumns(updatedColumns); }; // Persist column settings to the role-specific STORAGE_KEY useEffect(() => { if (Object.keys(visibleColumns).length > 0) { localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns)); } }, [visibleColumns, STORAGE_KEY]); // 获取表单值的辅助函数,确保所有值都是字符串 const getFormValues = () => { // formApi 未就绪时回落到 URL 派生的初始值,避免首次 loadLogs 丢掉 ?username=xxx 等过滤条件 const formValues = formApi ? formApi.getValues() : formInitValues; // 每次调用取"此刻"的默认值,避免闭包陈旧 const [freshStart, freshEnd] = getFreshDateRange(); let start_timestamp = freshStart; let end_timestamp = freshEnd; if ( formValues.dateRange && Array.isArray(formValues.dateRange) && formValues.dateRange.length === 2 ) { start_timestamp = formValues.dateRange[0]; end_timestamp = formValues.dateRange[1]; } // 所有字符串字段做 trim,避免复制粘贴带上首尾空格导致精确匹配失败 return { username: (formValues.username || '').trim(), token_name: (formValues.token_name || '').trim(), model_name: (formValues.model_name || '').trim(), start_timestamp, end_timestamp, channel: (formValues.channel || '').trim(), group: (formValues.group || '').trim(), // user_id 额外剥离非数字(兼容 IME/中文输入法粘贴绕过 onKeyDown) user_id: (formValues.user_id || '').toString().replace(/\D/g, ''), logType: formValues.logType ? parseInt(formValues.logType) : 0, }; }; // Statistics functions const statRequest = useRef(0); const getLogSelfStat = async (signal, requestId) => { const { token_name, model_name, start_timestamp, end_timestamp, group, logType: formLogType, } = getFormValues(); // 表单是唯一真源:getFormValues 已保证返回数字,未定义则为 0 const currentLogType = formLogType || 0; let localStartTimestamp = Date.parse(start_timestamp) / 1000; let localEndTimestamp = Date.parse(end_timestamp) / 1000; const params = new URLSearchParams({ type: currentLogType, token_name, model_name, start_timestamp: localStartTimestamp, end_timestamp: localEndTimestamp, group, }); const url = `/api/log/self/stat?${params.toString()}`; const res = await API.get(url, { signal }); if (signal?.aborted || requestId !== statRequest.current) return; const { success, message, data } = res.data; if (success) { setStat(data); } else { showError(message); } }; const getLogStat = async (signal, requestId) => { const { username, token_name, model_name, start_timestamp, end_timestamp, channel, group, user_id, logType: formLogType, } = getFormValues(); // 表单唯一真源 const currentLogType = formLogType || 0; let localStartTimestamp = Date.parse(start_timestamp) / 1000; let localEndTimestamp = Date.parse(end_timestamp) / 1000; const params = new URLSearchParams({ type: currentLogType, username, token_name, model_name, start_timestamp: localStartTimestamp, end_timestamp: localEndTimestamp, channel, group, user_id, }); const url = `/api/log/stat?${params.toString()}`; const res = await API.get(url, { signal }); if (signal?.aborted || requestId !== statRequest.current) return; const { success, message, data } = res.data; if (success) { setStat(data); } else { showError(message); } }; const handleEyeClick = async (signal) => { const requestId = ++statRequest.current; setLoadingStat(true); try { const getStat = isAdminUser ? getLogStat : getLogSelfStat; await getStat(signal, requestId); if (!signal?.aborted && requestId === statRequest.current) setShowStat(true); } catch (error) { if (!signal?.aborted && !error.isAxiosError) showError(error); } finally { if (requestId === statRequest.current) setLoadingStat(false); } }; // User info function const showUserInfoFunc = async (userId) => { if (!isAdminUser) { return; } const res = await API.get(`/api/user/${userId}`); const { success, message, data } = res.data; if (success) { setUserInfoData(data); setShowUserInfoModal(true); } else { showError(message); } }; // Format logs data const setLogsFormat = (logs) => { let expandDatesLocal = {}; for (let i = 0; i < logs.length; i++) { logs[i].timestamp2string = timestamp2string(logs[i].created_at); logs[i].key = logs[i].id; let other = getLogOther(logs[i].other); let expandDataLocal = []; if (isAdminUser && (logs[i].type === 0 || logs[i].type === 2)) { expandDataLocal.push({ key: t('渠道信息'), value: `${logs[i].channel} - ${logs[i].channel_name || t('[未知]')}`, }); } if (other?.ws || other?.audio) { expandDataLocal.push({ key: t('语音输入'), value: other.audio_input, }); expandDataLocal.push({ key: t('语音输出'), value: other.audio_output, }); expandDataLocal.push({ key: t('文字输入'), value: other.text_input, }); expandDataLocal.push({ key: t('文字输出'), value: other.text_output, }); } if (other?.cache_tokens > 0) { expandDataLocal.push({ key: t('缓存 Tokens'), value: other.cache_tokens, }); } if (other?.cache_creation_tokens > 0) { expandDataLocal.push({ key: t('缓存创建 Tokens'), value: other.cache_creation_tokens, }); } if (logs[i].type === 2) { expandDataLocal.push({ key: t('日志详情'), value: t('查看简化计费摘要'), }); if (logs[i]?.content) { expandDataLocal.push({ key: t('其他详情'), value: logs[i].content, }); } } if (logs[i].type === 2) { let modelMapped = other?.is_model_mapped && other?.upstream_model_name && other?.upstream_model_name !== ''; if (isRootUser && modelMapped) { expandDataLocal.push({ key: t('请求并计费模型'), value: logs[i].model_name, }); expandDataLocal.push({ key: t('实际模型'), value: other.upstream_model_name, }); } expandDataLocal.push({ key: t('计费过程'), value: t('已切换为摘要展示'), }); if (other?.reasoning_effort) { expandDataLocal.push({ key: t('Reasoning Effort'), value: other.reasoning_effort, }); } } if (other?.request_path) { expandDataLocal.push({ key: t('请求路径'), value: other.request_path, }); } if (isAdminUser) { let localCountMode = ''; if (other?.admin_info?.local_count_tokens) { localCountMode = t('本地计费'); } else { localCountMode = t('上游返回'); } expandDataLocal.push({ key: t('计费模式'), value: localCountMode, }); } expandDatesLocal[logs[i].key] = expandDataLocal; } setExpandData(expandDatesLocal); setLogs(logs); }; // 请求序列号:丢弃乱序回来的过期响应,防止旧结果覆盖新结果 const logsRequestIdRef = useRef(0); // Load logs function const loadLogs = async (startIdx, pageSize, customLogType = null, signal) => { const reqId = ++logsRequestIdRef.current; setLoading(true); let url = ''; const { username, token_name, model_name, start_timestamp, end_timestamp, channel, group, user_id, logType: formLogType, } = getFormValues(); // 表单是 logType 的唯一真源;customLogType 仍保留用于显式覆盖(外部传参场景) const currentLogType = customLogType !== null ? customLogType : formLogType || 0; let localStartTimestamp = Date.parse(start_timestamp) / 1000; let localEndTimestamp = Date.parse(end_timestamp) / 1000; // 时间范围校验:起始晚于结束直接提示并中止,避免无意义请求 if ( Number.isFinite(localStartTimestamp) && Number.isFinite(localEndTimestamp) && localStartTimestamp > localEndTimestamp ) { showError(t('开始时间不能晚于结束时间')); if (reqId === logsRequestIdRef.current) setLoading(false); return; } if (isAdminUser) { const params = new URLSearchParams({ p: startIdx, page_size: pageSize, type: currentLogType, username, token_name, model_name, start_timestamp: localStartTimestamp, end_timestamp: localEndTimestamp, channel, group, user_id, }); url = `/api/log/?${params.toString()}`; } else { const params = new URLSearchParams({ p: startIdx, page_size: pageSize, type: currentLogType, token_name, model_name, start_timestamp: localStartTimestamp, end_timestamp: localEndTimestamp, group, }); url = `/api/log/self?${params.toString()}`; } try { const res = await API.get(url, { signal }); // 丢弃过期响应,只处理仍然是最新的请求 if (reqId !== logsRequestIdRef.current || signal?.aborted) return; const { success, message, data } = res.data; if (success) { const newPageData = Array.isArray(data?.items) ? data.items : []; setActivePage(signal ? startIdx : data?.page || 1); setPageSize(data?.page_size || pageSize); setLogCount(data?.total || 0); // 记录本次成功查询的筛选条件(与展示数据/总数一致),供「导出全部筛选结果」复用 appliedExportParamsRef.current = { username, token_name, model_name, start_timestamp: localStartTimestamp, end_timestamp: localEndTimestamp, channel, group, user_id, type: currentLogType, }; setLogsFormat(newPageData); } else { showError(message); } } catch (error) { if (!signal?.aborted && reqId === logsRequestIdRef.current) showError(error.message || error); } finally { if (reqId === logsRequestIdRef.current) setLoading(false); } }; // Page handlers const handlePageChange = (page) => { setActivePage(page); loadLogs(page, pageSize).then((r) => {}); }; const handlePageSizeChange = async (size) => { localStorage.setItem('page-size', size + ''); setPageSize(size); setActivePage(1); loadLogs(1, size) .then() .catch((reason) => { showError(reason); }); }; // 同步表单筛选到 URL,支持分享;只覆盖 URL_SYNC_FIELDS,不触碰 tab/utm_* const syncFiltersToUrl = () => { if (typeof window === 'undefined') return; const formValues = formApi ? formApi.getValues() : {}; const sp = new URLSearchParams(window.location.search); URL_SYNC_FIELDS.forEach((key) => { const v = (formValues[key] || '').toString().trim(); // logType 默认 '0',视为空不写入 URL if (v && !(key === 'logType' && v === '0')) sp.set(key, v); else sp.delete(key); }); const newQuery = sp.toString(); const newUrl = window.location.pathname + (newQuery ? '?' + newQuery : '') + window.location.hash; window.history.replaceState({}, '', newUrl); }; // Refresh function const refresh = async ({ page = 1, signal } = {}) => { syncFiltersToUrl(); // 并行触发但等待两者完成,避免 stat 与 list 结果基于不同过滤条件导致错乱 await Promise.all([ handleEyeClick(signal), loadLogs(page, pageSize, null, signal), ]); }; // Copy text function const copyText = async (e, text) => { e.stopPropagation(); if (await copy(text)) { showSuccess(t('已复制:{{name}}', { name: text })); } else { Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text }); } }; // Initialize data const onMount2 = useEffectEvent(() => { const localPageSize = parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE; setPageSize(localPageSize); loadLogs(activePage, localPageSize) .then() .catch((reason) => { showError(reason); }); }); useEffect(() => onMount2(), [onMount2]); // Initialize statistics when formApi is available const onScopeChange3 = useEffectEvent(() => { if (formApi) { handleEyeClick(); } }); useEffect(() => onScopeChange3(), [onScopeChange3, formApi]); // 订阅"任务完成"事件:任务转终态时后端会产生消费日志,这里跟随刷新 // 用 ref 保存最新的加载函数,避免依赖数组里塞太多 state 导致频繁重订阅 const refreshRef = useRef(); refreshRef.current = async () => { // 只在 formApi 就绪时刷新,否则 loadLogs 拿不到过滤条件 if (!formApi) return; await Promise.all([handleEyeClick(), loadLogs(activePage || 1, pageSize)]); }; useEffect(() => { const unsub = subscribe(EVENTS.TASK_COMPLETED, () => { // 节流:任务完成事件可能在一轮轮询中批量出现 if (refreshRef.current) refreshRef.current(); }); return unsub; }, []); // Check if any record has expandable content const hasExpandableRows = () => { return logs.some( (log) => expandData[log.key] && expandData[log.key].length > 0, ); }; return { // Basic state logs, expandData, showStat, loading, loadingStat, activePage, logCount, pageSize, stat, isAdminUser, isRootUser, // Form state formApi, setFormApi, formInitValues, getFormValues, getFreshInitValues, // Column visibility visibleColumns, setVisibleColumns, getDefaultColumnVisibility, showColumnSelector, setShowColumnSelector, handleColumnVisibilityChange, handleSelectAll, initDefaultColumns, COLUMN_KEYS, // Compact mode compactMode, setCompactMode, // User info modal showUserInfo, setShowUserInfoModal, userInfoData, showUserInfoFunc, // Export modal showExportModal, setShowExportModal, fetchLogsForExport, // Functions loadLogs, handlePageChange, handlePageSizeChange, refresh, copyText, handleEyeClick, setLogsFormat, hasExpandableRows, // Translation t, }; };