/* 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 . For commercial licensing, please contact support@quantumnous.com */ import React, { useState, useCallback, useEffect } from 'react'; import { API, showError, showSuccess } from '../../helpers'; /** * 风控看板数据 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 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('保存成功'); // 阈值变化后,列表里"是否命中"的状态标签依赖新规则计算,需联动刷新 await Promise.all([fetchRules(), fetchSuspects()]); return true; } showError(res.data.message || '保存失败'); return false; } catch (e) { showError(e?.message || '保存失败'); 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('已触发后台扫描'); return true; } showError(res.data.message); return false; } catch (e) { showError(e?.message || '触发失败'); 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); params.append('page_size', 20); 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); } } catch (e) { console.error('查询封号日志失败', e); } finally { setBanLogLoading(false); } }, [banLogStatus, banLogPage], ); 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('解封成功'); // 解封会改变两个数据集的状态,并发刷新 await Promise.all([fetchSuspects(), fetchBanLogs()]); return true; } showError(res.data.message); return false; } catch (e) { showError(e?.message || '解封失败'); 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, fetchBanLogs, }; }; export default useRiskControlData;