/* 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 React, { useEffect, useMemo, useState } from 'react'; import { Modal, Button, Checkbox, Radio, RadioGroup } from '@/components/ui'; import { renderExportQuota, getLogOther, timestamp2string, showError, showSuccess, showWarning, } from '../../../../helpers'; // 单次导出上限(需与后端 logExportLimit 保持一致),用于弹窗内提前提示截断 const EXPORT_LIMIT = 10000; const TYPE_LABELS = { 1: '充值', 2: '消费', 3: '管理', 4: '系统', 5: '错误', 6: '退款', }; function getCacheTokens(record) { const other = getLogOther(record.other); const v = Number(other.cache_tokens || other.cached_tokens || 0); return Number.isFinite(v) ? v : 0; } function getCacheCreationTokens(record) { const other = getLogOther(record.other); let v = Number(other.cache_creation_tokens || 0); if (!v) { v = Number(other.cache_creation_tokens_5m || 0) + Number(other.cache_creation_tokens_1h || 0); } return Number.isFinite(v) ? v : 0; } // 字段定义:label 经 t() 翻译;width 为 Excel 列宽;adminOnly 仅管理员可见;value 取值函数 // quota 渲染为¥金额,与页面显示一致 const FIELD_DEFS = [ { id: 'time', label: '时间', width: 20, value: (r) => (r.created_at ? timestamp2string(r.created_at) : ''), }, { id: 'channel', label: '渠道ID', width: 10, adminOnly: true, value: (r) => r.channel || '', }, { id: 'channelName', label: '渠道名称', width: 16, adminOnly: true, value: (r) => r.channel_name || '', }, { id: 'username', label: '用户名', width: 14, adminOnly: true, value: (r) => r.username || '', }, { id: 'userId', label: '用户ID', width: 10, adminOnly: true, value: (r) => r.user_id || '', }, { id: 'tokenName', label: '密钥名称', width: 16, value: (r) => r.token_name || '', }, { id: 'group', label: '分组', width: 12, value: (r) => r.group || '' }, { id: 'type', label: '类型', width: 10, // 与页面一致:类型标签做 i18n 翻译(t 由 buildSheet 传入) value: (r, t) => t(TYPE_LABELS[r.type] || '未知'), }, { id: 'model', label: '模型', width: 24, value: (r) => r.model_name || '' }, { id: 'useTime', label: '耗时(秒)', width: 10, value: (r) => r.use_time || 0, }, { id: 'promptTokens', label: '输入Tokens', width: 12, value: (r) => r.prompt_tokens || 0, }, { id: 'completionTokens', label: '输出Tokens', width: 12, value: (r) => r.completion_tokens || 0, }, { id: 'cacheTokens', label: '缓存Tokens', width: 12, value: (r) => getCacheTokens(r), }, { id: 'cacheCreationTokens', label: '缓存创建Tokens', width: 14, value: (r) => getCacheCreationTokens(r), }, { id: 'quota', label: '消耗额度', width: 14, value: (r) => renderExportQuota(r.quota || 0, 6), }, { id: 'ip', label: 'IP', width: 16, adminOnly: true, value: (r) => r.ip || '', }, ]; function buildExportFilename() { const now = new Date(); const ts = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; return `usage-logs-${ts}.xlsx`; } const UsageLogsExportModal = ({ showExportModal, setShowExportModal, logs = [], logCount = 0, isAdminUser, fetchLogsForExport, t, }) => { const prefsKey = isAdminUser ? 'usage-logs-export-prefs-admin' : 'usage-logs-export-prefs-user'; // 当前角色可见字段 const availableFields = useMemo( () => FIELD_DEFS.filter((f) => !f.adminOnly || isAdminUser), [isAdminUser], ); const loadPrefs = () => { try { const p = JSON.parse(localStorage.getItem(prefsKey) || 'null'); return p && typeof p === 'object' ? p : null; } catch { return null; } }; const [scope, setScope] = useState(() => loadPrefs()?.scope === 'page' ? 'page' : 'all', ); const [selected, setSelected] = useState(() => { const saved = loadPrefs()?.fields; const useSaved = Array.isArray(saved) && saved.length > 0; return availableFields.reduce((acc, f) => { acc[f.id] = useSaved ? saved.includes(f.id) : true; return acc; }, {}); }); const [exporting, setExporting] = useState(false); // 持久化偏好 useEffect(() => { const fields = availableFields .filter((f) => selected[f.id]) .map((f) => f.id); try { localStorage.setItem(prefsKey, JSON.stringify({ scope, fields })); } catch { // 忽略 localStorage 写入失败 } }, [scope, selected, availableFields, prefsKey]); const selectedCount = availableFields.filter((f) => selected[f.id]).length; const toggle = (id, checked) => setSelected((prev) => ({ ...prev, [id]: checked })); const setAll = (checked) => setSelected( availableFields.reduce((acc, f) => { acc[f.id] = checked; return acc; }, {}), ); const pageCount = logs.length; // 仅「当前页」可据内存数据判定空;「全部筛选结果」的真实条数在导出时按当前筛选实拉, // 不用可能过期的 logCount 来禁用按钮(避免编辑筛选未查询时被误禁用) const pageNoData = scope === 'page' && pageCount === 0; const buildSheet = (XLSX, rows, fields, header) => { const aoa = [header, ...rows.map((r) => fields.map((f) => f.value(r, t)))]; const ws = XLSX.utils.aoa_to_sheet(aoa); ws['!cols'] = fields.map((f) => ({ wch: f.width || 14 })); return ws; }; const handleExport = async () => { const fields = availableFields.filter((f) => selected[f.id]); if (fields.length === 0) { showError(t('请至少选择一个导出字段')); return; } setExporting(true); try { let rows = []; if (scope === 'page') { rows = logs; } else { const data = await fetchLogsForExport(); if (!data) return; // 失败已在 hook 内提示 rows = data.items || []; if (data.truncated) { showWarning( t('数据量较大,仅导出前 {{limit}} 条,请缩小筛选范围以导出全部', { limit: data.limit || EXPORT_LIMIT, }), ); } } if (!rows || rows.length === 0) { showError(t('当前无数据可导出')); return; } const header = fields.map((f) => t(f.label)); const XLSX = await import('xlsx'); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet( wb, buildSheet(XLSX, rows, fields, header), t('消耗明细'), ); XLSX.writeFile(wb, buildExportFilename()); showSuccess(t('导出成功')); setShowExportModal(false); } catch (err) { showError(err.message); } finally { setExporting(false); } }; return ( setShowExportModal(false)} maskClosable={!exporting} footer={ setShowExportModal(false)} disabled={exporting} > {t('取消')} {t('导出 Excel')} } > {t('导出范围')} setScope(e.target.value)} > {t('全部筛选结果')} {t('当前页')} {scope === 'page' ? t('本次将导出当前页 {{n}} 条', { n: pageCount }) : t('本次将导出约 {{n}} 条', { n: logCount })} {scope === 'all' && logCount > EXPORT_LIMIT && ( {' '} {t('(超过上限,仅导出最新 {{limit}} 条,建议缩小筛选范围)', { limit: EXPORT_LIMIT, })} )} {t('导出字段')} setAll(true)} > {t('全选')} setAll(false)} > {t('清空')} {availableFields.map((f) => ( toggle(f.id, e.target.checked)} > {t(f.label)} ))} {t('消耗额度以人民币(¥)金额导出。')} ); }; export default UsageLogsExportModal;
{t('消耗额度以人民币(¥)金额导出。')}