sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization

- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等,
  semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi
- 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复
- 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志
- 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求
- 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新
- 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
This commit is contained in:
qiubaishen
2026-11-18 10:22:02 +08:00
parent 914e5e2c67
commit db8cdf3360
157 changed files with 29960 additions and 1197 deletions
+3 -22
View File
@@ -35,7 +35,6 @@ export const useAnalyticsData = (active = true) => {
const [financeTrend, setFinanceTrend] = useState([]);
const [channelConsumption, setChannelConsumption] = useState([]);
const [userRanking, setUserRanking] = useState([]);
const [topupChannel, setTopupChannel] = useState([]);
const [dailyStats, setDailyStats] = useState([]);
const [userTopupRanking, setUserTopupRanking] = useState([]);
const [period, setPeriod] = useState('today'); // today, week, month, quarter, custom
@@ -173,23 +172,8 @@ export const useAnalyticsData = (active = true) => {
[buildQueryParams],
);
// 获取充值渠道分布
const fetchTopupChannel = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(
`/api/analytics/topup-channel?${queryParams}`,
);
if (res.data.success) {
setTopupChannel(res.data.data || []);
}
} catch (error) {
console.error('获取充值渠道分布失败:', error);
}
},
[buildQueryParams],
);
// 充值渠道分布面板已于 2026-11 从运营看板撤下(位置让给「企业用量分析」)。
// 组件 TopupChannelChart 与后端 /api/analytics/topup-channel 都保留,这里只是不再拉取。
// 获取每日统计
const fetchDailyStats = useCallback(
@@ -229,7 +213,7 @@ export const useAnalyticsData = (active = true) => {
// 刷新所有数据。
// 概览不参与全页 loading:它只影响顶部 6 张卡片(卡片自己有骨架屏),
// 却是耗时最长的一个请求,纳入遮罩会让下面的图表白白陪等。
// 返回的 Promise 仍然等齐全部 8 个请求,刷新按钮据此显示完整进度。
// 返回的 Promise 仍然等齐全部 7 个请求,刷新按钮据此显示完整进度。
const refreshAll = useCallback(
async (currentPeriod, currentDateRange, force = false) => {
const overviewTask = fetchOverview(force);
@@ -240,7 +224,6 @@ export const useAnalyticsData = (active = true) => {
fetchFinanceTrend(currentPeriod, currentDateRange),
fetchChannelConsumption(currentPeriod, currentDateRange),
fetchUserRanking(currentPeriod, currentDateRange),
fetchTopupChannel(currentPeriod, currentDateRange),
fetchDailyStats(currentPeriod, currentDateRange),
fetchUserTopupRanking(currentPeriod, currentDateRange),
]);
@@ -255,7 +238,6 @@ export const useAnalyticsData = (active = true) => {
fetchFinanceTrend,
fetchChannelConsumption,
fetchUserRanking,
fetchTopupChannel,
fetchDailyStats,
fetchUserTopupRanking,
],
@@ -303,7 +285,6 @@ export const useAnalyticsData = (active = true) => {
financeTrend,
channelConsumption,
userRanking,
topupChannel,
dailyStats,
userTopupRanking,
period,
+97
View File
@@ -0,0 +1,97 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { API } from '../../helpers';
// 可选窗口。默认 24h;7d 用于看跨天的周期性(工作日/夜间的命中率差异)。
export const ORG_CACHE_WINDOWS = [
{ key: '24h', hours: 24 },
{ key: '7d', hours: 24 * 7 },
];
/**
* 单企业逐小时缓存报表 Hook(看板点击某行后的抽屉)。
*
* 与 useOrgRealtimeUsage 不同,这里**不轮询**:抽屉是用户主动点开看的,
* 数据又是按小时聚合的,轮询除了重复打同一份 60 秒服务端缓存没有任何收益。
* orgId 为空(抽屉关着)时一个请求都不发。
*/
export const useOrgCacheHourly = (orgId, hours = 24) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const mountedRef = useRef(true);
// 请求序号:切窗口(24h↔7d)时两个请求会同时在飞,7d 慢一点就会后到并覆盖 24h 的结果。
// 只认最后一次发出的请求,丢弃过期响应。
const seqRef = useRef(0);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const fetchOnce = useCallback(
async (refresh = false) => {
if (!orgId) return;
const seq = ++seqRef.current;
setLoading(true);
setError(null);
try {
const res = await API.get(
`/api/analytics/org-cache-hourly?org_id=${orgId}&hours=${hours}${
refresh ? '&refresh=true' : ''
}`,
);
if (!mountedRef.current || seq !== seqRef.current) return;
if (res.data.success) {
setData(res.data.data || null);
} else {
setError(res.data.message || '');
setData(null);
}
} catch (e) {
if (!mountedRef.current || seq !== seqRef.current) return;
setError(e?.message || '');
setData(null);
} finally {
if (mountedRef.current && seq === seqRef.current) setLoading(false);
}
},
[orgId, hours],
);
useEffect(() => {
if (!orgId) {
// 关抽屉时清掉旧数据:否则下次点开别的企业会先闪一帧上一家的曲线。
seqRef.current++;
setData(null);
setError(null);
setLoading(false);
return;
}
fetchOnce(false);
}, [orgId, hours, fetchOnce]);
return { data, loading, error, refresh: () => fetchOnce(true) };
};
export default useOrgCacheHourly;
+129
View File
@@ -0,0 +1,129 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { API } from '../../helpers';
// 轮询间隔与服务端缓存 TTL 对齐(后端 orgRealtimeCacheTTL = 3s)。
// 调小没有意义:多出来的请求只会读到同一份缓存。
const POLL_INTERVAL_MS = 3000;
/**
* 企业实时用量(并发 / RPM / TPM)轮询 Hook。
*
* 参数 active:是否激活。false 时停表且不发任何请求(用于 Tab 懒加载)。
*
* 三道闸门避免无谓请求堆积:
* 1. active 为 false —— 用户不在运营看板 Tab;
* 2. 页面不可见(切到别的标签页 / 最小化)—— 没人看的数据不必拉;
* 3. 上一轮还在飞 —— 后端慢时不叠加请求,否则会越积越多。
*/
export const useOrgRealtimeUsage = (active = true, { limit = 10 } = {}) => {
const [data, setData] = useState(null);
// 仅首次加载显示骨架;后续 3 秒一次的刷新静默进行,否则表格会一直闪。
const [loading, setLoading] = useState(false);
const [sortBy, setSortBy] = useState('tpm');
const inFlightRef = useRef(false);
const mountedRef = useRef(true);
const loadedRef = useRef(false);
// 用 ref 读排序维度:轮询定时器只建一次,不应因为换排序就重建。
const sortByRef = useRef(sortBy);
sortByRef.current = sortBy;
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const fetchOnce = useCallback(
async (silent = true) => {
if (inFlightRef.current) return;
inFlightRef.current = true;
if (!silent) setLoading(true);
try {
const res = await API.get(
`/api/analytics/org-realtime?limit=${limit}&sort_by=${sortByRef.current}`,
);
if (!mountedRef.current) return;
if (res.data.success) {
setData(res.data.data || null);
loadedRef.current = true;
}
} catch (error) {
// 轮询接口不弹 toast:3 秒一次的报错提示会把页面淹掉。
console.error('获取企业实时用量失败:', error);
} finally {
inFlightRef.current = false;
if (!silent && mountedRef.current) setLoading(false);
}
},
[limit],
);
// 切换排序维度立即重拉一次,不等下一个轮询周期。
const changeSortBy = useCallback(
(next) => {
if (!next || next === sortByRef.current) return;
sortByRef.current = next;
setSortBy(next);
fetchOnce(true);
},
[fetchOnce],
);
useEffect(() => {
if (!active) return undefined;
// 首次进入显示骨架,之后(切走再切回)静默刷新。
fetchOnce(!loadedRef.current ? false : true);
const timer = setInterval(() => {
if (
typeof document !== 'undefined' &&
document.visibilityState !== 'visible'
) {
return;
}
fetchOnce(true);
}, POLL_INTERVAL_MS);
// 从后台切回前台时立刻补一次,避免盯着一屏最多 3 秒前的旧数据。
const onVisibilityChange = () => {
if (document.visibilityState === 'visible') fetchOnce(true);
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => {
clearInterval(timer);
document.removeEventListener('visibilitychange', onVisibilityChange);
};
}, [active, fetchOnce]);
return {
data,
loading,
sortBy,
setSortBy: changeSortBy,
refresh: () => fetchOnce(true),
};
};
export default useOrgRealtimeUsage;
+19 -1
View File
@@ -35,7 +35,11 @@ export const useNavigation = (
orgEntry = {},
) => {
// 解构成基础类型,避免父组件每次渲染传入新对象字面量导致 useMemo 失效
const { showOrgEntry = false, orgEntryPath = '/org' } = orgEntry;
const {
showOrgEntry = false,
orgEntryPath = '/org',
showPartnerEntry = false,
} = orgEntry;
// WeyAi 网页端入口:按 /api/status 开关与 /api/client/v1/web/access 决定是否显示
const { visible: weyaiVisible, url: weyaiUrl } = useWeyAiWebEntry();
const mainNavLinks = useMemo(() => {
@@ -106,6 +110,19 @@ export const useNavigation = (
};
const allLinks = [
// 平台开放且具备新版伙伴权限时展示;放在前面,窄屏也容易找到。
...(showPartnerEntry
? [
{
text: t('伙伴工作台'),
itemKey: 'partnerWorkspace',
mobileText: t('导航'),
to: '/console/my-commission',
requireAuth: true,
alwaysShow: true,
},
]
: []),
{
text: t('密钥管理'),
itemKey: 'keyManagement',
@@ -191,6 +208,7 @@ export const useNavigation = (
userGroup,
showOrgEntry,
orgEntryPath,
showPartnerEntry,
weyaiVisible,
weyaiUrl,
]);
@@ -0,0 +1,89 @@
/*
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 { useContext, useEffect, useState } from 'react';
import { API } from '../../helpers/api';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import { resolvePartnerWorkspaceIdentity } from '../../pages/PartnerPortal/redirect';
import { partnerScope } from '../../pages/CommissionV2/partnerScope';
// 顶栏入口与工作台使用同一套服务端鉴权,不根据平台角色或旧版伙伴记录推断。
export function usePartnerWorkspaceAccess(organizationId = null) {
const [userState] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
const user = userState?.user;
const scope = partnerScope(user?.id, organizationId);
const portalEnabled = statusState?.status?.commission_partner_portal_enabled;
// 分佣总开关关闭时不发起伙伴身份探测;旧后端不返回该字段,视为开启。
const commissionEnabled = statusState?.status?.commission_enabled !== false;
const enabled =
commissionEnabled &&
(portalEnabled === true || portalEnabled === 'true') &&
scope.valid &&
!userState?.authChecking;
const [access, setAccess] = useState(null);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
let cancelled = false;
setAccess(null);
if (!enabled) return undefined;
resolvePartnerWorkspaceIdentity((url, config) =>
API.get(scope.url(url), {
...config,
headers: scope.headers,
}),
).then(({ status, partnerType }) => {
if (!cancelled)
setAccess({ user, status, partnerType, attempt, scopeKey: scope.key });
});
return () => {
cancelled = true;
};
}, [enabled, user, attempt, scope.key]);
// 绑定本次登录的用户快照,切换账号时在 effect 执行前就隐藏旧入口。
let status = 'loading';
let partnerType = '';
if (statusState?.status !== undefined && !userState?.authChecking) {
if (!enabled) status = 'denied';
else if (
access?.user === user &&
access?.attempt === attempt &&
access?.scopeKey === scope.key
) {
status = access.status;
partnerType = access.partnerType || '';
}
}
return {
status,
partnerType,
retry: () => setAttempt((value) => value + 1),
};
}
// 顶栏「伙伴工作台」与控制台侧栏「我的提成」只给个人伙伴:
// 企业伙伴(含企业登录与管理企业的个人会话)统一从企业中心「企业分佣」进入,避免两处入口。
export function usePartnerWorkspaceEntry() {
const { status, partnerType } = usePartnerWorkspaceAccess();
return status === 'allowed' && partnerType === 'individual';
}
+76 -79
View File
@@ -63,6 +63,12 @@ export const useImageTaskManagement = () => {
// 上次轮询到的状态签名(status|progress),无变化时逐步退避
const lastSeenRef = useRef(new Map());
// 图片链接刷新:同一任务同一类型的请求进行中时复用(图片 onError 与批量刷新会同时触发);
// refreshedUrlKeysRef 记录本次挂载已刷新过的链接,批量刷新跳过它们
const urlRefreshInFlightRef = useRef(new Map());
const refreshedUrlKeysRef = useRef(new Set());
const urlRefreshTimerRef = useRef(null);
/**
* 将后端任务数据转换为前端格式
*/
@@ -339,6 +345,47 @@ export const useImageTaskManagement = () => {
);
}, []);
// 调用 refresh-url 并写回任务;返回新 URL(失败返回 null,请求异常向上抛出)。
// 不走全局错误提示:后台刷新静默,手动刷新由调用方给出提示。
const requestTaskUrlRefresh = useCallback(
(taskId, type, urlToRefresh) => {
const key = `${taskId}|${type}`;
const inFlight = urlRefreshInFlightRef.current.get(key);
if (inFlight) return inFlight;
const params = { task_id: taskId, type };
// 有有效 COS URL(不是 base64)时传给后端刷新;为空或 base64 时不传,后端从数据库读取 base64 并上传
if (urlToRefresh && !urlToRefresh.startsWith('data:')) {
params.url = urlToRefresh;
}
const request = API.get('/api/images/refresh-url', {
params,
skipErrorHandler: true,
})
.then((response) => {
const newUrl = response.data?.success ? response.data?.data?.url : '';
if (!newUrl) return null;
refreshedUrlKeysRef.current.add(key);
if (mountedRef.current) {
// 根据类型更新对应的URL,并清除base64数据(因为已上传到COS)
updateTask(
taskId,
type === 'source'
? { sourceImageUrl: newUrl, sourceImageBase64: null }
: { imageUrl: newUrl, imageBase64: null },
);
}
return newUrl;
})
.finally(() => {
urlRefreshInFlightRef.current.delete(key);
});
urlRefreshInFlightRef.current.set(key, request);
return request;
},
[updateTask],
);
// 刷新任务图片URL
// type: 'generated'(生成图,默认)或 'source'(原图,图生图模式)
// 支持两种场景:
@@ -358,45 +405,14 @@ export const useImageTaskManagement = () => {
const urlToRefresh =
type === 'source' ? task.sourceImageUrl : task.imageUrl;
// 如果URL是base64格式(data: 开头),说明前端保存了base64但还没上传到COS
// 这种情况需要上传到COS
const isBase64Url = urlToRefresh && urlToRefresh.startsWith('data:');
try {
// 构建请求参数
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(taskId)}&type=${type}`;
// 如果有有效的COS URL(不是base64),传递给后端刷新
if (urlToRefresh && !isBase64Url) {
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
}
// 如果URL是空的或者是base64格式,不传url参数,后端会从数据库读取base64并上传
const response = await API.get(apiUrl);
if (response.data?.success && response.data?.data?.url) {
const newUrl = response.data.data.url;
console.log(
`${type === 'source' ? '原图' : '生成图'}URL刷新成功,新URL:`,
newUrl,
);
// 根据类型更新对应的URL,并清除base64数据(因为已上传到COS)
if (type === 'source') {
updateTask(taskId, {
sourceImageUrl: newUrl,
sourceImageBase64: null,
});
} else {
updateTask(taskId, { imageUrl: newUrl, imageBase64: null });
}
const newUrl = await requestTaskUrlRefresh(taskId, type, urlToRefresh);
if (newUrl) {
if (!silent) showSuccess(i18next.t('链接已刷新'));
return true;
} else {
if (!silent) showError(i18next.t('刷新链接失败'));
return false;
}
if (!silent) showError(i18next.t('刷新链接失败'));
return false;
} catch (error) {
console.error('刷新URL失败:', error);
if (!silent)
@@ -408,64 +424,43 @@ export const useImageTaskManagement = () => {
return false;
}
},
[tasks, updateTask],
[tasks, requestTaskUrlRefresh],
);
// 批量刷新所有成功状态任务的图片链接(静默模式,用于页面加载时自动刷新)
// 跳过本次挂载已刷新过的任务(如图片 onError 已先刷新);页面卸载后停止
const refreshAllSuccessUrls = useCallback(
async (taskList) => {
// 筛选出成功状态的任务
const successTasks = taskList.filter((task) => task.status === 'success');
if (successTasks.length === 0) {
return;
}
console.log(`开始批量刷新 ${successTasks.length} 个任务的图片链接...`);
const successTasks = taskList.filter(
(task) =>
task.status === 'success' &&
!refreshedUrlKeysRef.current.has(`${task.id}|generated`),
);
// 并发刷新,但限制并发数避免请求过多
const BATCH_SIZE = 5;
let refreshedCount = 0;
for (let i = 0; i < successTasks.length; i += BATCH_SIZE) {
const batch = successTasks.slice(i, i + BATCH_SIZE);
if (!mountedRef.current) return;
const batch = successTasks
.slice(i, i + BATCH_SIZE)
.filter(
(task) => !refreshedUrlKeysRef.current.has(`${task.id}|generated`),
);
await Promise.all(
batch.map(async (task) => {
try {
// 构建请求参数
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(task.id)}&type=generated`;
const urlToRefresh = task.imageUrl;
const isBase64Url =
urlToRefresh && urlToRefresh.startsWith('data:');
if (urlToRefresh && !isBase64Url) {
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
}
const response = await API.get(apiUrl);
if (response.data?.success && response.data?.data?.url) {
const newUrl = response.data.data.url;
updateTask(task.id, { imageUrl: newUrl, imageBase64: null });
refreshedCount++;
}
} catch (error) {
// 静默失败,不影响其他任务
console.warn(`刷新任务 ${task.id} 链接失败:`, error.message);
}
}),
);
}
if (refreshedCount > 0) {
console.log(
`批量刷新完成,成功刷新 ${refreshedCount} 个任务的图片链接`,
batch.map((task) =>
requestTaskUrlRefresh(task.id, 'generated', task.imageUrl).catch(
(error) => {
// 静默失败,不影响其他任务
console.warn(`刷新任务 ${task.id} 链接失败:`, error.message);
},
),
),
);
}
},
[updateTask],
[requestTaskUrlRefresh],
);
// 取消/删除任务
@@ -546,7 +541,8 @@ export const useImageTaskManagement = () => {
// 自动刷新成功任务的图片链接(在后台静默执行,不阻塞页面)
if (autoRefreshUrls) {
// 使用 setTimeout 确保不阻塞 UI 渲染
setTimeout(() => {
clearTimeout(urlRefreshTimerRef.current);
urlRefreshTimerRef.current = setTimeout(() => {
refreshAllSuccessUrls(convertedTasks);
}, 500);
}
@@ -655,6 +651,7 @@ export const useImageTaskManagement = () => {
return () => {
mountedRef.current = false;
clearTimeout(pollingTimerRef.current);
clearTimeout(urlRefreshTimerRef.current);
document.removeEventListener('visibilitychange', onVisibility);
};
}, [refreshTasks, schedulePoll]);
@@ -58,7 +58,8 @@ export const useModelPricingData = () => {
const [groupRatio, setGroupRatio] = useState({});
// 模型级等级折扣修正系数(四期):{分组: {模型: 系数}},有效倍率 = groupRatio[g] × (系数 ?? 1)
const [groupModelDiscount, setGroupModelDiscount] = useState({});
// 折扣展示口径:enterprise=企业作用域按企业等级折扣展示(个人密钥调用仍按个人等级计费)
// 折扣展示口径:enterprise=按企业等级折扣展示——用户只要属于可用企业(含个人会话、个人密钥、
// 体验中心),标价与扣费都按所属企业等级;personal=不属于任何企业,按个人等级。
const [discountScope, setDiscountScope] = useState('personal');
const [usableGroup, setUsableGroup] = useState({});
const [endpointMap, setEndpointMap] = useState({});
+5 -7
View File
@@ -18,10 +18,9 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../common/useEffectEvent';
import { writeClipboardText } from '../../helpers/clipboard';
import { useState, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { API, copy, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
@@ -464,13 +463,12 @@ export const useModelsData = () => {
}
};
// Copy text helper
// Copy text helper:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
// 裸调只会报错而复制不到,公共 copy 带 execCommand 降级
const copyText = async (text) => {
try {
await writeClipboardText(text);
if (await copy(text)) {
showSuccess(t('复制成功'));
} catch (error) {
console.error('Copy failed:', error);
} else {
showError(t('复制失败'));
}
};
+56 -1
View File
@@ -372,6 +372,9 @@ export function useOrgTokens(orgId) {
const [tokens, setTokens] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
// 列表加载失败:业务文案字符串,或无文案时为 true;空串表示无错误。
// 页面据此展示错误态+重试,而不是误显示"暂无令牌"
const [error, setError] = useState('');
const fetch = useCallback(
async (page = 1, pageSize = 20) => {
@@ -385,8 +388,14 @@ export function useOrgTokens(orgId) {
if (res.data.success) {
setTokens(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
setError('');
} else {
// 无文案时用 true 兜底,保证页面仍进入错误态
setError(res.data.message || true);
showError(res.data.message);
}
} catch (err) {
setError(err.message || true);
showError(err.message);
} finally {
setLoading(false);
@@ -423,7 +432,8 @@ export function useOrgTokens(orgId) {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return true;
// 返回后端保存后的令牌(分组可能被后端回落改写),无数据时退化为 true
return res.data.data || true;
}
showError(res.data.message);
return false;
@@ -435,6 +445,27 @@ export function useOrgTokens(orgId) {
[orgId],
);
const getTokenEditOptions = useCallback(
async (tokenId, projectId) => {
if (!orgId) return null;
try {
const params = {};
if (projectId != null) params.project_id = projectId;
const res = await API.get(`/api/org/tokens/${tokenId}/edit-options`, {
headers: getOrgHeaders(orgId),
params,
});
if (res.data.success) return res.data.data || null;
showError(res.data.message);
return null;
} catch (err) {
showError(err.message);
return null;
}
},
[orgId],
);
const deleteToken = useCallback(
async (tokenId) => {
if (!orgId) return false;
@@ -455,13 +486,37 @@ export function useOrgTokens(orgId) {
[orgId],
);
// 列表只下发脱敏密钥;显示/复制时按需取完整密钥(后端留痕),失败返回 null
const fetchTokenKey = useCallback(
async (tokenId) => {
if (!orgId) return null;
try {
const res = await API.post(`/api/org/tokens/${tokenId}/key`, null, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return res.data.data?.key || null;
}
showError(res.data.message);
return null;
} catch (err) {
showError(err.message);
return null;
}
},
[orgId],
);
return {
tokens,
total,
loading,
error,
fetch,
createToken,
updateToken,
getTokenEditOptions,
deleteToken,
fetchTokenKey,
};
}
@@ -0,0 +1,110 @@
/*
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 assert from 'node:assert/strict';
import test from 'node:test';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { build } from 'esbuild';
// Execute the actual hook with React. Only its HTTP/error boundary is replaced.
const bundled = await build({
entryPoints: [fileURLToPath(new URL('./useOrgData.js', import.meta.url))],
bundle: true,
write: false,
platform: 'node',
format: 'cjs',
external: ['react', 'i18next'],
plugins: [
{
name: 'http-boundary',
setup(builder) {
builder.onResolve(
{ filter: /^\.\.\/\.\.\/helpers(?:\/api)?$/ },
() => ({
path: 'test-http-boundary',
external: true,
}),
);
},
},
],
});
const require = createRequire(import.meta.url);
function renderTokensHook(orgId) {
const calls = [];
const errors = [];
const transport = {
API: {
async get(url, config) {
calls.push({ url, ...config });
return {
data: { success: true, data: { groups: ['default', 'vip'] } },
};
},
},
showError: (message) => errors.push(message),
};
const module = { exports: {} };
vm.runInNewContext(bundled.outputFiles[0].text, {
module,
exports: module.exports,
require: (name) =>
name === 'test-http-boundary' ? transport : require(name),
});
let hook;
function Probe() {
hook = module.exports.useOrgTokens(orgId);
return null;
}
renderToString(React.createElement(Probe));
return { hook, calls, errors, transport };
}
test('token edit options explicitly send zero when unbinding a project', async () => {
const { hook, calls } = renderTokensHook(12);
const data = await hook.getTokenEditOptions(7, 0);
assert.equal(calls[0].url, '/api/org/tokens/7/edit-options');
assert.equal(calls[0].headers['X-Org-Id'], '12');
assert.equal(calls[0].params.project_id, 0);
assert.deepEqual(data.groups, ['default', 'vip']);
});
test('token edit options distinguish omitted project from an explicit project', async () => {
const { hook, calls } = renderTokensHook(12);
await hook.getTokenEditOptions(7);
await hook.getTokenEditOptions(7, 35);
assert.equal(Object.hasOwn(calls[0].params, 'project_id'), false);
assert.equal(calls[1].params.project_id, 35);
});
test('token edit options fail closed on HTTP and business errors', async () => {
const { hook, transport, errors } = renderTokensHook(12);
transport.API.get = async () => ({
data: { success: false, message: 'denied' },
});
assert.equal(await hook.getTokenEditOptions(7, 0), null);
transport.API.get = async () => {
throw new Error('offline');
};
assert.equal(await hook.getTokenEditOptions(7, 0), null);
assert.deepEqual(errors, ['denied', 'offline']);
});
+7
View File
@@ -71,6 +71,10 @@ export const useTaskLogsData = ({
PROGRESS: 'progress',
QUOTA: 'quota',
FAIL_REASON: 'fail_reason',
// 企业消费明细「绘图与视频」:部门资金归属快照两列(F-36),仅企业模式
...(organizationMode
? { FUND_DEPT: 'fund_dept', FUND_ACCOUNT: 'fund_account' }
: {}),
};
// Basic state
@@ -189,6 +193,9 @@ export const useTaskLogsData = ({
[COLUMN_KEYS.PROGRESS]: true,
[COLUMN_KEYS.QUOTA]: true,
[COLUMN_KEYS.FAIL_REASON]: true,
...(organizationMode
? { [COLUMN_KEYS.FUND_DEPT]: true, [COLUMN_KEYS.FUND_ACCOUNT]: true }
: {}),
};
};