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,67 @@
/*
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, Tag } from '@douyinfe/semi-ui';
import { isAdmin } from '../../../helpers';
const AdminTokensActions = ({
selectedRowKeys,
onBatchAction,
onRefresh,
t,
}) => {
const hasSelection = selectedRowKeys && selectedRowKeys.length > 0;
return (
<div className='flex flex-wrap items-center gap-2 w-full md:w-auto order-2 md:order-1'>
{hasSelection && (
<Tag color='violet' shape='circle' size='small'>
{t('已选 {{count}} 项', { count: selectedRowKeys.length })}
</Tag>
)}
{isAdmin() && hasSelection && (
<>
<Button size='small' onClick={() => onBatchAction('enable')}>
{t('批量启用')}
</Button>
<Button
size='small'
type='warning'
onClick={() => onBatchAction('disable')}
>
{t('批量禁用')}
</Button>
<Button
size='small'
type='danger'
onClick={() => onBatchAction('delete')}
>
{t('批量删除')}
</Button>
</>
)}
<Button size='small' type='tertiary' onClick={onRefresh}>
{t('刷新')}
</Button>
</div>
);
};
export default AdminTokensActions;
@@ -0,0 +1,289 @@
/*
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,
Space,
Tag,
Typography,
Popover,
Dropdown,
} from '@douyinfe/semi-ui';
import { IconMore } from '@douyinfe/semi-icons';
import {
renderGroup,
renderQuota,
isAdmin,
timestamp2string,
} from '../../../helpers';
const { Text } = Typography;
const statusMeta = {
1: { color: 'green', label: '已启用' },
2: { color: 'grey', label: '已禁用' },
3: { color: 'red', label: '已过期' },
4: { color: 'orange', label: '已耗尽' },
};
const renderStatus = (status, t) => {
const meta = statusMeta[status] || { color: 'red', label: t('未知状态') };
return (
<Tag color={meta.color} shape='circle' size='small'>
{t(meta.label)}
</Tag>
);
};
/**
* 用户列:display_name 主显,user_id 与 username 小字辅显
*/
const renderUserCell = (text, record, t) => {
const displayName = record.display_name || record.username || t('未知用户');
return (
<div className='flex flex-col leading-tight'>
<Text strong className='!text-sm'>
{displayName}
</Text>
<div className='flex items-center gap-1 text-xs text-[var(--semi-color-text-2)]'>
<span>#{record.user_id}</span>
{record.username && record.username !== displayName && (
<span className='truncate max-w-[120px]'>@{record.username}</span>
)}
</div>
</div>
);
};
const renderKey = (text, record) => {
// 后端已脱敏,前端再加 sk- 前缀
return (
<code className='text-xs bg-[var(--semi-color-fill-0)] px-2 py-0.5 rounded font-mono'>
sk-{text}
</code>
);
};
const renderQuotaCell = (text, record, t) => {
if (record.unlimited_quota) {
return (
<Tag color='violet' shape='circle' size='small'>
{t('无限制')}
</Tag>
);
}
const used = record.used_quota || 0;
const remain = record.remain_quota || 0;
const popoverContent = (
<div className='text-xs p-2'>
<div>
{t('已用')}: {renderQuota(used)}
</div>
<div>
{t('剩余')}: {renderQuota(remain)}
</div>
</div>
);
return (
<Popover content={popoverContent} position='top'>
<Tag color='white' shape='circle' size='small'>
{renderQuota(remain)}
</Tag>
</Popover>
);
};
const renderTime = (ts, t) => {
if (!ts || ts === 0)
return <span className='text-[var(--semi-color-text-2)]'>—</span>;
if (ts === -1)
return (
<Tag color='blue' shape='circle' size='small'>
{t('永不过期')}
</Tag>
);
return <span className='text-xs'>{timestamp2string(ts)}</span>;
};
const renderScope = (orgId, t) => {
if (!orgId || orgId === 0) {
return (
<Tag color='blue' shape='circle' size='small'>
{t('个人')}
</Tag>
);
}
return (
<Tag color='purple' shape='circle' size='small'>
{t('企业')} #{orgId}
</Tag>
);
};
const renderOperations = (
text,
record,
{ showEditTokenModal, showEnableDisableModal, showDeleteTokenModal, t },
) => {
if (record.DeletedAt) return <></>;
const isEnabled = record.status === 1;
if (!isAdmin()) return null;
return (
<Space>
<Button
size='small'
type='tertiary'
onClick={() => showEditTokenModal(record)}
>
{t('编辑')}
</Button>
{isEnabled ? (
<Button
size='small'
type='danger'
onClick={() => showEnableDisableModal(record, 'disable')}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={() => showEnableDisableModal(record, 'enable')}
>
{t('启用')}
</Button>
)}
<Dropdown
trigger='click'
position='bottomRight'
menu={[
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => showDeleteTokenModal(record),
},
]}
>
<Button size='small' type='tertiary' icon={<IconMore />} />
</Dropdown>
</Space>
);
};
export const getAdminTokensColumns = ({
t,
showEditTokenModal,
showEnableDisableModal,
showDeleteTokenModal,
}) => {
return [
{
title: 'ID',
dataIndex: 'id',
width: 70,
},
{
title: t('用户'),
dataIndex: 'user',
width: 180,
render: (text, record) => renderUserCell(text, record, t),
},
{
title: t('秘钥名称'),
dataIndex: 'name',
render: (text) => (
<span className='truncate inline-block max-w-[160px]' title={text}>
{text || <Text type='tertiary'>—</Text>}
</span>
),
},
{
title: t('秘钥'),
dataIndex: 'key',
render: renderKey,
},
{
title: t('状态'),
dataIndex: 'status',
width: 90,
render: (text) => renderStatus(text, t),
},
{
title: t('归属'),
dataIndex: 'organization_id',
width: 100,
render: (text) => renderScope(text, t),
},
{
title: t('分组'),
dataIndex: 'group',
width: 110,
render: (text) => <div>{renderGroup(text)}</div>,
},
{
title: t('剩余额度'),
dataIndex: 'remain_quota',
width: 110,
render: (text, record) => renderQuotaCell(text, record, t),
},
{
title: t('已用额度'),
dataIndex: 'used_quota',
width: 110,
render: (text) => (
<Text type='tertiary' size='small'>
{renderQuota(text || 0)}
</Text>
),
},
{
title: t('创建时间'),
dataIndex: 'created_time',
width: 160,
render: (text) => renderTime(text, t),
},
{
title: t('过期时间'),
dataIndex: 'expired_time',
width: 160,
render: (text) => renderTime(text, t),
},
{
title: t('最近访问'),
dataIndex: 'accessed_time',
width: 160,
render: (text) => renderTime(text, t),
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
width: 200,
render: (text, record) =>
renderOperations(text, record, {
showEditTokenModal,
showEnableDisableModal,
showDeleteTokenModal,
t,
}),
},
];
};
@@ -0,0 +1,46 @@
/*
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 { Typography, Tag } from '@douyinfe/semi-ui';
import { IconKey } from '@douyinfe/semi-icons';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const AdminTokensDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center gap-2 text-brand'>
<IconKey />
<Text>{t('秘钥管理')}</Text>
<Tag color='orange' shape='circle' size='small'>
{t('管理员')}
</Tag>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default AdminTokensDescription;
@@ -0,0 +1,168 @@
/*
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, { useRef } from 'react';
import { Form, Button } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
const AdminTokensFilters = ({
formInitValues,
setFormApi,
searchTokens,
debouncedSearch,
loadTokens,
pageSize,
groupOptions,
loading,
searching,
t,
}) => {
const formApiRef = useRef(null);
const handleReset = () => {
if (!formApiRef.current) return;
formApiRef.current.reset();
// 重置后立即用初始值刷新(不走 debounce)
loadTokens(1, pageSize, formInitValues);
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => {
setFormApi(api);
formApiRef.current = api;
}}
onSubmit={() => searchTokens(pageSize)}
allowEmpty
autoComplete='off'
layout='horizontal'
trigger='change'
className='w-full md:w-auto order-1 md:order-2'
>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto flex-wrap'>
<div className='w-full md:w-56'>
<Form.Input
field='keyword'
prefix={<IconSearch />}
placeholder={t('秘钥名称 / Key 片段')}
showClear
pure
size='small'
/>
</div>
<div className='w-full md:w-44'>
<Form.Input
field='user_keyword'
placeholder={t('用户名/昵称')}
showClear
pure
size='small'
/>
</div>
<div className='w-full md:w-28'>
<Form.Input
field='user_id'
placeholder={t('用户ID')}
type='number'
showClear
pure
size='small'
/>
</div>
<div className='w-full md:w-44'>
<Form.Select
field='statuses'
placeholder={t('状态(多选)')}
multiple
optionList={[
{ label: t('已启用'), value: 1 },
{ label: t('已禁用'), value: 2 },
{ label: t('已过期'), value: 3 },
{ label: t('已耗尽'), value: 4 },
]}
showClear
pure
size='small'
className='w-full'
onChange={debouncedSearch}
/>
</div>
<div className='w-full md:w-36'>
<Form.Select
field='group'
placeholder={t('分组')}
optionList={groupOptions}
showClear
pure
size='small'
className='w-full'
onChange={debouncedSearch}
/>
</div>
<div className='w-full md:w-32'>
<Form.Select
field='unlimited'
placeholder={t('额度类型')}
optionList={[
{ label: t('无限额度'), value: true },
{ label: t('有限额度'), value: false },
]}
showClear
pure
size='small'
className='w-full'
onChange={debouncedSearch}
/>
</div>
<div className='w-full md:w-32'>
<Form.Select
field='org_scope'
placeholder={t('归属')}
optionList={[
{ label: t('全部'), value: 'all' },
{ label: t('个人'), value: 'personal' },
{ label: t('企业'), value: 'org' },
]}
showClear={false}
pure
size='small'
className='w-full'
onChange={debouncedSearch}
/>
</div>
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading || searching}
size='small'
>
{t('查询')}
</Button>
<Button type='tertiary' onClick={handleReset} size='small'>
{t('重置')}
</Button>
</div>
</div>
</Form>
);
};
export default AdminTokensFilters;
@@ -0,0 +1,129 @@
/*
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 } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getAdminTokensColumns } from './AdminTokensColumnDefs';
const AdminTokensTable = ({
tokens,
loading,
activePage,
pageSize,
tokenCount,
compactMode,
selectedRowKeys,
setSelectedRowKeys,
handlePageChange,
handlePageSizeChange,
handleRow,
setEditingToken,
setShowEdit,
setModalToken,
setEnableDisableAction,
setShowEnableDisable,
setShowDelete,
t,
}) => {
const showEditTokenModal = (token) => {
setEditingToken(token);
setShowEdit(true);
};
const showEnableDisableModal = (token, action) => {
setModalToken(token);
setEnableDisableAction(action);
setShowEnableDisable(true);
};
const showDeleteTokenModal = (token) => {
setModalToken(token);
setShowDelete(true);
};
const columns = useMemo(
() =>
getAdminTokensColumns({
t,
showEditTokenModal,
showEnableDisableModal,
showDeleteTokenModal,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[t],
);
const tableColumns = useMemo(
() =>
compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns,
[compactMode, columns],
);
const rowSelection = {
selectedRowKeys,
onChange: (keys) => setSelectedRowKeys(keys),
};
return (
<CardTable
columns={tableColumns}
dataSource={tokens}
rowKey='id'
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
pageSizeOpts: [10, 20, 50, 100],
showSizeChanger: true,
onPageSizeChange: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
loading={loading}
onRow={handleRow}
rowSelection={rowSelection}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='overflow-hidden'
size='middle'
/>
);
};
export default AdminTokensTable;
+219
View File
@@ -0,0 +1,219 @@
/*
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 AdminTokensTable from './AdminTokensTable';
import AdminTokensActions from './AdminTokensActions';
import AdminTokensFilters from './AdminTokensFilters';
import AdminTokensDescription from './AdminTokensDescription';
import AdminEditTokenModal from './modals/AdminEditTokenModal';
import AdminEnableDisableTokenModal from './modals/AdminEnableDisableTokenModal';
import AdminDeleteTokenModal from './modals/AdminDeleteTokenModal';
import AdminBatchActionModal from './modals/AdminBatchActionModal';
import { useAdminTokensData } from '../../../hooks/admin-tokens/useAdminTokensData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
const AdminTokensPage = () => {
const data = useAdminTokensData();
const isMobile = useIsMobile();
const {
tokens,
loading,
searching,
activePage,
pageSize,
tokenCount,
groupOptions,
selectedRowKeys,
setSelectedRowKeys,
showEdit,
editingToken,
setEditingToken,
setShowEdit,
closeEdit,
showEnableDisable,
setShowEnableDisable,
enableDisableAction,
setEnableDisableAction,
showDelete,
setShowDelete,
showBatchAction,
setShowBatchAction,
batchAction,
setBatchAction,
modalToken,
setModalToken,
formInitValues,
setFormApi,
loadTokens,
searchTokens,
debouncedSearch,
refresh,
manageToken,
batchManageTokens,
handlePageChange,
handlePageSizeChange,
handleRow,
compactMode,
setCompactMode,
t,
} = data;
const handleBatchClick = (action) => {
setBatchAction(action);
setShowBatchAction(true);
};
const handleBatchConfirm = async () => {
await batchManageTokens(selectedRowKeys, batchAction);
setShowBatchAction(false);
};
const handleEnableDisableConfirm = async () => {
if (!modalToken) return;
await manageToken(modalToken.id, enableDisableAction);
setShowEnableDisable(false);
};
const handleDeleteConfirm = async () => {
if (!modalToken) return;
await manageToken(modalToken.id, 'delete');
setShowDelete(false);
};
const handleEditConfirm = async () => {
closeEdit();
await refresh();
};
return (
<>
<AdminEditTokenModal
visible={showEdit}
onCancel={closeEdit}
onConfirm={handleEditConfirm}
token={editingToken}
groupOptions={groupOptions}
t={t}
/>
<AdminEnableDisableTokenModal
visible={showEnableDisable}
onCancel={() => setShowEnableDisable(false)}
onConfirm={handleEnableDisableConfirm}
token={modalToken}
action={enableDisableAction}
t={t}
/>
<AdminDeleteTokenModal
visible={showDelete}
onCancel={() => setShowDelete(false)}
onConfirm={handleDeleteConfirm}
token={modalToken}
t={t}
/>
<AdminBatchActionModal
visible={showBatchAction}
onCancel={() => setShowBatchAction(false)}
onConfirm={handleBatchConfirm}
action={batchAction}
count={selectedRowKeys.length}
t={t}
/>
<CardPro
type='type1'
descriptionArea={
<AdminTokensDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<AdminTokensActions
selectedRowKeys={selectedRowKeys}
onBatchAction={handleBatchClick}
onRefresh={refresh}
t={t}
/>
<AdminTokensFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchTokens={searchTokens}
debouncedSearch={debouncedSearch}
loadTokens={loadTokens}
pageSize={pageSize}
groupOptions={groupOptions}
loading={loading}
searching={searching}
t={t}
/>
</div>
}
paginationArea={createCardProPagination({
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
onPageChange: handlePageChange,
onPageSizeChange: handlePageSizeChange,
isMobile: isMobile,
t,
})}
t={t}
>
<AdminTokensTable
tokens={tokens}
loading={loading}
activePage={activePage}
pageSize={pageSize}
tokenCount={tokenCount}
compactMode={compactMode}
selectedRowKeys={selectedRowKeys}
setSelectedRowKeys={setSelectedRowKeys}
handlePageChange={handlePageChange}
handlePageSizeChange={handlePageSizeChange}
handleRow={handleRow}
setEditingToken={setEditingToken}
setShowEdit={setShowEdit}
setModalToken={setModalToken}
setEnableDisableAction={setEnableDisableAction}
setShowEnableDisable={setShowEnableDisable}
setShowDelete={setShowDelete}
t={t}
/>
</CardPro>
</>
);
};
export default AdminTokensPage;
@@ -0,0 +1,73 @@
/*
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, Banner } from '@douyinfe/semi-ui';
const actionMeta = {
enable: { title: '批量启用', danger: false, hint: '将选中秘钥批量启用' },
disable: {
title: '批量禁用',
danger: true,
hint: '将选中秘钥批量禁用,用户将无法使用',
},
delete: {
title: '批量删除',
danger: true,
hint: '将选中秘钥批量删除,操作不可恢复',
},
};
const AdminBatchActionModal = ({
visible,
onCancel,
onConfirm,
action,
count,
t,
}) => {
const meta = actionMeta[action] || {
title: '批量操作',
danger: false,
hint: '',
};
return (
<Modal
title={t(meta.title)}
visible={visible}
onCancel={onCancel}
onOk={onConfirm}
type={meta.danger ? 'danger' : 'warning'}
okType={meta.danger ? 'danger' : 'primary'}
okText={t('确认执行')}
>
<div className='space-y-2'>
<div>{t('共选中 {{count}} 个秘钥', { count })}</div>
<Banner
type={meta.danger ? 'danger' : 'info'}
description={t(meta.hint)}
closeIcon={null}
/>
</div>
</Modal>
);
};
export default AdminBatchActionModal;
@@ -0,0 +1,63 @@
/*
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, Typography, Banner } from '@douyinfe/semi-ui';
const { Text } = Typography;
const AdminDeleteTokenModal = ({ visible, onCancel, onConfirm, token, t }) => {
if (!token) return null;
const isOrgToken = token.organization_id && token.organization_id > 0;
return (
<Modal
title={t('确定要删除此秘钥吗?')}
visible={visible}
onCancel={onCancel}
onOk={onConfirm}
type='danger'
okType='danger'
okText={t('确认删除')}
>
<div className='space-y-2'>
{isOrgToken && (
<Banner
type='warning'
description={t(
'该秘钥属于企业 Token,删除将影响企业内多用户的使用',
)}
closeIcon={null}
/>
)}
<div>{t('删除后将无法恢复,且会立即终止使用此秘钥的所有调用')}</div>
<Text type='tertiary' size='small'>
{t('秘钥名称')}:{token.name || '—'}
</Text>
<br />
<Text type='tertiary' size='small'>
{t('所属用户')}:{token.display_name || token.username || '—'} (ID:{' '}
{token.user_id})
</Text>
</div>
</Modal>
);
};
export default AdminDeleteTokenModal;
@@ -0,0 +1,252 @@
/*
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, useRef, useState } from 'react';
import { Modal, Form, Typography, Banner, Spin, Tag } from '@douyinfe/semi-ui';
import { API, showError, renderQuotaWithPrompt } from '../../../../helpers';
import {
quotaToMoney,
moneyToQuota,
} from '../../../common/ui/QuotaInput';
const { Text } = Typography;
const statusMeta = {
1: { color: 'green', label: '已启用' },
2: { color: 'grey', label: '已禁用' },
3: { color: 'red', label: '已过期' },
4: { color: 'orange', label: '已耗尽' },
};
/**
* 管理员编辑秘钥弹窗
* 允许修改:name / group / unlimited_quota / remain_quota / expired_time
* 不修改:
* - status —— 启用/禁用走专用按钮,避免在编辑路径上绕过状态校验
* - user_id / key / used_quota / model_limits / allow_ips —— 由用户自管
*/
const AdminEditTokenModal = ({
visible,
onCancel,
onConfirm,
token,
groupOptions,
t,
}) => {
const formApiRef = useRef(null);
const [submitting, setSubmitting] = useState(false);
const [unlimited, setUnlimited] = useState(false);
const [neverExpire, setNeverExpire] = useState(false);
useEffect(() => {
if (visible && token) {
// expired_time 视为"永不过期"的情况:-1(约定)或 0(旧数据兜底)
const isNeverExpire =
token.expired_time === -1 || token.expired_time === 0;
setUnlimited(!!token.unlimited_quota);
setNeverExpire(isNeverExpire);
setTimeout(() => {
formApiRef.current?.setValues({
name: token.name || '',
group: token.group || '',
unlimited_quota: !!token.unlimited_quota,
// remain_quota 内部单位是 token 数;UI 用元(quota_per_unit 额度 = ¥1)
remain_quota_amount: token.unlimited_quota
? 0
: quotaToMoney(token.remain_quota || 0) || 0,
expired_time:
!isNeverExpire && token.expired_time > 0
? new Date(token.expired_time * 1000)
: null,
never_expire: isNeverExpire,
});
}, 0);
}
}, [visible, token]);
const handleSubmit = async () => {
if (!formApiRef.current) return;
let values;
try {
values = await formApiRef.current.validate();
} catch (e) {
return;
}
if (!token) return;
// 显式校验:未勾选"永不过期"时必须选过期时间,避免被默默改为 -1
if (!values.never_expire && !values.expired_time) {
showError(t('请选择过期时间'));
return;
}
setSubmitting(true);
// 注意:不传 status / model_limits / allow_ips / model_limits_enabled
// status 由专用按钮处理;其余字段由 Token 所属用户自行管理
// 后端 AdminUpdateTokenById 会保留 DB 中的原值
const payload = {
id: token.id,
name: values.name || '',
group: values.group || '',
unlimited_quota: !!values.unlimited_quota,
remain_quota: values.unlimited_quota
? token.remain_quota
: moneyToQuota(values.remain_quota_amount || 0) || 0,
expired_time: values.never_expire
? -1
: Math.floor(new Date(values.expired_time).getTime() / 1000),
};
try {
const res = await API.put('/api/token/admin', payload);
const { success, message } = res.data;
if (success) {
onConfirm && onConfirm();
} else {
showError(message);
}
} catch (e) {
console.error('[AdminEditToken] save failed:', e);
showError(e.message || t('保存失败'));
} finally {
setSubmitting(false);
}
};
if (!token) return null;
const isOrgToken = token.organization_id && token.organization_id > 0;
const curStatusMeta = statusMeta[token.status] || statusMeta[2];
return (
<Modal
title={t('编辑秘钥')}
visible={visible}
onCancel={onCancel}
onOk={handleSubmit}
confirmLoading={submitting}
okText={t('保存')}
cancelText={t('取消')}
width={560}
>
<Spin spinning={submitting}>
<div className='mb-3'>
<Banner
type='info'
description={
<span>
{t('正在以管理员身份编辑')}{' '}
<Text strong>
{token.display_name || token.username || '—'}
</Text>{' '}
(ID: {token.user_id}) {t('的秘钥')}
<Tag
color={curStatusMeta.color}
shape='circle'
size='small'
className='!ml-2'
>
{t(curStatusMeta.label)}
</Tag>
</span>
}
closeIcon={null}
/>
{isOrgToken && (
<Banner
type='warning'
description={t(
'该秘钥属于企业 Token,修改额度或过期时间将影响企业内多用户的使用',
)}
closeIcon={null}
className='!mt-2'
/>
)}
<div className='mt-2 text-xs text-[var(--semi-color-text-2)]'>
{t('启用 / 禁用请使用列表中的专用按钮')}
</div>
</div>
<Form
getFormApi={(api) => (formApiRef.current = api)}
labelPosition='left'
labelWidth={110}
>
<Form.Input
field='name'
label={t('秘钥名称')}
placeholder={t('给秘钥起个名字')}
maxLength={30}
rules={[{ required: true, message: t('请输入秘钥名称') }]}
/>
<Form.Select
field='group'
label={t('分组')}
optionList={groupOptions}
allowClear
placeholder={t('使用用户默认分组')}
className='w-full'
/>
<Form.Switch
field='unlimited_quota'
label={t('无限额度')}
onChange={(v) => setUnlimited(v)}
/>
{!unlimited && (
<Form.InputNumber
field='remain_quota_amount'
label={t('剩余额度(元)')}
min={0}
precision={2}
step={1}
suffix='¥'
extraText={
<Text type='tertiary' size='small'>
{t('当前已用')}:{' '}
{renderQuotaWithPrompt(token.used_quota || 0)}
</Text>
}
className='w-full'
/>
)}
<Form.Switch
field='never_expire'
label={t('永不过期')}
onChange={(v) => setNeverExpire(v)}
/>
{!neverExpire && (
<Form.DatePicker
field='expired_time'
label={t('过期时间')}
type='dateTime'
className='w-full'
/>
)}
</Form>
</Spin>
</Modal>
);
};
export default AdminEditTokenModal;
@@ -0,0 +1,63 @@
/*
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, Typography } from '@douyinfe/semi-ui';
const { Text } = Typography;
const AdminEnableDisableTokenModal = ({
visible,
onCancel,
onConfirm,
token,
action,
t,
}) => {
const isDisable = action === 'disable';
if (!token) return null;
return (
<Modal
title={isDisable ? t('确定要禁用此秘钥吗?') : t('确定要启用此秘钥吗?')}
visible={visible}
onCancel={onCancel}
onOk={onConfirm}
type='warning'
>
<div className='space-y-1'>
<div>
{isDisable
? t('禁用后用户将无法使用此秘钥调用 API')
: t('启用后用户即可重新使用此秘钥')}
</div>
<Text type='tertiary' size='small'>
{t('秘钥名称')}:{token.name || '—'}
</Text>
<br />
<Text type='tertiary' size='small'>
{t('所属用户')}:{token.display_name || token.username || '—'} (ID:{' '}
{token.user_id})
</Text>
</div>
</Modal>
);
};
export default AdminEnableDisableTokenModal;
@@ -0,0 +1,308 @@
/*
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,
Dropdown,
Modal,
Switch,
Typography,
Select,
} from '@douyinfe/semi-ui';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
import { isRoot } from '../../../helpers';
// 批量删除/删除禁用渠道的确认文案:批量场景不逐个查反向引用,给固定影响说明
const renderBatchDeleteContent = (t) => (
<div>
<div>{t('此修改将不可逆')}</div>
<div style={{ marginTop: 8 }}>
{t('被删除的渠道若被其他渠道列为兜底,会自动从这些兜底链中移除')}
</div>
</div>
);
const ChannelsActions = ({
enableBatchDelete,
batchDeleteChannels,
setShowBatchSetTag,
testAllChannels,
fixChannelsAbilities,
updateAllChannelsBalance,
deleteAllDisabledChannels,
compactMode,
setCompactMode,
idSort,
setIdSort,
setEnableBatchDelete,
enableTagMode,
setEnableTagMode,
statusFilter,
setStatusFilter,
getFormValues,
loadChannels,
searchChannels,
activeTypeKey,
activePage,
pageSize,
setActivePage,
t,
}) => {
return (
<div className='flex flex-col gap-2'>
{/* 第一行:批量操作按钮 + 设置开关 */}
<div className='flex flex-col md:flex-row justify-between gap-2'>
{/* 左侧:批量操作按钮 */}
<div className='flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto order-2 md:order-1'>
{isRoot() && (
<Button
size='small'
disabled={!enableBatchDelete}
type='danger'
className='w-full md:w-auto'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除所选通道?'),
content: renderBatchDeleteContent(t),
onOk: () => batchDeleteChannels(),
});
}}
>
{t('删除所选通道')}
</Button>
)}
{isRoot() && (
<Button
size='small'
disabled={!enableBatchDelete}
type='tertiary'
onClick={() => setShowBatchSetTag(true)}
className='w-full md:w-auto'
>
{t('批量设置标签')}
</Button>
)}
<Dropdown
size='small'
trigger='click'
render={
<Dropdown.Menu>
{isRoot() && (
<Dropdown.Item>
<Button
size='small'
type='tertiary'
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定?'),
content: t('确定要测试所有通道吗?'),
onOk: () => testAllChannels(),
size: 'small',
centered: true,
});
}}
>
{t('测试所有通道')}
</Button>
</Dropdown.Item>
)}
{isRoot() && (
<Dropdown.Item>
<Button
size='small'
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定是否要修复数据库一致性?'),
content: t(
'进行该操作时,可能导致渠道访问错误,请仅在数据库出现问题时使用',
),
onOk: () => fixChannelsAbilities(),
size: 'sm',
centered: true,
});
}}
>
{t('修复数据库一致性')}
</Button>
</Dropdown.Item>
)}
{isRoot() && (
<Dropdown.Item>
<Button
size='small'
type='secondary'
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定?'),
content: t('确定要更新所有已启用通道余额吗?'),
onOk: () => updateAllChannelsBalance(),
size: 'sm',
centered: true,
});
}}
>
{t('更新所有已启用通道余额')}
</Button>
</Dropdown.Item>
)}
{isRoot() && (
<Dropdown.Item>
<Button
size='small'
type='danger'
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除禁用通道?'),
content: renderBatchDeleteContent(t),
onOk: () => deleteAllDisabledChannels(),
size: 'sm',
centered: true,
});
}}
>
{t('删除禁用通道')}
</Button>
</Dropdown.Item>
)}
</Dropdown.Menu>
}
>
<Button
size='small'
theme='light'
type='tertiary'
className='w-full md:w-auto'
>
{t('批量操作')}
</Button>
</Dropdown>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
{/* 右侧:设置开关区域 */}
<div className='flex flex-col md:flex-row items-start md:items-center gap-2 w-full md:w-auto order-1 md:order-2'>
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('使用ID排序')}
</Typography.Text>
<Switch
size='small'
checked={idSort}
onChange={(v) => {
localStorage.setItem('id-sort', v + '');
setIdSort(v);
const { searchKeyword, searchGroup, searchModel } =
getFormValues();
if (
searchKeyword === '' &&
searchGroup === '' &&
searchModel === ''
) {
loadChannels(activePage, pageSize, v, enableTagMode);
} else {
searchChannels(
enableTagMode,
activeTypeKey,
statusFilter,
activePage,
pageSize,
v,
);
}
}}
/>
</div>
{isRoot() && (
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('开启批量操作')}
</Typography.Text>
<Switch
size='small'
checked={enableBatchDelete}
onChange={(v) => {
localStorage.setItem('enable-batch-delete', v + '');
setEnableBatchDelete(v);
}}
/>
</div>
)}
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('标签聚合模式')}
</Typography.Text>
<Switch
size='small'
checked={enableTagMode}
onChange={(v) => {
localStorage.setItem('enable-tag-mode', v + '');
setEnableTagMode(v);
setActivePage(1);
loadChannels(1, pageSize, idSort, v);
}}
/>
</div>
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('状态筛选')}
</Typography.Text>
<Select
size='small'
value={statusFilter}
onChange={(v) => {
localStorage.setItem('channel-status-filter', v);
setStatusFilter(v);
setActivePage(1);
loadChannels(
1,
pageSize,
idSort,
enableTagMode,
activeTypeKey,
v,
);
}}
>
<Select.Option value='all'>{t('全部')}</Select.Option>
<Select.Option value='enabled'>{t('已启用')}</Select.Option>
<Select.Option value='disabled'>{t('已禁用')}</Select.Option>
</Select>
</div>
</div>
</div>
</div>
);
};
export default ChannelsActions;
@@ -0,0 +1,848 @@
/*
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,
Dropdown,
InputNumber,
Modal,
Progress,
Space,
SplitButtonGroup,
Tag,
Tooltip,
} from '@douyinfe/semi-ui';
import {
API,
timestamp2string,
renderGroup,
renderQuota,
getChannelIcon,
renderQuotaWithAmount,
showSuccess,
showError,
isRoot,
hoverOrClickTrigger,
} from '../../../helpers';
import { CHANNEL_OPTIONS } from '../../../constants';
import { IconTreeTriangleDown, IconMore } from '@douyinfe/semi-icons';
import { ShuffleBrandIcon } from '../../common/icons/BrandIcons';
// 删除单个渠道的确认文案:若该渠道被其他渠道列为兜底,追加影响说明。
// 查询失败不阻塞删除,仅回退为原确认文案
const buildDeleteConfirmContent = async (channelId, t) => {
const baseText = t('此修改将不可逆');
let referrers = [];
try {
const res = await API.get(`/api/channel/${channelId}/fallback_referrers`, {
skipErrorHandler: true,
});
if (res?.data?.success && Array.isArray(res.data.data)) {
referrers = res.data.data;
}
} catch (err) {
console.error('加载兜底反向引用失败:', err);
}
if (referrers.length === 0) return baseText;
return (
<div>
<div>{baseText}</div>
<div style={{ marginTop: 8 }}>
{t(
'该渠道被以下 {{count}} 个渠道列为兜底,删除后会从它们的兜底链中移除(兜底链变空时失败次数配置一并清空):',
{ count: referrers.length },
)}
</div>
<div style={{ marginTop: 4 }}>
{referrers.slice(0, 5).map((r) => (
<Tag key={r.id} color='orange' style={{ marginRight: 4 }}>
#{r.id} {r.name}
</Tag>
))}
{referrers.length > 5
? t('等 {{n}} 个', { n: referrers.length })
: null}
</div>
</div>
);
};
// Render functions
const renderType = (type, channelInfo = undefined, t) => {
let type2label = new Map();
for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
}
type2label[0] = { value: 0, label: t('未知类型'), color: 'grey' };
let icon = getChannelIcon(type);
if (channelInfo?.is_multi_key) {
icon =
channelInfo?.multi_key_mode === 'random' ? (
<div className='flex items-center gap-1'>
<ShuffleBrandIcon size={14} color='rgb(59 130 246)' />
{icon}
</div>
) : (
<div className='flex items-center gap-1'>
<IconTreeTriangleDown className='text-blue-500' />
{icon}
</div>
);
}
return (
<Tag color={type2label[type]?.color} shape='circle' prefixIcon={icon}>
{type2label[type]?.label}
</Tag>
);
};
const renderTagType = (t) => {
return (
<Tag color='light-blue' shape='circle' type='light'>
{t('标签聚合')}
</Tag>
);
};
const renderStatus = (status, channelInfo = undefined, t) => {
if (channelInfo) {
if (channelInfo.is_multi_key) {
let keySize = channelInfo.multi_key_size;
let enabledKeySize = keySize;
if (channelInfo.multi_key_status_list) {
enabledKeySize =
keySize - Object.keys(channelInfo.multi_key_status_list).length;
}
return renderMultiKeyStatus(status, keySize, enabledKeySize, t);
}
}
switch (status) {
case 1:
return (
<Tag color='green' shape='circle'>
{t('已启用')}
</Tag>
);
case 2:
return (
<Tag color='red' shape='circle'>
{t('已禁用')}
</Tag>
);
case 3:
return (
<Tag color='yellow' shape='circle'>
{t('自动禁用')}
</Tag>
);
default:
return (
<Tag color='grey' shape='circle'>
{t('未知状态')}
</Tag>
);
}
};
const renderMultiKeyStatus = (status, keySize, enabledKeySize, t) => {
switch (status) {
case 1:
return (
<Tag color='green' shape='circle'>
{t('已启用')} {enabledKeySize}/{keySize}
</Tag>
);
case 2:
return (
<Tag color='red' shape='circle'>
{t('已禁用')} {enabledKeySize}/{keySize}
</Tag>
);
case 3:
return (
<Tag color='yellow' shape='circle'>
{t('自动禁用')} {enabledKeySize}/{keySize}
</Tag>
);
default:
return (
<Tag color='grey' shape='circle'>
{t('未知状态')} {enabledKeySize}/{keySize}
</Tag>
);
}
};
const renderResponseTime = (responseTime, t) => {
let time = responseTime / 1000;
time = time.toFixed(2) + t(' 秒');
if (responseTime === 0) {
return (
<Tag color='grey' shape='circle'>
{t('未测试')}
</Tag>
);
} else if (responseTime <= 1000) {
return (
<Tag color='green' shape='circle'>
{time}
</Tag>
);
} else if (responseTime <= 3000) {
return (
<Tag color='lime' shape='circle'>
{time}
</Tag>
);
} else if (responseTime <= 5000) {
return (
<Tag color='yellow' shape='circle'>
{time}
</Tag>
);
} else {
return (
<Tag color='red' shape='circle'>
{time}
</Tag>
);
}
};
// 格式化额度数量显示
const formatQuotaCount = (count) => {
if (count >= 1000000000) {
return (count / 1000000000).toFixed(1) + 'B';
}
if (count >= 1000000) {
return (count / 1000000).toFixed(1) + 'M';
}
if (count >= 1000) {
return (count / 1000).toFixed(1) + 'K';
}
return count.toString();
};
const renderDailyQuota = (record, dailyQuotaInfo, t) => {
const limit = record.daily_quota_limit || 0;
// 如果没有设置限额,显示"不限"
if (limit === 0) {
return (
<Tag color='grey' shape='circle'>
{t('不限')}
</Tag>
);
}
// 如果有日消耗信息
if (dailyQuotaInfo && dailyQuotaInfo[record.id]) {
const info = dailyQuotaInfo[record.id];
const percent = info.usage_percent || 0;
const isExceeded = info.limit_exceeded;
let strokeColor = 'var(--semi-color-success)';
if (percent >= 100) {
strokeColor = 'var(--semi-color-danger)';
} else if (percent >= 80) {
strokeColor = 'var(--semi-color-warning)';
} else if (percent >= 50) {
strokeColor = 'var(--semi-color-primary)';
}
return (
<Tooltip
content={
<div>
<div>
{t('日限额')}: {formatQuotaCount(limit)}
</div>
<div>
{t('已使用')}: {formatQuotaCount(info.daily_quota)}
</div>
<div>
{t('使用率')}: {percent}%
</div>
{isExceeded && (
<div style={{ color: 'var(--semi-color-danger)' }}>
{t('已达限额,今日不再调度')}
</div>
)}
</div>
}
>
<div style={{ width: 80 }}>
<Progress
percent={percent}
strokeColor={strokeColor}
size='small'
showInfo
format={(percent) => `${percent}%`}
/>
</div>
</Tooltip>
);
}
// 没有消耗数据时显示限额
return (
<Tooltip content={t('日限额') + ': ' + formatQuotaCount(limit)}>
<Tag color='blue' shape='circle'>
{formatQuotaCount(limit)}
</Tag>
</Tooltip>
);
};
export const getChannelsColumns = ({
t,
COLUMN_KEYS,
updateChannelBalance,
manageChannel,
manageTag,
submitTagEdit,
testChannel,
setCurrentTestChannel,
setShowModelTestModal,
setEditingChannel,
setShowEdit,
setShowEditTag,
setEditingTag,
copySelectedChannel,
refresh,
activePage,
channels,
setShowMultiKeyManageModal,
setCurrentMultiKeyChannel,
isChannelExcluded,
dailyQuotaInfo,
}) => {
return [
{
key: COLUMN_KEYS.ID,
title: t('ID'),
dataIndex: 'id',
},
{
key: COLUMN_KEYS.NAME,
title: t('名称'),
dataIndex: 'name',
render: (text, record, index) => {
if (record.remark && record.remark.trim() !== '') {
return (
<Tooltip
content={
<div className='flex flex-col gap-2 max-w-xs'>
<div className='text-sm'>{record.remark}</div>
<Button
size='small'
type='primary'
theme='outline'
onClick={(e) => {
e.stopPropagation();
navigator.clipboard
.writeText(record.remark)
.then(() => {
showSuccess(t('复制成功'));
})
.catch(() => {
showError(t('复制失败'));
});
}}
>
{t('复制')}
</Button>
</div>
}
trigger={hoverOrClickTrigger()}
position='topLeft'
>
<span>{text}</span>
</Tooltip>
);
}
return text;
},
},
{
key: COLUMN_KEYS.GROUP,
title: t('分组'),
dataIndex: 'group',
render: (text, record, index) => (
<div>
<Space spacing={2}>
{text
?.split(',')
.sort((a, b) => {
if (a === 'default') return -1;
if (b === 'default') return 1;
return a.localeCompare(b);
})
.map((item, index) => renderGroup(item))}
</Space>
</div>
),
},
{
key: COLUMN_KEYS.TYPE,
title: t('类型'),
dataIndex: 'type',
render: (text, record, index) => {
if (record.children === undefined) {
if (record.channel_info) {
if (record.channel_info.is_multi_key) {
return <>{renderType(text, record.channel_info, t)}</>;
}
}
return <>{renderType(text, undefined, t)}</>;
} else {
return <>{renderTagType(t)}</>;
}
},
},
{
key: COLUMN_KEYS.STATUS,
title: t('状态'),
dataIndex: 'status',
render: (text, record, index) => {
if (text === 3) {
if (record.other_info === '') {
record.other_info = '{}';
}
let otherInfo = JSON.parse(record.other_info);
let reason = otherInfo['status_reason'];
let time = otherInfo['status_time'];
return (
<div>
<Tooltip
content={
t('原因:') + reason + t(',时间:') + timestamp2string(time)
}
>
{renderStatus(text, record.channel_info, t)}
</Tooltip>
</div>
);
} else {
return renderStatus(text, record.channel_info, t);
}
},
},
{
key: COLUMN_KEYS.AUTOBAN_EXCLUSION,
title: t('自动封禁'),
dataIndex: 'autoban_exclusion',
render: (text, record, index) => {
if (record.children !== undefined) {
// 标签模式下不显示
return null;
}
const excluded = isChannelExcluded
? isChannelExcluded(record.id)
: false;
return (
<Tag color={excluded ? 'orange' : 'green'} shape='circle'>
{excluded ? t('已排除') : t('参与')}
</Tag>
);
},
},
{
key: COLUMN_KEYS.RESPONSE_TIME,
title: t('响应时间'),
dataIndex: 'response_time',
render: (text, record, index) => <div>{renderResponseTime(text, t)}</div>,
},
{
key: COLUMN_KEYS.BALANCE,
title: t('已用/剩余'),
dataIndex: 'expired_time',
render: (text, record, index) => {
if (record.children === undefined) {
return (
<div>
<Space spacing={1}>
<Tooltip content={t('已用额度')}>
<Tag color='white' type='ghost' shape='circle'>
{renderQuota(record.used_quota)}
</Tag>
</Tooltip>
<Tooltip
content={
isRoot()
? t('剩余额度$') + record.balance + t(',点击更新')
: t('剩余额度$') + record.balance
}
>
<Tag
color='white'
type='ghost'
shape='circle'
onClick={
isRoot() ? () => updateChannelBalance(record) : undefined
}
>
{renderQuotaWithAmount(record.balance)}
</Tag>
</Tooltip>
</Space>
</div>
);
} else {
return (
<Tooltip content={t('已用额度')}>
<Tag color='white' type='ghost' shape='circle'>
{renderQuota(record.used_quota)}
</Tag>
</Tooltip>
);
}
},
},
{
key: COLUMN_KEYS.PRIORITY,
title: t('优先级'),
dataIndex: 'priority',
render: (text, record, index) => {
if (record.children === undefined) {
return (
<div>
{isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='priority'
onBlur={(e) => {
manageChannel(
record.id,
'priority',
record,
e.target.value,
);
}}
keepFocus={true}
innerButtons
defaultValue={record.priority}
min={-999}
size='small'
/>
) : (
<span>{record.priority}</span>
)}
</div>
);
} else {
return isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='priority'
keepFocus={true}
onBlur={(e) => {
Modal.warning({
title: t('修改子渠道优先级'),
content:
t('确定要修改所有子渠道优先级为 ') +
e.target.value +
t(' 吗?'),
onOk: () => {
if (e.target.value === '') {
return;
}
submitTagEdit('priority', {
tag: record.key,
priority: e.target.value,
});
},
});
}}
innerButtons
defaultValue={record.priority}
min={-999}
size='small'
/>
) : (
<span>{record.priority}</span>
);
}
},
},
{
key: COLUMN_KEYS.WEIGHT,
title: t('权重'),
dataIndex: 'weight',
render: (text, record, index) => {
if (record.children === undefined) {
return (
<div>
{isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='weight'
onBlur={(e) => {
manageChannel(record.id, 'weight', record, e.target.value);
}}
keepFocus={true}
innerButtons
defaultValue={record.weight}
min={0}
size='small'
/>
) : (
<span>{record.weight}</span>
)}
</div>
);
} else {
return isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='weight'
keepFocus={true}
onBlur={(e) => {
Modal.warning({
title: t('修改子渠道权重'),
content:
t('确定要修改所有子渠道权重为 ') +
e.target.value +
t(' 吗?'),
onOk: () => {
if (e.target.value === '') {
return;
}
submitTagEdit('weight', {
tag: record.key,
weight: e.target.value,
});
},
});
}}
innerButtons
defaultValue={record.weight}
min={-999}
size='small'
/>
) : (
<span>{record.weight}</span>
);
}
},
},
{
key: COLUMN_KEYS.DAILY_QUOTA,
title: t('日限额'),
dataIndex: 'daily_quota_limit',
render: (text, record, index) => {
if (record.children !== undefined) {
// 标签聚合模式不显示
return null;
}
return renderDailyQuota(record, dailyQuotaInfo, t);
},
},
{
key: COLUMN_KEYS.OPERATE,
title: '',
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) => {
if (record.children === undefined) {
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: async () => {
const content = await buildDeleteConfirmContent(record.id, t);
Modal.confirm({
title: t('确定是否要删除此渠道?'),
content,
onOk: () => {
(async () => {
await manageChannel(record.id, 'delete', record);
await refresh();
setTimeout(() => {
if (channels.length === 0 && activePage > 1) {
refresh(activePage - 1);
}
}, 100);
})();
},
});
},
},
{
node: 'item',
name: t('复制'),
type: 'tertiary',
onClick: () => {
Modal.confirm({
title: t('确定是否要复制此渠道?'),
content: t('复制渠道的所有信息'),
onOk: () => copySelectedChannel(record),
});
},
},
];
return (
<Space wrap>
{isRoot() && (
<SplitButtonGroup
className='overflow-hidden'
aria-label={t('测试单个渠道操作项目组')}
>
<Button
size='small'
type='tertiary'
onClick={() => testChannel(record, '')}
>
{t('测试')}
</Button>
<Button
size='small'
type='tertiary'
icon={<IconTreeTriangleDown />}
onClick={() => {
setCurrentTestChannel(record);
setShowModelTestModal(true);
}}
/>
</SplitButtonGroup>
)}
{isRoot() && (
<>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={() =>
manageChannel(record.id, 'disable', record)
}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={() => manageChannel(record.id, 'enable', record)}
>
{t('启用')}
</Button>
)}
{record.channel_info?.is_multi_key ? (
<SplitButtonGroup aria-label={t('多密钥渠道操作项目组')}>
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={[
{
node: 'item',
name: t('多密钥管理'),
onClick: () => {
setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true);
},
},
]}
>
<Button
type='tertiary'
size='small'
icon={<IconTreeTriangleDown />}
/>
</Dropdown>
</SplitButtonGroup>
) : (
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
)}
<Dropdown
trigger='click'
position='bottomRight'
menu={moreMenuItems}
>
<Button icon={<IconMore />} type='tertiary' size='small' />
</Dropdown>
</>
)}
</Space>
);
} else {
// 标签操作按钮
return (
<Space wrap>
{isRoot() && (
<>
<Button
type='tertiary'
size='small'
onClick={() => manageTag(record.key, 'enable')}
>
{t('启用全部')}
</Button>
<Button
type='tertiary'
size='small'
onClick={() => manageTag(record.key, 'disable')}
>
{t('禁用全部')}
</Button>
<Button
type='tertiary'
size='small'
onClick={() => {
setShowEditTag(true);
setEditingTag(record.key);
}}
>
{t('编辑')}
</Button>
</>
)}
</Space>
);
}
},
},
];
};
@@ -0,0 +1,188 @@
/*
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 { IconSearch } from '@douyinfe/semi-icons';
import { isRoot } from '../../../helpers';
const ChannelsFilters = ({
setEditingChannel,
setShowEdit,
refresh,
setShowColumnSelector,
formInitValues,
setFormApi,
searchChannels,
enableTagMode,
formApi,
groupOptions,
loading,
searching,
autoBanExclusionFilter,
setAutoBanExclusionFilter,
t,
}) => {
return (
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<div className='flex gap-2 w-full md:w-auto order-2 md:order-1'>
{isRoot() && (
<Button
size='small'
theme='light'
type='primary'
className='w-full md:w-auto'
onClick={() => {
setEditingChannel({
id: undefined,
});
setShowEdit(true);
}}
>
{t('添加渠道')}
</Button>
)}
<Button
size='small'
type='tertiary'
className='w-full md:w-auto'
onClick={refresh}
>
{t('刷新')}
</Button>
<Button
size='small'
type='tertiary'
onClick={() => setShowColumnSelector(true)}
className='w-full md:w-auto'
>
{t('列设置')}
</Button>
</div>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto order-1 md:order-2'>
<Form
initValues={formInitValues}
getFormApi={(api) => setFormApi(api)}
onSubmit={() => searchChannels(enableTagMode)}
allowEmpty={true}
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className='flex flex-col md:flex-row items-center gap-2 w-full'
>
<div className='relative w-full md:w-64'>
<Form.Input
size='small'
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('渠道ID,名称,密钥,API地址')}
showClear
pure
/>
</div>
<div className='w-full md:w-48'>
<Form.Input
size='small'
field='searchModel'
prefix={<IconSearch />}
placeholder={t('模型关键字')}
showClear
pure
/>
</div>
<div className='w-full md:w-32'>
<Form.Select
size='small'
field='searchGroup'
placeholder={t('选择分组')}
optionList={[
{ label: t('选择分组'), value: null },
...groupOptions,
]}
className='w-full'
showClear
pure
onChange={() => {
// 延迟执行搜索,让表单值先更新
setTimeout(() => {
searchChannels(enableTagMode);
}, 0);
}}
/>
</div>
<div className='w-full md:w-32'>
<Form.Select
size='small'
field='autoBanExclusionFilter'
placeholder={t('自动封禁')}
value={autoBanExclusionFilter}
optionList={[
{ label: t('全部'), value: 'all' },
{ label: t('参与'), value: 'included' },
{ label: t('已排除'), value: 'excluded' },
]}
className='w-full'
showClear
pure
onChange={(value) => {
const newValue = value || 'all';
localStorage.setItem(
'channel-autoban-exclusion-filter',
newValue,
);
setAutoBanExclusionFilter(newValue);
}}
/>
</div>
<Button
size='small'
type='tertiary'
htmlType='submit'
loading={loading || searching}
className='w-full md:w-auto'
>
{t('查询')}
</Button>
<Button
size='small'
type='tertiary'
onClick={() => {
if (formApi) {
formApi.reset();
// 重置后立即查询,使用setTimeout确保表单重置完成
setTimeout(() => {
refresh();
}, 100);
}
}}
className='w-full md:w-auto'
>
{t('重置')}
</Button>
</Form>
</div>
</div>
);
};
export default ChannelsFilters;
@@ -0,0 +1,225 @@
/*
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 } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getChannelsColumns } from './ChannelsColumnDefs';
const ChannelsTable = (channelsData) => {
const {
channels,
loading,
searching,
activePage,
pageSize,
channelCount,
enableBatchDelete,
compactMode,
visibleColumns,
setSelectedChannels,
handlePageChange,
handlePageSizeChange,
handleRow,
t,
COLUMN_KEYS,
// Column functions and data
updateChannelBalance,
manageChannel,
manageTag,
submitTagEdit,
testChannel,
setCurrentTestChannel,
setShowModelTestModal,
setEditingChannel,
setShowEdit,
setShowEditTag,
setEditingTag,
copySelectedChannel,
refresh,
// Multi-key management
setShowMultiKeyManageModal,
setCurrentMultiKeyChannel,
// Auto-ban exclusion
isChannelExcluded,
excludedChannels,
autoBanExclusionFilter,
// Daily quota info
dailyQuotaInfo,
} = channelsData;
// Filter channels based on auto-ban exclusion filter
const filteredChannels = useMemo(() => {
if (!autoBanExclusionFilter || autoBanExclusionFilter === 'all') {
return channels;
}
return channels
.map((channel) => {
// 处理标签聚合模式
if (channel.children !== undefined) {
const filteredChildren = channel.children.filter((child) => {
const excluded = isChannelExcluded
? isChannelExcluded(child.id)
: false;
if (autoBanExclusionFilter === 'excluded') {
return excluded;
} else if (autoBanExclusionFilter === 'included') {
return !excluded;
}
return true;
});
if (filteredChildren.length === 0) {
return null;
}
return {
...channel,
children: filteredChildren,
};
}
// 非标签模式
const excluded = isChannelExcluded
? isChannelExcluded(channel.id)
: false;
if (autoBanExclusionFilter === 'excluded') {
return excluded ? channel : null;
} else if (autoBanExclusionFilter === 'included') {
return !excluded ? channel : null;
}
return channel;
})
.filter(Boolean);
}, [channels, autoBanExclusionFilter, isChannelExcluded, excludedChannels]);
// Get all columns
const allColumns = useMemo(() => {
return getChannelsColumns({
t,
COLUMN_KEYS,
updateChannelBalance,
manageChannel,
manageTag,
submitTagEdit,
testChannel,
setCurrentTestChannel,
setShowModelTestModal,
setEditingChannel,
setShowEdit,
setShowEditTag,
setEditingTag,
copySelectedChannel,
refresh,
activePage,
channels,
setShowMultiKeyManageModal,
setCurrentMultiKeyChannel,
isChannelExcluded,
dailyQuotaInfo,
});
}, [
t,
COLUMN_KEYS,
updateChannelBalance,
manageChannel,
manageTag,
submitTagEdit,
testChannel,
setCurrentTestChannel,
setShowModelTestModal,
setEditingChannel,
setShowEdit,
setShowEditTag,
setEditingTag,
copySelectedChannel,
refresh,
activePage,
channels,
setShowMultiKeyManageModal,
setCurrentMultiKeyChannel,
isChannelExcluded,
excludedChannels,
dailyQuotaInfo,
]);
// 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(() => {
return compactMode
? visibleColumnsList.map(({ fixed, ...rest }) => rest)
: visibleColumnsList;
}, [compactMode, visibleColumnsList]);
return (
<CardTable
columns={tableColumns}
dataSource={filteredChannels}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: channelCount,
pageSizeOpts: [10, 20, 50, 100],
showSizeChanger: true,
onPageSizeChange: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
expandAllRows={false}
onRow={handleRow}
rowSelection={
enableBatchDelete
? {
onChange: (selectedRowKeys, selectedRows) => {
setSelectedChannels(selectedRows);
},
}
: null
}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
size='middle'
loading={loading || searching}
/>
);
};
export default ChannelsTable;
@@ -0,0 +1,97 @@
/*
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 { Tabs, TabPane, Tag } from '@douyinfe/semi-ui';
import { CHANNEL_OPTIONS } from '../../../constants';
import { getChannelIcon } from '../../../helpers';
const ChannelsTabs = ({
enableTagMode,
activeTypeKey,
setActiveTypeKey,
channelTypeCounts,
availableTypeKeys,
loadChannels,
activePage,
pageSize,
idSort,
setActivePage,
t,
}) => {
if (enableTagMode) return null;
const handleTabChange = (key) => {
setActiveTypeKey(key);
setActivePage(1);
loadChannels(1, pageSize, idSort, enableTagMode, key);
};
return (
<Tabs
activeKey={activeTypeKey}
type='card'
collapsible
onChange={handleTabChange}
className='mb-2'
>
<TabPane
itemKey='all'
tab={
<span className='flex items-center gap-2'>
{t('全部')}
<Tag
color={activeTypeKey === 'all' ? 'red' : 'grey'}
shape='circle'
>
{channelTypeCounts['all'] || 0}
</Tag>
</span>
}
/>
{CHANNEL_OPTIONS.filter((opt) =>
availableTypeKeys.includes(String(opt.value)),
).map((option) => {
const key = String(option.value);
const count = channelTypeCounts[option.value] || 0;
return (
<TabPane
key={key}
itemKey={key}
tab={
<span className='flex items-center gap-2'>
{getChannelIcon(option.value)}
{option.label}
<Tag
color={activeTypeKey === key ? 'red' : 'grey'}
shape='circle'
>
{count}
</Tag>
</span>
}
/>
);
})}
</Tabs>
);
};
export default ChannelsTabs;
+88
View File
@@ -0,0 +1,88 @@
/*
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 ChannelsTable from './ChannelsTable';
import ChannelsActions from './ChannelsActions';
import ChannelsFilters from './ChannelsFilters';
import ChannelsTabs from './ChannelsTabs';
import { useChannelsData } from '../../../hooks/channels/useChannelsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import BatchTagModal from './modals/BatchTagModal';
import ModelTestModal from './modals/ModelTestModal';
import ColumnSelectorModal from './modals/ColumnSelectorModal';
import EditChannelModal from './modals/EditChannelModal';
import EditTagModal from './modals/EditTagModal';
import MultiKeyManageModal from './modals/MultiKeyManageModal';
import { createCardProPagination } from '../../../helpers/utils';
const ChannelsPage = () => {
const channelsData = useChannelsData();
const isMobile = useIsMobile();
return (
<>
{/* Modals */}
<ColumnSelectorModal {...channelsData} />
<EditTagModal
visible={channelsData.showEditTag}
tag={channelsData.editingTag}
handleClose={() => channelsData.setShowEditTag(false)}
refresh={channelsData.refresh}
/>
<EditChannelModal
refresh={channelsData.refresh}
visible={channelsData.showEdit}
handleClose={channelsData.closeEdit}
editingChannel={channelsData.editingChannel}
/>
<BatchTagModal {...channelsData} />
<ModelTestModal {...channelsData} />
<MultiKeyManageModal
visible={channelsData.showMultiKeyManageModal}
onCancel={() => channelsData.setShowMultiKeyManageModal(false)}
channel={channelsData.currentMultiKeyChannel}
onRefresh={channelsData.refresh}
/>
{/* Main Content */}
<CardPro
type='type3'
tabsArea={<ChannelsTabs {...channelsData} />}
actionsArea={<ChannelsActions {...channelsData} />}
searchArea={<ChannelsFilters {...channelsData} />}
paginationArea={createCardProPagination({
currentPage: channelsData.activePage,
pageSize: channelsData.pageSize,
total: channelsData.channelCount,
onPageChange: channelsData.handlePageChange,
onPageSizeChange: channelsData.handlePageSizeChange,
isMobile: isMobile,
t: channelsData.t,
})}
t={channelsData.t}
>
<ChannelsTable {...channelsData} />
</CardPro>
</>
);
};
export default ChannelsPage;
@@ -0,0 +1,63 @@
/*
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, Input, Typography } from '@douyinfe/semi-ui';
const BatchTagModal = ({
showBatchSetTag,
setShowBatchSetTag,
batchSetChannelTag,
batchSetTagValue,
setBatchSetTagValue,
selectedChannels,
t,
}) => {
return (
<Modal
title={t('批量设置标签')}
visible={showBatchSetTag}
onOk={batchSetChannelTag}
onCancel={() => setShowBatchSetTag(false)}
maskClosable={false}
centered={true}
size='small'
className='!rounded-lg'
>
<div className='mb-5'>
<Typography.Text>{t('请输入要设置的标签名称')}</Typography.Text>
</div>
<Input
placeholder={t('请输入标签名称')}
value={batchSetTagValue}
onChange={(v) => setBatchSetTagValue(v)}
/>
<div className='mt-4'>
<Typography.Text type='secondary'>
{t('已选择 ${count} 个渠道').replace(
'${count}',
selectedChannels.length,
)}
</Typography.Text>
</div>
</Modal>
);
};
export default BatchTagModal;
@@ -0,0 +1,128 @@
/*
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 { getChannelsColumns } from '../ChannelsColumnDefs';
const ColumnSelectorModal = ({
showColumnSelector,
setShowColumnSelector,
visibleColumns,
handleColumnVisibilityChange,
handleSelectAll,
initDefaultColumns,
COLUMN_KEYS,
t,
// Props needed for getChannelsColumns
updateChannelBalance,
manageChannel,
manageTag,
submitTagEdit,
testChannel,
setCurrentTestChannel,
setShowModelTestModal,
setEditingChannel,
setShowEdit,
setShowEditTag,
setEditingTag,
copySelectedChannel,
refresh,
activePage,
channels,
}) => {
// Get all columns for display in selector
const allColumns = getChannelsColumns({
t,
COLUMN_KEYS,
updateChannelBalance,
manageChannel,
manageTag,
submitTagEdit,
testChannel,
setCurrentTestChannel,
setShowModelTestModal,
setEditingChannel,
setShowEdit,
setShowEditTag,
setEditingTag,
copySelectedChannel,
refresh,
activePage,
channels,
});
return (
<Modal
title={t('列设置')}
visible={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
footer={
<div className='flex justify-end'>
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('取消')}
</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('确定')}
</Button>
</div>
}
>
<div style={{ marginBottom: 20 }}>
<Checkbox
checked={Object.values(visibleColumns).every((v) => v === true)}
indeterminate={
Object.values(visibleColumns).some((v) => v === true) &&
!Object.values(visibleColumns).every((v) => v === true)
}
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 columns without title
if (!column.title) {
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;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,724 @@
/*
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, { useState, useEffect, useRef } from 'react';
import {
API,
showError,
showInfo,
showSuccess,
showWarning,
verifyJSON,
selectFilter,
} from '../../../../helpers';
import {
SideSheet,
Space,
Button,
Typography,
Spin,
Banner,
Card,
Tag,
Avatar,
Form,
} from '@douyinfe/semi-ui';
import {
IconSave,
IconClose,
IconBookmark,
IconUser,
IconCode,
IconSetting,
} from '@douyinfe/semi-icons';
import { getChannelModels } from '../../../../helpers';
import { useTranslation } from 'react-i18next';
const { Text, Title } = Typography;
const MODEL_MAPPING_EXAMPLE = {
'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
};
const EditTagModal = (props) => {
const { t } = useTranslation();
const { visible, tag, handleClose, refresh } = props;
const [loading, setLoading] = useState(false);
const [originModelOptions, setOriginModelOptions] = useState([]);
const [modelOptions, setModelOptions] = useState([]);
const [groupOptions, setGroupOptions] = useState([]);
const [customModel, setCustomModel] = useState('');
const originInputs = {
tag: '',
new_tag: null,
model_mapping: null,
groups: [],
models: [],
param_override: null,
header_override: null,
};
const [inputs, setInputs] = useState(originInputs);
const formApiRef = useRef(null);
const getInitValues = () => ({ ...originInputs });
const handleInputChange = (name, value) => {
setInputs((inputs) => ({ ...inputs, [name]: value }));
if (formApiRef.current) {
formApiRef.current.setValue(name, value);
}
if (name === 'type') {
let localModels = [];
switch (value) {
case 2:
localModels = [
'mj_imagine',
'mj_variation',
'mj_reroll',
'mj_blend',
'mj_upscale',
'mj_describe',
'mj_uploads',
];
break;
case 5:
localModels = [
'swap_face',
'mj_imagine',
'mj_video',
'mj_edits',
'mj_variation',
'mj_reroll',
'mj_blend',
'mj_upscale',
'mj_describe',
'mj_zoom',
'mj_shorten',
'mj_modal',
'mj_inpaint',
'mj_custom_zoom',
'mj_high_variation',
'mj_low_variation',
'mj_pan',
'mj_uploads',
];
break;
case 36:
localModels = ['suno_music', 'suno_lyrics'];
break;
case 53:
localModels = [
'NousResearch/Hermes-4-405B-FP8',
'Qwen/Qwen3-235B-A22B-Thinking-2507',
'Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8',
'Qwen/Qwen3-235B-A22B-Instruct-2507',
'zai-org/GLM-4.5-FP8',
'openai/gpt-oss-120b',
'deepseek-ai/DeepSeek-R1-0528',
'deepseek-ai/DeepSeek-R1',
'deepseek-ai/DeepSeek-V3-0324',
'deepseek-ai/DeepSeek-V3.1',
];
break;
default:
localModels = getChannelModels(value);
break;
}
if (inputs.models.length === 0) {
setInputs((inputs) => ({ ...inputs, models: localModels }));
}
}
};
const fetchModels = async () => {
try {
let res = await API.get(`/api/channel/models`);
let localModelOptions = res.data.data.map((model) => ({
label: model.id,
value: model.id,
}));
setOriginModelOptions(localModelOptions);
} catch (error) {
showError(error.message);
}
};
const fetchGroups = async () => {
try {
let res = await API.get(`/api/group/`);
if (res === undefined) {
return;
}
setGroupOptions(
res.data.data.map((group) => ({
label: group,
value: group,
})),
);
} catch (error) {
showError(error.message);
}
};
const handleSave = async (values) => {
setLoading(true);
const formVals = values || formApiRef.current?.getValues() || {};
let data = { tag };
if (formVals.model_mapping) {
if (!verifyJSON(formVals.model_mapping)) {
showInfo(t('模型映射必须是合法的 JSON 格式!'));
setLoading(false);
return;
}
data.model_mapping = formVals.model_mapping;
}
if (formVals.groups && formVals.groups.length > 0) {
data.groups = formVals.groups.join(',');
}
if (formVals.models && formVals.models.length > 0) {
data.models = formVals.models.join(',');
}
if (
formVals.param_override !== undefined &&
formVals.param_override !== null
) {
if (typeof formVals.param_override !== 'string') {
showInfo('参数覆盖必须是合法的 JSON 格式!');
setLoading(false);
return;
}
const trimmedParamOverride = formVals.param_override.trim();
if (trimmedParamOverride !== '' && !verifyJSON(trimmedParamOverride)) {
showInfo('参数覆盖必须是合法的 JSON 格式!');
setLoading(false);
return;
}
data.param_override = trimmedParamOverride;
}
if (
formVals.header_override !== undefined &&
formVals.header_override !== null
) {
if (typeof formVals.header_override !== 'string') {
showInfo('请求头覆盖必须是合法的 JSON 格式!');
setLoading(false);
return;
}
const trimmedHeaderOverride = formVals.header_override.trim();
if (trimmedHeaderOverride !== '' && !verifyJSON(trimmedHeaderOverride)) {
showInfo('请求头覆盖必须是合法的 JSON 格式!');
setLoading(false);
return;
}
data.header_override = trimmedHeaderOverride;
}
data.new_tag = formVals.new_tag;
if (
data.model_mapping === undefined &&
data.groups === undefined &&
data.models === undefined &&
data.new_tag === undefined &&
data.param_override === undefined &&
data.header_override === undefined
) {
showWarning(t('没有任何修改!'));
setLoading(false);
return;
}
await submit(data);
setLoading(false);
};
const submit = async (data) => {
try {
const res = await API.put('/api/channel/tag', data);
if (res?.data?.success) {
showSuccess(t('标签更新成功!'));
refresh();
handleClose();
}
} catch (error) {
showError(error);
}
};
useEffect(() => {
let localModelOptions = [...originModelOptions];
inputs.models.forEach((model) => {
if (!localModelOptions.find((option) => option.label === model)) {
localModelOptions.push({
label: model,
value: model,
});
}
});
setModelOptions(localModelOptions);
}, [originModelOptions, inputs.models]);
useEffect(() => {
const fetchTagModels = async () => {
if (!tag) return;
setLoading(true);
try {
const res = await API.get(`/api/channel/tag/models?tag=${tag}`);
if (res?.data?.success) {
const models = res.data.data ? res.data.data.split(',') : [];
handleInputChange('models', models);
} else {
showError(res.data.message);
}
} catch (error) {
showError(error.message);
} finally {
setLoading(false);
}
};
fetchModels().then();
fetchGroups().then();
fetchTagModels().then();
if (formApiRef.current) {
formApiRef.current.setValues({
...getInitValues(),
tag: tag,
new_tag: tag,
});
}
setInputs({
...originInputs,
tag: tag,
new_tag: tag,
});
}, [visible, tag]);
useEffect(() => {
if (formApiRef.current) {
formApiRef.current.setValues(inputs);
}
}, [inputs]);
const addCustomModels = () => {
if (customModel.trim() === '') return;
const modelArray = customModel.split(',').map((model) => model.trim());
let localModels = [...inputs.models];
let localModelOptions = [...modelOptions];
const addedModels = [];
modelArray.forEach((model) => {
if (model && !localModels.includes(model)) {
localModels.push(model);
localModelOptions.push({
key: model,
text: model,
value: model,
});
addedModels.push(model);
}
});
setModelOptions(localModelOptions);
setCustomModel('');
handleInputChange('models', localModels);
if (addedModels.length > 0) {
showSuccess(
t('已新增 {{count}} 个模型:{{list}}', {
count: addedModels.length,
list: addedModels.join(', '),
}),
);
} else {
showInfo(t('未发现新增模型'));
}
};
return (
<SideSheet
placement='right'
title={
<Space>
<Tag color='blue' shape='circle'>
{t('编辑')}
</Tag>
<Title heading={4} className='m-0'>
{t('编辑标签')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={visible}
width={600}
onCancel={handleClose}
footer={
<div className='flex justify-end'>
<Space>
<Button
theme='solid'
onClick={() => formApiRef.current?.submitForm()}
loading={loading}
icon={<IconSave />}
>
{t('保存')}
</Button>
<Button
theme='light'
type='primary'
onClick={handleClose}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
>
<Form
key={tag || 'edit'}
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={handleSave}
>
{() => (
<Spin spinning={loading}>
<div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Tag Info */}
<div className='flex items-center mb-2'>
<Avatar size='small' color='blue' className='mr-2 shadow-md'>
<IconBookmark size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('标签信息')}</Text>
<div className='text-xs text-gray-600'>
{t('标签的基本配置')}
</div>
</div>
</div>
<Banner
type='warning'
description={t('所有编辑均为覆盖操作,留空则不更改')}
className='!rounded-lg mb-4'
/>
<div className='space-y-4'>
<Form.Input
field='new_tag'
label={t('标签名称')}
placeholder={t('请输入新标签,留空则解散标签')}
onChange={(value) => handleInputChange('new_tag', value)}
/>
</div>
</Card>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Model Config */}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='purple'
className='mr-2 shadow-md'
>
<IconCode size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('模型配置')}</Text>
<div className='text-xs text-gray-600'>
{t('模型选择和映射设置')}
</div>
</div>
</div>
<div className='space-y-4'>
<Banner
type='info'
description={t(
'当前模型列表为该标签下所有渠道模型列表最长的一个,并非所有渠道的并集,请注意可能导致某些渠道模型丢失。',
)}
className='!rounded-lg mb-4'
/>
<Form.Select
field='models'
label={t('模型')}
placeholder={t('请选择该渠道所支持的模型,留空则不更改')}
multiple
filter={selectFilter}
autoClearSearchValue={false}
searchPosition='dropdown'
optionList={modelOptions}
style={{ width: '100%' }}
onChange={(value) => handleInputChange('models', value)}
/>
<Form.Input
field='custom_model'
label={t('自定义模型名称')}
placeholder={t('输入自定义模型名称')}
onChange={(value) => setCustomModel(value.trim())}
suffix={
<Button
size='small'
type='primary'
onClick={addCustomModels}
>
{t('填入')}
</Button>
}
/>
<Form.TextArea
field='model_mapping'
label={t('模型重定向')}
placeholder={t(
'此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,留空则不更改',
)}
autosize
onChange={(value) =>
handleInputChange('model_mapping', value)
}
extraText={
<Space>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() =>
handleInputChange(
'model_mapping',
JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2),
)
}
>
{t('填入模板')}
</Text>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() =>
handleInputChange(
'model_mapping',
JSON.stringify({}, null, 2),
)
}
>
{t('清空重定向')}
</Text>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() => handleInputChange('model_mapping', '')}
>
{t('不更改')}
</Text>
</Space>
}
/>
</div>
</Card>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Advanced Settings */}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='orange'
className='mr-2 shadow-md'
>
<IconSetting size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('高级设置')}</Text>
<div className='text-xs text-gray-600'>
{t('渠道的高级配置选项')}
</div>
</div>
</div>
<div className='space-y-4'>
<Form.TextArea
field='param_override'
label={t('参数覆盖')}
placeholder={
t('此项可选,用于覆盖请求参数。不支持覆盖 stream 参数') +
'\n' +
t('旧格式(直接覆盖):') +
'\n{\n "temperature": 0,\n "max_tokens": 1000\n}' +
'\n\n' +
t('新格式(支持条件判断与json自定义):') +
'\n{\n "operations": [\n {\n "path": "temperature",\n "mode": "set",\n "value": 0.7,\n "conditions": [\n {\n "path": "model",\n "mode": "prefix",\n "value": "gpt"\n }\n ]\n }\n ]\n}'
}
autosize
showClear
onChange={(value) =>
handleInputChange('param_override', value)
}
extraText={
<div className='flex gap-2 flex-wrap'>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() =>
handleInputChange(
'param_override',
JSON.stringify({ temperature: 0 }, null, 2),
)
}
>
{t('旧格式模板')}
</Text>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() =>
handleInputChange(
'param_override',
JSON.stringify(
{
operations: [
{
path: 'temperature',
mode: 'set',
value: 0.7,
conditions: [
{
path: 'model',
mode: 'prefix',
value: 'gpt',
},
],
logic: 'AND',
},
],
},
null,
2,
),
)
}
>
{t('新格式模板')}
</Text>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() =>
handleInputChange('param_override', null)
}
>
{t('不更改')}
</Text>
</div>
}
/>
<Form.TextArea
field='header_override'
label={t('请求头覆盖')}
placeholder={
t('此项可选,用于覆盖请求头参数') +
'\n' +
t('格式示例:') +
'\n{\n "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0",\n "Authorization": "Bearer {api_key}"\n}'
}
autosize
showClear
onChange={(value) =>
handleInputChange('header_override', value)
}
extraText={
<div className='flex flex-col gap-1'>
<div className='flex gap-2 flex-wrap items-center'>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() =>
handleInputChange(
'header_override',
JSON.stringify(
{
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
Authorization: 'Bearer {api_key}',
},
null,
2,
),
)
}
>
{t('填入模板')}
</Text>
<Text
className='!text-semi-color-primary cursor-pointer'
onClick={() =>
handleInputChange('header_override', null)
}
>
{t('不更改')}
</Text>
</div>
<div>
<Text type='tertiary' size='small'>
{t('支持变量:')}
</Text>
<div className='text-xs text-tertiary ml-2'>
<div>
{t('渠道密钥')}: {'{api_key}'}
</div>
</div>
</div>
</div>
}
/>
</div>
</Card>
<Card className='!rounded-2xl shadow-sm border-0'>
{/* Header: Group Settings */}
<div className='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<IconUser size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('分组设置')}</Text>
<div className='text-xs text-gray-600'>
{t('用户分组配置')}
</div>
</div>
</div>
<div className='space-y-4'>
<Form.Select
field='groups'
label={t('分组')}
placeholder={t('请选择可以使用该渠道的分组,留空则不更改')}
multiple
allowAdditions
additionLabel={t(
'请在系统设置页面编辑分组倍率以添加新的分组:',
)}
optionList={groupOptions}
style={{ width: '100%' }}
onChange={(value) => handleInputChange('groups', value)}
/>
</div>
</Card>
</div>
</Spin>
)}
</Form>
</SideSheet>
);
};
export default EditTagModal;
@@ -0,0 +1,401 @@
/*
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, { useState, useEffect, useMemo } from 'react';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Modal,
Checkbox,
Spin,
Input,
Typography,
Empty,
Tabs,
Collapse,
Tooltip,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../common/illustrations';
import { IconSearch, IconInfoCircle } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
import { getModelCategories } from '../../../../helpers/render';
const ModelSelectModal = ({
visible,
models = [],
selected = [],
redirectModels = [],
onConfirm,
onCancel,
}) => {
const { t } = useTranslation();
const [checkedList, setCheckedList] = useState(selected);
const [keyword, setKeyword] = useState('');
const [activeTab, setActiveTab] = useState('new');
const isMobile = useIsMobile();
const normalizeModelName = (model) =>
typeof model === 'string' ? model.trim() : '';
const normalizedRedirectModels = useMemo(
() =>
Array.from(
new Set(
(redirectModels || [])
.map((model) => normalizeModelName(model))
.filter(Boolean),
),
),
[redirectModels],
);
const normalizedSelectedSet = useMemo(() => {
const set = new Set();
(selected || []).forEach((model) => {
const normalized = normalizeModelName(model);
if (normalized) {
set.add(normalized);
}
});
return set;
}, [selected]);
const classificationSet = useMemo(() => {
const set = new Set(normalizedSelectedSet);
normalizedRedirectModels.forEach((model) => set.add(model));
return set;
}, [normalizedSelectedSet, normalizedRedirectModels]);
const redirectOnlySet = useMemo(() => {
const set = new Set();
normalizedRedirectModels.forEach((model) => {
if (!normalizedSelectedSet.has(model)) {
set.add(model);
}
});
return set;
}, [normalizedRedirectModels, normalizedSelectedSet]);
const filteredModels = models.filter((m) =>
String(m || '')
.toLowerCase()
.includes(keyword.toLowerCase()),
);
// 分类模型:新获取的模型和已有模型
const isExistingModel = (model) =>
classificationSet.has(normalizeModelName(model));
const newModels = filteredModels.filter((model) => !isExistingModel(model));
const existingModels = filteredModels.filter((model) =>
isExistingModel(model),
);
// 同步外部选中值
useEffect(() => {
if (visible) {
setCheckedList(selected);
}
}, [visible, selected]);
// 当模型列表变化时,设置默认tab
useEffect(() => {
if (visible) {
// 默认显示新获取模型tab,如果没有新模型则显示已有模型
const hasNewModels = newModels.length > 0;
setActiveTab(hasNewModels ? 'new' : 'existing');
}
}, [visible, newModels.length, selected]);
const handleOk = () => {
onConfirm && onConfirm(checkedList);
};
// 按厂商分类模型
const categorizeModels = (models) => {
const categories = getModelCategories(t);
const categorizedModels = {};
const uncategorizedModels = [];
models.forEach((model) => {
let foundCategory = false;
for (const [key, category] of Object.entries(categories)) {
if (key !== 'all' && category.filter({ model_name: model })) {
if (!categorizedModels[key]) {
categorizedModels[key] = {
label: category.label,
icon: category.icon,
models: [],
};
}
categorizedModels[key].models.push(model);
foundCategory = true;
break;
}
}
if (!foundCategory) {
uncategorizedModels.push(model);
}
});
// 如果有未分类模型,添加到"其他"分类
if (uncategorizedModels.length > 0) {
categorizedModels['other'] = {
label: t('其他'),
icon: null,
models: uncategorizedModels,
};
}
return categorizedModels;
};
const newModelsByCategory = categorizeModels(newModels);
const existingModelsByCategory = categorizeModels(existingModels);
// Tab列表配置
const tabList = [
...(newModels.length > 0
? [
{
tab: `${t('新获取的模型')} (${newModels.length})`,
itemKey: 'new',
},
]
: []),
...(existingModels.length > 0
? [
{
tab: `${t('已有的模型')} (${existingModels.length})`,
itemKey: 'existing',
},
]
: []),
];
// 处理分类全选/取消全选
const handleCategorySelectAll = (categoryModels, isChecked) => {
let newCheckedList = [...checkedList];
if (isChecked) {
// 全选:添加该分类下所有未选中的模型
categoryModels.forEach((model) => {
if (!newCheckedList.includes(model)) {
newCheckedList.push(model);
}
});
} else {
// 取消全选:移除该分类下所有已选中的模型
newCheckedList = newCheckedList.filter(
(model) => !categoryModels.includes(model),
);
}
setCheckedList(newCheckedList);
};
// 检查分类是否全选
const isCategoryAllSelected = (categoryModels) => {
return (
categoryModels.length > 0 &&
categoryModels.every((model) => checkedList.includes(model))
);
};
// 检查分类是否部分选中
const isCategoryIndeterminate = (categoryModels) => {
const selectedCount = categoryModels.filter((model) =>
checkedList.includes(model),
).length;
return selectedCount > 0 && selectedCount < categoryModels.length;
};
const renderModelsByCategory = (modelsByCategory, categoryKeyPrefix) => {
const categoryEntries = Object.entries(modelsByCategory);
if (categoryEntries.length === 0) return null;
return (
<Collapse
key={`${categoryKeyPrefix}_${categoryEntries.length}`}
defaultActiveKey={[]}
>
{categoryEntries.map(([key, categoryData], index) => (
<Collapse.Panel
key={`${categoryKeyPrefix}_${index}`}
itemKey={`${categoryKeyPrefix}_${index}`}
header={`${categoryData.label} (${categoryData.models.length})`}
extra={
<Checkbox
checked={isCategoryAllSelected(categoryData.models)}
indeterminate={isCategoryIndeterminate(categoryData.models)}
onChange={(e) => {
e.stopPropagation(); // 防止触发面板折叠
handleCategorySelectAll(
categoryData.models,
e.target.checked,
);
}}
onClick={(e) => e.stopPropagation()} // 防止点击checkbox时折叠面板
/>
}
>
<div className='flex items-center gap-2 mb-3'>
{categoryData.icon}
<Typography.Text type='secondary' size='small'>
{t('已选择 {{selected}} / {{total}}', {
selected: categoryData.models.filter((model) =>
checkedList.includes(model),
).length,
total: categoryData.models.length,
})}
</Typography.Text>
</div>
<div className='grid grid-cols-2 gap-x-4'>
{categoryData.models.map((model) => (
<Checkbox key={model} value={model} className='my-1'>
<span className='flex items-center gap-2'>
<span>{model}</span>
{redirectOnlySet.has(normalizeModelName(model)) && (
<Tooltip
position='top'
content={t('来自模型重定向,尚未加入模型列表')}
>
<IconInfoCircle
size='small'
className='text-amber-500 cursor-help'
/>
</Tooltip>
)}
</span>
</Checkbox>
))}
</div>
</Collapse.Panel>
))}
</Collapse>
);
};
return (
<Modal
header={
<div className='flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 py-4'>
<Typography.Title heading={5} className='m-0'>
{t('选择模型')}
</Typography.Title>
<div className='flex-shrink-0'>
<Tabs
type='slash'
size='small'
tabList={tabList}
activeKey={activeTab}
onChange={(key) => setActiveTab(key)}
/>
</div>
</div>
}
visible={visible}
onOk={handleOk}
onCancel={onCancel}
okText={t('确定')}
cancelText={t('取消')}
size={isMobile ? 'full-width' : 'large'}
closeOnEsc
maskClosable
centered
>
<Input
prefix={<IconSearch size={14} />}
placeholder={t('搜索模型')}
value={keyword}
onChange={(v) => setKeyword(v)}
showClear
/>
<Spin spinning={!models || models.length === 0}>
<div style={{ maxHeight: 400, overflowY: 'auto', paddingRight: 8 }}>
{filteredModels.length === 0 ? (
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无匹配模型')}
style={{ padding: 30 }}
/>
) : (
<Checkbox.Group
value={checkedList}
onChange={(vals) => setCheckedList(vals)}
>
{activeTab === 'new' && newModels.length > 0 && (
<div>{renderModelsByCategory(newModelsByCategory, 'new')}</div>
)}
{activeTab === 'existing' && existingModels.length > 0 && (
<div>
{renderModelsByCategory(existingModelsByCategory, 'existing')}
</div>
)}
</Checkbox.Group>
)}
</div>
</Spin>
<Typography.Text
type='secondary'
size='small'
className='block text-right mt-4'
>
<div className='flex items-center justify-end gap-2'>
{(() => {
const currentModels =
activeTab === 'new' ? newModels : existingModels;
const currentSelected = currentModels.filter((model) =>
checkedList.includes(model),
).length;
const isAllSelected =
currentModels.length > 0 &&
currentSelected === currentModels.length;
const isIndeterminate =
currentSelected > 0 && currentSelected < currentModels.length;
return (
<>
<span>
{t('已选择 {{selected}} / {{total}}', {
selected: currentSelected,
total: currentModels.length,
})}
</span>
<Checkbox
checked={isAllSelected}
indeterminate={isIndeterminate}
onChange={(e) => {
handleCategorySelectAll(currentModels, e.target.checked);
}}
/>
</>
);
})()}
</div>
</Typography.Text>
</Modal>
);
};
export default ModelSelectModal;
@@ -0,0 +1,321 @@
/*
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,
Input,
Table,
Tag,
Typography,
Select,
} from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
import { copy, showError, showInfo, showSuccess } from '../../../../helpers';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
const ModelTestModal = ({
showModelTestModal,
currentTestChannel,
handleCloseModal,
isBatchTesting,
batchTestModels,
modelSearchKeyword,
setModelSearchKeyword,
selectedModelKeys,
setSelectedModelKeys,
modelTestResults,
testingModels,
testChannel,
modelTablePage,
setModelTablePage,
selectedEndpointType,
setSelectedEndpointType,
allSelectingRef,
isMobile,
t,
}) => {
const hasChannel = Boolean(currentTestChannel);
const filteredModels = hasChannel
? currentTestChannel.models
.split(',')
.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase()),
)
: [];
const endpointTypeOptions = [
{ value: '', label: t('自动检测') },
{ value: 'openai', label: 'OpenAI (/v1/chat/completions)' },
{ value: 'openai-response', label: 'OpenAI Response (/v1/responses)' },
{ value: 'anthropic', label: 'Anthropic (/v1/messages)' },
{
value: 'gemini',
label: 'Gemini (/v1beta/models/{model}:generateContent)',
},
{ value: 'jina-rerank', label: 'Jina Rerank (/rerank)' },
{
value: 'image-generation',
label: t('图像生成') + ' (/v1/images/generations)',
},
{ value: 'embeddings', label: 'Embeddings (/v1/embeddings)' },
];
const handleCopySelected = () => {
if (selectedModelKeys.length === 0) {
showError(t('请先选择模型!'));
return;
}
copy(selectedModelKeys.join(',')).then((ok) => {
if (ok) {
showSuccess(
t('已复制 ${count} 个模型').replace(
'${count}',
selectedModelKeys.length,
),
);
} else {
showError(t('复制失败,请手动复制'));
}
});
};
const handleSelectSuccess = () => {
if (!currentTestChannel) return;
const successKeys = currentTestChannel.models
.split(',')
.filter((m) => m.toLowerCase().includes(modelSearchKeyword.toLowerCase()))
.filter((m) => {
const result = modelTestResults[`${currentTestChannel.id}-${m}`];
return result && result.success;
});
if (successKeys.length === 0) {
showInfo(t('暂无成功模型'));
}
setSelectedModelKeys(successKeys);
};
const columns = [
{
title: t('模型名称'),
dataIndex: 'model',
render: (text) => (
<div className='flex items-center'>
<Typography.Text strong>{text}</Typography.Text>
</div>
),
},
{
title: t('状态'),
dataIndex: 'status',
render: (text, record) => {
const testResult =
modelTestResults[`${currentTestChannel.id}-${record.model}`];
const isTesting = testingModels.has(record.model);
if (isTesting) {
return (
<Tag color='blue' shape='circle'>
{t('测试中')}
</Tag>
);
}
if (!testResult) {
return (
<Tag color='grey' shape='circle'>
{t('未开始')}
</Tag>
);
}
return (
<div className='flex items-center gap-2'>
<Tag color={testResult.success ? 'green' : 'red'} shape='circle'>
{testResult.success ? t('成功') : t('失败')}
</Tag>
{testResult.success && (
<Typography.Text type='tertiary'>
{t('请求时长: ${time}s').replace(
'${time}',
testResult.time.toFixed(2),
)}
</Typography.Text>
)}
</div>
);
},
},
{
title: '',
dataIndex: 'operate',
render: (text, record) => {
const isTesting = testingModels.has(record.model);
return (
<Button
type='tertiary'
onClick={() =>
testChannel(
currentTestChannel,
record.model,
selectedEndpointType,
)
}
loading={isTesting}
size='small'
>
{t('测试')}
</Button>
);
},
},
];
const dataSource = (() => {
if (!hasChannel) return [];
const start = (modelTablePage - 1) * MODEL_TABLE_PAGE_SIZE;
const end = start + MODEL_TABLE_PAGE_SIZE;
return filteredModels.slice(start, end).map((model) => ({
model,
key: model,
}));
})();
return (
<Modal
title={
hasChannel ? (
<div className='flex flex-col gap-2 w-full'>
<div className='flex items-center gap-2'>
<Typography.Text
strong
className='!text-[var(--semi-color-text-0)] !text-base'
>
{currentTestChannel.name} {t('渠道的模型测试')}
</Typography.Text>
<Typography.Text type='tertiary' size='small'>
{t('共')} {currentTestChannel.models.split(',').length}{' '}
{t('个模型')}
</Typography.Text>
</div>
</div>
) : null
}
visible={showModelTestModal}
onCancel={handleCloseModal}
footer={
hasChannel ? (
<div className='flex justify-end'>
{isBatchTesting ? (
<Button type='danger' onClick={handleCloseModal}>
{t('停止测试')}
</Button>
) : (
<Button type='tertiary' onClick={handleCloseModal}>
{t('取消')}
</Button>
)}
<Button
onClick={batchTestModels}
loading={isBatchTesting}
disabled={isBatchTesting}
>
{isBatchTesting
? t('测试中...')
: t('批量测试${count}个模型').replace(
'${count}',
filteredModels.length,
)}
</Button>
</div>
) : null
}
maskClosable={!isBatchTesting}
className='!rounded-lg'
size={isMobile ? 'full-width' : 'large'}
>
{hasChannel && (
<div className='model-test-scroll'>
{/* 端点类型选择器 */}
<div className='flex items-center gap-2 w-full mb-2'>
<Typography.Text strong>{t('端点类型')}:</Typography.Text>
<Select
value={selectedEndpointType}
onChange={setSelectedEndpointType}
optionList={endpointTypeOptions}
className='!w-full'
placeholder={t('选择端点类型')}
/>
</div>
{/* 搜索与操作按钮 */}
<div className='flex items-center justify-end gap-2 w-full mb-2'>
<Input
placeholder={t('搜索模型...')}
value={modelSearchKeyword}
onChange={(v) => {
setModelSearchKeyword(v);
setModelTablePage(1);
}}
className='!w-full'
prefix={<IconSearch />}
showClear
/>
<Button onClick={handleCopySelected}>{t('复制已选')}</Button>
<Button type='tertiary' onClick={handleSelectSuccess}>
{t('选择成功')}
</Button>
</div>
<Table
columns={columns}
dataSource={dataSource}
rowSelection={{
selectedRowKeys: selectedModelKeys,
onChange: (keys) => {
if (allSelectingRef.current) {
allSelectingRef.current = false;
return;
}
setSelectedModelKeys(keys);
},
onSelectAll: (checked) => {
allSelectingRef.current = true;
setSelectedModelKeys(checked ? filteredModels : []);
},
}}
pagination={{
currentPage: modelTablePage,
pageSize: MODEL_TABLE_PAGE_SIZE,
total: filteredModels.length,
showSizeChanger: false,
onPageChange: (page) => setModelTablePage(page),
}}
/>
</div>
)}
</Modal>
);
};
export default ModelTestModal;
@@ -0,0 +1,739 @@
/*
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, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
Modal,
Button,
Table,
Tag,
Typography,
Space,
Tooltip,
Popconfirm,
Empty,
Spin,
Select,
Row,
Col,
Badge,
Progress,
Card,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../common/illustrations';
import {
API,
showError,
showSuccess,
timestamp2string,
} from '../../../../helpers';
const { Text } = Typography;
const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [keyStatusList, setKeyStatusList] = useState([]);
const [operationLoading, setOperationLoading] = useState({});
// Pagination states
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0);
const [, setTotalPages] = useState(0);
// Statistics states
const [enabledCount, setEnabledCount] = useState(0);
const [manualDisabledCount, setManualDisabledCount] = useState(0);
const [autoDisabledCount, setAutoDisabledCount] = useState(0);
// Filter states
const [statusFilter, setStatusFilter] = useState(null); // null=all, 1=enabled, 2=manual_disabled, 3=auto_disabled
// Load key status data
const loadKeyStatus = async (
page = currentPage,
size = pageSize,
status = statusFilter,
) => {
if (!channel?.id) return;
setLoading(true);
try {
const requestData = {
channel_id: channel.id,
action: 'get_key_status',
page: page,
page_size: size,
};
// Add status filter if specified
if (status !== null) {
requestData.status = status;
}
const res = await API.post('/api/channel/multi_key/manage', requestData);
if (res.data.success) {
const data = res.data.data;
setKeyStatusList(data.keys || []);
setTotal(data.total || 0);
setCurrentPage(data.page || 1);
setPageSize(data.page_size || 10);
setTotalPages(data.total_pages || 0);
// Update statistics (these are always the overall statistics)
setEnabledCount(data.enabled_count || 0);
setManualDisabledCount(data.manual_disabled_count || 0);
setAutoDisabledCount(data.auto_disabled_count || 0);
} else {
showError(res.data.message);
}
} catch (error) {
console.error(error);
showError(t('获取密钥状态失败'));
} finally {
setLoading(false);
}
};
// Disable a specific key
const handleDisableKey = async (keyIndex) => {
const operationId = `disable_${keyIndex}`;
setOperationLoading((prev) => ({ ...prev, [operationId]: true }));
try {
const res = await API.post('/api/channel/multi_key/manage', {
channel_id: channel.id,
action: 'disable_key',
key_index: keyIndex,
});
if (res.data.success) {
showSuccess(t('密钥已禁用'));
await loadKeyStatus(currentPage, pageSize); // Reload current page
onRefresh && onRefresh(); // Refresh parent component
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('禁用密钥失败'));
} finally {
setOperationLoading((prev) => ({ ...prev, [operationId]: false }));
}
};
// Enable a specific key
const handleEnableKey = async (keyIndex) => {
const operationId = `enable_${keyIndex}`;
setOperationLoading((prev) => ({ ...prev, [operationId]: true }));
try {
const res = await API.post('/api/channel/multi_key/manage', {
channel_id: channel.id,
action: 'enable_key',
key_index: keyIndex,
});
if (res.data.success) {
showSuccess(t('密钥已启用'));
await loadKeyStatus(currentPage, pageSize); // Reload current page
onRefresh && onRefresh(); // Refresh parent component
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('启用密钥失败'));
} finally {
setOperationLoading((prev) => ({ ...prev, [operationId]: false }));
}
};
// Enable all disabled keys
const handleEnableAll = async () => {
setOperationLoading((prev) => ({ ...prev, enable_all: true }));
try {
const res = await API.post('/api/channel/multi_key/manage', {
channel_id: channel.id,
action: 'enable_all_keys',
});
if (res.data.success) {
showSuccess(res.data.message || t('已启用所有密钥'));
// Reset to first page after bulk operation
setCurrentPage(1);
await loadKeyStatus(1, pageSize);
onRefresh && onRefresh(); // Refresh parent component
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('启用所有密钥失败'));
} finally {
setOperationLoading((prev) => ({ ...prev, enable_all: false }));
}
};
// Disable all enabled keys
const handleDisableAll = async () => {
setOperationLoading((prev) => ({ ...prev, disable_all: true }));
try {
const res = await API.post('/api/channel/multi_key/manage', {
channel_id: channel.id,
action: 'disable_all_keys',
});
if (res.data.success) {
showSuccess(res.data.message || t('已禁用所有密钥'));
// Reset to first page after bulk operation
setCurrentPage(1);
await loadKeyStatus(1, pageSize);
onRefresh && onRefresh(); // Refresh parent component
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('禁用所有密钥失败'));
} finally {
setOperationLoading((prev) => ({ ...prev, disable_all: false }));
}
};
// Delete all disabled keys
const handleDeleteDisabledKeys = async () => {
setOperationLoading((prev) => ({ ...prev, delete_disabled: true }));
try {
const res = await API.post('/api/channel/multi_key/manage', {
channel_id: channel.id,
action: 'delete_disabled_keys',
});
if (res.data.success) {
showSuccess(res.data.message);
// Reset to first page after deletion as data structure might change
setCurrentPage(1);
await loadKeyStatus(1, pageSize);
onRefresh && onRefresh(); // Refresh parent component
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('删除禁用密钥失败'));
} finally {
setOperationLoading((prev) => ({ ...prev, delete_disabled: false }));
}
};
// Delete a specific key
const handleDeleteKey = async (keyIndex) => {
const operationId = `delete_${keyIndex}`;
setOperationLoading((prev) => ({ ...prev, [operationId]: true }));
try {
const res = await API.post('/api/channel/multi_key/manage', {
channel_id: channel.id,
action: 'delete_key',
key_index: keyIndex,
});
if (res.data.success) {
showSuccess(t('密钥已删除'));
await loadKeyStatus(currentPage, pageSize); // Reload current page
onRefresh && onRefresh(); // Refresh parent component
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('删除密钥失败'));
} finally {
setOperationLoading((prev) => ({ ...prev, [operationId]: false }));
}
};
// Handle page size change
const handlePageSizeChange = (size) => {
setPageSize(size);
setCurrentPage(1); // Reset to first page
loadKeyStatus(1, size);
};
// Handle status filter change
const handleStatusFilterChange = (status) => {
setStatusFilter(status);
setCurrentPage(1); // Reset to first page when filter changes
loadKeyStatus(1, pageSize, status);
};
// Effect to load data when modal opens
useEffect(() => {
if (visible && channel?.id) {
setCurrentPage(1); // Reset to first page when opening
loadKeyStatus(1, pageSize);
}
}, [visible, channel?.id]);
// Reset pagination when modal closes
useEffect(() => {
if (!visible) {
setCurrentPage(1);
setKeyStatusList([]);
setTotal(0);
setTotalPages(0);
setEnabledCount(0);
setManualDisabledCount(0);
setAutoDisabledCount(0);
setStatusFilter(null); // Reset filter
}
}, [visible]);
// Percentages for progress display
const enabledPercent =
total > 0 ? Math.round((enabledCount / total) * 100) : 0;
const manualDisabledPercent =
total > 0 ? Math.round((manualDisabledCount / total) * 100) : 0;
const autoDisabledPercent =
total > 0 ? Math.round((autoDisabledCount / total) * 100) : 0;
// 取消饼图:不再需要图表数据与配置
// Get status tag component
const renderStatusTag = (status) => {
switch (status) {
case 1:
return (
<Tag color='green' shape='circle' size='small'>
{t('已启用')}
</Tag>
);
case 2:
return (
<Tag color='red' shape='circle' size='small'>
{t('已禁用')}
</Tag>
);
case 3:
return (
<Tag color='orange' shape='circle' size='small'>
{t('自动禁用')}
</Tag>
);
default:
return (
<Tag color='grey' shape='circle' size='small'>
{t('未知状态')}
</Tag>
);
}
};
// Table columns definition
const columns = [
{
title: t('索引'),
dataIndex: 'index',
render: (text) => `#${text}`,
},
// {
// title: t('密钥预览'),
// dataIndex: 'key_preview',
// render: (text) => (
// <Text code style={{ fontSize: '12px' }}>
// {text}
// </Text>
// ),
// },
{
title: t('状态'),
dataIndex: 'status',
render: (status) => renderStatusTag(status),
},
{
title: t('禁用原因'),
dataIndex: 'reason',
render: (reason, record) => {
if (record.status === 1 || !reason) {
return <Text type='quaternary'>-</Text>;
}
return (
<Tooltip content={reason}>
<Text style={{ maxWidth: '200px', display: 'block' }} ellipsis>
{reason}
</Text>
</Tooltip>
);
},
},
{
title: t('禁用时间'),
dataIndex: 'disabled_time',
render: (time, record) => {
if (record.status === 1 || !time) {
return <Text type='quaternary'>-</Text>;
}
return (
<Tooltip content={timestamp2string(time)}>
<Text style={{ fontSize: '12px' }}>{timestamp2string(time)}</Text>
</Tooltip>
);
},
},
{
title: t('操作'),
key: 'action',
fixed: 'right',
width: 150,
render: (_, record) => (
<Space>
{record.status === 1 ? (
<Button
type='danger'
size='small'
loading={operationLoading[`disable_${record.index}`]}
onClick={() => handleDisableKey(record.index)}
>
{t('禁用')}
</Button>
) : (
<Button
type='primary'
size='small'
loading={operationLoading[`enable_${record.index}`]}
onClick={() => handleEnableKey(record.index)}
>
{t('启用')}
</Button>
)}
<Popconfirm
title={t('确定要删除此密钥吗?')}
content={t('此操作不可撤销,将永久删除该密钥')}
onConfirm={() => handleDeleteKey(record.index)}
okType={'danger'}
position={'topRight'}
>
<Button
type='danger'
size='small'
loading={operationLoading[`delete_${record.index}`]}
>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
return (
<Modal
title={
<Space>
<Text>{t('多密钥管理')}</Text>
{channel?.name && (
<Tag size='small' shape='circle' color='white'>
{channel.name}
</Tag>
)}
<Tag size='small' shape='circle' color='white'>
{t('总密钥数')}: {total}
</Tag>
{channel?.channel_info?.multi_key_mode && (
<Tag size='small' shape='circle' color='white'>
{channel.channel_info.multi_key_mode === 'random'
? t('随机模式')
: t('轮询模式')}
</Tag>
)}
</Space>
}
visible={visible}
onCancel={onCancel}
width={900}
footer={null}
>
<div className='flex flex-col mb-5'>
{/* Stats & Mode */}
<div
className='rounded-xl p-4 mb-3'
style={{
background: 'var(--semi-color-bg-1)',
border: '1px solid var(--semi-color-border)',
}}
>
<Row gutter={16} align='middle'>
<Col span={8}>
<div
style={{
background: 'var(--semi-color-bg-0)',
border: '1px solid var(--semi-color-border)',
borderRadius: 12,
padding: 12,
}}
>
<div className='flex items-center gap-2 mb-2'>
<Badge dot type='success' />
<Text type='tertiary'>{t('已启用')}</Text>
</div>
<div className='flex items-end gap-2 mb-2'>
<Text
style={{ fontSize: 18, fontWeight: 700, color: '#22c55e' }}
>
{enabledCount}
</Text>
<Text
style={{ fontSize: 18, color: 'var(--semi-color-text-2)' }}
>
/ {total}
</Text>
</div>
<Progress
percent={enabledPercent}
showInfo={false}
size='small'
stroke='#22c55e'
style={{ height: 6, borderRadius: 999 }}
/>
</div>
</Col>
<Col span={8}>
<div
style={{
background: 'var(--semi-color-bg-0)',
border: '1px solid var(--semi-color-border)',
borderRadius: 12,
padding: 12,
}}
>
<div className='flex items-center gap-2 mb-2'>
<Badge dot type='danger' />
<Text type='tertiary'>{t('手动禁用')}</Text>
</div>
<div className='flex items-end gap-2 mb-2'>
<Text
style={{ fontSize: 18, fontWeight: 700, color: '#ef4444' }}
>
{manualDisabledCount}
</Text>
<Text
style={{ fontSize: 18, color: 'var(--semi-color-text-2)' }}
>
/ {total}
</Text>
</div>
<Progress
percent={manualDisabledPercent}
showInfo={false}
size='small'
stroke='#ef4444'
style={{ height: 6, borderRadius: 999 }}
/>
</div>
</Col>
<Col span={8}>
<div
style={{
background: 'var(--semi-color-bg-0)',
border: '1px solid var(--semi-color-border)',
borderRadius: 12,
padding: 12,
}}
>
<div className='flex items-center gap-2 mb-2'>
<Badge dot type='warning' />
<Text type='tertiary'>{t('自动禁用')}</Text>
</div>
<div className='flex items-end gap-2 mb-2'>
<Text
style={{ fontSize: 18, fontWeight: 700, color: '#f59e0b' }}
>
{autoDisabledCount}
</Text>
<Text
style={{ fontSize: 18, color: 'var(--semi-color-text-2)' }}
>
/ {total}
</Text>
</div>
<Progress
percent={autoDisabledPercent}
showInfo={false}
size='small'
stroke='#f59e0b'
style={{ height: 6, borderRadius: 999 }}
/>
</div>
</Col>
</Row>
</div>
{/* Table */}
<div className='flex-1 flex flex-col min-h-0'>
<Spin spinning={loading}>
<Card className='!rounded-xl'>
<Table
title={() => (
// xs 断点下两栏各占满一行:原来固定 14/10 分栏,在 358px 的弹窗体里
// 右栏只有 ~124px,却要放约 330px 的四个按钮,「删除自动禁用密钥」
// 会溢出到 .semi-modal-body{overflow-x:hidden} 之外被裁掉
<Row gutter={12} style={{ width: '100%' }}>
<Col xs={24} sm={14}>
<Row gutter={12} style={{ alignItems: 'center' }}>
<Col>
<Select
value={statusFilter}
onChange={handleStatusFilterChange}
size='small'
placeholder={t('全部状态')}
>
<Select.Option value={null}>
{t('全部状态')}
</Select.Option>
<Select.Option value={1}>
{t('已启用')}
</Select.Option>
<Select.Option value={2}>
{t('手动禁用')}
</Select.Option>
<Select.Option value={3}>
{t('自动禁用')}
</Select.Option>
</Select>
</Col>
</Row>
</Col>
<Col
span={10}
style={{ display: 'flex', justifyContent: 'flex-end' }}
>
<Space>
<Button
size='small'
type='tertiary'
onClick={() => loadKeyStatus(currentPage, pageSize)}
loading={loading}
>
{t('刷新')}
</Button>
{manualDisabledCount + autoDisabledCount > 0 && (
<Popconfirm
title={t('确定要启用所有密钥吗?')}
onConfirm={handleEnableAll}
position={'topRight'}
>
<Button
size='small'
type='primary'
loading={operationLoading.enable_all}
>
{t('启用全部')}
</Button>
</Popconfirm>
)}
{enabledCount > 0 && (
<Popconfirm
title={t('确定要禁用所有的密钥吗?')}
onConfirm={handleDisableAll}
okType={'danger'}
position={'topRight'}
>
<Button
size='small'
type='danger'
loading={operationLoading.disable_all}
>
{t('禁用全部')}
</Button>
</Popconfirm>
)}
<Popconfirm
title={t('确定要删除所有已自动禁用的密钥吗?')}
content={t(
'此操作不可撤销,将永久删除已自动禁用的密钥',
)}
onConfirm={handleDeleteDisabledKeys}
okType={'danger'}
position={'topRight'}
>
<Button
size='small'
type='warning'
loading={operationLoading.delete_disabled}
>
{t('删除自动禁用密钥')}
</Button>
</Popconfirm>
</Space>
</Col>
</Row>
)}
columns={columns}
dataSource={keyStatusList}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: total,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOpts: [10, 20, 50, 100],
onChange: (page, size) => {
setCurrentPage(page);
loadKeyStatus(page, size);
},
onShowSizeChange: (current, size) => {
setCurrentPage(1);
handlePageSizeChange(size);
},
}}
size='small'
bordered={false}
rowKey='index'
scroll={{ x: 'max-content' }}
empty={
<Empty
image={
<IllustrationNoResult
style={{ width: 140, height: 140 }}
/>
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 140, height: 140 }}
/>
}
title={t('暂无密钥数据')}
description={t('请检查渠道配置或刷新重试')}
style={{ padding: 30 }}
/>
}
/>
</Card>
</Spin>
</div>
</div>
</Modal>
);
};
export default MultiKeyManageModal;
@@ -0,0 +1,69 @@
/*
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 { Skeleton, Typography } from '@douyinfe/semi-ui';
import { useMinimumLoadingTime } from '../../../hooks/common/useMinimumLoadingTime';
import { IconEyeOpened } from '@douyinfe/semi-icons';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const MjLogsActions = ({
loading,
showBanner,
isAdminUser,
compactMode,
setCompactMode,
t,
}) => {
const showSkeleton = useMinimumLoadingTime(loading);
const placeholder = (
<div className='flex items-center mb-2 md:mb-0'>
<IconEyeOpened className='mr-2' />
<Skeleton.Title style={{ width: 300, height: 21, borderRadius: 6 }} />
</div>
);
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<Skeleton loading={showSkeleton} active placeholder={placeholder}>
<div className='flex items-center mb-2 md:mb-0'>
<IconEyeOpened className='mr-2' />
<Text>
{isAdminUser && showBanner
? t(
'当前未开启Midjourney回调,部分项目可能无法获得绘图结果,可在运营设置中开启。',
)
: t('Midjourney 任务记录')}
</Text>
</div>
</Skeleton>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default MjLogsActions;
@@ -0,0 +1,509 @@
/*
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, Progress, Tag, Typography } from '@douyinfe/semi-ui';
import {
Palette,
ZoomIn,
Shuffle,
Move,
FileText,
Blend,
Upload,
Minimize2,
RotateCcw,
PaintBucket,
Focus,
Move3D,
Monitor,
UserCheck,
HelpCircle,
CheckCircle,
Clock,
Copy,
FileX,
Pause,
XCircle,
Loader,
AlertCircle,
Hash,
Video,
} from 'lucide-react';
const colors = [
'amber',
'blue',
'cyan',
'green',
'grey',
'indigo',
'light-blue',
'lime',
'orange',
'pink',
'purple',
'red',
'teal',
'violet',
'yellow',
];
// Render functions
function renderType(type, t) {
switch (type) {
case 'IMAGINE':
return (
<Tag color='blue' shape='circle' prefixIcon={<Palette size={14} />}>
{t('绘图')}
</Tag>
);
case 'UPSCALE':
return (
<Tag color='orange' shape='circle' prefixIcon={<ZoomIn size={14} />}>
{t('放大')}
</Tag>
);
case 'VIDEO':
return (
<Tag color='orange' shape='circle' prefixIcon={<Video size={14} />}>
{t('视频')}
</Tag>
);
case 'EDITS':
return (
<Tag color='orange' shape='circle' prefixIcon={<Video size={14} />}>
{t('编辑')}
</Tag>
);
case 'VARIATION':
return (
<Tag color='purple' shape='circle' prefixIcon={<Shuffle size={14} />}>
{t('变换')}
</Tag>
);
case 'HIGH_VARIATION':
return (
<Tag color='purple' shape='circle' prefixIcon={<Shuffle size={14} />}>
{t('强变换')}
</Tag>
);
case 'LOW_VARIATION':
return (
<Tag color='purple' shape='circle' prefixIcon={<Shuffle size={14} />}>
{t('弱变换')}
</Tag>
);
case 'PAN':
return (
<Tag color='cyan' shape='circle' prefixIcon={<Move size={14} />}>
{t('平移')}
</Tag>
);
case 'DESCRIBE':
return (
<Tag color='yellow' shape='circle' prefixIcon={<FileText size={14} />}>
{t('图生文')}
</Tag>
);
case 'BLEND':
return (
<Tag color='lime' shape='circle' prefixIcon={<Blend size={14} />}>
{t('图混合')}
</Tag>
);
case 'UPLOAD':
return (
<Tag color='blue' shape='circle' prefixIcon={<Upload size={14} />}>{t('上传文件')}</Tag>
);
case 'SHORTEN':
return (
<Tag color='pink' shape='circle' prefixIcon={<Minimize2 size={14} />}>
{t('缩词')}
</Tag>
);
case 'REROLL':
return (
<Tag color='indigo' shape='circle' prefixIcon={<RotateCcw size={14} />}>
{t('重绘')}
</Tag>
);
case 'INPAINT':
return (
<Tag
color='violet'
shape='circle'
prefixIcon={<PaintBucket size={14} />}
>
{t('局部重绘-提交')}
</Tag>
);
case 'ZOOM':
return (
<Tag color='teal' shape='circle' prefixIcon={<Focus size={14} />}>
{t('变焦')}
</Tag>
);
case 'CUSTOM_ZOOM':
return (
<Tag color='teal' shape='circle' prefixIcon={<Move3D size={14} />}>
{t('自定义变焦-提交')}
</Tag>
);
case 'MODAL':
return (
<Tag color='green' shape='circle' prefixIcon={<Monitor size={14} />}>
{t('窗口处理')}
</Tag>
);
case 'SWAP_FACE':
return (
<Tag
color='light-green'
shape='circle'
prefixIcon={<UserCheck size={14} />}
>
{t('换脸')}
</Tag>
);
default:
return (
<Tag color='white' shape='circle' prefixIcon={<HelpCircle size={14} />}>
{t('未知')}
</Tag>
);
}
}
function renderCode(code, t) {
switch (code) {
case 1:
return (
<Tag
color='green'
shape='circle'
prefixIcon={<CheckCircle size={14} />}
>
{t('已提交')}
</Tag>
);
case 21:
return (
<Tag color='lime' shape='circle' prefixIcon={<Clock size={14} />}>
{t('等待中')}
</Tag>
);
case 22:
return (
<Tag color='orange' shape='circle' prefixIcon={<Copy size={14} />}>
{t('重复提交')}
</Tag>
);
case 0:
return (
<Tag color='yellow' shape='circle' prefixIcon={<FileX size={14} />}>
{t('未提交')}
</Tag>
);
default:
return (
<Tag color='white' shape='circle' prefixIcon={<HelpCircle size={14} />}>
{t('未知')}
</Tag>
);
}
}
function renderStatus(type, t) {
switch (type) {
case 'SUCCESS':
return (
<Tag
color='green'
shape='circle'
prefixIcon={<CheckCircle size={14} />}
>
{t('成功')}
</Tag>
);
case 'NOT_START':
return (
<Tag color='grey' shape='circle' prefixIcon={<Pause size={14} />}>
{t('未启动')}
</Tag>
);
case 'SUBMITTED':
return (
<Tag color='yellow' shape='circle' prefixIcon={<Clock size={14} />}>
{t('队列中')}
</Tag>
);
case 'IN_PROGRESS':
return (
<Tag color='blue' shape='circle' prefixIcon={<Loader size={14} />}>
{t('执行中')}
</Tag>
);
case 'FAILURE':
return (
<Tag color='red' shape='circle' prefixIcon={<XCircle size={14} />}>
{t('失败')}
</Tag>
);
case 'MODAL':
return (
<Tag
color='yellow'
shape='circle'
prefixIcon={<AlertCircle size={14} />}
>
{t('窗口等待')}
</Tag>
);
default:
return (
<Tag color='white' shape='circle' prefixIcon={<HelpCircle size={14} />}>
{t('未知')}
</Tag>
);
}
}
const renderTimestamp = (timestampInSeconds) => {
const date = new Date(timestampInSeconds * 1000);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
function renderDuration(submit_time, finishTime, t) {
if (!submit_time || !finishTime) return 'N/A';
const start = new Date(submit_time);
const finish = new Date(finishTime);
const durationMs = finish - start;
const durationSec = (durationMs / 1000).toFixed(1);
const color = durationSec > 60 ? 'red' : 'green';
return (
<Tag color={color} shape='circle' prefixIcon={<Clock size={14} />}>
{durationSec} {t('秒')}
</Tag>
);
}
export const getMjLogsColumns = ({
t,
COLUMN_KEYS,
copyText,
openContentModal,
openImageModal,
isAdminUser,
}) => {
return [
{
key: COLUMN_KEYS.SUBMIT_TIME,
title: t('提交时间'),
dataIndex: 'submit_time',
render: (text, record, index) => {
return <div>{renderTimestamp(text / 1000)}</div>;
},
},
{
key: COLUMN_KEYS.DURATION,
title: t('花费时间'),
dataIndex: 'finish_time',
render: (finish, record) => {
return renderDuration(record.submit_time, finish, t);
},
},
{
key: COLUMN_KEYS.CHANNEL,
title: t('渠道'),
dataIndex: 'channel_id',
render: (text, record, index) => {
return isAdminUser ? (
<div>
<Tag
color={colors[parseInt(text) % colors.length]}
shape='circle'
prefixIcon={<Hash size={14} />}
onClick={() => {
copyText(text);
}}
>
{' '}
{text}{' '}
</Tag>
</div>
) : (
<></>
);
},
},
{
key: COLUMN_KEYS.TYPE,
title: t('类型'),
dataIndex: 'action',
render: (text, record, index) => {
return <div>{renderType(text, t)}</div>;
},
},
{
key: COLUMN_KEYS.TASK_ID,
title: t('任务ID'),
dataIndex: 'mj_id',
render: (text, record, index) => {
return <div>{text}</div>;
},
},
{
key: COLUMN_KEYS.SUBMIT_RESULT,
title: t('提交结果'),
dataIndex: 'code',
render: (text, record, index) => {
return isAdminUser ? <div>{renderCode(text, t)}</div> : <></>;
},
},
{
key: COLUMN_KEYS.TASK_STATUS,
title: t('任务状态'),
dataIndex: 'status',
render: (text, record, index) => {
return <div>{renderStatus(text, t)}</div>;
},
},
{
key: COLUMN_KEYS.PROGRESS,
title: t('进度'),
dataIndex: 'progress',
render: (text, record, index) => {
return (
<div>
{
<Progress
stroke={
record.status === 'FAILURE'
? 'var(--semi-color-warning)'
: null
}
percent={text ? parseInt(text.replace('%', '')) : 0}
showInfo={true}
aria-label='drawing progress'
style={{ minWidth: '160px' }}
/>
}
</div>
);
},
},
{
key: COLUMN_KEYS.IMAGE,
title: t('结果图片'),
dataIndex: 'image_url',
render: (text, record, index) => {
if (!text) {
return t('无');
}
return (
<Button
size='small'
onClick={() => {
openImageModal(text);
}}
>
{t('查看图片')}
</Button>
);
},
},
{
key: COLUMN_KEYS.PROMPT,
title: 'Prompt',
dataIndex: 'prompt',
render: (text, record, index) => {
if (!text) {
return t('无');
}
return (
<Typography.Text
ellipsis={{ showTooltip: true }}
style={{ width: 100 }}
onClick={() => {
openContentModal(text);
}}
>
{text}
</Typography.Text>
);
},
},
{
key: COLUMN_KEYS.PROMPT_EN,
title: 'PromptEn',
dataIndex: 'prompt_en',
render: (text, record, index) => {
if (!text) {
return t('无');
}
return (
<Typography.Text
ellipsis={{ showTooltip: true }}
style={{ width: 100 }}
onClick={() => {
openContentModal(text);
}}
>
{text}
</Typography.Text>
);
},
},
{
key: COLUMN_KEYS.FAIL_REASON,
title: t('失败原因'),
dataIndex: 'fail_reason',
fixed: 'right',
render: (text, record, index) => {
if (!text) {
return t('无');
}
return (
<Typography.Text
ellipsis={{ showTooltip: true }}
style={{ width: 100 }}
onClick={() => {
openContentModal(text);
}}
>
{text}
</Typography.Text>
);
},
},
];
};
@@ -0,0 +1,130 @@
/*
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 { IconSearch } from '@douyinfe/semi-icons';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
const MjLogsFilters = ({
formInitValues,
setFormApi,
refresh,
setShowColumnSelector,
formApi,
loading,
isAdminUser,
t,
}) => {
return (
<Form
initValues={formInitValues}
getFormApi={(api) => setFormApi(api)}
onSubmit={refresh}
allowEmpty={true}
autoComplete='off'
layout='vertical'
trigger='change'
stopValidateWithError={false}
>
<div className='flex flex-col gap-2'>
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2'>
{/* 时间选择器 */}
<div className='col-span-1 lg:col-span-2'>
<Form.DatePicker
field='dateRange'
className='w-full'
type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]}
showClear
pure
size='small'
presets={DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text),
start: preset.start(),
end: preset.end(),
}))}
/>
</div>
{/* 任务 ID */}
<Form.Input
field='mj_id'
prefix={<IconSearch />}
placeholder={t('任务 ID')}
showClear
pure
size='small'
/>
{/* 渠道 ID - 仅管理员可见 */}
{isAdminUser && (
<Form.Input
field='channel_id'
prefix={<IconSearch />}
placeholder={t('渠道 ID')}
showClear
pure
size='small'
/>
)}
</div>
{/* 操作按钮区域 */}
<div className='flex justify-between items-center'>
<div></div>
<div className='flex gap-2'>
<Button
type='tertiary'
htmlType='submit'
loading={loading}
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={() => {
if (formApi) {
formApi.reset();
setTimeout(() => {
refresh();
}, 100);
}
}}
size='small'
>
{t('重置')}
</Button>
<Button
type='tertiary'
onClick={() => setShowColumnSelector(true)}
size='small'
>
{t('列设置')}
</Button>
</div>
</div>
</div>
</Form>
);
};
export default MjLogsFilters;
@@ -0,0 +1,108 @@
/*
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 } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getMjLogsColumns } from './MjLogsColumnDefs';
const MjLogsTable = (mjLogsData) => {
const {
logs,
loading,
activePage,
pageSize,
logCount,
compactMode,
visibleColumns,
handlePageChange,
handlePageSizeChange,
copyText,
openContentModal,
openImageModal,
isAdminUser,
t,
COLUMN_KEYS,
} = mjLogsData;
// Get all columns
const allColumns = useMemo(() => {
return getMjLogsColumns({
t,
COLUMN_KEYS,
copyText,
openContentModal,
openImageModal,
isAdminUser,
});
}, [t, COLUMN_KEYS, copyText, openContentModal, openImageModal, isAdminUser]);
// 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(() => {
return compactMode
? visibleColumnsList.map(({ fixed, ...rest }) => rest)
: visibleColumnsList;
}, [compactMode, visibleColumnsList]);
return (
<CardTable
columns={tableColumns}
dataSource={logs}
rowKey='key'
loading={loading}
scroll={compactMode ? undefined : { x: 'max-content' }}
className='rounded-xl overflow-hidden'
size='middle'
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: logCount,
pageSizeOptions: [10, 20, 50, 100],
showSizeChanger: true,
onPageSizeChange: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
/>
);
};
export default MjLogsTable;
+65
View File
@@ -0,0 +1,65 @@
/*
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 { Layout } from '@douyinfe/semi-ui';
import CardPro from '../../common/ui/CardPro';
import MjLogsTable from './MjLogsTable';
import MjLogsActions from './MjLogsActions';
import MjLogsFilters from './MjLogsFilters';
import ColumnSelectorModal from './modals/ColumnSelectorModal';
import ContentModal from './modals/ContentModal';
import { useMjLogsData } from '../../../hooks/mj-logs/useMjLogsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
const MjLogsPage = () => {
const mjLogsData = useMjLogsData();
const isMobile = useIsMobile();
return (
<>
{/* Modals */}
<ColumnSelectorModal {...mjLogsData} />
<ContentModal {...mjLogsData} />
<Layout>
<CardPro
type='type2'
statsArea={<MjLogsActions {...mjLogsData} />}
searchArea={<MjLogsFilters {...mjLogsData} />}
paginationArea={createCardProPagination({
currentPage: mjLogsData.activePage,
pageSize: mjLogsData.pageSize,
total: mjLogsData.logCount,
onPageChange: mjLogsData.handlePageChange,
onPageSizeChange: mjLogsData.handlePageSizeChange,
isMobile: isMobile,
t: mjLogsData.t,
})}
t={mjLogsData.t}
>
<MjLogsTable {...mjLogsData} />
</CardPro>
</Layout>
</>
);
};
export default MjLogsPage;
@@ -0,0 +1,109 @@
/*
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 { getMjLogsColumns } from '../MjLogsColumnDefs';
const ColumnSelectorModal = ({
showColumnSelector,
setShowColumnSelector,
visibleColumns,
handleColumnVisibilityChange,
handleSelectAll,
initDefaultColumns,
COLUMN_KEYS,
isAdminUser,
copyText,
openContentModal,
openImageModal,
t,
}) => {
// Get all columns for display in selector
const allColumns = getMjLogsColumns({
t,
COLUMN_KEYS,
copyText,
openContentModal,
openImageModal,
isAdminUser,
});
return (
<Modal
title={t('列设置')}
visible={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
footer={
<div className='flex justify-end'>
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('取消')}
</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('确定')}
</Button>
</div>
}
>
<div style={{ marginBottom: 20 }}>
<Checkbox
checked={Object.values(visibleColumns).every((v) => v === true)}
indeterminate={
Object.values(visibleColumns).some((v) => v === true) &&
!Object.values(visibleColumns).every((v) => v === true)
}
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.SUBMIT_RESULT)
) {
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,61 @@
/*
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, ImagePreview } from '@douyinfe/semi-ui';
const ContentModal = ({
isModalOpen,
setIsModalOpen,
modalContent,
isModalOpenurl,
setIsModalOpenurl,
modalImageUrl,
}) => {
return (
<>
{/* Text Content Modal */}
<Modal
visible={isModalOpen}
onOk={() => setIsModalOpen(false)}
onCancel={() => setIsModalOpen(false)}
closable={null}
bodyStyle={{
height: '400px',
overflowX: 'hidden',
overflowY: 'auto',
}}
width={800}
>
<p style={{ whiteSpace: 'pre-line', overflowWrap: 'anywhere' }}>
{modalContent}
</p>
</Modal>
{/* Image Preview Modal */}
<ImagePreview
src={modalImageUrl}
visible={isModalOpenurl}
onVisibleChange={(visible) => setIsModalOpenurl(visible)}
/>
</>
);
};
export default ContentModal;
@@ -0,0 +1,267 @@
/*
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 } from '@douyinfe/semi-ui';
import { Copy, Lock } from 'lucide-react';
import {
getLobeHubIcon,
formatPriceInfo,
getDiscountBadgeText,
} from '../../../../helpers';
// Simplified vendor color schemes — fewer layers, better performance
// tint: 用于卡片装饰纹理(点阵/柔光)的供应商主题色(text-* 供 currentColor 取色)
// accentBg: 顶部识别色条。必须写成字面量类名——此前用
// accent.replaceAll('border-','bg-') 运行时拼接,Tailwind JIT 扫不到
// 拼接产物(bg-emerald-300 等未在源码中出现),色条实际从未渲染
const vendorColors = {
OpenAI: {
accentBg: 'bg-emerald-300 dark:bg-emerald-700',
bg: 'bg-emerald-50 dark:bg-emerald-900/20',
border: 'border-emerald-200 dark:border-emerald-800/50',
hoverBorder: 'hover:border-emerald-400 dark:hover:border-emerald-600',
tint: 'text-emerald-600 dark:text-emerald-400',
},
Anthropic: {
accentBg: 'bg-amber-300 dark:bg-amber-700',
bg: 'bg-amber-50 dark:bg-amber-900/20',
border: 'border-amber-200 dark:border-amber-800/50',
hoverBorder: 'hover:border-amber-400 dark:hover:border-amber-600',
tint: 'text-amber-600 dark:text-amber-400',
},
Google: {
accentBg: 'bg-blue-300 dark:bg-blue-700',
bg: 'bg-blue-50 dark:bg-blue-900/20',
border: 'border-blue-200 dark:border-blue-800/50',
hoverBorder: 'hover:border-blue-400 dark:hover:border-blue-600',
tint: 'text-blue-600 dark:text-blue-400',
},
Meta: {
accentBg: 'bg-blue-300 dark:bg-blue-700',
bg: 'bg-blue-50 dark:bg-blue-900/20',
border: 'border-blue-200 dark:border-blue-800/50',
hoverBorder: 'hover:border-blue-400 dark:hover:border-blue-600',
tint: 'text-blue-600 dark:text-blue-400',
},
Mistral: {
accentBg: 'bg-orange-300 dark:bg-orange-700',
bg: 'bg-orange-50 dark:bg-orange-900/20',
border: 'border-orange-200 dark:border-orange-800/50',
hoverBorder: 'hover:border-orange-400 dark:hover:border-orange-600',
tint: 'text-orange-600 dark:text-orange-400',
},
Midjourney: {
accentBg: 'bg-brand-from dark:bg-brand-deep',
bg: 'bg-brand/5 dark:bg-brand-deep/20',
border: 'border-brand/20 dark:border-brand-deep/50',
hoverBorder: 'hover:border-brand-from dark:hover:border-brand-deep',
tint: 'text-brand-deep dark:text-brand-from',
},
default: {
accentBg: 'bg-brand-from dark:bg-brand-deep',
bg: 'bg-gray-50 dark:bg-neutral-800/50',
border: 'border-gray-200 dark:border-neutral-700/50',
hoverBorder: 'hover:border-brand-from dark:hover:border-brand-deep',
tint: 'text-gray-500 dark:text-gray-400',
},
};
const getVendorColors = (vendorName) => {
return vendorColors[vendorName] || vendorColors.default;
};
const BentoCard = ({ model, priceData, hidePrice, onClick, onCopy, t }) => {
const colors = getVendorColors(model.vendor_name);
const getModelIcon = (model) => {
if (!model) return <Avatar size='small'>?</Avatar>;
if (model.icon)
return (
<div className='w-8 h-8 flex items-center justify-center'>
{getLobeHubIcon(model.icon, 24)}
</div>
);
if (model.vendor_icon)
return (
<div className='w-8 h-8 flex items-center justify-center'>
{getLobeHubIcon(model.vendor_icon, 24)}
</div>
);
return (
<Avatar
size='small'
style={{
backgroundColor: 'var(--brand-primary)',
fontSize: 12,
}}
>
{model.model_name?.slice(0, 2).toUpperCase()}
</Avatar>
);
};
return (
<div
onClick={onClick}
className={`
group relative col-span-1 h-auto min-h-[140px]
app-card app-card-hover overflow-hidden
`}
>
{/* Top accent line —— 供应商识别色,常驻可见(原 opacity-0 仅 hover 显示,
* 改用统一 .app-card 中性边框后会丢失供应商区分,尤其移动端无 hover;
* 改为常驻 70%、hover 提到 100% 强化)。 */}
<div
className={`
absolute top-0 left-0 right-0 h-[2px] ${colors.accentBg}
opacity-70 group-hover:opacity-100 transition-opacity duration-300
`}
/>
{/* ===== 装饰背景层(纯 CSS,pointer-events 关闭,不影响交互) ===== */}
{/* 1. 供应商主题色点阵纹理 —— currentColor 取 tint 色,极低透明度只做质感 */}
<div
aria-hidden='true'
className={`absolute inset-0 pointer-events-none ${colors.tint} opacity-[0.05] dark:opacity-[0.07] group-hover:opacity-[0.09] transition-opacity duration-500`}
style={{
backgroundImage: 'radial-gradient(currentColor 1px, transparent 1px)',
backgroundSize: '14px 14px',
maskImage: 'linear-gradient(135deg, black 0%, transparent 55%)',
WebkitMaskImage: 'linear-gradient(135deg, black 0%, transparent 55%)',
}}
/>
{/* 2. 右上角柔光 —— 供应商浅色晕染,hover 时轻微增强 */}
<div
aria-hidden='true'
className={`absolute -top-10 -right-10 w-32 h-32 rounded-full ${colors.bg} blur-2xl opacity-60 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none`}
/>
{/* 3. 右下角供应商图标水印 —— 浅浅的品牌图案 */}
{(model.vendor_icon || model.icon) && (
<div
aria-hidden='true'
className='absolute -bottom-5 -right-4 pointer-events-none opacity-[0.06] dark:opacity-[0.08] group-hover:opacity-[0.12] transition-all duration-500 rotate-[-12deg] group-hover:rotate-[-6deg] group-hover:scale-110'
>
{getLobeHubIcon(model.vendor_icon || model.icon, 88)}
</div>
)}
<div className='relative flex-1 p-5 flex flex-col justify-between h-full'>
<div className='flex flex-col gap-3'>
{/* Header */}
<div className='flex items-start justify-between'>
<div
className={`
p-2.5 ${colors.bg} rounded-xl border ${colors.border}
transition-transform duration-300
group-hover:scale-105
`}
>
{getModelIcon(model)}
</div>
<button
onClick={(e) => {
e.stopPropagation();
onCopy(model.model_name);
}}
className='p-1.5 text-gray-400 dark:text-neutral-500 hover:text-brand-deep dark:hover:text-brand-from hover:bg-brand/5 dark:hover:bg-brand-deep/30 rounded-lg transition-colors duration-200'
title={t('复制模型名称')}
>
<Copy size={16} />
</button>
</div>
{/* Model Name */}
<h3 className='font-bold text-gray-900 dark:text-white tracking-tight text-base truncate'>
{model.model_name}
</h3>
{/* 等级锁态:仅可见(当前等级不可调用) */}
{model.level_locked && (
<span
className='inline-flex items-center gap-1 mt-1 px-2 py-0.5 rounded-md text-[11px] bg-gray-100 dark:bg-neutral-800 text-gray-500 dark:text-neutral-400'
title={t('当前等级无权调用此模型,升级等级后可用')}
>
<Lock size={11} />
{t('仅可见')}
</span>
)}
{/* Description — show if available */}
{model.description && (
<p className='text-xs text-gray-500 dark:text-neutral-400 line-clamp-1'>
{model.description}
</p>
)}
</div>
{/* Pricing Tags */}
{!hidePrice && (
<div className='mt-4 relative'>
{/* 折扣徽标:实付价低于管理员维护的官方牌价时出现,
* 半浮于价格框上沿,品牌深-主色渐变强调(随主题预设联动,
* 深起点保证与卡片浅色品牌纹理拉开对比);加价/未配置官方价时不渲染 */}
{getDiscountBadgeText(priceData) && (
<span
className='absolute -top-2.5 right-3 z-10 px-2 py-0.5 rounded-full
text-[11px] font-bold text-white leading-4
bg-gradient-to-r from-brand-deep to-brand
shadow-md shadow-brand/30 select-none'
title={t(
'相比官方牌价的折扣,按当前计价分组实付价计算(已含您的等级折扣),仅供参考',
)}
>
{getDiscountBadgeText(priceData)}
</span>
)}
<div
className={`
px-3 py-2.5
bg-gray-50/80 dark:bg-neutral-800/60
rounded-xl border border-gray-200/50 dark:border-neutral-700/50
text-xs font-mono text-gray-600 dark:text-neutral-300
flex flex-col gap-1
`}
>
{formatPriceInfo(priceData, t)}
{/* 计价分组标注:明确该价格按哪个分组倍率计算,
* 消除「最优倍率视图」下与实际账单分组不一致的歧义 */}
{priceData?.usedGroup && (
<span
className='text-[10px] leading-4 font-sans'
style={{ color: 'var(--semi-color-text-3)' }}
title={t('该价格按 {{group}} 分组倍率计算', {
group: priceData.usedGroup,
})}
>
{t('按 {{group}} 分组计价', { group: priceData.usedGroup })}
</span>
)}
</div>
</div>
)}
</div>
</div>
);
};
export default React.memo(BentoCard);
@@ -0,0 +1,318 @@
/*
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, useRef, useEffect, useState } from 'react';
import { calculateModelPrice, getLobeHubIcon } from '../../../../helpers';
import BentoCard from './BentoCard';
import { Empty } from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../common/illustrations';
import { Layers } from 'lucide-react';
// Vendor accent colors for section headers
const vendorAccents = {
OpenAI: 'from-emerald-500 to-teal-500',
Anthropic: 'from-amber-500 to-orange-500',
Google: 'from-blue-500 to-brand-to',
Meta: 'from-blue-600 to-blue-700',
Mistral: 'from-orange-500 to-red-500',
Midjourney: 'from-brand-from to-brand-to',
default: 'from-brand-from to-brand-to',
};
const getVendorAccent = (vendor) =>
vendorAccents[vendor] || vendorAccents.default;
// Skeleton card for loading state
const SkeletonCard = () => (
<div className='app-card overflow-hidden min-h-[140px] animate-pulse'>
<div className='p-5 flex flex-col gap-3'>
<div className='flex items-start justify-between'>
<div className='w-12 h-12 bg-gray-200 dark:bg-neutral-700 rounded-xl' />
<div className='w-6 h-6 bg-gray-200 dark:bg-neutral-700 rounded-lg' />
</div>
<div className='w-3/4 h-5 bg-gray-200 dark:bg-neutral-700 rounded-lg' />
<div className='mt-2 px-3 py-3 bg-gray-100 dark:bg-neutral-800 rounded-xl'>
<div className='w-full h-3 bg-gray-200 dark:bg-neutral-700 rounded mb-2' />
<div className='w-2/3 h-3 bg-gray-200 dark:bg-neutral-700 rounded' />
</div>
</div>
</div>
);
// Hook: observe element visibility via IntersectionObserver
const useInView = (options = {}) => {
const ref = useRef(null);
const [inView, setInView] = useState(false);
useEffect(() => {
const el = ref.current;
if (!el) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setInView(true);
observer.disconnect(); // only trigger once
}
},
{ rootMargin: '200px 0px', ...options },
);
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, inView];
};
const BentoGrid = ({
filteredModels,
loading,
selectedGroup,
groupRatio,
groupModelDiscount,
tokenUnit,
displayPrice,
currency,
hidePrice,
t,
copyText,
openModelDetail,
}) => {
// Group models by Vendor for sections
const sections = useMemo(() => {
if (!filteredModels) return [];
const groups = {};
filteredModels.forEach((model) => {
const vendor = model.vendor_name || 'Others';
if (!groups[vendor]) {
groups[vendor] = [];
}
groups[vendor].push(model);
});
// Sort keys with priority vendors first
const sortedKeys = Object.keys(groups).sort((a, b) => {
const priority = ['OpenAI', 'Anthropic', 'Google', 'Midjourney'];
const idxA = priority.indexOf(a);
const idxB = priority.indexOf(b);
if (idxA !== -1 && idxB !== -1) return idxA - idxB;
if (idxA !== -1) return -1;
if (idxB !== -1) return 1;
return a.localeCompare(b);
});
return sortedKeys.map((key) => ({
title: key,
models: groups[key],
}));
}, [filteredModels]);
// Loading skeleton state
if (loading) {
return (
<div className='container mx-auto px-6 py-6 pb-20'>
{[1, 2].map((sectionIdx) => (
<div key={sectionIdx} className='mb-10'>
{/* Skeleton section header */}
<div className='flex items-center gap-4 mb-5'>
<div className='w-10 h-10 bg-gray-200 dark:bg-neutral-700 rounded-xl animate-pulse' />
<div className='w-32 h-6 bg-gray-200 dark:bg-neutral-700 rounded-lg animate-pulse' />
<div className='flex-1 h-px bg-gray-200 dark:bg-neutral-700' />
<div className='w-16 h-7 bg-gray-200 dark:bg-neutral-700 rounded-full animate-pulse' />
</div>
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5'>
{Array.from({ length: 8 }).map((_, i) => (
<SkeletonCard key={i} />
))}
</div>
</div>
))}
</div>
);
}
if (filteredModels.length === 0) {
return (
<div className='flex flex-col items-center justify-center py-32'>
<div className='relative'>
<div className='absolute inset-0 bg-gradient-to-r from-brand-from/10 to-brand-to/10 blur-3xl rounded-full' />
<Empty
image={<IllustrationNoResult style={{ width: 180, height: 180 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 180, height: 180 }} />
}
description={
<span className='text-gray-500 dark:text-neutral-400 font-medium mt-4 block'>
{t('No models found')}
</span>
}
/>
</div>
</div>
);
}
return (
<div className='container mx-auto px-6 py-6 pb-20'>
{sections.map((section, sectionIndex) => (
<VendorSection
key={section.title}
section={section}
sectionIndex={sectionIndex}
selectedGroup={selectedGroup}
groupRatio={groupRatio}
groupModelDiscount={groupModelDiscount}
tokenUnit={tokenUnit}
displayPrice={displayPrice}
currency={currency}
hidePrice={hidePrice}
t={t}
copyText={copyText}
openModelDetail={openModelDetail}
/>
))}
{/* CSS for animations */}
<style>{`
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
`}</style>
</div>
);
};
// Lazy-rendered vendor section — only renders cards when scrolled into view
const VendorSection = React.memo(
({
section,
sectionIndex,
selectedGroup,
groupRatio,
groupModelDiscount,
tokenUnit,
displayPrice,
currency,
hidePrice,
t,
copyText,
openModelDetail,
}) => {
const [sectionRef, isInView] = useInView();
const accent = getVendorAccent(section.title);
// 分组标题优先展示真实供应商 logo(取该组任一模型的 vendor_icon),
// 没有时回退到原来的渐变通用图标
const vendorIcon = section.models.find((m) => m.vendor_icon)?.vendor_icon;
return (
<div ref={sectionRef} className='mb-10'>
{/* Section Header */}
<div className='flex items-center gap-4 mb-5'>
{vendorIcon ? (
<div className='p-2.5 rounded-xl bg-white/80 dark:bg-neutral-800/80 backdrop-blur-sm border border-gray-200/60 dark:border-neutral-700/60 shadow-sm'>
<div className='w-5 h-5 flex items-center justify-center'>
{getLobeHubIcon(vendorIcon, 20)}
</div>
</div>
) : (
<div
className={`p-2.5 rounded-xl bg-gradient-to-br ${accent} shadow-lg shadow-brand/20`}
>
<Layers size={20} className='text-white' />
</div>
)}
<h2 className='text-2xl font-bold text-gray-900 dark:text-white tracking-tight'>
{section.title}
</h2>
<div className='flex-1 h-px bg-gradient-to-r from-gray-200 via-gray-300/50 to-transparent dark:from-neutral-700 dark:via-neutral-800/50 dark:to-transparent' />
<div className='flex items-center gap-2'>
<span
className={`text-sm font-bold font-mono px-3 py-1.5 rounded-full bg-gradient-to-r ${accent} text-white shadow-md`}
>
{section.models.length}
</span>
<span className='text-sm text-gray-500 dark:text-neutral-400 font-medium'>
{t('MODELS')}
</span>
</div>
</div>
{/* Cards Grid — render skeletons when not in view */}
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5'>
{isInView
? section.models.map((model, index) => {
const priceData = calculateModelPrice({
record: model,
selectedGroup,
groupRatio,
groupModelDiscount,
tokenUnit,
displayPrice,
currency,
});
// Cap animation delay at 600ms so cards never stay invisible too long
const delay = Math.min(index * 40, 600);
return (
<div
key={model.key || index}
style={{
animationDelay: `${delay}ms`,
animation: 'fadeInUp 0.35s ease-out forwards',
opacity: 0,
}}
>
<BentoCard
model={model}
priceData={priceData}
hidePrice={hidePrice}
t={t}
onClick={() => openModelDetail(model)}
onCopy={copyText}
/>
</div>
);
})
: // Placeholder skeleton cards when section is not yet visible
Array.from({ length: Math.min(section.models.length, 8) }).map(
(_, i) => <SkeletonCard key={i} />,
)}
</div>
</div>
);
},
);
VendorSection.displayName = 'VendorSection';
export default BentoGrid;
@@ -0,0 +1,117 @@
/*
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, { useState, useEffect, useRef, useCallback } from 'react';
import { Search, Sparkles } from 'lucide-react';
const BentoHero = ({ searchValue, setSearchValue, t }) => {
// Debounced search: local state for instant typing feedback, debounced propagation
const [localSearch, setLocalSearch] = useState(searchValue);
const debounceTimer = useRef(null);
// Sync external value → local (e.g. if cleared by parent)
// Also clear any pending debounce to avoid overriding the external change
useEffect(() => {
setLocalSearch(searchValue);
if (debounceTimer.current) {
clearTimeout(debounceTimer.current);
debounceTimer.current = null;
}
}, [searchValue]);
const handleSearchChange = useCallback(
(e) => {
const value = e.target.value;
setLocalSearch(value);
// Debounce: propagate to parent after 300ms of no typing
if (debounceTimer.current) clearTimeout(debounceTimer.current);
debounceTimer.current = setTimeout(() => {
setSearchValue(value);
}, 300);
},
[setSearchValue],
);
// Cleanup timer on unmount
useEffect(() => {
return () => {
if (debounceTimer.current) clearTimeout(debounceTimer.current);
};
}, []);
return (
<div className='relative w-full pt-16 md:pt-20 pb-8 px-6 flex flex-col items-center justify-center text-center z-10 overflow-hidden'>
{/* Lightweight decorative elements */}
<div className='absolute inset-0 overflow-hidden pointer-events-none'>
<Sparkles className='absolute top-20 left-[15%] w-6 h-6 text-brand-via/40 dark:text-brand-via/25' />
<Sparkles className='absolute top-32 right-[20%] w-4 h-4 text-brand-from/30 dark:text-brand-from/20' />
{/* Aurora 柔光斑 —— 纯 CSS 装饰,营造氛围;色相全部取品牌渐变三段,随主题预设联动 */}
<div className='absolute -top-24 left-[8%] w-72 h-72 rounded-full bg-brand-from/10 dark:bg-brand-from/[0.07] blur-3xl' />
<div className='absolute -top-16 right-[5%] w-80 h-80 rounded-full bg-brand-to/10 dark:bg-brand-to/[0.06] blur-3xl' />
<div className='absolute top-24 left-[45%] w-56 h-56 rounded-full bg-brand-via/10 dark:bg-brand-via/[0.05] blur-3xl' />
</div>
{/* Badge chip */}
<div className='relative mb-5'>
<span className='inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-semibold tracking-wide uppercase bg-white/70 dark:bg-neutral-900/70 backdrop-blur-sm border border-brand-from/30 dark:border-brand-from/20 text-brand-deep dark:text-brand-from shadow-sm shadow-brand/10'>
<Sparkles className='w-3.5 h-3.5' />
{t('模型超市')}
</span>
</div>
{/* Title */}
<h1 className='text-4xl md:text-6xl font-extrabold tracking-tight mb-4'>
<span className='bg-clip-text text-transparent bg-gradient-to-r from-brand-from via-brand-via to-brand-to'>
{t('Search available models')}
</span>
</h1>
{/* Subtitle */}
<p className='max-w-xl text-sm md:text-base text-gray-500 dark:text-neutral-400 mb-6'>
{t('一站式浏览、比价与接入各大 AI 模型')}
</p>
{/* Search Input — simplified, fewer layers */}
<div className='relative w-full max-w-2xl group'>
<div className='relative flex items-center bg-white/80 dark:bg-neutral-900/80 backdrop-blur-xl border border-gray-200/80 dark:border-neutral-700/50 rounded-full overflow-hidden shadow-lg shadow-gray-200/50 dark:shadow-black/30 transition-all duration-300 focus-within:border-brand-from dark:focus-within:border-brand focus-within:shadow-xl focus-within:shadow-brand/20 dark:focus-within:shadow-brand-deep/20'>
<div className='pl-6 text-gray-400 dark:text-neutral-500 group-focus-within:text-brand dark:group-focus-within:text-brand-from transition-colors duration-300'>
<Search size={22} />
</div>
<input
type='text'
className='w-full bg-transparent border-none py-4 px-4 pr-6 text-lg text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-neutral-500 focus:outline-none focus:ring-0'
placeholder={t('Search models...')}
value={localSearch}
onChange={handleSearchChange}
/>
</div>
</div>
{/* Status hint */}
<p className='mt-4 text-sm text-gray-500 dark:text-neutral-500 font-medium'>
<span className='inline-flex items-center gap-1.5'>
<span className='w-2 h-2 bg-brand rounded-full animate-pulse' />
{t('实时更新')}
</span>
</p>
</div>
);
};
export default BentoHero;
@@ -0,0 +1,295 @@
/*
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, { useRef, useState, useEffect } from 'react';
import { Button, Select } from '@douyinfe/semi-ui';
import { IconFilter } from '@douyinfe/semi-icons';
import { ChevronDown } from 'lucide-react';
import { getLobeHubIcon } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
// 供应商 pill 折叠态的单行高度(px):pill 高约 38px,留 6px 余量。
// 超过该高度说明 pill 折行了,此时才显示「展开/收起」按钮
const COLLAPSED_ROW_HEIGHT = 44;
const FilterBar = ({
vendorsMap,
filterVendor,
setFilterVendor,
filterGroup,
setFilterGroup,
groupCountModels,
groupRatio,
autoGroups,
showRatio,
onOpenDrawer,
t,
models, // filtered models for counts
allModels = [], // 完整模型列表(未经筛选),用于判断供应商下是否有可用模型
}) => {
// 手机端不走「折叠一行 + 展开」这套:窄屏下 9 个供应商展开后是 5 行 pill 墙,
// 把首屏内容整个推下去。改为主流移动端做法——单行横向滚动 chip 条。
const isMobile = useIsMobile();
// 供应商较多时折为一行 + 展开按钮,避免长横向滚动难以浏览
const vendorRowRef = useRef(null);
const [vendorsExpanded, setVendorsExpanded] = useState(false);
const [vendorsOverflow, setVendorsOverflow] = useState(false);
// 供应商下没有任何可用模型时不展示该供应商(vendorsMap 返回的是全部供应商记录,
// 模型可能被等级策略/渠道下线剔除,须以实际模型列表为准)
const availableVendorNames = React.useMemo(() => {
const names = new Set();
(allModels || []).forEach((m) => {
if (m.vendor_name) names.add(m.vendor_name);
});
return names;
}, [allModels]);
// Prepare Vendor List
const vendorsList = Object.values(vendorsMap || {})
.filter((vendor) => availableVendorNames.has(vendor.name))
.sort((a, b) => a.name.localeCompare(b.name));
// 折叠态下把当前选中的供应商提到最前,避免选中 pill 折行到
// 被隐藏的第二行后用户看不到当前生效的筛选项;展开态保持字母序
// 手机端横向滚动条不做提序:点击后 chip 会跳到行首,手指下的元素位移,体感很糟
const selectedIdx =
!isMobile && !vendorsExpanded && filterVendor !== 'all'
? vendorsList.findIndex((v) => v.name === filterVendor)
: -1;
const displayVendors =
selectedIdx > 0
? [
vendorsList[selectedIdx],
...vendorsList.slice(0, selectedIdx),
...vendorsList.slice(selectedIdx + 1),
]
: vendorsList;
// 检测供应商 pill 是否折行(窗口尺寸/供应商列表变化时重新计算),
// 只有确实放不下一行时才渲染「展开」按钮。
// 依赖「显示顺序的名称串」而非 length:折叠态容器盒尺寸被 max-height 钳住,
// 内容变化(名称宽度、选中项提序导致的排布变化)不会触发 ResizeObserver,
// 需靠依赖项重算
const vendorNamesKey = displayVendors.map((v) => v.name).join('|');
useEffect(() => {
// 手机端是横向滚动,不存在折行,无需测高(也避免 max-height 钳制误判)
if (isMobile) {
setVendorsOverflow(false);
return;
}
const el = vendorRowRef.current;
if (!el) return;
const check = () =>
setVendorsOverflow(el.scrollHeight > COLLAPSED_ROW_HEIGHT + 4);
check();
const observer = new ResizeObserver(check);
observer.observe(el);
return () => observer.disconnect();
}, [vendorNamesKey, isMobile]);
// Prepare Groups for Select
const groupOptions = [
{ value: 'all', label: t('全部分组'), otherKey: 'View' },
...autoGroups.map((g) => ({ value: g, label: g, type: 'auto' })),
...Object.keys(groupRatio).map((g) => ({
value: g,
label: g,
type: 'custom',
})),
].filter((v, i, a) => a.findIndex((t) => t.value === v.value) === i); // Deduplicate
return (
// 吸顶位置必须让开固定顶栏:滚动容器从视口 y=0 开始,写 top-0 会让整条筛选栏
// (手机端是 flex-col,供应商横滑条在第一行)吸到顶栏底下被完全盖住,
// 用户得一路滚回页首才能碰到筛选。--app-header-height 由 PageLayout 发布,
// 已包含跑马灯高度。
<div
className='sticky z-40 w-full transition-all duration-300'
style={{ top: 'var(--app-header-height, 0px)' }}
>
{/* Glassmorphism background —— 中央高不透明保证 sticky 吸顶时 pill 可读,
* 两翼渐隐融入页面背景,消除宽屏下横贯全屏的生硬纯白色带 */}
<div className='absolute inset-0 backdrop-blur-xl bg-gradient-to-r from-white/30 via-white/80 to-white/30 dark:from-neutral-900/40 dark:via-neutral-900/85 dark:to-neutral-900/40' />
{/* 品牌色晕染层:两翼各一枚低透明度光斑 + 贯穿的极淡品牌渐变,
* 给横带罩上一层主题色氛围(全部 token 派生,随预设/暗色联动) */}
<div className='absolute inset-0 overflow-hidden pointer-events-none'>
<div className='absolute inset-0 bg-gradient-to-r from-brand-from/[0.07] via-transparent to-brand-to/[0.07]' />
<div className='absolute -left-12 -top-20 w-64 h-64 rounded-full bg-brand-from/10 dark:bg-brand-from/[0.08] blur-3xl' />
<div className='absolute -right-12 -top-20 w-64 h-64 rounded-full bg-brand-to/10 dark:bg-brand-to/[0.08] blur-3xl' />
</div>
{/* 上下发丝线:顶部极淡、底部稍强的品牌渐变,替代原来的灰色底边框 */}
<div className='absolute top-0 left-0 right-0 h-[1px] bg-gradient-to-r from-transparent via-brand-via/15 to-transparent' />
<div className='absolute bottom-0 left-0 right-0 h-[1px] bg-gradient-to-r from-transparent via-brand-via/35 to-transparent' />
<div className='relative container mx-auto px-4 md:px-6 py-3'>
<div className='flex flex-col md:flex-row items-center justify-between gap-3 md:gap-4'>
{/* Left: Vendor pills —— 桌面端折叠为一行可展开;手机端单行横向滚动 */}
<div className='flex-1 w-full md:w-auto flex items-start gap-2 min-w-0'>
<div
ref={vendorRowRef}
className={
isMobile
? // 负外边距让 chip 条通栏,右侧被裁的半个 chip 就是「可横滑」的视觉提示;
// scroll-snap 让手指松开后停在 chip 边界而不是半个字上
'flex-1 min-w-0 flex flex-nowrap items-center gap-2 overflow-x-auto scrollbar-hide snap-x scroll-pl-4 -mx-4 px-4 py-0.5 overscroll-x-contain'
: 'flex-1 flex flex-wrap items-center gap-2 overflow-hidden transition-[max-height] duration-300'
}
style={
isMobile
? undefined
: {
// 展开上限只为 max-height 过渡动画服务,取一个大到不会截断真实内容的值
// (~1500px 约可容纳 30+ 行 pill;超出属极端配置,此时下方内容仍可正常滚动)
maxHeight: vendorsExpanded
? '1500px'
: `${COLLAPSED_ROW_HEIGHT}px`,
}
}
>
{/* All Vendors Button */}
<button
onClick={() => setFilterVendor('all')}
className={`
flex-shrink-0 snap-start rounded-full font-semibold
px-3 py-1.5 text-[13px] md:px-4 md:py-2 md:text-sm
transition-all duration-300 transform md:hover:scale-105
${
filterVendor === 'all'
? 'bg-gradient-to-r from-brand-from via-brand-via to-brand-to text-white shadow-lg shadow-brand/25'
: 'bg-gray-100/80 dark:bg-neutral-800/80 text-gray-600 dark:text-gray-300 hover:bg-gray-200/80 dark:hover:bg-neutral-700/80 border border-gray-200/50 dark:border-neutral-700/50'
}
`}
>
{t('全部供应商')}
{vendorsList.length > 0 && (
<span
className={`ml-1.5 text-xs font-mono ${
filterVendor === 'all'
? 'text-white/80'
: 'text-gray-400 dark:text-neutral-500'
}`}
>
{vendorsList.length}
</span>
)}
</button>
{displayVendors.map((vendor) => {
const isActive = filterVendor === vendor.name;
return (
<button
key={vendor.id}
onClick={() => setFilterVendor(vendor.name)}
className={`
flex-shrink-0 snap-start flex items-center rounded-full font-medium
gap-1.5 px-3 py-1.5 text-[13px] md:gap-2 md:px-4 md:py-2 md:text-sm
transition-all duration-300 transform md:hover:scale-105 border
${
isActive
? 'border-brand-from bg-brand/5 dark:bg-brand-deep/30 text-brand-deep dark:text-brand-from shadow-md shadow-brand/10'
: 'border-gray-200/50 dark:border-neutral-700/50 bg-gray-100/80 dark:bg-neutral-800/80 text-gray-600 dark:text-gray-300 hover:bg-gray-200/80 dark:hover:bg-neutral-700/80 hover:border-gray-300 dark:hover:border-neutral-600'
}
`}
>
{vendor.icon && (
<div className='w-4 h-4 flex items-center justify-center transition-transform group-hover:scale-110'>
{getLobeHubIcon(vendor.icon, 16)}
</div>
)}
<span className='whitespace-nowrap'>{vendor.name}</span>
</button>
);
})}
</div>
{/* 展开/收起按钮 —— 仅桌面端、且 pill 确实折行(供应商较多)时出现 */}
{!isMobile && (vendorsOverflow || vendorsExpanded) && (
<button
onClick={() => setVendorsExpanded((v) => !v)}
className='flex-shrink-0 flex items-center gap-1 px-3 py-2 rounded-full text-sm font-medium border border-dashed border-gray-300 dark:border-neutral-600 text-gray-500 dark:text-gray-400 hover:text-brand-deep dark:hover:text-brand-from hover:border-brand-from/60 hover:bg-brand/5 dark:hover:bg-brand-deep/20 transition-all duration-300'
title={vendorsExpanded ? t('收起') : t('展开')}
>
<span>{vendorsExpanded ? t('收起') : t('展开')}</span>
<ChevronDown
size={14}
className={`transition-transform duration-300 ${
vendorsExpanded ? 'rotate-180' : ''
}`}
/>
</button>
)}
</div>
{/* Right: Group Selector & Advanced Filter */}
<div className='flex items-center gap-2 md:gap-3 flex-shrink-0 w-full md:w-auto'>
{/* Group Selector with glassmorphism —— 手机端与「更多」平分一行,撑满可用宽度 */}
<div className='flex flex-1 md:flex-none items-center gap-2 min-w-0 bg-gray-100/80 dark:bg-neutral-800/80 backdrop-blur-sm rounded-xl p-1.5 border border-gray-200/50 dark:border-neutral-700/50'>
<span className='text-xs font-bold text-gray-500 dark:text-gray-400 pl-2 uppercase hidden sm:block tracking-wider'>
{t('分组')}
</span>
<Select
value={filterGroup}
onChange={setFilterGroup}
style={{
width: isMobile ? '100%' : 150,
border: 'none',
backgroundColor: 'transparent',
}}
dropdownClassName='dark:bg-neutral-800 backdrop-blur-xl'
size='small'
optionList={groupOptions.map((g) => ({
value: g.value,
label: (
<div className='flex justify-between items-center w-full'>
<span className='font-medium'>{g.label}</span>
{showRatio && groupRatio[g.value] && (
<span className='text-brand dark:text-brand-from text-xs font-mono ml-2 bg-brand/5 dark:bg-brand-deep/30 px-1.5 py-0.5 rounded'>
x{groupRatio[g.value]}
</span>
)}
</div>
),
}))}
/>
</div>
{/* Divider */}
<div className='w-px h-6 bg-gradient-to-b from-transparent via-gray-300 dark:via-neutral-600 to-transparent hidden md:block' />
{/* Filter Drawer Trigger with gradient hover */}
<Button
icon={<IconFilter />}
theme='solid'
type='tertiary'
className='!flex-shrink-0 !bg-gray-100/80 dark:!bg-neutral-800/80 !text-gray-700 dark:!text-gray-200 hover:!bg-gradient-to-r hover:!from-brand-from hover:!via-brand-via hover:!to-brand-to hover:!text-white !border !border-gray-200/50 dark:!border-neutral-700/50 hover:!border-transparent !transition-all !duration-300 !rounded-xl'
onClick={onOpenDrawer}
>
{t('更多')}
</Button>
</div>
</div>
</div>
</div>
);
};
export default FilterBar;
@@ -0,0 +1,239 @@
/*
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 { SideSheet, Button } from '@douyinfe/semi-ui';
import {
Filter,
Users,
CreditCard,
Tag,
Layers,
X,
Sparkles,
} from 'lucide-react';
import PricingTags from '../filter/PricingTags';
import PricingQuotaTypes from '../filter/PricingQuotaTypes';
import PricingEndpointTypes from '../filter/PricingEndpointTypes';
import PricingGroups from '../filter/PricingGroups';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const FilterDrawer = ({
visible,
onClose,
t,
filterTag,
setFilterTag,
filterQuotaType,
setFilterQuotaType,
filterEndpointType,
setFilterEndpointType,
filterGroup,
setFilterGroup,
autoGroups,
usableGroup = {},
endpointMap,
groupRatio,
showRatio = true,
allModels,
tagModels,
quotaTypeModels,
endpointTypeModels,
groupCountModels,
}) => {
// 380px 在 390px 视口上只剩一条 10px 缝,既不好看也点不中遮罩关闭,手机端直接铺满
const isMobile = useIsMobile();
return (
<SideSheet
title={null}
headerStyle={{ display: 'none' }}
visible={visible}
onCancel={onClose}
width={isMobile ? '100%' : 380}
maskStyle={{
backgroundColor: 'rgba(0, 0, 0, 0.5)',
backdropFilter: 'blur(4px)',
}}
bodyStyle={{
padding: '0',
background: 'var(--semi-color-bg-0)',
}}
disableScroll={false}
>
{/* 自定义头部 */}
<div className='relative bg-white dark:bg-neutral-900'>
{/* 顶部装饰线 */}
<div className='absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-brand-from via-brand-via to-brand-to' />
{/* 头部内容 */}
<div className='relative px-6 py-5 pt-6'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-3'>
<div className='relative'>
<div className='absolute -inset-1 bg-gradient-to-br from-brand-from/40 to-brand-to/40 rounded-xl blur-md' />
<div className='relative p-2.5 bg-gradient-to-br from-brand-from to-brand-to rounded-xl shadow-lg'>
<Filter size={20} className='text-white' />
</div>
<Sparkles
size={12}
className='absolute -top-1 -right-1 text-brand-via'
/>
</div>
<div>
<h2 className='text-lg font-bold bg-clip-text text-transparent bg-gradient-to-r from-brand-from to-brand-to dark:from-brand-from dark:to-brand-to'>
{t('显示设置')}
</h2>
<p className='text-xs text-gray-500 dark:text-gray-400 mt-0.5'>
{t('筛选并精确查找模型')}
</p>
</div>
</div>
{/* 关闭按钮 */}
<button
onClick={onClose}
className='p-2 rounded-xl bg-gray-100/80 hover:bg-gray-200/80 dark:bg-neutral-800/80 dark:hover:bg-neutral-700/80 transition-all duration-200 hover:scale-105 group'
>
<X
size={18}
className='text-gray-500 group-hover:text-gray-700 dark:text-gray-400 dark:group-hover:text-gray-200'
/>
</button>
</div>
</div>
</div>
{/* 分隔线 */}
<div className='h-px bg-gradient-to-r from-transparent via-brand-via/20 dark:via-brand-via to-transparent mx-4' />
{/* 筛选内容 —— 分区卡片:单一标题行(内置组件标题传 null 隐藏,避免双标题)、
* 浅色品牌 chip 替代整列实色渐变块,视觉更克制(云控制台惯例) */}
<div className='flex-1 overflow-y-auto px-5 py-5 bg-gray-50 dark:bg-neutral-900 app-scrollbar'>
<div className='space-y-3'>
{/* 用户分组 */}
<section className='bg-white dark:bg-neutral-900 rounded-xl px-4 pt-3 pb-2 border border-gray-100 dark:border-neutral-800 shadow-sm [&>*:last-child]:!mb-0'>
<div className='flex items-center gap-2 mb-2.5'>
<div className='w-7 h-7 rounded-lg bg-brand/10 dark:bg-brand-deep/30 flex items-center justify-center'>
<Users
size={14}
className='text-brand-deep dark:text-brand-from'
/>
</div>
<h3 className='text-sm font-semibold text-gray-800 dark:text-gray-200'>
{t('用户分组')}
</h3>
</div>
<PricingGroups
filterGroup={filterGroup}
setFilterGroup={setFilterGroup}
groupRatio={groupRatio}
usableGroup={usableGroup}
showRatio={showRatio}
t={t}
models={groupCountModels}
title={null}
/>
</section>
{/* 计费类型 */}
<section className='bg-white dark:bg-neutral-900 rounded-xl px-4 pt-3 pb-2 border border-gray-100 dark:border-neutral-800 shadow-sm [&>*:last-child]:!mb-0'>
<div className='flex items-center gap-2 mb-2.5'>
<div className='w-7 h-7 rounded-lg bg-brand/10 dark:bg-brand-deep/30 flex items-center justify-center'>
<CreditCard
size={14}
className='text-brand-deep dark:text-brand-from'
/>
</div>
<h3 className='text-sm font-semibold text-gray-800 dark:text-gray-200'>
{t('计费类型')}
</h3>
</div>
<PricingQuotaTypes
filterQuotaType={filterQuotaType}
setFilterQuotaType={setFilterQuotaType}
t={t}
models={quotaTypeModels}
title={null}
/>
</section>
{/* 标签 */}
<section className='bg-white dark:bg-neutral-900 rounded-xl px-4 pt-3 pb-2 border border-gray-100 dark:border-neutral-800 shadow-sm [&>*:last-child]:!mb-0'>
<div className='flex items-center gap-2 mb-2.5'>
<div className='w-7 h-7 rounded-lg bg-brand/10 dark:bg-brand-deep/30 flex items-center justify-center'>
<Tag
size={14}
className='text-brand-deep dark:text-brand-from'
/>
</div>
<h3 className='text-sm font-semibold text-gray-800 dark:text-gray-200'>
{t('标签')}
</h3>
</div>
<PricingTags
filterTag={filterTag}
setFilterTag={setFilterTag}
t={t}
models={tagModels}
allModels={allModels}
title={null}
/>
</section>
{/* 端点类型 */}
<section className='bg-white dark:bg-neutral-900 rounded-xl px-4 pt-3 pb-2 border border-gray-100 dark:border-neutral-800 shadow-sm [&>*:last-child]:!mb-0'>
<div className='flex items-center gap-2 mb-2.5'>
<div className='w-7 h-7 rounded-lg bg-brand/10 dark:bg-brand-deep/30 flex items-center justify-center'>
<Layers
size={14}
className='text-brand-deep dark:text-brand-from'
/>
</div>
<h3 className='text-sm font-semibold text-gray-800 dark:text-gray-200'>
{t('端点类型')}
</h3>
</div>
<PricingEndpointTypes
filterEndpointType={filterEndpointType}
setFilterEndpointType={setFilterEndpointType}
endpointMap={endpointMap}
t={t}
models={endpointTypeModels}
title={null}
/>
</section>
</div>
</div>
{/* 底部操作区 */}
<div className='p-4 bg-white dark:bg-neutral-900 border-t border-gray-200 dark:border-neutral-800'>
<Button
block
theme='solid'
onClick={onClose}
className='!bg-gradient-to-r !from-brand-from !to-brand-to hover:!from-brand-from hover:!to-brand-to !rounded-xl !h-11 !font-medium !shadow-lg !shadow-brand/20 hover:!shadow-brand/30 transition-all'
>
{t('完成')}
</Button>
</div>
</SideSheet>
);
};
export default FilterDrawer;
@@ -0,0 +1,242 @@
/*
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, { useState, useEffect, useRef } from 'react';
import { useModelPricingData } from '../../../../hooks/model-pricing/useModelPricingData';
import { usePricingFilterCounts } from '../../../../hooks/model-pricing/usePricingFilterCounts';
import BentoHero from './BentoHero';
import BentoGrid from './BentoGrid';
import FilterBar from './FilterBar';
import FilterDrawer from './FilterDrawer';
import ModelDetailSideSheet from '../modal/ModelDetailSideSheet';
import { ImagePreview } from '@douyinfe/semi-ui';
import PageBackground from '../../../common/PageBackground';
const PricingBentoPage = () => {
const pricingData = useModelPricingData();
const [showSettings, setShowSettings] = useState(false);
const pageRef = useRef(null);
// 为父级滚动容器 (.semi-layout) 添加自定义滚动条样式类
// 进入页面时添加,离开时移除
useEffect(() => {
const el = pageRef.current;
if (!el) return;
// 向上查找真正的滚动容器 (.semi-layout with overflow-y: auto)
let scrollParent = el.parentElement;
while (scrollParent) {
const style = window.getComputedStyle(scrollParent);
if (
scrollParent.classList.contains('semi-layout') &&
(style.overflowY === 'auto' || style.overflowY === 'scroll')
) {
break;
}
scrollParent = scrollParent.parentElement;
}
if (scrollParent) {
scrollParent.classList.add('pricing-page-scrollbar');
}
return () => {
if (scrollParent) {
scrollParent.classList.remove('pricing-page-scrollbar');
}
};
}, []);
// Destructure what we need
const {
searchValue,
setSearchValue,
filterVendor,
setFilterVendor,
filteredModels,
loading,
selectedGroup,
groupRatio,
groupModelDiscount,
discountScope,
tokenUnit,
displayPrice,
currency,
showRatio,
hidePrice,
t,
copyText,
openModelDetail,
// Filter props for drawer
filterTag,
setFilterTag,
filterQuotaType,
setFilterQuotaType,
filterEndpointType,
setFilterEndpointType,
filterGroup,
setFilterGroup,
autoGroups,
endpointMap,
vendorsMap,
// Modal props
showModelDetail,
closeModelDetail,
selectedModel,
usableGroup,
modalImageUrl,
isModalOpenurl,
setIsModalOpenurl,
models, // Full list
} = pricingData;
const { quotaTypeModels, endpointTypeModels, tagModels, groupCountModels } =
usePricingFilterCounts({
models: models,
filterGroup,
filterQuotaType,
filterEndpointType,
filterVendor,
filterTag,
searchValue,
});
return (
<div
ref={pageRef}
className='min-h-screen relative text-gray-900 dark:text-white selection:bg-brand/30 font-sans transition-colors duration-500'
>
{/* ===== BACKGROUND ===== */}
{/* 统一页面背景层 —— 与全站其他页面(user-center / experience / key-management)
* 同源,走 bg-glow-* 主题变量,跟随管理员「背景晕染起色/止色」配置。
* 用 fixed 包一层让背景随滚动固定(定价页内容很长)。 */}
<div className='fixed inset-0 -z-40 pointer-events-none'>
<PageBackground variant='rich' />
</div>
{/* ===== CONTENT ===== */}
{/* 1. Hero & Search */}
<BentoHero
searchValue={searchValue}
setSearchValue={setSearchValue}
t={t}
/>
{/* 2. Filter Bar (Sticky) */}
<FilterBar
vendorsMap={vendorsMap}
filterVendor={filterVendor}
setFilterVendor={setFilterVendor}
filterGroup={filterGroup}
setFilterGroup={setFilterGroup}
groupCountModels={groupCountModels}
groupRatio={groupRatio}
autoGroups={autoGroups}
showRatio={showRatio}
onOpenDrawer={() => setShowSettings(true)}
t={t}
models={filteredModels}
allModels={models}
/>
{/* 企业作用域计价口径提示:标价含企业等级折扣,个人密钥/体验中心调用仍按个人等级计费 */}
{discountScope === 'enterprise' && !hidePrice && (
<div className='container mx-auto px-6 pt-3'>
<div
className='rounded-xl border border-amber-200/70 dark:border-amber-700/50
bg-amber-50/80 dark:bg-amber-900/20 px-4 py-2 text-sm
text-amber-800 dark:text-amber-300'
>
{t(
'当前为企业作用域:以下价格已按企业等级折扣展示;使用个人密钥或体验中心调用时按个人等级计费。',
)}
</div>
</div>
)}
{/* 3. Main Content Grid */}
<BentoGrid
filteredModels={filteredModels}
loading={loading}
selectedGroup={selectedGroup}
groupRatio={groupRatio}
groupModelDiscount={groupModelDiscount}
tokenUnit={tokenUnit}
displayPrice={displayPrice}
currency={currency}
hidePrice={hidePrice}
t={t}
copyText={copyText}
openModelDetail={openModelDetail}
/>
{/* 4. Advanced Filters Drawer */}
<FilterDrawer
visible={showSettings}
onClose={() => setShowSettings(false)}
t={t}
filterTag={filterTag}
setFilterTag={setFilterTag}
filterQuotaType={filterQuotaType}
setFilterQuotaType={setFilterQuotaType}
filterEndpointType={filterEndpointType}
setFilterEndpointType={setFilterEndpointType}
filterGroup={filterGroup}
setFilterGroup={setFilterGroup}
autoGroups={autoGroups}
usableGroup={usableGroup}
endpointMap={endpointMap}
groupRatio={groupRatio}
showRatio={showRatio}
allModels={pricingData.models}
tagModels={tagModels}
quotaTypeModels={quotaTypeModels}
endpointTypeModels={endpointTypeModels}
groupCountModels={groupCountModels}
/>
{/* 5. Legacy Modals (Detail View & Image Preview) */}
<ModelDetailSideSheet
visible={showModelDetail}
onClose={closeModelDetail}
modelData={selectedModel}
groupRatio={groupRatio}
groupModelDiscount={groupModelDiscount}
usableGroup={usableGroup}
currency={currency}
tokenUnit={tokenUnit}
displayPrice={displayPrice}
showRatio={showRatio}
hidePrice={hidePrice}
vendorsMap={vendorsMap}
endpointMap={endpointMap}
autoGroups={autoGroups}
t={t}
/>
<ImagePreview
src={modalImageUrl}
visible={isModalOpenurl}
onVisibleChange={(visible) => setIsModalOpenurl(visible)}
/>
</div>
);
};
export default PricingBentoPage;
@@ -0,0 +1,107 @@
/*
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 SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
const PricingDisplaySettings = ({
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
showRatio,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
loading = false,
t,
}) => {
const items = [
{
value: 'recharge',
label: t('充值价格显示'),
},
{
value: 'tableView',
label: t('表格视图'),
},
{
value: 'tokenUnit',
label: t('按K显示单位'),
},
];
const currencyItems = [
{ value: 'USD', label: 'USD (¥)' },
{ value: 'CNY', label: 'CNY (¥)' },
{ value: 'CUSTOM', label: t('自定义货币') },
];
const handleChange = (value) => {
switch (value) {
case 'recharge':
setShowWithRecharge(!showWithRecharge);
break;
case 'tableView':
setViewMode(viewMode === 'table' ? 'card' : 'table');
break;
case 'tokenUnit':
setTokenUnit(tokenUnit === 'K' ? 'M' : 'K');
break;
}
};
const getActiveValues = () => {
const activeValues = [];
if (showWithRecharge) activeValues.push('recharge');
if (viewMode === 'table') activeValues.push('tableView');
if (tokenUnit === 'K') activeValues.push('tokenUnit');
return activeValues;
};
return (
<div>
<SelectableButtonGroup
title={t('显示设置')}
items={items}
activeValue={getActiveValues()}
onChange={handleChange}
withCheckbox
collapsible={false}
loading={loading}
t={t}
/>
{showWithRecharge && (
<SelectableButtonGroup
title={t('货币单位')}
items={currencyItems}
activeValue={currency}
onChange={setCurrency}
collapsible={false}
loading={loading}
t={t}
/>
)}
</div>
);
};
export default PricingDisplaySettings;
@@ -0,0 +1,106 @@
/*
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 SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
/**
* 端点类型筛选组件
* @param {string|'all'} filterEndpointType 当前值
* @param {Function} setFilterEndpointType setter
* @param {Array} models 模型列表
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingEndpointTypes = ({
filterEndpointType,
setFilterEndpointType,
models = [],
allModels = [],
loading = false,
t,
// 外层已有分区标题时传 null 隐藏内置标题(如 FilterDrawer),避免双标题
title,
}) => {
// 获取系统中所有端点类型(基于 allModels,如果未提供则退化为 models)
const getAllEndpointTypes = () => {
const endpointTypes = new Set();
(allModels.length > 0 ? allModels : models).forEach((model) => {
if (
model.supported_endpoint_types &&
Array.isArray(model.supported_endpoint_types)
) {
model.supported_endpoint_types.forEach((endpoint) => {
endpointTypes.add(endpoint);
});
}
});
return Array.from(endpointTypes).sort();
};
// 计算每个端点类型的模型数量
const getEndpointTypeCount = (endpointType) => {
if (endpointType === 'all') {
return models.length;
}
return models.filter(
(model) =>
model.supported_endpoint_types &&
model.supported_endpoint_types.includes(endpointType),
).length;
};
// 端点类型显示名称映射
const getEndpointTypeLabel = (endpointType) => {
return endpointType;
};
const availableEndpointTypes = getAllEndpointTypes();
const items = [
{
value: 'all',
label: t('全部端点'),
tagCount: getEndpointTypeCount('all'),
disabled: models.length === 0,
},
...availableEndpointTypes.map((endpointType) => {
const count = getEndpointTypeCount(endpointType);
return {
value: endpointType,
label: getEndpointTypeLabel(endpointType),
tagCount: count,
disabled: count === 0,
};
}),
];
return (
<SelectableButtonGroup
title={title === undefined ? t('端点类型') : title}
items={items}
activeValue={filterEndpointType}
onChange={setFilterEndpointType}
loading={loading}
t={t}
/>
);
};
export default PricingEndpointTypes;
@@ -0,0 +1,92 @@
/*
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 SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
/**
* 分组筛选组件
* @param {string} filterGroup 当前选中的分组,'all' 表示不过滤
* @param {Function} setFilterGroup 设置选中分组
* @param {Record<string, any>} usableGroup 后端返回的可用分组对象
* @param {Record<string, number>} groupRatio 分组倍率对象
* @param {Array} models 模型列表
* @param {boolean} loading 是否加载中
* @param {boolean} showRatio 是否显示倍率
* @param {Function} t i18n
*/
const PricingGroups = ({
filterGroup,
setFilterGroup,
usableGroup = {},
groupRatio = {},
models = [],
loading = false,
showRatio = true,
t,
// 外层已有分区标题时传 null 隐藏内置标题(如 FilterDrawer),避免双标题
title,
}) => {
const groups = [
'all',
...Object.keys(usableGroup).filter((key) => key !== ''),
];
const items = groups.map((g) => {
const modelCount =
g === 'all'
? models.length
: models.filter((m) => m.enable_groups && m.enable_groups.includes(g))
.length;
let ratioDisplay = '';
if (g === 'all') {
ratioDisplay = t('全部');
} else if (showRatio) {
// 只在 showRatio 为 true 时显示倍率
const ratio = groupRatio[g];
if (ratio !== undefined && ratio !== null) {
ratioDisplay = `x${ratio}`;
} else {
ratioDisplay = 'x1';
}
} else {
// showRatio 为 false 时显示模型数量
ratioDisplay = `${modelCount}`;
}
return {
value: g,
label: g === 'all' ? t('全部分组') : g,
tagCount: ratioDisplay,
disabled: modelCount === 0,
};
});
return (
<SelectableButtonGroup
title={title === undefined ? t('可用令牌分组') : title}
items={items}
activeValue={filterGroup}
onChange={setFilterGroup}
loading={loading}
t={t}
/>
);
};
export default PricingGroups;
@@ -0,0 +1,64 @@
/*
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 SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
/**
* 计费类型筛选组件
* @param {string|'all'|0|1|2|3} filterQuotaType 当前值
* @param {Function} setFilterQuotaType setter
* @param {Array} models 模型列表
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingQuotaTypes = ({
filterQuotaType,
setFilterQuotaType,
models = [],
loading = false,
t,
// 外层已有分区标题时传 null 隐藏内置标题(如 FilterDrawer),避免双标题
title,
}) => {
const qtyCount = (type) =>
models.filter((m) => (type === 'all' ? true : m.quota_type === type))
.length;
const items = [
{ value: 'all', label: t('全部类型'), tagCount: qtyCount('all') },
{ value: 0, label: t('按量计费'), tagCount: qtyCount(0) },
{ value: 1, label: t('按次计费'), tagCount: qtyCount(1) },
{ value: 2, label: t('按秒计费'), tagCount: qtyCount(2) },
{ value: 3, label: t('按分辨率计费'), tagCount: qtyCount(3) },
];
return (
<SelectableButtonGroup
title={title === undefined ? t('计费类型') : title}
items={items}
activeValue={filterQuotaType}
onChange={setFilterQuotaType}
loading={loading}
t={t}
/>
);
};
export default PricingQuotaTypes;
@@ -0,0 +1,112 @@
/*
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 SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
/**
* 模型标签筛选组件
* @param {string|'all'} filterTag 当前选中的标签
* @param {Function} setFilterTag setter
* @param {Array} models 当前过滤后模型列表(用于计数)
* @param {Array} allModels 所有模型列表(用于获取所有标签)
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingTags = ({
filterTag,
setFilterTag,
models = [],
allModels = [],
loading = false,
t,
// 外层已有分区标题时传 null 隐藏内置标题(如 FilterDrawer),避免双标题
title,
}) => {
// 提取系统所有标签
const getAllTags = React.useMemo(() => {
const tagSet = new Set();
(allModels.length > 0 ? allModels : models).forEach((model) => {
if (model.tags) {
model.tags
.split(/[,;|]+/) // 逗号、分号或竖线(保留空格,允许多词标签如 "open weights")
.map((tag) => tag.trim())
.filter(Boolean)
.forEach((tag) => tagSet.add(tag.toLowerCase()));
}
});
return Array.from(tagSet).sort((a, b) => a.localeCompare(b));
}, [allModels, models]);
// 计算标签对应的模型数量
const getTagCount = React.useCallback(
(tag) => {
if (tag === 'all') return models.length;
const tagLower = tag.toLowerCase();
return models.filter((model) => {
if (!model.tags) return false;
return model.tags
.toLowerCase()
.split(/[,;|]+/)
.map((tg) => tg.trim())
.includes(tagLower);
}).length;
},
[models],
);
const items = React.useMemo(() => {
const result = [
{
value: 'all',
label: t('全部标签'),
tagCount: getTagCount('all'),
disabled: models.length === 0,
},
];
getAllTags.forEach((tag) => {
const count = getTagCount(tag);
result.push({
value: tag,
label: tag,
tagCount: count,
disabled: count === 0,
});
});
return result;
}, [getAllTags, getTagCount, t, models.length]);
return (
<SelectableButtonGroup
title={title === undefined ? t('标签') : title}
items={items}
activeValue={filterTag}
onChange={setFilterTag}
loading={loading}
t={t}
/>
);
};
export default PricingTags;
@@ -0,0 +1,129 @@
/*
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 SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
import { getLobeHubIcon } from '../../../../helpers';
/**
* 供应商筛选组件
* @param {string|'all'} filterVendor 当前值
* @param {Function} setFilterVendor setter
* @param {Array} models 模型列表
* @param {Array} allModels 所有模型列表(用于获取全部供应商)
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingVendors = ({
filterVendor,
setFilterVendor,
models = [],
allModels = [],
loading = false,
t,
}) => {
// 获取系统中所有供应商(基于 allModels,如果未提供则退化为 models)
const getAllVendors = React.useMemo(() => {
const vendors = new Set();
const vendorIcons = new Map();
let hasUnknownVendor = false;
(allModels.length > 0 ? allModels : models).forEach((model) => {
if (model.vendor_name) {
vendors.add(model.vendor_name);
if (model.vendor_icon && !vendorIcons.has(model.vendor_name)) {
vendorIcons.set(model.vendor_name, model.vendor_icon);
}
} else {
hasUnknownVendor = true;
}
});
return {
vendors: Array.from(vendors).sort(),
vendorIcons,
hasUnknownVendor,
};
}, [allModels, models]);
// 计算每个供应商的模型数量(基于当前过滤后的 models)
const getVendorCount = React.useCallback(
(vendor) => {
if (vendor === 'all') {
return models.length;
}
if (vendor === 'unknown') {
return models.filter((model) => !model.vendor_name).length;
}
return models.filter((model) => model.vendor_name === vendor).length;
},
[models],
);
// 生成供应商选项
const items = React.useMemo(() => {
const result = [
{
value: 'all',
label: t('全部供应商'),
tagCount: getVendorCount('all'),
disabled: models.length === 0,
},
];
// 添加所有已知供应商
getAllVendors.vendors.forEach((vendor) => {
const count = getVendorCount(vendor);
const icon = getAllVendors.vendorIcons.get(vendor);
result.push({
value: vendor,
label: vendor,
icon: icon ? getLobeHubIcon(icon, 16) : null,
tagCount: count,
disabled: count === 0,
});
});
// 如果系统中存在未知供应商,添加"未知供应商"选项
if (getAllVendors.hasUnknownVendor) {
const count = getVendorCount('unknown');
result.push({
value: 'unknown',
label: t('未知供应商'),
tagCount: count,
disabled: count === 0,
});
}
return result;
}, [getAllVendors, getVendorCount, t]);
return (
<SelectableButtonGroup
title={t('供应商')}
items={items}
activeValue={filterVendor}
onChange={setFilterVendor}
loading={loading}
t={t}
/>
);
};
export default PricingVendors;
@@ -0,0 +1,27 @@
/*
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 PricingBentoPage from '../bento/PricingBentoPage';
const PricingPage = () => {
return <PricingBentoPage />;
};
export default PricingPage;
@@ -0,0 +1,143 @@
/*
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 } from '@douyinfe/semi-ui';
import PricingGroups from '../filter/PricingGroups';
import PricingQuotaTypes from '../filter/PricingQuotaTypes';
import PricingVendors from '../filter/PricingVendors';
import PricingTags from '../filter/PricingTags';
import { resetPricingFilters } from '../../../../helpers/utils';
import { usePricingFilterCounts } from '../../../../hooks/model-pricing/usePricingFilterCounts';
const PricingSidebar = ({
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
handleChange,
setActiveKey,
showRatio,
viewMode,
setViewMode,
filterGroup,
setFilterGroup,
handleGroupClick,
filterQuotaType,
setFilterQuotaType,
filterEndpointType,
setFilterEndpointType,
filterVendor,
setFilterVendor,
filterTag,
setFilterTag,
currentPage,
setCurrentPage,
tokenUnit,
setTokenUnit,
loading,
t,
...categoryProps
}) => {
const {
quotaTypeModels,
vendorModels,
tagModels,
groupCountModels,
} = usePricingFilterCounts({
models: categoryProps.models,
filterGroup,
filterQuotaType,
filterEndpointType,
filterVendor,
filterTag,
searchValue: categoryProps.searchValue,
});
const handleResetFilters = () =>
resetPricingFilters({
handleChange,
setShowWithRecharge,
setCurrency,
setViewMode,
setFilterGroup,
setFilterQuotaType,
setFilterEndpointType,
setFilterVendor,
setFilterTag,
setCurrentPage,
setTokenUnit,
});
return (
<div className='p-2'>
<div className='flex items-center justify-between mb-6'>
<div className='text-lg font-semibold text-gray-800'>{t('筛选')}</div>
<Button
theme='outline'
type='tertiary'
onClick={handleResetFilters}
className='text-gray-500 hover:text-gray-700'
>
{t('重置')}
</Button>
</div>
<PricingVendors
filterVendor={filterVendor}
setFilterVendor={setFilterVendor}
models={vendorModels}
allModels={categoryProps.models}
loading={loading}
t={t}
/>
<PricingTags
filterTag={filterTag}
setFilterTag={setFilterTag}
models={tagModels}
allModels={categoryProps.models}
loading={loading}
t={t}
/>
<PricingGroups
filterGroup={filterGroup}
setFilterGroup={handleGroupClick}
usableGroup={categoryProps.usableGroup}
groupRatio={categoryProps.groupRatio}
models={groupCountModels}
loading={loading}
showRatio={showRatio}
t={t}
/>
<PricingQuotaTypes
filterQuotaType={filterQuotaType}
setFilterQuotaType={setFilterQuotaType}
models={quotaTypeModels}
loading={loading}
t={t}
/>
</div>
);
};
export default PricingSidebar;
@@ -0,0 +1,59 @@
/*
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 PricingTopSection from '../header/PricingTopSection';
import PricingView from './PricingView';
const PricingContent = ({ isMobile, sidebarProps, ...props }) => {
return (
<div
className={isMobile ? 'pricing-content-mobile' : 'pricing-scroll-hide'}
>
{/* 固定的顶部区域(分类介绍 + 搜索和操作) */}
<div className='pricing-search-header'>
<PricingTopSection
{...props}
isMobile={isMobile}
sidebarProps={sidebarProps}
showWithRecharge={sidebarProps.showWithRecharge}
setShowWithRecharge={sidebarProps.setShowWithRecharge}
currency={sidebarProps.currency}
setCurrency={sidebarProps.setCurrency}
showRatio={sidebarProps.showRatio}
viewMode={sidebarProps.viewMode}
setViewMode={sidebarProps.setViewMode}
tokenUnit={sidebarProps.tokenUnit}
setTokenUnit={sidebarProps.setTokenUnit}
/>
</div>
{/* 可滚动的内容区域 */}
<div
className={
isMobile ? 'pricing-view-container-mobile' : 'pricing-view-container'
}
>
<PricingView {...props} viewMode={sidebarProps.viewMode} />
</div>
</div>
);
};
export default PricingContent;
@@ -0,0 +1,32 @@
/*
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 PricingTable from '../../view/table/PricingTable';
import PricingCardView from '../../view/card/PricingCardView';
const PricingView = ({ viewMode = 'table', ...props }) => {
return viewMode === 'card' ? (
<PricingCardView {...props} />
) : (
<PricingTable {...props} />
);
};
export default PricingView;
@@ -0,0 +1,115 @@
/*
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, { useState, memo } from 'react';
import PricingFilterModal from '../../modal/PricingFilterModal';
import PricingVendorIntroWithSkeleton from './PricingVendorIntroWithSkeleton';
import SearchActions from './SearchActions';
const PricingTopSection = memo(
({
selectedRowKeys,
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile,
sidebarProps,
filterVendor,
models,
filteredModels,
loading,
searchValue,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
t,
}) => {
const [showFilterModal, setShowFilterModal] = useState(false);
return (
<>
{isMobile ? (
<>
<div className='w-full'>
<SearchActions
selectedRowKeys={selectedRowKeys}
copyText={copyText}
handleChange={handleChange}
handleCompositionStart={handleCompositionStart}
handleCompositionEnd={handleCompositionEnd}
isMobile={isMobile}
searchValue={searchValue}
setShowFilterModal={setShowFilterModal}
showWithRecharge={showWithRecharge}
setShowWithRecharge={setShowWithRecharge}
currency={currency}
setCurrency={setCurrency}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
t={t}
/>
</div>
<PricingFilterModal
visible={showFilterModal}
onClose={() => setShowFilterModal(false)}
sidebarProps={sidebarProps}
t={t}
/>
</>
) : (
<PricingVendorIntroWithSkeleton
loading={loading}
filterVendor={filterVendor}
models={filteredModels}
allModels={models}
t={t}
selectedRowKeys={selectedRowKeys}
copyText={copyText}
handleChange={handleChange}
handleCompositionStart={handleCompositionStart}
handleCompositionEnd={handleCompositionEnd}
isMobile={isMobile}
searchValue={searchValue}
setShowFilterModal={setShowFilterModal}
showWithRecharge={showWithRecharge}
setShowWithRecharge={setShowWithRecharge}
currency={currency}
setCurrency={setCurrency}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
/>
)}
</>
);
},
);
PricingTopSection.displayName = 'PricingTopSection';
export default PricingTopSection;
@@ -0,0 +1,413 @@
/*
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, { useState, useEffect, useMemo, useCallback, memo } from 'react';
import {
Card,
Tag,
Avatar,
Typography,
Tooltip,
Modal,
} from '@douyinfe/semi-ui';
import { getLobeHubIcon } from '../../../../../helpers';
import SearchActions from './SearchActions';
const { Paragraph } = Typography;
const CONFIG = {
CAROUSEL_INTERVAL: 2000,
ICON_SIZE: 40,
UNKNOWN_VENDOR: 'unknown',
};
const THEME_COLORS = {
allVendors: {
primary: '37 99 235',
background: 'rgba(59, 130, 246, 0.08)',
},
specific: {
primary: '16 185 129',
background: 'rgba(16, 185, 129, 0.1)',
},
};
const COMPONENT_STYLES = {
tag: {
backgroundColor: 'rgba(255,255,255,0.95)',
color: '#1f2937',
border: '1px solid rgba(255,255,255,0.8)',
fontWeight: '500',
},
avatarContainer:
'w-16 h-16 rounded-2xl bg-white/90 shadow-md backdrop-blur-sm flex items-center justify-center',
titleText: { color: 'white' },
descriptionText: { color: 'rgba(255,255,255,0.9)' },
};
const CONTENT_TEXTS = {
unknown: {
displayName: (t) => t('未知供应商'),
description: (t) =>
t(
'包含来自未知或未标明供应商的AI模型,这些模型可能来自小型供应商或开源项目。',
),
},
all: {
description: (t) =>
t('查看所有可用的AI模型供应商,包括众多知名供应商的模型。'),
},
fallback: {
description: (t) => t('该供应商提供多种AI模型,适用于不同的应用场景。'),
},
};
const getVendorDisplayName = (vendorName, t) => {
return vendorName === CONFIG.UNKNOWN_VENDOR
? CONTENT_TEXTS.unknown.displayName(t)
: vendorName;
};
const createDefaultAvatar = () => (
<div className={COMPONENT_STYLES.avatarContainer}>
<Avatar size='large' color='transparent'>
AI
</Avatar>
</div>
);
const getAvatarBackgroundColor = (isAllVendors) =>
isAllVendors
? THEME_COLORS.allVendors.background
: THEME_COLORS.specific.background;
const getAvatarText = (vendorName) =>
vendorName === CONFIG.UNKNOWN_VENDOR
? '?'
: vendorName.charAt(0).toUpperCase();
const createAvatarContent = (vendor, isAllVendors) => {
if (vendor.icon) {
return getLobeHubIcon(vendor.icon, CONFIG.ICON_SIZE);
}
return (
<Avatar
size='large'
style={{ backgroundColor: getAvatarBackgroundColor(isAllVendors) }}
>
{getAvatarText(vendor.name)}
</Avatar>
);
};
const renderVendorAvatar = (vendor, t, isAllVendors = false) => {
if (!vendor) {
return createDefaultAvatar();
}
const displayName = getVendorDisplayName(vendor.name, t);
const avatarContent = createAvatarContent(vendor, isAllVendors);
return (
<Tooltip content={displayName} position='top'>
<div className={COMPONENT_STYLES.avatarContainer}>{avatarContent}</div>
</Tooltip>
);
};
const PricingVendorIntro = memo(
({
filterVendor,
models = [],
allModels = [],
t,
selectedRowKeys = [],
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile = false,
searchValue = '',
setShowFilterModal,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
}) => {
const [currentOffset, setCurrentOffset] = useState(0);
const [descModalVisible, setDescModalVisible] = useState(false);
const [descModalContent, setDescModalContent] = useState('');
const handleOpenDescModal = useCallback((content) => {
setDescModalContent(content || '');
setDescModalVisible(true);
}, []);
const handleCloseDescModal = useCallback(() => {
setDescModalVisible(false);
}, []);
const renderDescriptionModal = useCallback(
() => (
<Modal
title={t('供应商介绍')}
visible={descModalVisible}
onCancel={handleCloseDescModal}
footer={null}
width={isMobile ? '95%' : 600}
bodyStyle={{
maxHeight: isMobile ? '70vh' : '60vh',
overflowY: 'auto',
}}
>
<div className='text-sm mb-4'>{descModalContent}</div>
</Modal>
),
[descModalVisible, descModalContent, handleCloseDescModal, isMobile, t],
);
const vendorInfo = useMemo(() => {
const vendors = new Map();
let unknownCount = 0;
const sourceModels =
Array.isArray(allModels) && allModels.length > 0 ? allModels : models;
sourceModels.forEach((model) => {
if (model.vendor_name) {
const existing = vendors.get(model.vendor_name);
if (existing) {
existing.count++;
} else {
vendors.set(model.vendor_name, {
name: model.vendor_name,
icon: model.vendor_icon,
description: model.vendor_description,
count: 1,
});
}
} else {
unknownCount++;
}
});
const vendorList = Array.from(vendors.values()).sort((a, b) =>
a.name.localeCompare(b.name),
);
if (unknownCount > 0) {
vendorList.push({
name: CONFIG.UNKNOWN_VENDOR,
icon: null,
description: CONTENT_TEXTS.unknown.description(t),
count: unknownCount,
});
}
return vendorList;
}, [allModels, models, t]);
const currentModelCount = models.length;
useEffect(() => {
if (filterVendor !== 'all' || vendorInfo.length <= 1) {
setCurrentOffset(0);
return;
}
const interval = setInterval(() => {
setCurrentOffset((prev) => (prev + 1) % vendorInfo.length);
}, CONFIG.CAROUSEL_INTERVAL);
return () => clearInterval(interval);
}, [filterVendor, vendorInfo.length]);
const getVendorDescription = useCallback(
(vendorKey) => {
if (vendorKey === 'all') {
return CONTENT_TEXTS.all.description(t);
}
if (vendorKey === CONFIG.UNKNOWN_VENDOR) {
return CONTENT_TEXTS.unknown.description(t);
}
const vendor = vendorInfo.find((v) => v.name === vendorKey);
return vendor?.description || CONTENT_TEXTS.fallback.description(t);
},
[vendorInfo, t],
);
const createCoverStyle = useCallback(
(primaryColor) => ({
'--palette-primary-darkerChannel': primaryColor,
backgroundImage: `linear-gradient(0deg, rgba(var(--palette-primary-darkerChannel) / 80%), rgba(var(--palette-primary-darkerChannel) / 80%)), url('/cover-4.webp')`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
}),
[],
);
const renderSearchActions = useCallback(
() => (
<SearchActions
selectedRowKeys={selectedRowKeys}
copyText={copyText}
handleChange={handleChange}
handleCompositionStart={handleCompositionStart}
handleCompositionEnd={handleCompositionEnd}
isMobile={isMobile}
searchValue={searchValue}
setShowFilterModal={setShowFilterModal}
showWithRecharge={showWithRecharge}
setShowWithRecharge={setShowWithRecharge}
currency={currency}
setCurrency={setCurrency}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
t={t}
/>
),
[
selectedRowKeys,
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile,
searchValue,
setShowFilterModal,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
t,
],
);
const renderHeaderCard = useCallback(
({ title, count, description, rightContent, primaryDarkerChannel }) => (
<Card
className='!rounded-2xl shadow-sm border-0'
cover={
<div
className='relative h-full'
style={createCoverStyle(primaryDarkerChannel)}
>
<div className='relative z-10 h-full flex items-center justify-between p-4'>
<div className='flex-1 min-w-0 mr-4'>
<div className='flex flex-row flex-wrap items-center gap-2 sm:gap-3 mb-2'>
<h2
className='text-lg sm:text-xl font-bold truncate'
style={COMPONENT_STYLES.titleText}
>
{title}
</h2>
<Tag
style={COMPONENT_STYLES.tag}
shape='circle'
size='small'
className='self-center'
>
{t('共 {{count}} 个模型', { count })}
</Tag>
</div>
<Paragraph
className='text-xs sm:text-sm leading-relaxed !mb-0 cursor-pointer'
style={COMPONENT_STYLES.descriptionText}
ellipsis={{ rows: 2 }}
onClick={() => handleOpenDescModal(description)}
>
{description}
</Paragraph>
</div>
<div className='flex-shrink-0'>{rightContent}</div>
</div>
</div>
}
>
{renderSearchActions()}
</Card>
),
[renderSearchActions, createCoverStyle, handleOpenDescModal, t],
);
const renderAllVendorsAvatar = useCallback(() => {
const currentVendor =
vendorInfo.length > 0
? vendorInfo[currentOffset % vendorInfo.length]
: null;
return renderVendorAvatar(currentVendor, t, true);
}, [vendorInfo, currentOffset, t]);
if (filterVendor === 'all') {
const headerCard = renderHeaderCard({
title: t('全部供应商'),
count: currentModelCount,
description: getVendorDescription('all'),
rightContent: renderAllVendorsAvatar(),
primaryDarkerChannel: THEME_COLORS.allVendors.primary,
});
return (
<>
{headerCard}
{renderDescriptionModal()}
</>
);
}
const currentVendor = vendorInfo.find((v) => v.name === filterVendor);
if (!currentVendor) {
return null;
}
const vendorDisplayName = getVendorDisplayName(currentVendor.name, t);
const headerCard = renderHeaderCard({
title: vendorDisplayName,
count: currentModelCount,
description:
currentVendor.description || getVendorDescription(currentVendor.name),
rightContent: renderVendorAvatar(currentVendor, t, false),
primaryDarkerChannel: THEME_COLORS.specific.primary,
});
return (
<>
{headerCard}
{renderDescriptionModal()}
</>
);
},
);
PricingVendorIntro.displayName = 'PricingVendorIntro';
export default PricingVendorIntro;
@@ -0,0 +1,212 @@
/*
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, { memo } from 'react';
import { Card, Skeleton } from '@douyinfe/semi-ui';
const THEME_COLORS = {
allVendors: {
primary: '37 99 235',
background: 'rgba(59, 130, 246, 0.1)',
border: 'rgba(59, 130, 246, 0.2)',
},
specific: {
primary: '16 185 129',
background: 'rgba(16, 185, 129, 0.1)',
border: 'rgba(16, 185, 129, 0.2)',
},
neutral: {
background: 'rgba(156, 163, 175, 0.1)',
border: 'rgba(156, 163, 175, 0.2)',
},
};
const SIZES = {
title: { width: { all: 120, specific: 100 }, height: 24 },
tag: { width: 80, height: 20 },
description: { height: 14 },
avatar: { width: 40, height: 40 },
searchInput: { height: 32 },
button: { width: 80, height: 32 },
};
const SKELETON_STYLES = {
cover: (primaryColor) => ({
'--palette-primary-darkerChannel': primaryColor,
backgroundImage: `linear-gradient(0deg, rgba(var(--palette-primary-darkerChannel) / 80%), rgba(var(--palette-primary-darkerChannel) / 80%)), url('/cover-4.webp')`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
}),
title: {
backgroundColor: 'rgba(255, 255, 255, 0.25)',
borderRadius: 8,
backdropFilter: 'blur(4px)',
},
tag: {
backgroundColor: 'rgba(255, 255, 255, 0.2)',
borderRadius: 9999,
backdropFilter: 'blur(4px)',
border: '1px solid rgba(255,255,255,0.3)',
},
description: {
backgroundColor: 'rgba(255, 255, 255, 0.2)',
borderRadius: 4,
backdropFilter: 'blur(4px)',
},
avatar: (isAllVendors) => {
const colors = isAllVendors
? THEME_COLORS.allVendors
: THEME_COLORS.specific;
return {
backgroundColor: colors.background,
borderRadius: 12,
border: `1px solid ${colors.border}`,
};
},
searchInput: {
backgroundColor: THEME_COLORS.neutral.background,
borderRadius: 8,
border: `1px solid ${THEME_COLORS.neutral.border}`,
},
button: {
backgroundColor: THEME_COLORS.neutral.background,
borderRadius: 8,
border: `1px solid ${THEME_COLORS.neutral.border}`,
},
};
const createSkeletonRect = (style = {}, key = null) => (
<div key={key} className='animate-pulse' style={style} />
);
const PricingVendorIntroSkeleton = memo(
({ isAllVendors = false, isMobile = false }) => {
const placeholder = (
<Card
className='!rounded-2xl shadow-sm border-0'
cover={
<div
className='relative h-full'
style={SKELETON_STYLES.cover(
isAllVendors
? THEME_COLORS.allVendors.primary
: THEME_COLORS.specific.primary,
)}
>
<div className='relative z-10 h-full flex items-center justify-between p-4'>
<div className='flex-1 min-w-0 mr-4'>
<div className='flex flex-row flex-wrap items-center gap-2 sm:gap-3 mb-2'>
{createSkeletonRect(
{
...SKELETON_STYLES.title,
width: isAllVendors
? SIZES.title.width.all
: SIZES.title.width.specific,
height: SIZES.title.height,
},
'title',
)}
{createSkeletonRect(
{
...SKELETON_STYLES.tag,
width: SIZES.tag.width,
height: SIZES.tag.height,
},
'tag',
)}
</div>
<div className='space-y-2'>
{createSkeletonRect(
{
...SKELETON_STYLES.description,
width: '100%',
height: SIZES.description.height,
},
'desc1',
)}
{createSkeletonRect(
{
...SKELETON_STYLES.description,
backgroundColor: 'rgba(255, 255, 255, 0.15)',
width: '75%',
height: SIZES.description.height,
},
'desc2',
)}
</div>
</div>
<div className='flex-shrink-0 w-16 h-16 rounded-2xl bg-white/90 shadow-md backdrop-blur-sm flex items-center justify-center'>
{createSkeletonRect(
{
...SKELETON_STYLES.avatar(isAllVendors),
width: SIZES.avatar.width,
height: SIZES.avatar.height,
},
'avatar',
)}
</div>
</div>
</div>
}
>
<div className='flex items-center gap-2 w-full'>
<div className='flex-1'>
{createSkeletonRect(
{
...SKELETON_STYLES.searchInput,
width: '100%',
height: SIZES.searchInput.height,
},
'search',
)}
</div>
{createSkeletonRect(
{
...SKELETON_STYLES.button,
width: SIZES.button.width,
height: SIZES.button.height,
},
'copy-button',
)}
{isMobile &&
createSkeletonRect(
{
...SKELETON_STYLES.button,
width: SIZES.button.width,
height: SIZES.button.height,
},
'filter-button',
)}
</div>
</Card>
);
return (
<Skeleton loading={true} active placeholder={placeholder}></Skeleton>
);
},
);
PricingVendorIntroSkeleton.displayName = 'PricingVendorIntroSkeleton';
export default PricingVendorIntroSkeleton;
@@ -0,0 +1,44 @@
/*
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, { memo } from 'react';
import PricingVendorIntro from './PricingVendorIntro';
import PricingVendorIntroSkeleton from './PricingVendorIntroSkeleton';
import { useMinimumLoadingTime } from '../../../../../hooks/common/useMinimumLoadingTime';
const PricingVendorIntroWithSkeleton = memo(
({ loading = false, filterVendor, ...restProps }) => {
const showSkeleton = useMinimumLoadingTime(loading);
if (showSkeleton) {
return (
<PricingVendorIntroSkeleton
isAllVendors={filterVendor === 'all'}
isMobile={restProps.isMobile}
/>
);
}
return <PricingVendorIntro filterVendor={filterVendor} {...restProps} />;
},
);
PricingVendorIntroWithSkeleton.displayName = 'PricingVendorIntroWithSkeleton';
export default PricingVendorIntroWithSkeleton;
@@ -0,0 +1,151 @@
/*
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, { memo, useCallback } from 'react';
import { Input, Button, Switch, Select, Divider } from '@douyinfe/semi-ui';
import { IconSearch, IconCopy, IconFilter } from '@douyinfe/semi-icons';
const SearchActions = memo(
({
selectedRowKeys = [],
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile = false,
searchValue = '',
setShowFilterModal,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
t,
}) => {
const handleCopyClick = useCallback(() => {
if (copyText && selectedRowKeys.length > 0) {
copyText(selectedRowKeys);
}
}, [copyText, selectedRowKeys]);
const handleFilterClick = useCallback(() => {
setShowFilterModal?.(true);
}, [setShowFilterModal]);
const handleViewModeToggle = useCallback(() => {
setViewMode?.(viewMode === 'table' ? 'card' : 'table');
}, [viewMode, setViewMode]);
const handleTokenUnitToggle = useCallback(() => {
setTokenUnit?.(tokenUnit === 'K' ? 'M' : 'K');
}, [tokenUnit, setTokenUnit]);
return (
<div className='flex items-center gap-2 w-full'>
<div className='flex-1'>
<Input
prefix={<IconSearch />}
placeholder={t('模糊搜索模型名称')}
value={searchValue}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
onChange={handleChange}
showClear
/>
</div>
<Button
theme='outline'
type='tertiary'
icon={<IconCopy style={{ color: '#ffffff' }} />}
onClick={handleCopyClick}
disabled={selectedRowKeys.length === 0}
className='!bg-blue-500 hover:!bg-blue-600 disabled:!bg-gray-300'
style={{ color: '#ffffff' }}
>
{t('复制')}
</Button>
{!isMobile && (
<>
<Divider layout='vertical' margin='8px' />
{/* 充值价格显示开关 */}
<div className='flex items-center gap-2'>
<span className='text-sm text-gray-600'>{t('充值价格显示')}</span>
<Switch
checked={showWithRecharge}
onChange={setShowWithRecharge}
/>
</div>
{/* 货币单位选择 */}
{showWithRecharge && (
<Select
value={currency}
onChange={setCurrency}
optionList={[
{ value: 'USD', label: 'USD' },
{ value: 'CNY', label: 'CNY' },
{ value: 'CUSTOM', label: t('自定义货币') },
]}
/>
)}
{/* 视图模式切换按钮 */}
<Button
theme={viewMode === 'table' ? 'solid' : 'outline'}
type={viewMode === 'table' ? 'primary' : 'tertiary'}
onClick={handleViewModeToggle}
>
{t('表格视图')}
</Button>
{/* Token单位切换按钮 */}
<Button
theme={tokenUnit === 'K' ? 'solid' : 'outline'}
type={tokenUnit === 'K' ? 'primary' : 'tertiary'}
onClick={handleTokenUnitToggle}
>
{tokenUnit}
</Button>
</>
)}
{isMobile && (
<Button
theme='outline'
type='tertiary'
icon={<IconFilter />}
onClick={handleFilterClick}
>
{t('筛选')}
</Button>
)}
</div>
);
},
);
SearchActions.displayName = 'SearchActions';
export default SearchActions;
@@ -0,0 +1,181 @@
/*
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, Typography, Button, Spin } from '@douyinfe/semi-ui';
import { X, Bot } from 'lucide-react';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import ModelHeader from './components/ModelHeader';
import ModelBasicInfo from './components/ModelBasicInfo';
import ModelEndpoints from './components/ModelEndpoints';
import ModelPricingTable from './components/ModelPricingTable';
const { Text } = Typography;
const ModelDetailSideSheet = ({
visible,
onClose,
modelData,
groupRatio,
groupModelDiscount,
currency,
tokenUnit,
displayPrice,
showRatio,
hidePrice,
usableGroup,
vendorsMap,
endpointMap,
autoGroups,
t,
}) => {
const isMobile = useIsMobile();
return (
<Modal
title={null}
header={null}
footer={null}
bodyStyle={{
padding: '0',
borderRadius: '20px',
overflow: 'hidden',
}}
className='model-detail-modal'
visible={visible}
width={isMobile ? '95%' : 560}
centered
closeIcon={null}
onCancel={onClose}
maskClosable={true}
maskStyle={{
backgroundColor: 'rgba(0, 0, 0, 0.4)',
backdropFilter: 'blur(8px)',
}}
>
{/* 自定义头部 */}
<div className='px-4 pt-4 pb-3'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<div className='p-1.5 bg-gradient-to-br from-brand-from to-brand-to rounded-lg'>
<Bot size={16} className='text-white' />
</div>
<div>
<h2 className='text-sm font-semibold text-gray-800 dark:text-gray-100'>
{t('模型详情')}
</h2>
<p className='text-[11px] text-gray-500 dark:text-gray-400'>
{t('查看模型定价与配置信息')}
</p>
</div>
</div>
{/* 关闭按钮 */}
<button
onClick={onClose}
className='p-1.5 rounded-lg bg-gray-100 hover:bg-gray-200 dark:bg-neutral-800 dark:hover:bg-neutral-700 transition-colors'
>
<X size={16} className='text-gray-500 dark:text-gray-400' />
</button>
</div>
{/* 模型标题 */}
{modelData && (
<div className='mt-2'>
<ModelHeader modelData={modelData} vendorsMap={vendorsMap} t={t} />
</div>
)}
</div>
{/* 内容区域 */}
<div
className='overflow-y-auto'
style={{
maxHeight: isMobile ? 'calc(85vh - 180px)' : 'calc(75vh - 160px)',
}}
>
<div className='px-4 pb-3'>
{!modelData ? (
<div className='flex flex-col justify-center items-center py-12'>
<Spin size='large' />
<Text type='secondary' className='mt-3'>
{t('加载中...')}
</Text>
</div>
) : (
/* 分区平铺 + 发丝分隔线:原先每区一层白卡边框,与弹窗自身、
* 区内表格边框叠出三层线框(用户反馈嵌套过多),改为零嵌套 */
<div className='divide-y divide-gray-100 dark:divide-neutral-800'>
{/* 基本信息 */}
<div className='py-3 first:pt-1'>
<ModelBasicInfo
modelData={modelData}
vendorsMap={vendorsMap}
t={t}
/>
</div>
{/* 端点信息 */}
<div className='py-3'>
<ModelEndpoints
modelData={modelData}
endpointMap={endpointMap}
t={t}
/>
</div>
{/* 定价表格 */}
{!hidePrice && (
<div className='py-3'>
<ModelPricingTable
modelData={modelData}
groupRatio={groupRatio}
groupModelDiscount={groupModelDiscount}
currency={currency}
tokenUnit={tokenUnit}
displayPrice={displayPrice}
showRatio={showRatio}
usableGroup={usableGroup}
autoGroups={autoGroups}
t={t}
/>
</div>
)}
</div>
)}
</div>
</div>
{/* 底部按钮 */}
<div className='px-4 pb-4 pt-2'>
<Button
block
theme='solid'
onClick={onClose}
className='!bg-gradient-to-r !from-brand-from !to-brand-to hover:!from-brand-from hover:!to-brand-to !rounded-xl !h-10 !font-medium !shadow-md !shadow-brand/20 transition-all'
>
{t('关闭')}
</Button>
</div>
</Modal>
);
};
export default ModelDetailSideSheet;
@@ -0,0 +1,68 @@
/*
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 } from '@douyinfe/semi-ui';
import { resetPricingFilters } from '../../../../helpers/utils';
import FilterModalContent from './components/FilterModalContent';
import FilterModalFooter from './components/FilterModalFooter';
const PricingFilterModal = ({ visible, onClose, sidebarProps, t }) => {
const handleResetFilters = () =>
resetPricingFilters({
handleChange: sidebarProps.handleChange,
setShowWithRecharge: sidebarProps.setShowWithRecharge,
setCurrency: sidebarProps.setCurrency,
setViewMode: sidebarProps.setViewMode,
setFilterGroup: sidebarProps.setFilterGroup,
setFilterQuotaType: sidebarProps.setFilterQuotaType,
setFilterEndpointType: sidebarProps.setFilterEndpointType,
setFilterVendor: sidebarProps.setFilterVendor,
setFilterTag: sidebarProps.setFilterTag,
setCurrentPage: sidebarProps.setCurrentPage,
setTokenUnit: sidebarProps.setTokenUnit,
});
const footer = (
<FilterModalFooter onReset={handleResetFilters} onConfirm={onClose} t={t} />
);
return (
<Modal
title={t('筛选')}
visible={visible}
onCancel={onClose}
footer={footer}
className='pricing-filter-modal'
style={{ width: '100%', height: '100%', margin: 0 }}
bodyStyle={{
padding: 0,
height: 'calc(100vh - 160px)',
overflowY: 'auto',
scrollbarWidth: 'none',
msOverflowStyle: 'none',
backgroundColor: 'var(--semi-color-bg-0)',
}}
>
<FilterModalContent sidebarProps={sidebarProps} t={t} />
</Modal>
);
};
export default PricingFilterModal;
@@ -0,0 +1,137 @@
/*
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 PricingDisplaySettings from '../../filter/PricingDisplaySettings';
import PricingGroups from '../../filter/PricingGroups';
import PricingQuotaTypes from '../../filter/PricingQuotaTypes';
import PricingEndpointTypes from '../../filter/PricingEndpointTypes';
import PricingVendors from '../../filter/PricingVendors';
import PricingTags from '../../filter/PricingTags';
import { usePricingFilterCounts } from '../../../../../hooks/model-pricing/usePricingFilterCounts';
const FilterModalContent = ({ sidebarProps, t }) => {
const {
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
handleChange,
setActiveKey,
showRatio,
viewMode,
setViewMode,
filterGroup,
setFilterGroup,
filterQuotaType,
setFilterQuotaType,
filterEndpointType,
setFilterEndpointType,
filterVendor,
setFilterVendor,
filterTag,
setFilterTag,
tokenUnit,
setTokenUnit,
loading,
...categoryProps
} = sidebarProps;
const {
quotaTypeModels,
endpointTypeModels,
vendorModels,
tagModels,
groupCountModels,
} = usePricingFilterCounts({
models: categoryProps.models,
filterGroup,
filterQuotaType,
filterEndpointType,
filterVendor,
filterTag,
searchValue: sidebarProps.searchValue,
});
return (
<>
<PricingDisplaySettings
showWithRecharge={showWithRecharge}
setShowWithRecharge={setShowWithRecharge}
currency={currency}
setCurrency={setCurrency}
showRatio={showRatio}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
loading={loading}
t={t}
/>
<PricingVendors
filterVendor={filterVendor}
setFilterVendor={setFilterVendor}
models={vendorModels}
allModels={categoryProps.models}
loading={loading}
t={t}
/>
<PricingTags
filterTag={filterTag}
setFilterTag={setFilterTag}
models={tagModels}
allModels={categoryProps.models}
loading={loading}
t={t}
/>
<PricingGroups
filterGroup={filterGroup}
setFilterGroup={setFilterGroup}
usableGroup={categoryProps.usableGroup}
groupRatio={categoryProps.groupRatio}
models={groupCountModels}
loading={loading}
showRatio={showRatio}
t={t}
/>
<PricingQuotaTypes
filterQuotaType={filterQuotaType}
setFilterQuotaType={setFilterQuotaType}
models={quotaTypeModels}
loading={loading}
t={t}
/>
<PricingEndpointTypes
filterEndpointType={filterEndpointType}
setFilterEndpointType={setFilterEndpointType}
models={endpointTypeModels}
allModels={categoryProps.models}
loading={loading}
t={t}
/>
</>
);
};
export default FilterModalContent;
@@ -0,0 +1,36 @@
/*
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 } from '@douyinfe/semi-ui';
const FilterModalFooter = ({ onReset, onConfirm, t }) => {
return (
<div className='flex justify-end'>
<Button theme='outline' type='tertiary' onClick={onReset}>
{t('重置')}
</Button>
<Button theme='solid' type='primary' onClick={onConfirm}>
{t('确定')}
</Button>
</div>
);
};
export default FilterModalFooter;
@@ -0,0 +1,90 @@
/*
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 { FileText, Sparkles } from 'lucide-react';
import { stringToColor } from '../../../../../helpers';
const ModelBasicInfo = ({ modelData, vendorsMap = {}, t }) => {
// 获取模型描述
const getModelDescription = () => {
if (!modelData) return t('暂无模型描述');
if (modelData.description) return modelData.description;
if (modelData.vendor_description)
return t('供应商信息:') + modelData.vendor_description;
return t('暂无模型描述');
};
// 获取模型标签
const getModelTags = () => {
const tags = [];
if (modelData?.tags) {
const customTags = modelData.tags.split(',').filter((tag) => tag.trim());
customTags.forEach((tag) => {
const tagText = tag.trim();
tags.push({ text: tagText, color: stringToColor(tagText) });
});
}
return tags;
};
const tags = getModelTags();
return (
<div className='space-y-3'>
{/* 标题行 —— 单行紧凑小节头(原大色块 chip+副标题在弹窗内层级过重) */}
<h3 className='flex items-center gap-1.5 text-[13px] font-semibold text-gray-900 dark:text-white'>
<FileText
size={14}
className='text-brand-deep dark:text-brand-from flex-shrink-0'
/>
{t('基本信息')}
</h3>
{/* 描述区域 */}
<div className='relative pl-3'>
<div className='absolute left-0 top-0 bottom-0 w-0.5 rounded-full bg-brand-from' />
<p className='text-sm text-gray-600 dark:text-gray-300 leading-relaxed'>
{getModelDescription()}
</p>
</div>
{/* 标签区域 */}
{tags.length > 0 && (
<div className='flex flex-wrap gap-1.5'>
{tags.map((tag, index) => (
<span
key={index}
className='inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium'
style={{
backgroundColor: `${tag.color}15`,
color: tag.color,
}}
>
<Sparkles size={10} />
{tag.text}
</span>
))}
</div>
)}
</div>
);
};
export default ModelBasicInfo;
@@ -0,0 +1,129 @@
/*
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 { Plug, Zap, ArrowRight, Globe } from 'lucide-react';
const ModelEndpoints = ({ modelData, endpointMap = {}, t }) => {
const types = modelData?.supported_endpoint_types || [];
const getEndpointInfo = (type) => {
const info = endpointMap[type] || {};
let path = info.path || '';
if (path.includes('{model}')) {
const modelName = modelData?.model_name || modelData?.modelName || '';
path = path.replaceAll('{model}', modelName);
}
return { path, method: info.method || 'POST' };
};
const getMethodColor = (method) => {
const colors = {
GET: {
bg: 'bg-emerald-500/10',
text: 'text-emerald-600 dark:text-emerald-400',
border: 'border-emerald-500/20',
},
POST: {
bg: 'bg-blue-500/10',
text: 'text-blue-600 dark:text-blue-400',
border: 'border-blue-500/20',
},
PUT: {
bg: 'bg-amber-500/10',
text: 'text-amber-600 dark:text-amber-400',
border: 'border-amber-500/20',
},
DELETE: {
bg: 'bg-red-500/10',
text: 'text-red-600 dark:text-red-400',
border: 'border-red-500/20',
},
};
return colors[method] || colors.POST;
};
return (
<div className='space-y-3'>
{/* 标题区域 —— 单行紧凑小节头 */}
<div className='flex items-center justify-between'>
<h3 className='flex items-center gap-1.5 text-[13px] font-semibold text-gray-900 dark:text-white'>
<Plug
size={14}
className='text-brand-deep dark:text-brand-from flex-shrink-0'
/>
{t('API端点')}
</h3>
<span className='text-xs text-gray-500 dark:text-gray-400 font-medium'>
<Globe size={12} className='inline mr-1' />
{types.length} {t('个端点')}
</span>
</div>
{/* 端点列表 */}
<div className='space-y-2'>
{types.map((type) => {
const { path, method } = getEndpointInfo(type);
const methodStyle = getMethodColor(method);
return (
<div
key={type}
className='flex items-center justify-between gap-3 py-2'
>
<div className='flex-1 min-w-0'>
<div className='flex items-center gap-2'>
<Zap size={12} className='text-brand flex-shrink-0' />
<span className='text-sm font-medium text-gray-900 dark:text-white'>
{type}
</span>
</div>
{path && (
<div className='flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 mt-0.5 ml-5'>
<ArrowRight size={10} className='flex-shrink-0' />
<code className='font-mono text-gray-600 dark:text-gray-300'>
{path}
</code>
</div>
)}
</div>
{path && (
<span
className={`flex-shrink-0 px-2 py-0.5 rounded text-xs font-semibold ${methodStyle.bg} ${methodStyle.text}`}
>
{method}
</span>
)}
</div>
);
})}
</div>
{types.length === 0 && (
<div className='text-center py-6 text-gray-400 dark:text-gray-500'>
<Plug size={24} className='mx-auto mb-2 opacity-50' />
<p className='text-sm'>{t('暂无端点信息')}</p>
</div>
)}
</div>
);
};
export default ModelEndpoints;
@@ -0,0 +1,96 @@
/*
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 { Typography, Toast, Avatar } from '@douyinfe/semi-ui';
import { getLobeHubIcon } from '../../../../../helpers';
const { Paragraph } = Typography;
const CARD_STYLES = {
container:
'w-12 h-12 rounded-2xl flex items-center justify-center relative shadow-md',
icon: 'w-8 h-8 flex items-center justify-center',
};
const ModelHeader = ({ modelData, vendorsMap = {}, t }) => {
// 获取模型图标(优先模型图标,其次供应商图标)
const getModelIcon = () => {
// 1) 优先使用模型自定义图标
if (modelData?.icon) {
return (
<div className={CARD_STYLES.container}>
<div className={CARD_STYLES.icon}>
{getLobeHubIcon(modelData.icon, 32)}
</div>
</div>
);
}
// 2) 退化为供应商图标
if (modelData?.vendor_icon) {
return (
<div className={CARD_STYLES.container}>
<div className={CARD_STYLES.icon}>
{getLobeHubIcon(modelData.vendor_icon, 32)}
</div>
</div>
);
}
// 如果没有供应商图标,使用模型名称的前两个字符
const avatarText = modelData?.model_name?.slice(0, 2).toUpperCase() || 'AI';
return (
<div className={CARD_STYLES.container}>
<Avatar
size='large'
style={{
width: 48,
height: 48,
borderRadius: 16,
fontSize: 16,
fontWeight: 'bold',
}}
>
{avatarText}
</Avatar>
</div>
);
};
return (
<div className='flex items-center'>
{getModelIcon()}
<div className='ml-3 font-normal'>
<Paragraph
className='!mb-0 !text-lg !font-medium'
copyable={{
content: modelData?.model_name || '',
onCopy: () => Toast.success({ content: t('已复制模型名称') }),
}}
>
<span className='truncate max-w-60 font-bold'>
{modelData?.model_name || t('未知模型')}
</span>
</Paragraph>
</div>
</div>
);
};
export default ModelHeader;
@@ -0,0 +1,358 @@
/*
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 {
Coins,
ChevronRight,
Layers,
Calculator,
BadgePercent,
} from 'lucide-react';
import {
calculateModelPrice,
formatOfficialPriceDisplay,
getDiscountBadgeText,
} from '../../../../../helpers';
const ModelPricingTable = ({
modelData,
groupRatio,
groupModelDiscount,
currency,
tokenUnit,
displayPrice,
showRatio,
usableGroup,
autoGroups = [],
t,
}) => {
const modelEnableGroups = Array.isArray(modelData?.enable_groups)
? modelData.enable_groups
: [];
const autoChain = autoGroups.filter((g) => modelEnableGroups.includes(g));
const availableGroups = Object.keys(usableGroup || {})
.filter((g) => g !== '' && g !== 'auto')
.filter((g) => modelEnableGroups.includes(g));
const getPriceData = (group) => {
return modelData
? calculateModelPrice({
record: modelData,
selectedGroup: group,
groupRatio,
groupModelDiscount,
tokenUnit,
displayPrice,
currency,
})
: { inputPrice: '-', outputPrice: '-', price: '-' };
};
const isPerToken = modelData?.quota_type === 0;
const isPerSecond = modelData?.quota_type === 2;
const isPerImageResolution = modelData?.quota_type === 3;
// 官方价参考行:仅当至少一个可用分组的实付价低于官方牌价时展示
//(与卡片折扣徽标同一保守口径,避免展示「站内比官方还贵」的对照)
const groupPriceDataList = availableGroups.map((g) => getPriceData(g));
const hasAnyDiscount = groupPriceDataList.some((pd) => pd?.discountBadge);
const officialDisplay =
hasAnyDiscount && modelData?.official_price
? formatOfficialPriceDisplay({
official: modelData.official_price,
tokenUnit,
displayPrice,
})
: null;
const billingLabel = isPerSecond
? t('按秒计费')
: isPerImageResolution
? t('按分辨率计费')
: isPerToken
? t('按量计费')
: t('按次计费');
const tokenLabel = tokenUnit === 'K' ? '1K' : '1M';
const samplePriceData = isPerToken
? getPriceData(availableGroups[0] || 'all')
: null;
const extraPriceColumns = Array.isArray(samplePriceData?.extraPrices)
? samplePriceData.extraPrices
: [];
// 按秒分档:列 = 各档位,由配置顺序决定
const videoTierColumns = isPerSecond
? (modelData?.video_second_pricing?.tiers || []).map((tier) => ({
key: tier.key,
label: tier.label || tier.key,
}))
: [];
const imageTierColumns = isPerImageResolution
? (modelData?.image_resolution_pricing?.tiers || []).map((tier) => ({
key: tier.key,
label: tier.label || tier.key,
}))
: [];
const tierColumns = isPerSecond ? videoTierColumns : imageTierColumns;
const isTierPricing = isPerSecond || isPerImageResolution;
const priceGridStyle = isTierPricing
? {
gridTemplateColumns: `minmax(76px, 1fr) repeat(${Math.max(tierColumns.length, 1)}, minmax(88px, max-content))`,
minWidth:
tierColumns.length > 0
? `${160 + tierColumns.length * 100}px`
: undefined,
}
: isPerToken
? {
gridTemplateColumns: `minmax(76px, 1fr) repeat(${2 + extraPriceColumns.length}, minmax(88px, max-content))`,
minWidth:
extraPriceColumns.length > 0
? `${260 + extraPriceColumns.length * 108}px`
: undefined,
}
: undefined;
return (
<div className='space-y-3'>
{/* 标题区域 —— 单行紧凑小节头 */}
<div className='flex items-center justify-between'>
<h3 className='flex items-center gap-1.5 text-[13px] font-semibold text-gray-900 dark:text-white'>
<Coins
size={14}
className='text-brand-deep dark:text-brand-from flex-shrink-0'
/>
{t('分组价格')}
</h3>
<span className='text-xs text-gray-500 dark:text-gray-400 font-medium'>
<Calculator size={12} className='inline mr-1' />
{billingLabel}
</span>
</div>
{/* Auto分组链路 */}
{autoChain.length > 0 && (
<div className='flex items-center flex-wrap gap-1.5 text-xs text-gray-500 dark:text-gray-400'>
<Layers size={12} className='text-brand' />
<span>{t('auto分组调用链路')}</span>
{autoChain.map((g, idx) => (
<React.Fragment key={g}>
<span className='px-1.5 py-0.5 rounded text-brand-deep dark:text-brand-from font-medium bg-brand/10'>
{g}
</span>
{idx < autoChain.length - 1 && (
<ChevronRight size={10} className='text-gray-400' />
)}
</React.Fragment>
))}
</div>
)}
{/* 价格表格 */}
<div className='overflow-x-auto'>
{/* 表头 */}
<div
className={`grid ${isPerToken || isTierPricing ? '' : 'grid-cols-2'} text-[11px] font-medium text-gray-400 dark:text-gray-400 border-b border-gray-100 dark:border-neutral-700 pb-2 mb-1`}
style={priceGridStyle}
>
<div>{t('分组')}</div>
{isPerSecond ? (
videoTierColumns.map((col) => (
<div key={col.key} className='text-right'>
{col.label} / {t('秒')}
</div>
))
) : isPerImageResolution ? (
imageTierColumns.map((col) => (
<div key={col.key} className='text-right'>
{col.label} / {t('张')}
</div>
))
) : isPerToken ? (
<>
<div className='text-right'>
{t('输入价格')} / {tokenLabel}
</div>
<div className='text-right'>
{t('输出价格')} / {tokenLabel}
</div>
{extraPriceColumns.map((item) => (
<div key={item.key} className='text-right'>
{t(item.labelKey)} / {tokenLabel}
</div>
))}
</>
) : (
<div className='text-right'>
{t('单价')} / {t('次')}
</div>
)}
</div>
{/* 官方价参考行:管理员维护的原厂牌价(不含分组倍率),供各分组折扣对照 */}
{officialDisplay && !isTierPricing && (
<div
className={`grid ${isPerToken ? '' : 'grid-cols-2'} items-center py-1.5 rounded-lg bg-gray-50/80 dark:bg-neutral-800/60`}
style={priceGridStyle}
>
<div className='flex items-center gap-1.5 pl-1'>
<BadgePercent size={12} className='text-gray-400' />
<span
className='text-sm text-gray-500 dark:text-gray-400'
title={t('管理员维护的模型原厂牌价,未含分组倍率,仅供对照')}
>
{t('官方价')}
</span>
</div>
{isPerToken ? (
<>
<div className='text-right'>
<span className='text-sm text-gray-500 dark:text-gray-400 line-through'>
{officialDisplay.input || '-'}
</span>
</div>
<div className='text-right'>
<span className='text-sm text-gray-500 dark:text-gray-400 line-through'>
{officialDisplay.output || '-'}
</span>
</div>
{extraPriceColumns.map((column) => (
<div key={column.key} className='text-right'>
<span className='text-sm text-gray-400'>-</span>
</div>
))}
</>
) : (
<div className='text-right'>
<span className='text-sm text-gray-500 dark:text-gray-400 line-through'>
{officialDisplay.perCall || '-'}
</span>
</div>
)}
</div>
)}
{/* 数据行 */}
<div className='space-y-0.5'>
{availableGroups.map((group, idx) => {
const priceData = groupPriceDataList[idx];
const discountText = getDiscountBadgeText(priceData);
return (
<div
key={group}
className={`grid ${isPerToken || isTierPricing ? '' : 'grid-cols-2'} items-center py-1.5`}
style={priceGridStyle}
>
<div className='flex items-center gap-1.5'>
<span
className={`w-1.5 h-1.5 rounded-full ${idx % 3 === 0 ? 'bg-emerald-500' : idx % 3 === 1 ? 'bg-blue-500' : 'bg-brand'}`}
/>
<span className='text-sm text-gray-700 dark:text-gray-200'>
{group}
</span>
{discountText && (
<span
className='px-1.5 py-[1px] rounded-full text-[10px] font-semibold leading-4
text-brand-deep dark:text-brand-from bg-brand/10 dark:bg-brand-deep/30
border border-brand/25 dark:border-brand-deep/50 select-none'
title={t(
'相比官方牌价的折扣,按当前计价分组实付价计算(已含您的等级折扣),仅供参考',
)}
>
{discountText}
</span>
)}
</div>
{isPerSecond ? (
videoTierColumns.map((col) => {
const tier = priceData.videoTiers?.find(
(vt) => vt.key === col.key,
);
return (
<div key={col.key} className='text-right'>
<span className='text-sm font-semibold text-emerald-600 dark:text-emerald-400'>
{tier?.price || '-'}
</span>
</div>
);
})
) : isPerImageResolution ? (
imageTierColumns.map((col) => {
const tier = priceData.imageTiers?.find(
(imageTier) => imageTier.key === col.key,
);
return (
<div key={col.key} className='text-right'>
<span className='text-sm font-semibold text-sky-600 dark:text-sky-400'>
{tier?.price || '-'}
</span>
</div>
);
})
) : isPerToken ? (
<>
<div className='text-right'>
<span className='text-sm font-semibold text-orange-600 dark:text-orange-400'>
{priceData.inputPrice}
</span>
</div>
<div className='text-right'>
<span className='text-sm font-semibold text-rose-600 dark:text-rose-400'>
{priceData.completionPrice || priceData.outputPrice}
</span>
</div>
{extraPriceColumns.map((column) => {
const item = priceData.extraPrices?.find(
(extra) => extra.key === column.key,
);
return (
<div key={column.key} className='text-right'>
<span className='text-sm font-semibold text-sky-600 dark:text-sky-400'>
{item?.price || '-'}
</span>
</div>
);
})}
</>
) : (
<div className='text-right'>
<span className='text-sm font-semibold text-brand-deep dark:text-brand-from'>
{priceData.price}
</span>
</div>
)}
</div>
);
})}
</div>
</div>
{availableGroups.length === 0 && (
<div className='text-center py-4 text-gray-400 dark:text-gray-400 text-xs'>
<Coins size={18} className='mx-auto mb-1 opacity-50' />
{t('暂无价格信息')}
</div>
)}
</div>
);
};
export default ModelPricingTable;
@@ -0,0 +1,144 @@
/*
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 { Card, Skeleton } from '@douyinfe/semi-ui';
const PricingCardSkeleton = ({
skeletonCount = 100,
rowSelection = false,
showRatio = false,
}) => {
const placeholder = (
<div className='px-2 pt-2'>
<div className='grid grid-cols-1 xl:grid-cols-2 2xl:grid-cols-3 gap-4'>
{Array.from({ length: skeletonCount }).map((_, index) => (
<Card
key={index}
className='!rounded-2xl border border-gray-200'
bodyStyle={{ padding: '24px' }}
>
{/* 头部:图标 + 模型名称 + 操作按钮 */}
<div className='flex items-start justify-between mb-3'>
<div className='flex items-start space-x-3 flex-1 min-w-0'>
{/* 模型图标骨架 */}
<div className='w-12 h-12 rounded-2xl flex items-center justify-center relative shadow-sm'>
<Skeleton.Avatar
size='large'
style={{ width: 48, height: 48, borderRadius: 16 }}
/>
</div>
{/* 模型名称和价格区域 */}
<div className='flex-1 min-w-0'>
{/* 模型名称骨架 */}
<Skeleton.Title
style={{
width: `${120 + (index % 3) * 30}px`,
height: 20,
marginBottom: 8,
}}
/>
{/* 价格信息骨架 */}
<Skeleton.Title
style={{
width: `${160 + (index % 4) * 20}px`,
height: 20,
marginBottom: 0,
}}
/>
</div>
</div>
<div className='flex items-center space-x-2 ml-3'>
{/* 复制按钮骨架 */}
<Skeleton.Button
size='small'
style={{ width: 16, height: 16, borderRadius: 4 }}
/>
{/* 勾选框骨架 */}
{rowSelection && (
<Skeleton.Button
size='small'
style={{ width: 16, height: 16, borderRadius: 2 }}
/>
)}
</div>
</div>
{/* 模型描述骨架 */}
<div className='mb-4'>
<Skeleton.Paragraph
rows={2}
style={{ marginBottom: 0 }}
title={false}
/>
</div>
{/* 标签区域骨架 */}
<div className='flex flex-wrap gap-2'>
{Array.from({ length: 2 + (index % 3) }).map((_, tagIndex) => (
<Skeleton.Button
key={tagIndex}
size='small'
style={{
width: 64,
height: 18,
borderRadius: 10,
}}
/>
))}
</div>
{/* 倍率信息骨架(可选) */}
{showRatio && (
<div className='mt-4 pt-3 border-t border-gray-100'>
<div className='flex items-center space-x-1 mb-2'>
<Skeleton.Title
style={{ width: 60, height: 12, marginBottom: 0 }}
/>
<Skeleton.Button
size='small'
style={{ width: 14, height: 14, borderRadius: 7 }}
/>
</div>
<div className='grid grid-cols-3 gap-2'>
{Array.from({ length: 3 }).map((_, ratioIndex) => (
<Skeleton.Title
key={ratioIndex}
style={{ width: '100%', height: 12, marginBottom: 0 }}
/>
))}
</div>
</div>
)}
</Card>
))}
</div>
{/* 分页骨架 */}
<div className='flex justify-center mt-6 py-4 border-t pricing-pagination-divider'>
<Skeleton.Button style={{ width: 300, height: 32 }} />
</div>
</div>
);
return <Skeleton loading={true} active placeholder={placeholder}></Skeleton>;
};
export default PricingCardSkeleton;
@@ -0,0 +1,396 @@
/*
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 {
Card,
Tag,
Tooltip,
Checkbox,
Empty,
Pagination,
Button,
Avatar,
} from '@douyinfe/semi-ui';
import { IconHelpCircle } from '@douyinfe/semi-icons';
import { Copy } from 'lucide-react';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../../common/illustrations';
import {
stringToColor,
calculateModelPrice,
formatPriceInfo,
getLobeHubIcon,
} from '../../../../../helpers';
import PricingCardSkeleton from './PricingCardSkeleton';
import { useMinimumLoadingTime } from '../../../../../hooks/common/useMinimumLoadingTime';
import { renderLimitedItems } from '../../../../common/ui/RenderUtils';
import { useIsMobile } from '../../../../../hooks/common/useIsMobile';
const CARD_STYLES = {
container:
'w-12 h-12 rounded-2xl flex items-center justify-center relative shadow-md',
icon: 'w-8 h-8 flex items-center justify-center',
selected: 'border-blue-500 bg-blue-50',
default: 'border-gray-200 hover:border-gray-300',
};
const PricingCardView = ({
filteredModels,
loading,
rowSelection,
pageSize,
setPageSize,
currentPage,
setCurrentPage,
selectedGroup,
groupRatio,
groupModelDiscount,
copyText,
setModalImageUrl,
setIsModalOpenurl,
currency,
tokenUnit,
displayPrice,
showRatio,
t,
selectedRowKeys = [],
setSelectedRowKeys,
openModelDetail,
}) => {
const showSkeleton = useMinimumLoadingTime(loading);
const startIndex = (currentPage - 1) * pageSize;
const paginatedModels = filteredModels.slice(
startIndex,
startIndex + pageSize,
);
const getModelKey = (model) => model.key ?? model.model_name ?? model.id;
const isMobile = useIsMobile();
const handleCheckboxChange = (model, checked) => {
if (!setSelectedRowKeys) return;
const modelKey = getModelKey(model);
const newKeys = checked
? Array.from(new Set([...selectedRowKeys, modelKey]))
: selectedRowKeys.filter((key) => key !== modelKey);
setSelectedRowKeys(newKeys);
rowSelection?.onChange?.(newKeys, null);
};
// 获取模型图标
const getModelIcon = (model) => {
if (!model || !model.model_name) {
return (
<div className={CARD_STYLES.container}>
<Avatar size='large'>?</Avatar>
</div>
);
}
// 1) 优先使用模型自定义图标
if (model.icon) {
return (
<div className={CARD_STYLES.container}>
<div className={CARD_STYLES.icon}>
{getLobeHubIcon(model.icon, 32)}
</div>
</div>
);
}
// 2) 退化为供应商图标
if (model.vendor_icon) {
return (
<div className={CARD_STYLES.container}>
<div className={CARD_STYLES.icon}>
{getLobeHubIcon(model.vendor_icon, 32)}
</div>
</div>
);
}
// 如果没有供应商图标,使用模型名称生成头像
const avatarText = model.model_name.slice(0, 2).toUpperCase();
return (
<div className={CARD_STYLES.container}>
<Avatar
size='large'
style={{
width: 48,
height: 48,
borderRadius: 16,
fontSize: 16,
fontWeight: 'bold',
}}
>
{avatarText}
</Avatar>
</div>
);
};
// 获取模型描述
const getModelDescription = (record) => {
return record.description || '';
};
// 渲染标签
const renderTags = (record) => {
// 计费类型标签(左边)
let billingTag = (
<Tag key='billing' shape='circle' color='white' size='small'>
-
</Tag>
);
if (record.quota_type === 3) {
billingTag = (
<Tag key='billing' shape='circle' color='blue' size='small'>
{t('按分辨率计费')}
</Tag>
);
} else if (record.quota_type === 2) {
billingTag = (
<Tag key='billing' shape='circle' color='green' size='small'>
{t('按秒计费')}
</Tag>
);
} else if (record.quota_type === 1) {
billingTag = (
<Tag key='billing' shape='circle' color='teal' size='small'>
{t('按次计费')}
</Tag>
);
} else if (record.quota_type === 0) {
billingTag = (
<Tag key='billing' shape='circle' color='violet' size='small'>
{t('按量计费')}
</Tag>
);
}
// 自定义标签(右边)
const customTags = [];
if (record.tags) {
const tagArr = record.tags.split(',').filter(Boolean);
tagArr.forEach((tg, idx) => {
customTags.push(
<Tag
key={`custom-${idx}`}
shape='circle'
color={stringToColor(tg)}
size='small'
>
{tg}
</Tag>,
);
});
}
return (
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>{billingTag}</div>
<div className='flex items-center gap-1'>
{customTags.length > 0 &&
renderLimitedItems({
items: customTags.map((tag, idx) => ({
key: `custom-${idx}`,
element: tag,
})),
renderItem: (item, idx) => item.element,
maxDisplay: 3,
})}
</div>
</div>
);
};
// 显示骨架屏
if (showSkeleton) {
return (
<PricingCardSkeleton
rowSelection={!!rowSelection}
showRatio={showRatio}
/>
);
}
if (!filteredModels || filteredModels.length === 0) {
return (
<div className='flex justify-center items-center py-20'>
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
/>
</div>
);
}
return (
<div className='px-2 pt-2'>
<div className='grid grid-cols-1 xl:grid-cols-2 2xl:grid-cols-3 gap-4'>
{paginatedModels.map((model, index) => {
const modelKey = getModelKey(model);
const isSelected = selectedRowKeys.includes(modelKey);
const priceData = calculateModelPrice({
record: model,
selectedGroup,
groupRatio,
groupModelDiscount,
tokenUnit,
displayPrice,
currency,
});
return (
<Card
key={modelKey || index}
className={`!rounded-2xl transition-all duration-200 hover:shadow-lg border cursor-pointer ${isSelected ? CARD_STYLES.selected : CARD_STYLES.default}`}
bodyStyle={{ height: '100%' }}
onClick={() => openModelDetail && openModelDetail(model)}
>
<div className='flex flex-col h-full'>
{/* 头部:图标 + 模型名称 + 操作按钮 */}
<div className='flex items-start justify-between mb-3'>
<div className='flex items-start space-x-3 flex-1 min-w-0'>
{getModelIcon(model)}
<div className='flex-1 min-w-0'>
<h3 className='text-lg font-bold text-gray-900 truncate'>
{model.model_name}
</h3>
<div className='flex items-center gap-3 text-xs mt-1'>
{formatPriceInfo(priceData, t)}
</div>
</div>
</div>
<div className='flex items-center space-x-2 ml-3'>
{/* 复制按钮 */}
<Button
size='small'
theme='outline'
type='tertiary'
icon={<Copy size={12} />}
onClick={(e) => {
e.stopPropagation();
copyText(model.model_name);
}}
/>
{/* 选择框 */}
{rowSelection && (
<Checkbox
checked={isSelected}
onChange={(e) => {
e.stopPropagation();
handleCheckboxChange(model, e.target.checked);
}}
/>
)}
</div>
</div>
{/* 模型描述 - 占据剩余空间 */}
<div className='flex-1 mb-4'>
<p
className='text-xs line-clamp-2 leading-relaxed'
style={{ color: 'var(--semi-color-text-2)' }}
>
{getModelDescription(model)}
</p>
</div>
{/* 底部区域 */}
<div className='mt-auto'>
{/* 标签区域 */}
{renderTags(model)}
{/* 倍率信息(可选) */}
{showRatio && (
<div className='pt-3'>
<div className='flex items-center space-x-1 mb-2'>
<span className='text-xs font-medium text-gray-700'>
{t('倍率信息')}
</span>
<Tooltip
content={t('倍率是为了方便换算不同价格的模型')}
>
<IconHelpCircle
className='text-blue-500 cursor-pointer'
size='small'
onClick={(e) => {
e.stopPropagation();
setModalImageUrl('/ratio.png');
setIsModalOpenurl(true);
}}
/>
</Tooltip>
</div>
<div className='grid grid-cols-3 gap-2 text-xs text-gray-600'>
<div>
{t('模型')}:{' '}
{model.quota_type === 0 ? model.model_ratio : t('无')}
</div>
<div>
{t('补全')}:{' '}
{model.quota_type === 0
? parseFloat(model.completion_ratio.toFixed(3))
: t('无')}
</div>
<div>
{t('分组')}: {priceData?.usedGroupRatio ?? '-'}
</div>
</div>
</div>
)}
</div>
</div>
</Card>
);
})}
</div>
{/* 分页 */}
{filteredModels.length > 0 && (
<div className='flex justify-center mt-6 py-4 border-t pricing-pagination-divider'>
<Pagination
currentPage={currentPage}
pageSize={pageSize}
total={filteredModels.length}
showSizeChanger={true}
pageSizeOptions={[10, 20, 50, 100]}
size={isMobile ? 'small' : 'default'}
showQuickJumper={isMobile}
onPageChange={(page) => setCurrentPage(page)}
onPageSizeChange={(size) => {
setPageSize(size);
setCurrentPage(1);
}}
/>
</div>
)}
</div>
);
};
export default PricingCardView;
@@ -0,0 +1,151 @@
/*
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 } from 'react';
import { Card, Table, Empty } from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../../common/illustrations';
import { getPricingTableColumns } from './PricingTableColumns';
import { useIsMobile } from '../../../../../hooks/common/useIsMobile';
const PricingTable = ({
filteredModels,
loading,
rowSelection,
pageSize,
setPageSize,
selectedGroup,
groupRatio,
groupModelDiscount,
copyText,
setModalImageUrl,
setIsModalOpenurl,
currency,
tokenUnit,
displayPrice,
searchValue,
showRatio,
compactMode = false,
openModelDetail,
t,
}) => {
const isMobile = useIsMobile();
const columns = useMemo(() => {
return getPricingTableColumns({
t,
selectedGroup,
groupRatio,
groupModelDiscount,
copyText,
setModalImageUrl,
setIsModalOpenurl,
currency,
tokenUnit,
displayPrice,
showRatio,
isMobile,
});
}, [
t,
selectedGroup,
groupRatio,
groupModelDiscount,
copyText,
setModalImageUrl,
setIsModalOpenurl,
currency,
tokenUnit,
displayPrice,
showRatio,
isMobile,
]);
// 更新列定义中的 searchValue
const processedColumns = useMemo(() => {
const cols = columns.map((column) => {
if (column.dataIndex === 'model_name') {
return {
...column,
filteredValue: searchValue ? [searchValue] : [],
};
}
return column;
});
// Remove fixed property when in compact mode (mobile view)
if (compactMode) {
return cols.map(({ fixed, ...rest }) => rest);
}
return cols;
}, [columns, searchValue, compactMode]);
const ModelTable = useMemo(
() => (
<Card className='!rounded-xl overflow-hidden' bordered={false}>
<Table
columns={processedColumns}
dataSource={filteredModels}
loading={loading}
rowSelection={rowSelection}
scroll={compactMode ? undefined : { x: 'max-content' }}
onRow={(record) => ({
onClick: () => openModelDetail && openModelDetail(record),
style: { cursor: 'pointer' },
})}
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
pagination={{
defaultPageSize: 20,
pageSize: pageSize,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: (size) => setPageSize(size),
}}
/>
</Card>
),
[
filteredModels,
loading,
processedColumns,
rowSelection,
pageSize,
setPageSize,
openModelDetail,
t,
compactMode,
],
);
return ModelTable;
};
export default PricingTable;
@@ -0,0 +1,322 @@
/*
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 { Tag, Space, Tooltip } from '@douyinfe/semi-ui';
import { IconHelpCircle } from '@douyinfe/semi-icons';
import {
renderModelTag,
stringToColor,
calculateModelPrice,
getLobeHubIcon,
} from '../../../../../helpers';
import {
renderLimitedItems,
renderDescription,
} from '../../../../common/ui/RenderUtils';
function renderQuotaType(type, t) {
switch (type) {
case 3:
return (
<Tag color='blue' shape='circle'>
{t('按分辨率计费')}
</Tag>
);
case 2:
return (
<Tag color='green' shape='circle'>
{t('按秒计费')}
</Tag>
);
case 1:
return (
<Tag color='teal' shape='circle'>
{t('按次计费')}
</Tag>
);
case 0:
return (
<Tag color='violet' shape='circle'>
{t('按量计费')}
</Tag>
);
default:
return t('未知');
}
}
// Render vendor name
const renderVendor = (vendorName, vendorIcon, t) => {
if (!vendorName) return '-';
return (
<Tag
color='white'
shape='circle'
prefixIcon={getLobeHubIcon(vendorIcon || 'Layers', 14)}
>
{vendorName}
</Tag>
);
};
// Render tags list using RenderUtils
const renderTags = (text) => {
if (!text) return '-';
const tagsArr = text.split(',').filter((tag) => tag.trim());
return renderLimitedItems({
items: tagsArr,
renderItem: (tag, idx) => (
<Tag
key={idx}
color={stringToColor(tag.trim())}
shape='circle'
size='small'
>
{tag.trim()}
</Tag>
),
maxDisplay: 3,
});
};
function renderSupportedEndpoints(endpoints) {
if (!endpoints || endpoints.length === 0) {
return null;
}
return (
<Space wrap>
{endpoints.map((endpoint, idx) => (
<Tag key={endpoint} color={stringToColor(endpoint)} shape='circle'>
{endpoint}
</Tag>
))}
</Space>
);
}
export const getPricingTableColumns = ({
t,
selectedGroup,
groupRatio,
groupModelDiscount,
copyText,
setModalImageUrl,
setIsModalOpenurl,
currency,
tokenUnit,
displayPrice,
showRatio,
isMobile = false,
}) => {
const priceDataCache = new WeakMap();
const getPriceData = (record) => {
let cache = priceDataCache.get(record);
if (!cache) {
cache = calculateModelPrice({
record,
selectedGroup,
groupRatio,
groupModelDiscount,
tokenUnit,
displayPrice,
currency,
});
priceDataCache.set(record, cache);
}
return cache;
};
const endpointColumn = {
title: t('可用端点类型'),
dataIndex: 'supported_endpoint_types',
render: (text, record, index) => {
return renderSupportedEndpoints(text);
},
};
const modelNameColumn = {
title: t('模型名称'),
dataIndex: 'model_name',
render: (text, record, index) => {
return renderModelTag(text, {
onClick: () => {
copyText(text);
},
});
},
onFilter: (value, record) =>
record.model_name.toLowerCase().includes(value.toLowerCase()),
};
const quotaColumn = {
title: t('计费类型'),
dataIndex: 'quota_type',
render: (text, record, index) => {
return renderQuotaType(parseInt(text), t);
},
sorter: (a, b) => a.quota_type - b.quota_type,
};
const descriptionColumn = {
title: t('描述'),
dataIndex: 'description',
render: (text) => renderDescription(text, 200),
};
const tagsColumn = {
title: t('标签'),
dataIndex: 'tags',
render: renderTags,
};
const vendorColumn = {
title: t('供应商'),
dataIndex: 'vendor_name',
render: (text, record) => renderVendor(text, record.vendor_icon, t),
};
const baseColumns = [
modelNameColumn,
vendorColumn,
descriptionColumn,
tagsColumn,
quotaColumn,
];
const ratioColumn = {
title: () => (
<div className='flex items-center space-x-1'>
<span>{t('倍率')}</span>
<Tooltip content={t('倍率是为了方便换算不同价格的模型')}>
<IconHelpCircle
className='text-blue-500 cursor-pointer'
onClick={() => {
setModalImageUrl('/ratio.png');
setIsModalOpenurl(true);
}}
/>
</Tooltip>
</div>
),
dataIndex: 'model_ratio',
render: (text, record, index) => {
const completionRatio = parseFloat(record.completion_ratio.toFixed(3));
const priceData = getPriceData(record);
return (
<div className='space-y-1'>
<div className='text-gray-700'>
{t('模型倍率')}:{record.quota_type === 0 ? text : t('无')}
</div>
<div className='text-gray-700'>
{t('补全倍率')}:
{record.quota_type === 0 ? completionRatio : t('无')}
</div>
<div className='text-gray-700'>
{t('分组倍率')}:{priceData?.usedGroupRatio ?? '-'}
</div>
</div>
);
},
};
const priceColumn = {
title: t('模型价格'),
dataIndex: 'model_price',
...(isMobile ? {} : { fixed: 'right' }),
render: (text, record, index) => {
const priceData = getPriceData(record);
if (priceData.isPerSecond) {
const videoTiers = Array.isArray(priceData.videoTiers)
? priceData.videoTiers
: [];
if (videoTiers.length === 0) {
return <div className='text-gray-700'>-</div>;
}
return (
<div className='space-y-1'>
{videoTiers.map((tier) => (
<div key={tier.key} className='text-gray-700'>
{tier.label}:{tier.price} / {t('秒')}
</div>
))}
</div>
);
}
if (priceData.isPerImageResolution) {
const imageTiers = Array.isArray(priceData.imageTiers)
? priceData.imageTiers
: [];
if (imageTiers.length === 0) {
return <div className='text-gray-700'>-</div>;
}
return (
<div className='space-y-1'>
{imageTiers.map((tier) => (
<div key={tier.key} className='text-gray-700'>
{tier.label}:{tier.price} / {t('张')}
</div>
))}
</div>
);
}
if (priceData.isPerToken) {
const extraPrices = Array.isArray(priceData.extraPrices)
? priceData.extraPrices
: [];
return (
<div className='space-y-1'>
<div className='text-gray-700'>
{t('输入')} {priceData.inputPrice} / 1{priceData.unitLabel} tokens
</div>
<div className='text-gray-700'>
{t('输出')} {priceData.completionPrice} / 1{priceData.unitLabel}{' '}
tokens
</div>
{extraPrices.map((item) => (
<div key={item.key} className='text-gray-700'>
{t(item.labelKey)} {item.price} / 1{priceData.unitLabel} tokens
</div>
))}
</div>
);
} else {
return (
<div className='text-gray-700'>
{t('模型价格')}:{priceData.price}
</div>
);
}
},
};
const columns = [...baseColumns];
columns.push(endpointColumn);
if (showRatio) {
columns.push(ratioColumn);
}
columns.push(priceColumn);
return columns;
};
@@ -0,0 +1,277 @@
/*
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, { useState } from 'react';
import MissingModelsModal from './modals/MissingModelsModal';
import PrefillGroupManagement from './modals/PrefillGroupManagement';
import EditPrefillGroupModal from './modals/EditPrefillGroupModal';
import BatchCategoryModal from './modals/BatchCategoryModal';
import { Button, Modal, Popover } from '@douyinfe/semi-ui';
import { showSuccess, showError, copy, isRoot } from '../../../helpers';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
import SelectionNotification from './components/SelectionNotification';
import UpstreamConflictModal from './modals/UpstreamConflictModal';
import SyncWizardModal from './modals/SyncWizardModal';
const ModelsActions = ({
selectedKeys,
setSelectedKeys,
setEditingModel,
setShowEdit,
batchDeleteModels,
batchUpdateCategory,
syncing,
previewing,
syncUpstream,
previewUpstreamDiff,
applyUpstreamOverwrite,
compactMode,
setCompactMode,
t,
}) => {
// Modal states
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showMissingModal, setShowMissingModal] = useState(false);
const [showGroupManagement, setShowGroupManagement] = useState(false);
const [showAddPrefill, setShowAddPrefill] = useState(false);
const [showCategoryModal, setShowCategoryModal] = useState(false);
const [prefillInit, setPrefillInit] = useState({ id: undefined });
const [showConflict, setShowConflict] = useState(false);
const [conflicts, setConflicts] = useState([]);
const [showSyncModal, setShowSyncModal] = useState(false);
const [syncLocale, setSyncLocale] = useState('zh');
const handleSyncUpstream = async (locale) => {
// 先预览
const data = await previewUpstreamDiff?.({ locale });
const conflictItems = data?.conflicts || [];
if (conflictItems.length > 0) {
setConflicts(conflictItems);
setShowConflict(true);
return;
}
// 无冲突,直接同步缺失
await syncUpstream?.({ locale });
};
// Handle delete selected models with confirmation
const handleDeleteSelectedModels = () => {
setShowDeleteModal(true);
};
// Handle delete confirmation
const handleConfirmDelete = () => {
batchDeleteModels();
setShowDeleteModal(false);
};
// Handle clear selection
const handleClearSelected = () => {
setSelectedKeys([]);
};
// Handle add selected models to prefill group
const handleCopyNames = async () => {
const text = selectedKeys.map((m) => m.model_name).join(',');
if (!text) return;
const ok = await copy(text);
if (ok) {
showSuccess(t('已复制模型名称'));
} else {
showError(t('复制失败'));
}
};
const handleAddToPrefill = () => {
// Prepare initial data
const items = selectedKeys.map((m) => m.model_name);
setPrefillInit({ id: undefined, type: 'model', items });
setShowAddPrefill(true);
};
return (
<>
<div className='flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1'>
{isRoot() && (
<Button
type='primary'
className='flex-1 md:flex-initial'
onClick={() => {
setEditingModel({
id: undefined,
});
setShowEdit(true);
}}
size='small'
>
{t('添加模型')}
</Button>
)}
<Button
type='secondary'
className='flex-1 md:flex-initial'
size='small'
onClick={() => setShowMissingModal(true)}
>
{t('未配置模型')}
</Button>
{isRoot() && (
<Popover
position='bottom'
trigger='hover'
content={
<div className='p-2 max-w-[360px]'>
<div className='text-[var(--semi-color-text-2)] text-sm'>
{t(
'模型社区需要大家的共同维护,如发现数据有误或想贡献新的模型数据,请访问:',
)}
</div>
<a
href='https://github.com/basellm/llm-metadata'
target='_blank'
rel='noreferrer'
className='text-blue-600 underline'
>
https://github.com/basellm/llm-metadata
</a>
</div>
}
>
<Button
type='secondary'
className='flex-1 md:flex-initial'
size='small'
loading={syncing || previewing}
onClick={() => {
setSyncLocale('zh');
setShowSyncModal(true);
}}
>
{t('同步')}
</Button>
</Popover>
)}
{isRoot() && (
<Button
type='secondary'
className='flex-1 md:flex-initial'
size='small'
onClick={() => setShowGroupManagement(true)}
>
{t('预填组管理')}
</Button>
)}
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
<SelectionNotification
selectedKeys={selectedKeys}
t={t}
onDelete={handleDeleteSelectedModels}
onAddPrefill={handleAddToPrefill}
onSetCategory={() => setShowCategoryModal(true)}
onClear={handleClearSelected}
onCopy={handleCopyNames}
/>
<Modal
title={t('批量删除模型')}
visible={showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
onOk={handleConfirmDelete}
type='warning'
>
<div>
{t('确定要删除所选的 {{count}} 个模型吗?', {
count: selectedKeys.length,
})}
</div>
</Modal>
<SyncWizardModal
visible={showSyncModal}
onClose={() => setShowSyncModal(false)}
loading={syncing || previewing}
t={t}
onConfirm={async ({ option, locale }) => {
setSyncLocale(locale);
if (option === 'official') {
await handleSyncUpstream(locale);
}
setShowSyncModal(false);
}}
/>
<MissingModelsModal
visible={showMissingModal}
onClose={() => setShowMissingModal(false)}
onConfigureModel={(name) => {
setEditingModel({ id: undefined, model_name: name });
setShowEdit(true);
setShowMissingModal(false);
}}
t={t}
/>
<PrefillGroupManagement
visible={showGroupManagement}
onClose={() => setShowGroupManagement(false)}
/>
<EditPrefillGroupModal
visible={showAddPrefill}
onClose={() => setShowAddPrefill(false)}
editingGroup={prefillInit}
onSuccess={() => setShowAddPrefill(false)}
/>
<UpstreamConflictModal
visible={showConflict}
onClose={() => setShowConflict(false)}
conflicts={conflicts}
onSubmit={async (payload) => {
return await applyUpstreamOverwrite?.({
overwrite: payload,
locale: syncLocale,
});
}}
t={t}
loading={syncing}
/>
<BatchCategoryModal
visible={showCategoryModal}
onClose={() => setShowCategoryModal(false)}
selectedModels={selectedKeys}
onConfirm={batchUpdateCategory}
t={t}
/>
</>
);
};
export default ModelsActions;
@@ -0,0 +1,190 @@
/*
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, { useState, useEffect } from 'react';
import {
Card,
Row,
Col,
Typography,
Tag,
Spin,
Empty,
} from '@douyinfe/semi-ui';
import { API, showError } from '../../../helpers';
import { MODEL_CATEGORY_NAMES } from '../../../constants';
const { Title, Text } = Typography;
const ModelsCategoryStats = ({ t }) => {
const [stats, setStats] = useState({});
const [loading, setLoading] = useState(false);
const loadStats = async () => {
setLoading(true);
try {
const res = await API.get('/api/models/category-stats');
const { success, message, data } = res.data;
if (success) {
setStats(data || {});
} else {
showError(message || t('获取统计数据失败'));
}
} catch (error) {
console.error('Load category stats failed:', error);
showError(t('获取统计数据失败'));
}
setLoading(false);
};
useEffect(() => {
loadStats();
}, []);
const getCategoryColor = (category) => {
const colorMap = {
text_generation: 'blue',
image_generation: 'purple',
video_generation: 'pink',
audio_tts: 'cyan',
audio_stt: 'teal',
audio_generation: 'green',
embedding: 'violet',
multimodal: 'indigo',
rerank: 'orange',
other: 'grey',
};
return colorMap[category] || 'grey';
};
const totalModels = Object.values(stats).reduce(
(sum, count) => sum + count,
0,
);
if (loading) {
return (
<Card style={{ marginBottom: '16px' }}>
<div style={{ textAlign: 'center', padding: '20px' }}>
<Spin />
</div>
</Card>
);
}
if (totalModels === 0) {
return (
<Card style={{ marginBottom: '16px' }}>
<Empty description={t('暂无模型数据')} />
</Card>
);
}
return (
<Card
title={
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Title heading={5} style={{ margin: 0 }}>
{t('模型分类统计')}
</Title>
<Tag color='blue' size='large'>
{t('总计')}: {totalModels}
</Tag>
</div>
}
style={{ marginBottom: '16px' }}
>
<Row gutter={[16, 16]}>
{Object.entries(MODEL_CATEGORY_NAMES).map(([category, name]) => {
const count = stats[category] || 0;
const percentage =
totalModels > 0 ? ((count / totalModels) * 100).toFixed(1) : 0;
return (
<Col key={category} xs={24} sm={12} md={8} lg={6} xl={4}>
<div
style={{
padding: '12px',
borderRadius: '8px',
background: 'var(--semi-color-fill-0)',
border: '1px solid var(--semi-color-border)',
transition: 'all 0.3s',
cursor: 'pointer',
}}
onMouseEnter={(e) => {
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow =
'0 4px 12px rgba(0,0,0,0.1)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '8px',
}}
>
<Tag
color={getCategoryColor(category)}
size='small'
style={{ marginRight: '8px' }}
>
{name}
</Tag>
</div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'baseline',
}}
>
<Text
strong
style={{
fontSize: '24px',
color: 'var(--semi-color-text-0)',
}}
>
{count}
</Text>
<Text type='tertiary' size='small'>
{percentage}%
</Text>
</div>
</div>
</Col>
);
})}
</Row>
</Card>
);
};
export default ModelsCategoryStats;
@@ -0,0 +1,454 @@
/*
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,
Space,
Tag,
Typography,
Modal,
Tooltip,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
getLobeHubIcon,
stringToColor,
isRoot,
} from '../../../helpers';
import {
renderLimitedItems,
renderDescription,
} from '../../common/ui/RenderUtils';
const { Text } = Typography;
// Render timestamp
function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>;
}
// Render model icon column: prefer model.icon, then fallback to vendor icon
const renderModelIconCol = (record, vendorMap) => {
const iconKey = record?.icon || vendorMap[record?.vendor_id]?.icon;
if (!iconKey) return '-';
return (
<div className='flex items-center justify-center'>
{getLobeHubIcon(iconKey, 20)}
</div>
);
};
// Render vendor column with icon
const renderVendorTag = (vendorId, vendorMap, t) => {
if (!vendorId || !vendorMap[vendorId]) return '-';
const v = vendorMap[vendorId];
return (
<Tag
color='white'
shape='circle'
prefixIcon={getLobeHubIcon(v.icon || 'Layers', 14)}
>
{v.name}
</Tag>
);
};
// Render categories (multiple)
const renderCategories = (categories, t, categoryNames) => {
if (!categories || categories.length === 0) {
return (
<Tag color='grey' size='small' shape='circle'>
{t('未分类')}
</Tag>
);
}
const colorMap = {
text_generation: 'blue',
image_generation: 'purple',
t_g_i: 'purple',
i_g_i: 'violet',
video_generation: 'pink',
t_g_v: 'pink',
i_g_v: 'red',
audio_tts: 'cyan',
audio_stt: 'teal',
audio_generation: 'green',
embedding: 'violet',
multimodal: 'indigo',
rerank: 'orange',
other: 'grey',
};
// If categories is a single string (legacy), convert to array
const categoriesArray = Array.isArray(categories) ? categories : [categories];
return renderLimitedItems({
items: categoriesArray,
renderItem: (category, idx) => {
const categoryName = categoryNames[category] || category;
return (
<Tag
key={idx}
color={colorMap[category] || 'grey'}
size='small'
shape='circle'
>
{categoryName}
</Tag>
);
},
maxDisplay: 3,
});
};
// Render groups (enable_groups)
const renderGroups = (groups) => {
if (!groups || groups.length === 0) return '-';
return renderLimitedItems({
items: groups,
renderItem: (g, idx) => (
<Tag key={idx} size='small' shape='circle' color={stringToColor(g)}>
{g}
</Tag>
),
});
};
// Render tags
const renderTags = (text) => {
if (!text) return '-';
const tagsArr = text.split(',').filter(Boolean);
return renderLimitedItems({
items: tagsArr,
renderItem: (tag, idx) => (
<Tag key={idx} size='small' shape='circle' color={stringToColor(tag)}>
{tag}
</Tag>
),
});
};
// Render endpoints (supports object map or legacy array)
const renderEndpoints = (value) => {
try {
const parsed = typeof value === 'string' ? JSON.parse(value) : value;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
const keys = Object.keys(parsed || {});
if (keys.length === 0) return '-';
return renderLimitedItems({
items: keys,
renderItem: (key, idx) => (
<Tag key={idx} size='small' shape='circle' color={stringToColor(key)}>
{key}
</Tag>
),
maxDisplay: 3,
});
}
if (Array.isArray(parsed)) {
if (parsed.length === 0) return '-';
return renderLimitedItems({
items: parsed,
renderItem: (ep, idx) => (
<Tag key={idx} color='white' size='small' shape='circle'>
{ep}
</Tag>
),
maxDisplay: 3,
});
}
return value || '-';
} catch (_) {
return value || '-';
}
};
// Render quota types (array) using common limited items renderer
const renderQuotaTypes = (arr, t) => {
if (!Array.isArray(arr) || arr.length === 0) return '-';
return renderLimitedItems({
items: arr,
renderItem: (qt, idx) => {
if (qt === 1) {
return (
<Tag key={`${qt}-${idx}`} color='teal' size='small' shape='circle'>
{t('按次计费')}
</Tag>
);
}
if (qt === 0) {
return (
<Tag key={`${qt}-${idx}`} color='violet' size='small' shape='circle'>
{t('按量计费')}
</Tag>
);
}
if (qt === 2) {
return (
<Tag key={`${qt}-${idx}`} color='green' size='small' shape='circle'>
{t('按秒计费')}
</Tag>
);
}
if (qt === 3) {
return (
<Tag key={`${qt}-${idx}`} color='blue' size='small' shape='circle'>
{t('按分辨率计费')}
</Tag>
);
}
return (
<Tag key={`${qt}-${idx}`} color='white' size='small' shape='circle'>
{qt}
</Tag>
);
},
maxDisplay: 3,
});
};
// Render bound channels
const renderBoundChannels = (channels) => {
if (!channels || channels.length === 0) return '-';
return renderLimitedItems({
items: channels,
renderItem: (c, idx) => (
<Tag key={idx} color='white' size='small' shape='circle'>
{c.name}({c.type})
</Tag>
),
});
};
// Render operations column
const renderOperations = (
text,
record,
setEditingModel,
setShowEdit,
manageModel,
refresh,
t,
) => {
return (
<Space wrap>
{isRoot() && (
<>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={() => manageModel(record.id, 'disable', record)}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={() => manageModel(record.id, 'enable', record)}
>
{t('启用')}
</Button>
)}
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingModel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='danger'
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此模型?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
await manageModel(record.id, 'delete', record);
await refresh();
})();
},
});
}}
>
{t('删除')}
</Button>
</>
)}
</Space>
);
};
// 名称匹配类型渲染(带匹配数量 Tooltip)
const renderNameRule = (rule, record, t) => {
const map = {
0: { color: 'green', label: t('精确') },
1: { color: 'blue', label: t('前缀') },
2: { color: 'orange', label: t('包含') },
3: { color: 'purple', label: t('后缀') },
};
const cfg = map[rule];
if (!cfg) return '-';
let label = cfg.label;
if (rule !== 0 && record.matched_count) {
label = `${cfg.label} ${record.matched_count}${t('个模型')}`;
}
const tagElement = (
<Tag color={cfg.color} size='small' shape='circle'>
{label}
</Tag>
);
if (
rule === 0 ||
!record.matched_models ||
record.matched_models.length === 0
) {
return tagElement;
}
return (
<Tooltip content={record.matched_models.join(', ')} showArrow>
{tagElement}
</Tooltip>
);
};
export const getModelsColumns = ({
t,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
categoryNames = {},
}) => {
return [
{
title: t('图标'),
dataIndex: 'icon',
width: 70,
align: 'center',
render: (text, record) => renderModelIconCol(record, vendorMap),
},
{
title: t('模型名称'),
dataIndex: 'model_name',
render: (text) => (
<Text copyable onClick={(e) => e.stopPropagation()}>
{text}
</Text>
),
},
{
title: t('匹配类型'),
dataIndex: 'name_rule',
render: (val, record) => renderNameRule(val, record, t),
},
{
title: t('参与官方同步'),
dataIndex: 'sync_official',
render: (val) => (
<Tag size='small' shape='circle' color={val === 1 ? 'green' : 'orange'}>
{val === 1 ? t('是') : t('否')}
</Tag>
),
},
{
title: t('描述'),
dataIndex: 'description',
render: (text) => renderDescription(text, 200),
},
{
title: t('供应商'),
dataIndex: 'vendor_id',
render: (vendorId, record) => renderVendorTag(vendorId, vendorMap, t),
},
{
title: t('分类'),
dataIndex: 'categories',
render: (categories) => renderCategories(categories, t, categoryNames),
},
{
title: t('标签'),
dataIndex: 'tags',
render: renderTags,
},
{
title: t('端点'),
dataIndex: 'endpoints',
render: renderEndpoints,
},
{
title: t('已绑定渠道'),
dataIndex: 'bound_channels',
render: renderBoundChannels,
},
{
title: t('可用分组'),
dataIndex: 'enable_groups',
render: renderGroups,
},
{
title: t('计费类型'),
dataIndex: 'quota_types',
render: (qts) => renderQuotaTypes(qts, t),
},
{
title: t('创建时间'),
dataIndex: 'created_time',
render: (text, record, index) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: t('更新时间'),
dataIndex: 'updated_time',
render: (text, record, index) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) =>
renderOperations(
text,
record,
setEditingModel,
setShowEdit,
manageModel,
refresh,
t,
),
},
];
};
@@ -0,0 +1,44 @@
/*
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 { Typography } from '@douyinfe/semi-ui';
import { Layers } from 'lucide-react';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const ModelsDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center text-green-500'>
<Layers size={16} className='mr-2' />
<Text>{t('模型管理')}</Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default ModelsDescription;
@@ -0,0 +1,125 @@
/*
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, { useRef } from 'react';
import { Form, Button } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
import { MODEL_CATEGORY_NAMES } from '../../../constants';
const ModelsFilters = ({
formInitValues,
setFormApi,
searchModels,
loading,
searching,
t,
}) => {
// Handle form reset and immediate search
const formApiRef = useRef(null);
const handleReset = () => {
if (!formApiRef.current) return;
formApiRef.current.reset();
setTimeout(() => {
searchModels();
}, 100);
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => {
setFormApi(api);
formApiRef.current = api;
}}
onSubmit={searchModels}
allowEmpty={true}
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className='w-full md:w-auto order-1 md:order-2'
>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto'>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('搜索模型名称')}
showClear
pure
size='small'
/>
</div>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchVendor'
prefix={<IconSearch />}
placeholder={t('搜索供应商')}
showClear
pure
size='small'
/>
</div>
<div className='relative w-full md:w-56'>
<Form.Select
field='searchCategory'
placeholder={t('选择分类')}
showClear
pure
size='small'
style={{ width: '100%' }}
>
<Form.Select.Option value=''>{t('全部分类')}</Form.Select.Option>
{Object.entries(MODEL_CATEGORY_NAMES).map(([key, name]) => (
<Form.Select.Option key={key} value={key}>
{name}
</Form.Select.Option>
))}
</Form.Select>
</div>
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading || searching}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={handleReset}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
);
};
export default ModelsFilters;
+121
View File
@@ -0,0 +1,121 @@
/*
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 } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getModelsColumns } from './ModelsColumnDefs';
import { useModelCategories } from '../../../hooks/models/useModelCategories';
const ModelsTable = (modelsData) => {
const {
models,
loading,
activePage,
pageSize,
modelCount,
compactMode,
handlePageChange,
handlePageSizeChange,
rowSelection,
handleRow,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
t,
} = modelsData;
// 加载分类名称映射
const { categoryNames } = useModelCategories();
// Get all columns
const columns = useMemo(() => {
return getModelsColumns({
t,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
categoryNames,
});
}, [
t,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
categoryNames,
]);
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
<CardTable
columns={tableColumns}
dataSource={models}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: modelCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
size='middle'
/>
);
};
export default ModelsTable;
+189
View File
@@ -0,0 +1,189 @@
/*
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 { Tabs, TabPane, Tag, Button, Dropdown, Modal } from '@douyinfe/semi-ui';
import { IconEdit, IconDelete } from '@douyinfe/semi-icons';
import {
getLobeHubIcon,
showError,
showSuccess,
isRoot,
} from '../../../helpers';
import { API } from '../../../helpers';
const ModelsTabs = ({
activeVendorKey,
setActiveVendorKey,
vendorCounts,
vendors,
loadModels,
activePage,
pageSize,
setActivePage,
setShowAddVendor,
setShowEditVendor,
setEditingVendor,
loadVendors,
t,
}) => {
const canManageVendors = isRoot();
const handleTabChange = (key) => {
setActiveVendorKey(key);
setActivePage(1);
loadModels(1, pageSize, key);
};
const handleEditVendor = (vendor, e) => {
e.stopPropagation(); // 阻止事件冒泡,避免触发tab切换
setEditingVendor(vendor);
setShowEditVendor(true);
};
const handleDeleteVendor = async (vendor, e) => {
e.stopPropagation(); // 阻止事件冒泡,避免触发tab切换
try {
const res = await API.delete(`/api/vendors/${vendor.id}`);
if (res.data.success) {
showSuccess(t('供应商删除成功'));
// 如果删除的是当前选中的供应商,切换到"全部"
if (activeVendorKey === String(vendor.id)) {
setActiveVendorKey('all');
loadModels(1, pageSize, 'all');
} else {
loadModels(activePage, pageSize, activeVendorKey);
}
loadVendors(); // 重新加载供应商列表
} else {
showError(res.data.message || t('删除失败'));
}
} catch (error) {
showError(error.response?.data?.message || t('删除失败'));
}
};
return (
<Tabs
activeKey={activeVendorKey}
type='card'
collapsible
onChange={handleTabChange}
className='mb-2'
tabBarExtraContent={
canManageVendors && (
<Button
type='primary'
size='small'
onClick={() => setShowAddVendor(true)}
>
{t('新增供应商')}
</Button>
)
}
>
<TabPane
itemKey='all'
tab={
<span className='flex items-center gap-2'>
{t('全部')}
<Tag
color={activeVendorKey === 'all' ? 'red' : 'grey'}
shape='circle'
>
{vendorCounts['all'] || 0}
</Tag>
</span>
}
/>
{vendors.map((vendor) => {
const key = String(vendor.id);
const count = vendorCounts[vendor.id] || 0;
return (
<TabPane
key={key}
itemKey={key}
tab={
<span className='flex items-center gap-2'>
{getLobeHubIcon(vendor.icon || 'Layers', 14)}
{vendor.name}
<Tag
color={activeVendorKey === key ? 'red' : 'grey'}
shape='circle'
>
{count}
</Tag>
{canManageVendors && (
<Dropdown
trigger='click'
position='bottomRight'
render={
<Dropdown.Menu>
<Dropdown.Item
icon={<IconEdit />}
onClick={(e) => handleEditVendor(vendor, e)}
>
{t('编辑')}
</Dropdown.Item>
<Dropdown.Item
type='danger'
icon={<IconDelete />}
onClick={(e) => {
e.stopPropagation();
Modal.confirm({
title: t('确认删除'),
content: t(
'确定要删除供应商 "{{name}}" 吗?此操作不可撤销。',
{ name: vendor.name },
),
onOk: () => handleDeleteVendor(vendor, e),
okText: t('删除'),
cancelText: t('取消'),
type: 'warning',
okType: 'danger',
});
}}
>
{t('删除')}
</Dropdown.Item>
</Dropdown.Menu>
}
onClickOutSide={(e) => e.stopPropagation()}
>
<Button
size='small'
type='tertiary'
theme='outline'
onClick={(e) => e.stopPropagation()}
>
{t('操作')}
</Button>
</Dropdown>
)}
</span>
}
/>
);
})}
</Tabs>
);
};
export default ModelsTabs;
@@ -0,0 +1,116 @@
/*
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 } from 'react';
import { Notification, Button, Space, Typography } from '@douyinfe/semi-ui';
import { isRoot } from '../../../../helpers';
// 固定通知 ID,保持同一个实例即可避免闪烁
const NOTICE_ID = 'models-batch-actions';
/**
* SelectionNotification 选择通知组件
* 1. 当 selectedKeys.length > 0 时,使用固定 id 创建/更新通知
* 2. 当 selectedKeys 清空时关闭通知
*/
const SelectionNotification = ({
selectedKeys = [],
t,
onDelete,
onAddPrefill,
onSetCategory,
onClear,
onCopy,
}) => {
// 根据选中数量决定显示/隐藏或更新通知
useEffect(() => {
const selectedCount = selectedKeys.length;
if (selectedCount > 0) {
const titleNode = (
<Space wrap>
<span>{t('批量操作')}</span>
<Typography.Text type='tertiary' size='small'>
{t('已选择 {{count}} 个模型', { count: selectedCount })}
</Typography.Text>
</Space>
);
const content = (
<Space wrap>
<Button size='small' type='tertiary' theme='solid' onClick={onClear}>
{t('取消全选')}
</Button>
{isRoot() && (
<Button
size='small'
type='primary'
theme='solid'
onClick={onAddPrefill}
>
{t('加入预填组')}
</Button>
)}
{isRoot() && (
<Button
size='small'
type='warning'
theme='solid'
onClick={onSetCategory}
>
{t('设置分类')}
</Button>
)}
<Button size='small' type='secondary' theme='solid' onClick={onCopy}>
{t('复制名称')}
</Button>
{isRoot() && (
<Button size='small' type='danger' theme='solid' onClick={onDelete}>
{t('删除所选')}
</Button>
)}
</Space>
);
// 使用相同 id 更新通知(若已存在则就地更新,不存在则创建)
Notification.info({
id: NOTICE_ID,
title: titleNode,
content,
duration: 0, // 不自动关闭
position: 'bottom',
showClose: false,
});
} else {
// 取消全部勾选时关闭通知
Notification.close(NOTICE_ID);
}
}, [selectedKeys, t, onDelete, onAddPrefill, onSetCategory, onClear, onCopy]);
// 卸载时确保关闭通知
useEffect(() => {
return () => {
Notification.close(NOTICE_ID);
};
}, []);
return null; // 该组件不渲染可见内容
};
export default SelectionNotification;
+151
View File
@@ -0,0 +1,151 @@
/*
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 ModelsTable from './ModelsTable';
import ModelsActions from './ModelsActions';
import ModelsFilters from './ModelsFilters';
import ModelsTabs from './ModelsTabs';
import ModelsCategoryStats from './ModelsCategoryStats';
import EditModelModal from './modals/EditModelModal';
import EditVendorModal from './modals/EditVendorModal';
import { useModelsData } from '../../../hooks/models/useModelsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
const ModelsPage = () => {
const modelsData = useModelsData();
const isMobile = useIsMobile();
const {
// Edit state
showEdit,
editingModel,
closeEdit,
refresh,
// Actions state
selectedKeys,
setSelectedKeys,
setEditingModel,
setShowEdit,
batchDeleteModels,
// Filters state
formInitValues,
setFormApi,
searchModels,
loading,
searching,
// Description state
compactMode,
setCompactMode,
// Vendor state
showAddVendor,
setShowAddVendor,
showEditVendor,
setShowEditVendor,
editingVendor,
setEditingVendor,
loadVendors,
// Translation
t,
} = modelsData;
return (
<>
<EditModelModal
refresh={refresh}
editingModel={editingModel}
visiable={showEdit}
handleClose={closeEdit}
/>
<EditVendorModal
visible={showAddVendor || showEditVendor}
handleClose={() => {
setShowAddVendor(false);
setShowEditVendor(false);
setEditingVendor({ id: undefined });
}}
editingVendor={showEditVendor ? editingVendor : { id: undefined }}
refresh={() => {
loadVendors();
refresh();
}}
/>
<ModelsCategoryStats t={t} />
<CardPro
type='type3'
tabsArea={<ModelsTabs {...modelsData} />}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<ModelsActions
selectedKeys={selectedKeys}
setSelectedKeys={setSelectedKeys}
setEditingModel={setEditingModel}
setShowEdit={setShowEdit}
batchDeleteModels={batchDeleteModels}
batchUpdateCategory={modelsData.batchUpdateCategory}
syncing={modelsData.syncing}
syncUpstream={modelsData.syncUpstream}
previewing={modelsData.previewing}
previewUpstreamDiff={modelsData.previewUpstreamDiff}
applyUpstreamOverwrite={modelsData.applyUpstreamOverwrite}
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<ModelsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchModels={searchModels}
loading={loading}
searching={searching}
t={t}
/>
</div>
</div>
}
paginationArea={createCardProPagination({
currentPage: modelsData.activePage,
pageSize: modelsData.pageSize,
total: modelsData.modelCount,
onPageChange: modelsData.handlePageChange,
onPageSizeChange: modelsData.handlePageSizeChange,
isMobile: isMobile,
t: modelsData.t,
})}
t={modelsData.t}
>
<ModelsTable {...modelsData} />
</CardPro>
</>
);
};
export default ModelsPage;
@@ -0,0 +1,191 @@
/*
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, { useState, useEffect } from 'react';
import { Modal, Select, Typography, Spin } from '@douyinfe/semi-ui';
import { API, showError } from '../../../../helpers';
const { Text } = Typography;
const BatchCategoryModal = ({
visible,
onClose,
selectedModels,
onConfirm,
t,
}) => {
const [selectedCategories, setSelectedCategories] = useState([]);
const [loading, setLoading] = useState(false);
const [categoriesLoading, setCategoriesLoading] = useState(false);
const [level1Categories, setLevel1Categories] = useState([]);
const [level2Categories, setLevel2Categories] = useState([]);
// 加载分类数据
const loadCategories = async () => {
setCategoriesLoading(true);
try {
const res = await API.get('/api/model_categories/flat');
const { success, data, message } = res.data;
if (success) {
const categoriesData = data || [];
// 分离一级和二级分类,只保留启用的分类
const level1 = categoriesData.filter(
(cat) => cat.parent_id === 0 && cat.status === 1,
);
const level2 = categoriesData.filter(
(cat) => cat.parent_id !== 0 && cat.status === 1,
);
setLevel1Categories(level1);
setLevel2Categories(level2);
} else {
showError(message || t('加载分类失败'));
}
} catch (error) {
showError(t('加载分类失败: ') + error.message);
} finally {
setCategoriesLoading(false);
}
};
// 当弹窗打开时加载分类
useEffect(() => {
if (visible) {
loadCategories();
}
}, [visible]);
const handleConfirm = async () => {
if (selectedCategories.length === 0) return;
setLoading(true);
try {
await onConfirm(selectedCategories);
setSelectedCategories([]);
onClose();
} finally {
setLoading(false);
}
};
const handleClose = () => {
setSelectedCategories([]);
onClose();
};
// 按一级分类分组二级分类
const groupedCategories = level1Categories
.map((level1) => {
const children = level2Categories.filter(
(level2) => level2.parent_id === level1.id,
);
return {
label: level1.category_name,
children: children.map((cat) => ({
label: cat.category_name,
value: cat.category_key,
})),
};
})
.filter((group) => group.children.length > 0); // 只显示有子分类的一级分类
return (
<Modal
title={t('批量设置模型分类')}
visible={visible}
onCancel={handleClose}
onOk={handleConfirm}
okText={t('确定')}
cancelText={t('取消')}
confirmLoading={loading}
okButtonProps={{ disabled: selectedCategories.length === 0 }}
>
<Spin spinning={categoriesLoading}>
<div className='space-y-4'>
<Text>
{t('已选择 {{count}} 个模型', { count: selectedModels.length })}
</Text>
<div className='mt-4'>
<Text strong style={{ display: 'block', marginBottom: '8px' }}>
{t('选择分类(可多选)')}:
</Text>
<Select
value={selectedCategories}
onChange={setSelectedCategories}
placeholder={
categoriesLoading
? t('加载中...')
: t('请选择一个或多个模型分类')
}
style={{ width: '100%' }}
multiple
maxTagCount={3}
showClear
disabled={categoriesLoading}
filter
>
{groupedCategories.map((group) => (
<Select.OptGroup key={group.label} label={group.label}>
{group.children.map((option) => (
<Select.Option key={option.value} value={option.value}>
{option.label}
</Select.Option>
))}
</Select.OptGroup>
))}
</Select>
<Text
type='tertiary'
size='small'
style={{ display: 'block', marginTop: '8px' }}
>
{t('提示:只显示二级分类,按一级分类分组')}
</Text>
</div>
{selectedModels.length > 0 && (
<div className='mt-4 p-3 bg-gray-50 dark:bg-gray-800 rounded'>
<Text type='secondary' size='small'>
{t('将为以下模型设置分类')}:
</Text>
<div className='mt-2 max-h-40 overflow-y-auto'>
{selectedModels.slice(0, 10).map((model, index) => (
<div key={model.id} className='text-sm py-1'>
• {model.model_name}
</div>
))}
{selectedModels.length > 10 && (
<Text type='tertiary' size='small'>
{t('...还有 {{count}} 个', {
count: selectedModels.length - 10,
})}
</Text>
)}
</div>
</div>
)}
</div>
</Spin>
</Modal>
);
};
export default BatchCategoryModal;
@@ -0,0 +1,696 @@
/*
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, { useState, useEffect, useRef, useMemo } from 'react';
import JSONEditor from '../../../common/ui/JSONEditor';
import {
SideSheet,
Form,
Button,
Space,
Spin,
Typography,
Card,
Tag,
Avatar,
Col,
Row,
} from '@douyinfe/semi-ui';
import { Save, X, FileText } from 'lucide-react';
import { IconLink } from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = Typography;
// Example endpoint template for quick fill
const ENDPOINT_TEMPLATE = {
openai: { path: '/v1/chat/completions', method: 'POST' },
'openai-response': { path: '/v1/responses', method: 'POST' },
anthropic: { path: '/v1/messages', method: 'POST' },
gemini: { path: '/v1beta/models/{model}:generateContent', method: 'POST' },
'jina-rerank': { path: '/rerank', method: 'POST' },
'image-generation': { path: '/v1/images/generations', method: 'POST' },
};
const nameRuleOptions = [
{ label: '精确名称匹配', value: 0 },
{ label: '前缀名称匹配', value: 1 },
{ label: '包含名称匹配', value: 2 },
{ label: '后缀名称匹配', value: 3 },
];
const EditModelModal = (props) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const isEdit = props.editingModel && props.editingModel.id !== undefined;
const placement = useMemo(() => (isEdit ? 'right' : 'left'), [isEdit]);
// 供应商列表
const [vendors, setVendors] = useState([]);
// 预填组(标签、端点)
const [tagGroups, setTagGroups] = useState([]);
const [endpointGroups, setEndpointGroups] = useState([]);
// 分类数据
const [level1Categories, setLevel1Categories] = useState([]);
const [level2Categories, setLevel2Categories] = useState([]);
const [allLevel2Categories, setAllLevel2Categories] = useState([]);
const [selectedLevel1Keys, setSelectedLevel1Keys] = useState([]);
// 获取供应商列表
const fetchVendors = async () => {
try {
const res = await API.get('/api/vendors/?page_size=1000'); // 获取全部供应商
if (res.data.success) {
const items = res.data.data.items || res.data.data || [];
setVendors(Array.isArray(items) ? items : []);
}
} catch (error) {
// ignore
}
};
// 获取分类数据
const fetchCategories = async () => {
try {
const res = await API.get('/api/model_categories/flat');
if (res.data.success) {
const categoriesData = res.data.data || [];
const level1 = categoriesData.filter((cat) => cat.parent_id === 0);
const level2 = categoriesData.filter((cat) => cat.parent_id !== 0);
setLevel1Categories(level1);
setAllLevel2Categories(level2);
}
} catch (error) {
// ignore
}
};
// 获取预填组(标签、端点)
const fetchPrefillGroups = async () => {
try {
const [tagRes, endpointRes] = await Promise.all([
API.get('/api/prefill_group?type=tag'),
API.get('/api/prefill_group?type=endpoint'),
]);
if (tagRes?.data?.success) {
setTagGroups(tagRes.data.data || []);
}
if (endpointRes?.data?.success) {
setEndpointGroups(endpointRes.data.data || []);
}
} catch (error) {
// ignore
}
};
useEffect(() => {
if (props.visiable) {
fetchVendors();
fetchPrefillGroups();
fetchCategories();
}
}, [props.visiable]);
const getInitValues = () => ({
model_name: props.editingModel?.model_name || '',
description: '',
icon: '',
tags: [],
vendor_id: undefined,
vendor: '',
vendor_icon: '',
categories: [],
level1_categories: [],
level2_categories: [],
endpoints: '',
name_rule: props.editingModel?.model_name ? 0 : undefined, // 通过未配置模型过来的固定为精确匹配
status: true,
sync_official: true,
});
const handleCancel = () => {
props.handleClose();
};
const loadModel = async () => {
if (!isEdit || !props.editingModel.id) return;
setLoading(true);
try {
const res = await API.get(`/api/models/${props.editingModel.id}`);
const { success, message, data } = res.data;
if (success) {
// 处理tags
if (data.tags) {
data.tags = data.tags.split(',').filter(Boolean);
} else {
data.tags = [];
}
// endpoints 保持原始 JSON 字符串,若为空设为空串
if (!data.endpoints) {
data.endpoints = '';
}
// 处理status/sync_official,将数字转为布尔值
data.status = data.status === 1;
data.sync_official = (data.sync_official ?? 1) === 1;
// 处理分类:从 categories 数组中分离出一级分类和二级分类
if (data.categories && Array.isArray(data.categories)) {
const level1Keys = [];
const level2Keys = [];
data.categories.forEach((categoryKey) => {
// 查找是一级还是二级分类
const isLevel1 = level1Categories.some(
(cat) => cat.category_key === categoryKey,
);
const isLevel2 = allLevel2Categories.some(
(cat) => cat.category_key === categoryKey,
);
if (isLevel1) {
level1Keys.push(categoryKey);
} else if (isLevel2) {
level2Keys.push(categoryKey);
}
});
data.level1_categories = level1Keys;
data.level2_categories = level2Keys;
// 设置选中的一级分类,用于过滤二级分类
setSelectedLevel1Keys(level1Keys);
// 更新可见的二级分类
if (level1Keys.length > 0) {
const level1Ids = level1Categories
.filter((cat) => level1Keys.includes(cat.category_key))
.map((cat) => cat.id);
const filtered = allLevel2Categories.filter((cat) =>
level1Ids.includes(cat.parent_id),
);
setLevel2Categories(filtered);
} else {
setLevel2Categories([]);
}
}
if (formApiRef.current) {
formApiRef.current.setValues({ ...getInitValues(), ...data });
}
} else {
showError(message);
}
} catch (error) {
showError(t('加载模型信息失败'));
}
setLoading(false);
};
useEffect(() => {
if (formApiRef.current) {
if (!isEdit) {
formApiRef.current.setValues({
...getInitValues(),
model_name: props.editingModel?.model_name || '',
});
}
}
}, [props.editingModel?.id, props.editingModel?.model_name]);
useEffect(() => {
if (props.visiable) {
if (isEdit) {
loadModel();
} else {
formApiRef.current?.setValues({
...getInitValues(),
model_name: props.editingModel?.model_name || '',
});
}
} else {
formApiRef.current?.reset();
}
}, [props.visiable, props.editingModel?.id, props.editingModel?.model_name]);
const submit = async (values) => {
setLoading(true);
try {
// 合并一级分类和二级分类到 categories 数组
const categories = [
...(values.level1_categories || []),
...(values.level2_categories || []),
];
const submitData = {
...values,
tags: Array.isArray(values.tags) ? values.tags.join(',') : values.tags,
endpoints: values.endpoints || '',
status: values.status ? 1 : 0,
sync_official: values.sync_official ? 1 : 0,
categories: categories, // 提交合并后的分类
};
// 删除临时字段
delete submitData.level1_categories;
delete submitData.level2_categories;
if (isEdit) {
submitData.id = props.editingModel.id;
const res = await API.put('/api/models/', submitData);
const { success, message } = res.data;
if (success) {
showSuccess(t('模型更新成功!'));
props.refresh();
props.handleClose();
} else {
showError(t(message));
}
} else {
const res = await API.post('/api/models/', submitData);
const { success, message } = res.data;
if (success) {
showSuccess(t('模型创建成功!'));
props.refresh();
props.handleClose();
} else {
showError(t(message));
}
}
} catch (error) {
showError(error.response?.data?.message || t('操作失败'));
}
setLoading(false);
formApiRef.current?.setValues(getInitValues());
};
return (
<SideSheet
placement={placement}
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新模型信息') : t('创建新的模型')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={props.visiable}
width={isMobile ? '100%' : 600}
footer={
<div className='flex justify-end'>
<Space>
<Button
theme='solid'
className='!rounded-lg'
onClick={() => formApiRef.current?.submitForm()}
icon={<Save size={16} />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
className='!rounded-lg'
type='primary'
onClick={handleCancel}
icon={<X size={16} />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
onCancel={() => handleCancel()}
>
<Spin spinning={loading}>
<Form
key={isEdit ? 'edit' : 'new'}
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
{({ values }) => (
<div className='p-2'>
{/* 基本信息 */}
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<FileText size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>
{t('设置模型的基本信息')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='model_name'
label={t('模型名称')}
placeholder={t('请输入模型名称,如:gpt-4')}
rules={[{ required: true, message: t('请输入模型名称') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.Select
field='name_rule'
label={t('名称匹配类型')}
placeholder={t('请选择名称匹配类型')}
optionList={nameRuleOptions.map((o) => ({
label: t(o.label),
value: o.value,
}))}
rules={[
{ required: true, message: t('请选择名称匹配类型') },
]}
extraText={t(
'根据模型名称和匹配规则查找模型元数据,优先级:精确 > 前缀 > 后缀 > 包含',
)}
style={{ width: '100%' }}
/>
</Col>
<Col span={24}>
<Form.Input
field='icon'
label={t('模型图标')}
placeholder={t('请输入图标名称')}
extraText={
<span>
{t(
"图标使用@lobehub/icons库,如:OpenAI、Claude.Color,支持链式参数:OpenAI.Avatar.type={'platform'}、OpenRouter.Avatar.shape={'square'},查询所有可用图标请 ",
)}
<Typography.Text
link={{
href: 'https://icons.lobehub.com/components/lobe-hub',
target: '_blank',
}}
icon={<IconLink />}
underline
>
{t('请点击我')}
</Typography.Text>
</span>
}
showClear
/>
</Col>
<Col span={24}>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('请输入模型描述')}
rows={3}
showClear
/>
</Col>
<Col span={24}>
<Form.TagInput
field='tags'
label={t('标签')}
placeholder={t('输入标签或使用","分隔多个标签')}
addOnBlur
showClear
onChange={(newTags) => {
if (!formApiRef.current) return;
const normalize = (tags) => {
if (!Array.isArray(tags)) return [];
return [
...new Set(
tags.flatMap((tag) =>
tag
.split(',')
.map((t) => t.trim())
.filter(Boolean),
),
),
];
};
const normalized = normalize(newTags);
formApiRef.current.setValue('tags', normalized);
}}
style={{ width: '100%' }}
{...(tagGroups.length > 0 && {
extraText: (
<Space wrap>
{tagGroups.map((group) => (
<Button
key={group.id}
size='small'
type='primary'
onClick={() => {
if (formApiRef.current) {
const currentTags =
formApiRef.current.getValue('tags') || [];
const newTags = [
...currentTags,
...(group.items || []),
];
const uniqueTags = [...new Set(newTags)];
formApiRef.current.setValue(
'tags',
uniqueTags,
);
}
}}
>
{group.name}
</Button>
))}
</Space>
),
})}
/>
</Col>
<Col span={24}>
<Form.Select
field='vendor_id'
label={t('供应商')}
placeholder={t('选择模型供应商')}
optionList={vendors.map((v) => ({
label: v.name,
value: v.id,
}))}
filter
showClear
onChange={(value) => {
const vendorInfo = vendors.find((v) => v.id === value);
if (vendorInfo && formApiRef.current) {
formApiRef.current.setValue(
'vendor',
vendorInfo.name,
);
}
}}
style={{ width: '100%' }}
/>
</Col>
<Col span={24}>
<Form.Select
field='level1_categories'
label={t('一级分类(可多选)')}
placeholder={t('选择一级分类')}
optionList={level1Categories.map((cat) => ({
label: cat.category_name,
value: cat.category_key,
}))}
multiple
maxTagCount={3}
showClear
style={{ width: '100%' }}
onChange={(values) => {
// 更新选中的一级分类keys
setSelectedLevel1Keys(values || []);
// 根据选中的一级分类过滤二级分类
if (values && values.length > 0) {
const level1Ids = level1Categories
.filter((cat) => values.includes(cat.category_key))
.map((cat) => cat.id);
const filtered = allLevel2Categories.filter((cat) =>
level1Ids.includes(cat.parent_id),
);
setLevel2Categories(filtered);
// 清除不在范围内的二级分类选择
if (formApiRef.current) {
const currentLevel2 =
formApiRef.current.getValue(
'level2_categories',
) || [];
const validLevel2 = currentLevel2.filter((key) =>
filtered.some((cat) => cat.category_key === key),
);
if (validLevel2.length !== currentLevel2.length) {
formApiRef.current.setValue(
'level2_categories',
validLevel2,
);
}
}
} else {
setLevel2Categories([]);
if (formApiRef.current) {
formApiRef.current.setValue(
'level2_categories',
[],
);
}
}
}}
extraText={t('选择模型的一级分类,可多选')}
/>
</Col>
<Col span={24}>
<Form.Select
field='level2_categories'
label={t('二级分类(可多选)')}
placeholder={
selectedLevel1Keys.length > 0
? t('选择二级分类')
: t('请先选择一级分类')
}
optionList={level2Categories.map((cat) => ({
label: `${cat.parent_category_name} - ${cat.category_name}`,
value: cat.category_key,
}))}
multiple
maxTagCount={3}
showClear
disabled={selectedLevel1Keys.length === 0}
style={{ width: '100%' }}
extraText={t(
'根据选择的一级分类自动过滤二级分类,可多选',
)}
/>
</Col>
<Col span={24}>
<JSONEditor
field='endpoints'
label={t('端点映射')}
placeholder={
'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'
}
value={values.endpoints}
onChange={(val) =>
formApiRef.current?.setValue('endpoints', val)
}
formApi={formApiRef.current}
editorType='object'
template={ENDPOINT_TEMPLATE}
templateLabel={t('填入模板')}
extraText={t('留空则使用默认端点;支持 {path, method}')}
extraFooter={
endpointGroups.length > 0 && (
<Space wrap>
{endpointGroups.map((group) => (
<Button
key={group.id}
size='small'
type='primary'
onClick={() => {
try {
const current =
formApiRef.current?.getValue(
'endpoints',
) || '';
let base = {};
if (current && current.trim())
base = JSON.parse(current);
const groupObj =
typeof group.items === 'string'
? JSON.parse(group.items || '{}')
: group.items || {};
const merged = { ...base, ...groupObj };
formApiRef.current?.setValue(
'endpoints',
JSON.stringify(merged, null, 2),
);
} catch (e) {
try {
const groupObj =
typeof group.items === 'string'
? JSON.parse(group.items || '{}')
: group.items || {};
formApiRef.current?.setValue(
'endpoints',
JSON.stringify(groupObj, null, 2),
);
} catch {}
}
}}
>
{group.name}
</Button>
))}
</Space>
)
}
/>
</Col>
<Col span={24}>
<Form.Switch
field='sync_official'
label={t('参与官方同步')}
extraText={t(
'关闭后,此模型将不会被“同步官方”自动覆盖或创建',
)}
size='large'
/>
</Col>
<Col span={24}>
<Form.Switch
field='status'
label={t('状态')}
size='large'
/>
</Col>
</Row>
</Card>
</div>
)}
</Form>
</Spin>
</SideSheet>
);
};
export default EditModelModal;
@@ -0,0 +1,274 @@
/*
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, { useState, useRef, useEffect } from 'react';
import JSONEditor from '../../../common/ui/JSONEditor';
import {
SideSheet,
Button,
Form,
Typography,
Space,
Tag,
Row,
Col,
Card,
Avatar,
Spin,
} from '@douyinfe/semi-ui';
import { IconLayers, IconSave, IconClose } from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = Typography;
// Example endpoint template for quick fill
const ENDPOINT_TEMPLATE = {
openai: { path: '/v1/chat/completions', method: 'POST' },
'openai-response': { path: '/v1/responses', method: 'POST' },
anthropic: { path: '/v1/messages', method: 'POST' },
gemini: { path: '/v1beta/models/{model}:generateContent', method: 'POST' },
'jina-rerank': { path: '/rerank', method: 'POST' },
'image-generation': { path: '/v1/images/generations', method: 'POST' },
};
const EditPrefillGroupModal = ({
visible,
onClose,
editingGroup,
onSuccess,
}) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
const formRef = useRef(null);
const isEdit = editingGroup && editingGroup.id !== undefined;
const [selectedType, setSelectedType] = useState(editingGroup?.type || 'tag');
// 当外部传入的编辑组类型变化时同步 selectedType
useEffect(() => {
setSelectedType(editingGroup?.type || 'tag');
}, [editingGroup?.type]);
const typeOptions = [
{ label: t('模型组'), value: 'model' },
{ label: t('标签组'), value: 'tag' },
{ label: t('端点组'), value: 'endpoint' },
];
// 提交表单
const handleSubmit = async (values) => {
setLoading(true);
try {
const submitData = {
...values,
};
if (values.type === 'endpoint') {
submitData.items = values.items || '';
} else {
submitData.items = Array.isArray(values.items) ? values.items : [];
}
if (editingGroup.id) {
submitData.id = editingGroup.id;
const res = await API.put('/api/prefill_group', submitData);
if (res.data.success) {
showSuccess(t('更新成功'));
onSuccess();
} else {
showError(res.data.message || t('更新失败'));
}
} else {
const res = await API.post('/api/prefill_group', submitData);
if (res.data.success) {
showSuccess(t('创建成功'));
onSuccess();
} else {
showError(res.data.message || t('创建失败'));
}
}
} catch (error) {
showError(t('操作失败'));
}
setLoading(false);
};
return (
<SideSheet
placement='left'
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新预填组') : t('创建新的预填组')}
</Title>
</Space>
}
visible={visible}
onCancel={onClose}
width={isMobile ? '100%' : 600}
bodyStyle={{ padding: '0' }}
footer={
<div className='flex justify-end'>
<Space>
<Button
theme='solid'
className='!rounded-lg'
onClick={() => formRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
className='!rounded-lg'
type='primary'
onClick={onClose}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
>
<Spin spinning={loading}>
<Form
getFormApi={(api) => (formRef.current = api)}
initValues={{
name: editingGroup?.name || '',
type: editingGroup?.type || 'tag',
description: editingGroup?.description || '',
items: (() => {
try {
if (editingGroup?.type === 'endpoint') {
// 保持原始字符串
return typeof editingGroup?.items === 'string'
? editingGroup.items
: JSON.stringify(editingGroup.items || {}, null, 2);
}
return Array.isArray(editingGroup?.items)
? editingGroup.items
: [];
} catch {
return editingGroup?.type === 'endpoint' ? '' : [];
}
})(),
}}
onSubmit={handleSubmit}
>
<div className='p-2'>
{/* 基本信息 */}
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<IconLayers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>
{t('设置预填组的基本信息')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='name'
label={t('组名')}
placeholder={t('请输入组名')}
rules={[{ required: true, message: t('请输入组名') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.Select
field='type'
label={t('类型')}
placeholder={t('选择组类型')}
optionList={typeOptions}
rules={[{ required: true, message: t('请选择组类型') }]}
style={{ width: '100%' }}
onChange={(val) => setSelectedType(val)}
/>
</Col>
<Col span={24}>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('请输入组描述')}
rows={3}
showClear
/>
</Col>
<Col span={24}>
{selectedType === 'endpoint' ? (
<JSONEditor
field='items'
label={t('端点映射')}
value={
formRef.current?.getValue('items') ??
(typeof editingGroup?.items === 'string'
? editingGroup.items
: JSON.stringify(editingGroup.items || {}, null, 2))
}
onChange={(val) =>
formRef.current?.setValue('items', val)
}
editorType='object'
placeholder={
'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'
}
template={ENDPOINT_TEMPLATE}
templateLabel={t('填入模板')}
extraText={t('键为端点类型,值为路径和方法对象')}
/>
) : (
<Form.TagInput
field='items'
label={t('项目')}
placeholder={t('输入项目名称,按回车添加')}
addOnBlur
showClear
style={{ width: '100%' }}
/>
)}
</Col>
</Row>
</Card>
</div>
</Form>
</Spin>
</SideSheet>
);
};
export default EditPrefillGroupModal;
@@ -0,0 +1,186 @@
/*
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, { useState, useRef, useEffect } from 'react';
import { Modal, Form, Col, Row } from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../../helpers';
import { Typography } from '@douyinfe/semi-ui';
import { IconLink } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const formApiRef = useRef(null);
const isMobile = useIsMobile();
const isEdit = editingVendor && editingVendor.id !== undefined;
const getInitValues = () => ({
name: '',
description: '',
icon: '',
status: true,
});
const handleCancel = () => {
handleClose();
formApiRef.current?.reset();
};
const loadVendor = async () => {
if (!isEdit || !editingVendor.id) return;
setLoading(true);
try {
const res = await API.get(`/api/vendors/${editingVendor.id}`);
const { success, message, data } = res.data;
if (success) {
// 将数字状态转为布尔值
data.status = data.status === 1;
if (formApiRef.current) {
formApiRef.current.setValues({ ...getInitValues(), ...data });
}
} else {
showError(message);
}
} catch (error) {
showError(t('加载供应商信息失败'));
}
setLoading(false);
};
useEffect(() => {
if (visible) {
if (isEdit) {
loadVendor();
} else {
formApiRef.current?.setValues(getInitValues());
}
} else {
formApiRef.current?.reset();
}
}, [visible, editingVendor?.id]);
const submit = async (values) => {
setLoading(true);
try {
// 转换 status 为数字
const submitData = {
...values,
status: values.status ? 1 : 0,
};
if (isEdit) {
submitData.id = editingVendor.id;
const res = await API.put('/api/vendors/', submitData);
const { success, message } = res.data;
if (success) {
showSuccess(t('供应商更新成功!'));
refresh();
handleClose();
} else {
showError(t(message));
}
} else {
const res = await API.post('/api/vendors/', submitData);
const { success, message } = res.data;
if (success) {
showSuccess(t('供应商创建成功!'));
refresh();
handleClose();
} else {
showError(t(message));
}
}
} catch (error) {
showError(error.response?.data?.message || t('操作失败'));
}
setLoading(false);
};
return (
<Modal
title={isEdit ? t('编辑供应商') : t('新增供应商')}
visible={visible}
onOk={() => formApiRef.current?.submitForm()}
onCancel={handleCancel}
confirmLoading={loading}
size={isMobile ? 'full-width' : 'small'}
>
<Form
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='name'
label={t('供应商名称')}
placeholder={t('请输入供应商名称,如:OpenAI')}
rules={[{ required: true, message: t('请输入供应商名称') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('请输入供应商描述')}
rows={3}
showClear
/>
</Col>
<Col span={24}>
<Form.Input
field='icon'
label={t('供应商图标')}
placeholder={t('请输入图标名称')}
extraText={
<span>
{t(
"图标使用@lobehub/icons库,如:OpenAI、Claude.Color,支持链式参数:OpenAI.Avatar.type={'platform'}、OpenRouter.Avatar.shape={'square'},查询所有可用图标请 ",
)}
<Typography.Text
link={{
href: 'https://icons.lobehub.com/components/lobe-hub',
target: '_blank',
}}
icon={<IconLink />}
underline
>
{t('请点击我')}
</Typography.Text>
</span>
}
showClear
/>
</Col>
<Col span={24}>
<Form.Switch field='status' label={t('状态')} initValue={true} />
</Col>
</Row>
</Form>
</Modal>
);
};
export default EditVendorModal;
@@ -0,0 +1,201 @@
/*
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, useState } from 'react';
import {
Modal,
Table,
Spin,
Button,
Typography,
Empty,
Input,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../common/illustrations';
import { IconSearch } from '@douyinfe/semi-icons';
import { API, showError } from '../../../../helpers';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const [loading, setLoading] = useState(false);
const [missingModels, setMissingModels] = useState([]);
const [searchKeyword, setSearchKeyword] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const isMobile = useIsMobile();
const fetchMissing = async () => {
setLoading(true);
try {
const res = await API.get('/api/models/missing');
if (res.data.success) {
setMissingModels(res.data.data || []);
} else {
showError(res.data.message);
}
} catch (_) {
showError(t('获取未配置模型失败'));
}
setLoading(false);
};
useEffect(() => {
if (visible) {
fetchMissing();
setSearchKeyword('');
setCurrentPage(1);
} else {
setMissingModels([]);
}
}, [visible]);
// 过滤和分页逻辑
const filteredModels = missingModels.filter((model) =>
model.toLowerCase().includes(searchKeyword.toLowerCase()),
);
const dataSource = (() => {
const start = (currentPage - 1) * MODEL_TABLE_PAGE_SIZE;
const end = start + MODEL_TABLE_PAGE_SIZE;
return filteredModels.slice(start, end).map((model) => ({
model,
key: model,
}));
})();
const columns = [
{
title: t('模型名称'),
dataIndex: 'model',
render: (text) => (
<div className='flex items-center'>
<Typography.Text strong>{text}</Typography.Text>
</div>
),
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
width: 120,
render: (text, record) => (
<Button
type='primary'
size='small'
onClick={() => onConfigureModel(record.model)}
>
{t('配置')}
</Button>
),
},
];
return (
<Modal
title={
<div className='flex flex-col gap-2 w-full'>
<div className='flex items-center gap-2'>
<Typography.Text
strong
className='!text-[var(--semi-color-text-0)] !text-base'
>
{t('未配置的模型列表')}
</Typography.Text>
<Typography.Text type='tertiary' size='small'>
{t('共')} {missingModels.length} {t('个未配置模型')}
</Typography.Text>
</div>
</div>
}
visible={visible}
onCancel={onClose}
footer={null}
size={isMobile ? 'full-width' : 'medium'}
className='!rounded-lg'
>
<Spin spinning={loading}>
{missingModels.length === 0 && !loading ? (
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无缺失模型')}
style={{ padding: 30 }}
/>
) : (
<div className='missing-models-content'>
{/* 搜索框 */}
<div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input
placeholder={t('搜索模型...')}
value={searchKeyword}
onChange={(v) => {
setSearchKeyword(v);
setCurrentPage(1);
}}
className='!w-full'
prefix={<IconSearch />}
showClear
/>
</div>
{/* 表格 */}
{filteredModels.length > 0 ? (
<Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
scroll={{ x: 'max-content' }}
columns={columns}
dataSource={dataSource}
pagination={{
currentPage: currentPage,
pageSize: MODEL_TABLE_PAGE_SIZE,
total: filteredModels.length,
showSizeChanger: false,
onPageChange: (page) => setCurrentPage(page),
}}
/>
) : (
<Empty
image={
<IllustrationNoResult style={{ width: 100, height: 100 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 100, height: 100 }}
/>
}
description={
searchKeyword ? t('未找到匹配的模型') : t('暂无缺失模型')
}
style={{ padding: 20 }}
/>
)}
</div>
)}
</Spin>
</Modal>
);
};
export default MissingModelsModal;
@@ -0,0 +1,308 @@
/*
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, { useState, useEffect } from 'react';
import {
SideSheet,
Button,
Typography,
Space,
Tag,
Popconfirm,
Card,
Avatar,
Spin,
Empty,
} from '@douyinfe/semi-ui';
import { IconPlus, IconLayers } from '@douyinfe/semi-icons';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../common/illustrations';
import {
API,
showError,
showSuccess,
stringToColor,
} from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import CardTable from '../../../common/ui/CardTable';
import EditPrefillGroupModal from './EditPrefillGroupModal';
import {
renderLimitedItems,
renderDescription,
} from '../../../common/ui/RenderUtils';
const { Text, Title } = Typography;
const PrefillGroupManagement = ({ visible, onClose }) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
const [groups, setGroups] = useState([]);
const [showEdit, setShowEdit] = useState(false);
const [editingGroup, setEditingGroup] = useState({ id: undefined });
const typeOptions = [
{ label: t('模型组'), value: 'model' },
{ label: t('标签组'), value: 'tag' },
{ label: t('端点组'), value: 'endpoint' },
];
// 加载组列表
const loadGroups = async () => {
setLoading(true);
try {
const res = await API.get('/api/prefill_group');
if (res.data.success) {
setGroups(res.data.data || []);
} else {
showError(res.data.message || t('获取组列表失败'));
}
} catch (error) {
showError(t('获取组列表失败'));
}
setLoading(false);
};
// 删除组
const deleteGroup = async (id) => {
try {
const res = await API.delete(`/api/prefill_group/${id}`);
if (res.data.success) {
showSuccess(t('删除成功'));
loadGroups();
} else {
showError(res.data.message || t('删除失败'));
}
} catch (error) {
showError(t('删除失败'));
}
};
// 编辑组
const handleEdit = (group = {}) => {
setEditingGroup(group);
setShowEdit(true);
};
// 关闭编辑
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingGroup({ id: undefined });
}, 300);
};
// 编辑成功回调
const handleEditSuccess = () => {
closeEdit();
loadGroups();
};
// 表格列定义
const columns = [
{
title: t('组名'),
dataIndex: 'name',
key: 'name',
render: (text, record) => (
<Space>
<Text strong>{text}</Text>
<Tag color='white' shape='circle' size='small'>
{typeOptions.find((opt) => opt.value === record.type)?.label ||
record.type}
</Tag>
</Space>
),
},
{
title: t('描述'),
dataIndex: 'description',
key: 'description',
render: (text) => renderDescription(text, 150),
},
{
title: t('项目内容'),
dataIndex: 'items',
key: 'items',
render: (items, record) => {
try {
if (record.type === 'endpoint') {
const obj =
typeof items === 'string'
? JSON.parse(items || '{}')
: items || {};
const keys = Object.keys(obj);
if (keys.length === 0)
return <Text type='tertiary'>{t('暂无项目')}</Text>;
return renderLimitedItems({
items: keys,
renderItem: (key, idx) => (
<Tag
key={idx}
size='small'
shape='circle'
color={stringToColor(key)}
>
{key}
</Tag>
),
maxDisplay: 3,
});
}
const itemsArray =
typeof items === 'string' ? JSON.parse(items) : items;
if (!Array.isArray(itemsArray) || itemsArray.length === 0) {
return <Text type='tertiary'>{t('暂无项目')}</Text>;
}
return renderLimitedItems({
items: itemsArray,
renderItem: (item, idx) => (
<Tag
key={idx}
size='small'
shape='circle'
color={stringToColor(item)}
>
{item}
</Tag>
),
maxDisplay: 3,
});
} catch {
return <Text type='tertiary'>{t('数据格式错误')}</Text>;
}
},
},
{
title: '',
key: 'action',
fixed: 'right',
width: 140,
render: (_, record) => (
<Space>
<Button size='small' onClick={() => handleEdit(record)}>
{t('编辑')}
</Button>
<Popconfirm
title={t('确定删除此组?')}
onConfirm={() => deleteGroup(record.id)}
>
<Button size='small' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
useEffect(() => {
if (visible) {
loadGroups();
}
}, [visible]);
return (
<>
<SideSheet
placement='left'
title={
<Space>
<Tag color='blue' shape='circle'>
{t('管理')}
</Tag>
<Title heading={4} className='m-0'>
{t('预填组管理')}
</Title>
</Space>
}
visible={visible}
onCancel={onClose}
width={isMobile ? '100%' : 800}
bodyStyle={{ padding: '0' }}
closeIcon={null}
>
<Spin spinning={loading}>
<div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='blue' className='mr-2 shadow-md'>
<IconLayers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('组列表')}</Text>
<div className='text-xs text-gray-600'>
{t('管理模型、标签、端点等预填组')}
</div>
</div>
</div>
<div className='flex justify-end mb-4'>
<Button
type='primary'
theme='solid'
size='small'
icon={<IconPlus />}
onClick={() => handleEdit()}
>
{t('新建组')}
</Button>
</div>
{groups.length > 0 ? (
<CardTable
columns={columns}
dataSource={groups}
rowKey='id'
hidePagination={true}
size='small'
scroll={{ x: 'max-content' }}
/>
) : (
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 150, height: 150 }}
/>
}
description={t('暂无预填组')}
style={{ padding: 30 }}
/>
)}
</Card>
</div>
</Spin>
</SideSheet>
{/* 编辑组件 */}
<EditPrefillGroupModal
visible={showEdit}
onClose={closeEdit}
editingGroup={editingGroup}
onSuccess={handleEditSuccess}
/>
</>
);
};
export default PrefillGroupManagement;
@@ -0,0 +1,132 @@
/*
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, useState } from 'react';
import { Modal, RadioGroup, Radio, Steps, Button } from '@douyinfe/semi-ui';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const SyncWizardModal = ({ visible, onClose, onConfirm, loading, t }) => {
const [step, setStep] = useState(0);
const [option, setOption] = useState('official');
const [locale, setLocale] = useState('zh');
const isMobile = useIsMobile();
useEffect(() => {
if (visible) {
setStep(0);
setOption('official');
setLocale('zh');
}
}, [visible]);
return (
<Modal
title={t('同步向导')}
visible={visible}
onCancel={onClose}
footer={
<div className='flex justify-end'>
{step === 1 && (
<Button onClick={() => setStep(0)}>{t('上一步')}</Button>
)}
<Button onClick={onClose}>{t('取消')}</Button>
{step === 0 && (
<Button
type='primary'
onClick={() => setStep(1)}
disabled={option !== 'official'}
>
{t('下一步')}
</Button>
)}
{step === 1 && (
<Button
type='primary'
theme='solid'
loading={loading}
onClick={async () => {
await onConfirm?.({ option, locale });
}}
>
{t('开始同步')}
</Button>
)}
</div>
}
width={isMobile ? '100%' : 'small'}
>
<div className='mb-3'>
<Steps type='basic' current={step} size='small'>
<Steps.Step title={t('选择方式')} description={t('选择同步来源')} />
<Steps.Step title={t('选择语言')} description={t('选择同步语言')} />
</Steps>
</div>
{step === 0 && (
<div className='mt-2 flex justify-center'>
<RadioGroup
value={option}
onChange={(e) => setOption(e?.target?.value ?? e)}
type='card'
direction='horizontal'
aria-label={t('同步方式选择')}
name='sync-mode-selection'
>
<Radio value='official' extra={t('从官方模型库同步')}>
{t('官方模型同步')}
</Radio>
<Radio value='config' extra={t('从配置文件同步')} disabled>
{t('配置文件同步')}
</Radio>
</RadioGroup>
</div>
)}
{step === 1 && (
<div className='mt-2'>
<div className='mb-2 text-[var(--semi-color-text-2)]'>
{t('请选择同步语言')}
</div>
<div className='flex justify-center'>
<RadioGroup
value={locale}
onChange={(e) => setLocale(e?.target?.value ?? e)}
type='card'
direction='horizontal'
aria-label={t('语言选择')}
name='sync-locale-selection'
>
<Radio value='en' extra='English'>
EN
</Radio>
<Radio value='zh' extra='中文'>
ZH
</Radio>
<Radio value='ja' extra='日本語'>
JA
</Radio>
</RadioGroup>
</div>
</div>
)}
</Modal>
);
};
export default SyncWizardModal;
@@ -0,0 +1,326 @@
/*
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, useCallback } from 'react';
import {
Modal,
Table,
Checkbox,
Typography,
Empty,
Tag,
Popover,
Input,
} from '@douyinfe/semi-ui';
import { MousePointerClick } from 'lucide-react';
import { hoverOrClickTrigger } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import { IconSearch } from '@douyinfe/semi-icons';
const { Text } = Typography;
const FIELD_LABELS = {
description: '描述',
icon: '图标',
tags: '标签',
vendor: '供应商',
name_rule: '命名规则',
status: '状态',
};
const FIELD_KEYS = Object.keys(FIELD_LABELS);
const UpstreamConflictModal = ({
visible,
onClose,
conflicts = [],
onSubmit,
t,
loading = false,
}) => {
const [selections, setSelections] = useState({});
const isMobile = useIsMobile();
const [currentPage, setCurrentPage] = useState(1);
const [searchKeyword, setSearchKeyword] = useState('');
const formatValue = (v) => {
if (v === null || v === undefined) return '-';
if (typeof v === 'string') return v || '-';
try {
return JSON.stringify(v, null, 2);
} catch (_) {
return String(v);
}
};
useEffect(() => {
if (visible) {
const init = {};
conflicts.forEach((item) => {
init[item.model_name] = new Set();
});
setSelections(init);
setCurrentPage(1);
setSearchKeyword('');
} else {
setSelections({});
}
}, [visible, conflicts]);
const toggleField = useCallback((modelName, field, checked) => {
setSelections((prev) => {
const next = { ...prev };
const set = new Set(next[modelName] || []);
if (checked) set.add(field);
else set.delete(field);
next[modelName] = set;
return next;
});
}, []);
// 构造数据源与过滤后的数据源
const dataSource = useMemo(
() =>
(conflicts || []).map((c) => ({
key: c.model_name,
model_name: c.model_name,
fields: c.fields || [],
})),
[conflicts],
);
const filteredDataSource = useMemo(() => {
const kw = (searchKeyword || '').toLowerCase();
if (!kw) return dataSource;
return dataSource.filter((item) =>
(item.model_name || '').toLowerCase().includes(kw),
);
}, [dataSource, searchKeyword]);
// 列头工具:当前过滤范围内可操作的行集合/勾选状态/批量设置
const getPresentRowsForField = useCallback(
(fieldKey) =>
(filteredDataSource || []).filter((row) =>
(row.fields || []).some((f) => f.field === fieldKey),
),
[filteredDataSource],
);
const getHeaderState = useCallback(
(fieldKey) => {
const presentRows = getPresentRowsForField(fieldKey);
const selectedCount = presentRows.filter((row) =>
selections[row.model_name]?.has(fieldKey),
).length;
const allCount = presentRows.length;
return {
headerChecked: allCount > 0 && selectedCount === allCount,
headerIndeterminate: selectedCount > 0 && selectedCount < allCount,
hasAny: allCount > 0,
};
},
[getPresentRowsForField, selections],
);
const applyHeaderChange = useCallback(
(fieldKey, checked) => {
setSelections((prev) => {
const next = { ...prev };
getPresentRowsForField(fieldKey).forEach((row) => {
const set = new Set(next[row.model_name] || []);
if (checked) set.add(fieldKey);
else set.delete(fieldKey);
next[row.model_name] = set;
});
return next;
});
},
[getPresentRowsForField],
);
const columns = useMemo(() => {
const base = [
{
title: t('模型'),
dataIndex: 'model_name',
fixed: 'left',
render: (text) => <Text strong>{text}</Text>,
},
];
const cols = FIELD_KEYS.map((fieldKey) => {
const rawLabel = FIELD_LABELS[fieldKey] || fieldKey;
const label = t(rawLabel);
const { headerChecked, headerIndeterminate, hasAny } =
getHeaderState(fieldKey);
if (!hasAny) return null;
const onHeaderChange = (e) =>
applyHeaderChange(fieldKey, e?.target?.checked);
return {
title: (
<div className='flex items-center gap-2'>
<Checkbox
checked={headerChecked}
indeterminate={headerIndeterminate}
onChange={onHeaderChange}
/>
<Text>{label}</Text>
</div>
),
dataIndex: fieldKey,
render: (_, record) => {
const f = (record.fields || []).find((x) => x.field === fieldKey);
if (!f) return <Text type='tertiary'>-</Text>;
const checked = selections[record.model_name]?.has(fieldKey) || false;
return (
<Checkbox
checked={checked}
onChange={(e) =>
toggleField(record.model_name, fieldKey, e?.target?.checked)
}
>
<Popover
// 触屏没有 hover:不改的话用户只能盲勾「覆盖」而看不到差异
trigger={hoverOrClickTrigger()}
position='top'
content={
<div className='p-2 max-w-[520px]'>
<div className='mb-2'>
<Text type='tertiary' size='small'>
{t('本地')}
</Text>
<pre className='whitespace-pre-wrap m-0'>
{formatValue(f.local)}
</pre>
</div>
<div>
<Text type='tertiary' size='small'>
{t('官方')}
</Text>
<pre className='whitespace-pre-wrap m-0'>
{formatValue(f.upstream)}
</pre>
</div>
</div>
}
>
<Tag
color='white'
size='small'
prefixIcon={<MousePointerClick size={14} />}
>
{t('点击查看差异')}
</Tag>
</Popover>
</Checkbox>
);
},
};
});
return [...base, ...cols.filter(Boolean)];
}, [
t,
selections,
filteredDataSource,
getHeaderState,
applyHeaderChange,
toggleField,
]);
const pagedDataSource = useMemo(() => {
const start = (currentPage - 1) * MODEL_TABLE_PAGE_SIZE;
const end = start + MODEL_TABLE_PAGE_SIZE;
return filteredDataSource.slice(start, end);
}, [filteredDataSource, currentPage]);
const handleOk = async () => {
const payload = Object.entries(selections)
.map(([modelName, set]) => ({
model_name: modelName,
fields: Array.from(set || []),
}))
.filter((x) => x.fields.length > 0);
const ok = await onSubmit?.(payload);
if (ok) onClose?.();
};
return (
<Modal
title={t('选择要覆盖的冲突项')}
visible={visible}
onCancel={onClose}
onOk={handleOk}
confirmLoading={loading}
okText={t('应用覆盖')}
cancelText={t('取消')}
width={isMobile ? '100%' : 1000}
>
{dataSource.length === 0 ? (
<Empty description={t('无冲突项')} className='p-6' />
) : (
<>
<div className='mb-3 text-[var(--semi-color-text-2)]'>
{t('仅会覆盖你勾选的字段,未勾选的字段保持本地不变。')}
</div>
{/* 搜索框 */}
<div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input
placeholder={t('搜索模型...')}
value={searchKeyword}
onChange={(v) => {
setSearchKeyword(v);
setCurrentPage(1);
}}
className='!w-full'
prefix={<IconSearch />}
showClear
/>
</div>
{filteredDataSource.length > 0 ? (
<Table
columns={columns}
dataSource={pagedDataSource}
pagination={{
currentPage: currentPage,
pageSize: MODEL_TABLE_PAGE_SIZE,
total: filteredDataSource.length,
showSizeChanger: false,
onPageChange: (page) => setCurrentPage(page),
}}
scroll={{ x: 'max-content' }}
/>
) : (
<Empty
description={
searchKeyword ? t('未找到匹配的模型') : t('无冲突项')
}
className='p-6'
/>
)}
</>
)}
</Modal>
);
};
export default UpstreamConflictModal;
@@ -0,0 +1,76 @@
/*
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 } from '@douyinfe/semi-ui';
import { isAdmin } from '../../../helpers';
const RedemptionsActions = ({
selectedKeys,
setEditingRedemption,
setShowEdit,
batchCopyRedemptions,
batchDeleteRedemptions,
t,
}) => {
// Add new redemption code
const handleAddRedemption = () => {
setEditingRedemption({
id: undefined,
});
setShowEdit(true);
};
return (
<div className='flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1'>
{isAdmin() && (
<Button
type='primary'
className='flex-1 md:flex-initial'
onClick={handleAddRedemption}
size='small'
>
{t('添加兑换码')}
</Button>
)}
<Button
type='tertiary'
className='flex-1 md:flex-initial'
onClick={batchCopyRedemptions}
size='small'
>
{t('复制所选兑换码到剪贴板')}
</Button>
{isAdmin() && (
<Button
type='danger'
className='w-full md:w-auto'
onClick={batchDeleteRedemptions}
size='small'
>
{t('清除失效兑换码')}
</Button>
)}
</div>
);
};
export default RedemptionsActions;
@@ -0,0 +1,233 @@
/*
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 { Tag, Button, Space, Popover, Dropdown } from '@douyinfe/semi-ui';
import { IconMore } from '@douyinfe/semi-icons';
import {
renderQuota,
timestamp2string,
isAdmin,
hoverOrClickTrigger,
} from '../../../helpers';
import {
REDEMPTION_STATUS,
REDEMPTION_STATUS_MAP,
REDEMPTION_ACTIONS,
} from '../../../constants/redemption.constants';
/**
* Check if redemption code is expired
*/
export const isExpired = (record) => {
return (
record.status === REDEMPTION_STATUS.UNUSED &&
record.expired_time !== 0 &&
record.expired_time < Math.floor(Date.now() / 1000)
);
};
/**
* Render timestamp
*/
const renderTimestamp = (timestamp) => {
return <>{timestamp2string(timestamp)}</>;
};
/**
* Render redemption code status
*/
const renderStatus = (status, record, t) => {
if (isExpired(record)) {
return (
<Tag color='orange' shape='circle'>
{t('已过期')}
</Tag>
);
}
const statusConfig = REDEMPTION_STATUS_MAP[status];
if (statusConfig) {
return (
<Tag color={statusConfig.color} shape='circle'>
{t(statusConfig.text)}
</Tag>
);
}
return (
<Tag color='black' shape='circle'>
{t('未知状态')}
</Tag>
);
};
/**
* Get redemption code table column definitions
*/
export const getRedemptionsColumns = ({
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDeleteRedemptionModal,
}) => {
return [
{
title: t('ID'),
dataIndex: 'id',
},
{
title: t('名称'),
dataIndex: 'name',
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
render: (text, record) => {
return <div>{renderStatus(text, record, t)}</div>;
},
},
{
title: t('额度'),
dataIndex: 'quota',
render: (text) => {
return (
<div>
<Tag color='grey' shape='circle'>
{renderQuota(parseInt(text))}
</Tag>
</div>
);
},
},
{
title: t('创建时间'),
dataIndex: 'created_time',
render: (text) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: t('过期时间'),
dataIndex: 'expired_time',
render: (text) => {
return <div>{text === 0 ? t('永不过期') : renderTimestamp(text)}</div>;
},
},
{
title: t('兑换人ID'),
dataIndex: 'used_user_id',
render: (text) => {
return <div>{text === 0 ? t('无') : text}</div>;
},
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
width: 205,
render: (text, record) => {
// Create dropdown menu items for more operations
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => {
showDeleteRedemptionModal(record);
},
},
];
if (record.status === REDEMPTION_STATUS.UNUSED && !isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('禁用'),
type: 'warning',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.DISABLE, record);
},
});
} else if (!isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('启用'),
type: 'secondary',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.ENABLE, record);
},
disabled: record.status === REDEMPTION_STATUS.USED,
});
}
return (
<Space>
<Popover
// 触屏必须 click:这是查看兑换码明文的唯一入口
trigger={hoverOrClickTrigger()}
content={record.key}
style={{ padding: 20 }}
position='top'
>
<Button type='tertiary' size='small'>
{t('查看')}
</Button>
</Popover>
<Button
size='small'
onClick={async () => {
await copyText(record.key);
}}
>
{t('复制')}
</Button>
{isAdmin() && (
<>
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingRedemption(record);
setShowEdit(true);
}}
disabled={record.status !== REDEMPTION_STATUS.UNUSED}
>
{t('编辑')}
</Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={moreMenuItems}
>
<Button type='tertiary' size='small' icon={<IconMore />} />
</Dropdown>
</>
)}
</Space>
);
},
},
];
};
@@ -0,0 +1,44 @@
/*
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 { Typography } from '@douyinfe/semi-ui';
import { Ticket } from 'lucide-react';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const RedemptionsDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center text-orange-500'>
<Ticket size={16} className='mr-2' />
<Text>{t('兑换码管理')}</Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default RedemptionsDescription;
@@ -0,0 +1,93 @@
/*
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, { useRef } from 'react';
import { Form, Button } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
const RedemptionsFilters = ({
formInitValues,
setFormApi,
searchRedemptions,
loading,
searching,
t,
}) => {
// Handle form reset and immediate search
const formApiRef = useRef(null);
const handleReset = () => {
if (!formApiRef.current) return;
formApiRef.current.reset();
setTimeout(() => {
searchRedemptions();
}, 100);
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => {
setFormApi(api);
formApiRef.current = api;
}}
onSubmit={searchRedemptions}
allowEmpty={true}
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className='w-full md:w-auto order-1 md:order-2'
>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto'>
<div className='relative w-full md:w-64'>
<Form.Input
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('关键字(id或者名称)')}
showClear
pure
size='small'
/>
</div>
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading || searching}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={handleReset}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
);
};
export default RedemptionsFilters;
@@ -0,0 +1,144 @@
/*
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 { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getRedemptionsColumns } from './RedemptionsColumnDefs';
import DeleteRedemptionModal from './modals/DeleteRedemptionModal';
const RedemptionsTable = (redemptionsData) => {
const {
redemptions,
loading,
activePage,
pageSize,
tokenCount,
compactMode,
handlePageChange,
rowSelection,
handleRow,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
t,
} = redemptionsData;
// Modal states
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingRecord, setDeletingRecord] = useState(null);
// Handle show delete modal
const showDeleteRedemptionModal = (record) => {
setDeletingRecord(record);
setShowDeleteModal(true);
};
// Get all columns
const columns = useMemo(() => {
return getRedemptionsColumns({
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDeleteRedemptionModal,
});
}, [
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDeleteRedemptionModal,
]);
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
<>
<CardTable
columns={tableColumns}
dataSource={redemptions}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: redemptionsData.handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
size='middle'
/>
<DeleteRedemptionModal
visible={showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
record={deletingRecord}
manageRedemption={manageRedemption}
refresh={refresh}
redemptions={redemptions}
activePage={activePage}
t={t}
/>
</>
);
};
export default RedemptionsTable;
+122
View File
@@ -0,0 +1,122 @@
/*
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 RedemptionsTable from './RedemptionsTable';
import RedemptionsActions from './RedemptionsActions';
import RedemptionsFilters from './RedemptionsFilters';
import RedemptionsDescription from './RedemptionsDescription';
import EditRedemptionModal from './modals/EditRedemptionModal';
import { useRedemptionsData } from '../../../hooks/redemptions/useRedemptionsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
const RedemptionsPage = () => {
const redemptionsData = useRedemptionsData();
const isMobile = useIsMobile();
const {
// Edit state
showEdit,
editingRedemption,
closeEdit,
refresh,
// Actions state
selectedKeys,
setEditingRedemption,
setShowEdit,
batchCopyRedemptions,
batchDeleteRedemptions,
// Filters state
formInitValues,
setFormApi,
searchRedemptions,
loading,
searching,
// UI state
compactMode,
setCompactMode,
// Translation
t,
} = redemptionsData;
return (
<>
<EditRedemptionModal
refresh={refresh}
editingRedemption={editingRedemption}
visiable={showEdit}
handleClose={closeEdit}
/>
<CardPro
type='type1'
descriptionArea={
<RedemptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<RedemptionsActions
selectedKeys={selectedKeys}
setEditingRedemption={setEditingRedemption}
setShowEdit={setShowEdit}
batchCopyRedemptions={batchCopyRedemptions}
batchDeleteRedemptions={batchDeleteRedemptions}
t={t}
/>
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<RedemptionsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchRedemptions={searchRedemptions}
loading={loading}
searching={searching}
t={t}
/>
</div>
</div>
}
paginationArea={createCardProPagination({
currentPage: redemptionsData.activePage,
pageSize: redemptionsData.pageSize,
total: redemptionsData.tokenCount,
onPageChange: redemptionsData.handlePageChange,
onPageSizeChange: redemptionsData.handlePageSizeChange,
isMobile: isMobile,
t: redemptionsData.t,
})}
t={redemptionsData.t}
>
<RedemptionsTable {...redemptionsData} />
</CardPro>
</>
);
};
export default RedemptionsPage;
@@ -0,0 +1,58 @@
/*
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 } from '@douyinfe/semi-ui';
import { REDEMPTION_ACTIONS } from '../../../../constants/redemption.constants';
const DeleteRedemptionModal = ({
visible,
onCancel,
record,
manageRedemption,
refresh,
redemptions,
activePage,
t,
}) => {
const handleConfirm = async () => {
await manageRedemption(record.id, REDEMPTION_ACTIONS.DELETE, record);
await refresh();
setTimeout(() => {
if (redemptions.length === 0 && activePage > 1) {
refresh(activePage - 1);
}
}, 100);
onCancel(); // Close modal after success
};
return (
<Modal
title={t('确定是否要删除此兑换码?')}
visible={visible}
onCancel={onCancel}
onOk={handleConfirm}
type='warning'
>
{t('此修改将不可逆')}
</Modal>
);
};
export default DeleteRedemptionModal;
@@ -0,0 +1,348 @@
/*
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, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
API,
downloadTextAsFile,
showError,
showSuccess,
renderQuota,
} from '../../../../helpers';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
SideSheet,
Space,
Spin,
Typography,
Card,
Tag,
Form,
Avatar,
Row,
Col,
} from '@douyinfe/semi-ui';
import {
IconCreditCard,
IconSave,
IconClose,
IconGift,
} from '@douyinfe/semi-icons';
const { Text, Title } = Typography;
const EditRedemptionModal = (props) => {
const { t } = useTranslation();
const isEdit = props.editingRedemption.id !== undefined;
const [loading, setLoading] = useState(isEdit);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const getInitValues = () => ({
name: '',
quota: 100000,
count: 1,
expired_time: null,
is_gift: false,
});
const handleCancel = () => {
props.handleClose();
};
const loadRedemption = async () => {
setLoading(true);
let res = await API.get(`/api/redemption/${props.editingRedemption.id}`);
const { success, message, data } = res.data;
if (success) {
if (data.expired_time === 0) {
data.expired_time = null;
} else {
data.expired_time = new Date(data.expired_time * 1000);
}
formApiRef.current?.setValues({ ...getInitValues(), ...data });
} else {
showError(message);
}
setLoading(false);
};
useEffect(() => {
if (formApiRef.current) {
if (isEdit) {
loadRedemption();
} else {
formApiRef.current.setValues(getInitValues());
}
}
}, [props.editingRedemption.id]);
const submit = async (values) => {
let name = values.name;
if (!isEdit && (!name || name === '')) {
name = renderQuota(values.quota);
}
setLoading(true);
let localInputs = { ...values };
localInputs.count = parseInt(localInputs.count) || 0;
localInputs.quota = parseInt(localInputs.quota) || 0;
localInputs.name = name;
if (!localInputs.expired_time) {
localInputs.expired_time = 0;
} else {
localInputs.expired_time = Math.floor(
localInputs.expired_time.getTime() / 1000,
);
}
let res;
if (isEdit) {
res = await API.put(`/api/redemption/`, {
...localInputs,
id: parseInt(props.editingRedemption.id),
});
} else {
res = await API.post(`/api/redemption/`, {
...localInputs,
});
}
const { success, message, data } = res.data;
if (success) {
if (isEdit) {
showSuccess(t('兑换码更新成功!'));
props.refresh();
props.handleClose();
} else {
showSuccess(t('兑换码创建成功!'));
props.refresh();
formApiRef.current?.setValues(getInitValues());
props.handleClose();
}
} else {
showError(message);
}
if (!isEdit && data) {
let text = '';
for (let i = 0; i < data.length; i++) {
text += data[i] + '\n';
}
Modal.confirm({
title: t('兑换码创建成功'),
content: (
<div>
<p>{t('兑换码创建成功,是否下载兑换码?')}</p>
<p>{t('兑换码将以文本文件的形式下载,文件名为兑换码的名称。')}</p>
</div>
),
onOk: () => {
downloadTextAsFile(text, `${localInputs.name}.txt`);
},
});
}
setLoading(false);
};
return (
<>
<SideSheet
placement={isEdit ? 'right' : 'left'}
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新兑换码信息') : t('创建新的兑换码')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={props.visiable}
width={isMobile ? '100%' : 600}
footer={
<div className='flex justify-end'>
<Space>
<Button
theme='solid'
onClick={() => formApiRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
type='primary'
onClick={handleCancel}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
onCancel={() => handleCancel()}
>
<Spin spinning={loading}>
<Form
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
{({ values }) => (
<div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Basic Info */}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='blue'
className='mr-2 shadow-md'
>
<IconGift size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('基本信息')}
</Text>
<div className='text-xs text-gray-600'>
{t('设置兑换码的基本信息')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='name'
label={t('名称')}
placeholder={t('请输入名称')}
style={{ width: '100%' }}
rules={
!isEdit
? []
: [{ required: true, message: t('请输入名称') }]
}
showClear
/>
</Col>
<Col span={24}>
<Form.DatePicker
field='expired_time'
label={t('过期时间')}
type='dateTime'
placeholder={t('选择过期时间(可选,留空为永久)')}
style={{ width: '100%' }}
showClear
/>
</Col>
</Row>
</Card>
<Card className='!rounded-2xl shadow-sm border-0'>
{/* Header: Quota Settings */}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='green'
className='mr-2 shadow-md'
>
<IconCreditCard size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('额度设置')}
</Text>
<div className='text-xs text-gray-600'>
{t('设置兑换码的额度和数量')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={12}>
<FormQuotaInput
field='quota'
label={t('额度')}
style={{ width: '100%' }}
rules={[
{ required: true, message: t('请输入额度') },
{
validator: (rule, v) => {
const num = parseInt(v, 10);
return num > 0
? Promise.resolve()
: Promise.reject(t('额度必须大于0'));
},
},
]}
showClear
/>
</Col>
{!isEdit && (
<Col span={12}>
<Form.InputNumber
field='count'
label={t('生成数量')}
min={1}
rules={[
{ required: true, message: t('请输入生成数量') },
{
validator: (rule, v) => {
const num = parseInt(v, 10);
return num > 0
? Promise.resolve()
: Promise.reject(t('生成数量必须大于0'));
},
},
]}
style={{ width: '100%' }}
showClear
/>
</Col>
)}
</Row>
<Form.Switch
field='is_gift'
label={t('赠送码')}
extraText={t(
'开启后兑换额度进入用户赠送钱包(运营赠送性质,计入分佣净消耗剔除);关闭则视为充值性质卡密,进入主余额',
)}
/>
</Card>
</div>
)}
</Form>
</Spin>
</SideSheet>
</>
);
};
export default EditRedemptionModal;
@@ -0,0 +1,217 @@
/*
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 } from '@douyinfe/semi-ui';
import {
ListTodo,
Clock,
CheckCircle2,
Download,
XCircle,
Loader2,
FileDown,
} from 'lucide-react';
import { exportToCsv, formatTimestampForCsv } from '../../../helpers/exportCsv';
const TaskLogsActions = ({
t,
logs = [],
isAdminUser,
usageRecordMode = false,
}) => {
const ExportIcon = usageRecordMode ? FileDown : Download;
const exportButtonClass = usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: 'hover:!bg-gray-100 dark:hover:!bg-neutral-800 !transition-all !duration-300';
// 计算任务统计
const stats = React.useMemo(() => {
const successCount = logs.filter((log) => log.status === 'SUCCESS').length;
const failureCount = logs.filter((log) => log.status === 'FAILURE').length;
const pendingCount = logs.filter(
(log) =>
log.status === 'IN_PROGRESS' ||
log.status === 'SUBMITTED' ||
log.status === 'QUEUED' ||
log.status === '',
).length;
return { successCount, failureCount, pendingCount, total: logs.length };
}, [logs]);
// CSV 导出:仅当前页已加载的数据,避免一次性拉取全量产生巨大请求
const handleExportCsv = () => {
if (!logs || logs.length === 0) return;
const columns = [
{
key: 'submit_time',
title: t('提交时间'),
format: (r) => formatTimestampForCsv(r.submit_time),
},
{
key: 'finish_time',
title: t('结束时间'),
format: (r) => formatTimestampForCsv(r.finish_time),
},
{
key: 'duration',
title: t('耗时(秒)'),
format: (r) =>
r.submit_time && r.finish_time ? r.finish_time - r.submit_time : '',
},
...(isAdminUser
? [
{ key: 'channel_id', title: t('渠道ID') },
{ key: 'channel_name', title: t('渠道名称') },
]
: []),
{ key: 'platform', title: t('平台') },
{ key: 'action', title: t('类型') },
{
key: 'model',
title: t('模型'),
format: (r) =>
r.properties?.origin_model_name ||
r.properties?.upstream_model_name ||
'',
},
{ key: 'task_id', title: t('任务ID') },
{ key: 'status', title: t('状态') },
{ key: 'progress', title: t('进度') },
{ key: 'quota', title: t('费用'), format: (r) => r.quota || '' },
{ key: 'fail_reason', title: t('详情') },
];
const ts = formatTimestampForCsv(Math.floor(Date.now() / 1000)).replace(
/[: ]/g,
'-',
);
exportToCsv(columns, logs, `task-logs-${ts}.csv`);
};
const StatBadge = ({ icon: Icon, label, value, gradient, iconBg }) => (
<div className='relative group'>
<div
className={`
relative overflow-hidden
px-3 py-2 rounded-xl
bg-gradient-to-br ${gradient}
border border-white/50 dark:border-neutral-700/50
shadow-sm hover:shadow-md
transition-all duration-300
hover:scale-[1.02]
`}
>
{/* 装饰光晕 */}
<div className='absolute -top-2 -right-2 w-10 h-10 bg-white/20 rounded-full blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300' />
<div className='relative flex items-center gap-2'>
<div
className={`flex items-center justify-center w-7 h-7 rounded-lg ${iconBg} shadow-sm`}
>
<Icon className='w-3.5 h-3.5 text-white' strokeWidth={2} />
</div>
<div className='flex flex-col'>
<span className='text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide'>
{label}
</span>
<span className='text-sm font-bold text-gray-800 dark:text-gray-100'>
{value}
</span>
</div>
</div>
</div>
</div>
);
return (
<div className='flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 w-full'>
{/* 左侧:标题和统计 */}
<div className='flex flex-wrap items-center gap-3'>
{/* 页面标识 */}
<div className='flex items-center gap-2 px-3 py-2 rounded-xl bg-gradient-to-r from-cyan-50 to-blue-50 dark:from-cyan-950/40 dark:to-blue-950/40 border border-cyan-200/50 dark:border-cyan-800/30'>
<div className='flex items-center justify-center w-8 h-8 rounded-lg bg-gradient-to-br from-cyan-500 to-blue-600 shadow-md'>
<ListTodo className='w-4 h-4 text-white' strokeWidth={2} />
</div>
<div className='flex flex-col'>
<span className='text-sm font-semibold text-gray-800 dark:text-gray-100'>
{t('任务记录')}
</span>
<span className='text-[10px] text-gray-500 dark:text-gray-400'>
{t('异步任务执行状态')}
</span>
</div>
</div>
{/* 快速统计 */}
{logs.length > 0 && (
<div className='hidden md:flex items-center gap-2'>
{/* 这些统计只包含当前页数据,因此 label 前缀"本页",避免用户误以为是全量统计 */}
<StatBadge
icon={CheckCircle2}
label={t('本页成功')}
value={stats.successCount}
gradient='from-emerald-50 to-green-50 dark:from-emerald-950/30 dark:to-green-950/30'
iconBg='bg-gradient-to-br from-emerald-500 to-green-600'
/>
<StatBadge
icon={XCircle}
label={t('本页失败')}
value={stats.failureCount}
gradient='from-rose-50 to-red-50 dark:from-rose-950/30 dark:to-red-950/30'
iconBg='bg-gradient-to-br from-rose-500 to-red-600'
/>
<StatBadge
icon={Loader2}
label={t('本页进行中')}
value={stats.pendingCount}
gradient='from-amber-50 to-orange-50 dark:from-amber-950/30 dark:to-orange-950/30'
iconBg='bg-gradient-to-br from-amber-500 to-orange-600'
/>
</div>
)}
</div>
{/* 右侧:操作按钮 */}
<div className='flex items-center gap-2'>
{/* 实时状态指示:只有真实存在进行中任务时才常亮,避免"实时更新"始终挂着误导用户 */}
{stats.pendingCount > 0 && (
<div className='hidden sm:flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-gradient-to-r from-brand-from/5 to-brand-to/5 dark:from-brand-from/30 dark:to-brand-to/30 border border-brand/50 dark:border-brand-deep/30'>
<Clock className='w-3.5 h-3.5 text-brand-deep dark:text-brand-from animate-pulse' />
<span className='text-xs font-medium text-brand-deep dark:text-brand-from'>
{t('实时更新中')}
</span>
</div>
)}
{/* 导出当前页为 CSV,空列表时禁用避免生成只有表头的无用文件 */}
<Button
size='small'
icon={<ExportIcon className='w-3.5 h-3.5' />}
onClick={handleExportCsv}
disabled={!logs || logs.length === 0}
className={exportButtonClass}
>
{t('导出本页')}
</Button>
</div>
</div>
);
};
export default TaskLogsActions;
@@ -0,0 +1,519 @@
/*
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 { Progress, Tooltip, Typography } from '@douyinfe/semi-ui';
import {
Music,
FileText,
HelpCircle,
CheckCircle,
Pause,
Clock,
Play,
XCircle,
Loader,
List,
Hash,
Video,
Sparkles,
Timer,
Image as ImageIcon,
ImagePlus,
Coins,
Cpu,
} from 'lucide-react';
import {
TASK_ACTION_FIRST_TAIL_GENERATE,
TASK_ACTION_GENERATE,
TASK_ACTION_REFERENCE_GENERATE,
TASK_ACTION_TEXT_GENERATE,
IMAGE_ACTION_GENERATE,
IMAGE_ACTION_EDIT,
} from '../../../constants/common.constant';
import { CHANNEL_OPTIONS } from '../../../constants/channel.constants';
import { renderQuota } from '../../../helpers';
// 仅保留与下方 COLOR_CONFIG 一一对应的色值,避免 amber/lime/violet/teal/indigo/light-blue
// 经历多级三元 fallback 后被挤压到少数颜色上,渠道颜色分布严重偏斜
const colors = [
'blue',
'cyan',
'green',
'grey',
'orange',
'pink',
'purple',
'red',
'yellow',
];
// 颜色配置映射
const COLOR_CONFIG = {
green: {
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',
gradient: 'from-emerald-500 to-green-600',
},
yellow: {
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',
gradient: 'from-amber-500 to-yellow-600',
},
blue: {
bg: 'bg-blue-50 dark:bg-blue-950/30',
text: 'text-blue-600 dark:text-blue-400',
border: 'border-blue-200/50 dark:border-blue-800/50',
gradient: 'from-blue-500 to-brand-to',
},
red: {
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',
gradient: 'from-rose-500 to-red-600',
},
orange: {
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',
gradient: 'from-orange-500 to-amber-600',
},
grey: {
bg: 'bg-gray-50 dark:bg-gray-900/30',
text: 'text-gray-600 dark:text-gray-400',
border: 'border-gray-200/50 dark:border-gray-700/50',
gradient: 'from-gray-400 to-gray-600',
},
pink: {
bg: 'bg-pink-50 dark:bg-pink-950/30',
text: 'text-pink-600 dark:text-pink-400',
border: 'border-pink-200/50 dark:border-pink-800/50',
gradient: 'from-pink-500 to-rose-600',
},
purple: {
bg: 'bg-brand/5 dark:bg-brand-deep/30',
text: 'text-brand-deep dark:text-brand-from',
border: 'border-brand/50 dark:border-brand-deep/50',
gradient: 'from-brand-from to-brand-to',
},
cyan: {
bg: 'bg-cyan-50 dark:bg-cyan-950/30',
text: 'text-cyan-600 dark:text-cyan-400',
border: 'border-cyan-200/50 dark:border-cyan-800/50',
gradient: 'from-cyan-500 to-teal-600',
},
};
// 自定义标签组件
const CustomTag = ({
icon: Icon,
label,
colorKey = 'grey',
animate = false,
}) => {
const config = COLOR_CONFIG[colorKey] || COLOR_CONFIG.grey;
return (
<span
className={`
inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium
${config.bg} ${config.text} border ${config.border}
transition-all duration-200 hover:scale-105
`}
>
<span
className={`flex items-center justify-center w-4 h-4 rounded-full bg-gradient-to-br ${config.gradient}`}
>
<Icon
className={`w-2.5 h-2.5 text-white ${animate ? 'animate-spin' : ''}`}
strokeWidth={2.5}
/>
</span>
{label}
</span>
);
};
// Render functions
const renderTimestamp = (timestampInSeconds) => {
const date = new Date(timestampInSeconds * 1000);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return (
<span className='text-xs text-gray-600 dark:text-gray-300 font-mono'>
{`${year}-${month}-${day}`}
<span className='text-gray-400 dark:text-gray-500 mx-1'>|</span>
{`${hours}:${minutes}:${seconds}`}
</span>
);
};
function renderDuration(submit_time, finishTime) {
if (!submit_time || !finishTime) return '-';
const durationSec = finishTime - submit_time;
const colorKey = durationSec > 60 ? 'red' : 'green';
return (
<CustomTag icon={Timer} label={`${durationSec} 秒`} colorKey={colorKey} />
);
}
const renderType = (type, t) => {
const typeConfig = {
MUSIC: { icon: Music, label: t('生成音乐'), color: 'grey' },
LYRICS: { icon: FileText, label: t('生成歌词'), color: 'pink' },
[TASK_ACTION_GENERATE]: {
icon: Sparkles,
label: t('图生视频'),
color: 'blue',
},
[TASK_ACTION_TEXT_GENERATE]: {
icon: Sparkles,
label: t('文生视频'),
color: 'blue',
},
[TASK_ACTION_FIRST_TAIL_GENERATE]: {
icon: Sparkles,
label: t('首尾生视频'),
color: 'blue',
},
[TASK_ACTION_REFERENCE_GENERATE]: {
icon: Sparkles,
label: t('参照生视频'),
color: 'blue',
},
[IMAGE_ACTION_GENERATE]: {
icon: Sparkles,
label: t('文生图'),
color: 'cyan',
},
[IMAGE_ACTION_EDIT]: {
icon: ImagePlus,
label: t('图像编辑'),
color: 'purple',
},
};
const config = typeConfig[type] || {
icon: HelpCircle,
label: t('未知'),
color: 'grey',
};
return (
<CustomTag
icon={config.icon}
label={config.label}
colorKey={config.color}
/>
);
};
const renderPlatform = (platform, t) => {
let option = CHANNEL_OPTIONS.find(
(opt) => String(opt.value) === String(platform),
);
if (option) {
return (
<CustomTag
icon={Video}
label={option.label}
colorKey={option.color || 'cyan'}
/>
);
}
if (platform === 'suno') {
return <CustomTag icon={Music} label='Suno' colorKey='green' />;
}
if (platform === 'image') {
return <CustomTag icon={ImageIcon} label={t('图片')} colorKey='cyan' />;
}
if (platform === 'video') {
return <CustomTag icon={Video} label={t('视频')} colorKey='blue' />;
}
if (platform === 'mj') {
return <CustomTag icon={Sparkles} label='Midjourney' colorKey='purple' />;
}
return <CustomTag icon={HelpCircle} label={t('未知')} colorKey='grey' />;
};
const renderStatus = (type, t) => {
const statusConfig = {
SUCCESS: { icon: CheckCircle, label: t('成功'), color: 'green' },
NOT_START: { icon: Pause, label: t('未启动'), color: 'grey' },
SUBMITTED: { icon: Clock, label: t('队列中'), color: 'yellow' },
IN_PROGRESS: {
icon: Play,
label: t('执行中'),
color: 'blue',
animate: false,
},
FAILURE: { icon: XCircle, label: t('失败'), color: 'red' },
QUEUED: { icon: List, label: t('排队中'), color: 'orange' },
UNKNOWN: { icon: HelpCircle, label: t('未知'), color: 'grey' },
'': { icon: Loader, label: t('正在提交'), color: 'grey', animate: true },
};
const config = statusConfig[type] || statusConfig['UNKNOWN'];
return (
<CustomTag
icon={config.icon}
label={config.label}
colorKey={config.color}
animate={config.animate}
/>
);
};
export const getTaskLogsColumns = ({
t,
COLUMN_KEYS,
copyText,
openContentModal,
isAdminUser,
openVideoModal,
}) => {
return [
{
key: COLUMN_KEYS.SUBMIT_TIME,
title: t('提交时间'),
dataIndex: 'submit_time',
render: (text, record, index) => {
return <div>{text ? renderTimestamp(text) : '-'}</div>;
},
},
{
key: COLUMN_KEYS.FINISH_TIME,
title: t('结束时间'),
dataIndex: 'finish_time',
render: (text, record, index) => {
return <div>{text ? renderTimestamp(text) : '-'}</div>;
},
},
{
key: COLUMN_KEYS.DURATION,
title: t('花费时间'),
dataIndex: 'finish_time',
render: (finish, record) => {
return <>{finish ? renderDuration(record.submit_time, finish) : '-'}</>;
},
},
{
key: COLUMN_KEYS.CHANNEL,
title: t('渠道'),
dataIndex: 'channel_id',
render: (text, record, index) => {
if (!isAdminUser) return null;
const idNum = parseInt(text);
const colorIndex = Number.isFinite(idNum)
? ((idNum % colors.length) + colors.length) % colors.length
: 0;
const colorKey = colors[colorIndex];
// 若后端返回 channel_name 则在 Tooltip 中显示名称,便于管理员快速识别;否则回落为 ID
const tooltipContent = record.channel_name || text;
return (
<Tooltip content={tooltipContent}>
<span onClick={() => copyText(text)} className='cursor-pointer'>
<CustomTag icon={Hash} label={text} colorKey={colorKey} />
</span>
</Tooltip>
);
},
},
{
key: COLUMN_KEYS.PLATFORM,
title: t('平台'),
dataIndex: 'platform',
render: (text, record, index) => {
return <div>{renderPlatform(text, t)}</div>;
},
},
{
key: COLUMN_KEYS.TYPE,
title: t('类型'),
dataIndex: 'action',
render: (text, record, index) => {
return <div>{renderType(text, t)}</div>;
},
},
{
key: COLUMN_KEYS.MODEL,
title: t('模型'),
dataIndex: 'properties',
render: (properties, record, index) => {
const modelName =
properties?.origin_model_name ||
properties?.upstream_model_name ||
'';
if (!modelName) {
return (
<span className='text-xs text-gray-400 dark:text-gray-500'>-</span>
);
}
return (
<Tooltip content={modelName}>
<span
onClick={() => copyText(modelName)}
className='cursor-pointer'
>
<CustomTag icon={Cpu} label={modelName} colorKey='purple' />
</span>
</Tooltip>
);
},
},
{
key: COLUMN_KEYS.TASK_ID,
title: t('任务ID'),
dataIndex: 'task_id',
render: (text, record, index) => {
return (
<Typography.Text
ellipsis={{ showTooltip: true }}
onClick={() => {
openContentModal(JSON.stringify(record, null, 2));
}}
className='cursor-pointer hover:text-blue-500 dark:hover:text-blue-400 transition-colors font-mono text-xs'
>
{text}
</Typography.Text>
);
},
},
{
key: COLUMN_KEYS.TASK_STATUS,
title: t('任务状态'),
dataIndex: 'status',
render: (text, record, index) => {
return <div>{renderStatus(text, t)}</div>;
},
},
{
key: COLUMN_KEYS.PROGRESS,
title: t('进度'),
dataIndex: 'progress',
render: (text, record, index) => {
if (isNaN(text?.replace('%', ''))) {
return <span className='text-xs text-gray-500'>{text || '-'}</span>;
}
const percent = text ? parseInt(text.replace('%', '')) : 0;
const isFailure = record.status === 'FAILURE';
return (
<div className='min-w-[140px]'>
<Progress
stroke={
isFailure
? 'var(--semi-color-warning)'
: 'var(--semi-color-primary)'
}
percent={percent}
showInfo={true}
aria-label='task progress'
size='small'
className='task-progress'
/>
</div>
);
},
},
{
key: COLUMN_KEYS.QUOTA,
title: t('费用'),
dataIndex: 'quota',
render: (quota, record, index) => {
if (quota === undefined || quota === null || quota === 0) {
return (
<span className='text-xs text-gray-400 dark:text-gray-500'>-</span>
);
}
return (
<CustomTag
icon={Coins}
label={renderQuota(quota, 6)}
colorKey='orange'
/>
);
},
},
{
key: COLUMN_KEYS.FAIL_REASON,
title: t('详情'),
dataIndex: 'fail_reason',
fixed: 'right',
render: (text, record, index) => {
const isVideoTask =
record.action === TASK_ACTION_GENERATE ||
record.action === TASK_ACTION_TEXT_GENERATE ||
record.action === TASK_ACTION_FIRST_TAIL_GENERATE ||
record.action === TASK_ACTION_REFERENCE_GENERATE;
const isSuccess = record.status === 'SUCCESS';
const isUrl = typeof text === 'string' && /^https?:\/\//.test(text);
if (isSuccess && isVideoTask && isUrl) {
const videoUrl = `/v1/videos/${record.task_id}/content`;
// text 是上游原始视频 URL,传给弹窗用于"复制链接";代理路径仅用于播放
return (
<a
href='#'
onClick={(e) => {
e.preventDefault();
openVideoModal(videoUrl, text);
}}
className='inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-gradient-to-r from-blue-500 to-brand-to text-white hover:from-blue-600 hover:to-brand-to transition-all duration-300 shadow-sm hover:shadow-md'
>
<Video className='w-3.5 h-3.5' />
{t('点击预览视频')}
</a>
);
}
if (!text) {
return (
<span className='text-xs text-gray-400 dark:text-gray-500'>
{t('无')}
</span>
);
}
return (
<Typography.Text
ellipsis={{ showTooltip: true }}
style={{ width: 100 }}
onClick={() => {
openContentModal(text);
}}
className='cursor-pointer hover:text-blue-500 dark:hover:text-blue-400 transition-colors text-xs'
>
{text}
</Typography.Text>
);
},
},
];
};
@@ -0,0 +1,359 @@
/*
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,
Hash,
Radio,
RefreshCcw,
RotateCcw,
Search,
SearchCheck,
Settings2,
SlidersHorizontal,
Filter,
Activity,
Layers,
} from 'lucide-react';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
import {
TASK_ACTION_FIRST_TAIL_GENERATE,
TASK_ACTION_GENERATE,
TASK_ACTION_REFERENCE_GENERATE,
TASK_ACTION_TEXT_GENERATE,
IMAGE_ACTION_GENERATE,
IMAGE_ACTION_EDIT,
} from '../../../constants/common.constant';
const TaskLogsFilters = ({
formInitValues,
setFormApi,
refresh,
setShowColumnSelector,
formApi,
loading,
isAdminUser,
getFreshInitValues,
usageRecordMode = false,
t,
}) => {
const SearchIcon = usageRecordMode ? SearchCheck : Search;
const ResetIcon = usageRecordMode ? RefreshCcw : RotateCcw;
const ColumnsIcon = usageRecordMode ? SlidersHorizontal : Settings2;
const primaryButtonClass = usageRecordMode
? 'usage-record-action-button usage-record-action-button-primary'
: '!bg-gradient-to-r !from-cyan-500 !to-blue-600 !border-0 hover:!from-cyan-600 hover:!to-blue-700 !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 }) => (
<div className='flex items-center justify-center w-5 h-5 text-gray-400 dark:text-gray-500'>
<Icon className='w-3.5 h-3.5' strokeWidth={2} />
</div>
);
return (
<Form
initValues={formInitValues}
getFormApi={(api) => setFormApi(api)}
onSubmit={refresh}
allowEmpty={true}
autoComplete='off'
layout='vertical'
trigger='change'
stopValidateWithError={false}
className={usageRecordMode ? 'usage-record-filter-form' : undefined}
>
<div className='flex flex-col gap-4'>
{/* 筛选区域标题 */}
<div className='flex items-center gap-2 pb-2 border-b border-gray-100 dark:border-neutral-800'>
<div className='flex items-center justify-center w-6 h-6 rounded-lg bg-gradient-to-br from-cyan-500 to-blue-600 shadow-sm'>
<Filter className='w-3.5 h-3.5 text-white' />
</div>
<span className='text-sm font-semibold text-gray-700 dark:text-gray-200'>
{t('筛选条件')}
</span>
</div>
{/* 搜索字段网格 */}
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3'>
{/* 时间选择器 */}
<div className='col-span-1 lg:col-span-2'>
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-500/20 to-blue-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.DatePicker
field='dateRange'
className='w-full'
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(),
}))}
/>
</div>
</div>
</div>
{/* 任务 ID */}
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-brand-from/20 to-brand-to/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.Input
field='task_id'
prefix={<InputPrefix icon={Hash} />}
placeholder={t('任务 ID')}
showClear
pure
size='small'
/>
</div>
</div>
{/* 任务状态 */}
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-emerald-500/20 to-green-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.Select
field='status'
prefix={<InputPrefix icon={Activity} />}
placeholder={t('任务状态')}
className='w-full'
showClear
pure
size='small'
>
<Form.Select.Option value=''>
{t('全部状态')}
</Form.Select.Option>
<Form.Select.Option value='SUBMITTED'>
{t('队列中')}
</Form.Select.Option>
<Form.Select.Option value='QUEUED'>
{t('排队中')}
</Form.Select.Option>
<Form.Select.Option value='IN_PROGRESS'>
{t('执行中')}
</Form.Select.Option>
<Form.Select.Option value='SUCCESS'>
{t('成功')}
</Form.Select.Option>
<Form.Select.Option value='FAILURE'>
{t('失败')}
</Form.Select.Option>
<Form.Select.Option value='NOT_START'>
{t('未启动')}
</Form.Select.Option>
<Form.Select.Option value='UNKNOWN'>
{t('未知')}
</Form.Select.Option>
</Form.Select>
</div>
</div>
{/* 任务类型 */}
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-teal-500/20 to-cyan-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.Select
field='action'
prefix={<InputPrefix icon={Layers} />}
placeholder={t('任务类型')}
className='w-full'
showClear
pure
size='small'
>
<Form.Select.Option value=''>
{t('全部类型')}
</Form.Select.Option>
<Form.Select.Option value='MUSIC'>
{t('生成音乐')}
</Form.Select.Option>
<Form.Select.Option value='LYRICS'>
{t('生成歌词')}
</Form.Select.Option>
<Form.Select.Option value={IMAGE_ACTION_GENERATE}>
{t('文生图')}
</Form.Select.Option>
<Form.Select.Option value={IMAGE_ACTION_EDIT}>
{t('图像编辑')}
</Form.Select.Option>
<Form.Select.Option value={TASK_ACTION_GENERATE}>
{t('图生视频')}
</Form.Select.Option>
<Form.Select.Option value={TASK_ACTION_TEXT_GENERATE}>
{t('文生视频')}
</Form.Select.Option>
<Form.Select.Option value={TASK_ACTION_FIRST_TAIL_GENERATE}>
{t('首尾生视频')}
</Form.Select.Option>
<Form.Select.Option value={TASK_ACTION_REFERENCE_GENERATE}>
{t('参照生视频')}
</Form.Select.Option>
</Form.Select>
</div>
</div>
{/* 渠道 ID - 仅管理员可见 */}
{isAdminUser && (
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-amber-500/20 to-orange-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.Input
field='channel_id'
prefix={<InputPrefix icon={Radio} />}
placeholder={t('渠道 ID')}
showClear
pure
size='small'
/>
</div>
</div>
)}
{/* 用户 ID - 仅管理员可见,与使用日志过滤器对齐 */}
{isAdminUser && (
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-sky-500/20 to-cyan-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.Input
field='user_id'
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>
)}
</div>
{/* 操作按钮区域 */}
<div className='flex justify-between items-center pt-2'>
<div></div>
<div className='flex gap-2'>
{/* 查询按钮 */}
<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={() => {
if (formApi) {
// 使用最新的"此刻"值重置,而不是 formApi.reset()(后者恢复挂载时的旧 dateRange,跨日 bug)
const fresh =
typeof getFreshInitValues === 'function'
? getFreshInitValues()
: formInitValues;
formApi.setValues(fresh, { isOverride: true });
setTimeout(() => {
refresh();
}, 100);
}
}}
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>
</div>
</div>
</div>
</Form>
);
};
export default TaskLogsFilters;
@@ -0,0 +1,118 @@
/*
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 } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getTaskLogsColumns } from './TaskLogsColumnDefs';
const TaskLogsTable = (taskLogsData) => {
const {
logs,
loading,
activePage,
pageSize,
logCount,
compactMode,
visibleColumns,
handlePageChange,
handlePageSizeChange,
copyText,
openContentModal,
openVideoModal,
isAdminUser,
t,
COLUMN_KEYS,
} = taskLogsData;
// Get all columns
const allColumns = useMemo(() => {
return getTaskLogsColumns({
t,
COLUMN_KEYS,
copyText,
openContentModal,
openVideoModal,
isAdminUser,
});
}, [t, COLUMN_KEYS, copyText, openContentModal, openVideoModal, isAdminUser]);
// 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(() => {
return compactMode
? visibleColumnsList.map(({ fixed, ...rest }) => rest)
: visibleColumnsList;
}, [compactMode, visibleColumnsList]);
return (
<CardTable
columns={tableColumns}
dataSource={logs}
rowKey='key'
loading={loading}
scroll={compactMode ? undefined : { x: 'max-content' }}
className='rounded-xl overflow-hidden task-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: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
/>
);
};
export default TaskLogsTable;
+115
View File
@@ -0,0 +1,115 @@
/*
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 TaskLogsTable from './TaskLogsTable';
import TaskLogsActions from './TaskLogsActions';
import TaskLogsFilters from './TaskLogsFilters';
import ColumnSelectorModal from './modals/ColumnSelectorModal';
import ContentModal from './modals/ContentModal';
import { useTaskLogsData } from '../../../hooks/task-logs/useTaskLogsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
const TaskLogsPage = ({ usageRecordMode = false }) => {
const taskLogsData = useTaskLogsData();
const isMobile = useIsMobile();
return (
<div className='relative'>
{/* 装饰性网格背景 */}
<div
className='absolute inset-0 opacity-[0.015] dark:opacity-[0.03] pointer-events-none'
style={{
backgroundImage: `
linear-gradient(rgba(6, 182, 212, 0.5) 1px, transparent 1px),
linear-gradient(90deg, rgba(6, 182, 212, 0.5) 1px, transparent 1px)
`,
backgroundSize: '24px 24px',
}}
/>
{/* Modals */}
<ColumnSelectorModal
{...taskLogsData}
usageRecordMode={usageRecordMode}
/>
<ContentModal
{...taskLogsData}
isVideo={false}
usageRecordMode={usageRecordMode}
/>
{/* 视频预览弹窗 */}
<ContentModal
isModalOpen={taskLogsData.isVideoModalOpen}
setIsModalOpen={taskLogsData.setIsVideoModalOpen}
modalContent={taskLogsData.videoUrl}
sourceUrl={taskLogsData.videoSourceUrl}
isVideo={true}
usageRecordMode={usageRecordMode}
/>
{/* Main Content */}
<CardPro
type='type2'
className='!bg-transparent !border-0 !shadow-none relative'
statsArea={
<TaskLogsActions
{...taskLogsData}
logs={taskLogsData.logs}
usageRecordMode={usageRecordMode}
/>
}
searchArea={
<TaskLogsFilters
{...taskLogsData}
usageRecordMode={usageRecordMode}
/>
}
paginationArea={createCardProPagination({
currentPage: taskLogsData.activePage,
pageSize: taskLogsData.pageSize,
total: taskLogsData.logCount,
onPageChange: taskLogsData.handlePageChange,
onPageSizeChange: taskLogsData.handlePageSizeChange,
isMobile: isMobile,
t: taskLogsData.t,
})}
t={taskLogsData.t}
>
{/* 表格容器 */}
<div className='relative mt-4'>
{/* 表格装饰光晕 —— 走冷色 cyan→blue→品牌,与任务日志图标族一致 */}
<div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-500/20 via-blue-500/20 to-brand-to/20 rounded-2xl opacity-50 blur-sm' />
{/* 表格内容 —— 统一 .app-card 玻璃卡(去掉散乱的 bg-white/80 + border + rounded) */}
<div className='relative app-card overflow-hidden'>
<TaskLogsTable
{...taskLogsData}
compactMode={usageRecordMode ? false : taskLogsData.compactMode}
/>
</div>
</div>
</CardPro>
</div>
);
};
export default TaskLogsPage;
@@ -0,0 +1,149 @@
/*
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 { getTaskLogsColumns } from '../TaskLogsColumnDefs';
const ColumnSelectorModal = ({
showColumnSelector,
setShowColumnSelector,
visibleColumns,
handleColumnVisibilityChange,
handleSelectAll,
initDefaultColumns,
COLUMN_KEYS,
isAdminUser,
copyText,
openContentModal,
usageRecordMode = false,
t,
}) => {
// Get all columns for display in selector
const allColumns = getTaskLogsColumns({
t,
COLUMN_KEYS,
copyText,
openContentModal,
isAdminUser,
});
// 计算"全选"状态时应忽略的 key:当前角色下不可见的管理员专属列
// 否则非管理员下 CHANNEL 永远为 false,导致 every 永远为 false、全选框永远半选
const isHiddenForRole = (key) => !isAdminUser && key === COLUMN_KEYS.CHANNEL;
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) {
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,268 @@
/*
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, { useState, useEffect } from 'react';
import { Modal, Button, Typography, Spin } from '@douyinfe/semi-ui';
import { IconExternalOpen, IconCopy } from '@douyinfe/semi-icons';
import { Check, Copy, ExternalLink, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const ContentModal = ({
isModalOpen,
setIsModalOpen,
modalContent,
// 上游原始可分享 URL,用于"复制链接"/"新标签页打开";未传则回落到 modalContent
sourceUrl,
isVideo,
usageRecordMode = false,
}) => {
const { t } = useTranslation();
const [videoError, setVideoError] = useState(false);
const [isLoading, setIsLoading] = useState(false);
// 复制/打开操作都用上游原始 URL,代理路径可能带鉴权或外部无法访问
const shareUrl = sourceUrl || modalContent;
useEffect(() => {
if (isModalOpen && isVideo) {
setVideoError(false);
setIsLoading(true);
}
}, [isModalOpen, isVideo]);
const handleVideoError = () => {
setVideoError(true);
setIsLoading(false);
};
const handleVideoLoaded = () => {
setIsLoading(false);
};
const handleCopyUrl = () => {
navigator.clipboard.writeText(shareUrl);
};
const handleOpenInNewTab = () => {
window.open(shareUrl, '_blank');
};
const renderVideoContent = () => {
if (videoError) {
return (
<div style={{ textAlign: 'center', padding: '40px' }}>
<Text
type='tertiary'
style={{ display: 'block', marginBottom: '16px' }}
>
{t('视频无法在当前浏览器中播放,这可能是由于:')}
</Text>
<Text
type='tertiary'
style={{ display: 'block', marginBottom: '8px', fontSize: '12px' }}
>
{t('• 视频服务商的跨域限制')}
</Text>
<Text
type='tertiary'
style={{ display: 'block', marginBottom: '8px', fontSize: '12px' }}
>
{t('• 需要特定的请求头或认证')}
</Text>
<Text
type='tertiary'
style={{ display: 'block', marginBottom: '16px', fontSize: '12px' }}
>
{t('• 防盗链保护机制')}
</Text>
<div style={{ marginTop: '20px' }}>
<Button
icon={
usageRecordMode ? (
<ExternalLink className='w-3.5 h-3.5' />
) : (
<IconExternalOpen />
)
}
onClick={handleOpenInNewTab}
style={{ marginRight: '8px' }}
className={
usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: undefined
}
>
{t('在新标签页中打开')}
</Button>
<Button
icon={
usageRecordMode ? (
<Copy className='w-3.5 h-3.5' />
) : (
<IconCopy />
)
}
onClick={handleCopyUrl}
className={
usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: undefined
}
>
{t('复制链接')}
</Button>
</div>
<div
style={{
marginTop: '16px',
padding: '8px',
backgroundColor: '#f8f9fa',
borderRadius: '4px',
}}
>
<Text
type='tertiary'
style={{ fontSize: '10px', wordBreak: 'break-all' }}
>
{shareUrl}
</Text>
</div>
</div>
);
}
return (
<div style={{ position: 'relative' }}>
{isLoading && (
<div
style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
zIndex: 10,
}}
>
<Spin size='large' />
</div>
)}
<video
src={modalContent}
controls
style={{ width: '100%' }}
autoPlay
crossOrigin='anonymous'
onError={handleVideoError}
onLoadedData={handleVideoLoaded}
onLoadStart={() => setIsLoading(true)}
/>
{/* 播放成功时也提供复制/新标签页按钮,复制的是上游分享 URL 而非代理路径 */}
<div
style={{
marginTop: '12px',
display: 'flex',
gap: '8px',
justifyContent: 'flex-end',
}}
>
<Button
size='small'
icon={
usageRecordMode ? <Copy className='w-3.5 h-3.5' /> : <IconCopy />
}
onClick={handleCopyUrl}
className={
usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: undefined
}
>
{t('复制链接')}
</Button>
<Button
size='small'
icon={
usageRecordMode ? (
<ExternalLink className='w-3.5 h-3.5' />
) : (
<IconExternalOpen />
)
}
onClick={handleOpenInNewTab}
className={
usageRecordMode
? 'usage-record-action-button usage-record-action-button-soft'
: undefined
}
>
{t('在新标签页打开')}
</Button>
</div>
</div>
);
};
return (
<Modal
visible={isModalOpen}
onOk={() => setIsModalOpen(false)}
onCancel={() => setIsModalOpen(false)}
closable={null}
bodyStyle={{
height: isVideo ? '450px' : '400px',
overflowX: 'hidden',
overflowY: 'auto',
padding: isVideo && videoError ? '0' : '24px',
}}
width={800}
okButtonProps={
usageRecordMode
? {
icon: <Check className='w-3.5 h-3.5' style={{ color: '#fff' }} />,
className:
'usage-record-action-button usage-record-action-button-primary',
}
: undefined
}
cancelButtonProps={
usageRecordMode
? {
icon: <X className='w-3.5 h-3.5' />,
className:
'usage-record-action-button usage-record-action-button-soft',
}
: undefined
}
>
{isVideo ? (
renderVideoContent()
) : (
<p style={{ whiteSpace: 'pre-line', overflowWrap: 'anywhere' }}>
{modalContent}
</p>
)}
</Modal>
);
};
export default ContentModal;
@@ -0,0 +1,118 @@
/*
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, { useState } from 'react';
import { Button } from '@douyinfe/semi-ui';
import { showError } from '../../../helpers';
import CopyTokensModal from './modals/CopyTokensModal';
import DeleteTokensModal from './modals/DeleteTokensModal';
const TokensActions = ({
selectedKeys,
setEditingToken,
setShowEdit,
batchCopyTokens,
batchDeleteTokens,
copyText,
t,
}) => {
// Modal states
const [showCopyModal, setShowCopyModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
// Handle copy selected tokens with options
const handleCopySelectedTokens = () => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个令牌!'));
return;
}
setShowCopyModal(true);
};
// Handle delete selected tokens with confirmation
const handleDeleteSelectedTokens = () => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个令牌!'));
return;
}
setShowDeleteModal(true);
};
// Handle delete confirmation
const handleConfirmDelete = () => {
batchDeleteTokens();
setShowDeleteModal(false);
};
return (
<>
<div className='flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
type='primary'
className='flex-1 md:flex-initial'
onClick={() => {
setEditingToken({
id: undefined,
});
setShowEdit(true);
}}
size='small'
>
{t('添加令牌')}
</Button>
<Button
type='tertiary'
className='flex-1 md:flex-initial'
onClick={handleCopySelectedTokens}
size='small'
>
{t('复制所选令牌')}
</Button>
<Button
type='danger'
className='w-full md:w-auto'
onClick={handleDeleteSelectedTokens}
size='small'
>
{t('删除所选令牌')}
</Button>
</div>
<CopyTokensModal
visible={showCopyModal}
onCancel={() => setShowCopyModal(false)}
selectedKeys={selectedKeys}
copyText={copyText}
t={t}
/>
<DeleteTokensModal
visible={showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
onConfirm={handleConfirmDelete}
selectedKeys={selectedKeys}
t={t}
/>
</>
);
};
export default TokensActions;
@@ -0,0 +1,511 @@
/*
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,
Dropdown,
Space,
SplitButtonGroup,
Tag,
AvatarGroup,
Avatar,
Tooltip,
Progress,
Popover,
Typography,
Input,
Modal,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
renderGroup,
renderQuota,
getModelCategories,
showError,
} from '../../../helpers';
import {
IconTreeTriangleDown,
IconCopy,
IconEyeOpened,
IconEyeClosed,
} from '@douyinfe/semi-icons';
// progress color helper
const getProgressColor = (pct) => {
if (pct === 100) return 'var(--semi-color-success)';
if (pct <= 10) return 'var(--semi-color-danger)';
if (pct <= 30) return 'var(--semi-color-warning)';
return undefined;
};
// Render functions
function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>;
}
// Render status column only (no usage)
const renderStatus = (text, record, t) => {
const enabled = text === 1;
let tagColor = 'black';
let tagText = t('未知状态');
if (enabled) {
tagColor = 'green';
tagText = t('已启用');
} else if (text === 2) {
tagColor = 'red';
tagText = t('已禁用');
} else if (text === 3) {
tagColor = 'yellow';
tagText = t('已过期');
} else if (text === 4) {
tagColor = 'grey';
tagText = t('已耗尽');
}
return (
<Tag color={tagColor} shape='circle' size='small'>
{tagText}
</Tag>
);
};
// Render group column
const renderGroupColumn = (text, t) => {
if (text === 'auto') {
return (
<Tooltip
content={t(
'当前分组为 auto,会自动选择最优分组,当一个组不可用时自动降级到下一个组(熔断机制)',
)}
position='top'
>
<Tag color='white' shape='circle'>
{' '}
{t('智能熔断')}{' '}
</Tag>
</Tooltip>
);
}
return renderGroup(text);
};
// Render token key column with show/hide and copy functionality
const renderTokenKey = (text, record, showKeys, setShowKeys, copyText) => {
const fullKey = 'sk-' + record.key;
const maskedKey =
'sk-' + record.key.slice(0, 4) + '**********' + record.key.slice(-4);
const revealed = !!showKeys[record.id];
return (
<div className='w-[200px]'>
<Input
readOnly
value={revealed ? fullKey : maskedKey}
size='small'
suffix={
<div className='flex items-center'>
<Button
theme='borderless'
size='small'
type='tertiary'
icon={revealed ? <IconEyeClosed /> : <IconEyeOpened />}
aria-label='toggle token visibility'
onClick={(e) => {
e.stopPropagation();
setShowKeys((prev) => ({ ...prev, [record.id]: !revealed }));
}}
/>
<Button
theme='borderless'
size='small'
type='tertiary'
icon={<IconCopy />}
aria-label='copy token key'
onClick={async (e) => {
e.stopPropagation();
await copyText(fullKey);
}}
/>
</div>
}
/>
</div>
);
};
// Render model limits column
const renderModelLimits = (text, record, t) => {
if (record.model_limits_enabled && text) {
const models = text.split(',').filter(Boolean);
const categories = getModelCategories(t);
const vendorAvatars = [];
const matchedModels = new Set();
Object.entries(categories).forEach(([key, category]) => {
if (key === 'all') return;
if (!category.icon || !category.filter) return;
const vendorModels = models.filter((m) =>
category.filter({ model_name: m }),
);
if (vendorModels.length > 0) {
vendorAvatars.push(
<Tooltip
key={key}
content={vendorModels.join(', ')}
position='top'
showArrow
>
<Avatar
size='extra-extra-small'
alt={category.label}
color='transparent'
>
{category.icon}
</Avatar>
</Tooltip>,
);
vendorModels.forEach((m) => matchedModels.add(m));
}
});
const unmatchedModels = models.filter((m) => !matchedModels.has(m));
if (unmatchedModels.length > 0) {
vendorAvatars.push(
<Tooltip
key='unknown'
content={unmatchedModels.join(', ')}
position='top'
showArrow
>
<Avatar size='extra-extra-small' alt='unknown'>
{t('其他')}
</Avatar>
</Tooltip>,
);
}
return <AvatarGroup size='extra-extra-small'>{vendorAvatars}</AvatarGroup>;
} else {
return (
<Tag color='white' shape='circle'>
{t('无限制')}
</Tag>
);
}
};
// Render IP restrictions column
const renderAllowIps = (text, t) => {
if (!text || text.trim() === '') {
return (
<Tag color='white' shape='circle'>
{t('无限制')}
</Tag>
);
}
const ips = text
.split('\n')
.map((ip) => ip.trim())
.filter(Boolean);
const displayIps = ips.slice(0, 1);
const extraCount = ips.length - displayIps.length;
const ipTags = displayIps.map((ip, idx) => (
<Tag key={idx} shape='circle'>
{ip}
</Tag>
));
if (extraCount > 0) {
ipTags.push(
<Tooltip
key='extra'
content={ips.slice(1).join(', ')}
position='top'
showArrow
>
<Tag shape='circle'>{'+' + extraCount}</Tag>
</Tooltip>,
);
}
return <Space wrap>{ipTags}</Space>;
};
// Render separate quota usage column
const renderQuotaUsage = (text, record, t) => {
const { Paragraph } = Typography;
const used = parseInt(record.used_quota) || 0;
const remain = parseInt(record.remain_quota) || 0;
const total = used + remain;
if (record.unlimited_quota) {
const popoverContent = (
<div className='text-xs p-2'>
<Paragraph copyable={{ content: renderQuota(used) }}>
{t('已用额度')}: {renderQuota(used)}
</Paragraph>
</div>
);
return (
<Popover content={popoverContent} position='top'>
<Tag color='white' shape='circle'>
{t('无限额度')}
</Tag>
</Popover>
);
}
const percent = total > 0 ? (remain / total) * 100 : 0;
const popoverContent = (
<div className='text-xs p-2'>
<Paragraph copyable={{ content: renderQuota(used) }}>
{t('已用额度')}: {renderQuota(used)}
</Paragraph>
<Paragraph copyable={{ content: renderQuota(remain) }}>
{t('剩余额度')}: {renderQuota(remain)} ({percent.toFixed(0)}%)
</Paragraph>
<Paragraph copyable={{ content: renderQuota(total) }}>
{t('总额度')}: {renderQuota(total)}
</Paragraph>
</div>
);
return (
<Popover content={popoverContent} position='top'>
<Tag color='white' shape='circle'>
<div className='flex flex-col items-end'>
<span className='text-xs leading-none'>{`${renderQuota(remain)} / ${renderQuota(total)}`}</span>
<Progress
percent={percent}
stroke={getProgressColor(percent)}
aria-label='quota usage'
format={() => `${percent.toFixed(0)}%`}
style={{ width: '100%', marginTop: '1px', marginBottom: 0 }}
/>
</div>
</Tag>
</Popover>
);
};
// Render operations column
const renderOperations = (
text,
record,
onOpenLink,
setEditingToken,
setShowEdit,
manageToken,
refresh,
t,
) => {
let chatsArray = [];
try {
const raw = localStorage.getItem('chats');
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
for (let i = 0; i < parsed.length; i++) {
const item = parsed[i];
const name = Object.keys(item)[0];
if (!name) continue;
chatsArray.push({
node: 'item',
key: i,
name,
value: item[name],
onClick: () => onOpenLink(name, item[name], record),
});
}
}
} catch (_) {
showError(t('聊天链接配置错误,请联系管理员'));
}
return (
<Space wrap>
<SplitButtonGroup
className='overflow-hidden'
aria-label={t('项目操作按钮组')}
>
<Button
size='small'
type='tertiary'
onClick={() => {
if (chatsArray.length === 0) {
showError(t('请联系管理员配置聊天链接'));
} else {
const first = chatsArray[0];
onOpenLink(first.name, first.value, record);
}
}}
>
{t('聊天')}
</Button>
<Dropdown trigger='click' position='bottomRight' menu={chatsArray}>
<Button
type='tertiary'
icon={<IconTreeTriangleDown />}
size='small'
></Button>
</Dropdown>
</SplitButtonGroup>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={async () => {
await manageToken(record.id, 'disable', record);
await refresh();
}}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={async () => {
await manageToken(record.id, 'enable', record);
await refresh();
}}
>
{t('启用')}
</Button>
)}
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingToken(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='danger'
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此令牌?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
await manageToken(record.id, 'delete', record);
await refresh();
})();
},
});
}}
>
{t('删除')}
</Button>
</Space>
);
};
export const getTokensColumns = ({
t,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
}) => {
return [
{
title: t('名称'),
dataIndex: 'name',
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
render: (text, record) => renderStatus(text, record, t),
},
{
title: t('剩余额度/总额度'),
key: 'quota_usage',
render: (text, record) => renderQuotaUsage(text, record, t),
},
{
title: t('分组'),
dataIndex: 'group',
key: 'group',
render: (text) => renderGroupColumn(text, t),
},
{
title: t('密钥'),
key: 'token_key',
render: (text, record) =>
renderTokenKey(text, record, showKeys, setShowKeys, copyText),
},
{
title: t('可用模型'),
dataIndex: 'model_limits',
render: (text, record) => renderModelLimits(text, record, t),
},
{
title: t('IP限制'),
dataIndex: 'allow_ips',
render: (text) => renderAllowIps(text, t),
},
{
title: t('创建时间'),
dataIndex: 'created_time',
render: (text, record, index) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: t('过期时间'),
dataIndex: 'expired_time',
render: (text, record, index) => {
return (
<div>
{record.expired_time === -1 ? t('永不过期') : renderTimestamp(text)}
</div>
);
},
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) =>
renderOperations(
text,
record,
onOpenLink,
setEditingToken,
setShowEdit,
manageToken,
refresh,
t,
),
},
];
};
@@ -0,0 +1,44 @@
/*
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 { Typography } from '@douyinfe/semi-ui';
import { Key } from 'lucide-react';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const TokensDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center text-blue-500'>
<Key size={16} className='mr-2' />
<Text>{t('令牌管理')}</Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default TokensDescription;
@@ -0,0 +1,106 @@
/*
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, { useRef } from 'react';
import { Form, Button } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
const TokensFilters = ({
formInitValues,
setFormApi,
searchTokens,
loading,
searching,
t,
}) => {
// Handle form reset and immediate search
const formApiRef = useRef(null);
const handleReset = () => {
if (!formApiRef.current) return;
formApiRef.current.reset();
setTimeout(() => {
searchTokens();
}, 100);
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => {
setFormApi(api);
formApiRef.current = api;
}}
onSubmit={searchTokens}
allowEmpty={true}
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className='w-full md:w-auto order-1 md:order-2'
>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto'>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('搜索关键字')}
showClear
pure
size='small'
/>
</div>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchToken'
prefix={<IconSearch />}
placeholder={t('密钥')}
showClear
pure
size='small'
/>
</div>
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading || searching}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={handleReset}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
);
};
export default TokensFilters;
+124
View File
@@ -0,0 +1,124 @@
/*
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 } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getTokensColumns } from './TokensColumnDefs';
const TokensTable = (tokensData) => {
const {
tokens,
loading,
activePage,
pageSize,
tokenCount,
compactMode,
handlePageChange,
handlePageSizeChange,
rowSelection,
handleRow,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
t,
} = tokensData;
// Get all columns
const columns = useMemo(() => {
return getTokensColumns({
t,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
});
}, [
t,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
]);
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
<CardTable
columns={tableColumns}
dataSource={tokens}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
size='middle'
/>
);
};
export default TokensTable;

Some files were not shown because too many files have changed in this diff Show More