/* 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 . 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 ( 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 (
{baseText}
{t( '该渠道被以下 {{count}} 个渠道列为兜底,删除后会从它们的兜底链中移除(兜底链变空时失败次数配置一并清空):', { count: referrers.length }, )}
{referrers.slice(0, 5).map((r) => ( #{r.id} {r.name} ))} {referrers.length > 5 ? t('等 {{n}} 个', { n: referrers.length }) : null}
); }; // 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' ? (
{icon}
) : (
{icon}
); } return ( {type2label[type]?.label} ); }; const renderTagType = (t) => { return ( {t('标签聚合')} ); }; 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 ( {t('已启用')} ); case 2: return ( {t('已禁用')} ); case 3: return ( {t('自动禁用')} ); default: return ( {t('未知状态')} ); } }; const renderMultiKeyStatus = (status, keySize, enabledKeySize, t) => { switch (status) { case 1: return ( {t('已启用')} {enabledKeySize}/{keySize} ); case 2: return ( {t('已禁用')} {enabledKeySize}/{keySize} ); case 3: return ( {t('自动禁用')} {enabledKeySize}/{keySize} ); default: return ( {t('未知状态')} {enabledKeySize}/{keySize} ); } }; const renderResponseTime = (responseTime, t) => { let time = responseTime / 1000; time = t('{{value}} 秒', { value: time.toFixed(2) }); if (responseTime === 0) { return ( {t('未测试')} ); } else if (responseTime <= 1000) { return ( {time} ); } else if (responseTime <= 3000) { return ( {time} ); } else if (responseTime <= 5000) { return ( {time} ); } else { return ( {time} ); } }; // 格式化额度数量显示 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 ( {t('不限')} ); } // 如果有日消耗信息 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 (
{t('日限额')}: {formatQuotaCount(limit)}
{t('已使用')}: {formatQuotaCount(info.daily_quota)}
{t('使用率')}: {percent}%
{isExceeded && (
{t('已达限额,今日不再调度')}
)} } >
`${percent}%`} />
); } // 没有消耗数据时显示限额 return ( {formatQuotaCount(limit)} ); }; 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 (
{record.remark}
} trigger={hoverOrClickTrigger()} position='topLeft' > {text}
); } return text; }, }, { key: COLUMN_KEYS.GROUP, title: t('分组'), dataIndex: 'group', render: (text, record, index) => (
{text ?.split(',') .sort((a, b) => { if (a === 'default') return -1; if (b === 'default') return 1; return a.localeCompare(b); }) .map((item, index) => renderGroup(item))}
), }, { 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) ) : ( {record.channel_info?.is_multi_key && ( {(record.channel_info.multi_key_size || 0) - Object.keys(record.channel_info.multi_key_status_list || {}) .length} /{record.channel_info.multi_key_size || 0} )} ); 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 (
{statusControl}
); } 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 ( {excluded ? t('已排除') : t('参与')} ); }, }, { key: COLUMN_KEYS.RESPONSE_TIME, title: t('响应时间'), dataIndex: 'response_time', render: (text, record, index) =>
{renderResponseTime(text, t)}
, }, { key: COLUMN_KEYS.BALANCE, title: t('已用/剩余'), dataIndex: 'expired_time', render: (text, record, index) => { if (record.children === undefined) { return (
{renderQuota(record.used_quota)} updateChannelBalance(record) : undefined } > {renderQuotaWithAmount(record.balance)}
); } else { return ( {renderQuota(record.used_quota)} ); } }, }, { key: COLUMN_KEYS.PRIORITY, title: t('优先级'), dataIndex: 'priority', render: (text, record, index) => { if (record.children === undefined) { return (
{isRoot() ? ( { manageChannel( record.id, 'priority', record, e.target.value, ); }} keepFocus={true} innerButtons defaultValue={record.priority} min={-999} size='small' /> ) : ( {record.priority} )}
); } else { return isRoot() ? ( { 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' /> ) : ( {record.priority} ); } }, }, { key: COLUMN_KEYS.WEIGHT, title: t('权重'), dataIndex: 'weight', render: (text, record, index) => { if (record.children === undefined) { return (
{isRoot() ? ( { manageChannel(record.id, 'weight', record, e.target.value); }} keepFocus={true} innerButtons defaultValue={record.weight} min={0} size='small' /> ) : ( {record.weight} )}
); } else { return isRoot() ? ( { 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' /> ) : ( {record.weight} ); } }, }, { 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 ( {isRoot() && ( <> {record.channel_info?.is_multi_key && ( )} )} ); } else { // 标签操作按钮 return ( {isRoot() && ( <> )} ); } }, }, ]; };