umami/src/components/hooks/queries/useReport.ts

89 lines
2.1 KiB
TypeScript
Raw Normal View History

import { produce } from 'immer';
2023-05-20 18:02:08 +02:00
import { useCallback, useEffect, useState } from 'react';
2024-01-29 03:33:40 +01:00
import { useApi } from './useApi';
import { useTimezone } from '../useTimezone';
import { useMessages } from '../useMessages';
2023-05-20 18:02:08 +02:00
2024-03-14 10:45:00 +01:00
export function useReport(reportId: string, defaultParameters: { [key: string]: any } = {}) {
const [report, setReport] = useState(null);
const [isRunning, setIsRunning] = useState(false);
const { get, post } = useApi();
const { timezone } = useTimezone();
const { formatMessage, labels } = useMessages();
const baseParameters = {
name: formatMessage(labels.untitled),
description: '',
parameters: {},
};
2023-12-13 05:05:45 +01:00
const loadReport = async (id: string) => {
2023-11-14 06:36:52 +01:00
const data: any = await get(`/reports/${id}`);
2023-07-02 07:02:49 +02:00
const { dateRange } = data?.parameters || {};
const { startDate, endDate } = dateRange || {};
if (startDate && endDate) {
dateRange.startDate = new Date(startDate);
dateRange.endDate = new Date(endDate);
}
setReport(data);
};
const runReport = useCallback(
2023-12-13 05:05:45 +01:00
async (parameters: { [key: string]: any }) => {
setIsRunning(true);
2023-05-31 01:49:22 +02:00
const { type } = report;
2023-08-15 07:36:18 +02:00
const data = await post(`/reports/${type}`, { ...parameters, timezone });
setReport(
2023-11-14 06:36:52 +01:00
produce((state: any) => {
state.parameters = parameters;
state.data = data;
return state;
}),
);
setIsRunning(false);
},
2023-12-13 05:05:45 +01:00
[report, timezone],
);
const updateReport = useCallback(
2023-12-13 05:05:45 +01:00
async (data: { [x: string]: any; parameters: any }) => {
setReport(
2023-11-14 06:36:52 +01:00
produce((state: any) => {
const { parameters, ...rest } = data;
if (parameters) {
state.parameters = { ...state.parameters, ...parameters };
}
for (const key in rest) {
state[key] = rest[key];
}
2023-05-20 18:02:08 +02:00
return state;
}),
);
},
[report],
);
2023-05-20 18:02:08 +02:00
useEffect(() => {
if (!reportId) {
setReport({ ...baseParameters, ...defaultParameters });
} else {
loadReport(reportId);
2023-05-20 18:02:08 +02:00
}
}, []);
return { report, runReport, updateReport, isRunning };
2023-05-20 18:02:08 +02:00
}
export default useReport;