feat: 自行开发设计 ui样式优化 超管端-控制台 相关的页面

This commit is contained in:
zhanjunhao
2026-11-09 21:45:37 +08:00
parent 54b3e0cc21
commit 5c0849e82b
242 changed files with 9242 additions and 5043 deletions
@@ -21,14 +21,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
/**
* 管理员(超管)视角的全平台 Token 管理数据 hook
*/
export const useAdminTokensData = () => {
const { t } = useTranslation();
const [compactMode, setCompactMode] = useTableCompactMode('admin-tokens');
// 数据状态
const [tokens, setTokens] = useState([]);
@@ -129,8 +127,10 @@ export const useAdminTokensData = () => {
};
// 核心:唯一的列表加载函数(loadTokens 兼容 searchTokens 的所有调用方式)
const listRequestIdRef = useRef(0);
const loadTokens = useCallback(
async (page = 1, size = pageSizeRef.current, filters = null) => {
const requestId = ++listRequestIdRef.current;
const useFilters = filters || getFormValues();
const filtered = hasAnyFilter(useFilters);
@@ -143,6 +143,7 @@ export const useAdminTokensData = () => {
try {
const qs = buildQuery(page, size, useFilters);
const res = await API.get(`/api/token/admin?${qs}`);
if (requestId !== listRequestIdRef.current) return;
const { success, message, data } = res.data;
if (success) {
// 边界:删除最后一页的所有记录后,page 已超出有效范围
@@ -161,11 +162,14 @@ export const useAdminTokensData = () => {
showError(message);
}
} catch (e) {
if (requestId !== listRequestIdRef.current) return;
console.error('[AdminTokens] loadTokens failed:', e);
showError(e.message || t('加载失败'));
} finally {
setLoading(false);
setSearching(false);
if (requestId === listRequestIdRef.current) {
setLoading(false);
setSearching(false);
}
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -333,10 +337,6 @@ export const useAdminTokensData = () => {
handlePageSizeChange,
handleRow,
// UI
compactMode,
setCompactMode,
// 翻译
t,
};
+9 -3
View File
@@ -51,6 +51,7 @@ export const useRiskControlData = (active = true) => {
const [banLogLoading, setBanLogLoading] = useState(false);
const [banLogStatus, setBanLogStatus] = useState(0); // 0=全部 1=已封号 2=已解封
const [banLogPage, setBanLogPage] = useState(1);
const [banLogPageSize, setBanLogPageSize] = useState(20);
const fetchSuspects = useCallback(
async (override) => {
@@ -144,7 +145,9 @@ export const useRiskControlData = (active = true) => {
const params = new URLSearchParams();
if (status > 0) params.append('status', status);
params.append('page', page);
params.append('page_size', 20);
const size = override?.pageSize || banLogPageSize;
params.append('page_size', size);
setBanLogPageSize(size);
setBanLogLoading(true);
try {
const res = await API.get(
@@ -155,14 +158,16 @@ export const useRiskControlData = (active = true) => {
setBanLogs(d.items || []);
setBanLogTotal(d.total || 0);
if (override?.page) setBanLogPage(override.page);
} else {
showError(res.data.message);
}
} catch (e) {
console.error('查询封号日志失败', e);
showError(e.message);
} finally {
setBanLogLoading(false);
}
},
[banLogStatus, banLogPage],
[banLogStatus, banLogPage, banLogPageSize],
);
const unbanUser = useCallback(
@@ -221,6 +226,7 @@ export const useRiskControlData = (active = true) => {
banLogStatus,
setBanLogStatus,
banLogPage,
banLogPageSize,
fetchBanLogs,
};
};
+48 -24
View File
@@ -26,9 +26,7 @@ import {
showSuccess,
loadChannelModels,
} from '../../helpers';
import {
ITEMS_PER_PAGE,
} from '../../constants';
import { ITEMS_PER_PAGE } from '../../constants';
import { useIsMobile } from '../common/useIsMobile';
import { useTableCompactMode } from '../common/useTableCompactMode';
@@ -100,6 +98,9 @@ export const useChannelsData = () => {
// Refs
const requestCounter = useRef(0);
const pendingBalanceUpdatesRef = useRef(new Set());
const lastBalanceUpdateAtRef = useRef(new Map());
const pendingChannelTestsRef = useRef(new Set());
const allSelectingRef = useRef(false);
const [formApi, setFormApi] = useState(null);
@@ -796,18 +797,32 @@ export const useChannelsData = () => {
};
const updateChannelBalance = async (record) => {
const res = await API.get(`/api/channel/update_balance/${record.id}/`);
const { success, message, balance } = res.data;
if (success) {
updateChannelProperty(record.id, (channel) => {
channel.balance = balance;
channel.balance_updated_time = Date.now() / 1000;
});
showInfo(
t('通道 ${name} 余额更新成功!').replace('${name}', record.name),
);
} else {
showError(message);
const requestKey = String(record.id);
if (pendingBalanceUpdatesRef.current.has(requestKey)) return;
const now = Date.now();
const lastUpdateAt = lastBalanceUpdateAtRef.current.get(requestKey);
// Keep fast responses from allowing another request within the same 200ms window.
if (lastUpdateAt !== undefined && now - lastUpdateAt < 200) return;
lastBalanceUpdateAtRef.current.set(requestKey, now);
pendingBalanceUpdatesRef.current.add(requestKey);
try {
const res = await API.get(`/api/channel/update_balance/${record.id}/`);
const { success, message, balance } = res.data;
if (success) {
updateChannelProperty(record.id, (channel) => {
channel.balance = balance;
channel.balance_updated_time = Date.now() / 1000;
});
showInfo(
t('通道 ${name} 余额更新成功!').replace('${name}', record.name),
);
} else {
showError(message);
}
} catch (error) {
showError(error.message || t('网络错误'));
} finally {
pendingBalanceUpdatesRef.current.delete(requestKey);
}
};
@@ -835,10 +850,13 @@ export const useChannelsData = () => {
return Promise.resolve();
}
// 添加到正在测试的模型集合
setTestingModels((prev) => new Set([...prev, model]));
// Ref locks take effect immediately, including repeated clicks before a render.
const requestKey = JSON.stringify([String(record.id), model, endpointType]);
if (pendingChannelTestsRef.current.has(requestKey)) return;
pendingChannelTestsRef.current.add(requestKey);
try {
setTestingModels((prev) => new Set([...prev, model]));
let url = `/api/channel/test/${record.id}?model=${model}`;
if (endpointType) {
url += `&endpoint_type=${endpointType}`;
@@ -903,6 +921,7 @@ export const useChannelsData = () => {
}));
showError(`${t('模型')} ${model}: ${error.message || t('测试失败')}`);
} finally {
pendingChannelTestsRef.current.delete(requestKey);
// 从正在测试的模型集合中移除
setTestingModels((prev) => {
const newSet = new Set(prev);
@@ -912,21 +931,25 @@ export const useChannelsData = () => {
}
};
// 批量测试单个渠道的所有模型,参考旧版实现
// 批量测试当前渠道已勾选的模型。
const batchTestModels = async () => {
if (isBatchTesting) return;
if (!currentTestChannel || !currentTestChannel.models) {
showError(t('渠道模型信息不完整'));
return;
}
const models = currentTestChannel.models
.split(',')
.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase()),
);
// Snapshot selections across pages; search only controls the visible list.
const models = [
...new Set(
currentTestChannel.models
.split(',')
.filter((model) => model && selectedModelKeys.includes(model)),
),
];
if (models.length === 0) {
showError(t('没有找到匹配的模型'));
showError(t('请先选择模型!'));
return;
}
@@ -1112,6 +1135,7 @@ export const useChannelsData = () => {
// Column states
visibleColumns,
setVisibleColumns,
showColumnSelector,
setShowColumnSelector,
COLUMN_KEYS,
+34
View File
@@ -0,0 +1,34 @@
/*
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 { useDebouncedCallback } from 'use-debounce';
export function useFilterSearch(search) {
const scheduleSearch = useDebouncedCallback(search, 300);
const submitSearch = () => {
scheduleSearch.cancel();
return search();
};
return {
scheduleSearch,
submitSearch,
cancelPendingSearch: scheduleSearch.cancel,
};
}
+8 -8
View File
@@ -137,6 +137,14 @@ export const useNavigation = (
to: '/user-center',
requireAuth: getHeaderModuleRequireAuth(modules, 'userCenter'),
},
{
text: t('控制台'),
itemKey: 'console',
to: '/console/analytics',
activePrefix: '/console',
adminOnly: true,
requireAuth: true,
},
// WeyAi 网页端:外链到网关的 /sso/start(每次点击都重新走一遍免登录授权),
// 需要登录;管理员可在「顶栏管理」里关闭
...(weyaiVisible
@@ -164,14 +172,6 @@ export const useNavigation = (
},
]
: []),
{
text: t('控制台'),
itemKey: 'console',
to: '/console/analytics',
activePrefix: '/console',
adminOnly: true,
requireAuth: true,
},
];
return allLinks.filter((link) => {
+3 -6
View File
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { writeClipboardImage } from '../../helpers/clipboard';
/**
* 图像生成管理钩子
@@ -263,12 +264,8 @@ const useImageGeneration = (onImageGenerated) => {
const blob = await imageUrlToBlob(imageUrl);
// 检查浏览器是否支持剪贴板API
if (navigator.clipboard && window.ClipboardItem) {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blob,
}),
]);
if (navigator.clipboard?.write && window.ClipboardItem) {
await writeClipboardImage(blob);
return true;
} else {
setError(t('您的浏览器不支持复制图片到剪贴板'));
+20 -16
View File
@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal } from '@/components/ui';
import {
@@ -29,7 +29,6 @@ import {
timestamp2string,
} from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useMjLogsData = () => {
const { t } = useTranslation();
@@ -87,9 +86,6 @@ export const useMjLogsData = () => {
const [visibleColumns, setVisibleColumns] = useState({});
const [showColumnSelector, setShowColumnSelector] = useState(false);
// Compact mode
const [compactMode, setCompactMode] = useTableCompactMode('mjLogs');
// Load saved column preferences from localStorage
useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY);
@@ -222,7 +218,9 @@ export const useMjLogsData = () => {
};
// Load logs function
const listRequestIdRef = useRef(0);
const loadLogs = async (page = 1, size = pageSize) => {
const requestId = ++listRequestIdRef.current;
setLoading(true);
const { channel_id, mj_id, start_timestamp, end_timestamp } =
getFormValues();
@@ -231,14 +229,22 @@ export const useMjLogsData = () => {
const url = isAdminUser
? `/api/mj/?p=${page}&page_size=${size}&channel_id=${channel_id}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`
: `/api/mj/self/?p=${page}&page_size=${size}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
const res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
syncPageData(data);
} else {
showError(message);
try {
const res = await API.get(url);
if (requestId !== listRequestIdRef.current) return;
const { success, message, data } = res.data;
if (success) {
syncPageData(data);
} else {
showError(message);
}
} catch (error) {
if (requestId === listRequestIdRef.current) {
showError(error.message || error);
}
} finally {
if (requestId === listRequestIdRef.current) setLoading(false);
}
setLoading(false);
};
// Page handlers
@@ -310,6 +316,8 @@ export const useMjLogsData = () => {
// Column visibility
visibleColumns,
setVisibleColumns,
getDefaultColumnVisibility,
showColumnSelector,
setShowColumnSelector,
handleColumnVisibilityChange,
@@ -317,10 +325,6 @@ export const useMjLogsData = () => {
initDefaultColumns,
COLUMN_KEYS,
// Compact mode
compactMode,
setCompactMode,
// Functions
loadLogs,
handlePageChange,
+35 -19
View File
@@ -17,7 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useMemo } from 'react';
import { writeClipboardText } from '../../helpers/clipboard';
import { useState, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
@@ -92,6 +93,7 @@ export const useModelsData = () => {
// Vendor list
const [vendors, setVendors] = useState([]);
const [vendorCounts, setVendorCounts] = useState({});
const vendorCountsRequestRef = useRef(0);
const [activeVendorKey, setActiveVendorKey] = useState('all');
const [showAddVendor, setShowAddVendor] = useState(false);
const [showEditVendor, setShowEditVendor] = useState(false);
@@ -120,6 +122,33 @@ export const useModelsData = () => {
}
};
// Counts belong to the full catalog, independently of the visible vendor filter.
const loadVendorCounts = async () => {
const requestId = ++vendorCountsRequestRef.current;
try {
const res = await API.get('/api/models/?p=1&page_size=1', {
disableDuplicate: true,
});
const { success, data, message } = res.data;
if (requestId !== vendorCountsRequestRef.current) return;
if (!success) {
showError(message);
return;
}
if (data.vendor_counts) {
const all =
data.total ??
Object.values(data.vendor_counts).reduce(
(sum, value) => sum + Number(value || 0),
0,
);
setVendorCounts({ ...data.vendor_counts, all });
}
} catch (error) {
if (requestId === vendorCountsRequestRef.current) showError(error);
}
};
// Load models data
const loadModels = async (
page = 1,
@@ -141,14 +170,6 @@ export const useModelsData = () => {
setActivePage(data.page || page);
setModelCount(data.total || newPageData.length);
setModelFormat(newPageData);
if (data.vendor_counts) {
const sumAll = Object.values(data.vendor_counts).reduce(
(acc, v) => acc + v,
0,
);
setVendorCounts({ ...data.vendor_counts, all: sumAll });
}
} else {
showError(message);
setModels([]);
@@ -163,7 +184,7 @@ export const useModelsData = () => {
// Refresh data
const refresh = async (page = activePage) => {
await loadModels(page, pageSize);
await Promise.all([loadModels(page, pageSize), loadVendorCounts()]);
};
// Sync upstream models/vendors for missing models only
@@ -278,13 +299,6 @@ export const useModelsData = () => {
setActivePage(data.page || 1);
setModelCount(data.total || newPageData.length);
setModelFormat(newPageData);
if (data.vendor_counts) {
const sumAll = Object.values(data.vendor_counts).reduce(
(acc, v) => acc + v,
0,
);
setVendorCounts({ ...data.vendor_counts, all: sumAll });
}
} else {
showError(message);
setModels([]);
@@ -399,7 +413,8 @@ export const useModelsData = () => {
if (res.data.success) {
successCount++;
} else {
showError(`删除模型 ${selectedKeys[index].model_name} 失败: ${res.data.message}`,
showError(
`删除模型 ${selectedKeys[index].model_name} 失败: ${res.data.message}`,
);
}
});
@@ -447,7 +462,7 @@ export const useModelsData = () => {
// Copy text helper
const copyText = async (text) => {
try {
await navigator.clipboard.writeText(text);
await writeClipboardText(text);
showSuccess(t('复制成功'));
} catch (error) {
console.error('Copy failed:', error);
@@ -459,6 +474,7 @@ export const useModelsData = () => {
useEffect(() => {
(async () => {
await loadVendors();
await loadVendorCounts();
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+12 -67
View File
@@ -17,6 +17,7 @@ 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 { useCallback } from 'react';
import { Toast, Modal } from '@/components/ui';
import { useTranslation } from 'react-i18next';
@@ -124,72 +125,16 @@ export const useMessageActions = (
}
const copyToClipboard = async (text) => {
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
Toast.success({
content: hasAttachments
? t('已复制文本(附件未包含)')
: t('消息已复制到剪贴板'),
duration: 2,
});
} catch (err) {
console.error('Clipboard API 复制失败:', err);
fallbackCopy(text);
}
} else {
fallbackCopy(text);
}
};
const fallbackCopy = (text) => {
try {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.cssText = `
position: fixed;
top: -9999px;
left: -9999px;
opacity: 0;
pointer-events: none;
z-index: -1;
`;
textArea.setAttribute('readonly', '');
document.body.appendChild(textArea);
textArea.select();
textArea.setSelectionRange(0, text.length);
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (successful) {
Toast.success({
content: hasAttachments
? t('已复制文本(附件未包含)')
: t('消息已复制到剪贴板'),
duration: 2,
});
} else {
throw new Error('execCommand copy failed');
}
} catch (err) {
console.error('回退复制方案也失败:', err);
let errorMessage = t(ERROR_MESSAGES.COPY_FAILED);
if (
window.location.protocol === 'http:' &&
window.location.hostname !== 'localhost'
) {
errorMessage = t(ERROR_MESSAGES.COPY_HTTPS_REQUIRED);
} else if (!navigator.clipboard && !document.execCommand) {
errorMessage = t(ERROR_MESSAGES.BROWSER_NOT_SUPPORTED);
}
Toast.error({
content: errorMessage,
duration: 4,
await writeClipboardText(text);
Toast.success({
content: hasAttachments
? t('已复制文本(附件未包含)')
: t('消息已复制到剪贴板'),
duration: 2,
});
} catch {
Toast.error({ content: t(ERROR_MESSAGES.COPY_FAILED), duration: 4 });
}
};
@@ -387,9 +332,9 @@ export const useMessageActions = (
// 切换角色
const handleRoleToggle = useCallback(
(targetMessage) => {
if (
!(targetMessage.role === 'assistant' || targetMessage.role === 'system')
) {
if (!(
targetMessage.role === 'assistant' || targetMessage.role === 'system'
)) {
return;
}
+2
View File
@@ -524,6 +524,8 @@ export const useTaskLogsData = ({
// Column visibility
visibleColumns,
setVisibleColumns,
getDefaultColumnVisibility,
showColumnSelector,
setShowColumnSelector,
handleColumnVisibilityChange,
+32 -25
View File
@@ -569,34 +569,39 @@ export const useLogsData = () => {
});
url = `/api/log/self?${params.toString()}`;
}
const res = await API.get(url);
// 丢弃过期响应,只处理仍然是最新的请求
if (reqId !== logsRequestIdRef.current) return;
const { success, message, data } = res.data;
if (success) {
const newPageData = Array.isArray(data?.items) ? data.items : [];
setActivePage(data?.page || 1);
setPageSize(data?.page_size || pageSize);
setLogCount(data?.total || 0);
try {
const res = await API.get(url);
// 丢弃过期响应,只处理仍然是最新的请求
if (reqId !== logsRequestIdRef.current) return;
const { success, message, data } = res.data;
if (success) {
const newPageData = Array.isArray(data?.items) ? data.items : [];
setActivePage(data?.page || 1);
setPageSize(data?.page_size || pageSize);
setLogCount(data?.total || 0);
// 记录本次成功查询的筛选条件(与展示数据/总数一致),供「导出全部筛选结果」复用
appliedExportParamsRef.current = {
username,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
channel,
group,
user_id,
type: currentLogType,
};
// 记录本次成功查询的筛选条件(与展示数据/总数一致),供「导出全部筛选结果」复用
appliedExportParamsRef.current = {
username,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
channel,
group,
user_id,
type: currentLogType,
};
setLogsFormat(newPageData);
} else {
showError(message);
setLogsFormat(newPageData);
} else {
showError(message);
}
} catch (error) {
if (reqId === logsRequestIdRef.current) showError(error.message || error);
} finally {
if (reqId === logsRequestIdRef.current) setLoading(false);
}
if (reqId === logsRequestIdRef.current) setLoading(false);
};
// Page handlers
@@ -718,6 +723,8 @@ export const useLogsData = () => {
// Column visibility
visibleColumns,
setVisibleColumns,
getDefaultColumnVisibility,
showColumnSelector,
setShowColumnSelector,
handleColumnVisibilityChange,