330 lines
11 KiB
JavaScript
330 lines
11 KiB
JavaScript
import { useState, useCallback, useEffect, useRef } from 'react';
|
|
import { API, showError } from '../../helpers';
|
|
import { useEffectEvent } from '../common/useEffectEvent';
|
|
import { useFilterSearch } from '../common/useFilterSearch';
|
|
|
|
const ANALYTICS_TIMEOUT_MS = 30_000;
|
|
|
|
/**
|
|
* 运营看板数据获取Hook
|
|
*
|
|
* 参数 active:是否激活。false 时不发起任何请求(用于 Tab 切换的懒加载)。
|
|
* 首次切换为 true 时自动加载一次;之后再切回保持现有数据,不重复拉。
|
|
*/
|
|
export const useAnalyticsData = (active = true) => {
|
|
const [loading, setLoading] = useState(false);
|
|
// 概览单独一个 loading:它是全页最慢的一个接口(活跃/消耗要跨月聚合),
|
|
// 和其余 7 个接口共用一个全页遮罩的话,整页都要等它,见 refreshAll。
|
|
const [overviewLoading, setOverviewLoading] = useState(false);
|
|
const [overview, setOverview] = useState(null);
|
|
const [userTrend, setUserTrend] = useState([]);
|
|
const [financeTrend, setFinanceTrend] = useState([]);
|
|
const [channelConsumption, setChannelConsumption] = useState([]);
|
|
const [userRanking, setUserRanking] = 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]
|
|
|
|
const activeRequest = useRef(null);
|
|
const loadedRef = useRef(false);
|
|
const cancelQuery = useCallback(() => {
|
|
activeRequest.current?.abort();
|
|
activeRequest.current = null;
|
|
}, []);
|
|
useEffect(() => cancelQuery, [cancelQuery]);
|
|
|
|
// 将 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, signal) => {
|
|
setOverviewLoading(true);
|
|
try {
|
|
const res = await API.get(
|
|
`/api/analytics/overview${force ? '?refresh=true' : ''}`,
|
|
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
|
|
);
|
|
if (signal.aborted) return;
|
|
if (res.data.success) {
|
|
setOverview(res.data.data);
|
|
} else {
|
|
showError(res.data.message);
|
|
}
|
|
} catch (error) {
|
|
if (!signal.aborted) console.error('获取概览数据失败:', error);
|
|
} finally {
|
|
if (!signal.aborted) setOverviewLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
// 获取用户趋势
|
|
const fetchUserTrend = useCallback(
|
|
async (currentPeriod, currentDateRange, signal) => {
|
|
try {
|
|
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
|
|
const res = await API.get(`/api/analytics/user-trend?${queryParams}`, {
|
|
signal,
|
|
timeout: ANALYTICS_TIMEOUT_MS,
|
|
});
|
|
if (signal.aborted) return;
|
|
if (res.data.success) {
|
|
setUserTrend(res.data.data || []);
|
|
}
|
|
} catch (error) {
|
|
if (!signal.aborted) console.error('获取用户趋势失败:', error);
|
|
}
|
|
},
|
|
[buildQueryParams],
|
|
);
|
|
|
|
// 获取收支趋势
|
|
const fetchFinanceTrend = useCallback(
|
|
async (currentPeriod, currentDateRange, signal) => {
|
|
try {
|
|
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
|
|
const res = await API.get(
|
|
`/api/analytics/finance-trend?${queryParams}`,
|
|
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
|
|
);
|
|
if (signal.aborted) return;
|
|
if (res.data.success) {
|
|
setFinanceTrend(res.data.data || []);
|
|
}
|
|
} catch (error) {
|
|
if (!signal.aborted) console.error('获取收支趋势失败:', error);
|
|
}
|
|
},
|
|
[buildQueryParams],
|
|
);
|
|
|
|
// 获取渠道消耗排行
|
|
const fetchChannelConsumption = useCallback(
|
|
async (currentPeriod, currentDateRange, signal) => {
|
|
try {
|
|
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
|
|
const separator = queryParams ? '&' : '';
|
|
const res = await API.get(
|
|
`/api/analytics/channel-consumption?${queryParams}${separator}limit=30`,
|
|
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
|
|
);
|
|
if (signal.aborted) return;
|
|
if (res.data.success) {
|
|
setChannelConsumption(res.data.data || []);
|
|
}
|
|
} catch (error) {
|
|
if (!signal.aborted) console.error('获取渠道消耗排行失败:', error);
|
|
}
|
|
},
|
|
[buildQueryParams],
|
|
);
|
|
|
|
// 获取用户排行
|
|
const fetchUserRanking = useCallback(
|
|
async (currentPeriod, currentDateRange, signal) => {
|
|
try {
|
|
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
|
|
const separator = queryParams ? '&' : '';
|
|
const res = await API.get(
|
|
`/api/analytics/user-ranking?${queryParams}${separator}limit=100`,
|
|
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
|
|
);
|
|
if (signal.aborted) return;
|
|
if (res.data.success) {
|
|
setUserRanking(res.data.data || []);
|
|
}
|
|
} catch (error) {
|
|
if (!signal.aborted) console.error('获取用户排行失败:', error);
|
|
}
|
|
},
|
|
[buildQueryParams],
|
|
);
|
|
|
|
// 充值渠道分布面板已于 2026-11 从运营看板撤下(位置让给「企业用量分析」)。
|
|
// 组件 TopupChannelChart 与后端 /api/analytics/topup-channel 都保留,这里只是不再拉取。
|
|
|
|
// 获取每日统计
|
|
const fetchDailyStats = useCallback(
|
|
async (currentPeriod, currentDateRange, signal) => {
|
|
try {
|
|
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
|
|
const res = await API.get(`/api/analytics/daily-stats?${queryParams}`, {
|
|
signal,
|
|
timeout: ANALYTICS_TIMEOUT_MS,
|
|
});
|
|
if (signal.aborted) return;
|
|
if (res.data.success) {
|
|
setDailyStats(res.data.data || []);
|
|
}
|
|
} catch (error) {
|
|
if (!signal.aborted) console.error('获取每日统计失败:', error);
|
|
}
|
|
},
|
|
[buildQueryParams],
|
|
);
|
|
|
|
// 获取用户充值排行
|
|
const fetchUserTopupRanking = useCallback(
|
|
async (currentPeriod, currentDateRange, signal) => {
|
|
try {
|
|
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
|
|
const separator = queryParams ? '&' : '';
|
|
const res = await API.get(
|
|
`/api/analytics/user-topup-ranking?${queryParams}${separator}limit=50`,
|
|
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
|
|
);
|
|
if (signal.aborted) return;
|
|
if (res.data.success) {
|
|
setUserTopupRanking(res.data.data || []);
|
|
}
|
|
} catch (error) {
|
|
if (!signal.aborted) console.error('获取用户充值排行失败:', error);
|
|
}
|
|
},
|
|
[buildQueryParams],
|
|
);
|
|
|
|
// 刷新所有数据。
|
|
// 概览不参与全页 loading:它只影响顶部 6 张卡片(卡片自己有骨架屏),
|
|
// 却是耗时最长的一个请求,纳入遮罩会让下面的图表白白陪等。
|
|
// 返回的 Promise 仍然等齐全部 7 个请求,刷新按钮据此显示完整进度。
|
|
const refreshAll = useCallback(
|
|
async (currentPeriod, currentDateRange, force = false) => {
|
|
cancelQuery();
|
|
const controller = new AbortController();
|
|
activeRequest.current = controller;
|
|
const { signal } = controller;
|
|
const overviewTask = fetchOverview(force, signal);
|
|
setLoading(true);
|
|
try {
|
|
await Promise.all([
|
|
fetchUserTrend(currentPeriod, currentDateRange, signal),
|
|
fetchFinanceTrend(currentPeriod, currentDateRange, signal),
|
|
fetchChannelConsumption(currentPeriod, currentDateRange, signal),
|
|
fetchUserRanking(currentPeriod, currentDateRange, signal),
|
|
fetchDailyStats(currentPeriod, currentDateRange, signal),
|
|
fetchUserTopupRanking(currentPeriod, currentDateRange, signal),
|
|
]);
|
|
} finally {
|
|
if (!signal.aborted) setLoading(false);
|
|
}
|
|
await overviewTask;
|
|
if (activeRequest.current === controller) {
|
|
activeRequest.current = null;
|
|
loadedRef.current = true;
|
|
}
|
|
},
|
|
[
|
|
cancelQuery,
|
|
fetchOverview,
|
|
fetchUserTrend,
|
|
fetchFinanceTrend,
|
|
fetchChannelConsumption,
|
|
fetchUserRanking,
|
|
fetchDailyStats,
|
|
fetchUserTopupRanking,
|
|
],
|
|
);
|
|
|
|
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
|
|
(conditions) =>
|
|
refreshAll(
|
|
conditions?.period ?? period,
|
|
conditions?.dateRange ?? dateRange,
|
|
!conditions,
|
|
),
|
|
cancelQuery,
|
|
);
|
|
|
|
const handlePeriodChange = (newPeriod) => {
|
|
setPeriod(newPeriod);
|
|
if (newPeriod !== 'custom') {
|
|
const emptyRange = [null, null];
|
|
setDateRange(emptyRange);
|
|
scheduleSearch({ period: newPeriod, dateRange: emptyRange });
|
|
}
|
|
};
|
|
|
|
const handleDateRangeChange = (newRange) => {
|
|
const range = newRange ?? [null, null];
|
|
setDateRange(range);
|
|
scheduleSearch({ period: 'custom', dateRange: range });
|
|
};
|
|
|
|
const resetFilters = () => {
|
|
cancelPendingSearch();
|
|
setPeriod('today');
|
|
setDateRange([null, null]);
|
|
void refreshAll('today', [null, null]);
|
|
};
|
|
|
|
const loadInitialData = useEffectEvent(() => {
|
|
if (!loadedRef.current && !activeRequest.current) {
|
|
void refreshAll(period, dateRange);
|
|
}
|
|
});
|
|
|
|
// StrictMode 会取消首次副作用,只有完整结束的请求批次才算加载过。
|
|
useEffect(() => {
|
|
if (active) loadInitialData();
|
|
}, [active, loadInitialData]);
|
|
|
|
return {
|
|
loading,
|
|
overviewLoading,
|
|
overview,
|
|
userTrend,
|
|
financeTrend,
|
|
channelConsumption,
|
|
userRanking,
|
|
dailyStats,
|
|
userTopupRanking,
|
|
period,
|
|
dateRange,
|
|
setPeriod: handlePeriodChange,
|
|
setDateRange: handleDateRangeChange,
|
|
submitSearch,
|
|
resetFilters,
|
|
};
|
|
};
|
|
|
|
export default useAnalyticsData;
|