Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,431 @@
|
||||
/*
|
||||
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, { useEffect, useMemo, useState } from 'react';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { Modal, Button, Checkbox, Radio, RadioGroup } from '@douyinfe/semi-ui';
|
||||
import { CheckSquare, Eraser, FileSpreadsheet, X } from 'lucide-react';
|
||||
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,
|
||||
usageRecordMode = false,
|
||||
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 = (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 wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(
|
||||
wb,
|
||||
buildSheet(rows, fields, header),
|
||||
t('消耗明细'),
|
||||
);
|
||||
XLSX.writeFile(wb, buildExportFilename());
|
||||
showSuccess(t('导出成功'));
|
||||
setShowExportModal(false);
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('导出消耗明细')}
|
||||
visible={showExportModal}
|
||||
onCancel={() => setShowExportModal(false)}
|
||||
maskClosable={!exporting}
|
||||
footer={
|
||||
<div className='flex justify-end gap-2'>
|
||||
<Button
|
||||
size={usageRecordMode ? 'small' : undefined}
|
||||
icon={usageRecordMode ? <X className='w-3.5 h-3.5' /> : undefined}
|
||||
onClick={() => setShowExportModal(false)}
|
||||
disabled={exporting}
|
||||
className={
|
||||
usageRecordMode
|
||||
? 'usage-record-action-button usage-record-action-button-soft'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{t('取消')}
|
||||
</Button>
|
||||
<Button
|
||||
size={usageRecordMode ? 'small' : undefined}
|
||||
theme={usageRecordMode ? undefined : 'solid'}
|
||||
icon={
|
||||
usageRecordMode ? (
|
||||
<FileSpreadsheet
|
||||
className='w-3.5 h-3.5'
|
||||
style={{ color: '#fff' }}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
onClick={handleExport}
|
||||
loading={exporting}
|
||||
disabled={selectedCount === 0 || pageNoData}
|
||||
className={
|
||||
usageRecordMode
|
||||
? 'usage-record-action-button usage-record-action-button-primary'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{t('导出 Excel')}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className='mb-4'>
|
||||
<div className='text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
{t('导出范围')}
|
||||
</div>
|
||||
<RadioGroup
|
||||
type='card'
|
||||
value={scope}
|
||||
onChange={(e) => setScope(e.target.value)}
|
||||
>
|
||||
<Radio
|
||||
value='all'
|
||||
extra={t('按当前筛选导出全部(最多 {{limit}} 条)', {
|
||||
limit: EXPORT_LIMIT,
|
||||
})}
|
||||
>
|
||||
{t('全部筛选结果')}
|
||||
</Radio>
|
||||
<Radio value='page' extra={t('仅导出当前页')}>
|
||||
{t('当前页')}
|
||||
</Radio>
|
||||
</RadioGroup>
|
||||
<div className='text-xs text-gray-500 dark:text-gray-400 mt-2'>
|
||||
{scope === 'page'
|
||||
? t('本次将导出当前页 {{n}} 条', { n: pageCount })
|
||||
: t('本次将导出约 {{n}} 条', { n: logCount })}
|
||||
{scope === 'all' && logCount > EXPORT_LIMIT && (
|
||||
<span className='text-amber-600 dark:text-amber-400'>
|
||||
{' '}
|
||||
{t('(超过上限,仅导出最新 {{limit}} 条,建议缩小筛选范围)', {
|
||||
limit: EXPORT_LIMIT,
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className='flex items-center justify-between mb-2'>
|
||||
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
|
||||
{t('导出字段')}
|
||||
</span>
|
||||
<div className='flex gap-2'>
|
||||
<Button
|
||||
size='small'
|
||||
theme={usageRecordMode ? undefined : 'borderless'}
|
||||
icon={
|
||||
usageRecordMode ? (
|
||||
<CheckSquare className='w-3.5 h-3.5' />
|
||||
) : undefined
|
||||
}
|
||||
onClick={() => setAll(true)}
|
||||
className={
|
||||
usageRecordMode
|
||||
? 'usage-record-action-button usage-record-action-button-soft'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{t('全选')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
theme={usageRecordMode ? undefined : 'borderless'}
|
||||
icon={
|
||||
usageRecordMode ? <Eraser className='w-3.5 h-3.5' /> : undefined
|
||||
}
|
||||
onClick={() => setAll(false)}
|
||||
className={
|
||||
usageRecordMode
|
||||
? 'usage-record-action-button usage-record-action-button-soft'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{t('清空')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className='flex flex-wrap rounded-lg p-3'
|
||||
style={{ border: '1px solid var(--semi-color-border)' }}
|
||||
>
|
||||
{availableFields.map((f) => (
|
||||
<div key={f.id} className='w-1/2 mb-2'>
|
||||
<Checkbox
|
||||
checked={!!selected[f.id]}
|
||||
onChange={(e) => toggle(f.id, e.target.checked)}
|
||||
>
|
||||
{t(f.label)}
|
||||
</Checkbox>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className='text-xs text-gray-400 dark:text-gray-500 mt-2'>
|
||||
{t('消耗额度以人民币(¥)金额导出。')}
|
||||
</p>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default UsageLogsExportModal;
|
||||
Reference in New Issue
Block a user