Skip to content

Commit 36fb972

Browse files
David Ingadavidsingal
David Inga
authored andcommitted
sorting fields for downloading csv
1 parent d2fbad0 commit 36fb972

File tree

1 file changed

+20
-3
lines changed
  • client/src/containers/admin/download-materials-data-button

1 file changed

+20
-3
lines changed

client/src/containers/admin/download-materials-data-button/component.tsx

+20-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useEffect, useState } from 'react';
1+
import { useCallback, useEffect, useMemo, useState } from 'react';
22
import { DownloadIcon } from '@heroicons/react/solid';
33

44
import Button from 'components/button';
@@ -9,6 +9,8 @@ import {
99
} from 'hooks/sourcing-locations';
1010
import { csvDownload } from 'utils/csv-download';
1111

12+
const yearExp = new RegExp(/^[0-9]{4}$/);
13+
1214
const DownloadMaterialsDataButton: React.FC = () => {
1315
const [isDownloading, setIsDownloading] = useState<boolean>(false);
1416

@@ -45,6 +47,21 @@ const DownloadMaterialsDataButton: React.FC = () => {
4547
);
4648

4749
const { data } = useSourcingLocationsMaterialsTabularData(sourcingData);
50+
const parsedData = useMemo(
51+
() =>
52+
data.map((row) => {
53+
// Adding _tons to the end of the year keys
54+
Object.keys(row)
55+
// Sorting years at the end
56+
.sort((a, b) => yearExp.test(a) && yearExp.test(b) && parseInt(a, 10) - parseInt(b, 10))
57+
.forEach((key) => {
58+
const newKey = yearExp.test(key) && `${key}_tons`;
59+
if (newKey) delete Object.assign(row, { [newKey]: row[key] })[key];
60+
});
61+
return row;
62+
}),
63+
[data],
64+
);
4865
const { updatedAt } = sourcingLocations?.data?.[0];
4966

5067
const handleDownload = useCallback(() => {
@@ -56,12 +73,12 @@ const DownloadMaterialsDataButton: React.FC = () => {
5673
useEffect(() => {
5774
if (isFetched && isSuccess && isDownloading) {
5875
csvDownload({
59-
data,
76+
data: parsedData,
6077
filename: `data_procurement_${updatedAt || ''}.csv`,
6178
});
6279
setIsDownloading(false);
6380
}
64-
}, [isFetched, isSuccess, data, updatedAt, isDownloading]);
81+
}, [isFetched, isSuccess, parsedData, updatedAt, isDownloading]);
6582

6683
return (
6784
<Button

0 commit comments

Comments
 (0)