Files
monkey-ai-web/src/hooks/org/useOrgData.js
T
qiubaishen db8cdf3360 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)
2026-11-18 10:22:02 +08:00

523 lines
14 KiB
JavaScript

/*
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/api';
import { showError } from '../../helpers';
import { buildOrgLogFilters } from '../../helpers/orgLogFilters.js';
import i18next from 'i18next';
// 获取企业X-Org-Id header
const getOrgHeaders = (orgId) => ({
'X-Org-Id': String(orgId),
});
// 获取企业仪表盘
export function useOrgDashboard(orgId) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const seqRef = useRef(0);
const orgRef = useRef(orgId);
orgRef.current = orgId;
useEffect(() => {
seqRef.current += 1;
setData(null);
setLoading(false);
}, [orgId]);
const fetch = useCallback(async () => {
if (!orgId) return;
const requestOrgId = orgId;
const seq = ++seqRef.current;
setLoading(true);
try {
const res = await API.get('/api/org/dashboard', {
headers: getOrgHeaders(requestOrgId),
});
if (
seq === seqRef.current &&
requestOrgId === orgRef.current &&
res.data.success
) {
setData(res.data.data);
}
} catch (err) {
if (seq === seqRef.current && requestOrgId === orgRef.current)
showError(err.message);
} finally {
if (seq === seqRef.current && requestOrgId === orgRef.current)
setLoading(false);
}
}, [orgId]);
return { data, loading, fetch };
}
// 获取企业额度
export function useOrgQuota(orgId) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const seqRef = useRef(0);
const orgRef = useRef(orgId);
orgRef.current = orgId;
useEffect(() => {
seqRef.current += 1;
setData(null);
setLoading(false);
}, [orgId]);
const fetch = useCallback(
async (memberPage = 1, memberPageSize = 10) => {
if (!orgId) return;
const seq = ++seqRef.current;
const requestOrgId = orgId;
setLoading(true);
try {
const res = await API.get('/api/org/quota', {
headers: getOrgHeaders(requestOrgId),
params: {
member_page: memberPage,
member_page_size: memberPageSize,
},
});
if (
seq === seqRef.current &&
requestOrgId === orgRef.current &&
res.data.success
) {
setData(res.data.data);
}
} catch (err) {
if (seq === seqRef.current && requestOrgId === orgRef.current)
showError(err.message);
} finally {
if (seq === seqRef.current && requestOrgId === orgRef.current)
setLoading(false);
}
},
[orgId],
);
return { data, loading, fetch };
}
// 获取企业审计日志
export function useOrgAuditLogs(orgId) {
const [logs, setLogs] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const seqRef = useRef(0);
const orgRef = useRef(orgId);
orgRef.current = orgId;
useEffect(() => {
seqRef.current += 1;
setLogs([]);
setTotal(0);
setLoading(false);
}, [orgId]);
const fetch = useCallback(
async (page = 1, pageSize = 20, action = '') => {
if (!orgId) return;
const requestOrgId = orgId;
const seq = ++seqRef.current;
setLoading(true);
try {
const res = await API.get('/api/org/audit', {
headers: getOrgHeaders(requestOrgId),
params: { p: page, page_size: pageSize, action },
});
if (
seq === seqRef.current &&
requestOrgId === orgRef.current &&
res.data.success
) {
setLogs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
}
} catch (err) {
if (seq === seqRef.current && requestOrgId === orgRef.current)
showError(err.message);
} finally {
if (seq === seqRef.current && requestOrgId === orgRef.current)
setLoading(false);
}
},
[orgId],
);
return { logs, total, loading, fetch };
}
// 获取企业提示词记录(方案 §35 一期):数据来自企业自行配置的数据库。
// 连接失败时后端返回业务错误,error 状态供页面提示管理员去企业设置检查配置。
export function useOrgPromptRecords(orgId) {
const [records, setRecords] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
// 请求代次:切企业/翻页会触发并发请求,晚到的过期响应不得覆盖最新结果
const seqRef = useRef(0);
useEffect(() => {
// 企业切换时立即作废在途请求并清空旧租户数据,避免新请求返回前短暂展示旧记录。
seqRef.current += 1;
setRecords([]);
setTotal(0);
setError('');
setLoading(false);
}, [orgId]);
const fetch = useCallback(
async (
page = 1,
pageSize = 20,
{ memberId, modelName, keyword, startTimestamp, endTimestamp } = {},
) => {
if (!orgId) return;
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const params = { p: page, page_size: pageSize };
if (memberId) params.member_id = memberId;
if (modelName) params.model_name = modelName;
if (keyword) params.keyword = keyword;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
const res = await API.get('/api/org/prompt-archive/records', {
headers: getOrgHeaders(orgId),
params,
});
if (seq !== seqRef.current) return;
if (res.data.success) {
setRecords(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
setRecords([]);
setTotal(0);
setError(res.data.message || i18next.t('查询失败'));
}
} catch (err) {
if (seq !== seqRef.current) return;
setRecords([]);
setTotal(0);
setError(err.message);
} finally {
if (seq === seqRef.current) {
setLoading(false);
}
}
},
[orgId],
);
return { records, total, loading, error, fetch };
}
// 获取企业成员消耗日志
export function useOrgMemberLogs(orgId) {
const [logs, setLogs] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (page = 1, pageSize = 20, filters = {}) => {
if (!orgId) return;
setLoading(true);
try {
const params = {
p: page,
page_size: pageSize,
...buildOrgLogFilters(filters),
};
const res = await API.get('/api/org/logs', {
headers: getOrgHeaders(orgId),
params,
});
if (res.data.success) {
setLogs(res.data.data?.items || []);
// 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,此处保留首页已知总数,避免分页器异常
const nextTotal = res.data.data?.total;
if (typeof nextTotal === 'number' && nextTotal >= 0) {
setTotal(nextTotal);
}
} else {
setLogs([]);
setTotal(0);
showError(res.data.message || i18next.t('加载消耗明细失败'));
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
return { logs, total, loading, fetch };
}
// 获取企业成员消耗汇总统计
export function useOrgLogsStat(orgId) {
const [stat, setStat] = useState({
quota: 0,
rpm: 0,
tpm: 0,
has_time_range: false,
});
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (filters = {}, noCache = false) => {
if (!orgId) return;
setLoading(true);
try {
const params = buildOrgLogFilters(filters);
if (noCache) params.nocache = 1;
const res = await API.get('/api/org/logs/stat', {
headers: getOrgHeaders(orgId),
params,
});
if (res.data.success) {
setStat(
res.data.data || {
quota: 0,
rpm: 0,
tpm: 0,
has_time_range: false,
},
);
} else {
setStat({
quota: 0,
rpm: 0,
tpm: 0,
has_time_range: false,
});
showError(res.data.message || i18next.t('加载消耗统计失败'));
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
return { stat, loading, fetch };
}
// 获取企业成员消耗排行榜
export function useOrgMemberRanking(orgId) {
const [ranking, setRanking] = useState([]);
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async ({ limit, ...filters } = {}, noCache = false) => {
if (!orgId) return;
setLoading(true);
try {
const params = buildOrgLogFilters(filters);
if (limit) params.limit = limit;
if (noCache) params.nocache = 1;
const res = await API.get('/api/org/logs/ranking', {
headers: getOrgHeaders(orgId),
params,
});
if (res.data.success) {
setRanking(res.data.data || []);
} else {
setRanking([]);
showError(res.data.message || i18next.t('加载成员排行失败'));
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
return { ranking, loading, fetch };
}
// 获取企业Token列表
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) => {
if (!orgId) return;
setLoading(true);
try {
const res = await API.get('/api/org/tokens', {
headers: getOrgHeaders(orgId),
params: { p: page, page_size: pageSize },
});
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);
}
},
[orgId],
);
const createToken = useCallback(
async (data) => {
if (!orgId) return null;
try {
const res = await API.post('/api/org/tokens', data, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return res.data.data;
}
showError(res.data.message);
return null;
} catch (err) {
showError(err.message);
return null;
}
},
[orgId],
);
const updateToken = useCallback(
async (tokenId, data) => {
if (!orgId) return false;
try {
const res = await API.put(`/api/org/tokens/${tokenId}`, data, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
// 返回后端保存后的令牌(分组可能被后端回落改写),无数据时退化为 true
return res.data.data || true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[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;
try {
const res = await API.delete(`/api/org/tokens/${tokenId}`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[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,
};
}