Files
monkey-ai-web/src/components/table/channels/ChannelsColumnDefs.jsx
T

872 lines
24 KiB
React

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { writeClipboardText } from '../../../helpers/clipboard';
import React, { useState } from 'react';
import { Switch } from 'antd';
import {
Button,
InputNumber,
Modal,
Progress,
Space,
Tag,
Tooltip,
} from '@/components/ui';
import {
API,
timestamp2string,
renderGroup,
renderQuota,
getChannelIcon,
renderQuotaWithAmount,
showSuccess,
showError,
isRoot,
hoverOrClickTrigger,
} from '../../../helpers';
import { CHANNEL_OPTIONS } from '../../../constants';
import { IconTreeTriangleDown } from '@/components/ui/icons';
import { ShuffleBrandIcon } from '../../common/icons/BrandIcons';
function ChannelStatusSwitch({ record, manageChannel, t }) {
const [loading, setLoading] = useState(false);
return (
<Switch
size='small'
checked={record.status === 1}
checkedChildren={t('启用')}
unCheckedChildren={t('禁用')}
disabled={!isRoot()}
loading={loading}
aria-label={t('状态')}
onClick={(_, event) => event.stopPropagation()}
onChange={async (checked) => {
setLoading(true);
try {
await manageChannel(
record.id,
checked ? 'enable' : 'disable',
record,
);
} catch (error) {
showError(error.message);
} finally {
setLoading(false);
}
}}
/>
);
}
// 删除单个渠道的确认文案:若该渠道被其他渠道列为兜底,追加影响说明。
// 查询失败不阻塞删除,仅回退为原确认文案
const buildDeleteConfirmContent = async (channelId, t) => {
const baseText = t('此修改将不可逆');
let referrers = [];
try {
const res = await API.get(`/api/channel/${channelId}/fallback_referrers`, {
skipErrorHandler: true,
});
if (res?.data?.success && Array.isArray(res.data.data)) {
referrers = res.data.data;
}
} catch (err) {
console.error('加载兜底反向引用失败:', err);
}
if (referrers.length === 0) return baseText;
return (
<div>
<div>{baseText}</div>
<div style={{ marginTop: 8 }}>
{t(
'该渠道被以下 {{count}} 个渠道列为兜底,删除后会从它们的兜底链中移除(兜底链变空时失败次数配置一并清空):',
{ count: referrers.length },
)}
</div>
<div style={{ marginTop: 4 }}>
{referrers.slice(0, 5).map((r) => (
<Tag key={r.id} color='orange' style={{ marginRight: 4 }}>
#{r.id} {r.name}
</Tag>
))}
{referrers.length > 5
? t('等 {{n}} 个', { n: referrers.length })
: null}
</div>
</div>
);
};
// Render functions
const renderType = (type, channelInfo = undefined, t) => {
let type2label = new Map();
for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
}
type2label[0] = { value: 0, label: t('未知类型'), color: 'grey' };
let icon = getChannelIcon(type);
if (channelInfo?.is_multi_key) {
icon =
channelInfo?.multi_key_mode === 'random' ? (
<div className='flex items-center gap-1'>
<ShuffleBrandIcon size={14} color='rgb(59 130 246)' />
{icon}
</div>
) : (
<div className='flex items-center gap-1'>
<IconTreeTriangleDown className='text-blue-500' />
{icon}
</div>
);
}
return (
<Tag color={type2label[type]?.color} shape='circle' prefixIcon={icon}>
{type2label[type]?.label}
</Tag>
);
};
const renderTagType = (t) => {
return (
<Tag color='light-blue' shape='circle' type='light'>
{t('标签聚合')}
</Tag>
);
};
const renderStatus = (status, channelInfo = undefined, t) => {
if (channelInfo) {
if (channelInfo.is_multi_key) {
let keySize = channelInfo.multi_key_size;
let enabledKeySize = keySize;
if (channelInfo.multi_key_status_list) {
enabledKeySize =
keySize - Object.keys(channelInfo.multi_key_status_list).length;
}
return renderMultiKeyStatus(status, keySize, enabledKeySize, t);
}
}
switch (status) {
case 1:
return (
<Tag color='green' shape='circle'>
{t('已启用')}
</Tag>
);
case 2:
return (
<Tag color='red' shape='circle'>
{t('已禁用')}
</Tag>
);
case 3:
return (
<Tag color='yellow' shape='circle'>
{t('自动禁用')}
</Tag>
);
default:
return (
<Tag color='grey' shape='circle'>
{t('未知状态')}
</Tag>
);
}
};
const renderMultiKeyStatus = (status, keySize, enabledKeySize, t) => {
switch (status) {
case 1:
return (
<Tag color='green' shape='circle'>
{t('已启用')} {enabledKeySize}/{keySize}
</Tag>
);
case 2:
return (
<Tag color='red' shape='circle'>
{t('已禁用')} {enabledKeySize}/{keySize}
</Tag>
);
case 3:
return (
<Tag color='yellow' shape='circle'>
{t('自动禁用')} {enabledKeySize}/{keySize}
</Tag>
);
default:
return (
<Tag color='grey' shape='circle'>
{t('未知状态')} {enabledKeySize}/{keySize}
</Tag>
);
}
};
const renderResponseTime = (responseTime, t) => {
let time = responseTime / 1000;
time = t('{{value}} 秒', { value: time.toFixed(2) });
if (responseTime === 0) {
return (
<Tag color='grey' shape='circle'>
{t('未测试')}
</Tag>
);
} else if (responseTime <= 1000) {
return (
<Tag color='green' shape='circle'>
{time}
</Tag>
);
} else if (responseTime <= 3000) {
return (
<Tag color='lime' shape='circle'>
{time}
</Tag>
);
} else if (responseTime <= 5000) {
return (
<Tag color='yellow' shape='circle'>
{time}
</Tag>
);
} else {
return (
<Tag color='red' shape='circle'>
{time}
</Tag>
);
}
};
// 格式化额度数量显示
const formatQuotaCount = (count) => {
if (count >= 1000000000) {
return (count / 1000000000).toFixed(1) + 'B';
}
if (count >= 1000000) {
return (count / 1000000).toFixed(1) + 'M';
}
if (count >= 1000) {
return (count / 1000).toFixed(1) + 'K';
}
return count.toString();
};
const renderDailyQuota = (record, dailyQuotaInfo, t) => {
const limit = record.daily_quota_limit || 0;
// 如果没有设置限额,显示"不限"
if (limit === 0) {
return (
<Tag color='grey' shape='circle'>
{t('不限')}
</Tag>
);
}
// 如果有日消耗信息
if (dailyQuotaInfo && dailyQuotaInfo[record.id]) {
const info = dailyQuotaInfo[record.id];
const percent = info.usage_percent || 0;
const isExceeded = info.limit_exceeded;
let strokeColor = 'var(--ui-color-success)';
if (percent >= 100) {
strokeColor = 'var(--ui-color-danger)';
} else if (percent >= 80) {
strokeColor = 'var(--ui-color-warning)';
} else if (percent >= 50) {
strokeColor = 'var(--ui-color-primary)';
}
return (
<Tooltip
content={
<div>
<div>
{t('日限额')}: {formatQuotaCount(limit)}
</div>
<div>
{t('已使用')}: {formatQuotaCount(info.daily_quota)}
</div>
<div>
{t('使用率')}: {percent}%
</div>
{isExceeded && (
<div style={{ color: 'var(--ui-color-danger)' }}>
{t('已达限额,今日不再调度')}
</div>
)}
</div>
}
>
<div style={{ width: 80 }}>
<Progress
percent={percent}
strokeColor={strokeColor}
size='small'
showInfo
format={(percent) => `${percent}%`}
/>
</div>
</Tooltip>
);
}
// 没有消耗数据时显示限额
return (
<Tooltip
content={t('日限额: {{value}}', { value: formatQuotaCount(limit) })}
>
<Tag color='blue' shape='circle'>
{formatQuotaCount(limit)}
</Tag>
</Tooltip>
);
};
export const getChannelsColumns = ({
t,
COLUMN_KEYS,
updateChannelBalance,
manageChannel,
manageTag,
submitTagEdit,
testChannel,
setCurrentTestChannel,
setShowModelTestModal,
setEditingChannel,
setShowEdit,
setShowEditTag,
setEditingTag,
copySelectedChannel,
refresh,
activePage,
channels,
setShowMultiKeyManageModal,
setCurrentMultiKeyChannel,
isChannelExcluded,
dailyQuotaInfo,
}) => {
return [
{
key: COLUMN_KEYS.ID,
title: t('ID'),
dataIndex: 'id',
},
{
key: COLUMN_KEYS.NAME,
title: t('名称'),
dataIndex: 'name',
render: (text, record, index) => {
if (record.remark && record.remark.trim() !== '') {
return (
<Tooltip
content={
<div className='flex flex-col gap-2 max-w-xs'>
<div className='text-sm'>{record.remark}</div>
<Button
size='small'
type='primary'
theme='outline'
onClick={async (e) => {
e.stopPropagation();
writeClipboardText(record.remark)
.then(() => {
showSuccess(t('复制成功'));
})
.catch(() => {
showError(t('复制失败'));
});
}}
>
{t('复制')}
</Button>
</div>
}
trigger={hoverOrClickTrigger()}
position='topLeft'
>
<span>{text}</span>
</Tooltip>
);
}
return text;
},
},
{
key: COLUMN_KEYS.GROUP,
title: t('分组'),
dataIndex: 'group',
render: (text, record, index) => (
<div>
<Space spacing={2}>
{text
?.split(',')
.sort((a, b) => {
if (a === 'default') return -1;
if (b === 'default') return 1;
return a.localeCompare(b);
})
.map((item, index) => renderGroup(item))}
</Space>
</div>
),
},
{
key: COLUMN_KEYS.TYPE,
title: t('类型'),
dataIndex: 'type',
render: (text, record, index) => {
if (record.children === undefined) {
if (record.channel_info) {
if (record.channel_info.is_multi_key) {
return <>{renderType(text, record.channel_info, t)}</>;
}
}
return <>{renderType(text, undefined, t)}</>;
} else {
return <>{renderTagType(t)}</>;
}
},
},
{
key: COLUMN_KEYS.STATUS,
title: t('状态'),
dataIndex: 'status',
render: (text, record, index) => {
const statusControl =
record.children !== undefined ? (
renderStatus(text, record.channel_info, t)
) : (
<Space>
<ChannelStatusSwitch
record={record}
manageChannel={manageChannel}
t={t}
/>
{record.channel_info?.is_multi_key && (
<span>
{(record.channel_info.multi_key_size || 0) -
Object.keys(record.channel_info.multi_key_status_list || {})
.length}
/{record.channel_info.multi_key_size || 0}
</span>
)}
</Space>
);
if (text === 3) {
let otherInfo;
try {
otherInfo =
typeof record.other_info === 'string'
? JSON.parse(record.other_info)
: record.other_info;
} catch {
return statusControl;
}
if (
!otherInfo ||
typeof otherInfo !== 'object' ||
Array.isArray(otherInfo) ||
(!otherInfo.status_reason && !otherInfo.status_time)
) {
return statusControl;
}
const reason = otherInfo.status_reason || '';
const time = otherInfo.status_time;
return (
<div>
<Tooltip
content={t('原因:{{reason}},时间:{{time}}', {
reason,
time: timestamp2string(time),
})}
>
{statusControl}
</Tooltip>
</div>
);
} else {
return statusControl;
}
},
},
{
key: COLUMN_KEYS.AUTOBAN_EXCLUSION,
title: t('自动封禁'),
dataIndex: 'autoban_exclusion',
render: (text, record, index) => {
if (record.children !== undefined) {
// 标签模式下不显示
return null;
}
const excluded = isChannelExcluded
? isChannelExcluded(record.id)
: false;
return (
<Tag color={excluded ? 'orange' : 'green'} shape='circle'>
{excluded ? t('已排除') : t('参与')}
</Tag>
);
},
},
{
key: COLUMN_KEYS.RESPONSE_TIME,
title: t('响应时间'),
dataIndex: 'response_time',
render: (text, record, index) => <div>{renderResponseTime(text, t)}</div>,
},
{
key: COLUMN_KEYS.BALANCE,
title: t('已用/剩余'),
dataIndex: 'expired_time',
render: (text, record, index) => {
if (record.children === undefined) {
return (
<div>
<Space spacing={1}>
<Tooltip content={t('已用额度')}>
<Tag color='white' type='ghost' shape='circle'>
{renderQuota(record.used_quota)}
</Tag>
</Tooltip>
<Tooltip
content={
isRoot()
? t('剩余额度${{balance}},点击更新', {
balance: record.balance,
})
: t('剩余额度${{balance}}', { balance: record.balance })
}
>
<Tag
color='white'
type='ghost'
shape='circle'
onClick={
isRoot() ? () => updateChannelBalance(record) : undefined
}
>
{renderQuotaWithAmount(record.balance)}
</Tag>
</Tooltip>
</Space>
</div>
);
} else {
return (
<Tooltip content={t('已用额度')}>
<Tag color='white' type='ghost' shape='circle'>
{renderQuota(record.used_quota)}
</Tag>
</Tooltip>
);
}
},
},
{
key: COLUMN_KEYS.PRIORITY,
title: t('优先级'),
dataIndex: 'priority',
render: (text, record, index) => {
if (record.children === undefined) {
return (
<div>
{isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='priority'
onBlur={(e) => {
manageChannel(
record.id,
'priority',
record,
e.target.value,
);
}}
keepFocus={true}
innerButtons
defaultValue={record.priority}
min={-999}
size='small'
/>
) : (
<span>{record.priority}</span>
)}
</div>
);
} else {
return isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='priority'
keepFocus={true}
onBlur={(e) => {
Modal.warning({
title: t('修改子渠道优先级'),
content: t('确定要修改所有子渠道优先级为 {{value}} 吗?', {
value: e.target.value,
}),
onOk: () => {
if (e.target.value === '') {
return;
}
submitTagEdit('priority', {
tag: record.key,
priority: e.target.value,
});
},
});
}}
innerButtons
defaultValue={record.priority}
min={-999}
size='small'
/>
) : (
<span>{record.priority}</span>
);
}
},
},
{
key: COLUMN_KEYS.WEIGHT,
title: t('权重'),
dataIndex: 'weight',
render: (text, record, index) => {
if (record.children === undefined) {
return (
<div>
{isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='weight'
onBlur={(e) => {
manageChannel(record.id, 'weight', record, e.target.value);
}}
keepFocus={true}
innerButtons
defaultValue={record.weight}
min={0}
size='small'
/>
) : (
<span>{record.weight}</span>
)}
</div>
);
} else {
return isRoot() ? (
<InputNumber
style={{ width: 70 }}
name='weight'
keepFocus={true}
onBlur={(e) => {
Modal.warning({
title: t('修改子渠道权重'),
content: t('确定要修改所有子渠道权重为 {{value}} 吗?', {
value: e.target.value,
}),
onOk: () => {
if (e.target.value === '') {
return;
}
submitTagEdit('weight', {
tag: record.key,
weight: e.target.value,
});
},
});
}}
innerButtons
defaultValue={record.weight}
min={-999}
size='small'
/>
) : (
<span>{record.weight}</span>
);
}
},
},
{
key: COLUMN_KEYS.DAILY_QUOTA,
title: t('日限额'),
dataIndex: 'daily_quota_limit',
render: (text, record, index) => {
if (record.children !== undefined) {
// 标签聚合模式不显示
return null;
}
return renderDailyQuota(record, dailyQuotaInfo, t);
},
},
{
key: COLUMN_KEYS.OPERATE,
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) => {
if (record.children === undefined) {
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: async () => {
const content = await buildDeleteConfirmContent(record.id, t);
Modal.confirm({
title: t('确定是否要删除此渠道?'),
content,
onOk: () => {
(async () => {
await manageChannel(record.id, 'delete', record);
await refresh();
setTimeout(() => {
if (channels.length === 0 && activePage > 1) {
refresh(activePage - 1);
}
}, 100);
})();
},
});
},
},
{
node: 'item',
name: t('复制'),
type: 'tertiary',
onClick: () => {
Modal.confirm({
title: t('确定是否要复制此渠道?'),
content: t('复制渠道的所有信息'),
onOk: () => copySelectedChannel(record),
});
},
},
];
return (
<Space wrap className='console-module-row-actions'>
{isRoot() && (
<>
<Button
type='link'
size='small'
onClick={() => testChannel(record, '')}
>
{t('测试')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setCurrentTestChannel(record);
setShowModelTestModal(true);
}}
>
{t('批量测试')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='link'
danger
size='small'
onClick={moreMenuItems[0].onClick}
>
{t('删除')}
</Button>
<Button
type='link'
size='small'
onClick={moreMenuItems[1].onClick}
>
{t('复制')}
</Button>
{record.channel_info?.is_multi_key && (
<Button
type='link'
size='small'
onClick={() => {
setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true);
}}
>
{t('多密钥管理')}
</Button>
)}
</>
)}
</Space>
);
} else {
// 标签操作按钮
return (
<Space wrap>
{isRoot() && (
<>
<Button
type='link'
size='small'
onClick={() => manageTag(record.key, 'enable')}
>
{t('启用全部')}
</Button>
<Button
type='link'
size='small'
onClick={() => manageTag(record.key, 'disable')}
>
{t('禁用全部')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setShowEditTag(true);
setEditingTag(record.key);
}}
>
{t('编辑')}
</Button>
</>
)}
</Space>
);
}
},
},
];
};