Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+306
View File
@@ -0,0 +1,306 @@
/*
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, showError } from '../../helpers';
/**
* 运营看板数据获取Hook
*
* 参数 active:是否激活。false 时不发起任何请求(用于 Tab 切换的懒加载)。
* 首次切换为 true 时自动加载一次;之后再切回保持现有数据,不重复拉。
*/
export const useAnalyticsData = (active = true) => {
const [loading, setLoading] = useState(false);
const [overview, setOverview] = useState(null);
const [userTrend, setUserTrend] = useState([]);
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
const [dateRange, setDateRange] = useState([null, null]); // 自定义日期范围 [startDate, endDate]
// 将 DatePicker 选择的日期转换为 UTC+8 当天零点/末尾的 Unix 时间戳(秒)
// DatePicker 返回的 Date 对象,其本地日期分量即用户选的日期,直接当作 CST 日期处理
const toCST = useCallback((date, isEndOfDay = false) => {
const d = new Date(date);
// 取本地日期分量(即用户在日历上选择的日期)
const year = d.getFullYear();
const month = d.getMonth();
const day = d.getDate();
// 构造该日期在 CST (UTC+8) 零点的 UTC 时间戳
// CST 零点 = UTC 同日零点 - 8小时
const cstMidnightMs =
Date.UTC(year, month, day, 0, 0, 0, 0) - 8 * 3600 * 1000;
if (isEndOfDay) {
// 当天结束 → 次日零点 CST
return Math.floor((cstMidnightMs + 24 * 3600 * 1000) / 1000);
}
return Math.floor(cstMidnightMs / 1000);
}, []);
// 构建查询参数
const buildQueryParams = useCallback(
(currentPeriod, currentDateRange) => {
const params = new URLSearchParams();
const usePeriod = currentPeriod || period;
const useRange = currentDateRange || dateRange;
if (usePeriod === 'custom' && useRange[0] && useRange[1]) {
// 自定义日期范围:统一使用 UTC+8 时区的天边界
const startTime = toCST(useRange[0], false);
const endTime = toCST(useRange[1], true);
params.append('start_time', startTime);
params.append('end_time', endTime);
} else if (usePeriod !== 'custom') {
params.append('period', usePeriod);
}
return params.toString();
},
[period, dateRange, toCST],
);
// 获取概览数据。后端对概览结果做了 60s 缓存,force=true 时穿透(用户主动点刷新)
const fetchOverview = useCallback(async (force = false) => {
try {
const res = await API.get(
`/api/analytics/overview${force ? '?refresh=true' : ''}`,
);
if (res.data.success) {
setOverview(res.data.data);
} else {
showError(res.data.message);
}
} catch (error) {
console.error('获取概览数据失败:', error);
}
}, []);
// 获取用户趋势
const fetchUserTrend = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/user-trend?${queryParams}`);
if (res.data.success) {
setUserTrend(res.data.data || []);
}
} catch (error) {
console.error('获取用户趋势失败:', error);
}
},
[buildQueryParams],
);
// 获取收支趋势
const fetchFinanceTrend = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(
`/api/analytics/finance-trend?${queryParams}`,
);
if (res.data.success) {
setFinanceTrend(res.data.data || []);
}
} catch (error) {
console.error('获取收支趋势失败:', error);
}
},
[buildQueryParams],
);
// 获取渠道消耗排行
const fetchChannelConsumption = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/channel-consumption?${queryParams}${separator}limit=30`,
);
if (res.data.success) {
setChannelConsumption(res.data.data || []);
}
} catch (error) {
console.error('获取渠道消耗排行失败:', error);
}
},
[buildQueryParams],
);
// 获取用户排行
const fetchUserRanking = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/user-ranking?${queryParams}${separator}limit=100`,
);
if (res.data.success) {
setUserRanking(res.data.data || []);
}
} catch (error) {
console.error('获取用户排行失败:', error);
}
},
[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],
);
// 获取每日统计
const fetchDailyStats = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/daily-stats?${queryParams}`);
if (res.data.success) {
setDailyStats(res.data.data || []);
}
} catch (error) {
console.error('获取每日统计失败:', error);
}
},
[buildQueryParams],
);
// 获取用户充值排行
const fetchUserTopupRanking = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/user-topup-ranking?${queryParams}${separator}limit=50`,
);
if (res.data.success) {
setUserTopupRanking(res.data.data || []);
}
} catch (error) {
console.error('获取用户充值排行失败:', error);
}
},
[buildQueryParams],
);
// 刷新所有数据
const refreshAll = useCallback(
async (currentPeriod, currentDateRange, force = false) => {
setLoading(true);
try {
await Promise.all([
fetchOverview(force),
fetchUserTrend(currentPeriod, currentDateRange),
fetchFinanceTrend(currentPeriod, currentDateRange),
fetchChannelConsumption(currentPeriod, currentDateRange),
fetchUserRanking(currentPeriod, currentDateRange),
fetchTopupChannel(currentPeriod, currentDateRange),
fetchDailyStats(currentPeriod, currentDateRange),
fetchUserTopupRanking(currentPeriod, currentDateRange),
]);
} finally {
setLoading(false);
}
},
[
fetchOverview,
fetchUserTrend,
fetchFinanceTrend,
fetchChannelConsumption,
fetchUserRanking,
fetchTopupChannel,
fetchDailyStats,
fetchUserTopupRanking,
],
);
// 切换时间周期
const handlePeriodChange = useCallback(
(newPeriod) => {
setPeriod(newPeriod);
if (newPeriod !== 'custom') {
setDateRange([null, null]);
refreshAll(newPeriod, [null, null]);
}
},
[refreshAll],
);
// 更新自定义日期范围
const handleDateRangeChange = useCallback(
(newRange) => {
setDateRange(newRange);
if (newRange[0] && newRange[1]) {
setPeriod('custom');
refreshAll('custom', newRange);
}
},
[refreshAll],
);
// 懒加载:仅在 active 第一次为 true 时拉数据。
// 由调用方传入 activeTab === 'operations',避免在 audit / risk Tab 时白白发起 8 个 API。
const loadedRef = useRef(false);
useEffect(() => {
if (!active || loadedRef.current) return;
loadedRef.current = true;
refreshAll(period, dateRange);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
return {
loading,
overview,
userTrend,
financeTrend,
channelConsumption,
userRanking,
topupChannel,
dailyStats,
userTopupRanking,
period,
dateRange,
setPeriod: handlePeriodChange,
setDateRange: handleDateRangeChange,
refreshAll,
};
};
export default useAnalyticsData;
@@ -0,0 +1,142 @@
/*
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';
/**
* 企业经营决策报表数据 Hook(单接口 /api/analytics/org-consumption/report,服务端基于汇总表计算)
*
* 参数 active:是否激活。false 时不发起任何请求(用于 Tab 懒加载)。
* 首次切换为 true 时自动加载一次;之后切回保持现有数据,不重复拉。
*
* 自带 period / dateRange 状态,与运营看板(useAnalyticsData)相互独立。
*/
export const useOrgConsumptionData = (active = true) => {
const [loading, setLoading] = useState(false);
const [report, setReport] = useState(null);
const [error, setError] = useState(false);
const [period, setPeriodState] = useState('week');
const [dateRange, setDateRangeState] = useState([null, null]);
// 只采纳最后一次请求的结果,避免快速切换时间段时旧响应覆盖新数据
const requestSeq = useRef(0);
// 与 useAnalyticsData 保持一致:DatePicker 选的本地日期分量当作 CST 日期处理
const toCST = useCallback((date, isEndOfDay = false) => {
const d = new Date(date);
const cstMidnightMs =
Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0) -
8 * 3600 * 1000;
if (isEndOfDay) {
return Math.floor((cstMidnightMs + 24 * 3600 * 1000) / 1000);
}
return Math.floor(cstMidnightMs / 1000);
}, []);
const buildQueryParams = useCallback(
(currentPeriod, currentDateRange) => {
const params = new URLSearchParams();
const usePeriod = currentPeriod || period;
const useRange = currentDateRange || dateRange;
if (usePeriod === 'custom' && useRange[0] && useRange[1]) {
params.append('start_time', toCST(useRange[0], false));
params.append('end_time', toCST(useRange[1], true));
} else if (usePeriod !== 'custom') {
params.append('period', usePeriod);
}
return params.toString();
},
[period, dateRange, toCST],
);
const refreshAll = useCallback(
async (currentPeriod, currentDateRange) => {
const seq = ++requestSeq.current;
setLoading(true);
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(
`/api/analytics/org-consumption/report?${queryParams}`,
{ skipErrorHandler: true },
);
if (seq !== requestSeq.current) return;
if (res.data?.success) {
setReport(res.data.data);
setError(false);
} else {
// 清掉旧时间段的数据,避免失败时把上一时段结果当成当前结果展示
setReport(null);
setError(true);
}
} catch (err) {
if (seq !== requestSeq.current) return;
console.error('获取企业经营报表失败:', err);
setReport(null);
setError(true);
} finally {
if (seq === requestSeq.current) setLoading(false);
}
},
[buildQueryParams],
);
const setPeriod = useCallback(
(newPeriod) => {
setPeriodState(newPeriod);
if (newPeriod !== 'custom') {
setDateRangeState([null, null]);
refreshAll(newPeriod, [null, null]);
}
},
[refreshAll],
);
const setDateRange = useCallback(
(newRange) => {
setDateRangeState(newRange);
if (newRange[0] && newRange[1]) {
setPeriodState('custom');
refreshAll('custom', newRange);
}
},
[refreshAll],
);
// 懒加载:仅在 active 首次为 true 时拉数据
const loadedRef = useRef(false);
useEffect(() => {
if (!active || loadedRef.current) return;
loadedRef.current = true;
refreshAll(period, dateRange);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
return {
loading,
report,
error,
period,
dateRange,
setPeriod,
setDateRange,
refreshAll,
};
};
export default useOrgConsumptionData;
+228
View File
@@ -0,0 +1,228 @@
/*
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';
/**
* 风控看板数据 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;