Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Download data now downloads according the api #1103

Merged
merged 4 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions client/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/).

### Added
- Added a new filter for business units in the analysis page
- On the analysis page, the user can now navigates in the subcategories in the charts view [LANDGRIF-1507](https://vizzuality.atlassian.net/browse/LANDGRIF-1507)

### Changed
- Download data button in the analysis page now downloads the data according to the filters applied from the API [LANDGRIF-1502](https://vizzuality.atlassian.net/browse/LANDGRIF-1502)

### Fixed
- Renew token when it is expired
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/search/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const Search: React.FC<SearchProps> = ({
<div
className={classnames('bg-white', {
'w-fit min-w-[260px]': size === 'base',
'w-44': size === 'sm',
'flex w-auto max-w-[160px]': size === 'sm',
})}
>
<div className="flex items-center justify-center w-full">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ import { useAppSelector } from 'store/hooks';
import { filtersForTabularAPI } from 'store/features/analysis/selector';
import { scenarios } from 'store/features/analysis/scenarios';
import { useIndicators } from 'hooks/indicators';
import { useImpactData, useDownloadImpactData } from 'hooks/impact';
import {
useImpactData,
useDownloadImpactData,
useDownloadImpactActualVsScenarioData,
useDownloadImpactScenarioVsScenarioData,
} from 'hooks/impact';
import { useImpactComparison, useImpactScenarioComparison } from 'hooks/impact/comparison';
import AnalysisDynamicMetadata from 'containers/analysis-visualization/analysis-dynamic-metadata';
import { Button } from 'components/button';
Expand Down Expand Up @@ -71,6 +76,20 @@ const AnalysisTable = () => {
onError: handleResponseError,
});

const downloadActualVsScenarioData = useDownloadImpactActualVsScenarioData({
onSuccess: () => {
toast.success('Data was downloaded successfully');
},
onError: handleResponseError,
});

const downloadScenarioVsScenarioData = useDownloadImpactScenarioVsScenarioData({
onSuccess: () => {
toast.success('Data was downloaded successfully');
},
onError: handleResponseError,
});

const filters = useAppSelector(filtersForTabularAPI);

const useIsComparison = useCallback(
Expand Down Expand Up @@ -114,17 +133,30 @@ const AnalysisTable = () => {
return {};
}, [sortingState]);

const params = {
indicatorIds,
startYear: filters.startYear,
endYear: filters.endYear,
groupBy: filters.groupBy,
...restFilters,
...sortingParams,
scenarioId: currentScenario,
'page[number]': paginationState.pageIndex,
'page[size]': paginationState.pageSize,
};
const params = useMemo(
() => ({
indicatorIds,
startYear: filters.startYear,
endYear: filters.endYear,
groupBy: filters.groupBy,
...restFilters,
...sortingParams,
scenarioId: currentScenario,
'page[number]': paginationState.pageIndex,
'page[size]': paginationState.pageSize,
}),
[
currentScenario,
filters.endYear,
filters.groupBy,
filters.startYear,
indicatorIds,
paginationState.pageIndex,
paginationState.pageSize,
restFilters,
sortingParams,
],
);

const plainImpactData = useImpactData(params, {
enabled: !isComparisonEnabled && isEnable,
Expand Down Expand Up @@ -173,17 +205,46 @@ const AnalysisTable = () => {
return impactTable[0]?.rows[0]?.values.find((value) => value.isProjected)?.year;
}, [impactTable]);

const handleDownloadData = useCallback(() => {
const csv = downloadImpactData.mutate();
// if (csv) {
// const link = document.createElement('a');
// link.setAttribute('href', csv);
// link.setAttribute('download', 'data.csv');
// document.body.appendChild(link);
// link.click();
// document.body.removeChild(link);
// }
}, [downloadImpactData]);
const handleDownloadData = useCallback(async () => {
let csv = null;
// actual vs scenario
if (!currentScenario && scenarioToCompare) {
csv = await downloadActualVsScenarioData.mutateAsync({
...omit(params, 'page[number]', 'page[size]'),
comparedScenarioId: scenarioToCompare,
});
}
// scenario vs scenario
else if (currentScenario && scenarioToCompare) {
csv = await downloadScenarioVsScenarioData.mutateAsync({
...omit(params, 'page[number]', 'page[size]', 'scenarioId'),
baseScenarioId: currentScenario,
comparedScenarioId: scenarioToCompare,
});
}
// no scenario or comparison
else {
csv = await downloadImpactData.mutateAsync(omit(params, 'page[number]', 'page[size]'));
}

if (csv) {
const url = window.URL.createObjectURL(new Blob([csv]));
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `impact_data_${Date.now()}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// do not pass pagination params to download data endpoint
}, [
currentScenario,
downloadActualVsScenarioData,
downloadImpactData,
downloadScenarioVsScenarioData,
params,
scenarioToCompare,
]);

const handleExpandedChange = useCallback(
<Mode extends ComparisonMode>(table: TableType<ImpactRowType<Mode>>) => {
Expand Down Expand Up @@ -472,9 +533,19 @@ const AnalysisTable = () => {
variant="secondary"
size="base"
className="flex-shrink-0"
disabled={isLoading}
disabled={
isLoading ||
downloadImpactData.isLoading ||
downloadActualVsScenarioData.isLoading ||
downloadScenarioVsScenarioData.isLoading
}
icon={<DownloadIcon />}
onClick={handleDownloadData}
loading={
downloadImpactData.isLoading ||
downloadActualVsScenarioData.isLoading ||
downloadScenarioVsScenarioData.isLoading
}
>
Download Data
</Button>
Expand Down
35 changes: 33 additions & 2 deletions client/src/hooks/impact/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,43 @@ export const useImpactData = <T = ImpactDataApiResponse<false>>(
return query;
};

const requestDownload = (params) =>
apiRawService.get('/impact/table/report', { params }).then((response) => response.data);

export const useDownloadImpactData = (options) => {
const requestDownload = () =>
apiRawService.get('/impact/table/report').then((response) => response.data);
const mutation = useMutation(requestDownload, {
mutationKey: ['download-impact-data'],
...options,
});
return mutation;
};

const requestActualVsScenarioDownload = (params) =>
apiRawService
.get('/impact/compare/scenario/vs/actual/report', {
params,
})
.then((response) => response.data);

export const useDownloadImpactActualVsScenarioData = (options) => {
const mutation = useMutation(requestActualVsScenarioDownload, {
mutationKey: ['download-actual-vs-scenario-data'],
...options,
});
return mutation;
};

const requestScenarioVsScenarioDownload = (params) =>
apiRawService
.get('/impact/compare/scenario/vs/scenario/report', {
params,
})
.then((response) => response.data);

export const useDownloadImpactScenarioVsScenarioData = (options) => {
const mutation = useMutation(requestScenarioVsScenarioDownload, {
mutationKey: ['download-scenario-vs-scenario-data'],
...options,
});
return mutation;
};
Loading