@@ -6,13 +6,12 @@ import clsx from "clsx";
66import Image from "next/image" ;
77
88import Button from "@/components/Button" ;
9- import CustomLink from "@/components/CustomLink" ;
109import { Report } from "@/queries/cooperative/report-section" ;
1110
1211import DropdownContainer from "./DropdownContainer" ;
1312
1413export type Reports = {
15- url : string ;
14+ file : { url : string } ;
1615 month ?: string ;
1716 year : number ;
1817} [ ] ;
@@ -29,7 +28,35 @@ const ReportCard: React.FC<IReportCard> = ({
2928 monthDropdownLabel,
3029 downloadButtonText,
3130} ) => {
32- const [ reportUrl , setReportUrl ] = useState < string > ( ) ;
31+ const [ selectedReport , setSelectedReport ] = useState < Reports [ number ] > ( ) ;
32+
33+ const handleDownload = ( ) => {
34+ if ( ! selectedReport || ! selectedReport . file . url ) return ;
35+ fetch ( selectedReport . file . url )
36+ . then ( ( response ) => response . blob ( ) )
37+ . then ( ( blob ) => {
38+ const url = window . URL . createObjectURL ( new Blob ( [ blob ] ) ) ;
39+ const link = document . createElement ( "a" ) ;
40+ link . href = url ;
41+
42+ const contentType = blob . type ;
43+
44+ const extension = contentType . split ( "/" ) [ 1 ] || "octet-stream" ;
45+ const fileExtension = extension === "json" ? "json" : extension ;
46+
47+ link . download = `${ selectedReport . month ? selectedReport . month + "-" : "" } ${ selectedReport . year } .${ fileExtension } ` ;
48+
49+ document . body . appendChild ( link ) ;
50+
51+ link . click ( ) ;
52+
53+ document . body . removeChild ( link ) ;
54+ window . URL . revokeObjectURL ( url ) ;
55+ } )
56+ . catch ( ( error ) => {
57+ console . error ( "Error fetching the file:" , error ) ;
58+ } ) ;
59+ } ;
3360
3461 return (
3562 < div
@@ -47,21 +74,20 @@ const ReportCard: React.FC<IReportCard> = ({
4774 < DropdownContainer
4875 { ...{
4976 reports,
50- setReportUrl ,
77+ setSelectedReport ,
5178 yearDropdownLabel,
5279 monthDropdownLabel,
5380 } }
5481 />
5582
56- < CustomLink href = { reportUrl ?? "" } >
57- < Button
58- variant = "primary"
59- className = "text-background-1"
60- disabled = { typeof reportUrl === "undefined" }
61- >
62- { downloadButtonText }
63- </ Button >
64- </ CustomLink >
83+ < Button
84+ variant = "primary"
85+ className = "text-background-1"
86+ disabled = { typeof selectedReport === "undefined" }
87+ onClick = { handleDownload }
88+ >
89+ { downloadButtonText }
90+ </ Button >
6591 </ div >
6692
6793 < div
0 commit comments