Files
monkey-ai-web/src/hooks/analytics/useOrgConsumptionData.js
T
2026-10-15 16:33:46 +08:00

143 lines
4.6 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';
/**
* 企业经营决策报表数据 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;