🎨 chore(web): apply ESLint and Prettier auto-fixes (baseline)

- Ran: bun run eslint:fix && bun run lint:fix
- Inserted AGPL license header via eslint-plugin-header
- Enforced no-multiple-empty-lines and other lint rules
- Formatted code using Prettier v3 (@so1ve/prettier-config)
- No functional changes; formatting-only baseline across JS/JSX files
This commit is contained in:
t0ng7u
2025-08-30 21:15:10 +08:00
parent 41cf516ec5
commit 0d57b1acd4
274 changed files with 11025 additions and 7659 deletions

View File

@@ -24,7 +24,7 @@ import {
Modal,
Switch,
Typography,
Select
Select,
} from '@douyinfe/semi-ui';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
@@ -52,19 +52,19 @@ const ChannelsActions = ({
activePage,
pageSize,
setActivePage,
t
t,
}) => {
return (
<div className="flex flex-col gap-2">
<div className='flex flex-col gap-2'>
{/* 第一行:批量操作按钮 + 设置开关 */}
<div className="flex flex-col md:flex-row justify-between 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">
<div className='flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
size='small'
disabled={!enableBatchDelete}
type='danger'
className="w-full md:w-auto"
className='w-full md:w-auto'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除所选通道?'),
@@ -81,7 +81,7 @@ const ChannelsActions = ({
disabled={!enableBatchDelete}
type='tertiary'
onClick={() => setShowBatchSetTag(true)}
className="w-full md:w-auto"
className='w-full md:w-auto'
>
{t('批量设置标签')}
</Button>
@@ -95,7 +95,7 @@ const ChannelsActions = ({
<Button
size='small'
type='tertiary'
className="w-full"
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定?'),
@@ -112,11 +112,13 @@ const ChannelsActions = ({
<Dropdown.Item>
<Button
size='small'
className="w-full"
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定是否要修复数据库一致性?'),
content: t('进行该操作时,可能导致渠道访问错误,请仅在数据库出现问题时使用'),
content: t(
'进行该操作时,可能导致渠道访问错误,请仅在数据库出现问题时使用',
),
onOk: () => fixChannelsAbilities(),
size: 'sm',
centered: true,
@@ -130,7 +132,7 @@ const ChannelsActions = ({
<Button
size='small'
type='secondary'
className="w-full"
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定?'),
@@ -148,7 +150,7 @@ const ChannelsActions = ({
<Button
size='small'
type='danger'
className="w-full"
className='w-full'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除禁用通道?'),
@@ -165,7 +167,12 @@ const ChannelsActions = ({
</Dropdown.Menu>
}
>
<Button size='small' theme='light' type='tertiary' className="w-full md:w-auto">
<Button
size='small'
theme='light'
type='tertiary'
className='w-full md:w-auto'
>
{t('批量操作')}
</Button>
</Dropdown>
@@ -178,9 +185,9 @@ const ChannelsActions = ({
</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">
<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
@@ -189,18 +196,30 @@ const ChannelsActions = ({
onChange={(v) => {
localStorage.setItem('id-sort', v + '');
setIdSort(v);
const { searchKeyword, searchGroup, searchModel } = getFormValues();
if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
const { searchKeyword, searchGroup, searchModel } =
getFormValues();
if (
searchKeyword === '' &&
searchGroup === '' &&
searchModel === ''
) {
loadChannels(activePage, pageSize, v, enableTagMode);
} else {
searchChannels(enableTagMode, activeTypeKey, statusFilter, activePage, pageSize, v);
searchChannels(
enableTagMode,
activeTypeKey,
statusFilter,
activePage,
pageSize,
v,
);
}
}}
/>
</div>
<div className="flex items-center justify-between w-full md:w-auto">
<Typography.Text strong className="mr-2">
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('开启批量操作')}
</Typography.Text>
<Switch
@@ -213,8 +232,8 @@ const ChannelsActions = ({
/>
</div>
<div className="flex items-center justify-between w-full md:w-auto">
<Typography.Text strong className="mr-2">
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('标签聚合模式')}
</Typography.Text>
<Switch
@@ -229,8 +248,8 @@ const ChannelsActions = ({
/>
</div>
<div className="flex items-center justify-between w-full md:w-auto">
<Typography.Text strong className="mr-2">
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('状态筛选')}
</Typography.Text>
<Select
@@ -240,12 +259,19 @@ const ChannelsActions = ({
localStorage.setItem('channel-status-filter', v);
setStatusFilter(v);
setActivePage(1);
loadChannels(1, pageSize, idSort, enableTagMode, activeTypeKey, v);
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.Option value='all'>{t('全部')}</Select.Option>
<Select.Option value='enabled'>{t('已启用')}</Select.Option>
<Select.Option value='disabled'>{t('已禁用')}</Select.Option>
</Select>
</div>
</div>
@@ -254,4 +280,4 @@ const ChannelsActions = ({
);
};
export default ChannelsActions;
export default ChannelsActions;

View File

@@ -27,14 +27,14 @@ import {
SplitButtonGroup,
Tag,
Tooltip,
Typography
Typography,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
renderGroup,
renderQuota,
getChannelIcon,
renderQuotaWithAmount
renderQuotaWithAmount,
} from '../../../helpers';
import { CHANNEL_OPTIONS } from '../../../constants';
import { IconTreeTriangleDown, IconMore } from '@douyinfe/semi-icons';
@@ -51,27 +51,22 @@ const renderType = (type, channelInfo = undefined, t) => {
let icon = getChannelIcon(type);
if (channelInfo?.is_multi_key) {
icon = (
icon =
channelInfo?.multi_key_mode === 'random' ? (
<div className="flex items-center gap-1">
<FaRandom className="text-blue-500" />
<div className='flex items-center gap-1'>
<FaRandom className='text-blue-500' />
{icon}
</div>
) : (
<div className="flex items-center gap-1">
<IconTreeTriangleDown className="text-blue-500" />
<div className='flex items-center gap-1'>
<IconTreeTriangleDown className='text-blue-500' />
{icon}
</div>
)
)
);
}
return (
<Tag
color={type2label[type]?.color}
shape='circle'
prefixIcon={icon}
>
<Tag color={type2label[type]?.color} shape='circle' prefixIcon={icon}>
{type2label[type]?.label}
</Tag>
);
@@ -79,11 +74,7 @@ const renderType = (type, channelInfo = undefined, t) => {
const renderTagType = (t) => {
return (
<Tag
color='light-blue'
shape='circle'
type='light'
>
<Tag color='light-blue' shape='circle' type='light'>
{t('标签聚合')}
</Tag>
);
@@ -95,7 +86,8 @@ const renderStatus = (status, channelInfo = undefined, t) => {
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;
enabledKeySize =
keySize - Object.keys(channelInfo.multi_key_status_list).length;
}
return renderMultiKeyStatus(status, keySize, enabledKeySize, t);
}
@@ -155,7 +147,7 @@ const renderMultiKeyStatus = (status, keySize, enabledKeySize, t) => {
</Tag>
);
}
}
};
const renderResponseTime = (responseTime, t) => {
let time = responseTime / 1000;
@@ -212,7 +204,7 @@ export const getChannelsColumns = ({
activePage,
channels,
setShowMultiKeyManageModal,
setCurrentMultiKeyChannel
setCurrentMultiKeyChannel,
}) => {
return [
{
@@ -276,7 +268,9 @@ export const getChannelsColumns = ({
return (
<div>
<Tooltip
content={t('原因:') + reason + t(',时间:') + timestamp2string(time)}
content={
t('原因:') + reason + t(',时间:') + timestamp2string(time)
}
>
{renderStatus(text, record.channel_info, t)}
</Tooltip>
@@ -291,9 +285,7 @@ export const getChannelsColumns = ({
key: COLUMN_KEYS.RESPONSE_TIME,
title: t('响应时间'),
dataIndex: 'response_time',
render: (text, record, index) => (
<div>{renderResponseTime(text, t)}</div>
),
render: (text, record, index) => <div>{renderResponseTime(text, t)}</div>,
},
{
key: COLUMN_KEYS.BALANCE,
@@ -309,7 +301,9 @@ export const getChannelsColumns = ({
{renderQuota(record.used_quota)}
</Tag>
</Tooltip>
<Tooltip content={t('剩余额度$') + record.balance + t(',点击更新')}>
<Tooltip
content={t('剩余额度$') + record.balance + t(',点击更新')}
>
<Tag
color='white'
type='ghost'
@@ -351,7 +345,7 @@ export const getChannelsColumns = ({
innerButtons
defaultValue={record.priority}
min={-999}
size="small"
size='small'
/>
</div>
);
@@ -364,7 +358,10 @@ export const getChannelsColumns = ({
onBlur={(e) => {
Modal.warning({
title: t('修改子渠道优先级'),
content: t('确定要修改所有子渠道优先级为 ') + e.target.value + t(' 吗?'),
content:
t('确定要修改所有子渠道优先级为 ') +
e.target.value +
t(' 吗?'),
onOk: () => {
if (e.target.value === '') {
return;
@@ -379,7 +376,7 @@ export const getChannelsColumns = ({
innerButtons
defaultValue={record.priority}
min={-999}
size="small"
size='small'
/>
);
}
@@ -403,7 +400,7 @@ export const getChannelsColumns = ({
innerButtons
defaultValue={record.weight}
min={0}
size="small"
size='small'
/>
</div>
);
@@ -416,7 +413,10 @@ export const getChannelsColumns = ({
onBlur={(e) => {
Modal.warning({
title: t('修改子渠道权重'),
content: t('确定要修改所有子渠道权重为 ') + e.target.value + t(' 吗?'),
content:
t('确定要修改所有子渠道权重为 ') +
e.target.value +
t(' 吗?'),
onOk: () => {
if (e.target.value === '') {
return;
@@ -431,7 +431,7 @@ export const getChannelsColumns = ({
innerButtons
defaultValue={record.weight}
min={-999}
size="small"
size='small'
/>
);
}
@@ -484,18 +484,18 @@ export const getChannelsColumns = ({
return (
<Space wrap>
<SplitButtonGroup
className="overflow-hidden"
className='overflow-hidden'
aria-label={t('测试单个渠道操作项目组')}
>
<Button
size="small"
size='small'
type='tertiary'
onClick={() => testChannel(record, '')}
>
{t('测试')}
</Button>
<Button
size="small"
size='small'
type='tertiary'
icon={<IconTreeTriangleDown />}
onClick={() => {
@@ -505,32 +505,28 @@ export const getChannelsColumns = ({
/>
</SplitButtonGroup>
{
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.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('多密钥渠道操作项目组')}
>
<SplitButtonGroup aria-label={t('多密钥渠道操作项目组')}>
<Button
type='tertiary'
size="small"
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
@@ -549,12 +545,12 @@ export const getChannelsColumns = ({
setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true);
},
}
},
]}
>
<Button
type='tertiary'
size="small"
size='small'
icon={<IconTreeTriangleDown />}
/>
</Dropdown>
@@ -562,7 +558,7 @@ export const getChannelsColumns = ({
) : (
<Button
type='tertiary'
size="small"
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
@@ -577,11 +573,7 @@ export const getChannelsColumns = ({
position='bottomRight'
menu={moreMenuItems}
>
<Button
icon={<IconMore />}
type='tertiary'
size="small"
/>
<Button icon={<IconMore />} type='tertiary' size='small' />
</Dropdown>
</Space>
);
@@ -591,21 +583,21 @@ export const getChannelsColumns = ({
<Space wrap>
<Button
type='tertiary'
size="small"
size='small'
onClick={() => manageTag(record.key, 'enable')}
>
{t('启用全部')}
</Button>
<Button
type='tertiary'
size="small"
size='small'
onClick={() => manageTag(record.key, 'disable')}
>
{t('禁用全部')}
</Button>
<Button
type='tertiary'
size="small"
size='small'
onClick={() => {
setShowEditTag(true);
setEditingTag(record.key);
@@ -619,4 +611,4 @@ export const getChannelsColumns = ({
},
},
];
};
};

View File

@@ -34,16 +34,16 @@ const ChannelsFilters = ({
groupOptions,
loading,
searching,
t
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">
<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'>
<Button
size='small'
theme='light'
type='primary'
className="w-full md:w-auto"
className='w-full md:w-auto'
onClick={() => {
setEditingChannel({
id: undefined,
@@ -57,7 +57,7 @@ const ChannelsFilters = ({
<Button
size='small'
type='tertiary'
className="w-full md:w-auto"
className='w-full md:w-auto'
onClick={refresh}
>
{t('刷新')}
@@ -67,54 +67,54 @@ const ChannelsFilters = ({
size='small'
type='tertiary'
onClick={() => setShowColumnSelector(true)}
className="w-full md:w-auto"
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">
<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"
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className="flex flex-col md:flex-row items-center gap-2 w-full"
className='flex flex-col md:flex-row items-center gap-2 w-full'
>
<div className="relative w-full md:w-64">
<div className='relative w-full md:w-64'>
<Form.Input
size='small'
field="searchKeyword"
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('渠道ID名称密钥API地址')}
showClear
pure
/>
</div>
<div className="w-full md:w-48">
<div className='w-full md:w-48'>
<Form.Input
size='small'
field="searchModel"
field='searchModel'
prefix={<IconSearch />}
placeholder={t('模型关键字')}
showClear
pure
/>
</div>
<div className="w-full md:w-32">
<div className='w-full md:w-32'>
<Form.Select
size='small'
field="searchGroup"
field='searchGroup'
placeholder={t('选择分组')}
optionList={[
{ label: t('选择分组'), value: null },
...groupOptions,
]}
className="w-full"
className='w-full'
showClear
pure
onChange={() => {
@@ -127,10 +127,10 @@ const ChannelsFilters = ({
</div>
<Button
size='small'
type="tertiary"
htmlType="submit"
type='tertiary'
htmlType='submit'
loading={loading || searching}
className="w-full md:w-auto"
className='w-full md:w-auto'
>
{t('查询')}
</Button>
@@ -146,7 +146,7 @@ const ChannelsFilters = ({
}, 100);
}
}}
className="w-full md:w-auto"
className='w-full md:w-auto'
>
{t('重置')}
</Button>
@@ -156,4 +156,4 @@ const ChannelsFilters = ({
);
};
export default ChannelsFilters;
export default ChannelsFilters;

View File

@@ -22,7 +22,7 @@ import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { getChannelsColumns } from './ChannelsColumnDefs';
@@ -142,25 +142,27 @@ const ChannelsTable = (channelsData) => {
rowSelection={
enableBatchDelete
? {
onChange: (selectedRowKeys, selectedRows) => {
setSelectedChannels(selectedRows);
},
}
onChange: (selectedRowKeys, selectedRows) => {
setSelectedChannels(selectedRows);
},
}
: null
}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className="rounded-xl overflow-hidden"
size="middle"
className='rounded-xl overflow-hidden'
size='middle'
loading={loading || searching}
/>
);
};
export default ChannelsTable;
export default ChannelsTable;

View File

@@ -33,7 +33,7 @@ const ChannelsTabs = ({
pageSize,
idSort,
setActivePage,
t
t,
}) => {
if (enableTagMode) return null;
@@ -46,24 +46,29 @@ const ChannelsTabs = ({
return (
<Tabs
activeKey={activeTypeKey}
type="card"
type='card'
collapsible
onChange={handleTabChange}
className="mb-2"
className='mb-2'
>
<TabPane
itemKey="all"
itemKey='all'
tab={
<span className="flex items-center gap-2">
<span className='flex items-center gap-2'>
{t('全部')}
<Tag color={activeTypeKey === 'all' ? 'red' : 'grey'} shape='circle'>
<Tag
color={activeTypeKey === 'all' ? 'red' : 'grey'}
shape='circle'
>
{channelTypeCounts['all'] || 0}
</Tag>
</span>
}
/>
{CHANNEL_OPTIONS.filter((opt) => availableTypeKeys.includes(String(opt.value))).map((option) => {
{CHANNEL_OPTIONS.filter((opt) =>
availableTypeKeys.includes(String(opt.value)),
).map((option) => {
const key = String(option.value);
const count = channelTypeCounts[option.value] || 0;
return (
@@ -71,10 +76,13 @@ const ChannelsTabs = ({
key={key}
itemKey={key}
tab={
<span className="flex items-center gap-2">
<span className='flex items-center gap-2'>
{getChannelIcon(option.value)}
{option.label}
<Tag color={activeTypeKey === key ? 'red' : 'grey'} shape='circle'>
<Tag
color={activeTypeKey === key ? 'red' : 'grey'}
shape='circle'
>
{count}
</Tag>
</span>
@@ -86,4 +94,4 @@ const ChannelsTabs = ({
);
};
export default ChannelsTabs;
export default ChannelsTabs;

View File

@@ -64,7 +64,7 @@ const ChannelsPage = () => {
{/* Main Content */}
<CardPro
type="type3"
type='type3'
tabsArea={<ChannelsTabs {...channelsData} />}
actionsArea={<ChannelsActions {...channelsData} />}
searchArea={<ChannelsFilters {...channelsData} />}
@@ -85,4 +85,4 @@ const ChannelsPage = () => {
);
};
export default ChannelsPage;
export default ChannelsPage;

View File

@@ -27,7 +27,7 @@ const BatchTagModal = ({
batchSetTagValue,
setBatchSetTagValue,
selectedChannels,
t
t,
}) => {
return (
<Modal
@@ -37,10 +37,10 @@ const BatchTagModal = ({
onCancel={() => setShowBatchSetTag(false)}
maskClosable={false}
centered={true}
size="small"
className="!rounded-lg"
size='small'
className='!rounded-lg'
>
<div className="mb-5">
<div className='mb-5'>
<Typography.Text>{t('请输入要设置的标签名称')}</Typography.Text>
</div>
<Input
@@ -48,13 +48,16 @@ const BatchTagModal = ({
value={batchSetTagValue}
onChange={(v) => setBatchSetTagValue(v)}
/>
<div className="mt-4">
<div className='mt-4'>
<Typography.Text type='secondary'>
{t('已选择 ${count} 个渠道').replace('${count}', selectedChannels.length)}
{t('已选择 ${count} 个渠道').replace(
'${count}',
selectedChannels.length,
)}
</Typography.Text>
</div>
</Modal>
);
};
export default BatchTagModal;
export default BatchTagModal;

View File

@@ -74,10 +74,8 @@ const ColumnSelectorModal = ({
visible={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
footer={
<div className="flex justify-end">
<Button onClick={() => initDefaultColumns()}>
{t('重置')}
</Button>
<div className='flex justify-end'>
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('取消')}
</Button>
@@ -100,7 +98,7 @@ const ColumnSelectorModal = ({
</Checkbox>
</div>
<div
className="flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4"
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) => {
@@ -110,10 +108,7 @@ const ColumnSelectorModal = ({
}
return (
<div
key={column.key}
className="w-1/2 mb-4 pr-2"
>
<div key={column.key} className='w-1/2 mb-4 pr-2'>
<Checkbox
checked={!!visibleColumns[column.key]}
onChange={(e) =>
@@ -130,4 +125,4 @@ const ColumnSelectorModal = ({
);
};
export default ColumnSelectorModal;
export default ColumnSelectorModal;

File diff suppressed because it is too large Load Diff

View File

@@ -289,7 +289,7 @@ const EditTagModal = (props) => {
t('已新增 {{count}} 个模型:{{list}}', {
count: addedModels.length,
list: addedModels.join(', '),
})
}),
);
} else {
showInfo(t('未发现新增模型'));
@@ -301,8 +301,10 @@ const EditTagModal = (props) => {
placement='right'
title={
<Space>
<Tag color="blue" shape="circle">{t('编辑')}</Tag>
<Title heading={4} className="m-0">
<Tag color='blue' shape='circle'>
{t('编辑')}
</Tag>
<Title heading={4} className='m-0'>
{t('编辑标签')}
</Title>
</Space>
@@ -312,10 +314,10 @@ const EditTagModal = (props) => {
width={600}
onCancel={handleClose}
footer={
<div className="flex justify-end bg-white">
<div className='flex justify-end bg-white'>
<Space>
<Button
theme="solid"
theme='solid'
onClick={() => formApiRef.current?.submitForm()}
loading={loading}
icon={<IconSave />}
@@ -323,8 +325,8 @@ const EditTagModal = (props) => {
{t('保存')}
</Button>
<Button
theme="light"
type="primary"
theme='light'
type='primary'
onClick={handleClose}
icon={<IconClose />}
>
@@ -343,26 +345,28 @@ const EditTagModal = (props) => {
>
{() => (
<Spin spinning={loading}>
<div className="p-2">
<Card className="!rounded-2xl shadow-sm border-0 mb-6">
<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">
<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>
<Text className='text-lg font-medium'>{t('标签信息')}</Text>
<div className='text-xs text-gray-600'>
{t('标签的基本配置')}
</div>
</div>
</div>
<Banner
type="warning"
type='warning'
description={t('所有编辑均为覆盖操作,留空则不更改')}
className="!rounded-lg mb-4"
className='!rounded-lg mb-4'
/>
<div className="space-y-4">
<div className='space-y-4'>
<Form.Input
field='new_tag'
label={t('标签名称')}
@@ -372,23 +376,31 @@ const EditTagModal = (props) => {
</div>
</Card>
<Card className="!rounded-2xl shadow-sm border-0 mb-6">
<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">
<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>
<Text className='text-lg font-medium'>{t('模型配置')}</Text>
<div className='text-xs text-gray-600'>
{t('模型选择和映射设置')}
</div>
</div>
</div>
<div className="space-y-4">
<div className='space-y-4'>
<Banner
type="info"
description={t('当前模型列表为该标签下所有渠道模型列表最长的一个,并非所有渠道的并集,请注意可能导致某些渠道模型丢失。')}
className="!rounded-lg mb-4"
type='info'
description={t(
'当前模型列表为该标签下所有渠道模型列表最长的一个,并非所有渠道的并集,请注意可能导致某些渠道模型丢失。',
)}
className='!rounded-lg mb-4'
/>
<Form.Select
field='models'
@@ -408,46 +420,87 @@ const EditTagModal = (props) => {
label={t('自定义模型名称')}
placeholder={t('输入自定义模型名称')}
onChange={(value) => setCustomModel(value.trim())}
suffix={<Button size='small' type='primary' onClick={addCustomModels}>{t('填入')}</Button>}
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>
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">
<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">
<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>
<Text className='text-lg font-medium'>{t('分组设置')}</Text>
<div className='text-xs text-gray-600'>
{t('用户分组配置')}
</div>
</div>
</div>
<div className="space-y-4">
<div className='space-y-4'>
<Form.Select
field='groups'
label={t('分组')}
placeholder={t('请选择可以使用该渠道的分组,留空则不更改')}
multiple
allowAdditions
additionLabel={t('请在系统设置页面编辑分组倍率以添加新的分组:')}
additionLabel={t(
'请在系统设置页面编辑分组倍率以添加新的分组:',
)}
optionList={groupOptions}
style={{ width: '100%' }}
onChange={(value) => handleInputChange('groups', value)}
@@ -462,4 +515,4 @@ const EditTagModal = (props) => {
);
};
export default EditTagModal;
export default EditTagModal;

View File

@@ -19,16 +19,31 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useState, useEffect } from 'react';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import { Modal, Checkbox, Spin, Input, Typography, Empty, Tabs, Collapse } from '@douyinfe/semi-ui';
import {
Modal,
Checkbox,
Spin,
Input,
Typography,
Empty,
Tabs,
Collapse,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { IconSearch } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
import { getModelCategories } from '../../../../helpers/render';
const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCancel }) => {
const ModelSelectModal = ({
visible,
models = [],
selected = [],
onConfirm,
onCancel,
}) => {
const { t } = useTranslation();
const [checkedList, setCheckedList] = useState(selected);
const [keyword, setKeyword] = useState('');
@@ -36,11 +51,15 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
const isMobile = useIsMobile();
const filteredModels = models.filter((m) => m.toLowerCase().includes(keyword.toLowerCase()));
const filteredModels = models.filter((m) =>
m.toLowerCase().includes(keyword.toLowerCase()),
);
// 分类模型:新获取的模型和已有模型
const newModels = filteredModels.filter(model => !selected.includes(model));
const existingModels = filteredModels.filter(model => selected.includes(model));
const newModels = filteredModels.filter((model) => !selected.includes(model));
const existingModels = filteredModels.filter((model) =>
selected.includes(model),
);
// 同步外部选中值
useEffect(() => {
@@ -68,7 +87,7 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
const categorizedModels = {};
const uncategorizedModels = [];
models.forEach(model => {
models.forEach((model) => {
let foundCategory = false;
for (const [key, category] of Object.entries(categories)) {
if (key !== 'all' && category.filter({ model_name: model })) {
@@ -76,7 +95,7 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
categorizedModels[key] = {
label: category.label,
icon: category.icon,
models: []
models: [],
};
}
categorizedModels[key].models.push(model);
@@ -94,7 +113,7 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
categorizedModels['other'] = {
label: t('其他'),
icon: null,
models: uncategorizedModels
models: uncategorizedModels,
};
}
@@ -106,14 +125,22 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
// Tab列表配置
const tabList = [
...(newModels.length > 0 ? [{
tab: `${t('新获取的模型')} (${newModels.length})`,
itemKey: 'new'
}] : []),
...(existingModels.length > 0 ? [{
tab: `${t('已有的模型')} (${existingModels.length})`,
itemKey: 'existing'
}] : [])
...(newModels.length > 0
? [
{
tab: `${t('新获取的模型')} (${newModels.length})`,
itemKey: 'new',
},
]
: []),
...(existingModels.length > 0
? [
{
tab: `${t('已有的模型')} (${existingModels.length})`,
itemKey: 'existing',
},
]
: []),
];
// 处理分类全选/取消全选
@@ -122,14 +149,16 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
if (isChecked) {
// 全选:添加该分类下所有未选中的模型
categoryModels.forEach(model => {
categoryModels.forEach((model) => {
if (!newCheckedList.includes(model)) {
newCheckedList.push(model);
}
});
} else {
// 取消全选:移除该分类下所有已选中的模型
newCheckedList = newCheckedList.filter(model => !categoryModels.includes(model));
newCheckedList = newCheckedList.filter(
(model) => !categoryModels.includes(model),
);
}
setCheckedList(newCheckedList);
@@ -137,12 +166,17 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
// 检查分类是否全选
const isCategoryAllSelected = (categoryModels) => {
return categoryModels.length > 0 && categoryModels.every(model => checkedList.includes(model));
return (
categoryModels.length > 0 &&
categoryModels.every((model) => checkedList.includes(model))
);
};
// 检查分类是否部分选中
const isCategoryIndeterminate = (categoryModels) => {
const selectedCount = categoryModels.filter(model => checkedList.includes(model)).length;
const selectedCount = categoryModels.filter((model) =>
checkedList.includes(model),
).length;
return selectedCount > 0 && selectedCount < categoryModels.length;
};
@@ -151,10 +185,15 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
if (categoryEntries.length === 0) return null;
// 生成所有面板的key确保都展开
const allActiveKeys = categoryEntries.map((_, index) => `${categoryKeyPrefix}_${index}`);
const allActiveKeys = categoryEntries.map(
(_, index) => `${categoryKeyPrefix}_${index}`,
);
return (
<Collapse key={`${categoryKeyPrefix}_${categoryEntries.length}`} defaultActiveKey={[]}>
<Collapse
key={`${categoryKeyPrefix}_${categoryEntries.length}`}
defaultActiveKey={[]}
>
{categoryEntries.map(([key, categoryData], index) => (
<Collapse.Panel
key={`${categoryKeyPrefix}_${index}`}
@@ -166,24 +205,29 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
indeterminate={isCategoryIndeterminate(categoryData.models)}
onChange={(e) => {
e.stopPropagation(); // 防止触发面板折叠
handleCategorySelectAll(categoryData.models, e.target.checked);
handleCategorySelectAll(
categoryData.models,
e.target.checked,
);
}}
onClick={(e) => e.stopPropagation()} // 防止点击checkbox时折叠面板
/>
}
>
<div className="flex items-center gap-2 mb-3">
<div className='flex items-center gap-2 mb-3'>
{categoryData.icon}
<Typography.Text type="secondary" size="small">
<Typography.Text type='secondary' size='small'>
{t('已选择 {{selected}} / {{total}}', {
selected: categoryData.models.filter(model => checkedList.includes(model)).length,
total: categoryData.models.length
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">
<div className='grid grid-cols-2 gap-x-4'>
{categoryData.models.map((model) => (
<Checkbox key={model} value={model} className="my-1">
<Checkbox key={model} value={model} className='my-1'>
{model}
</Checkbox>
))}
@@ -197,14 +241,14 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
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">
<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">
<div className='flex-shrink-0'>
<Tabs
type="slash"
size="small"
type='slash'
size='small'
tabList={tabList}
activeKey={activeTab}
onChange={(key) => setActiveTab(key)}
@@ -234,17 +278,22 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
<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 }} />}
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)}>
<Checkbox.Group
value={checkedList}
onChange={(vals) => setCheckedList(vals)}
>
{activeTab === 'new' && newModels.length > 0 && (
<div>
{renderModelsByCategory(newModelsByCategory, 'new')}
</div>
<div>{renderModelsByCategory(newModelsByCategory, 'new')}</div>
)}
{activeTab === 'existing' && existingModels.length > 0 && (
<div>
@@ -256,20 +305,30 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
</div>
</Spin>
<Typography.Text type="secondary" size="small" className="block text-right mt-4">
<div className="flex items-center justify-end gap-2">
<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;
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
total: currentModels.length,
})}
</span>
<Checkbox
@@ -288,4 +347,4 @@ const ModelSelectModal = ({ visible, models = [], selected = [], onConfirm, onCa
);
};
export default ModelSelectModal;
export default ModelSelectModal;

View File

@@ -24,7 +24,7 @@ import {
Input,
Table,
Tag,
Typography
Typography,
} from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
import { copy, showError, showInfo, showSuccess } from '../../../../helpers';
@@ -47,16 +47,16 @@ const ModelTestModal = ({
setModelTablePage,
allSelectingRef,
isMobile,
t
t,
}) => {
const hasChannel = Boolean(currentTestChannel);
const filteredModels = hasChannel
? currentTestChannel.models
.split(',')
.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
)
.split(',')
.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase()),
)
: [];
const handleCopySelected = () => {
@@ -66,7 +66,12 @@ const ModelTestModal = ({
}
copy(selectedModelKeys.join(',')).then((ok) => {
if (ok) {
showSuccess(t('已复制 ${count} 个模型').replace('${count}', selectedModelKeys.length));
showSuccess(
t('已复制 ${count} 个模型').replace(
'${count}',
selectedModelKeys.length,
),
);
} else {
showError(t('复制失败,请手动复制'));
}
@@ -93,16 +98,17 @@ const ModelTestModal = ({
title: t('模型名称'),
dataIndex: 'model',
render: (text) => (
<div className="flex items-center">
<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 testResult =
modelTestResults[`${currentTestChannel.id}-${record.model}`];
const isTesting = testingModels.has(record.model);
if (isTesting) {
@@ -122,21 +128,21 @@ const ModelTestModal = ({
}
return (
<div className="flex items-center gap-2">
<Tag
color={testResult.success ? 'green' : 'red'}
shape='circle'
>
<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 type='tertiary'>
{t('请求时长: ${time}s').replace(
'${time}',
testResult.time.toFixed(2),
)}
</Typography.Text>
)}
</div>
);
}
},
},
{
title: '',
@@ -153,8 +159,8 @@ const ModelTestModal = ({
{t('测试')}
</Button>
);
}
}
},
},
];
const dataSource = (() => {
@@ -169,108 +175,109 @@ const ModelTestModal = ({
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>
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>
</div>
) : null}
) : 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
footer={
hasChannel ? (
<div className='flex justify-end'>
{isBatchTesting ? (
<Button type='danger' onClick={handleCloseModal}>
{t('停止测试')}
</Button>
) : (
<Button type='tertiary' onClick={handleCloseModal}>
{t('取消')}
</Button>
)}
</Button>
</div>
) : null}
<Button
onClick={batchTestModels}
loading={isBatchTesting}
disabled={isBatchTesting}
>
{isBatchTesting
? t('测试中...')
: t('批量测试${count}个模型').replace(
'${count}',
filteredModels.length,
)}
</Button>
</div>
) : null
}
maskClosable={!isBatchTesting}
className="!rounded-lg"
className='!rounded-lg'
size={isMobile ? 'full-width' : 'large'}
>
{hasChannel && (<div className="model-test-scroll">
{/* 搜索与操作按钮 */}
<div className="flex items-center justify-end gap-2 w-full mb-2">
<Input
placeholder={t('搜索模型...')}
value={modelSearchKeyword}
onChange={(v) => {
setModelSearchKeyword(v);
setModelTablePage(1);
{hasChannel && (
<div className='model-test-scroll'>
{/* 搜索与操作按钮 */}
<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),
}}
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;
export default ModelTestModal;

View File

@@ -35,19 +35,22 @@ import {
Col,
Badge,
Progress,
Card
Card,
} from '@douyinfe/semi-ui';
import { IllustrationNoResult, IllustrationNoResultDark } from '@douyinfe/semi-illustrations';
import { API, showError, showSuccess, timestamp2string } from '../../../../helpers';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import {
API,
showError,
showSuccess,
timestamp2string,
} from '../../../../helpers';
const { Text } = Typography;
const MultiKeyManageModal = ({
visible,
onCancel,
channel,
onRefresh
}) => {
const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [keyStatusList, setKeyStatusList] = useState([]);
@@ -68,7 +71,11 @@ const MultiKeyManageModal = ({
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) => {
const loadKeyStatus = async (
page = currentPage,
size = pageSize,
status = statusFilter,
) => {
if (!channel?.id) return;
setLoading(true);
@@ -77,7 +84,7 @@ const MultiKeyManageModal = ({
channel_id: channel.id,
action: 'get_key_status',
page: page,
page_size: size
page_size: size,
};
// Add status filter if specified
@@ -113,13 +120,13 @@ const MultiKeyManageModal = ({
// Disable a specific key
const handleDisableKey = async (keyIndex) => {
const operationId = `disable_${keyIndex}`;
setOperationLoading(prev => ({ ...prev, [operationId]: true }));
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
key_index: keyIndex,
});
if (res.data.success) {
@@ -132,20 +139,20 @@ const MultiKeyManageModal = ({
} catch (error) {
showError(t('禁用密钥失败'));
} finally {
setOperationLoading(prev => ({ ...prev, [operationId]: false }));
setOperationLoading((prev) => ({ ...prev, [operationId]: false }));
}
};
// Enable a specific key
const handleEnableKey = async (keyIndex) => {
const operationId = `enable_${keyIndex}`;
setOperationLoading(prev => ({ ...prev, [operationId]: true }));
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
key_index: keyIndex,
});
if (res.data.success) {
@@ -158,18 +165,18 @@ const MultiKeyManageModal = ({
} catch (error) {
showError(t('启用密钥失败'));
} finally {
setOperationLoading(prev => ({ ...prev, [operationId]: false }));
setOperationLoading((prev) => ({ ...prev, [operationId]: false }));
}
};
// Enable all disabled keys
const handleEnableAll = async () => {
setOperationLoading(prev => ({ ...prev, enable_all: true }));
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'
action: 'enable_all_keys',
});
if (res.data.success) {
@@ -184,18 +191,18 @@ const MultiKeyManageModal = ({
} catch (error) {
showError(t('启用所有密钥失败'));
} finally {
setOperationLoading(prev => ({ ...prev, enable_all: false }));
setOperationLoading((prev) => ({ ...prev, enable_all: false }));
}
};
// Disable all enabled keys
const handleDisableAll = async () => {
setOperationLoading(prev => ({ ...prev, disable_all: true }));
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'
action: 'disable_all_keys',
});
if (res.data.success) {
@@ -210,18 +217,18 @@ const MultiKeyManageModal = ({
} catch (error) {
showError(t('禁用所有密钥失败'));
} finally {
setOperationLoading(prev => ({ ...prev, disable_all: false }));
setOperationLoading((prev) => ({ ...prev, disable_all: false }));
}
};
// Delete all disabled keys
const handleDeleteDisabledKeys = async () => {
setOperationLoading(prev => ({ ...prev, delete_disabled: true }));
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'
action: 'delete_disabled_keys',
});
if (res.data.success) {
@@ -236,7 +243,7 @@ const MultiKeyManageModal = ({
} catch (error) {
showError(t('删除禁用密钥失败'));
} finally {
setOperationLoading(prev => ({ ...prev, delete_disabled: false }));
setOperationLoading((prev) => ({ ...prev, delete_disabled: false }));
}
};
@@ -246,7 +253,7 @@ const MultiKeyManageModal = ({
loadKeyStatus(page, pageSize);
};
// Handle page size change
// Handle page size change
const handlePageSizeChange = (size) => {
setPageSize(size);
setCurrentPage(1); // Reset to first page
@@ -283,9 +290,12 @@ const MultiKeyManageModal = ({
}, [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;
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;
// 取消饼图:不再需要图表数据与配置
@@ -293,13 +303,29 @@ const MultiKeyManageModal = ({
const renderStatusTag = (status) => {
switch (status) {
case 1:
return <Tag color='green' shape='circle' size='small'>{t('已启用')}</Tag>;
return (
<Tag color='green' shape='circle' size='small'>
{t('已启用')}
</Tag>
);
case 2:
return <Tag color='red' shape='circle' size='small'>{t('已禁用')}</Tag>;
return (
<Tag color='red' shape='circle' size='small'>
{t('已禁用')}
</Tag>
);
case 3:
return <Tag color='orange' shape='circle' size='small'>{t('自动禁用')}</Tag>;
return (
<Tag color='orange' shape='circle' size='small'>
{t('自动禁用')}
</Tag>
);
default:
return <Tag color='grey' shape='circle' size='small'>{t('未知状态')}</Tag>;
return (
<Tag color='grey' shape='circle' size='small'>
{t('未知状态')}
</Tag>
);
}
};
@@ -349,9 +375,7 @@ const MultiKeyManageModal = ({
}
return (
<Tooltip content={timestamp2string(time)}>
<Text style={{ fontSize: '12px' }}>
{timestamp2string(time)}
</Text>
<Text style={{ fontSize: '12px' }}>{timestamp2string(time)}</Text>
</Tooltip>
);
},
@@ -393,14 +417,18 @@ const MultiKeyManageModal = ({
<Space>
<Text>{t('多密钥管理')}</Text>
{channel?.name && (
<Tag size='small' shape='circle' color='white'>{channel.name}</Tag>
<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('轮询模式')}
{channel.channel_info.multi_key_mode === 'random'
? t('随机模式')
: t('轮询模式')}
</Tag>
)}
</Space>
@@ -410,60 +438,123 @@ const MultiKeyManageModal = ({
width={900}
footer={null}
>
<div className="flex flex-col mb-5">
<div className='flex flex-col mb-5'>
{/* Stats & Mode */}
<div
className="rounded-xl p-4 mb-3"
className='rounded-xl p-4 mb-3'
style={{
background: 'var(--semi-color-bg-1)',
border: '1px solid var(--semi-color-border)'
border: '1px solid var(--semi-color-border)',
}}
>
<Row gutter={16} align="middle">
<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">
<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 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 }} />
<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">
<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 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 }} />
<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">
<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 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 }} />
<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">
<div className='flex-1 flex flex-col min-h-0'>
<Spin spinning={loading}>
<Card className='!rounded-xl'>
<Table
@@ -478,15 +569,26 @@ const MultiKeyManageModal = ({
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.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' }}>
<Col
span={10}
style={{ display: 'flex', justifyContent: 'flex-end' }}
>
<Space>
<Button
size='small'
@@ -496,7 +598,7 @@ const MultiKeyManageModal = ({
>
{t('刷新')}
</Button>
{(manualDisabledCount + autoDisabledCount) > 0 && (
{manualDisabledCount + autoDisabledCount > 0 && (
<Popconfirm
title={t('确定要启用所有密钥吗?')}
onConfirm={handleEnableAll}
@@ -529,7 +631,9 @@ const MultiKeyManageModal = ({
)}
<Popconfirm
title={t('确定要删除所有已自动禁用的密钥吗?')}
content={t('此操作不可撤销,将永久删除已自动禁用的密钥')}
content={t(
'此操作不可撤销,将永久删除已自动禁用的密钥',
)}
onConfirm={handleDeleteDisabledKeys}
okType={'danger'}
position={'topRight'}
@@ -562,7 +666,7 @@ const MultiKeyManageModal = ({
onShowSizeChange: (current, size) => {
setCurrentPage(1);
handlePageSizeChange(size);
}
},
}}
size='small'
bordered={false}
@@ -570,8 +674,16 @@ const MultiKeyManageModal = ({
scroll={{ x: 'max-content' }}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 140, height: 140 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 140, height: 140 }} />}
image={
<IllustrationNoResult
style={{ width: 140, height: 140 }}
/>
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 140, height: 140 }}
/>
}
title={t('暂无密钥数据')}
description={t('请检查渠道配置或刷新重试')}
style={{ padding: 30 }}
@@ -586,4 +698,4 @@ const MultiKeyManageModal = ({
);
};
export default MultiKeyManageModal;
export default MultiKeyManageModal;

View File

@@ -36,20 +36,22 @@ const MjLogsActions = ({
const showSkeleton = useMinimumLoadingTime(loading);
const placeholder = (
<div className="flex items-center mb-2 md:mb-0">
<IconEyeOpened className="mr-2" />
<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">
<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" />
<div className='flex items-center mb-2 md:mb-0'>
<IconEyeOpened className='mr-2' />
<Text>
{isAdminUser && showBanner
? t('当前未开启Midjourney回调部分项目可能无法获得绘图结果可在运营设置中开启。')
? t(
'当前未开启Midjourney回调部分项目可能无法获得绘图结果可在运营设置中开启。',
)
: t('Midjourney 任务记录')}
</Text>
</div>
@@ -64,4 +66,4 @@ const MjLogsActions = ({
);
};
export default MjLogsActions;
export default MjLogsActions;

View File

@@ -18,12 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import {
Button,
Progress,
Tag,
Typography
} from '@douyinfe/semi-ui';
import { Button, Progress, Tag, Typography } from '@douyinfe/semi-ui';
import {
Palette,
ZoomIn,
@@ -49,7 +44,7 @@ import {
Loader,
AlertCircle,
Hash,
Video
Video,
} from 'lucide-react';
const colors = [
@@ -153,7 +148,11 @@ function renderType(type, t) {
);
case 'INPAINT':
return (
<Tag color='violet' shape='circle' prefixIcon={<PaintBucket size={14} />}>
<Tag
color='violet'
shape='circle'
prefixIcon={<PaintBucket size={14} />}
>
{t('局部重绘-提交')}
</Tag>
);
@@ -177,7 +176,11 @@ function renderType(type, t) {
);
case 'SWAP_FACE':
return (
<Tag color='light-green' shape='circle' prefixIcon={<UserCheck size={14} />}>
<Tag
color='light-green'
shape='circle'
prefixIcon={<UserCheck size={14} />}
>
{t('换脸')}
</Tag>
);
@@ -194,7 +197,11 @@ function renderCode(code, t) {
switch (code) {
case 1:
return (
<Tag color='green' shape='circle' prefixIcon={<CheckCircle size={14} />}>
<Tag
color='green'
shape='circle'
prefixIcon={<CheckCircle size={14} />}
>
{t('已提交')}
</Tag>
);
@@ -229,7 +236,11 @@ function renderStatus(type, t) {
switch (type) {
case 'SUCCESS':
return (
<Tag color='green' shape='circle' prefixIcon={<CheckCircle size={14} />}>
<Tag
color='green'
shape='circle'
prefixIcon={<CheckCircle size={14} />}
>
{t('成功')}
</Tag>
);
@@ -259,7 +270,11 @@ function renderStatus(type, t) {
);
case 'MODAL':
return (
<Tag color='yellow' shape='circle' prefixIcon={<AlertCircle size={14} />}>
<Tag
color='yellow'
shape='circle'
prefixIcon={<AlertCircle size={14} />}
>
{t('窗口等待')}
</Tag>
);
@@ -415,7 +430,7 @@ export const getMjLogsColumns = ({
}
return (
<Button
size="small"
size='small'
onClick={() => {
openImageModal(text);
}}
@@ -493,4 +508,4 @@ export const getMjLogsColumns = ({
},
},
];
};
};

View File

@@ -37,23 +37,23 @@ const MjLogsFilters = ({
getFormApi={(api) => setFormApi(api)}
onSubmit={refresh}
allowEmpty={true}
autoComplete="off"
layout="vertical"
trigger="change"
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='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">
<div className='col-span-1 lg:col-span-2'>
<Form.DatePicker
field='dateRange'
className="w-full"
className='w-full'
type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]}
showClear
pure
size="small"
size='small'
/>
</div>
@@ -64,7 +64,7 @@ const MjLogsFilters = ({
placeholder={t('任务 ID')}
showClear
pure
size="small"
size='small'
/>
{/* 渠道 ID - 仅管理员可见 */}
@@ -75,20 +75,20 @@ const MjLogsFilters = ({
placeholder={t('渠道 ID')}
showClear
pure
size="small"
size='small'
/>
)}
</div>
{/* 操作按钮区域 */}
<div className="flex justify-between items-center">
<div className='flex justify-between items-center'>
<div></div>
<div className="flex gap-2">
<div className='flex gap-2'>
<Button
type='tertiary'
htmlType='submit'
loading={loading}
size="small"
size='small'
>
{t('查询')}
</Button>
@@ -102,14 +102,14 @@ const MjLogsFilters = ({
}, 100);
}
}}
size="small"
size='small'
>
{t('重置')}
</Button>
<Button
type='tertiary'
onClick={() => setShowColumnSelector(true)}
size="small"
size='small'
>
{t('列设置')}
</Button>
@@ -120,4 +120,4 @@ const MjLogsFilters = ({
);
};
export default MjLogsFilters;
export default MjLogsFilters;

View File

@@ -55,14 +55,7 @@ const MjLogsTable = (mjLogsData) => {
openImageModal,
isAdminUser,
});
}, [
t,
COLUMN_KEYS,
copyText,
openContentModal,
openImageModal,
isAdminUser,
]);
}, [t, COLUMN_KEYS, copyText, openContentModal, openImageModal, isAdminUser]);
// Filter columns based on visibility settings
const getVisibleColumns = () => {
@@ -86,13 +79,11 @@ const MjLogsTable = (mjLogsData) => {
rowKey='key'
loading={loading}
scroll={compactMode ? undefined : { x: 'max-content' }}
className="rounded-xl overflow-hidden"
size="middle"
className='rounded-xl overflow-hidden'
size='middle'
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
@@ -114,4 +105,4 @@ const MjLogsTable = (mjLogsData) => {
);
};
export default MjLogsTable;
export default MjLogsTable;

View File

@@ -41,7 +41,7 @@ const MjLogsPage = () => {
<Layout>
<CardPro
type="type2"
type='type2'
statsArea={<MjLogsActions {...mjLogsData} />}
searchArea={<MjLogsFilters {...mjLogsData} />}
paginationArea={createCardProPagination({
@@ -62,4 +62,4 @@ const MjLogsPage = () => {
);
};
export default MjLogsPage;
export default MjLogsPage;

View File

@@ -51,10 +51,8 @@ const ColumnSelectorModal = ({
visible={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
footer={
<div className="flex justify-end">
<Button onClick={() => initDefaultColumns()}>
{t('重置')}
</Button>
<div className='flex justify-end'>
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('取消')}
</Button>
@@ -77,7 +75,7 @@ const ColumnSelectorModal = ({
</Checkbox>
</div>
<div
className="flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4"
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) => {
@@ -91,7 +89,7 @@ const ColumnSelectorModal = ({
}
return (
<div key={column.key} className="w-1/2 mb-4 pr-2">
<div key={column.key} className='w-1/2 mb-4 pr-2'>
<Checkbox
checked={!!visibleColumns[column.key]}
onChange={(e) =>
@@ -108,4 +106,4 @@ const ColumnSelectorModal = ({
);
};
export default ColumnSelectorModal;
export default ColumnSelectorModal;

View File

@@ -52,4 +52,4 @@ const ContentModal = ({
);
};
export default ContentModal;
export default ContentModal;

View File

@@ -32,30 +32,30 @@ const PricingDisplaySettings = ({
tokenUnit,
setTokenUnit,
loading = false,
t
t,
}) => {
const items = [
{
value: 'recharge',
label: t('充值价格显示')
label: t('充值价格显示'),
},
{
value: 'ratio',
label: t('显示倍率')
label: t('显示倍率'),
},
{
value: 'tableView',
label: t('表格视图')
label: t('表格视图'),
},
{
value: 'tokenUnit',
label: t('按K显示单位')
}
label: t('按K显示单位'),
},
];
const currencyItems = [
{ value: 'USD', label: 'USD ($)' },
{ value: 'CNY', label: 'CNY (¥)' }
{ value: 'CNY', label: 'CNY (¥)' },
];
const handleChange = (value) => {
@@ -112,4 +112,4 @@ const PricingDisplaySettings = ({
);
};
export default PricingDisplaySettings;
export default PricingDisplaySettings;

View File

@@ -28,13 +28,23 @@ import SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingEndpointTypes = ({ filterEndpointType, setFilterEndpointType, models = [], allModels = [], loading = false, t }) => {
const PricingEndpointTypes = ({
filterEndpointType,
setFilterEndpointType,
models = [],
allModels = [],
loading = false,
t,
}) => {
// 获取系统中所有端点类型(基于 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 => {
(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);
});
}
@@ -47,9 +57,10 @@ const PricingEndpointTypes = ({ filterEndpointType, setFilterEndpointType, model
if (endpointType === 'all') {
return models.length;
}
return models.filter(model =>
model.supported_endpoint_types &&
model.supported_endpoint_types.includes(endpointType)
return models.filter(
(model) =>
model.supported_endpoint_types &&
model.supported_endpoint_types.includes(endpointType),
).length;
};
@@ -61,16 +72,21 @@ const PricingEndpointTypes = ({ filterEndpointType, setFilterEndpointType, model
const availableEndpointTypes = getAllEndpointTypes();
const items = [
{ value: 'all', label: t('全部端点'), tagCount: getEndpointTypeCount('all'), disabled: models.length === 0 },
...availableEndpointTypes.map(endpointType => {
{
value: 'all',
label: t('全部端点'),
tagCount: getEndpointTypeCount('all'),
disabled: models.length === 0,
},
...availableEndpointTypes.map((endpointType) => {
const count = getEndpointTypeCount(endpointType);
return ({
return {
value: endpointType,
label: getEndpointTypeLabel(endpointType),
tagCount: count,
disabled: count === 0
});
})
disabled: count === 0,
};
}),
];
return (
@@ -85,4 +101,4 @@ const PricingEndpointTypes = ({ filterEndpointType, setFilterEndpointType, model
);
};
export default PricingEndpointTypes;
export default PricingEndpointTypes;

View File

@@ -30,13 +30,26 @@ import SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingGroups = ({ filterGroup, setFilterGroup, usableGroup = {}, groupRatio = {}, models = [], loading = false, t }) => {
const groups = ['all', ...Object.keys(usableGroup).filter(key => key !== '')];
const PricingGroups = ({
filterGroup,
setFilterGroup,
usableGroup = {},
groupRatio = {},
models = [],
loading = false,
t,
}) => {
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;
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('全部');
@@ -52,7 +65,7 @@ const PricingGroups = ({ filterGroup, setFilterGroup, usableGroup = {}, groupRat
value: g,
label: g === 'all' ? t('全部分组') : g,
tagCount: ratioDisplay,
disabled: modelCount === 0
disabled: modelCount === 0,
};
});
@@ -68,4 +81,4 @@ const PricingGroups = ({ filterGroup, setFilterGroup, usableGroup = {}, groupRat
);
};
export default PricingGroups;
export default PricingGroups;

View File

@@ -28,8 +28,16 @@ import SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingQuotaTypes = ({ filterQuotaType, setFilterQuotaType, models = [], loading = false, t }) => {
const qtyCount = (type) => models.filter(m => type === 'all' ? true : m.quota_type === type).length;
const PricingQuotaTypes = ({
filterQuotaType,
setFilterQuotaType,
models = [],
loading = false,
t,
}) => {
const qtyCount = (type) =>
models.filter((m) => (type === 'all' ? true : m.quota_type === type))
.length;
const items = [
{ value: 'all', label: t('全部类型'), tagCount: qtyCount('all') },
@@ -49,4 +57,4 @@ const PricingQuotaTypes = ({ filterQuotaType, setFilterQuotaType, models = [], l
);
};
export default PricingQuotaTypes;
export default PricingQuotaTypes;

View File

@@ -29,18 +29,25 @@ import SelectableButtonGroup from '../../../common/ui/SelectableButtonGroup';
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingTags = ({ filterTag, setFilterTag, models = [], allModels = [], loading = false, t }) => {
const PricingTags = ({
filterTag,
setFilterTag,
models = [],
allModels = [],
loading = false,
t,
}) => {
// 提取系统所有标签
const getAllTags = React.useMemo(() => {
const tagSet = new Set();
(allModels.length > 0 ? allModels : models).forEach(model => {
(allModels.length > 0 ? allModels : models).forEach((model) => {
if (model.tags) {
model.tags
.split(/[,;|\s]+/) // 逗号、分号、竖线或空白字符
.map(tag => tag.trim())
.map((tag) => tag.trim())
.filter(Boolean)
.forEach(tag => tagSet.add(tag.toLowerCase()));
.forEach((tag) => tagSet.add(tag.toLowerCase()));
}
});
@@ -48,19 +55,22 @@ const PricingTags = ({ filterTag, setFilterTag, models = [], allModels = [], loa
}, [allModels, models]);
// 计算标签对应的模型数量
const getTagCount = React.useCallback((tag) => {
if (tag === 'all') return models.length;
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(/[,;|\s]+/)
.map(tg => tg.trim())
.includes(tagLower);
}).length;
}, [models]);
const tagLower = tag.toLowerCase();
return models.filter((model) => {
if (!model.tags) return false;
return model.tags
.toLowerCase()
.split(/[,;|\s]+/)
.map((tg) => tg.trim())
.includes(tagLower);
}).length;
},
[models],
);
const items = React.useMemo(() => {
const result = [
@@ -69,10 +79,10 @@ const PricingTags = ({ filterTag, setFilterTag, models = [], allModels = [], loa
label: t('全部标签'),
tagCount: getTagCount('all'),
disabled: models.length === 0,
}
},
];
getAllTags.forEach(tag => {
getAllTags.forEach((tag) => {
const count = getTagCount(tag);
result.push({
value: tag,

View File

@@ -30,14 +30,21 @@ import { getLobeHubIcon } from '../../../../helpers';
* @param {boolean} loading 是否加载中
* @param {Function} t i18n
*/
const PricingVendors = ({ filterVendor, setFilterVendor, models = [], allModels = [], loading = false, t }) => {
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 => {
(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)) {
@@ -51,20 +58,23 @@ const PricingVendors = ({ filterVendor, setFilterVendor, models = [], allModels
return {
vendors: Array.from(vendors).sort(),
vendorIcons,
hasUnknownVendor
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 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(() => {
@@ -73,12 +83,12 @@ const PricingVendors = ({ filterVendor, setFilterVendor, models = [], allModels
value: 'all',
label: t('全部供应商'),
tagCount: getVendorCount('all'),
disabled: models.length === 0
}
disabled: models.length === 0,
},
];
// 添加所有已知供应商
getAllVendors.vendors.forEach(vendor => {
getAllVendors.vendors.forEach((vendor) => {
const count = getVendorCount(vendor);
const icon = getAllVendors.vendorIcons.get(vendor);
result.push({
@@ -86,7 +96,7 @@ const PricingVendors = ({ filterVendor, setFilterVendor, models = [], allModels
label: vendor,
icon: icon ? getLobeHubIcon(icon, 16) : null,
tagCount: count,
disabled: count === 0
disabled: count === 0,
});
});
@@ -97,7 +107,7 @@ const PricingVendors = ({ filterVendor, setFilterVendor, models = [], allModels
value: 'unknown',
label: t('未知供应商'),
tagCount: count,
disabled: count === 0
disabled: count === 0,
});
}
@@ -116,4 +126,4 @@ const PricingVendors = ({ filterVendor, setFilterVendor, models = [], allModels
);
};
export default PricingVendors;
export default PricingVendors;

View File

@@ -36,23 +36,19 @@ const PricingPage = () => {
showRatio,
setShowRatio,
viewMode,
setViewMode
setViewMode,
};
return (
<div className="bg-white">
<Layout className="pricing-layout">
<div className='bg-white'>
<Layout className='pricing-layout'>
{!isMobile && (
<Sider
className="pricing-scroll-hide pricing-sidebar"
>
<Sider className='pricing-scroll-hide pricing-sidebar'>
<PricingSidebar {...allProps} />
</Sider>
)}
<Content
className="pricing-scroll-hide pricing-content"
>
<Content className='pricing-scroll-hide pricing-content'>
<PricingContent
{...allProps}
isMobile={isMobile}
@@ -86,4 +82,4 @@ const PricingPage = () => {
);
};
export default PricingPage;
export default PricingPage;

View File

@@ -58,7 +58,6 @@ const PricingSidebar = ({
t,
...categoryProps
}) => {
const {
quotaTypeModels,
endpointTypeModels,
@@ -92,16 +91,14 @@ const PricingSidebar = ({
});
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>
<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"
theme='outline'
type='tertiary'
onClick={handleResetFilters}
className="text-gray-500 hover:text-gray-700"
className='text-gray-500 hover:text-gray-700'
>
{t('重置')}
</Button>
@@ -155,4 +152,4 @@ const PricingSidebar = ({
);
};
export default PricingSidebar;
export default PricingSidebar;

View File

@@ -23,9 +23,11 @@ import PricingView from './PricingView';
const PricingContent = ({ isMobile, sidebarProps, ...props }) => {
return (
<div className={isMobile ? "pricing-content-mobile" : "pricing-scroll-hide"}>
<div
className={isMobile ? 'pricing-content-mobile' : 'pricing-scroll-hide'}
>
{/* 固定的顶部区域(分类介绍 + 搜索和操作) */}
<div className="pricing-search-header">
<div className='pricing-search-header'>
<PricingTopSection
{...props}
isMobile={isMobile}
@@ -44,11 +46,15 @@ const PricingContent = ({ isMobile, sidebarProps, ...props }) => {
</div>
{/* 可滚动的内容区域 */}
<div className={isMobile ? "pricing-view-container-mobile" : "pricing-view-container"}>
<div
className={
isMobile ? 'pricing-view-container-mobile' : 'pricing-view-container'
}
>
<PricingView {...props} viewMode={sidebarProps.viewMode} />
</div>
</div>
);
};
export default PricingContent;
export default PricingContent;

View File

@@ -21,13 +21,12 @@ 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} />;
const PricingView = ({ viewMode = 'table', ...props }) => {
return viewMode === 'card' ? (
<PricingCardView {...props} />
) : (
<PricingTable {...props} />
);
};
export default PricingView;
export default PricingView;

View File

@@ -22,98 +22,100 @@ 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,
showRatio,
setShowRatio,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
t
}) => {
const [showFilterModal, setShowFilterModal] = useState(false);
const PricingTopSection = memo(
({
selectedRowKeys,
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile,
sidebarProps,
filterVendor,
models,
filteredModels,
loading,
searchValue,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
showRatio,
setShowRatio,
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}
showRatio={showRatio}
setShowRatio={setShowRatio}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
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}
showRatio={showRatio}
setShowRatio={setShowRatio}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
t={t}
/>
</div>
<PricingFilterModal
visible={showFilterModal}
onClose={() => setShowFilterModal(false)}
sidebarProps={sidebarProps}
t={t}
/>
</div>
<PricingFilterModal
visible={showFilterModal}
onClose={() => setShowFilterModal(false)}
sidebarProps={sidebarProps}
</>
) : (
<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}
showRatio={showRatio}
setShowRatio={setShowRatio}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
/>
</>
) : (
<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}
showRatio={showRatio}
setShowRatio={setShowRatio}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
/>
)}
</>
);
});
)}
</>
);
},
);
PricingTopSection.displayName = 'PricingTopSection';
export default PricingTopSection;
export default PricingTopSection;

View File

@@ -18,7 +18,14 @@ 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 {
Card,
Tag,
Avatar,
Typography,
Tooltip,
Modal,
} from '@douyinfe/semi-ui';
import { getLobeHubIcon } from '../../../../../helpers';
import SearchActions from './SearchActions';
@@ -27,18 +34,18 @@ const { Paragraph } = Typography;
const CONFIG = {
CAROUSEL_INTERVAL: 2000,
ICON_SIZE: 40,
UNKNOWN_VENDOR: 'unknown'
UNKNOWN_VENDOR: 'unknown',
};
const THEME_COLORS = {
allVendors: {
primary: '37 99 235',
background: 'rgba(59, 130, 246, 0.08)'
background: 'rgba(59, 130, 246, 0.08)',
},
specific: {
primary: '16 185 129',
background: 'rgba(16, 185, 129, 0.1)'
}
background: 'rgba(16, 185, 129, 0.1)',
},
};
const COMPONENT_STYLES = {
@@ -46,41 +53,54 @@ const COMPONENT_STYLES = {
backgroundColor: 'rgba(255,255,255,0.95)',
color: '#1f2937',
border: '1px solid rgba(255,255,255,0.8)',
fontWeight: '500'
fontWeight: '500',
},
avatarContainer: 'w-16 h-16 rounded-2xl bg-white/90 shadow-md backdrop-blur-sm flex items-center justify-center',
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)' }
descriptionText: { color: 'rgba(255,255,255,0.9)' },
};
const CONTENT_TEXTS = {
unknown: {
displayName: (t) => t('未知供应商'),
description: (t) => t('包含来自未知或未标明供应商的AI模型这些模型可能来自小型供应商或开源项目。')
description: (t) =>
t(
'包含来自未知或未标明供应商的AI模型这些模型可能来自小型供应商或开源项目。',
),
},
all: {
description: (t) => t('查看所有可用的AI模型供应商包括众多知名供应商的模型。')
description: (t) =>
t('查看所有可用的AI模型供应商包括众多知名供应商的模型。'),
},
fallback: {
description: (t) => t('该供应商提供多种AI模型适用于不同的应用场景。')
}
description: (t) => t('该供应商提供多种AI模型适用于不同的应用场景。'),
},
};
const getVendorDisplayName = (vendorName, t) => {
return vendorName === CONFIG.UNKNOWN_VENDOR ? CONTENT_TEXTS.unknown.displayName(t) : vendorName;
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>
<Avatar size='large' color='transparent'>
AI
</Avatar>
</div>
);
const getAvatarBackgroundColor = (isAllVendors) =>
isAllVendors ? THEME_COLORS.allVendors.background : THEME_COLORS.specific.background;
isAllVendors
? THEME_COLORS.allVendors.background
: THEME_COLORS.specific.background;
const getAvatarText = (vendorName) =>
vendorName === CONFIG.UNKNOWN_VENDOR ? '?' : vendorName.charAt(0).toUpperCase();
vendorName === CONFIG.UNKNOWN_VENDOR
? '?'
: vendorName.charAt(0).toUpperCase();
const createAvatarContent = (vendor, isAllVendors) => {
if (vendor.icon) {
@@ -89,7 +109,7 @@ const createAvatarContent = (vendor, isAllVendors) => {
return (
<Avatar
size="large"
size='large'
style={{ backgroundColor: getAvatarBackgroundColor(isAllVendors) }}
>
{getAvatarText(vendor.name)}
@@ -106,245 +126,294 @@ const renderVendorAvatar = (vendor, t, isAllVendors = false) => {
const avatarContent = createAvatarContent(vendor, isAllVendors);
return (
<Tooltip content={displayName} position="top">
<div className={COMPONENT_STYLES.avatarContainer}>
{avatarContent}
</div>
<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,
showRatio,
setShowRatio,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit
}) => {
const [currentOffset, setCurrentOffset] = useState(0);
const [descModalVisible, setDescModalVisible] = useState(false);
const [descModalContent, setDescModalContent] = useState('');
const PricingVendorIntro = memo(
({
filterVendor,
models = [],
allModels = [],
t,
selectedRowKeys = [],
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile = false,
searchValue = '',
setShowFilterModal,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
showRatio,
setShowRatio,
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 handleOpenDescModal = useCallback((content) => {
setDescModalContent(content || '');
setDescModalVisible(true);
}, []);
const handleCloseDescModal = useCallback(() => {
setDescModalVisible(false);
}, []);
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}
showRatio={showRatio}
setShowRatio={setShowRatio}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
t={t}
/>
), [selectedRowKeys, copyText, handleChange, handleCompositionStart, handleCompositionEnd, isMobile, searchValue, setShowFilterModal, showWithRecharge, setShowWithRecharge, currency, setCurrency, showRatio, setShowRatio, 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)}
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="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='text-sm mb-4'>{descModalContent}</div>
</Modal>
),
[descModalVisible, descModalContent, handleCloseDescModal, isMobile, t],
);
<div className="flex-shrink-0">
{rightContent}
</div>
</div>
</div>
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,
});
}
>
{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]);
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}
showRatio={showRatio}
setShowRatio={setShowRatio}
viewMode={viewMode}
setViewMode={setViewMode}
tokenUnit={tokenUnit}
setTokenUnit={setTokenUnit}
t={t}
/>
),
[
selectedRowKeys,
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile,
searchValue,
setShowFilterModal,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
showRatio,
setShowRatio,
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);
if (filterVendor === 'all') {
const headerCard = renderHeaderCard({
title: t('全部供应商'),
title: vendorDisplayName,
count: currentModelCount,
description: getVendorDescription('all'),
rightContent: renderAllVendorsAvatar(),
primaryDarkerChannel: THEME_COLORS.allVendors.primary
description:
currentVendor.description || getVendorDescription(currentVendor.name),
rightContent: renderVendorAvatar(currentVendor, t, false),
primaryDarkerChannel: THEME_COLORS.specific.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;
export default PricingVendorIntro;

View File

@@ -24,17 +24,17 @@ const THEME_COLORS = {
allVendors: {
primary: '37 99 235',
background: 'rgba(59, 130, 246, 0.1)',
border: 'rgba(59, 130, 246, 0.2)'
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)'
border: 'rgba(16, 185, 129, 0.2)',
},
neutral: {
background: 'rgba(156, 163, 175, 0.1)',
border: 'rgba(156, 163, 175, 0.2)'
}
border: 'rgba(156, 163, 175, 0.2)',
},
};
const SIZES = {
@@ -43,7 +43,7 @@ const SIZES = {
description: { height: 14 },
avatar: { width: 40, height: 40 },
searchInput: { height: 32 },
button: { width: 80, height: 32 }
button: { width: 80, height: 32 },
};
const SKELETON_STYLES = {
@@ -52,129 +52,161 @@ const SKELETON_STYLES = {
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'
backgroundRepeat: 'no-repeat',
}),
title: {
backgroundColor: 'rgba(255, 255, 255, 0.25)',
borderRadius: 8,
backdropFilter: 'blur(4px)'
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)'
border: '1px solid rgba(255,255,255,0.3)',
},
description: {
backgroundColor: 'rgba(255, 255, 255, 0.2)',
borderRadius: 4,
backdropFilter: 'blur(4px)'
backdropFilter: 'blur(4px)',
},
avatar: (isAllVendors) => {
const colors = isAllVendors ? THEME_COLORS.allVendors : THEME_COLORS.specific;
const colors = isAllVendors
? THEME_COLORS.allVendors
: THEME_COLORS.specific;
return {
backgroundColor: colors.background,
borderRadius: 12,
border: `1px solid ${colors.border}`
border: `1px solid ${colors.border}`,
};
},
searchInput: {
backgroundColor: THEME_COLORS.neutral.background,
borderRadius: 8,
border: `1px solid ${THEME_COLORS.neutral.border}`
border: `1px solid ${THEME_COLORS.neutral.border}`,
},
button: {
backgroundColor: THEME_COLORS.neutral.background,
borderRadius: 8,
border: `1px solid ${THEME_COLORS.neutral.border}`
}
border: `1px solid ${THEME_COLORS.neutral.border}`,
},
};
const createSkeletonRect = (style = {}, key = null) => (
<div key={key} className="animate-pulse" style={style} />
<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')}
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="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 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>
}
>
<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>
</Card>
);
{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>
);
});
return (
<Skeleton loading={true} active placeholder={placeholder}></Skeleton>
);
},
);
PricingVendorIntroSkeleton.displayName = 'PricingVendorIntroSkeleton';
export default PricingVendorIntroSkeleton;
export default PricingVendorIntroSkeleton;

View File

@@ -22,30 +22,23 @@ 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);
const PricingVendorIntroWithSkeleton = memo(
({ loading = false, filterVendor, ...restProps }) => {
const showSkeleton = useMinimumLoadingTime(loading);
if (showSkeleton) {
return (
<PricingVendorIntroSkeleton
isAllVendors={filterVendor === 'all'}
isMobile={restProps.isMobile}
/>
);
}
if (showSkeleton) {
return (
<PricingVendorIntroSkeleton
isAllVendors={filterVendor === 'all'}
isMobile={restProps.isMobile}
/>
);
}
return (
<PricingVendorIntro
filterVendor={filterVendor}
{...restProps}
/>
);
});
return <PricingVendorIntro filterVendor={filterVendor} {...restProps} />;
},
);
PricingVendorIntroWithSkeleton.displayName = 'PricingVendorIntroWithSkeleton';
export default PricingVendorIntroWithSkeleton;
export default PricingVendorIntroWithSkeleton;

View File

@@ -21,138 +21,137 @@ 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,
showRatio,
setShowRatio,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
t
}) => {
const handleCopyClick = useCallback(() => {
if (copyText && selectedRowKeys.length > 0) {
copyText(selectedRowKeys);
}
}, [copyText, selectedRowKeys]);
const SearchActions = memo(
({
selectedRowKeys = [],
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
isMobile = false,
searchValue = '',
setShowFilterModal,
showWithRecharge,
setShowWithRecharge,
currency,
setCurrency,
showRatio,
setShowRatio,
viewMode,
setViewMode,
tokenUnit,
setTokenUnit,
t,
}) => {
const handleCopyClick = useCallback(() => {
if (copyText && selectedRowKeys.length > 0) {
copyText(selectedRowKeys);
}
}, [copyText, selectedRowKeys]);
const handleFilterClick = useCallback(() => {
setShowFilterModal?.(true);
}, [setShowFilterModal]);
const handleFilterClick = useCallback(() => {
setShowFilterModal?.(true);
}, [setShowFilterModal]);
const handleViewModeToggle = useCallback(() => {
setViewMode?.(viewMode === 'table' ? 'card' : 'table');
}, [viewMode, setViewMode]);
const handleViewModeToggle = useCallback(() => {
setViewMode?.(viewMode === 'table' ? 'card' : 'table');
}, [viewMode, setViewMode]);
const handleTokenUnitToggle = useCallback(() => {
setTokenUnit?.(tokenUnit === 'K' ? 'M' : 'K');
}, [tokenUnit, setTokenUnit]);
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>
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="primary"
icon={<IconCopy />}
onClick={handleCopyClick}
disabled={selectedRowKeys.length === 0}
className="!bg-blue-500 hover:!bg-blue-600 !text-white disabled:!bg-gray-300 disabled:!text-gray-500"
>
{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' }
]}
/>
)}
{/* 显示倍率开关 */}
<div className="flex items-center gap-2">
<span className="text-sm text-gray-600">{t('倍率')}</span>
<Switch
checked={showRatio}
onChange={setShowRatio}
/>
</div>
{/* 视图模式切换按钮 */}
<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}
theme='outline'
type='primary'
icon={<IconCopy />}
onClick={handleCopyClick}
disabled={selectedRowKeys.length === 0}
className='!bg-blue-500 hover:!bg-blue-600 !text-white disabled:!bg-gray-300 disabled:!text-gray-500'
>
{t('筛选')}
{t('复制')}
</Button>
)}
</div>
);
});
{!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' },
]}
/>
)}
{/* 显示倍率开关 */}
<div className='flex items-center gap-2'>
<span className='text-sm text-gray-600'>{t('倍率')}</span>
<Switch checked={showRatio} onChange={setShowRatio} />
</div>
{/* 视图模式切换按钮 */}
<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;
export default SearchActions;

View File

@@ -18,14 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import {
SideSheet,
Typography,
Button,
} from '@douyinfe/semi-ui';
import {
IconClose,
} from '@douyinfe/semi-icons';
import { SideSheet, Typography, Button } from '@douyinfe/semi-ui';
import { IconClose } from '@douyinfe/semi-icons';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import ModelHeader from './components/ModelHeader';
@@ -54,36 +48,46 @@ const ModelDetailSideSheet = ({
return (
<SideSheet
placement="right"
title={<ModelHeader modelData={modelData} vendorsMap={vendorsMap} t={t} />}
placement='right'
title={
<ModelHeader modelData={modelData} vendorsMap={vendorsMap} t={t} />
}
bodyStyle={{
padding: '0',
display: 'flex',
flexDirection: 'column',
borderBottom: '1px solid var(--semi-color-border)'
borderBottom: '1px solid var(--semi-color-border)',
}}
visible={visible}
width={isMobile ? '100%' : 600}
closeIcon={
<Button
className="semi-button-tertiary semi-button-size-small semi-button-borderless"
type="button"
className='semi-button-tertiary semi-button-size-small semi-button-borderless'
type='button'
icon={<IconClose />}
onClick={onClose}
/>
}
onCancel={onClose}
>
<div className="p-2">
<div className='p-2'>
{!modelData && (
<div className="flex justify-center items-center py-10">
<Text type="secondary">{t('加载中...')}</Text>
<div className='flex justify-center items-center py-10'>
<Text type='secondary'>{t('加载中...')}</Text>
</div>
)}
{modelData && (
<>
<ModelBasicInfo modelData={modelData} vendorsMap={vendorsMap} t={t} />
<ModelEndpoints modelData={modelData} endpointMap={endpointMap} t={t} />
<ModelBasicInfo
modelData={modelData}
vendorsMap={vendorsMap}
t={t}
/>
<ModelEndpoints
modelData={modelData}
endpointMap={endpointMap}
t={t}
/>
<ModelPricingTable
modelData={modelData}
groupRatio={groupRatio}
@@ -102,4 +106,4 @@ const ModelDetailSideSheet = ({
);
};
export default ModelDetailSideSheet;
export default ModelDetailSideSheet;

View File

@@ -23,12 +23,7 @@ import { resetPricingFilters } from '../../../../helpers/utils';
import FilterModalContent from './components/FilterModalContent';
import FilterModalFooter from './components/FilterModalFooter';
const PricingFilterModal = ({
visible,
onClose,
sidebarProps,
t
}) => {
const PricingFilterModal = ({ visible, onClose, sidebarProps, t }) => {
const handleResetFilters = () =>
resetPricingFilters({
handleChange: sidebarProps.handleChange,
@@ -46,11 +41,7 @@ const PricingFilterModal = ({
});
const footer = (
<FilterModalFooter
onReset={handleResetFilters}
onConfirm={onClose}
t={t}
/>
<FilterModalFooter onReset={handleResetFilters} onConfirm={onClose} t={t} />
);
return (
@@ -65,7 +56,7 @@ const PricingFilterModal = ({
height: 'calc(100vh - 160px)',
overflowY: 'auto',
scrollbarWidth: 'none',
msOverflowStyle: 'none'
msOverflowStyle: 'none',
}}
>
<FilterModalContent sidebarProps={sidebarProps} t={t} />
@@ -73,4 +64,4 @@ const PricingFilterModal = ({
);
};
export default PricingFilterModal;
export default PricingFilterModal;

View File

@@ -135,4 +135,4 @@ const FilterModalContent = ({ sidebarProps, t }) => {
);
};
export default FilterModalContent;
export default FilterModalContent;

View File

@@ -22,23 +22,15 @@ import { Button } from '@douyinfe/semi-ui';
const FilterModalFooter = ({ onReset, onConfirm, t }) => {
return (
<div className="flex justify-end">
<Button
theme="outline"
type='tertiary'
onClick={onReset}
>
<div className='flex justify-end'>
<Button theme='outline' type='tertiary' onClick={onReset}>
{t('重置')}
</Button>
<Button
theme="solid"
type="primary"
onClick={onConfirm}
>
<Button theme='solid' type='primary' onClick={onConfirm}>
{t('确定')}
</Button>
</div>
);
};
export default FilterModalFooter;
export default FilterModalFooter;

View File

@@ -47,8 +47,8 @@ const ModelBasicInfo = ({ modelData, vendorsMap = {}, t }) => {
const tags = [];
if (modelData?.tags) {
const customTags = modelData.tags.split(',').filter(tag => tag.trim());
customTags.forEach(tag => {
const customTags = modelData.tags.split(',').filter((tag) => tag.trim());
customTags.forEach((tag) => {
const tagText = tag.trim();
tags.push({ text: tagText, color: stringToColor(tagText) });
});
@@ -58,27 +58,24 @@ const ModelBasicInfo = ({ modelData, vendorsMap = {}, t }) => {
};
return (
<Card className="!rounded-2xl shadow-sm border-0 mb-6">
<div className="flex items-center mb-4">
<Avatar size="small" color="blue" className="mr-2 shadow-md">
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
<div className='flex items-center mb-4'>
<Avatar size='small' color='blue' className='mr-2 shadow-md'>
<IconInfoCircle size={16} />
</Avatar>
<div>
<Text className="text-lg font-medium">{t('基本信息')}</Text>
<div className="text-xs text-gray-600">{t('模型的详细描述和基本特性')}</div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>
{t('模型的详细描述和基本特性')}
</div>
</div>
</div>
<div className="text-gray-600">
<p className="mb-4">{getModelDescription()}</p>
<div className='text-gray-600'>
<p className='mb-4'>{getModelDescription()}</p>
{getModelTags().length > 0 && (
<Space wrap>
{getModelTags().map((tag, index) => (
<Tag
key={index}
color={tag.color}
shape="circle"
size="small"
>
<Tag key={index} color={tag.color} shape='circle' size='small'>
{tag.text}
</Tag>
))}
@@ -89,4 +86,4 @@ const ModelBasicInfo = ({ modelData, vendorsMap = {}, t }) => {
);
};
export default ModelBasicInfo;
export default ModelBasicInfo;

View File

@@ -30,7 +30,7 @@ const ModelEndpoints = ({ modelData, endpointMap = {}, t }) => {
const mapping = endpointMap;
const types = modelData.supported_endpoint_types || [];
return types.map(type => {
return types.map((type) => {
const info = mapping[type] || {};
let path = info.path || '';
// 如果路径中包含 {model} 占位符,替换为真实模型名称
@@ -42,22 +42,19 @@ const ModelEndpoints = ({ modelData, endpointMap = {}, t }) => {
return (
<div
key={type}
className="flex justify-between border-b border-dashed last:border-0 py-2 last:pb-0"
className='flex justify-between border-b border-dashed last:border-0 py-2 last:pb-0'
style={{ borderColor: 'var(--semi-color-border)' }}
>
<span className="flex items-center pr-5">
<Badge dot type="success" className="mr-2" />
{type}{path && ''}
<span className='flex items-center pr-5'>
<Badge dot type='success' className='mr-2' />
{type}
{path && ''}
{path && (
<span className="text-gray-500 md:ml-1 break-all">
{path}
</span>
<span className='text-gray-500 md:ml-1 break-all'>{path}</span>
)}
</span>
{path && (
<span className="text-gray-500 text-xs md:ml-1">
{method}
</span>
<span className='text-gray-500 text-xs md:ml-1'>{method}</span>
)}
</div>
);
@@ -65,14 +62,16 @@ const ModelEndpoints = ({ modelData, endpointMap = {}, t }) => {
};
return (
<Card className="!rounded-2xl shadow-sm border-0 mb-6">
<div className="flex items-center mb-4">
<Avatar size="small" color="purple" className="mr-2 shadow-md">
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
<div className='flex items-center mb-4'>
<Avatar size='small' color='purple' className='mr-2 shadow-md'>
<IconLink size={16} />
</Avatar>
<div>
<Text className="text-lg font-medium">{t('API端点')}</Text>
<div className="text-xs text-gray-600">{t('模型支持的接口端点信息')}</div>
<Text className='text-lg font-medium'>{t('API端点')}</Text>
<div className='text-xs text-gray-600'>
{t('模型支持的接口端点信息')}
</div>
</div>
</div>
{renderAPIEndpoints()}
@@ -80,4 +79,4 @@ const ModelEndpoints = ({ modelData, endpointMap = {}, t }) => {
);
};
export default ModelEndpoints;
export default ModelEndpoints;

View File

@@ -24,8 +24,9 @@ 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",
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 }) => {
@@ -57,13 +58,13 @@ const ModelHeader = ({ modelData, vendorsMap = {}, t }) => {
return (
<div className={CARD_STYLES.container}>
<Avatar
size="large"
size='large'
style={{
width: 48,
height: 48,
borderRadius: 16,
fontSize: 16,
fontWeight: 'bold'
fontWeight: 'bold',
}}
>
{avatarText}
@@ -73,21 +74,23 @@ const ModelHeader = ({ modelData, vendorsMap = {}, t }) => {
};
return (
<div className="flex items-center">
<div className='flex items-center'>
{getModelIcon()}
<div className="ml-3 font-normal">
<div className='ml-3 font-normal'>
<Paragraph
className="!mb-0 !text-lg !font-medium"
className='!mb-0 !text-lg !font-medium'
copyable={{
content: modelData?.model_name || '',
onCopy: () => Toast.success({ content: t('已复制模型名称') })
onCopy: () => Toast.success({ content: t('已复制模型名称') }),
}}
>
<span className="truncate max-w-60 font-bold">{modelData?.model_name || t('未知模型')}</span>
<span className='truncate max-w-60 font-bold'>
{modelData?.model_name || t('未知模型')}
</span>
</Paragraph>
</div>
</div>
);
};
export default ModelHeader;
export default ModelHeader;

View File

@@ -35,37 +35,50 @@ const ModelPricingTable = ({
autoGroups = [],
t,
}) => {
const modelEnableGroups = Array.isArray(modelData?.enable_groups) ? modelData.enable_groups : [];
const autoChain = autoGroups.filter(g => modelEnableGroups.includes(g));
const modelEnableGroups = Array.isArray(modelData?.enable_groups)
? modelData.enable_groups
: [];
const autoChain = autoGroups.filter((g) => modelEnableGroups.includes(g));
const renderGroupPriceTable = () => {
// 仅展示模型可用的分组:模型 enable_groups 与用户可用分组的交集
const availableGroups = Object.keys(usableGroup || {})
.filter(g => g !== '')
.filter(g => g !== 'auto')
.filter(g => modelEnableGroups.includes(g));
.filter((g) => g !== '')
.filter((g) => g !== 'auto')
.filter((g) => modelEnableGroups.includes(g));
// 准备表格数据
const tableData = availableGroups.map(group => {
const priceData = modelData ? calculateModelPrice({
record: modelData,
selectedGroup: group,
groupRatio,
tokenUnit,
displayPrice,
currency
}) : { inputPrice: '-', outputPrice: '-', price: '-' };
const tableData = availableGroups.map((group) => {
const priceData = modelData
? calculateModelPrice({
record: modelData,
selectedGroup: group,
groupRatio,
tokenUnit,
displayPrice,
currency,
})
: { inputPrice: '-', outputPrice: '-', price: '-' };
// 获取分组倍率
const groupRatioValue = groupRatio && groupRatio[group] ? groupRatio[group] : 1;
const groupRatioValue =
groupRatio && groupRatio[group] ? groupRatio[group] : 1;
return {
key: group,
group: group,
ratio: groupRatioValue,
billingType: modelData?.quota_type === 0 ? t('按量计费') : (modelData?.quota_type === 1 ? t('按次计费') : '-'),
billingType:
modelData?.quota_type === 0
? t('按量计费')
: modelData?.quota_type === 1
? t('按次计费')
: '-',
inputPrice: modelData?.quota_type === 0 ? priceData.inputPrice : '-',
outputPrice: modelData?.quota_type === 0 ? (priceData.completionPrice || priceData.outputPrice) : '-',
outputPrice:
modelData?.quota_type === 0
? priceData.completionPrice || priceData.outputPrice
: '-',
fixedPrice: modelData?.quota_type === 1 ? priceData.price : '-',
};
});
@@ -76,8 +89,9 @@ const ModelPricingTable = ({
title: t('分组'),
dataIndex: 'group',
render: (text) => (
<Tag color="white" size="small" shape="circle">
{text}{t('分组')}
<Tag color='white' size='small' shape='circle'>
{text}
{t('分组')}
</Tag>
),
},
@@ -89,7 +103,7 @@ const ModelPricingTable = ({
title: t('倍率'),
dataIndex: 'ratio',
render: (text) => (
<Tag color="white" size="small" shape="circle">
<Tag color='white' size='small' shape='circle'>
{text}x
</Tag>
),
@@ -105,7 +119,7 @@ const ModelPricingTable = ({
if (text === t('按量计费')) color = 'violet';
else if (text === t('按次计费')) color = 'teal';
return (
<Tag color={color} size="small" shape="circle">
<Tag color={color} size='small' shape='circle'>
{text || '-'}
</Tag>
);
@@ -121,8 +135,10 @@ const ModelPricingTable = ({
dataIndex: 'inputPrice',
render: (text) => (
<>
<div className="font-semibold text-orange-600">{text}</div>
<div className="text-xs text-gray-500">/ {tokenUnit === 'K' ? '1K' : '1M'} tokens</div>
<div className='font-semibold text-orange-600'>{text}</div>
<div className='text-xs text-gray-500'>
/ {tokenUnit === 'K' ? '1K' : '1M'} tokens
</div>
</>
),
},
@@ -131,11 +147,13 @@ const ModelPricingTable = ({
dataIndex: 'outputPrice',
render: (text) => (
<>
<div className="font-semibold text-orange-600">{text}</div>
<div className="text-xs text-gray-500">/ {tokenUnit === 'K' ? '1K' : '1M'} tokens</div>
<div className='font-semibold text-orange-600'>{text}</div>
<div className='text-xs text-gray-500'>
/ {tokenUnit === 'K' ? '1K' : '1M'} tokens
</div>
</>
),
}
},
);
} else {
// 按次计费
@@ -144,8 +162,8 @@ const ModelPricingTable = ({
dataIndex: 'fixedPrice',
render: (text) => (
<>
<div className="font-semibold text-orange-600">{text}</div>
<div className="text-xs text-gray-500">/ </div>
<div className='font-semibold text-orange-600'>{text}</div>
<div className='text-xs text-gray-500'>/ </div>
</>
),
});
@@ -156,32 +174,37 @@ const ModelPricingTable = ({
dataSource={tableData}
columns={columns}
pagination={false}
size="small"
size='small'
bordered={false}
className="!rounded-lg"
className='!rounded-lg'
/>
);
};
return (
<Card className="!rounded-2xl shadow-sm border-0">
<div className="flex items-center mb-4">
<Avatar size="small" color="orange" className="mr-2 shadow-md">
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-4'>
<Avatar size='small' color='orange' className='mr-2 shadow-md'>
<IconCoinMoneyStroked size={16} />
</Avatar>
<div>
<Text className="text-lg font-medium">{t('分组价格')}</Text>
<div className="text-xs text-gray-600">{t('不同用户分组的价格信息')}</div>
<Text className='text-lg font-medium'>{t('分组价格')}</Text>
<div className='text-xs text-gray-600'>
{t('不同用户分组的价格信息')}
</div>
</div>
</div>
{autoChain.length > 0 && (
<div className="flex flex-wrap items-center gap-1 mb-4">
<span className="text-sm text-gray-600">{t('auto分组调用链路')}</span>
<span className="text-sm"></span>
<div className='flex flex-wrap items-center gap-1 mb-4'>
<span className='text-sm text-gray-600'>{t('auto分组调用链路')}</span>
<span className='text-sm'></span>
{autoChain.map((g, idx) => (
<React.Fragment key={g}>
<Tag color="white" size="small" shape="circle">{g}{t('分组')}</Tag>
{idx < autoChain.length - 1 && <span className="text-sm"></span>}
<Tag color='white' size='small' shape='circle'>
{g}
{t('分组')}
</Tag>
{idx < autoChain.length - 1 && <span className='text-sm'></span>}
</React.Fragment>
))}
</div>
@@ -191,4 +214,4 @@ const ModelPricingTable = ({
);
};
export default ModelPricingTable;
export default ModelPricingTable;

View File

@@ -23,35 +23,35 @@ import { Card, Skeleton } from '@douyinfe/semi-ui';
const PricingCardSkeleton = ({
skeletonCount = 100,
rowSelection = false,
showRatio = 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">
<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"
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='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">
<div className='w-12 h-12 rounded-2xl flex items-center justify-center relative shadow-sm'>
<Skeleton.Avatar
size="large"
size='large'
style={{ width: 48, height: 48, borderRadius: 16 }}
/>
</div>
{/* 模型名称和价格区域 */}
<div className="flex-1 min-w-0">
<div className='flex-1 min-w-0'>
{/* 模型名称骨架 */}
<Skeleton.Title
style={{
width: `${120 + (index % 3) * 30}px`,
height: 20,
marginBottom: 8
marginBottom: 8,
}}
/>
{/* 价格信息骨架 */}
@@ -59,24 +59,30 @@ const PricingCardSkeleton = ({
style={{
width: `${160 + (index % 4) * 20}px`,
height: 20,
marginBottom: 0
marginBottom: 0,
}}
/>
</div>
</div>
<div className="flex items-center space-x-2 ml-3">
<div className='flex items-center space-x-2 ml-3'>
{/* 复制按钮骨架 */}
<Skeleton.Button size="small" style={{ width: 16, height: 16, borderRadius: 4 }} />
<Skeleton.Button
size='small'
style={{ width: 16, height: 16, borderRadius: 4 }}
/>
{/* 勾选框骨架 */}
{rowSelection && (
<Skeleton.Button size="small" style={{ width: 16, height: 16, borderRadius: 2 }} />
<Skeleton.Button
size='small'
style={{ width: 16, height: 16, borderRadius: 2 }}
/>
)}
</div>
</div>
{/* 模型描述骨架 */}
<div className="mb-4">
<div className='mb-4'>
<Skeleton.Paragraph
rows={2}
style={{ marginBottom: 0 }}
@@ -85,15 +91,15 @@ const PricingCardSkeleton = ({
</div>
{/* 标签区域骨架 */}
<div className="flex flex-wrap gap-2">
<div className='flex flex-wrap gap-2'>
{Array.from({ length: 2 + (index % 3) }).map((_, tagIndex) => (
<Skeleton.Button
key={tagIndex}
size="small"
size='small'
style={{
width: 64,
height: 18,
borderRadius: 10
borderRadius: 10,
}}
/>
))}
@@ -101,14 +107,17 @@ const PricingCardSkeleton = ({
{/* 倍率信息骨架(可选) */}
{showRatio && (
<div className="mt-4 pt-3 border-t border-gray-100">
<div className="flex items-center space-x-1 mb-2">
<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 }} />
<Skeleton.Button
size='small'
style={{ width: 14, height: 14, borderRadius: 7 }}
/>
</div>
<div className="grid grid-cols-3 gap-2">
<div className='grid grid-cols-3 gap-2'>
{Array.from({ length: 3 }).map((_, ratioIndex) => (
<Skeleton.Title
key={ratioIndex}
@@ -123,15 +132,13 @@ const PricingCardSkeleton = ({
</div>
{/* 分页骨架 */}
<div className="flex justify-center mt-6 py-4 border-t pricing-pagination-divider">
<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>
);
return <Skeleton loading={true} active placeholder={placeholder}></Skeleton>;
};
export default PricingCardSkeleton;
export default PricingCardSkeleton;

View File

@@ -18,21 +18,39 @@ 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 {
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 '@douyinfe/semi-illustrations';
import { stringToColor, calculateModelPrice, formatPriceInfo, getLobeHubIcon } from '../../../../../helpers';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-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"
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 = ({
@@ -59,7 +77,10 @@ const PricingCardView = ({
}) => {
const showSkeleton = useMinimumLoadingTime(loading);
const startIndex = (currentPage - 1) * pageSize;
const paginatedModels = filteredModels.slice(startIndex, startIndex + pageSize);
const paginatedModels = filteredModels.slice(
startIndex,
startIndex + pageSize,
);
const getModelKey = (model) => model.key ?? model.model_name ?? model.id;
const isMobile = useIsMobile();
@@ -109,13 +130,13 @@ const PricingCardView = ({
return (
<div className={CARD_STYLES.container}>
<Avatar
size="large"
size='large'
style={{
width: 48,
height: 48,
borderRadius: 16,
fontSize: 16,
fontWeight: 'bold'
fontWeight: 'bold',
}}
>
{avatarText}
@@ -133,19 +154,19 @@ const PricingCardView = ({
const renderTags = (record) => {
// 计费类型标签(左边)
let billingTag = (
<Tag key="billing" shape='circle' color='white' size='small'>
<Tag key='billing' shape='circle' color='white' size='small'>
-
</Tag>
);
if (record.quota_type === 1) {
billingTag = (
<Tag key="billing" shape='circle' color='teal' size='small'>
<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'>
<Tag key='billing' shape='circle' color='violet' size='small'>
{t('按量计费')}
</Tag>
);
@@ -157,24 +178,31 @@ const PricingCardView = ({
const tagArr = record.tags.split(',').filter(Boolean);
tagArr.forEach((tg, idx) => {
customTags.push(
<Tag key={`custom-${idx}`} shape='circle' color={stringToColor(tg)} size='small'>
<Tag
key={`custom-${idx}`}
shape='circle'
color={stringToColor(tg)}
size='small'
>
{tg}
</Tag>
</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 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>
);
@@ -192,10 +220,12 @@ const PricingCardView = ({
if (!filteredModels || filteredModels.length === 0) {
return (
<div className="flex justify-center items-center py-20">
<div className='flex justify-center items-center py-20'>
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
/>
</div>
@@ -203,8 +233,8 @@ const PricingCardView = ({
}
return (
<div className="px-2 pt-2">
<div className="grid grid-cols-1 xl:grid-cols-2 2xl:grid-cols-3 gap-4">
<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);
@@ -225,27 +255,27 @@ const PricingCardView = ({
bodyStyle={{ height: '100%' }}
onClick={() => openModelDetail && openModelDetail(model)}
>
<div className="flex flex-col h-full">
<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">
<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">
<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">
<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">
<div className='flex items-center space-x-2 ml-3'>
{/* 复制按钮 */}
<Button
size="small"
theme="outline"
type="tertiary"
size='small'
theme='outline'
type='tertiary'
icon={<Copy size={12} />}
onClick={(e) => {
e.stopPropagation();
@@ -267,9 +297,9 @@ const PricingCardView = ({
</div>
{/* 模型描述 - 占据剩余空间 */}
<div className="flex-1 mb-4">
<div className='flex-1 mb-4'>
<p
className="text-xs line-clamp-2 leading-relaxed"
className='text-xs line-clamp-2 leading-relaxed'
style={{ color: 'var(--semi-color-text-2)' }}
>
{getModelDescription(model)}
@@ -277,19 +307,23 @@ const PricingCardView = ({
</div>
{/* 底部区域 */}
<div className="mt-auto">
<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('倍率是为了方便换算不同价格的模型')}>
<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"
className='text-blue-500 cursor-pointer'
size='small'
onClick={(e) => {
e.stopPropagation();
setModalImageUrl('/ratio.png');
@@ -298,12 +332,16 @@ const PricingCardView = ({
/>
</Tooltip>
</div>
<div className="grid grid-cols-3 gap-2 text-xs text-gray-600">
<div className='grid grid-cols-3 gap-2 text-xs text-gray-600'>
<div>
{t('模型')}: {model.quota_type === 0 ? model.model_ratio : t('无')}
{t('模型')}:{' '}
{model.quota_type === 0 ? model.model_ratio : t('无')}
</div>
<div>
{t('补全')}: {model.quota_type === 0 ? parseFloat(model.completion_ratio.toFixed(3)) : t('无')}
{t('补全')}:{' '}
{model.quota_type === 0
? parseFloat(model.completion_ratio.toFixed(3))
: t('无')}
</div>
<div>
{t('分组')}: {priceData?.usedGroupRatio ?? '-'}
@@ -320,7 +358,7 @@ const PricingCardView = ({
{/* 分页 */}
{filteredModels.length > 0 && (
<div className="flex justify-center mt-6 py-4 border-t pricing-pagination-divider">
<div className='flex justify-center mt-6 py-4 border-t pricing-pagination-divider'>
<Pagination
currentPage={currentPage}
pageSize={pageSize}
@@ -341,4 +379,4 @@ const PricingCardView = ({
);
};
export default PricingCardView;
export default PricingCardView;

View File

@@ -21,7 +21,7 @@ import React, { useMemo } from 'react';
import { Card, Table, Empty } from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { getPricingTableColumns } from './PricingTableColumns';
@@ -43,9 +43,8 @@ const PricingTable = ({
showRatio,
compactMode = false,
openModelDetail,
t
t,
}) => {
const columns = useMemo(() => {
return getPricingTableColumns({
t,
@@ -74,11 +73,11 @@ const PricingTable = ({
// 更新列定义中的 searchValue
const processedColumns = useMemo(() => {
const cols = columns.map(column => {
const cols = columns.map((column) => {
if (column.dataIndex === 'model_name') {
return {
...column,
filteredValue: searchValue ? [searchValue] : []
filteredValue: searchValue ? [searchValue] : [],
};
}
return column;
@@ -91,38 +90,55 @@ const PricingTable = ({
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]);
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;
export default PricingTable;

View File

@@ -20,8 +20,16 @@ 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';
import {
renderModelTag,
stringToColor,
calculateModelPrice,
getLobeHubIcon,
} from '../../../../../helpers';
import {
renderLimitedItems,
renderDescription,
} from '../../../../common/ui/RenderUtils';
import { useIsMobile } from '../../../../../hooks/common/useIsMobile';
function renderQuotaType(type, t) {
@@ -47,7 +55,11 @@ function renderQuotaType(type, t) {
const renderVendor = (vendorName, vendorIcon, t) => {
if (!vendorName) return '-';
return (
<Tag color='white' shape='circle' prefixIcon={getLobeHubIcon(vendorIcon || 'Layers', 14)}>
<Tag
color='white'
shape='circle'
prefixIcon={getLobeHubIcon(vendorIcon || 'Layers', 14)}
>
{vendorName}
</Tag>
);
@@ -56,15 +68,20 @@ const renderVendor = (vendorName, vendorIcon, t) => {
// Render tags list using RenderUtils
const renderTags = (text) => {
if (!text) return '-';
const tagsArr = text.split(',').filter(tag => tag.trim());
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
key={idx}
color={stringToColor(tag.trim())}
shape='circle'
size='small'
>
{tag.trim()}
</Tag>
),
maxDisplay: 3
maxDisplay: 3,
});
};
@@ -75,11 +92,7 @@ function renderSupportedEndpoints(endpoints) {
return (
<Space wrap>
{endpoints.map((endpoint, idx) => (
<Tag
key={endpoint}
color={stringToColor(endpoint)}
shape='circle'
>
<Tag key={endpoint} color={stringToColor(endpoint)} shape='circle'>
{endpoint}
</Tag>
))}
@@ -133,7 +146,7 @@ export const getPricingTableColumns = ({
return renderModelTag(text, {
onClick: () => {
copyText(text);
}
},
});
},
onFilter: (value, record) =>
@@ -167,15 +180,21 @@ export const getPricingTableColumns = ({
render: (text, record) => renderVendor(text, record.vendor_icon, t),
};
const baseColumns = [modelNameColumn, vendorColumn, descriptionColumn, tagsColumn, quotaColumn];
const baseColumns = [
modelNameColumn,
vendorColumn,
descriptionColumn,
tagsColumn,
quotaColumn,
];
const ratioColumn = {
title: () => (
<div className="flex items-center space-x-1">
<div className='flex items-center space-x-1'>
<span>{t('倍率')}</span>
<Tooltip content={t('倍率是为了方便换算不同价格的模型')}>
<IconHelpCircle
className="text-blue-500 cursor-pointer"
className='text-blue-500 cursor-pointer'
onClick={() => {
setModalImageUrl('/ratio.png');
setIsModalOpenurl(true);
@@ -190,14 +209,15 @@ export const getPricingTableColumns = ({
const priceData = getPriceData(record);
return (
<div className="space-y-1">
<div className="text-gray-700">
<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 className='text-gray-700'>
{t('补全倍率')}
{record.quota_type === 0 ? completionRatio : t('无')}
</div>
<div className="text-gray-700">
<div className='text-gray-700'>
{t('分组倍率')}{priceData?.usedGroupRatio ?? '-'}
</div>
</div>
@@ -214,18 +234,19 @@ export const getPricingTableColumns = ({
if (priceData.isPerToken) {
return (
<div className="space-y-1">
<div className="text-gray-700">
<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 className='text-gray-700'>
{t('输出')} {priceData.completionPrice} / 1{priceData.unitLabel}{' '}
tokens
</div>
</div>
);
} else {
return (
<div className="text-gray-700">
<div className='text-gray-700'>
{t('模型价格')}{priceData.price}
</div>
);
@@ -240,4 +261,4 @@ export const getPricingTableColumns = ({
}
columns.push(priceColumn);
return columns;
};
};

View File

@@ -61,7 +61,7 @@ const ModelsActions = ({
// Handle add selected models to prefill group
const handleCopyNames = async () => {
const text = selectedKeys.map(m => m.model_name).join(',');
const text = selectedKeys.map((m) => m.model_name).join(',');
if (!text) return;
const ok = await copy(text);
if (ok) {
@@ -80,34 +80,34 @@ const ModelsActions = ({
return (
<>
<div className="flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1">
<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"
type='primary'
className='flex-1 md:flex-initial'
onClick={() => {
setEditingModel({
id: undefined,
});
setShowEdit(true);
}}
size="small"
size='small'
>
{t('添加模型')}
</Button>
<Button
type="secondary"
className="flex-1 md:flex-initial"
size="small"
type='secondary'
className='flex-1 md:flex-initial'
size='small'
onClick={() => setShowMissingModal(true)}
>
{t('未配置模型')}
</Button>
<Button
type="secondary"
className="flex-1 md:flex-initial"
size="small"
type='secondary'
className='flex-1 md:flex-initial'
size='small'
onClick={() => setShowGroupManagement(true)}
>
{t('预填组管理')}
@@ -134,10 +134,12 @@ const ModelsActions = ({
visible={showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
onOk={handleConfirmDelete}
type="warning"
type='warning'
>
<div>
{t('确定要删除所选的 {{count}} 个模型吗?', { count: selectedKeys.length })}
{t('确定要删除所选的 {{count}} 个模型吗?', {
count: selectedKeys.length,
})}
</div>
</Modal>
@@ -167,4 +169,4 @@ const ModelsActions = ({
);
};
export default ModelsActions;
export default ModelsActions;

View File

@@ -18,13 +18,23 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Button, Space, Tag, Typography, Modal, Tooltip } from '@douyinfe/semi-ui';
import {
Button,
Space,
Tag,
Typography,
Modal,
Tooltip,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
getLobeHubIcon,
stringToColor
stringToColor,
} from '../../../helpers';
import { renderLimitedItems, renderDescription } from '../../common/ui/RenderUtils';
import {
renderLimitedItems,
renderDescription,
} from '../../common/ui/RenderUtils';
const { Text } = Typography;
@@ -38,7 +48,7 @@ const renderModelIconCol = (record, vendorMap) => {
const iconKey = record?.icon || vendorMap[record?.vendor_id]?.icon;
if (!iconKey) return '-';
return (
<div className="flex items-center justify-center">
<div className='flex items-center justify-center'>
{getLobeHubIcon(iconKey, 20)}
</div>
);
@@ -65,7 +75,7 @@ const renderGroups = (groups) => {
return renderLimitedItems({
items: groups,
renderItem: (g, idx) => (
<Tag key={idx} size="small" shape='circle' color={stringToColor(g)}>
<Tag key={idx} size='small' shape='circle' color={stringToColor(g)}>
{g}
</Tag>
),
@@ -79,7 +89,7 @@ const renderTags = (text) => {
return renderLimitedItems({
items: tagsArr,
renderItem: (tag, idx) => (
<Tag key={idx} size="small" shape='circle' color={stringToColor(tag)}>
<Tag key={idx} size='small' shape='circle' color={stringToColor(tag)}>
{tag}
</Tag>
),
@@ -96,7 +106,7 @@ const renderEndpoints = (value) => {
return renderLimitedItems({
items: keys,
renderItem: (key, idx) => (
<Tag key={idx} size="small" shape='circle' color={stringToColor(key)}>
<Tag key={idx} size='small' shape='circle' color={stringToColor(key)}>
{key}
</Tag>
),
@@ -108,7 +118,7 @@ const renderEndpoints = (value) => {
return renderLimitedItems({
items: parsed,
renderItem: (ep, idx) => (
<Tag key={idx} color="white" size="small" shape='circle'>
<Tag key={idx} color='white' size='small' shape='circle'>
{ep}
</Tag>
),
@@ -157,7 +167,7 @@ const renderBoundChannels = (channels) => {
return renderLimitedItems({
items: channels,
renderItem: (c, idx) => (
<Tag key={idx} color="white" size="small" shape='circle'>
<Tag key={idx} color='white' size='small' shape='circle'>
{c.name}({c.type})
</Tag>
),
@@ -165,20 +175,28 @@ const renderBoundChannels = (channels) => {
};
// Render operations column
const renderOperations = (text, record, setEditingModel, setShowEdit, manageModel, refresh, t) => {
const renderOperations = (
text,
record,
setEditingModel,
setShowEdit,
manageModel,
refresh,
t,
) => {
return (
<Space wrap>
{record.status === 1 ? (
<Button
type='danger'
size="small"
size='small'
onClick={() => manageModel(record.id, 'disable', record)}
>
{t('禁用')}
</Button>
) : (
<Button
size="small"
size='small'
onClick={() => manageModel(record.id, 'enable', record)}
>
{t('启用')}
@@ -187,7 +205,7 @@ const renderOperations = (text, record, setEditingModel, setShowEdit, manageMode
<Button
type='tertiary'
size="small"
size='small'
onClick={() => {
setEditingModel(record);
setShowEdit(true);
@@ -198,7 +216,7 @@ const renderOperations = (text, record, setEditingModel, setShowEdit, manageMode
<Button
type='danger'
size="small"
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此模型?'),
@@ -235,12 +253,16 @@ const renderNameRule = (rule, record, t) => {
}
const tagElement = (
<Tag color={cfg.color} size="small" shape='circle'>
<Tag color={cfg.color} size='small' shape='circle'>
{label}
</Tag>
);
if (rule === 0 || !record.matched_models || record.matched_models.length === 0) {
if (
rule === 0 ||
!record.matched_models ||
record.matched_models.length === 0
) {
return tagElement;
}
@@ -334,15 +356,16 @@ export const getModelsColumns = ({
title: '',
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) => renderOperations(
text,
record,
setEditingModel,
setShowEdit,
manageModel,
refresh,
t
),
render: (text, record, index) =>
renderOperations(
text,
record,
setEditingModel,
setShowEdit,
manageModel,
refresh,
t,
),
},
];
};
};

View File

@@ -26,9 +26,9 @@ 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" />
<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>
@@ -41,4 +41,4 @@ const ModelsDescription = ({ compactMode, setCompactMode, t }) => {
);
};
export default ModelsDescription;
export default ModelsDescription;

View File

@@ -49,42 +49,42 @@ const ModelsFilters = ({
}}
onSubmit={searchModels}
allowEmpty={true}
autoComplete="off"
layout="horizontal"
trigger="change"
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className="w-full md:w-auto order-1 md:order-2"
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">
<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"
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('搜索模型名称')}
showClear
pure
size="small"
size='small'
/>
</div>
<div className="relative w-full md:w-56">
<div className='relative w-full md:w-56'>
<Form.Input
field="searchVendor"
field='searchVendor'
prefix={<IconSearch />}
placeholder={t('搜索供应商')}
showClear
pure
size="small"
size='small'
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<div className='flex gap-2 w-full md:w-auto'>
<Button
type="tertiary"
htmlType="submit"
type='tertiary'
htmlType='submit'
loading={loading || searching}
className="flex-1 md:flex-initial md:w-auto"
size="small"
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
@@ -92,8 +92,8 @@ const ModelsFilters = ({
<Button
type='tertiary'
onClick={handleReset}
className="flex-1 md:flex-initial md:w-auto"
size="small"
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
@@ -103,4 +103,4 @@ const ModelsFilters = ({
);
};
export default ModelsFilters;
export default ModelsFilters;

View File

@@ -60,13 +60,15 @@ const ModelsTable = (modelsData) => {
// 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;
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
@@ -90,15 +92,17 @@ const ModelsTable = (modelsData) => {
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className="rounded-xl overflow-hidden"
size="middle"
className='rounded-xl overflow-hidden'
size='middle'
/>
);
};
export default ModelsTable;
export default ModelsTable;

View File

@@ -36,7 +36,7 @@ const ModelsTabs = ({
setShowEditVendor,
setEditingVendor,
loadVendors,
t
t,
}) => {
const handleTabChange = (key) => {
setActiveVendorKey(key);
@@ -75,14 +75,14 @@ const ModelsTabs = ({
return (
<Tabs
activeKey={activeVendorKey}
type="card"
type='card'
collapsible
onChange={handleTabChange}
className="mb-2"
className='mb-2'
tabBarExtraContent={
<Button
type="primary"
size="small"
type='primary'
size='small'
onClick={() => setShowAddVendor(true)}
>
{t('新增供应商')}
@@ -90,11 +90,14 @@ const ModelsTabs = ({
}
>
<TabPane
itemKey="all"
itemKey='all'
tab={
<span className="flex items-center gap-2">
<span className='flex items-center gap-2'>
{t('全部')}
<Tag color={activeVendorKey === 'all' ? 'red' : 'grey'} shape='circle'>
<Tag
color={activeVendorKey === 'all' ? 'red' : 'grey'}
shape='circle'
>
{vendorCounts['all'] || 0}
</Tag>
</span>
@@ -109,15 +112,18 @@ const ModelsTabs = ({
key={key}
itemKey={key}
tab={
<span className="flex items-center gap-2">
<span className='flex items-center gap-2'>
{getLobeHubIcon(vendor.icon || 'Layers', 14)}
{vendor.name}
<Tag color={activeVendorKey === key ? 'red' : 'grey'} shape='circle'>
<Tag
color={activeVendorKey === key ? 'red' : 'grey'}
shape='circle'
>
{count}
</Tag>
<Dropdown
trigger="click"
position="bottomRight"
trigger='click'
position='bottomRight'
render={
<Dropdown.Menu>
<Dropdown.Item
@@ -127,13 +133,16 @@ const ModelsTabs = ({
{t('编辑')}
</Dropdown.Item>
<Dropdown.Item
type="danger"
type='danger'
icon={<IconDelete />}
onClick={(e) => {
e.stopPropagation();
Modal.confirm({
title: t('确认删除'),
content: t('确定要删除供应商 "{{name}}" 吗?此操作不可撤销。', { name: vendor.name }),
content: t(
'确定要删除供应商 "{{name}}" 吗?此操作不可撤销。',
{ name: vendor.name },
),
onOk: () => handleDeleteVendor(vendor, e),
okText: t('删除'),
cancelText: t('取消'),
@@ -149,9 +158,9 @@ const ModelsTabs = ({
onClickOutSide={(e) => e.stopPropagation()}
>
<Button
size="small"
type="tertiary"
theme="outline"
size='small'
type='tertiary'
theme='outline'
onClick={(e) => e.stopPropagation()}
>
{t('操作')}
@@ -166,4 +175,4 @@ const ModelsTabs = ({
);
};
export default ModelsTabs;
export default ModelsTabs;

View File

@@ -28,7 +28,14 @@ const NOTICE_ID = 'models-batch-actions';
* 1. 当 selectedKeys.length > 0 时,使用固定 id 创建/更新通知
* 2. 当 selectedKeys 清空时关闭通知
*/
const SelectionNotification = ({ selectedKeys = [], t, onDelete, onAddPrefill, onClear, onCopy }) => {
const SelectionNotification = ({
selectedKeys = [],
t,
onDelete,
onAddPrefill,
onClear,
onCopy,
}) => {
// 根据选中数量决定显示/隐藏或更新通知
useEffect(() => {
const selectedCount = selectedKeys.length;
@@ -37,42 +44,29 @@ const SelectionNotification = ({ selectedKeys = [], t, onDelete, onAddPrefill, o
const titleNode = (
<Space wrap>
<span>{t('批量操作')}</span>
<Typography.Text type="tertiary" size="small">{t('已选择 {{count}} 个模型', { count: selectedCount })}</Typography.Text>
<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}
>
<Button size='small' type='tertiary' theme='solid' onClick={onClear}>
{t('取消全选')}
</Button>
<Button
size="small"
type="primary"
theme="solid"
size='small'
type='primary'
theme='solid'
onClick={onAddPrefill}
>
{t('加入预填组')}
</Button>
<Button
size="small"
type="secondary"
theme="solid"
onClick={onCopy}
>
<Button size='small' type='secondary' theme='solid' onClick={onCopy}>
{t('复制名称')}
</Button>
<Button
size="small"
type="danger"
theme="solid"
onClick={onDelete}
>
<Button size='small' type='danger' theme='solid' onClick={onDelete}>
{t('删除所选')}
</Button>
</Space>

View File

@@ -95,10 +95,10 @@ const ModelsPage = () => {
/>
<CardPro
type="type3"
type='type3'
tabsArea={<ModelsTabs {...modelsData} />}
actionsArea={
<div className="flex flex-col md:flex-row justify-between items-center gap-2 w-full">
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<ModelsActions
selectedKeys={selectedKeys}
setSelectedKeys={setSelectedKeys}
@@ -110,7 +110,7 @@ const ModelsPage = () => {
t={t}
/>
<div className="w-full md:w-full lg:w-auto order-1 md:order-2">
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<ModelsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}

View File

@@ -290,7 +290,9 @@ const EditModelModal = (props) => {
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>{t('设置模型的基本信息')}</div>
<div className='text-xs text-gray-600'>
{t('设置模型的基本信息')}
</div>
</div>
</div>
<Row gutter={12}>
@@ -309,9 +311,16 @@ const EditModelModal = (props) => {
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('根据模型名称和匹配规则查找模型元数据,优先级:精确 > 前缀 > 后缀 > 包含')}
optionList={nameRuleOptions.map((o) => ({
label: t(o.label),
value: o.value,
}))}
rules={[
{ required: true, message: t('请选择名称匹配类型') },
]}
extraText={t(
'根据模型名称和匹配规则查找模型元数据,优先级:精确 > 前缀 > 后缀 > 包含',
)}
style={{ width: '100%' }}
/>
</Col>
@@ -323,9 +332,14 @@ const EditModelModal = (props) => {
placeholder={t('请输入图标名称')}
extraText={
<span>
{t('图标使用@lobehub/icons库OpenAI、Claude.Color支持链式参数OpenAI.Avatar.type={\'platform\'}、OpenRouter.Avatar.shape={\'square\'},查询所有可用图标请 ')}
{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' }}
link={{
href: 'https://icons.lobehub.com/components/lobe-hub',
target: '_blank',
}}
icon={<IconLink />}
underline
>
@@ -357,7 +371,16 @@ const EditModelModal = (props) => {
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)))];
return [
...new Set(
tags.flatMap((tag) =>
tag
.split(',')
.map((t) => t.trim())
.filter(Boolean),
),
),
];
};
const normalized = normalize(newTags);
formApiRef.current.setValue('tags', normalized);
@@ -366,17 +389,24 @@ const EditModelModal = (props) => {
{...(tagGroups.length > 0 && {
extraText: (
<Space wrap>
{tagGroups.map(group => (
{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 currentTags =
formApiRef.current.getValue('tags') || [];
const newTags = [
...currentTags,
...(group.items || []),
];
const uniqueTags = [...new Set(newTags)];
formApiRef.current.setValue('tags', uniqueTags);
formApiRef.current.setValue(
'tags',
uniqueTags,
);
}
}}
>
@@ -384,7 +414,7 @@ const EditModelModal = (props) => {
</Button>
))}
</Space>
)
),
})}
/>
</Col>
@@ -393,13 +423,19 @@ const EditModelModal = (props) => {
field='vendor_id'
label={t('供应商')}
placeholder={t('选择模型供应商')}
optionList={vendors.map(v => ({ label: v.name, value: v.id }))}
optionList={vendors.map((v) => ({
label: v.name,
value: v.id,
}))}
filter
showClear
onChange={(value) => {
const vendorInfo = vendors.find(v => v.id === value);
const vendorInfo = vendors.find((v) => v.id === value);
if (vendorInfo && formApiRef.current) {
formApiRef.current.setValue('vendor', vendorInfo.name);
formApiRef.current.setValue(
'vendor',
vendorInfo.name,
);
}
}}
style={{ width: '100%' }}
@@ -409,49 +445,71 @@ const EditModelModal = (props) => {
<JSONEditor
field='endpoints'
label={t('端点映射')}
placeholder={'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'}
placeholder={
'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'
}
value={values.endpoints}
onChange={(val) => formApiRef.current?.setValue('endpoints', val)}
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) {
extraFooter={
endpointGroups.length > 0 && (
<Space wrap>
{endpointGroups.map((group) => (
<Button
key={group.id}
size='small'
type='primary'
onClick={() => {
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>
)}
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='status'
label={t('状态')}
size="large"
size='large'
/>
</Col>
</Row>
@@ -464,4 +522,4 @@ const EditModelModal = (props) => {
);
};
export default EditModelModal;
export default EditModelModal;

View File

@@ -32,11 +32,7 @@ import {
Avatar,
Spin,
} from '@douyinfe/semi-ui';
import {
IconLayers,
IconSave,
IconClose,
} from '@douyinfe/semi-icons';
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';
@@ -53,7 +49,12 @@ const ENDPOINT_TEMPLATE = {
'image-generation': { path: '/v1/images/generations', method: 'POST' },
};
const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) => {
const EditPrefillGroupModal = ({
visible,
onClose,
editingGroup,
onSuccess,
}) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
@@ -112,7 +113,7 @@ const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) =>
return (
<SideSheet
placement="left"
placement='left'
title={
<Space>
{isEdit ? (
@@ -193,13 +194,15 @@ const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) =>
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>{t('设置预填组的基本信息')}</div>
<div className='text-xs text-gray-600'>
{t('设置预填组的基本信息')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field="name"
field='name'
label={t('组名')}
placeholder={t('请输入组名')}
rules={[{ required: true, message: t('请输入组名') }]}
@@ -208,7 +211,7 @@ const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) =>
</Col>
<Col span={24}>
<Form.Select
field="type"
field='type'
label={t('类型')}
placeholder={t('选择组类型')}
optionList={typeOptions}
@@ -219,7 +222,7 @@ const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) =>
</Col>
<Col span={24}>
<Form.TextArea
field="description"
field='description'
label={t('描述')}
placeholder={t('请输入组描述')}
rows={3}
@@ -229,19 +232,28 @@ const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) =>
<Col span={24}>
{selectedType === 'endpoint' ? (
<JSONEditor
field="items"
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)}
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}'}
placeholder={
'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'
}
template={ENDPOINT_TEMPLATE}
templateLabel={t('填入模板')}
extraText={t('键为端点类型,值为路径和方法对象')}
/>
) : (
<Form.TagInput
field="items"
field='items'
label={t('项目')}
placeholder={t('输入项目名称,按回车添加')}
addOnBlur
@@ -259,4 +271,4 @@ const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) =>
);
};
export default EditPrefillGroupModal;
export default EditPrefillGroupModal;

View File

@@ -18,12 +18,7 @@ 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 { 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';
@@ -138,7 +133,7 @@ const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
<Row gutter={12}>
<Col span={24}>
<Form.Input
field="name"
field='name'
label={t('供应商名称')}
placeholder={t('请输入供应商名称OpenAI')}
rules={[{ required: true, message: t('请输入供应商名称') }]}
@@ -147,7 +142,7 @@ const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
</Col>
<Col span={24}>
<Form.TextArea
field="description"
field='description'
label={t('描述')}
placeholder={t('请输入供应商描述')}
rows={3}
@@ -156,14 +151,19 @@ const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
</Col>
<Col span={24}>
<Form.Input
field="icon"
field='icon'
label={t('供应商图标')}
placeholder={t("请输入图标名称")}
placeholder={t('请输入图标名称')}
extraText={
<span>
{t('图标使用@lobehub/icons库OpenAI、Claude.Color支持链式参数OpenAI.Avatar.type={\'platform\'}、OpenRouter.Avatar.shape={\'square\'},查询所有可用图标请 ')}
{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' }}
link={{
href: 'https://icons.lobehub.com/components/lobe-hub',
target: '_blank',
}}
icon={<IconLink />}
underline
>
@@ -175,11 +175,7 @@ const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
/>
</Col>
<Col span={24}>
<Form.Switch
field="status"
label={t('状态')}
initValue={true}
/>
<Form.Switch field='status' label={t('状态')} initValue={true} />
</Col>
</Row>
</Form>
@@ -187,4 +183,4 @@ const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
);
};
export default EditVendorModal;
export default EditVendorModal;

View File

@@ -18,19 +18,25 @@ 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 '@douyinfe/semi-illustrations';
import {
Modal,
Table,
Spin,
Button,
Typography,
Empty,
Input,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-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 MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const [loading, setLoading] = useState(false);
const [missingModels, setMissingModels] = useState([]);
const [searchKeyword, setSearchKeyword] = useState('');
@@ -64,7 +70,7 @@ const MissingModelsModal = ({
// 过滤和分页逻辑
const filteredModels = missingModels.filter((model) =>
model.toLowerCase().includes(searchKeyword.toLowerCase())
model.toLowerCase().includes(searchKeyword.toLowerCase()),
);
const dataSource = (() => {
@@ -81,10 +87,10 @@ const MissingModelsModal = ({
title: t('模型名称'),
dataIndex: 'model',
render: (text) => (
<div className="flex items-center">
<div className='flex items-center'>
<Typography.Text strong>{text}</Typography.Text>
</div>
)
),
},
{
title: '',
@@ -93,25 +99,28 @@ const MissingModelsModal = ({
width: 100,
render: (text, record) => (
<Button
type="primary"
size="small"
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">
<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">
<Typography.Text type='tertiary' size='small'>
{t('共')} {missingModels.length} {t('个未配置模型')}
</Typography.Text>
</div>
@@ -121,20 +130,22 @@ const MissingModelsModal = ({
onCancel={onClose}
footer={null}
size={isMobile ? 'full-width' : 'medium'}
className="!rounded-lg"
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 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无缺失模型')}
style={{ padding: 30 }}
/>
) : (
<div className="missing-models-content">
<div className='missing-models-content'>
{/* 搜索框 */}
<div className="flex items-center justify-end gap-2 w-full mb-4">
<div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input
placeholder={t('搜索模型...')}
value={searchKeyword}
@@ -142,7 +153,7 @@ const MissingModelsModal = ({
setSearchKeyword(v);
setCurrentPage(1);
}}
className="!w-full"
className='!w-full'
prefix={<IconSearch />}
showClear
/>
@@ -163,9 +174,17 @@ const MissingModelsModal = ({
/>
) : (
<Empty
image={<IllustrationNoResult style={{ width: 100, height: 100 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 100, height: 100 }} />}
description={searchKeyword ? t('未找到匹配的模型') : t('暂无缺失模型')}
image={
<IllustrationNoResult style={{ width: 100, height: 100 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 100, height: 100 }}
/>
}
description={
searchKeyword ? t('未找到匹配的模型') : t('暂无缺失模型')
}
style={{ padding: 20 }}
/>
)}

View File

@@ -30,20 +30,25 @@ import {
Spin,
Empty,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconLayers,
} from '@douyinfe/semi-icons';
import { IconPlus, IconLayers } from '@douyinfe/semi-icons';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { API, showError, showSuccess, stringToColor } from '../../../../helpers';
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';
import {
renderLimitedItems,
renderDescription,
} from '../../../common/ui/RenderUtils';
const { Text, Title } = Typography;
@@ -121,8 +126,9 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
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 color='white' shape='circle' size='small'>
{typeOptions.find((opt) => opt.value === record.type)?.label ||
record.type}
</Tag>
</Space>
),
@@ -140,34 +146,49 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
render: (items, record) => {
try {
if (record.type === 'endpoint') {
const obj = typeof items === 'string' ? JSON.parse(items || '{}') : (items || {});
const obj =
typeof items === 'string'
? JSON.parse(items || '{}')
: items || {};
const keys = Object.keys(obj);
if (keys.length === 0) return <Text type="tertiary">{t('暂无项目')}</Text>;
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)}>
<Tag
key={idx}
size='small'
shape='circle'
color={stringToColor(key)}
>
{key}
</Tag>
),
maxDisplay: 3,
});
}
const itemsArray = typeof items === 'string' ? JSON.parse(items) : items;
const itemsArray =
typeof items === 'string' ? JSON.parse(items) : items;
if (!Array.isArray(itemsArray) || itemsArray.length === 0) {
return <Text type="tertiary">{t('暂无项目')}</Text>;
return <Text type='tertiary'>{t('暂无项目')}</Text>;
}
return renderLimitedItems({
items: itemsArray,
renderItem: (item, idx) => (
<Tag key={idx} size="small" shape='circle' color={stringToColor(item)}>
<Tag
key={idx}
size='small'
shape='circle'
color={stringToColor(item)}
>
{item}
</Tag>
),
maxDisplay: 3,
});
} catch {
return <Text type="tertiary">{t('数据格式错误')}</Text>;
return <Text type='tertiary'>{t('数据格式错误')}</Text>;
}
},
},
@@ -178,20 +199,14 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
width: 140,
render: (_, record) => (
<Space>
<Button
size="small"
onClick={() => handleEdit(record)}
>
<Button size='small' onClick={() => handleEdit(record)}>
{t('编辑')}
</Button>
<Popconfirm
title={t('确定删除此组?')}
onConfirm={() => deleteGroup(record.id)}
>
<Button
size="small"
type="danger"
>
<Button size='small' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
@@ -209,7 +224,7 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
return (
<>
<SideSheet
placement="left"
placement='left'
title={
<Space>
<Tag color='blue' shape='circle'>
@@ -235,14 +250,16 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('组列表')}</Text>
<div className='text-xs text-gray-600'>{t('管理模型、标签、端点等预填组')}</div>
<div className='text-xs text-gray-600'>
{t('管理模型、标签、端点等预填组')}
</div>
</div>
</div>
<div className="flex justify-end mb-4">
<div className='flex justify-end mb-4'>
<Button
type="primary"
type='primary'
theme='solid'
size="small"
size='small'
icon={<IconPlus />}
onClick={() => handleEdit()}
>
@@ -253,15 +270,21 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
<CardTable
columns={columns}
dataSource={groups}
rowKey="id"
rowKey='id'
hidePagination={true}
size="small"
size='small'
scroll={{ x: 'max-content' }}
/>
) : (
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 150, height: 150 }}
/>
}
description={t('暂无预填组')}
style={{ padding: 30 }}
/>
@@ -282,4 +305,4 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
);
};
export default PrefillGroupManagement;
export default PrefillGroupManagement;

View File

@@ -26,9 +26,8 @@ const RedemptionsActions = ({
setShowEdit,
batchCopyRedemptions,
batchDeleteRedemptions,
t
t,
}) => {
// Add new redemption code
const handleAddRedemption = () => {
setEditingRedemption({
@@ -38,30 +37,30 @@ const RedemptionsActions = ({
};
return (
<div className="flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1">
<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"
type='primary'
className='flex-1 md:flex-initial'
onClick={handleAddRedemption}
size="small"
size='small'
>
{t('添加兑换码')}
</Button>
<Button
type='tertiary'
className="flex-1 md:flex-initial"
className='flex-1 md:flex-initial'
onClick={batchCopyRedemptions}
size="small"
size='small'
>
{t('复制所选兑换码到剪贴板')}
</Button>
<Button
type='danger'
className="w-full md:w-auto"
className='w-full md:w-auto'
onClick={batchDeleteRedemptions}
size="small"
size='small'
>
{t('清除失效兑换码')}
</Button>
@@ -69,4 +68,4 @@ const RedemptionsActions = ({
);
};
export default RedemptionsActions;
export default RedemptionsActions;

View File

@@ -21,15 +21,21 @@ import React from 'react';
import { Tag, Button, Space, Popover, Dropdown } from '@douyinfe/semi-ui';
import { IconMore } from '@douyinfe/semi-icons';
import { renderQuota, timestamp2string } from '../../../helpers';
import { REDEMPTION_STATUS, REDEMPTION_STATUS_MAP, REDEMPTION_ACTIONS } from '../../../constants/redemption.constants';
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 &&
return (
record.status === REDEMPTION_STATUS.UNUSED &&
record.expired_time !== 0 &&
record.expired_time < Math.floor(Date.now() / 1000);
record.expired_time < Math.floor(Date.now() / 1000)
);
};
/**
@@ -45,7 +51,9 @@ const renderTimestamp = (timestamp) => {
const renderStatus = (status, record, t) => {
if (isExpired(record)) {
return (
<Tag color='orange' shape='circle'>{t('已过期')}</Tag>
<Tag color='orange' shape='circle'>
{t('已过期')}
</Tag>
);
}
@@ -77,7 +85,7 @@ export const getRedemptionsColumns = ({
refresh,
redemptions,
activePage,
showDeleteRedemptionModal
showDeleteRedemptionModal,
}) => {
return [
{
@@ -145,7 +153,7 @@ export const getRedemptionsColumns = ({
onClick: () => {
showDeleteRedemptionModal(record);
},
}
},
];
if (record.status === REDEMPTION_STATUS.UNUSED && !isExpired(record)) {
@@ -171,16 +179,17 @@ export const getRedemptionsColumns = ({
return (
<Space>
<Popover content={record.key} style={{ padding: 20 }} position='top'>
<Button
type='tertiary'
size="small"
>
<Popover
content={record.key}
style={{ padding: 20 }}
position='top'
>
<Button type='tertiary' size='small'>
{t('查看')}
</Button>
</Popover>
<Button
size="small"
size='small'
onClick={async () => {
await copyText(record.key);
}}
@@ -189,7 +198,7 @@ export const getRedemptionsColumns = ({
</Button>
<Button
type='tertiary'
size="small"
size='small'
onClick={() => {
setEditingRedemption(record);
setShowEdit(true);
@@ -203,15 +212,11 @@ export const getRedemptionsColumns = ({
position='bottomRight'
menu={moreMenuItems}
>
<Button
type='tertiary'
size="small"
icon={<IconMore />}
/>
<Button type='tertiary' size='small' icon={<IconMore />} />
</Dropdown>
</Space>
);
},
},
];
};
};

View File

@@ -26,9 +26,9 @@ 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" />
<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>
@@ -41,4 +41,4 @@ const RedemptionsDescription = ({ compactMode, setCompactMode, t }) => {
);
};
export default RedemptionsDescription;
export default RedemptionsDescription;

View File

@@ -27,9 +27,8 @@ const RedemptionsFilters = ({
searchRedemptions,
loading,
searching,
t
t,
}) => {
// Handle form reset and immediate search
const formApiRef = useRef(null);
@@ -50,38 +49,38 @@ const RedemptionsFilters = ({
}}
onSubmit={searchRedemptions}
allowEmpty={true}
autoComplete="off"
layout="horizontal"
trigger="change"
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className="w-full md:w-auto order-1 md:order-2"
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">
<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"
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('关键字(id或者名称)')}
showClear
pure
size="small"
size='small'
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<div className='flex gap-2 w-full md:w-auto'>
<Button
type="tertiary"
htmlType="submit"
type='tertiary'
htmlType='submit'
loading={loading || searching}
className="flex-1 md:flex-initial md:w-auto"
size="small"
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
<Button
type="tertiary"
type='tertiary'
onClick={handleReset}
className="flex-1 md:flex-initial md:w-auto"
size="small"
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
@@ -91,4 +90,4 @@ const RedemptionsFilters = ({
);
};
export default RedemptionsFilters;
export default RedemptionsFilters;

View File

@@ -22,7 +22,7 @@ import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { getRedemptionsColumns, isExpired } from './RedemptionsColumnDefs';
import DeleteRedemptionModal from './modals/DeleteRedemptionModal';
@@ -67,7 +67,7 @@ const RedemptionsTable = (redemptionsData) => {
refresh,
redemptions,
activePage,
showDeleteRedemptionModal
showDeleteRedemptionModal,
});
}, [
t,
@@ -83,13 +83,15 @@ const RedemptionsTable = (redemptionsData) => {
// 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;
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
@@ -114,13 +116,15 @@ const RedemptionsTable = (redemptionsData) => {
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className="rounded-xl overflow-hidden"
size="middle"
className='rounded-xl overflow-hidden'
size='middle'
/>
<DeleteRedemptionModal
@@ -137,4 +141,4 @@ const RedemptionsTable = (redemptionsData) => {
);
};
export default RedemptionsTable;
export default RedemptionsTable;

View File

@@ -71,7 +71,7 @@ const RedemptionsPage = () => {
/>
<CardPro
type="type1"
type='type1'
descriptionArea={
<RedemptionsDescription
compactMode={compactMode}
@@ -80,7 +80,7 @@ const RedemptionsPage = () => {
/>
}
actionsArea={
<div className="flex flex-col md:flex-row justify-between items-center gap-2 w-full">
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<RedemptionsActions
selectedKeys={selectedKeys}
setEditingRedemption={setEditingRedemption}
@@ -90,7 +90,7 @@ const RedemptionsPage = () => {
t={t}
/>
<div className="w-full md:w-full lg:w-auto order-1 md:order-2">
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<RedemptionsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
@@ -119,4 +119,4 @@ const RedemptionsPage = () => {
);
};
export default RedemptionsPage;
export default RedemptionsPage;

View File

@@ -21,15 +21,15 @@ import React from 'react';
import { Modal } from '@douyinfe/semi-ui';
import { REDEMPTION_ACTIONS } from '../../../../constants/redemption.constants';
const DeleteRedemptionModal = ({
visible,
onCancel,
record,
manageRedemption,
const DeleteRedemptionModal = ({
visible,
onCancel,
record,
manageRedemption,
refresh,
redemptions,
activePage,
t
t,
}) => {
const handleConfirm = async () => {
await manageRedemption(record.id, REDEMPTION_ACTIONS.DELETE, record);
@@ -48,11 +48,11 @@ const DeleteRedemptionModal = ({
visible={visible}
onCancel={onCancel}
onOk={handleConfirm}
type="warning"
type='warning'
>
{t('此修改将不可逆')}
</Modal>
);
};
export default DeleteRedemptionModal;
export default DeleteRedemptionModal;

View File

@@ -109,7 +109,9 @@ const EditRedemptionModal = (props) => {
if (!localInputs.expired_time) {
localInputs.expired_time = 0;
} else {
localInputs.expired_time = Math.floor(localInputs.expired_time.getTime() / 1000);
localInputs.expired_time = Math.floor(
localInputs.expired_time.getTime() / 1000,
);
}
let res;
if (isEdit) {
@@ -164,11 +166,16 @@ const EditRedemptionModal = (props) => {
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 ? (
<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>
@@ -177,10 +184,10 @@ const EditRedemptionModal = (props) => {
visible={props.visiable}
width={isMobile ? '100%' : 600}
footer={
<div className="flex justify-end bg-white">
<div className='flex justify-end bg-white'>
<Space>
<Button
theme="solid"
theme='solid'
onClick={() => formApiRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
@@ -188,8 +195,8 @@ const EditRedemptionModal = (props) => {
{t('提交')}
</Button>
<Button
theme="light"
type="primary"
theme='light'
type='primary'
onClick={handleCancel}
icon={<IconClose />}
>
@@ -204,20 +211,28 @@ const EditRedemptionModal = (props) => {
<Spin spinning={loading}>
<Form
initValues={getInitValues()}
getFormApi={(api) => formApiRef.current = api}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
{({ values }) => (
<div className="p-2">
<Card className="!rounded-2xl shadow-sm border-0 mb-6">
<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">
<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>
<Text className='text-lg font-medium'>
{t('基本信息')}
</Text>
<div className='text-xs text-gray-600'>
{t('设置兑换码的基本信息')}
</div>
</div>
</div>
@@ -228,7 +243,11 @@ const EditRedemptionModal = (props) => {
label={t('名称')}
placeholder={t('请输入名称')}
style={{ width: '100%' }}
rules={!isEdit ? [] : [{ required: true, message: t('请输入名称') }]}
rules={
!isEdit
? []
: [{ required: true, message: t('请输入名称') }]
}
showClear
/>
</Col>
@@ -245,15 +264,23 @@ const EditRedemptionModal = (props) => {
</Row>
</Card>
<Card className="!rounded-2xl shadow-sm border-0">
<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">
<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>
<Text className='text-lg font-medium'>
{t('额度设置')}
</Text>
<div className='text-xs text-gray-600'>
{t('设置兑换码的额度和数量')}
</div>
</div>
</div>
@@ -276,7 +303,9 @@ const EditRedemptionModal = (props) => {
},
},
]}
extraText={renderQuotaWithPrompt(Number(values.quota) || 0)}
extraText={renderQuotaWithPrompt(
Number(values.quota) || 0,
)}
data={[
{ value: 500000, label: '1$' },
{ value: 5000000, label: '10$' },
@@ -321,4 +350,4 @@ const EditRedemptionModal = (props) => {
);
};
export default EditRedemptionModal;
export default EditRedemptionModal;

View File

@@ -24,15 +24,11 @@ import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const TaskLogsActions = ({
compactMode,
setCompactMode,
t,
}) => {
const TaskLogsActions = ({ 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 mb-2 md:mb-0">
<IconEyeOpened className="mr-2" />
<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 mb-2 md:mb-0'>
<IconEyeOpened className='mr-2' />
<Text>{t('任务记录')}</Text>
</div>
<CompactModeToggle
@@ -44,4 +40,4 @@ const TaskLogsActions = ({
);
};
export default TaskLogsActions;
export default TaskLogsActions;

View File

@@ -18,11 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import {
Progress,
Tag,
Typography
} from '@douyinfe/semi-ui';
import { Progress, Tag, Typography } from '@douyinfe/semi-ui';
import {
Music,
FileText,
@@ -36,9 +32,12 @@ import {
List,
Hash,
Video,
Sparkles
Sparkles,
} from 'lucide-react';
import { TASK_ACTION_GENERATE, TASK_ACTION_TEXT_GENERATE } from '../../../constants/common.constant';
import {
TASK_ACTION_GENERATE,
TASK_ACTION_TEXT_GENERATE,
} from '../../../constants/common.constant';
import { CHANNEL_OPTIONS } from '../../../constants/channel.constants';
const colors = [
@@ -122,7 +121,9 @@ const renderType = (type, t) => {
};
const renderPlatform = (platform, t) => {
let option = CHANNEL_OPTIONS.find(opt => String(opt.value) === String(platform));
let option = CHANNEL_OPTIONS.find(
(opt) => String(opt.value) === String(platform),
);
if (option) {
return (
<Tag color={option.color} shape='circle' prefixIcon={<Video size={14} />}>
@@ -150,7 +151,11 @@ const renderStatus = (type, t) => {
switch (type) {
case 'SUCCESS':
return (
<Tag color='green' shape='circle' prefixIcon={<CheckCircle size={14} />}>
<Tag
color='green'
shape='circle'
prefixIcon={<CheckCircle size={14} />}
>
{t('成功')}
</Tag>
);
@@ -310,23 +315,21 @@ export const getTaskLogsColumns = ({
render: (text, record, index) => {
return (
<div>
{
isNaN(text?.replace('%', '')) ? (
text || '-'
) : (
<Progress
stroke={
record.status === 'FAILURE'
? 'var(--semi-color-warning)'
: null
}
percent={text ? parseInt(text.replace('%', '')) : 0}
showInfo={true}
aria-label='task progress'
style={{ minWidth: '160px' }}
/>
)
}
{isNaN(text?.replace('%', '')) ? (
text || '-'
) : (
<Progress
stroke={
record.status === 'FAILURE'
? 'var(--semi-color-warning)'
: null
}
percent={text ? parseInt(text.replace('%', '')) : 0}
showInfo={true}
aria-label='task progress'
style={{ minWidth: '160px' }}
/>
)}
</div>
);
},
@@ -338,14 +341,16 @@ export const getTaskLogsColumns = ({
fixed: 'right',
render: (text, record, index) => {
// 仅当为视频生成任务且成功,且 fail_reason 是 URL 时显示可点击链接
const isVideoTask = record.action === TASK_ACTION_GENERATE || record.action === TASK_ACTION_TEXT_GENERATE;
const isVideoTask =
record.action === TASK_ACTION_GENERATE ||
record.action === TASK_ACTION_TEXT_GENERATE;
const isSuccess = record.status === 'SUCCESS';
const isUrl = typeof text === 'string' && /^https?:\/\//.test(text);
if (isSuccess && isVideoTask && isUrl) {
return (
<a
href="#"
onClick={e => {
href='#'
onClick={(e) => {
e.preventDefault();
openVideoModal(text);
}}
@@ -371,4 +376,4 @@ export const getTaskLogsColumns = ({
},
},
];
};
};

View File

@@ -37,23 +37,23 @@ const TaskLogsFilters = ({
getFormApi={(api) => setFormApi(api)}
onSubmit={refresh}
allowEmpty={true}
autoComplete="off"
layout="vertical"
trigger="change"
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='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">
<div className='col-span-1 lg:col-span-2'>
<Form.DatePicker
field='dateRange'
className="w-full"
className='w-full'
type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]}
showClear
pure
size="small"
size='small'
/>
</div>
@@ -64,7 +64,7 @@ const TaskLogsFilters = ({
placeholder={t('任务 ID')}
showClear
pure
size="small"
size='small'
/>
{/* 渠道 ID - 仅管理员可见 */}
@@ -75,20 +75,20 @@ const TaskLogsFilters = ({
placeholder={t('渠道 ID')}
showClear
pure
size="small"
size='small'
/>
)}
</div>
{/* 操作按钮区域 */}
<div className="flex justify-between items-center">
<div className='flex justify-between items-center'>
<div></div>
<div className="flex gap-2">
<div className='flex gap-2'>
<Button
type='tertiary'
htmlType='submit'
loading={loading}
size="small"
size='small'
>
{t('查询')}
</Button>
@@ -103,14 +103,14 @@ const TaskLogsFilters = ({
}, 100);
}
}}
size="small"
size='small'
>
{t('重置')}
</Button>
<Button
type='tertiary'
onClick={() => setShowColumnSelector(true)}
size="small"
size='small'
>
{t('列设置')}
</Button>
@@ -121,4 +121,4 @@ const TaskLogsFilters = ({
);
};
export default TaskLogsFilters;
export default TaskLogsFilters;

View File

@@ -55,14 +55,7 @@ const TaskLogsTable = (taskLogsData) => {
openVideoModal,
isAdminUser,
});
}, [
t,
COLUMN_KEYS,
copyText,
openContentModal,
openVideoModal,
isAdminUser,
]);
}, [t, COLUMN_KEYS, copyText, openContentModal, openVideoModal, isAdminUser]);
// Filter columns based on visibility settings
const getVisibleColumns = () => {
@@ -86,13 +79,11 @@ const TaskLogsTable = (taskLogsData) => {
rowKey='key'
loading={loading}
scroll={compactMode ? undefined : { x: 'max-content' }}
className="rounded-xl overflow-hidden"
size="middle"
className='rounded-xl overflow-hidden'
size='middle'
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
@@ -114,4 +105,4 @@ const TaskLogsTable = (taskLogsData) => {
);
};
export default TaskLogsTable;
export default TaskLogsTable;

View File

@@ -48,7 +48,7 @@ const TaskLogsPage = () => {
<Layout>
<CardPro
type="type2"
type='type2'
statsArea={<TaskLogsActions {...taskLogsData} />}
searchArea={<TaskLogsFilters {...taskLogsData} />}
paginationArea={createCardProPagination({
@@ -69,4 +69,4 @@ const TaskLogsPage = () => {
);
};
export default TaskLogsPage;
export default TaskLogsPage;

View File

@@ -49,10 +49,8 @@ const ColumnSelectorModal = ({
visible={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
footer={
<div className="flex justify-end">
<Button onClick={() => initDefaultColumns()}>
{t('重置')}
</Button>
<div className='flex justify-end'>
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('取消')}
</Button>
@@ -75,7 +73,7 @@ const ColumnSelectorModal = ({
</Checkbox>
</div>
<div
className="flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4"
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) => {
@@ -85,7 +83,7 @@ const ColumnSelectorModal = ({
}
return (
<div key={column.key} className="w-1/2 mb-4 pr-2">
<div key={column.key} className='w-1/2 mb-4 pr-2'>
<Checkbox
checked={!!visibleColumns[column.key]}
onChange={(e) =>
@@ -102,4 +100,4 @@ const ColumnSelectorModal = ({
);
};
export default ColumnSelectorModal;
export default ColumnSelectorModal;

View File

@@ -44,4 +44,4 @@ const ContentModal = ({
);
};
export default ContentModal;
export default ContentModal;

View File

@@ -62,35 +62,35 @@ const TokensActions = ({
return (
<>
<div className="flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1">
<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"
type='primary'
className='flex-1 md:flex-initial'
onClick={() => {
setEditingToken({
id: undefined,
});
setShowEdit(true);
}}
size="small"
size='small'
>
{t('添加令牌')}
</Button>
<Button
type='tertiary'
className="flex-1 md:flex-initial"
className='flex-1 md:flex-initial'
onClick={handleCopySelectedTokens}
size="small"
size='small'
>
{t('复制所选令牌')}
</Button>
<Button
type='danger'
className="w-full md:w-auto"
className='w-full md:w-auto'
onClick={handleDeleteSelectedTokens}
size="small"
size='small'
>
{t('删除所选令牌')}
</Button>
@@ -115,4 +115,4 @@ const TokensActions = ({
);
};
export default TokensActions;
export default TokensActions;

View File

@@ -31,14 +31,14 @@ import {
Popover,
Typography,
Input,
Modal
Modal,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
renderGroup,
renderQuota,
getModelCategories,
showError
showError,
} from '../../../helpers';
import {
IconTreeTriangleDown,
@@ -92,10 +92,15 @@ const renderGroupColumn = (text, t) => {
if (text === 'auto') {
return (
<Tooltip
content={t('当前分组为 auto会自动选择最优分组当一个组不可用时自动降级到下一个组熔断机制')}
content={t(
'当前分组为 auto会自动选择最优分组当一个组不可用时自动降级到下一个组熔断机制',
)}
position='top'
>
<Tag color='white' shape='circle'> {t('智能熔断')} </Tag>
<Tag color='white' shape='circle'>
{' '}
{t('智能熔断')}{' '}
</Tag>
</Tooltip>
);
}
@@ -105,7 +110,8 @@ const renderGroupColumn = (text, t) => {
// 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 maskedKey =
'sk-' + record.key.slice(0, 4) + '**********' + record.key.slice(-4);
const revealed = !!showKeys[record.id];
return (
@@ -124,7 +130,7 @@ const renderTokenKey = (text, record, showKeys, setShowKeys, copyText) => {
aria-label='toggle token visibility'
onClick={(e) => {
e.stopPropagation();
setShowKeys(prev => ({ ...prev, [record.id]: !revealed }));
setShowKeys((prev) => ({ ...prev, [record.id]: !revealed }));
}}
/>
<Button
@@ -156,14 +162,25 @@ const renderModelLimits = (text, record, t) => {
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 }));
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'>
<Tooltip
key={key}
content={vendorModels.join(', ')}
position='top'
showArrow
>
<Avatar
size='extra-extra-small'
alt={category.label}
color='transparent'
>
{category.icon}
</Avatar>
</Tooltip>
</Tooltip>,
);
vendorModels.forEach((m) => matchedModels.add(m));
}
@@ -172,19 +189,20 @@ const renderModelLimits = (text, record, t) => {
const unmatchedModels = models.filter((m) => !matchedModels.has(m));
if (unmatchedModels.length > 0) {
vendorAvatars.push(
<Tooltip key='unknown' content={unmatchedModels.join(', ')} position='top' showArrow>
<Tooltip
key='unknown'
content={unmatchedModels.join(', ')}
position='top'
showArrow
>
<Avatar size='extra-extra-small' alt='unknown'>
{t('其他')}
</Avatar>
</Tooltip>
</Tooltip>,
);
}
return (
<AvatarGroup size='extra-extra-small'>
{vendorAvatars}
</AvatarGroup>
);
return <AvatarGroup size='extra-extra-small'>{vendorAvatars}</AvatarGroup>;
} else {
return (
<Tag color='white' shape='circle'>
@@ -226,10 +244,8 @@ const renderAllowIps = (text, t) => {
position='top'
showArrow
>
<Tag shape='circle'>
{'+' + extraCount}
</Tag>
</Tooltip>
<Tag shape='circle'>{'+' + extraCount}</Tag>
</Tooltip>,
);
}
@@ -291,7 +307,16 @@ const renderQuotaUsage = (text, record, t) => {
};
// Render operations column
const renderOperations = (text, record, onOpenLink, setEditingToken, setShowEdit, manageToken, refresh, t) => {
const renderOperations = (
text,
record,
onOpenLink,
setEditingToken,
setShowEdit,
manageToken,
refresh,
t,
) => {
let chatsArray = [];
try {
const raw = localStorage.getItem('chats');
@@ -317,11 +342,11 @@ const renderOperations = (text, record, onOpenLink, setEditingToken, setShowEdit
return (
<Space wrap>
<SplitButtonGroup
className="overflow-hidden"
className='overflow-hidden'
aria-label={t('项目操作按钮组')}
>
<Button
size="small"
size='small'
type='tertiary'
onClick={() => {
if (chatsArray.length === 0) {
@@ -334,15 +359,11 @@ const renderOperations = (text, record, onOpenLink, setEditingToken, setShowEdit
>
{t('聊天')}
</Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={chatsArray}
>
<Dropdown trigger='click' position='bottomRight' menu={chatsArray}>
<Button
type='tertiary'
icon={<IconTreeTriangleDown />}
size="small"
size='small'
></Button>
</Dropdown>
</SplitButtonGroup>
@@ -350,7 +371,7 @@ const renderOperations = (text, record, onOpenLink, setEditingToken, setShowEdit
{record.status === 1 ? (
<Button
type='danger'
size="small"
size='small'
onClick={async () => {
await manageToken(record.id, 'disable', record);
await refresh();
@@ -360,7 +381,7 @@ const renderOperations = (text, record, onOpenLink, setEditingToken, setShowEdit
</Button>
) : (
<Button
size="small"
size='small'
onClick={async () => {
await manageToken(record.id, 'enable', record);
await refresh();
@@ -372,7 +393,7 @@ const renderOperations = (text, record, onOpenLink, setEditingToken, setShowEdit
<Button
type='tertiary'
size="small"
size='small'
onClick={() => {
setEditingToken(record);
setShowEdit(true);
@@ -383,7 +404,7 @@ const renderOperations = (text, record, onOpenLink, setEditingToken, setShowEdit
<Button
type='danger'
size="small"
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此令牌?'),
@@ -439,7 +460,8 @@ export const getTokensColumns = ({
{
title: t('密钥'),
key: 'token_key',
render: (text, record) => renderTokenKey(text, record, showKeys, setShowKeys, copyText),
render: (text, record) =>
renderTokenKey(text, record, showKeys, setShowKeys, copyText),
},
{
title: t('可用模型'),
@@ -473,16 +495,17 @@ export const getTokensColumns = ({
title: '',
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) => renderOperations(
text,
record,
onOpenLink,
setEditingToken,
setShowEdit,
manageToken,
refresh,
t
),
render: (text, record, index) =>
renderOperations(
text,
record,
onOpenLink,
setEditingToken,
setShowEdit,
manageToken,
refresh,
t,
),
},
];
};
};

View File

@@ -26,9 +26,9 @@ 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" />
<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>
@@ -41,4 +41,4 @@ const TokensDescription = ({ compactMode, setCompactMode, t }) => {
);
};
export default TokensDescription;
export default TokensDescription;

View File

@@ -49,42 +49,42 @@ const TokensFilters = ({
}}
onSubmit={searchTokens}
allowEmpty={true}
autoComplete="off"
layout="horizontal"
trigger="change"
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className="w-full md:w-auto order-1 md:order-2"
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">
<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"
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('搜索关键字')}
showClear
pure
size="small"
size='small'
/>
</div>
<div className="relative w-full md:w-56">
<div className='relative w-full md:w-56'>
<Form.Input
field="searchToken"
field='searchToken'
prefix={<IconSearch />}
placeholder={t('密钥')}
showClear
pure
size="small"
size='small'
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<div className='flex gap-2 w-full md:w-auto'>
<Button
type="tertiary"
htmlType="submit"
type='tertiary'
htmlType='submit'
loading={loading || searching}
className="flex-1 md:flex-initial md:w-auto"
size="small"
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
@@ -92,8 +92,8 @@ const TokensFilters = ({
<Button
type='tertiary'
onClick={handleReset}
className="flex-1 md:flex-initial md:w-auto"
size="small"
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
@@ -103,4 +103,4 @@ const TokensFilters = ({
);
};
export default TokensFilters;
export default TokensFilters;

View File

@@ -76,13 +76,15 @@ const TokensTable = (tokensData) => {
// 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;
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
@@ -106,15 +108,17 @@ const TokensTable = (tokensData) => {
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className="rounded-xl overflow-hidden"
size="middle"
className='rounded-xl overflow-hidden'
size='middle'
/>
);
};
export default TokensTable;
export default TokensTable;

View File

@@ -18,8 +18,20 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import { Notification, Button, Space, Toast, Typography, Select } from '@douyinfe/semi-ui';
import { API, showError, getModelCategories, selectFilter } from '../../../helpers';
import {
Notification,
Button,
Space,
Toast,
Typography,
Select,
} from '@douyinfe/semi-ui';
import {
API,
showError,
getModelCategories,
selectFilter,
} from '../../../helpers';
import CardPro from '../../common/ui/CardPro';
import TokensTable from './TokensTable';
import TokensActions from './TokensActions';
@@ -33,9 +45,17 @@ import { createCardProPagination } from '../../../helpers/utils';
function TokensPage() {
// Define the function first, then pass it into the hook to avoid TDZ errors
const openFluentNotificationRef = useRef(null);
const tokensData = useTokensData((key) => openFluentNotificationRef.current?.(key));
const tokensData = useTokensData((key) =>
openFluentNotificationRef.current?.(key),
);
const isMobile = useIsMobile();
const latestRef = useRef({ tokens: [], selectedKeys: [], t: (k) => k, selectedModel: '', prefillKey: '' });
const latestRef = useRef({
tokens: [],
selectedKeys: [],
t: (k) => k,
selectedModel: '',
prefillKey: '',
});
const [modelOptions, setModelOptions] = useState([]);
const [selectedModel, setSelectedModel] = useState('');
const [fluentNoticeOpen, setFluentNoticeOpen] = useState(false);
@@ -50,7 +70,13 @@ function TokensPage() {
selectedModel,
prefillKey,
};
}, [tokensData.tokens, tokensData.selectedKeys, tokensData.t, selectedModel, prefillKey]);
}, [
tokensData.tokens,
tokensData.selectedKeys,
tokensData.t,
selectedModel,
prefillKey,
]);
const loadModels = async () => {
try {
@@ -68,7 +94,7 @@ function TokensPage() {
}
return {
label: (
<span className="flex items-center gap-1">
<span className='flex items-center gap-1'>
{icon}
{model}
</span>
@@ -90,7 +116,7 @@ function TokensPage() {
const SUPPRESS_KEY = 'fluent_notify_suppressed';
if (modelOptions.length === 0) {
// fire-and-forget; a later effect will refresh the notice content
loadModels()
loadModels();
}
if (!key && localStorage.getItem(SUPPRESS_KEY) === '1') return;
const container = document.getElementById('fluent-new-api-container');
@@ -123,19 +149,29 @@ function TokensPage() {
/>
</div>
<Space>
<Button theme="solid" type="primary" onClick={handlePrefillToFluent}>
<Button
theme='solid'
type='primary'
onClick={handlePrefillToFluent}
>
{t('一键填充到 FluentRead')}
</Button>
{!key && (
<Button type="warning" onClick={() => {
localStorage.setItem(SUPPRESS_KEY, '1');
Notification.close('fluent-detected');
Toast.info(t('已关闭后续提醒'));
}}>
<Button
type='warning'
onClick={() => {
localStorage.setItem(SUPPRESS_KEY, '1');
Notification.close('fluent-detected');
Toast.info(t('已关闭后续提醒'));
}}
>
{t('不再提醒')}
</Button>
)}
<Button type="tertiary" onClick={() => Notification.close('fluent-detected')}>
<Button
type='tertiary'
onClick={() => Notification.close('fluent-detected')}
>
{t('关闭')}
</Button>
</Space>
@@ -149,7 +185,13 @@ function TokensPage() {
// Prefill to Fluent handler
const handlePrefillToFluent = () => {
const { tokens, selectedKeys, t, selectedModel: chosenModel, prefillKey: overrideKey } = latestRef.current;
const {
tokens,
selectedKeys,
t,
selectedModel: chosenModel,
prefillKey: overrideKey,
} = latestRef.current;
const container = document.getElementById('fluent-new-api-container');
if (!container) {
Toast.error(t('未检测到 Fluent 容器'));
@@ -167,7 +209,7 @@ function TokensPage() {
try {
status = JSON.parse(status);
serverAddress = status.server_address || '';
} catch (_) { }
} catch (_) {}
}
if (!serverAddress) serverAddress = window.location.origin;
@@ -175,9 +217,12 @@ function TokensPage() {
if (overrideKey) {
apiKeyToUse = 'sk-' + overrideKey;
} else {
const token = (selectedKeys && selectedKeys.length === 1)
? selectedKeys[0]
: (tokens && tokens.length > 0 ? tokens[0] : null);
const token =
selectedKeys && selectedKeys.length === 1
? selectedKeys[0]
: tokens && tokens.length > 0
? tokens[0]
: null;
if (!token) {
Toast.warning(t('没有可用令牌用于填充'));
return;
@@ -192,7 +237,9 @@ function TokensPage() {
model: chosenModel,
};
container.dispatchEvent(new CustomEvent('fluent:prefill', { detail: payload }));
container.dispatchEvent(
new CustomEvent('fluent:prefill', { detail: payload }),
);
Toast.success(t('已发送到 Fluent'));
Notification.close('fluent-detected');
};
@@ -230,13 +277,18 @@ function TokensPage() {
const existing = document.querySelector(selector);
if (existing) {
console.log('Fluent container detected (initial):', existing);
window.dispatchEvent(new CustomEvent('fluent-container:appeared', { detail: existing }));
window.dispatchEvent(
new CustomEvent('fluent-container:appeared', { detail: existing }),
);
}
const isOrContainsTarget = (node) => {
if (!(node && node.nodeType === 1)) return false;
if (node.id === 'fluent-new-api-container') return true;
return typeof node.querySelector === 'function' && !!node.querySelector(selector);
return (
typeof node.querySelector === 'function' &&
!!node.querySelector(selector)
);
};
const observer = new MutationObserver((mutations) => {
@@ -247,7 +299,9 @@ function TokensPage() {
const el = document.querySelector(selector);
if (el) {
console.log('Fluent container appeared:', el);
window.dispatchEvent(new CustomEvent('fluent-container:appeared', { detail: el }));
window.dispatchEvent(
new CustomEvent('fluent-container:appeared', { detail: el }),
);
}
break;
}
@@ -310,7 +364,7 @@ function TokensPage() {
/>
<CardPro
type="type1"
type='type1'
descriptionArea={
<TokensDescription
compactMode={compactMode}
@@ -319,7 +373,7 @@ function TokensPage() {
/>
}
actionsArea={
<div className="flex flex-col md:flex-row justify-between items-center gap-2 w-full">
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<TokensActions
selectedKeys={selectedKeys}
setEditingToken={setEditingToken}
@@ -330,7 +384,7 @@ function TokensPage() {
t={t}
/>
<div className="w-full md:w-full lg:w-auto order-1 md:order-2">
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<TokensFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
@@ -359,4 +413,4 @@ function TokensPage() {
);
}
export default TokensPage;
export default TokensPage;

View File

@@ -49,17 +49,10 @@ const CopyTokensModal = ({ visible, onCancel, selectedKeys, copyText, t }) => {
onCancel={onCancel}
footer={
<Space>
<Button
type='tertiary'
onClick={handleCopyWithName}
>
<Button type='tertiary' onClick={handleCopyWithName}>
{t('名称+密钥')}
</Button>
<Button
onClick={handleCopyKeyOnly}
>
{t('仅密钥')}
</Button>
<Button onClick={handleCopyKeyOnly}>{t('仅密钥')}</Button>
</Space>
}
>
@@ -68,4 +61,4 @@ const CopyTokensModal = ({ visible, onCancel, selectedKeys, copyText, t }) => {
);
};
export default CopyTokensModal;
export default CopyTokensModal;

View File

@@ -20,20 +20,28 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react';
import { Modal } from '@douyinfe/semi-ui';
const DeleteTokensModal = ({ visible, onCancel, onConfirm, selectedKeys, t }) => {
const DeleteTokensModal = ({
visible,
onCancel,
onConfirm,
selectedKeys,
t,
}) => {
return (
<Modal
title={t('批量删除令牌')}
visible={visible}
onCancel={onCancel}
onOk={onConfirm}
type="warning"
type='warning'
>
<div>
{t('确定要删除所选的 {{count}} 个令牌吗?', { count: selectedKeys.length })}
{t('确定要删除所选的 {{count}} 个令牌吗?', {
count: selectedKeys.length,
})}
</div>
</Modal>
);
};
export default DeleteTokensModal;
export default DeleteTokensModal;

View File

@@ -111,7 +111,7 @@ const EditTokenModal = (props) => {
}
return {
label: (
<span className="flex items-center gap-1">
<span className='flex items-center gap-1'>
{icon}
{model}
</span>
@@ -239,7 +239,8 @@ const EditTokenModal = (props) => {
let successCount = 0;
for (let i = 0; i < count; i++) {
let { tokenCount: _tc, ...localInputs } = values;
const baseName = values.name.trim() === '' ? 'default' : values.name.trim();
const baseName =
values.name.trim() === '' ? 'default' : values.name.trim();
if (i !== 0 || values.name.trim() === '') {
localInputs.name = `${baseName}-${generateRandomSuffix()}`;
} else {
@@ -343,7 +344,9 @@ const EditTokenModal = (props) => {
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>{t('设置令牌的基本信息')}</div>
<div className='text-xs text-gray-600'>
{t('设置令牌的基本信息')}
</div>
</div>
</div>
<Row gutter={12}>
@@ -387,13 +390,16 @@ const EditTokenModal = (props) => {
{
validator: (rule, value) => {
// 允许 -1 表示永不过期,也允许空值在必填校验时被拦截
if (value === -1 || !value) return Promise.resolve();
if (value === -1 || !value)
return Promise.resolve();
const time = Date.parse(value);
if (isNaN(time)) {
return Promise.reject(t('过期时间格式错误!'));
}
if (time <= Date.now()) {
return Promise.reject(t('过期时间不能早于当前时间!'));
return Promise.reject(
t('过期时间不能早于当前时间!'),
);
}
return Promise.resolve();
},
@@ -444,7 +450,9 @@ const EditTokenModal = (props) => {
label={t('新建数量')}
min={1}
extraText={t('批量创建时会在名称后自动添加随机后缀')}
rules={[{ required: true, message: t('请输入新建数量') }]}
rules={[
{ required: true, message: t('请输入新建数量') },
]}
style={{ width: '100%' }}
/>
</Col>
@@ -460,7 +468,9 @@ const EditTokenModal = (props) => {
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('额度设置')}</Text>
<div className='text-xs text-gray-600'>{t('设置令牌可用额度和数量')}</div>
<div className='text-xs text-gray-600'>
{t('设置令牌可用额度和数量')}
</div>
</div>
</div>
<Row gutter={12}>
@@ -472,7 +482,11 @@ const EditTokenModal = (props) => {
type='number'
disabled={values.unlimited_quota}
extraText={renderQuotaWithPrompt(values.remain_quota)}
rules={values.unlimited_quota ? [] : [{ required: true, message: t('请输入额度') }]}
rules={
values.unlimited_quota
? []
: [{ required: true, message: t('请输入额度') }]
}
data={[
{ value: 500000, label: '1$' },
{ value: 5000000, label: '10$' },
@@ -488,7 +502,9 @@ const EditTokenModal = (props) => {
field='unlimited_quota'
label={t('无限额度')}
size='large'
extraText={t('令牌的额度仅用于限制令牌本身的最大额度使用量,实际的使用受到账户的剩余额度限制')}
extraText={t(
'令牌的额度仅用于限制令牌本身的最大额度使用量,实际的使用受到账户的剩余额度限制',
)}
/>
</Col>
</Row>
@@ -497,12 +513,18 @@ const EditTokenModal = (props) => {
{/* 访问限制 */}
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='purple' className='mr-2 shadow-md'>
<Avatar
size='small'
color='purple'
className='mr-2 shadow-md'
>
<IconLink size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('访问限制')}</Text>
<div className='text-xs text-gray-600'>{t('设置令牌的访问限制')}</div>
<div className='text-xs text-gray-600'>
{t('设置令牌的访问限制')}
</div>
</div>
</div>
<Row gutter={12}>
@@ -510,7 +532,9 @@ const EditTokenModal = (props) => {
<Form.Select
field='model_limits'
label={t('模型限制列表')}
placeholder={t('请选择该令牌支持的模型,留空支持所有模型')}
placeholder={t(
'请选择该令牌支持的模型,留空支持所有模型',
)}
multiple
optionList={models}
extraText={t('非必要,不建议启用模型限制')}
@@ -543,4 +567,4 @@ const EditTokenModal = (props) => {
);
};
export default EditTokenModal;
export default EditTokenModal;

View File

@@ -43,7 +43,7 @@ const LogsActions = ({
);
return (
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full">
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<Skeleton loading={needSkeleton} active placeholder={placeholder}>
<Space>
<Tag
@@ -92,4 +92,4 @@ const LogsActions = ({
);
};
export default LogsActions;
export default LogsActions;

View File

@@ -24,7 +24,7 @@ import {
Tag,
Tooltip,
Popover,
Typography
Typography,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
@@ -38,7 +38,7 @@ import {
renderModelPriceSimple,
renderAudioModelPrice,
renderClaudeModelPrice,
renderModelPrice
renderModelPrice,
} from '../../../helpers';
import { IconHelpCircle } from '@douyinfe/semi-icons';
import { Route } from 'lucide-react';
@@ -181,7 +181,7 @@ function renderModelName(record, copyText, t) {
if (!modelMapped) {
return renderModelTag(record.model_name, {
onClick: (event) => {
copyText(event, record.model_name).then((r) => { });
copyText(event, record.model_name).then((r) => {});
},
});
} else {
@@ -198,7 +198,7 @@ function renderModelName(record, copyText, t) {
</Typography.Text>
{renderModelTag(record.model_name, {
onClick: (event) => {
copyText(event, record.model_name).then((r) => { });
copyText(event, record.model_name).then((r) => {});
},
})}
</div>
@@ -209,7 +209,7 @@ function renderModelName(record, copyText, t) {
{renderModelTag(other.upstream_model_name, {
onClick: (event) => {
copyText(event, other.upstream_model_name).then(
(r) => { },
(r) => {},
);
},
})}
@@ -220,7 +220,7 @@ function renderModelName(record, copyText, t) {
>
{renderModelTag(record.model_name, {
onClick: (event) => {
copyText(event, record.model_name).then((r) => { });
copyText(event, record.model_name).then((r) => {});
},
suffixIcon: (
<Route
@@ -264,7 +264,8 @@ export const getLogsColumns = ({
}
}
return isAdminUser && (record.type === 0 || record.type === 2 || record.type === 5) ? (
return isAdminUser &&
(record.type === 0 || record.type === 2 || record.type === 5) ? (
<Space>
<Tooltip content={record.channel_name || t('未知渠道')}>
<span>
@@ -456,10 +457,14 @@ export const getLogsColumns = ({
{
key: COLUMN_KEYS.IP,
title: (
<div className="flex items-center gap-1">
<div className='flex items-center gap-1'>
{t('IP')}
<Tooltip content={t('只有当用户设置开启IP记录时才会进行请求和错误类型日志的IP记录')}>
<IconHelpCircle className="text-gray-400 cursor-help" />
<Tooltip
content={t(
'只有当用户设置开启IP记录时才会进行请求和错误类型日志的IP记录',
)}
>
<IconHelpCircle className='text-gray-400 cursor-help' />
</Tooltip>
</div>
),
@@ -538,33 +543,33 @@ export const getLogsColumns = ({
}
let content = other?.claude
? renderModelPriceSimple(
other.model_ratio,
other.model_price,
other.group_ratio,
other?.user_group_ratio,
other.cache_tokens || 0,
other.cache_ratio || 1.0,
other.cache_creation_tokens || 0,
other.cache_creation_ratio || 1.0,
false,
1.0,
other?.is_system_prompt_overwritten,
'claude'
)
other.model_ratio,
other.model_price,
other.group_ratio,
other?.user_group_ratio,
other.cache_tokens || 0,
other.cache_ratio || 1.0,
other.cache_creation_tokens || 0,
other.cache_creation_ratio || 1.0,
false,
1.0,
other?.is_system_prompt_overwritten,
'claude',
)
: renderModelPriceSimple(
other.model_ratio,
other.model_price,
other.group_ratio,
other?.user_group_ratio,
other.cache_tokens || 0,
other.cache_ratio || 1.0,
0,
1.0,
false,
1.0,
other?.is_system_prompt_overwritten,
'openai'
);
other.model_ratio,
other.model_price,
other.group_ratio,
other?.user_group_ratio,
other.cache_tokens || 0,
other.cache_ratio || 1.0,
0,
1.0,
false,
1.0,
other?.is_system_prompt_overwritten,
'openai',
);
return (
<Typography.Paragraph
ellipsis={{
@@ -578,4 +583,4 @@ export const getLogsColumns = ({
},
},
];
};
};

View File

@@ -54,7 +54,7 @@ const LogsFilters = ({
placeholder={[t('开始时间'), t('结束时间')]}
showClear
pure
size="small"
size='small'
/>
</div>
@@ -65,7 +65,7 @@ const LogsFilters = ({
placeholder={t('令牌名称')}
showClear
pure
size="small"
size='small'
/>
<Form.Input
@@ -74,7 +74,7 @@ const LogsFilters = ({
placeholder={t('模型名称')}
showClear
pure
size="small"
size='small'
/>
<Form.Input
@@ -83,7 +83,7 @@ const LogsFilters = ({
placeholder={t('分组')}
showClear
pure
size="small"
size='small'
/>
{isAdminUser && (
@@ -94,7 +94,7 @@ const LogsFilters = ({
placeholder={t('渠道 ID')}
showClear
pure
size="small"
size='small'
/>
<Form.Input
field='username'
@@ -102,7 +102,7 @@ const LogsFilters = ({
placeholder={t('用户名称')}
showClear
pure
size="small"
size='small'
/>
</>
)}
@@ -124,26 +124,14 @@ const LogsFilters = ({
refresh();
}, 0);
}}
size="small"
size='small'
>
<Form.Select.Option value='0'>
{t('全部')}
</Form.Select.Option>
<Form.Select.Option value='1'>
{t('充值')}
</Form.Select.Option>
<Form.Select.Option value='2'>
{t('消费')}
</Form.Select.Option>
<Form.Select.Option value='3'>
{t('管理')}
</Form.Select.Option>
<Form.Select.Option value='4'>
{t('系统')}
</Form.Select.Option>
<Form.Select.Option value='5'>
{t('错误')}
</Form.Select.Option>
<Form.Select.Option value='0'>{t('全部')}</Form.Select.Option>
<Form.Select.Option value='1'>{t('充值')}</Form.Select.Option>
<Form.Select.Option value='2'>{t('消费')}</Form.Select.Option>
<Form.Select.Option value='3'>{t('管理')}</Form.Select.Option>
<Form.Select.Option value='4'>{t('系统')}</Form.Select.Option>
<Form.Select.Option value='5'>{t('错误')}</Form.Select.Option>
</Form.Select>
</div>
@@ -152,7 +140,7 @@ const LogsFilters = ({
type='tertiary'
htmlType='submit'
loading={loading}
size="small"
size='small'
>
{t('查询')}
</Button>
@@ -167,14 +155,14 @@ const LogsFilters = ({
}, 100);
}
}}
size="small"
size='small'
>
{t('重置')}
</Button>
<Button
type='tertiary'
onClick={() => setShowColumnSelector(true)}
size="small"
size='small'
>
{t('列设置')}
</Button>
@@ -185,4 +173,4 @@ const LogsFilters = ({
);
};
export default LogsFilters;
export default LogsFilters;

View File

@@ -55,13 +55,7 @@ const LogsTable = (logsData) => {
showUserInfoFunc,
isAdminUser,
});
}, [
t,
COLUMN_KEYS,
copyText,
showUserInfoFunc,
isAdminUser,
]);
}, [t, COLUMN_KEYS, copyText, showUserInfoFunc, isAdminUser]);
// Filter columns based on visibility settings
const getVisibleColumns = () => {
@@ -99,9 +93,7 @@ const LogsTable = (logsData) => {
size='middle'
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
@@ -125,4 +117,4 @@ const LogsTable = (logsData) => {
);
};
export default LogsTable;
export default LogsTable;

View File

@@ -40,7 +40,7 @@ const LogsPage = () => {
{/* Main Content */}
<CardPro
type="type2"
type='type2'
statsArea={<LogsActions {...logsData} />}
searchArea={<LogsFilters {...logsData} />}
paginationArea={createCardProPagination({
@@ -60,4 +60,4 @@ const LogsPage = () => {
);
};
export default LogsPage;
export default LogsPage;

View File

@@ -49,10 +49,8 @@ const ColumnSelectorModal = ({
visible={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
footer={
<div className="flex justify-end">
<Button onClick={() => initDefaultColumns()}>
{t('重置')}
</Button>
<div className='flex justify-end'>
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('取消')}
</Button>
@@ -75,7 +73,7 @@ const ColumnSelectorModal = ({
</Checkbox>
</div>
<div
className="flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4"
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) => {
@@ -90,7 +88,7 @@ const ColumnSelectorModal = ({
}
return (
<div key={column.key} className="w-1/2 mb-4 pr-2">
<div key={column.key} className='w-1/2 mb-4 pr-2'>
<Checkbox
checked={!!visibleColumns[column.key]}
onChange={(e) =>
@@ -107,4 +105,4 @@ const ColumnSelectorModal = ({
);
};
export default ColumnSelectorModal;
export default ColumnSelectorModal;

View File

@@ -28,7 +28,7 @@ const UserInfoModal = ({
t,
}) => {
const infoItemStyle = {
marginBottom: '16px'
marginBottom: '16px',
};
const labelStyle = {
@@ -37,7 +37,7 @@ const UserInfoModal = ({
marginBottom: '2px',
fontSize: '12px',
color: 'var(--semi-color-text-2)',
gap: '6px'
gap: '6px',
};
const renderLabel = (text, type = 'tertiary') => (
@@ -50,19 +50,19 @@ const UserInfoModal = ({
const valueStyle = {
fontSize: '14px',
fontWeight: '600',
color: 'var(--semi-color-text-0)'
color: 'var(--semi-color-text-0)',
};
const rowStyle = {
display: 'flex',
justifyContent: 'space-between',
marginBottom: '16px',
gap: '20px'
gap: '20px',
};
const colStyle = {
flex: 1,
minWidth: 0
minWidth: 0,
};
return (
@@ -100,7 +100,9 @@ const UserInfoModal = ({
</div>
<div style={colStyle}>
{renderLabel(t('已用额度'), 'warning')}
<div style={valueStyle}>{renderQuota(userInfoData.used_quota)}</div>
<div style={valueStyle}>
{renderQuota(userInfoData.used_quota)}
</div>
</div>
</div>
@@ -108,7 +110,9 @@ const UserInfoModal = ({
<div style={rowStyle}>
<div style={colStyle}>
{renderLabel(t('请求次数'), 'warning')}
<div style={valueStyle}>{renderNumber(userInfoData.request_count)}</div>
<div style={valueStyle}>
{renderNumber(userInfoData.request_count)}
</div>
</div>
{userInfoData.group && (
<div style={colStyle}>
@@ -130,25 +134,38 @@ const UserInfoModal = ({
{userInfoData.aff_count !== undefined && (
<div style={colStyle}>
{renderLabel(t('邀请人数'), 'tertiary')}
<div style={valueStyle}>{renderNumber(userInfoData.aff_count)}</div>
<div style={valueStyle}>
{renderNumber(userInfoData.aff_count)}
</div>
</div>
)}
</div>
)}
{/* 邀请获得额度 */}
{userInfoData.aff_quota !== undefined && userInfoData.aff_quota > 0 && (
<div style={infoItemStyle}>
{renderLabel(t('邀请获得额度'), 'success')}
<div style={valueStyle}>{renderQuota(userInfoData.aff_quota)}</div>
</div>
)}
{userInfoData.aff_quota !== undefined &&
userInfoData.aff_quota > 0 && (
<div style={infoItemStyle}>
{renderLabel(t('邀请获得额度'), 'success')}
<div style={valueStyle}>
{renderQuota(userInfoData.aff_quota)}
</div>
</div>
)}
{/* 备注 */}
{userInfoData.remark && (
<div style={{ marginBottom: 0 }}>
{renderLabel(t('备注'), 'tertiary')}
<div style={{ ...valueStyle, wordBreak: 'break-all', lineHeight: '1.4' }}>{userInfoData.remark}</div>
<div
style={{
...valueStyle,
wordBreak: 'break-all',
lineHeight: '1.4',
}}
>
{userInfoData.remark}
</div>
</div>
)}
</div>
@@ -157,4 +174,4 @@ const UserInfoModal = ({
);
};
export default UserInfoModal;
export default UserInfoModal;

View File

@@ -20,27 +20,19 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react';
import { Button } from '@douyinfe/semi-ui';
const UsersActions = ({
setShowAddUser,
t
}) => {
const UsersActions = ({ setShowAddUser, t }) => {
// Add new user
const handleAddUser = () => {
setShowAddUser(true);
};
return (
<div className="flex gap-2 w-full md:w-auto order-2 md:order-1">
<Button
className="w-full md:w-auto"
onClick={handleAddUser}
size="small"
>
<div className='flex gap-2 w-full md:w-auto order-2 md:order-1'>
<Button className='w-full md:w-auto' onClick={handleAddUser} size='small'>
{t('添加用户')}
</Button>
</div>
);
};
export default UsersActions;
export default UsersActions;

View File

@@ -70,14 +70,18 @@ const renderUsername = (text, record) => {
return <span>{text}</span>;
}
const maxLen = 10;
const displayRemark = remark.length > maxLen ? remark.slice(0, maxLen) + '…' : remark;
const displayRemark =
remark.length > maxLen ? remark.slice(0, maxLen) + '…' : remark;
return (
<Space spacing={2}>
<span>{text}</span>
<Tooltip content={remark} position="top" showArrow>
<Tag color='white' shape='circle' className="!text-xs">
<div className="flex items-center gap-1">
<div className="w-2 h-2 flex-shrink-0 rounded-full" style={{ backgroundColor: '#10b981' }} />
<Tooltip content={remark} position='top' showArrow>
<Tag color='white' shape='circle' className='!text-xs'>
<div className='flex items-center gap-1'>
<div
className='w-2 h-2 flex-shrink-0 rounded-full'
style={{ backgroundColor: '#10b981' }}
/>
{displayRemark}
</div>
</Tag>
@@ -107,18 +111,16 @@ const renderStatistics = (text, record, showEnableDisableModal, t) => {
}
const content = (
<Tag
color={tagColor}
shape='circle'
size='small'
>
<Tag color={tagColor} shape='circle' size='small'>
{tagText}
</Tag>
);
const tooltipContent = (
<div className='text-xs'>
<div>{t('调用次数')}: {renderNumber(record.request_count)}</div>
<div>
{t('调用次数')}: {renderNumber(record.request_count)}
</div>
</div>
);
@@ -173,14 +175,16 @@ const renderInviteInfo = (text, record, t) => {
return (
<div>
<Space spacing={1}>
<Tag color='white' shape='circle' className="!text-xs">
<Tag color='white' shape='circle' className='!text-xs'>
{t('邀请')}: {renderNumber(record.aff_count)}
</Tag>
<Tag color='white' shape='circle' className="!text-xs">
<Tag color='white' shape='circle' className='!text-xs'>
{t('收益')}: {renderQuota(record.aff_history_quota)}
</Tag>
<Tag color='white' shape='circle' className="!text-xs">
{record.inviter_id === 0 ? t('无邀请人') : `${t('邀请人')}: ${record.inviter_id}`}
<Tag color='white' shape='circle' className='!text-xs'>
{record.inviter_id === 0
? t('无邀请人')
: `${t('邀请人')}: ${record.inviter_id}`}
</Tag>
</Space>
</div>
@@ -190,15 +194,19 @@ const renderInviteInfo = (text, record, t) => {
/**
* Render operations column
*/
const renderOperations = (text, record, {
setEditingUser,
setShowEditUser,
showPromoteModal,
showDemoteModal,
showEnableDisableModal,
showDeleteModal,
t
}) => {
const renderOperations = (
text,
record,
{
setEditingUser,
setShowEditUser,
showPromoteModal,
showDemoteModal,
showEnableDisableModal,
showDeleteModal,
t,
},
) => {
if (record.DeletedAt !== null) {
return <></>;
}
@@ -208,14 +216,14 @@ const renderOperations = (text, record, {
{record.status === 1 ? (
<Button
type='danger'
size="small"
size='small'
onClick={() => showEnableDisableModal(record, 'disable')}
>
{t('禁用')}
</Button>
) : (
<Button
size="small"
size='small'
onClick={() => showEnableDisableModal(record, 'enable')}
>
{t('启用')}
@@ -223,7 +231,7 @@ const renderOperations = (text, record, {
)}
<Button
type='tertiary'
size="small"
size='small'
onClick={() => {
setEditingUser(record);
setShowEditUser(true);
@@ -233,21 +241,21 @@ const renderOperations = (text, record, {
</Button>
<Button
type='warning'
size="small"
size='small'
onClick={() => showPromoteModal(record)}
>
{t('提升')}
</Button>
<Button
type='secondary'
size="small"
size='small'
onClick={() => showDemoteModal(record)}
>
{t('降级')}
</Button>
<Button
type='danger'
size="small"
size='small'
onClick={() => showDeleteModal(record)}
>
{t('注销')}
@@ -266,7 +274,7 @@ export const getUsersColumns = ({
showPromoteModal,
showDemoteModal,
showEnableDisableModal,
showDeleteModal
showDeleteModal,
}) => {
return [
{
@@ -281,7 +289,8 @@ export const getUsersColumns = ({
{
title: t('状态'),
dataIndex: 'info',
render: (text, record, index) => renderStatistics(text, record, showEnableDisableModal, t),
render: (text, record, index) =>
renderStatistics(text, record, showEnableDisableModal, t),
},
{
title: t('剩余额度/总额度'),
@@ -312,15 +321,16 @@ export const getUsersColumns = ({
dataIndex: 'operate',
fixed: 'right',
width: 200,
render: (text, record, index) => renderOperations(text, record, {
setEditingUser,
setShowEditUser,
showPromoteModal,
showDemoteModal,
showEnableDisableModal,
showDeleteModal,
t
}),
render: (text, record, index) =>
renderOperations(text, record, {
setEditingUser,
setShowEditUser,
showPromoteModal,
showDemoteModal,
showEnableDisableModal,
showDeleteModal,
t,
}),
},
];
};
};

View File

@@ -26,9 +26,9 @@ const { Text } = Typography;
const UsersDescription = ({ 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">
<IconUserAdd className="mr-2" />
<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'>
<IconUserAdd className='mr-2' />
<Text>{t('用户管理')}</Text>
</div>
<CompactModeToggle
@@ -40,4 +40,4 @@ const UsersDescription = ({ compactMode, setCompactMode, t }) => {
);
};
export default UsersDescription;
export default UsersDescription;

View File

@@ -31,9 +31,8 @@ const UsersFilters = ({
groupOptions,
loading,
searching,
t
t,
}) => {
const formApiRef = useRef(null);
const handleReset = () => {
@@ -55,26 +54,26 @@ const UsersFilters = ({
searchUsers(1, pageSize);
}}
allowEmpty={true}
autoComplete="off"
layout="horizontal"
trigger="change"
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className="w-full md:w-auto order-1 md:order-2"
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">
<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"
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('支持搜索用户的 ID、用户名、显示名称和邮箱地址')}
showClear
pure
size="small"
size='small'
/>
</div>
<div className="w-full md:w-48">
<div className='w-full md:w-48'>
<Form.Select
field="searchGroup"
field='searchGroup'
placeholder={t('选择分组')}
optionList={groupOptions}
onChange={(value) => {
@@ -83,27 +82,27 @@ const UsersFilters = ({
searchUsers(1, pageSize);
}, 100);
}}
className="w-full"
className='w-full'
showClear
pure
size="small"
size='small'
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<div className='flex gap-2 w-full md:w-auto'>
<Button
type="tertiary"
htmlType="submit"
type='tertiary'
htmlType='submit'
loading={loading || searching}
className="flex-1 md:flex-initial md:w-auto"
size="small"
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"
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
@@ -113,4 +112,4 @@ const UsersFilters = ({
);
};
export default UsersFilters;
export default UsersFilters;

View File

@@ -22,7 +22,7 @@ import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { getUsersColumns } from './UsersColumnDefs';
import PromoteUserModal from './modals/PromoteUserModal';
@@ -103,23 +103,21 @@ const UsersTable = (usersData) => {
showPromoteModal: showPromoteUserModal,
showDemoteModal: showDemoteUserModal,
showEnableDisableModal: showEnableDisableUserModal,
showDeleteModal: showDeleteUserModal
showDeleteModal: showDeleteUserModal,
});
}, [
t,
setEditingUser,
setShowEditUser,
]);
}, [t, setEditingUser, setShowEditUser]);
// 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;
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
@@ -143,13 +141,15 @@ const UsersTable = (usersData) => {
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className="overflow-hidden"
size="middle"
className='overflow-hidden'
size='middle'
/>
{/* Modal components */}
@@ -192,4 +192,4 @@ const UsersTable = (usersData) => {
);
};
export default UsersTable;
export default UsersTable;

View File

@@ -78,7 +78,7 @@ const UsersPage = () => {
/>
<CardPro
type="type1"
type='type1'
descriptionArea={
<UsersDescription
compactMode={compactMode}
@@ -87,11 +87,8 @@ const UsersPage = () => {
/>
}
actionsArea={
<div className="flex flex-col md:flex-row justify-between items-center gap-2 w-full">
<UsersActions
setShowAddUser={setShowAddUser}
t={t}
/>
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<UsersActions setShowAddUser={setShowAddUser} t={t} />
<UsersFilters
formInitValues={formInitValues}
@@ -124,4 +121,4 @@ const UsersPage = () => {
);
};
export default UsersPage;
export default UsersPage;

View File

@@ -33,11 +33,7 @@ import {
Row,
Col,
} from '@douyinfe/semi-ui';
import {
IconSave,
IconClose,
IconUserAdd,
} from '@douyinfe/semi-icons';
import { IconSave, IconClose, IconUserAdd } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
const { Text, Title } = Typography;
@@ -80,8 +76,10 @@ const AddUserModal = (props) => {
placement={'left'}
title={
<Space>
<Tag color="green" shape="circle">{t('新建')}</Tag>
<Title heading={4} className="m-0">
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
<Title heading={4} className='m-0'>
{t('添加用户')}
</Title>
</Space>
@@ -90,10 +88,10 @@ const AddUserModal = (props) => {
visible={props.visible}
width={isMobile ? '100%' : 600}
footer={
<div className="flex justify-end bg-white">
<div className='flex justify-end bg-white'>
<Space>
<Button
theme="solid"
theme='solid'
onClick={() => formApiRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
@@ -101,8 +99,8 @@ const AddUserModal = (props) => {
{t('提交')}
</Button>
<Button
theme="light"
type="primary"
theme='light'
type='primary'
onClick={handleCancel}
icon={<IconClose />}
>
@@ -117,7 +115,7 @@ const AddUserModal = (props) => {
<Spin spinning={loading}>
<Form
initValues={getInitValues()}
getFormApi={(api) => formApiRef.current = api}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
onSubmitFail={(errs) => {
const first = Object.values(errs)[0];
@@ -125,15 +123,17 @@ const AddUserModal = (props) => {
formApiRef.current?.scrollToError();
}}
>
<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">
<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'>
<IconUserAdd size={16} />
</Avatar>
<div>
<Text className="text-lg font-medium">{t('用户信息')}</Text>
<div className="text-xs text-gray-600">{t('创建新用户账户')}</div>
<Text className='text-lg font-medium'>{t('用户信息')}</Text>
<div className='text-xs text-gray-600'>
{t('创建新用户账户')}
</div>
</div>
</div>
@@ -183,4 +183,4 @@ const AddUserModal = (props) => {
);
};
export default AddUserModal;
export default AddUserModal;

View File

@@ -29,7 +29,7 @@ const DeleteUserModal = ({
activePage,
refresh,
manageUser,
t
t,
}) => {
const handleConfirm = async () => {
await manageUser(user.id, 'delete', user);
@@ -48,11 +48,11 @@ const DeleteUserModal = ({
visible={visible}
onCancel={onCancel}
onOk={handleConfirm}
type="danger"
type='danger'
>
{t('相当于删除用户,此修改将不可逆')}
</Modal>
);
};
export default DeleteUserModal;
export default DeleteUserModal;

View File

@@ -27,11 +27,11 @@ const DemoteUserModal = ({ visible, onCancel, onConfirm, user, t }) => {
visible={visible}
onCancel={onCancel}
onOk={onConfirm}
type="warning"
type='warning'
>
{t('此操作将降低用户的权限级别')}
</Modal>
);
};
export default DemoteUserModal;
export default DemoteUserModal;

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