Files
monkey-ai-web/src/hooks/org/useOrgData.js
T
zhanjunhao a5e351a6f9 refactor(shared): 提取公共状态逻辑并修复用户列表分页
统一存储解析、通知已读状态、表格偏好和企业日志筛选参数。修复切换每页条数时沿用旧页码、丢失筛选条件和重复触发分页回调的问题。
同步调整项目检查脚本、格式配置和开发文档。
2026-10-21 18:47:21 +08:00

467 lines
12 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';
// 获取企业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 || '查询失败');
}
} 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 || '加载消耗明细失败');
}
} 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 || '加载消耗统计失败');
}
} 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 || '加载成员排行失败');
}
} 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);
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);
}
} catch (err) {
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) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[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],
);
return {
tokens,
total,
loading,
fetch,
createToken,
updateToken,
deleteToken,
};
}