1
- import { useCallback , useEffect , useState } from 'react' ;
1
+ import { useCallback , useEffect , useMemo , useState } from 'react' ;
2
2
import { DownloadIcon } from '@heroicons/react/solid' ;
3
3
4
4
import Button from 'components/button' ;
9
9
} from 'hooks/sourcing-locations' ;
10
10
import { csvDownload } from 'utils/csv-download' ;
11
11
12
+ const yearExp = new RegExp ( / ^ [ 0 - 9 ] { 4 } $ / ) ;
13
+
12
14
const DownloadMaterialsDataButton : React . FC = ( ) => {
13
15
const [ isDownloading , setIsDownloading ] = useState < boolean > ( false ) ;
14
16
@@ -45,6 +47,21 @@ const DownloadMaterialsDataButton: React.FC = () => {
45
47
) ;
46
48
47
49
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
+ ) ;
48
65
const { updatedAt } = sourcingLocations ?. data ?. [ 0 ] ;
49
66
50
67
const handleDownload = useCallback ( ( ) => {
@@ -56,12 +73,12 @@ const DownloadMaterialsDataButton: React.FC = () => {
56
73
useEffect ( ( ) => {
57
74
if ( isFetched && isSuccess && isDownloading ) {
58
75
csvDownload ( {
59
- data,
76
+ data : parsedData ,
60
77
filename : `data_procurement_${ updatedAt || '' } .csv` ,
61
78
} ) ;
62
79
setIsDownloading ( false ) ;
63
80
}
64
- } , [ isFetched , isSuccess , data , updatedAt , isDownloading ] ) ;
81
+ } , [ isFetched , isSuccess , parsedData , updatedAt , isDownloading ] ) ;
65
82
66
83
return (
67
84
< Button
0 commit comments