Files
monkey-ai-web/src/hooks/analytics/useRiskControlData.js
T
qiubaishen 61294dc597 merge: 合入总仓库 weiyuan(bfdfb339) web/ 新功能,保留 ui-optimization 的 UI 重构
来源:luoguang/monkey-ai weiyuan@bfdfb339 的 web/(经 sync/main-weiyuan-web-bfdfb339 同步)
同步基准:总仓库 a2ca13cb = 本仓库初始导入 d8f3aee2

冲突处理原则:保留 ui-optimization 的 UI(样式/结构/组件),嫁接 weiyuan 的功能逻辑。
- i18n:按键三方合并;ours 的「令牌→密钥」改名键上移植 theirs 的术语修订
- task-logs / OrgLogs:ours 已手工移植同一功能(6ad95e2),保留 ours
- 删除:OrgCreate(theirs 下线 /org/create)、旧 image 组件与 VideoRegenerateModal(theirs 体验中心重写)、
  OrgAvatarSection / PricingBentoPage / CommissionConsole(ours 重构中已移除)
- 测试:users-pagination 的 i18next mock 补 t();theirs 新增文件补 license header
2026-11-10 12:01:21 +08:00

236 lines
7.2 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 React, { useState, useCallback, useEffect } from 'react';
import { API, showError, showSuccess } from '../../helpers';
import i18next from 'i18next';
/**
* 风控看板数据 Hook
*
* - 顶部筛选:windowMinutes / minRequests / maxAvgQuota / maxTotalQuota
* - 数据:高频低消耗用户列表 + 当前规则配置 + 自动封号历史
*
* 参数 active:是否激活。false 时不发起任何请求(用于 Tab 切换的懒加载)。
* 首次切换为 true 时自动加载所有数据。
*/
export const useRiskControlData = (active = true) => {
const [loading, setLoading] = useState(false);
const [items, setItems] = useState([]);
const [windowRange, setWindowRange] = useState({ start: 0, end: 0 });
// 默认筛选:24h、请求 ≥ 100、不限平均消耗(前端表格按平均升序)
const [filters, setFilters] = useState({
windowMinutes: 1440,
minRequests: 100,
maxAvgQuota: 0,
maxTotalQuota: 0,
limit: 100,
});
const [rules, setRules] = useState([]);
const [rulesLoading, setRulesLoading] = useState(false);
// 封号历史
const [banLogs, setBanLogs] = useState([]);
const [banLogTotal, setBanLogTotal] = useState(0);
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) => {
const f = { ...filters, ...(override || {}) };
const params = new URLSearchParams();
params.append('window_minutes', f.windowMinutes);
params.append('min_requests', f.minRequests);
if (f.maxAvgQuota > 0) params.append('max_avg_quota', f.maxAvgQuota);
if (f.maxTotalQuota > 0)
params.append('max_total_quota', f.maxTotalQuota);
params.append('limit', f.limit);
setLoading(true);
try {
const res = await API.get(
`/api/analytics/risk/high-freq-low-cost?${params.toString()}`,
);
if (res.data.success) {
const d = res.data.data || {};
setItems(d.items || []);
setWindowRange({
start: d.window_start || 0,
end: d.window_end || 0,
});
} else {
showError(res.data.message);
}
} catch (e) {
console.error('查询高频低消耗用户失败', e);
} finally {
setLoading(false);
}
},
[filters],
);
const fetchRules = useCallback(async () => {
setRulesLoading(true);
try {
const res = await API.get('/api/analytics/risk/rules');
if (res.data.success) {
setRules(res.data.data || []);
}
} catch (e) {
console.error('查询风控规则失败', e);
} finally {
setRulesLoading(false);
}
}, []);
const saveRule = useCallback(
async (rule) => {
try {
const res = await API.post('/api/analytics/risk/rules', rule);
if (res.data.success) {
showSuccess(i18next.t('保存成功'));
// 阈值变化后,列表里"是否命中"的状态标签依赖新规则计算,需联动刷新
await Promise.all([fetchRules(), fetchSuspects()]);
return true;
}
showError(res.data.message || i18next.t('保存失败'));
return false;
} catch (e) {
showError(e?.message || i18next.t('保存失败'));
return false;
}
},
[fetchRules, fetchSuspects],
);
const triggerScanNow = useCallback(async () => {
try {
const res = await API.post('/api/analytics/risk/rules/run-now');
if (res.data.success) {
showSuccess(i18next.t('已触发后台扫描'));
return true;
}
showError(res.data.message);
return false;
} catch (e) {
showError(e?.message || i18next.t('触发失败'));
return false;
}
}, []);
const fetchBanLogs = useCallback(
async (override) => {
const status =
override?.status !== undefined ? override.status : banLogStatus;
const page = override?.page || banLogPage;
const params = new URLSearchParams();
if (status > 0) params.append('status', status);
params.append('page', page);
const size = override?.pageSize || banLogPageSize;
params.append('page_size', size);
setBanLogPageSize(size);
setBanLogLoading(true);
try {
const res = await API.get(
`/api/analytics/risk/ban-logs?${params.toString()}`,
);
if (res.data.success) {
const d = res.data.data || {};
setBanLogs(d.items || []);
setBanLogTotal(d.total || 0);
if (override?.page) setBanLogPage(override.page);
} else {
showError(res.data.message);
}
} catch (e) {
showError(e.message);
} finally {
setBanLogLoading(false);
}
},
[banLogStatus, banLogPage, banLogPageSize],
);
const unbanUser = useCallback(
async ({ userId, banLogId, reason }) => {
try {
const res = await API.post('/api/analytics/risk/unban', {
user_id: userId,
ban_log_id: banLogId || 0,
reason: reason || '',
});
if (res.data.success) {
showSuccess(i18next.t('解封成功'));
// 解封会改变两个数据集的状态,并发刷新
await Promise.all([fetchSuspects(), fetchBanLogs()]);
return true;
}
showError(res.data.message);
return false;
} catch (e) {
showError(e?.message || i18next.t('解封失败'));
return false;
}
},
[fetchSuspects, fetchBanLogs],
);
// 懒加载:仅在 active 第一次为 true 时拉数据。
// 由调用方传入 activeTab === 'risk',避免在运营 Tab 时白白发起 3 个 API。
const loadedRef = React.useRef(false);
useEffect(() => {
if (!active || loadedRef.current) return;
loadedRef.current = true;
fetchSuspects();
fetchRules();
fetchBanLogs();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
return {
loading,
items,
windowRange,
filters,
setFilters,
fetchSuspects,
rules,
rulesLoading,
fetchRules,
saveRule,
triggerScanNow,
unbanUser,
// 封号历史
banLogs,
banLogTotal,
banLogLoading,
banLogStatus,
setBanLogStatus,
banLogPage,
banLogPageSize,
fetchBanLogs,
};
};
export default useRiskControlData;