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
@@ -0,0 +1,470 @@
.usage-logs-page.usage-logs-panel,
.usage-logs-page .usage-logs-panel {
overflow: hidden;
}
.usage-logs-page.usage-logs-panel::before,
.usage-logs-page .usage-logs-panel::before {
content: '';
position: absolute;
inset: 0;
z-index: 0;
pointer-events: none;
opacity: 0.015;
background-image:
linear-gradient(
color-mix(in srgb, var(--brand-gradient-via) 50%, transparent) 1px,
transparent 1px
),
linear-gradient(
90deg,
color-mix(in srgb, var(--brand-gradient-via) 50%, transparent) 1px,
transparent 1px
);
background-size: 24px 24px;
}
.dark .usage-logs-page.usage-logs-panel::before,
.dark .usage-logs-page .usage-logs-panel::before {
opacity: 0.03;
}
.usage-logs-page .semi-card-header {
position: relative;
z-index: 1;
border-bottom: 1px solid rgb(255 255 255 / 0.42);
background: linear-gradient(
180deg,
rgb(255 255 255 / 0.34),
rgb(255 255 255 / 0.16)
);
backdrop-filter: blur(20px);
}
.dark .usage-logs-page .semi-card-header {
border-bottom-color: rgb(255 255 255 / 0.08);
background: linear-gradient(
180deg,
rgb(255 255 255 / 0.06),
rgb(255 255 255 / 0.025)
);
}
.usage-logs-page .semi-card-body {
position: relative;
z-index: 1;
background: transparent;
}
.usage-logs-page .semi-card-footer {
position: relative;
z-index: 1;
}
.usage-logs-filter-form {
border: 1px solid rgb(255 255 255 / 0.5);
border-radius: 24px;
background: rgb(255 255 255 / 0.34);
padding: 16px;
box-shadow: 0 18px 48px rgb(15 23 42 / 0.07);
backdrop-filter: blur(22px) saturate(1.35);
}
.usage-logs-filter-content {
display: flex;
flex-direction: column;
gap: 16px;
}
.usage-logs-filter-title {
display: flex;
align-items: center;
gap: 8px;
padding-bottom: 8px;
border-bottom: 1px solid rgb(243 244 246);
}
.dark .usage-logs-filter-title {
border-bottom-color: rgb(38 38 38);
}
.usage-logs-filter-title-icon {
display: inline-flex;
width: 24px;
height: 24px;
align-items: center;
justify-content: center;
border-radius: 10px;
background: linear-gradient(
135deg,
var(--brand-gradient-from),
var(--brand-gradient-to)
);
box-shadow: 0 4px 10px rgb(15 23 42 / 0.12);
}
.dark .usage-logs-filter-form {
border-color: rgb(255 255 255 / 0.1);
background: rgb(255 255 255 / 0.045);
box-shadow: 0 18px 48px rgb(0 0 0 / 0.24);
}
.usage-logs-filter-form .semi-input-wrapper,
.usage-logs-filter-form .semi-select,
.usage-logs-filter-form .semi-datepicker,
.usage-logs-filter-form .semi-datepicker-range {
border: 1px solid rgb(255 255 255 / 0.5) !important;
border-radius: 14px !important;
background: rgb(255 255 255 / 0.48) !important;
box-shadow: 0 8px 24px rgb(15 23 42 / 0.04);
backdrop-filter: blur(14px);
}
.dark .usage-logs-filter-form .semi-input-wrapper,
.dark .usage-logs-filter-form .semi-select,
.dark .usage-logs-filter-form .semi-datepicker,
.dark .usage-logs-filter-form .semi-datepicker-range {
border-color: rgb(255 255 255 / 0.1) !important;
background: rgb(255 255 255 / 0.055) !important;
box-shadow: none;
}
.usage-logs-filter-form .semi-input-prefix {
margin-left: 4px;
margin-right: 6px;
}
.usage-logs-table-shell {
position: relative;
}
.usage-logs-glass-table {
border: 1px solid rgb(255 255 255 / 0.48);
background: rgb(255 255 255 / 0.32);
box-shadow: 0 24px 72px rgb(15 23 42 / 0.08);
backdrop-filter: blur(24px) saturate(1.3);
}
.dark .usage-logs-glass-table {
border-color: rgb(255 255 255 / 0.1);
background: rgb(255 255 255 / 0.035);
box-shadow: 0 24px 72px rgb(0 0 0 / 0.28);
}
.usage-logs-glass-table .semi-table-tbody .semi-table-row {
transition:
background 160ms ease,
transform 160ms ease;
}
.usage-logs-glass-table .semi-table-tbody .semi-table-row:hover {
background: color-mix(
in srgb,
var(--brand-primary) 7%,
transparent
) !important;
}
.usage-logs-glass-table .semi-table-expanded-row-cell {
background: linear-gradient(
180deg,
rgb(255 255 255 / 0.24),
rgb(255 255 255 / 0.1)
) !important;
padding: 18px 24px !important;
}
.dark .usage-logs-glass-table .semi-table-expanded-row-cell {
background: linear-gradient(
180deg,
rgb(255 255 255 / 0.045),
rgb(255 255 255 / 0.02)
) !important;
}
.usage-billing-detail {
border: 1px solid rgb(255 255 255 / 0.5);
border-radius: 24px;
background:
radial-gradient(
circle at 0% 0%,
color-mix(in srgb, var(--brand-primary) 10%, transparent),
transparent 34%
),
rgb(255 255 255 / 0.36);
padding: 16px;
box-shadow: 0 18px 46px rgb(15 23 42 / 0.08);
backdrop-filter: blur(24px) saturate(1.35);
}
.dark .usage-billing-detail {
border-color: rgb(255 255 255 / 0.1);
background:
radial-gradient(
circle at 0% 0%,
color-mix(in srgb, var(--brand-primary) 16%, transparent),
transparent 34%
),
rgb(255 255 255 / 0.035);
box-shadow: 0 18px 46px rgb(0 0 0 / 0.3);
}
.usage-logs-date-panel {
--usage-date-accent: var(--brand-gradient-via);
--usage-date-accent-strong: var(--brand-gradient-to);
--usage-date-soft: color-mix(
in srgb,
var(--brand-gradient-via) 12%,
transparent
);
--usage-date-border: rgb(255 255 255 / 0.5);
}
.usage-logs-date-panel.semi-datepicker,
.usage-logs-date-panel .semi-datepicker {
overflow: hidden;
border: 1px solid var(--usage-date-border);
border-radius: 28px;
background:
radial-gradient(
circle at 10% 0%,
color-mix(in srgb, var(--brand-gradient-from) 18%, transparent),
transparent 32%
),
radial-gradient(
circle at 100% 18%,
color-mix(in srgb, var(--brand-gradient-to) 12%, transparent),
transparent 28%
),
rgb(255 255 255 / 0.82);
box-shadow:
0 28px 80px rgb(15 23 42 / 0.18),
inset 0 1px 0 rgb(255 255 255 / 0.64);
backdrop-filter: blur(28px) saturate(1.35);
}
.dark .usage-logs-date-panel.semi-datepicker,
.dark .usage-logs-date-panel .semi-datepicker {
--usage-date-border: rgb(255 255 255 / 0.1);
background:
radial-gradient(
circle at 10% 0%,
color-mix(in srgb, var(--brand-gradient-from) 20%, transparent),
transparent 34%
),
radial-gradient(
circle at 100% 18%,
color-mix(in srgb, var(--brand-gradient-to) 18%, transparent),
transparent 30%
),
rgb(15 23 42 / 0.86);
box-shadow:
0 28px 90px rgb(0 0 0 / 0.45),
inset 0 1px 0 rgb(255 255 255 / 0.08);
}
.usage-logs-date-panel .semi-datepicker-navigation {
height: 34px;
padding: 14px 18px 10px;
}
.usage-logs-date-panel .semi-datepicker-navigation-month .semi-button {
min-width: 132px;
height: 38px;
border: 0;
border-radius: 16px;
background: linear-gradient(
135deg,
var(--brand-gradient-from),
var(--brand-gradient-to)
);
color: #fff;
font-size: 15px;
font-weight: 700;
box-shadow: 0 10px 24px
color-mix(in srgb, var(--brand-gradient-via) 28%, transparent);
}
.usage-logs-date-panel .semi-datepicker-navigation-left .semi-button,
.usage-logs-date-panel .semi-datepicker-navigation-right .semi-button {
min-width: 34px;
width: 34px;
height: 34px;
border: 1px solid rgb(255 255 255 / 0.48);
border-radius: 14px;
background: rgb(255 255 255 / 0.58);
color: var(--usage-date-accent-strong);
box-shadow: 0 8px 18px rgb(15 23 42 / 0.08);
backdrop-filter: blur(12px);
}
.dark .usage-logs-date-panel .semi-datepicker-navigation-left .semi-button,
.dark .usage-logs-date-panel .semi-datepicker-navigation-right .semi-button {
border-color: rgb(255 255 255 / 0.1);
background: rgb(255 255 255 / 0.08);
color: color-mix(in srgb, var(--brand-gradient-from) 78%, white);
box-shadow: none;
}
.usage-logs-date-panel .semi-datepicker-month {
padding: 6px 18px 12px;
}
.usage-logs-date-panel .semi-datepicker-weekday {
margin-bottom: 8px;
border-bottom: 0;
color: rgb(100 116 139);
font-size: 12px;
}
.dark .usage-logs-date-panel .semi-datepicker-weekday {
color: rgb(148 163 184);
}
.usage-logs-date-panel .semi-datepicker-weekday-item,
.usage-logs-date-panel .semi-datepicker-day {
width: 34px;
height: 34px;
}
.usage-logs-date-panel .semi-datepicker-day-main {
width: 30px;
height: 30px;
border-radius: 12px;
font-weight: 500;
transition:
background 160ms ease,
color 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.usage-logs-date-panel .semi-datepicker-day-main:hover {
background: var(--usage-date-soft);
color: var(--usage-date-accent-strong);
transform: translateY(-1px);
}
.usage-logs-date-panel .semi-datepicker-day-today .semi-datepicker-day-main {
background: rgb(255 255 255 / 0.72);
color: var(--usage-date-accent-strong);
box-shadow: inset 0 0 0 1px
color-mix(in srgb, var(--brand-gradient-via) 38%, transparent);
}
.dark
.usage-logs-date-panel
.semi-datepicker-day-today
.semi-datepicker-day-main {
background: rgb(255 255 255 / 0.08);
}
.usage-logs-date-panel .semi-datepicker-day-inrange .semi-datepicker-day-main,
.usage-logs-date-panel .semi-datepicker-day-inhover .semi-datepicker-day-main,
.usage-logs-date-panel
.semi-datepicker-day-inoffsetrange
.semi-datepicker-day-main,
.usage-logs-date-panel .semi-datepicker-day-hoverday .semi-datepicker-day-main {
width: 34px;
background: color-mix(in srgb, var(--brand-gradient-via) 12%, transparent);
color: var(--usage-date-accent-strong);
}
.usage-logs-date-panel .semi-datepicker-day-selected .semi-datepicker-day-main,
.usage-logs-date-panel
.semi-datepicker-day-selected-start
.semi-datepicker-day-main,
.usage-logs-date-panel
.semi-datepicker-day-selected-end
.semi-datepicker-day-main {
background: linear-gradient(
135deg,
var(--brand-gradient-from),
var(--brand-gradient-to)
);
color: #fff;
box-shadow: 0 10px 22px
color-mix(in srgb, var(--brand-gradient-via) 32%, transparent);
}
.usage-logs-date-panel .semi-datepicker-switch,
.usage-logs-date-panel .semi-datepicker-footer,
.usage-logs-date-panel .semi-datepicker-quick-control-bottom {
border-color: rgb(226 232 240 / 0.74);
background: rgb(255 255 255 / 0.42);
backdrop-filter: blur(16px);
}
.dark .usage-logs-date-panel .semi-datepicker-switch,
.dark .usage-logs-date-panel .semi-datepicker-footer,
.dark .usage-logs-date-panel .semi-datepicker-quick-control-bottom {
border-color: rgb(255 255 255 / 0.08);
background: rgb(255 255 255 / 0.045);
}
.usage-logs-date-panel .semi-datepicker-switch-date,
.usage-logs-date-panel .semi-datepicker-switch-time {
padding-top: 12px;
padding-bottom: 12px;
}
.usage-logs-date-panel .semi-datepicker-switch-date-active,
.usage-logs-date-panel .semi-datepicker-switch-time-active {
color: var(--usage-date-accent-strong);
}
.usage-logs-date-panel .semi-datepicker-quick-control-top-range-content,
.usage-logs-date-panel .semi-datepicker-quick-control-bottom-range-content {
grid-template-columns: repeat(5, minmax(86px, 1fr));
gap: 10px;
padding: 12px 20px;
}
.usage-logs-date-panel .semi-datepicker-quick-control-top-range-content-item,
.usage-logs-date-panel
.semi-datepicker-quick-control-bottom-range-content-item {
max-width: none;
}
.usage-logs-date-panel
.semi-datepicker-quick-control-top-range-content-item
.semi-button,
.usage-logs-date-panel
.semi-datepicker-quick-control-bottom-range-content-item
.semi-button {
width: 100%;
border: 1px solid
color-mix(in srgb, var(--brand-gradient-via) 46%, transparent);
border-radius: 999px;
background: rgb(255 255 255 / 0.54);
color: var(--usage-date-accent-strong);
font-weight: 600;
}
.dark
.usage-logs-date-panel
.semi-datepicker-quick-control-top-range-content-item
.semi-button,
.dark
.usage-logs-date-panel
.semi-datepicker-quick-control-bottom-range-content-item
.semi-button {
background: rgb(255 255 255 / 0.07);
}
@media (max-width: 768px) {
.usage-logs-date-panel.semi-datepicker,
.usage-logs-date-panel .semi-datepicker {
max-width: calc(100vw - 24px);
border-radius: 22px;
}
.usage-logs-date-panel .semi-datepicker-month-grid {
overflow-x: auto;
}
.usage-logs-date-panel .semi-datepicker-quick-control-top-range-content,
.usage-logs-date-panel .semi-datepicker-quick-control-bottom-range-content {
grid-template-columns: repeat(2, minmax(118px, 1fr));
}
}
@@ -0,0 +1,648 @@
/*
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 from 'react';
import {
Avatar,
Space,
Tag,
Tooltip,
Popover,
Typography,
} from '@douyinfe/semi-ui';
import {
renderGroup,
renderQuota,
stringToColor,
getLogOther,
renderModelTag,
renderModelPriceSimple,
hoverOrClickTrigger,
} from '../../../helpers';
import { IconHelpCircle } from '@douyinfe/semi-icons';
import { Route } from 'lucide-react';
const colors = [
'amber',
'blue',
'cyan',
'green',
'grey',
'indigo',
'light-blue',
'lime',
'orange',
'pink',
'purple',
'red',
'teal',
'violet',
'yellow',
];
// 类型配置映射
const TYPE_CONFIG = {
1: {
label: '充值',
gradient: 'from-cyan-500 to-teal-500',
bgLight: 'bg-cyan-50',
bgDark: 'dark:bg-cyan-950/30',
textLight: 'text-cyan-700',
textDark: 'dark:text-cyan-300',
},
2: {
label: '消费',
gradient: 'from-emerald-500 to-green-500',
bgLight: 'bg-emerald-50',
bgDark: 'dark:bg-emerald-950/30',
textLight: 'text-emerald-700',
textDark: 'dark:text-emerald-300',
},
3: {
label: '管理',
gradient: 'from-amber-500 to-orange-500',
bgLight: 'bg-amber-50',
bgDark: 'dark:bg-amber-950/30',
textLight: 'text-amber-700',
textDark: 'dark:text-amber-300',
},
4: {
label: '系统',
gradient: 'from-brand-from to-brand-to',
bgLight: 'bg-brand/5',
bgDark: 'dark:bg-brand-deep/30',
textLight: 'text-brand-deep',
textDark: 'dark:text-brand-from',
},
5: {
label: '错误',
gradient: 'from-rose-500 to-red-500',
bgLight: 'bg-rose-50',
bgDark: 'dark:bg-rose-950/30',
textLight: 'text-rose-700',
textDark: 'dark:text-rose-300',
},
default: {
label: '未知',
gradient: 'from-gray-400 to-gray-500',
bgLight: 'bg-gray-50',
bgDark: 'dark:bg-gray-900/30',
textLight: 'text-gray-600',
textDark: 'dark:text-gray-400',
},
};
// Render functions
function renderType(type, t) {
const config = TYPE_CONFIG[type] || TYPE_CONFIG.default;
return (
<span
className={`
inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium
${config.bgLight} ${config.bgDark} ${config.textLight} ${config.textDark}
border border-current/10
transition-all duration-200 hover:scale-105
`}
>
<span
className={`w-1.5 h-1.5 rounded-full bg-gradient-to-r ${config.gradient}`}
/>
{t(config.label)}
</span>
);
}
function renderIsStream(bool, t) {
if (bool) {
return (
<span className='inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-blue-50 dark:bg-blue-950/30 text-blue-600 dark:text-blue-400 border border-blue-200/50 dark:border-blue-800/50'>
<span className='w-1 h-1 rounded-full bg-blue-500 animate-pulse' />
{t('流')}
</span>
);
} else {
return (
<span className='inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-gray-50 dark:bg-gray-900/30 text-gray-500 dark:text-gray-400 border border-gray-200/50 dark:border-gray-700/50'>
{t('非流')}
</span>
);
}
}
function renderUseTime(type, t) {
const time = parseInt(type);
let colorConfig;
if (time < 101) {
colorConfig = {
bg: 'bg-emerald-50 dark:bg-emerald-950/30',
text: 'text-emerald-600 dark:text-emerald-400',
border: 'border-emerald-200/50 dark:border-emerald-800/50',
dot: 'bg-emerald-500',
};
} else if (time < 300) {
colorConfig = {
bg: 'bg-amber-50 dark:bg-amber-950/30',
text: 'text-amber-600 dark:text-amber-400',
border: 'border-amber-200/50 dark:border-amber-800/50',
dot: 'bg-amber-500',
};
} else {
colorConfig = {
bg: 'bg-rose-50 dark:bg-rose-950/30',
text: 'text-rose-600 dark:text-rose-400',
border: 'border-rose-200/50 dark:border-rose-800/50',
dot: 'bg-rose-500',
};
}
return (
<span
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium ${colorConfig.bg} ${colorConfig.text} border ${colorConfig.border}`}
>
{time}s
</span>
);
}
function renderFirstUseTime(type, t) {
let time = parseFloat(type) / 1000.0;
time = time.toFixed(1);
let colorConfig;
if (time < 3) {
colorConfig = {
bg: 'bg-teal-50 dark:bg-teal-950/30',
text: 'text-teal-600 dark:text-teal-400',
border: 'border-teal-200/50 dark:border-teal-800/50',
};
} else if (time < 10) {
colorConfig = {
bg: 'bg-orange-50 dark:bg-orange-950/30',
text: 'text-orange-600 dark:text-orange-400',
border: 'border-orange-200/50 dark:border-orange-800/50',
};
} else {
colorConfig = {
bg: 'bg-red-50 dark:bg-red-950/30',
text: 'text-red-600 dark:text-red-400',
border: 'border-red-200/50 dark:border-red-800/50',
};
}
return (
<span
className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium ${colorConfig.bg} ${colorConfig.text} border ${colorConfig.border}`}
>
{time}s
</span>
);
}
function renderModelName(record, copyText, t, isRootUser) {
let other = getLogOther(record.other);
let modelMapped =
isRootUser &&
other?.is_model_mapped &&
other?.upstream_model_name &&
other?.upstream_model_name !== '';
if (!modelMapped) {
return renderModelTag(record.model_name, {
onClick: (event) => {
copyText(event, record.model_name).then((r) => {});
},
});
} else {
return (
<>
<Space vertical align={'start'}>
<Popover
// 触屏没有 hover,Semi 默认 trigger='hover' 时这个详情面板永远打不开
trigger={hoverOrClickTrigger()}
content={
<div style={{ padding: 10 }}>
<Space vertical align={'start'}>
<div className='flex items-center'>
<Typography.Text strong style={{ marginRight: 8 }}>
{t('请求并计费模型')}:
</Typography.Text>
{renderModelTag(record.model_name, {
onClick: (event) => {
copyText(event, record.model_name).then((r) => {});
},
})}
</div>
<div className='flex items-center'>
<Typography.Text strong style={{ marginRight: 8 }}>
{t('实际模型')}:
</Typography.Text>
{renderModelTag(other.upstream_model_name, {
onClick: (event) => {
copyText(event, other.upstream_model_name).then(
(r) => {},
);
},
})}
</div>
</Space>
</div>
}
>
{renderModelTag(record.model_name, {
onClick: (event) => {
copyText(event, record.model_name).then((r) => {});
},
suffixIcon: (
<Route
style={{ width: '0.9em', height: '0.9em', opacity: 0.75 }}
/>
),
})}
</Popover>
</Space>
</>
);
}
}
export const getLogsColumns = ({
t,
COLUMN_KEYS,
copyText,
showUserInfoFunc,
isAdminUser,
isRootUser = false,
}) => {
return [
{
key: COLUMN_KEYS.TIME,
title: t('时间'),
dataIndex: 'timestamp2string',
},
{
key: COLUMN_KEYS.CHANNEL,
title: t('渠道'),
dataIndex: 'channel',
render: (text, record, index) => {
let isMultiKey = false;
let multiKeyIndex = -1;
let other = getLogOther(record.other);
if (other?.admin_info) {
let adminInfo = other.admin_info;
if (adminInfo?.is_multi_key) {
isMultiKey = true;
multiKeyIndex = adminInfo.multi_key_index;
}
}
return isAdminUser &&
(record.type === 0 || record.type === 2 || record.type === 5) ? (
<Space>
<Tooltip content={record.channel_name || t('未知渠道')}>
<span>
<Tag
color={colors[parseInt(text) % colors.length]}
shape='circle'
>
{text}
</Tag>
</span>
</Tooltip>
{isMultiKey && (
<Tag color='white' shape='circle'>
{multiKeyIndex}
</Tag>
)}
</Space>
) : null;
},
},
{
key: COLUMN_KEYS.USERNAME,
title: t('用户'),
dataIndex: 'username',
render: (text, record, index) => {
// 优先显示 display_name,如果没有则显示 username
const displayText = record.display_name || text;
return isAdminUser ? (
<div>
<Avatar
size='extra-small'
color={stringToColor(text)}
style={{ marginRight: 4 }}
onClick={(event) => {
event.stopPropagation();
showUserInfoFunc(record.user_id);
}}
>
{typeof displayText === 'string' && displayText.slice(0, 1)}
</Avatar>
{displayText}
</div>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.TOKEN,
title: t('令牌'),
dataIndex: 'token_name',
render: (text, record, index) => {
return record.type === 0 || record.type === 2 || record.type === 5 ? (
<div>
<Tag
color='grey'
shape='circle'
onClick={(event) => {
copyText(event, text);
}}
>
{' '}
{t(text)}{' '}
</Tag>
</div>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.GROUP,
title: t('分组'),
dataIndex: 'group',
render: (text, record, index) => {
if (record.type === 0 || record.type === 2 || record.type === 5) {
if (record.group) {
return <>{renderGroup(record.group)}</>;
} else {
let other = null;
try {
other = JSON.parse(record.other);
} catch (e) {
console.error(
`Failed to parse record.other: "${record.other}".`,
e,
);
}
if (other === null) {
return <></>;
}
if (other.group !== undefined) {
return <>{renderGroup(other.group)}</>;
} else {
return <></>;
}
}
} else {
return <></>;
}
},
},
{
key: COLUMN_KEYS.TYPE,
title: t('类型'),
dataIndex: 'type',
render: (text, record, index) => {
return <>{renderType(text, t)}</>;
},
},
{
key: COLUMN_KEYS.MODEL,
title: t('模型'),
dataIndex: 'model_name',
render: (text, record, index) => {
return record.type === 0 || record.type === 2 || record.type === 5 ? (
<>{renderModelName(record, copyText, t, isRootUser)}</>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.USE_TIME,
title: t('用时/首字'),
dataIndex: 'use_time',
render: (text, record, index) => {
if (!(record.type === 2 || record.type === 5)) {
return <></>;
}
if (record.is_stream) {
let other = getLogOther(record.other);
return (
<>
<Space>
{renderUseTime(text, t)}
{renderFirstUseTime(other?.frt, t)}
{renderIsStream(record.is_stream, t)}
</Space>
</>
);
} else {
return (
<>
<Space>
{renderUseTime(text, t)}
{renderIsStream(record.is_stream, t)}
</Space>
</>
);
}
},
},
{
key: COLUMN_KEYS.PROMPT,
title: t('输入'),
dataIndex: 'prompt_tokens',
render: (text, record, index) => {
return record.type === 0 || record.type === 2 || record.type === 5 ? (
<>{<span> {text} </span>}</>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.COMPLETION,
title: t('输出'),
dataIndex: 'completion_tokens',
render: (text, record, index) => {
return parseInt(text) > 0 &&
(record.type === 0 || record.type === 2 || record.type === 5) ? (
<>{<span> {text} </span>}</>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.COST,
title: t('花费'),
dataIndex: 'quota',
render: (text, record, index) => {
return record.type === 0 || record.type === 2 || record.type === 5 ? (
<>{renderQuota(text, 6)}</>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.IP,
title: (
<div className='flex items-center gap-1'>
{t('IP')}
<Tooltip
content={t(
'只有当用户设置开启IP记录时,才会进行请求和错误类型日志的IP记录',
)}
>
<IconHelpCircle className='text-gray-400 cursor-help' />
</Tooltip>
</div>
),
dataIndex: 'ip',
render: (text, record, index) => {
return (record.type === 2 || record.type === 5) && text ? (
<Tooltip content={text}>
<span>
<Tag
color='orange'
shape='circle'
onClick={(event) => {
copyText(event, text);
}}
>
{text}
</Tag>
</span>
</Tooltip>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.RETRY,
title: t('重试'),
dataIndex: 'retry',
render: (text, record, index) => {
if (!(record.type === 2 || record.type === 5)) {
return <></>;
}
let content = t('渠道') + `:${record.channel}`;
if (record.other !== '') {
let other = JSON.parse(record.other);
if (other === null) {
return <></>;
}
if (other.admin_info !== undefined) {
if (
other.admin_info.use_channel !== null &&
other.admin_info.use_channel !== undefined &&
other.admin_info.use_channel !== ''
) {
let useChannel = other.admin_info.use_channel;
let useChannelStr = useChannel.join('->');
content = t('渠道') + `:${useChannelStr}`;
}
}
}
return isAdminUser ? <div>{content}</div> : <></>;
},
},
{
key: COLUMN_KEYS.DETAILS,
title: t('详情'),
dataIndex: 'content',
fixed: 'right',
render: (text, record, index) => {
let other = getLogOther(record.other);
if (other == null || record.type !== 2) {
return (
<Typography.Paragraph
ellipsis={{
rows: 2,
showTooltip: {
type: 'popover',
opts: { style: { width: 240 } },
},
}}
style={{ maxWidth: 240 }}
>
{text}
</Typography.Paragraph>
);
}
let content = other?.claude
? renderModelPriceSimple(
other.model_ratio,
other.model_price,
other.group_ratio,
other?.user_group_ratio,
other.cache_tokens || 0,
other.cache_ratio || 1.0,
other.cache_creation_tokens || 0,
other.cache_creation_ratio || 1.0,
other.cache_creation_tokens_5m || 0,
other.cache_creation_ratio_5m ||
other.cache_creation_ratio ||
1.0,
other.cache_creation_tokens_1h || 0,
other.cache_creation_ratio_1h ||
other.cache_creation_ratio ||
1.0,
false,
1.0,
other?.is_system_prompt_overwritten,
'claude',
)
: renderModelPriceSimple(
other.model_ratio,
other.model_price,
other.group_ratio,
other?.user_group_ratio,
other.cache_tokens || 0,
other.cache_ratio || 1.0,
0,
1.0,
0,
1.0,
0,
1.0,
false,
1.0,
other?.is_system_prompt_overwritten,
'openai',
);
return (
<Typography.Paragraph
ellipsis={{
rows: 3,
}}
style={{ maxWidth: 240, whiteSpace: 'pre-line' }}
>
{content}
</Typography.Paragraph>
);
},
},
];
};
@@ -0,0 +1,307 @@
/*
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 from 'react';
import { Button, Form } from '@douyinfe/semi-ui';
import {
Calendar,
Cpu,
Download,
FileDown,
Filter,
Hash,
Key,
Layers,
Radio,
RefreshCcw,
RotateCcw,
Search,
SearchCheck,
Settings2,
SlidersHorizontal,
Users,
} from 'lucide-react';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
const LogsFilters = ({
formInitValues,
setFormApi,
refresh,
setShowColumnSelector,
setShowExportModal,
formApi,
loading,
isAdminUser,
getFreshInitValues,
usageRecordMode = false,
t,
}) => {
const controlClass = 'w-full';
const SearchIcon = usageRecordMode ? SearchCheck : Search;
const ResetIcon = usageRecordMode ? RefreshCcw : RotateCcw;
const ColumnsIcon = usageRecordMode ? SlidersHorizontal : Settings2;
const ExportIcon = usageRecordMode ? FileDown : Download;
const primaryButtonClass = usageRecordMode
? 'usage-record-action-button usage-record-action-button-primary'
: '!bg-gradient-to-r !from-brand-from !to-brand-to !border-0 hover:!from-brand-from hover:!to-brand-to !shadow-md hover:!shadow-lg !transition-all !duration-300';
const softButtonClass = usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: 'hover:!bg-gray-100 dark:hover:!bg-neutral-800 !transition-all !duration-300';
const InputPrefix = ({ icon: Icon }) => (
<Icon
className='ml-1 mr-1.5 w-3.5 h-3.5 text-gray-400 dark:text-gray-500'
strokeWidth={2}
/>
);
const resetFilters = () => {
if (!formApi) return;
const fresh =
typeof getFreshInitValues === 'function'
? getFreshInitValues()
: formInitValues;
formApi.setValues(fresh, { isOverride: true });
setTimeout(() => {
refresh();
}, 100);
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => setFormApi(api)}
onSubmit={refresh}
allowEmpty={true}
autoComplete='off'
layout='vertical'
trigger='change'
stopValidateWithError={false}
className='usage-logs-filter-form'
>
<div className='usage-logs-filter-content'>
<header className='usage-logs-filter-title'>
<span className='usage-logs-filter-title-icon'>
<Filter className='w-3.5 h-3.5 text-white' />
</span>
<span className='text-sm font-semibold text-gray-700 dark:text-gray-200'>
{t('筛选条件')}
</span>
</header>
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3'>
<Form.DatePicker
field='dateRange'
className={`${controlClass} lg:col-span-2`}
dropdownClassName='usage-logs-date-panel'
type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]}
showClear
pure
size='small'
prefix={<InputPrefix icon={Calendar} />}
presets={DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text),
start: preset.start(),
end: preset.end(),
}))}
/>
<Form.Input
field='token_name'
className={controlClass}
prefix={<InputPrefix icon={Key} />}
placeholder={t('令牌名称')}
showClear
pure
size='small'
/>
<Form.Input
field='model_name'
className={controlClass}
prefix={<InputPrefix icon={Cpu} />}
placeholder={t('模型名称')}
showClear
pure
size='small'
/>
<Form.Input
field='group'
className={controlClass}
prefix={<InputPrefix icon={Layers} />}
placeholder={t('分组')}
showClear
pure
size='small'
/>
{isAdminUser && (
<>
<Form.Input
field='channel'
className={controlClass}
prefix={<InputPrefix icon={Radio} />}
placeholder={t('渠道 ID')}
showClear
pure
size='small'
/>
<Form.Input
field='username'
className={controlClass}
prefix={<InputPrefix icon={Users} />}
placeholder={t('用户名称')}
showClear
pure
size='small'
/>
<Form.Input
field='user_id'
className={controlClass}
prefix={<InputPrefix icon={Hash} />}
placeholder={t('用户 ID')}
showClear
pure
size='small'
inputMode='numeric'
onKeyDown={(e) => {
if (
[
'Backspace',
'Delete',
'Tab',
'Escape',
'Enter',
'ArrowLeft',
'ArrowRight',
'ArrowUp',
'ArrowDown',
'Home',
'End',
].includes(e.key)
)
return;
if (
(e.ctrlKey || e.metaKey) &&
['a', 'c', 'v', 'x', 'z'].includes(e.key.toLowerCase())
)
return;
if (!/^\d$/.test(e.key)) e.preventDefault();
}}
onPaste={(e) => {
const paste = (
e.clipboardData || window.clipboardData
).getData('text');
if (!/^\d+$/.test(paste)) {
e.preventDefault();
const digits = paste.replace(/\D/g, '');
if (digits && formApi) {
formApi.setValue('user_id', digits);
}
}
}}
/>
</>
)}
</div>
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3'>
<Form.Select
field='logType'
placeholder={t('日志类型')}
className='w-full sm:w-auto min-w-[140px]'
showClear
pure
onChange={() => {
setTimeout(() => {
refresh();
}, 0);
}}
size='small'
>
<Form.Select.Option value='0'>{t('全部')}</Form.Select.Option>
<Form.Select.Option value='1'>{t('充值')}</Form.Select.Option>
<Form.Select.Option value='2'>{t('消费')}</Form.Select.Option>
<Form.Select.Option value='3'>{t('管理')}</Form.Select.Option>
<Form.Select.Option value='4'>{t('系统')}</Form.Select.Option>
{/* 错误日志仅管理员及以上可见,后端 self 接口同步过滤 */}
{isAdminUser && (
<Form.Select.Option value='5'>{t('错误')}</Form.Select.Option>
)}
</Form.Select>
<div className='flex flex-wrap gap-2 w-full sm:w-auto sm:justify-end'>
<Button
type='tertiary'
htmlType='submit'
loading={loading}
size='small'
className={primaryButtonClass}
style={usageRecordMode ? undefined : { color: '#ffffff' }}
icon={
<SearchIcon
className='w-3.5 h-3.5'
style={{ color: '#ffffff' }}
/>
}
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={resetFilters}
size='small'
icon={<ResetIcon className='w-3.5 h-3.5' />}
className={softButtonClass}
>
{t('重置')}
</Button>
<Button
type='tertiary'
onClick={() => setShowColumnSelector(true)}
size='small'
icon={<ColumnsIcon className='w-3.5 h-3.5' />}
className={softButtonClass}
>
{t('列设置')}
</Button>
<Button
type='tertiary'
size='small'
icon={<ExportIcon className='w-3.5 h-3.5' />}
onClick={() => setShowExportModal(true)}
className={softButtonClass}
>
{t('导出')}
</Button>
</div>
</div>
</div>
</Form>
);
};
export default LogsFilters;
@@ -0,0 +1,468 @@
/*
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, { useMemo, useState } from 'react';
import { Button, Empty, Modal, Typography } from '@douyinfe/semi-ui';
import {
Coins,
Cpu,
Eye,
Gauge,
Layers3,
ReceiptText,
RadioTower,
Sparkles,
} from 'lucide-react';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getLogOther, renderQuota } from '../../../helpers';
import { getLogsColumns } from './UsageLogsColumnDefs';
const { Text } = Typography;
const formatCount = (value) => {
const num = Number(value || 0);
if (!Number.isFinite(num)) return '-';
return num.toLocaleString();
};
const formatRatio = (value) => {
const num = Number(value);
if (!Number.isFinite(num)) return '-';
return `${Number.isInteger(num) ? num : num.toFixed(3).replace(/0+$/, '').replace(/\.$/, '')}x`;
};
const MetricCard = ({ icon: Icon, label, value, tone = 'brand' }) => {
const toneClass = {
brand:
'bg-brand/10 text-brand-deep border-brand/20 dark:bg-brand/15 dark:text-brand-from',
emerald:
'bg-emerald-50 text-emerald-700 border-emerald-200/70 dark:bg-emerald-900/[0.18] dark:text-emerald-300 dark:border-emerald-700/30',
cyan: 'bg-cyan-50 text-cyan-700 border-cyan-200/70 dark:bg-cyan-900/[0.18] dark:text-cyan-300 dark:border-cyan-700/30',
amber:
'bg-amber-50 text-amber-700 border-amber-200/70 dark:bg-amber-900/[0.18] dark:text-amber-300 dark:border-amber-700/30',
}[tone];
return (
<div className='rounded-2xl border border-white/55 bg-white/[0.45] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045]'>
<div className='mb-2 flex items-center gap-2'>
<span
className={`inline-flex h-7 w-7 items-center justify-center rounded-xl border ${toneClass}`}
>
<Icon size={14} />
</span>
<Text type='tertiary' size='small'>
{label}
</Text>
</div>
<div className='truncate text-base font-semibold text-gray-900 dark:text-white'>
{value}
</div>
</div>
);
};
const DetailPill = ({ label, value }) => {
if (value === undefined || value === null || value === '' || value === '-')
return null;
return (
<span className='inline-flex items-center gap-1 rounded-full border border-white/55 bg-white/[0.45] px-2.5 py-1 text-xs text-gray-600 backdrop-blur dark:border-white/10 dark:bg-white/[0.055] dark:text-gray-300'>
<span className='text-gray-400 dark:text-gray-500'>{label}</span>
<strong className='font-semibold text-gray-800 dark:text-gray-100'>
{value}
</strong>
</span>
);
};
const UsageBillingDetail = ({ record, expandItems, isAdminUser, t }) => {
const other = getLogOther(record.other) || {};
const inputTokens = Number(record.prompt_tokens || 0);
const outputTokens = Number(record.completion_tokens || 0);
const cacheTokens =
Number(other.cache_tokens || 0) +
Number(other.cache_creation_tokens || 0) +
Number(other.cache_creation_tokens_5m || 0) +
Number(other.cache_creation_tokens_1h || 0);
const textTokens = inputTokens + outputTokens;
const effectiveGroupRatio =
Number.isFinite(Number(other.user_group_ratio)) &&
Number(other.user_group_ratio) !== -1
? other.user_group_ratio
: other.group_ratio;
const details = [
{ label: t('输入'), value: formatCount(inputTokens) },
outputTokens > 0 && { label: t('输出'), value: formatCount(outputTokens) },
other.cache_tokens > 0 && {
label: t('缓存命中'),
value: formatCount(other.cache_tokens),
},
other.cache_creation_tokens > 0 && {
label: t('缓存创建'),
value: formatCount(other.cache_creation_tokens),
},
other.cache_creation_tokens_5m > 0 && {
label: t('5m 缓存创建'),
value: formatCount(other.cache_creation_tokens_5m),
},
other.cache_creation_tokens_1h > 0 && {
label: t('1h 缓存创建'),
value: formatCount(other.cache_creation_tokens_1h),
},
other.model_ratio != null && {
label: t('模型倍率'),
value: formatRatio(other.model_ratio),
},
other.completion_ratio != null && {
label: t('输出倍率'),
value: formatRatio(other.completion_ratio),
},
other.cache_ratio != null &&
cacheTokens > 0 && {
label: t('缓存倍率'),
value: formatRatio(other.cache_ratio),
},
other.cache_creation_ratio != null &&
other.cache_creation_tokens > 0 && {
label: t('缓存创建倍率'),
value: formatRatio(other.cache_creation_ratio),
},
other.cache_creation_ratio_5m != null &&
other.cache_creation_tokens_5m > 0 && {
label: t('5m 缓存倍率'),
value: formatRatio(other.cache_creation_ratio_5m),
},
other.cache_creation_ratio_1h != null &&
other.cache_creation_tokens_1h > 0 && {
label: t('1h 缓存倍率'),
value: formatRatio(other.cache_creation_ratio_1h),
},
effectiveGroupRatio != null && {
label: t('分组倍率'),
value: formatRatio(effectiveGroupRatio),
},
other.audio_input > 0 && {
label: t('音频输入'),
value: formatCount(other.audio_input),
},
other.audio_output > 0 && {
label: t('音频输出'),
value: formatCount(other.audio_output),
},
other.audio_input_token_count > 0 && {
label: t('音频计费 Tokens'),
value: formatCount(other.audio_input_token_count),
},
other.audio_ratio != null &&
(other.audio_input > 0 || other.audio_input_token_count > 0) && {
label: t('音频倍率'),
value: formatRatio(other.audio_ratio),
},
other.audio_completion_ratio != null &&
other.audio_output > 0 && {
label: t('音频输出倍率'),
value: formatRatio(other.audio_completion_ratio),
},
other.image &&
other.image_output > 0 && {
label: t('图片 Tokens'),
value: formatCount(other.image_output),
},
other.web_search && {
label: t('联网搜索'),
value: `${formatCount(other.web_search_call_count || 0)} ${t('次')}`,
},
other.file_search && {
label: t('文件搜索'),
value: `${formatCount(other.file_search_call_count || 0)} ${t('次')}`,
},
other.image_generation_call && {
label: t('图片生成'),
value: t('已计费'),
},
].filter(Boolean);
const mappedModel =
other?.is_model_mapped &&
other?.upstream_model_name &&
other.upstream_model_name !== record.model_name;
const billingMode =
isAdminUser && other?.admin_info
? other?.admin_info?.local_count_tokens
? t('本地计费')
: t('上游返回')
: '';
const metrics = [
{
icon: Coins,
label: t('本次花费'),
value: renderQuota(record.quota, 6),
tone: 'brand',
},
{
icon: Gauge,
label: t('文本 Tokens'),
value: formatCount(textTokens),
tone: 'emerald',
},
{
icon: Cpu,
label: mappedModel ? t('计费模型') : t('模型'),
value: record.model_name || '-',
tone: 'cyan',
},
isAdminUser && {
icon: RadioTower,
label: t('渠道'),
value: record.channel
? `${record.channel}${record.channel_name ? ` · ${record.channel_name}` : ''}`
: '-',
tone: 'amber',
},
].filter(Boolean);
if (record.type !== 2) {
return (
<div className='usage-billing-detail'>
<div className='grid gap-2 sm:grid-cols-2 lg:grid-cols-3'>
{expandItems.map((item) => (
<MetricCard
key={item.key}
icon={Sparkles}
label={item.key}
value={item.value}
/>
))}
</div>
</div>
);
}
return (
<div className='usage-billing-detail'>
<div className='mb-3 flex flex-wrap items-center justify-between gap-2'>
<div>
<div className='flex items-center gap-2 text-sm font-semibold text-gray-900 dark:text-white'>
<Sparkles size={15} className='text-brand' />
{t('计费摘要')}
</div>
<Text type='tertiary' size='small'>
{t('保留关键成本因子,省略冗长计算公式')}
</Text>
</div>
<div className='rounded-full border border-brand/20 bg-brand/10 px-3 py-1 text-sm font-semibold text-brand-deep dark:bg-brand/15 dark:text-brand-from'>
{renderQuota(record.quota, 6)}
</div>
</div>
<div className='grid gap-3 sm:grid-cols-2 xl:grid-cols-4'>
{metrics.map((item) => (
<MetricCard key={item.label} {...item} />
))}
</div>
<div className='mt-3 rounded-2xl border border-white/55 bg-white/[0.35] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.04]'>
<div className='mb-2 flex items-center gap-2 text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<Layers3 size={13} />
{t('成本因子')}
</div>
<div className='flex flex-wrap gap-2'>
{details.map((item) => (
<DetailPill key={item.label} {...item} />
))}
{mappedModel && (
<DetailPill
label={t('实际模型')}
value={other.upstream_model_name}
/>
)}
{billingMode && (
<DetailPill label={t('计费源')} value={billingMode} />
)}
</div>
</div>
</div>
);
};
const LogsTable = (logsData) => {
const {
logs,
expandData,
loading,
activePage,
pageSize,
logCount,
compactMode,
visibleColumns,
handlePageChange,
handlePageSizeChange,
copyText,
showUserInfoFunc,
hasExpandableRows,
isAdminUser,
isRootUser,
t,
COLUMN_KEYS,
} = logsData;
const [detailRecord, setDetailRecord] = useState(null);
// Get all columns
const allColumns = useMemo(() => {
return getLogsColumns({
t,
COLUMN_KEYS,
copyText,
showUserInfoFunc,
isAdminUser,
isRootUser,
});
}, [t, COLUMN_KEYS, copyText, showUserInfoFunc, isAdminUser, isRootUser]);
// Filter columns based on visibility settings
const getVisibleColumns = () => {
return allColumns.filter((column) => visibleColumns[column.key]);
};
const visibleColumnsList = useMemo(() => {
return getVisibleColumns();
}, [visibleColumns, allColumns]);
const tableColumns = useMemo(() => {
const baseColumns = compactMode
? visibleColumnsList.map(({ fixed, ...rest }) => rest)
: visibleColumnsList;
if (!hasExpandableRows()) return baseColumns;
return [
...baseColumns,
{
title: t('计费详情'),
key: 'billingDetailAction',
fixed: compactMode ? undefined : 'right',
width: 120,
render: (_, record) => {
const canView =
expandData[record.key] && expandData[record.key].length > 0;
return (
<Button
size='small'
theme='light'
type='primary'
disabled={!canView}
icon={<Eye size={14} />}
onClick={(e) => {
e?.stopPropagation?.();
if (canView) setDetailRecord(record);
}}
className='usage-record-action-button usage-record-action-button-soft !rounded-full'
>
{t('查看')}
</Button>
);
},
},
];
}, [
compactMode,
visibleColumnsList,
expandData,
hasExpandableRows,
t,
]);
return (
<>
<CardTable
columns={tableColumns}
dataSource={logs}
rowKey='key'
loading={loading}
scroll={compactMode ? undefined : { x: 'max-content' }}
className='rounded-xl overflow-hidden usage-logs-table'
size='middle'
empty={
<div className='py-12'>
<Empty
image={
<IllustrationNoResult style={{ width: 180, height: 180 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 180, height: 180 }} />
}
description={
<div className='flex flex-col items-center gap-2'>
<span className='text-gray-500 dark:text-gray-400 text-sm'>
{t('搜索无结果')}
</span>
<span className='text-gray-400 dark:text-gray-500 text-xs'>
{t('尝试调整筛选条件')}
</span>
</div>
}
/>
</div>
}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: logCount,
pageSizeOptions: [10, 20, 50, 100],
showSizeChanger: true,
onPageSizeChange: (size) => {
handlePageSizeChange(size);
},
onPageChange: handlePageChange,
}}
hidePagination={true}
/>
<Modal
visible={!!detailRecord}
onCancel={() => setDetailRecord(null)}
footer={null}
centered
width={860}
title={
<div className='flex items-center gap-2'>
<span className='inline-flex h-9 w-9 items-center justify-center rounded-2xl bg-brand/10 text-brand-deep dark:bg-brand/15 dark:text-brand-from'>
<ReceiptText size={18} />
</span>
<span>{t('计费详情')}</span>
</div>
}
bodyStyle={{ padding: 20 }}
>
{detailRecord && (
<UsageBillingDetail
record={detailRecord}
expandItems={expandData[detailRecord.key] || []}
isAdminUser={isAdminUser}
t={t}
/>
)}
</Modal>
</>
);
};
export default LogsTable;
+72
View File
@@ -0,0 +1,72 @@
/*
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 from 'react';
import CardPro from '../../common/ui/CardPro';
import LogsTable from './UsageLogsTable';
import LogsFilters from './UsageLogsFilters';
import ColumnSelectorModal from './modals/ColumnSelectorModal';
import UserInfoModal from './modals/UserInfoModal';
import UsageLogsExportModal from './modals/UsageLogsExportModal';
import { useLogsData } from '../../../hooks/usage-logs/useUsageLogsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
import './UsageLogs.css';
const LogsPage = ({ usageRecordMode = false }) => {
const logsData = useLogsData();
const isMobile = useIsMobile();
return (
<>
{/* Modals */}
<ColumnSelectorModal {...logsData} usageRecordMode={usageRecordMode} />
<UserInfoModal {...logsData} />
<UsageLogsExportModal {...logsData} usageRecordMode={usageRecordMode} />
{/* Main Content */}
<CardPro
type='type2'
className='usage-logs-page usage-logs-panel !bg-white/[0.34] dark:!bg-neutral-950/[0.34] !border-white/50 dark:!border-white/10 !shadow-[0_24px_80px_rgba(15,23,42,0.08)] dark:!shadow-[0_24px_80px_rgba(0,0,0,0.32)] relative !backdrop-blur-2xl !backdrop-saturate-150'
searchArea={
<LogsFilters {...logsData} usageRecordMode={usageRecordMode} />
}
paginationArea={createCardProPagination({
currentPage: logsData.activePage,
pageSize: logsData.pageSize,
total: logsData.logCount,
onPageChange: logsData.handlePageChange,
onPageSizeChange: logsData.handlePageSizeChange,
isMobile: isMobile,
t: logsData.t,
})}
t={logsData.t}
>
<div className='app-card usage-logs-table-shell usage-logs-glass-table mt-4 overflow-hidden'>
<LogsTable
{...logsData}
compactMode={usageRecordMode ? false : logsData.compactMode}
/>
</div>
</CardPro>
</>
);
};
export default LogsPage;
@@ -0,0 +1,160 @@
/*
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 from 'react';
import { Modal, Button, Checkbox } from '@douyinfe/semi-ui';
import { Check, RefreshCcw, X } from 'lucide-react';
import { getLogsColumns } from '../UsageLogsColumnDefs';
const ColumnSelectorModal = ({
showColumnSelector,
setShowColumnSelector,
visibleColumns,
handleColumnVisibilityChange,
handleSelectAll,
initDefaultColumns,
COLUMN_KEYS,
isAdminUser,
isRootUser,
copyText,
showUserInfoFunc,
usageRecordMode = false,
t,
}) => {
// Get all columns for display in selector
const allColumns = getLogsColumns({
t,
COLUMN_KEYS,
copyText,
showUserInfoFunc,
isAdminUser,
isRootUser,
});
// 计算"全选"状态时应忽略的 key:当前角色下不可见的管理员专属列
// 否则非管理员下 CHANNEL/USERNAME/RETRY 永远为 false,全选框永远半选
const isHiddenForRole = (key) =>
!isAdminUser &&
(key === COLUMN_KEYS.CHANNEL ||
key === COLUMN_KEYS.USERNAME ||
key === COLUMN_KEYS.RETRY);
const effectiveValues = Object.entries(visibleColumns)
.filter(([key]) => !isHiddenForRole(key))
.map(([, v]) => v);
const allChecked =
effectiveValues.length > 0 && effectiveValues.every((v) => v === true);
const someChecked = effectiveValues.some((v) => v === true);
return (
<Modal
title={t('列设置')}
visible={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
footer={
<div className='flex justify-end gap-2'>
<Button
size={usageRecordMode ? 'small' : undefined}
icon={
usageRecordMode ? (
<RefreshCcw className='w-3.5 h-3.5' />
) : undefined
}
onClick={() => initDefaultColumns()}
className={
usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: undefined
}
>
{t('重置')}
</Button>
<Button
size={usageRecordMode ? 'small' : undefined}
icon={usageRecordMode ? <X className='w-3.5 h-3.5' /> : undefined}
onClick={() => setShowColumnSelector(false)}
className={
usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: undefined
}
>
{t('取消')}
</Button>
<Button
size={usageRecordMode ? 'small' : undefined}
icon={
usageRecordMode ? (
<Check className='w-3.5 h-3.5' style={{ color: '#fff' }} />
) : undefined
}
onClick={() => setShowColumnSelector(false)}
className={
usageRecordMode
? 'usage-record-action-button usage-record-action-button-primary'
: undefined
}
>
{t('确定')}
</Button>
</div>
}
>
<div style={{ marginBottom: 20 }}>
<Checkbox
checked={allChecked}
indeterminate={someChecked && !allChecked}
onChange={(e) => handleSelectAll(e.target.checked)}
>
{t('全选')}
</Checkbox>
</div>
<div
className='flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4'
style={{ border: '1px solid var(--semi-color-border)' }}
>
{allColumns.map((column) => {
// Skip admin-only columns for non-admin users
if (
!isAdminUser &&
(column.key === COLUMN_KEYS.CHANNEL ||
column.key === COLUMN_KEYS.USERNAME ||
column.key === COLUMN_KEYS.RETRY)
) {
return null;
}
return (
<div key={column.key} className='w-1/2 mb-4 pr-2'>
<Checkbox
checked={!!visibleColumns[column.key]}
onChange={(e) =>
handleColumnVisibilityChange(column.key, e.target.checked)
}
>
{column.title}
</Checkbox>
</div>
);
})}
</div>
</Modal>
);
};
export default ColumnSelectorModal;
@@ -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;
@@ -0,0 +1,177 @@
/*
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 from 'react';
import { Modal, Badge } from '@douyinfe/semi-ui';
import { renderQuota, renderNumber } from '../../../../helpers';
const UserInfoModal = ({
showUserInfo,
setShowUserInfoModal,
userInfoData,
t,
}) => {
const infoItemStyle = {
marginBottom: '16px',
};
const labelStyle = {
display: 'flex',
alignItems: 'center',
marginBottom: '2px',
fontSize: '12px',
color: 'var(--semi-color-text-2)',
gap: '6px',
};
const renderLabel = (text, type = 'tertiary') => (
<div style={labelStyle}>
<Badge dot type={type} />
{text}
</div>
);
const valueStyle = {
fontSize: '14px',
fontWeight: '600',
color: 'var(--semi-color-text-0)',
};
const rowStyle = {
display: 'flex',
justifyContent: 'space-between',
marginBottom: '16px',
gap: '20px',
};
const colStyle = {
flex: 1,
minWidth: 0,
};
return (
<Modal
title={t('用户信息')}
visible={showUserInfo}
onCancel={() => setShowUserInfoModal(false)}
footer={null}
centered
closable
maskClosable
width={600}
>
{userInfoData && (
<div style={{ padding: 20 }}>
{/* 基本信息 */}
<div style={rowStyle}>
<div style={colStyle}>
{renderLabel(t('用户名'), 'primary')}
<div style={valueStyle}>{userInfoData.username}</div>
</div>
{userInfoData.display_name && (
<div style={colStyle}>
{renderLabel(t('显示名称'), 'primary')}
<div style={valueStyle}>{userInfoData.display_name}</div>
</div>
)}
</div>
{/* 余额信息 */}
<div style={rowStyle}>
<div style={colStyle}>
{renderLabel(t('余额'), 'success')}
<div style={valueStyle}>{renderQuota(userInfoData.quota)}</div>
</div>
<div style={colStyle}>
{renderLabel(t('已用额度'), 'warning')}
<div style={valueStyle}>
{renderQuota(userInfoData.used_quota)}
</div>
</div>
</div>
{/* 统计信息 */}
<div style={rowStyle}>
<div style={colStyle}>
{renderLabel(t('请求次数'), 'warning')}
<div style={valueStyle}>
{renderNumber(userInfoData.request_count)}
</div>
</div>
{userInfoData.group && (
<div style={colStyle}>
{renderLabel(t('用户组'), 'tertiary')}
<div style={valueStyle}>{userInfoData.group}</div>
</div>
)}
</div>
{/* 邀请信息 */}
{(userInfoData.aff_code || userInfoData.aff_count !== undefined) && (
<div style={rowStyle}>
{userInfoData.aff_code && (
<div style={colStyle}>
{renderLabel(t('邀请码'), 'tertiary')}
<div style={valueStyle}>{userInfoData.aff_code}</div>
</div>
)}
{userInfoData.aff_count !== undefined && (
<div style={colStyle}>
{renderLabel(t('邀请人数'), 'tertiary')}
<div style={valueStyle}>
{renderNumber(userInfoData.aff_count)}
</div>
</div>
)}
</div>
)}
{/* 邀请获得额度 */}
{userInfoData.aff_quota !== undefined &&
userInfoData.aff_quota > 0 && (
<div style={infoItemStyle}>
{renderLabel(t('邀请获得额度'), 'success')}
<div style={valueStyle}>
{renderQuota(userInfoData.aff_quota)}
</div>
</div>
)}
{/* 备注 */}
{userInfoData.remark && (
<div style={{ marginBottom: 0 }}>
{renderLabel(t('备注'), 'tertiary')}
<div
style={{
...valueStyle,
wordBreak: 'break-all',
lineHeight: '1.4',
}}
>
{userInfoData.remark}
</div>
</div>
)}
</div>
)}
</Modal>
);
};
export default UserInfoModal;