2023-05-29 06:37:34 +02:00
|
|
|
import { produce } from 'immer';
|
2023-05-20 18:02:08 +02:00
|
|
|
import { useCallback, useEffect, useState } from 'react';
|
2023-05-29 06:37:34 +02:00
|
|
|
import useApi from './useApi';
|
|
|
|
|
|
|
|
const baseParameters = {
|
|
|
|
name: 'Untitled',
|
|
|
|
description: '',
|
|
|
|
parameters: {},
|
|
|
|
};
|
2023-05-20 18:02:08 +02:00
|
|
|
|
2023-05-25 06:40:02 +02:00
|
|
|
export function useReport(reportId, defaultParameters) {
|
2023-05-29 06:37:34 +02:00
|
|
|
const [report, setReport] = useState(null);
|
|
|
|
const [isRunning, setIsRunning] = useState(false);
|
|
|
|
const { get, post } = useApi();
|
|
|
|
|
|
|
|
const loadReport = async id => {
|
|
|
|
const data = 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);
|
|
|
|
}
|
|
|
|
|
2023-05-29 06:37:34 +02:00
|
|
|
setReport(data);
|
|
|
|
};
|
|
|
|
|
|
|
|
const runReport = useCallback(
|
|
|
|
async parameters => {
|
|
|
|
setIsRunning(true);
|
|
|
|
|
2023-05-31 01:49:22 +02:00
|
|
|
const { type } = report;
|
|
|
|
|
|
|
|
const data = await post(`/reports/${type}`, parameters);
|
2023-05-29 06:37:34 +02:00
|
|
|
|
|
|
|
setReport(
|
|
|
|
produce(state => {
|
|
|
|
state.parameters = parameters;
|
|
|
|
state.data = data;
|
|
|
|
|
|
|
|
return state;
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
|
|
|
setIsRunning(false);
|
|
|
|
},
|
|
|
|
[report],
|
|
|
|
);
|
|
|
|
|
|
|
|
const updateReport = useCallback(
|
|
|
|
async data => {
|
|
|
|
setReport(
|
|
|
|
produce(state => {
|
|
|
|
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
|
|
|
|
2023-05-29 06:37:34 +02:00
|
|
|
return state;
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
[report],
|
|
|
|
);
|
2023-05-20 18:02:08 +02:00
|
|
|
|
|
|
|
useEffect(() => {
|
2023-05-29 06:37:34 +02:00
|
|
|
if (!reportId) {
|
|
|
|
setReport({ ...baseParameters, ...defaultParameters });
|
|
|
|
} else {
|
|
|
|
loadReport(reportId);
|
2023-05-20 18:02:08 +02:00
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
2023-05-29 06:37:34 +02:00
|
|
|
return { report, runReport, updateReport, isRunning };
|
2023-05-20 18:02:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export default useReport;
|