1- import { EventAttributes , createEvents } from 'ics' ;
21import React , { useState } from 'react' ;
3- import { AbsenceWithRelations } from '../../app/api/getAbsences/route' ;
2+ import {
3+ getAbsenceEvents ,
4+ createCalendarFile ,
5+ } from '../../app/api/ics/[id]/ics' ;
46
57export default function CalendarDownload ( ) {
68 const [ error , setError ] = useState < string | null > ( null ) ;
79
8- const searchAbsences = async ( ) : Promise < EventAttributes [ ] > => {
9- try {
10- const res = await fetch ( '/api/getAbsences/' ) ;
11- if ( ! res . ok ) {
12- throw new Error ( `Failed to fetch: ${ res . statusText } ` ) ;
13- }
14- const data = await res . json ( ) ;
15- if ( ! data . events || ! Array . isArray ( data . events ) ) {
16- throw new Error ( 'Invalid data format.' ) ;
17- }
18- return data . events . map ( ( absence : AbsenceWithRelations ) => {
19- const substituteTeacherString = absence . substituteTeacher
20- ? `(${ absence . substituteTeacher . firstName } ${ absence . substituteTeacher . lastName [ 0 ] } )`
21- : '' ;
22- const lessonString = absence . lessonPlan || 'Lesson Plan Not Submitted' ;
23- const notesLine = absence . notes ? `\nNotes: ${ absence . notes } ` : '' ;
24-
25- const startDate = new Date ( absence . lessonDate ) ;
26- const endDate = new Date ( absence . lessonDate ) ;
27- endDate . setDate ( startDate . getDate ( ) + 1 ) ;
28-
29- return {
30- start : [
31- startDate . getFullYear ( ) ,
32- startDate . getMonth ( ) + 1 ,
33- startDate . getDate ( ) ,
34- ] ,
35- end : [
36- endDate . getFullYear ( ) ,
37- endDate . getMonth ( ) + 1 ,
38- endDate . getDate ( ) ,
39- ] ,
40- title : `${ absence . subject . name } : ${ absence . absentTeacher . firstName } ${ absence . absentTeacher . lastName [ 0 ] } ${ substituteTeacherString } ` ,
41- description : `Subject: ${ absence . subject . name } \nLesson Plan: ${ lessonString } ${ notesLine } ` ,
42- location : absence . location . name ,
43- } ;
44- } ) ;
45- } catch ( err ) {
46- console . error ( 'Error fetching absences:' , err ) ;
47- throw err ;
48- }
49- } ;
50-
51- const createCalendarFile = ( events : EventAttributes [ ] ) : Promise < File > => {
52- return new Promise ( ( resolve , reject ) => {
53- createEvents ( events , ( error , value ) => {
54- if ( error ) {
55- console . error ( 'Error creating events:' , error ) ;
56- reject ( error ) ;
57- } else {
58- resolve ( new File ( [ value ] , 'Absences.ics' , { type : 'text/calendar' } ) ) ;
59- }
60- } ) ;
61- } ) ;
62- } ;
63-
6410 const downloadFile = ( file : File ) => {
6511 const url = URL . createObjectURL ( file ) ;
6612 const anchor = document . createElement ( 'a' ) ;
@@ -77,7 +23,7 @@ export default function CalendarDownload() {
7723 setError ( null ) ;
7824
7925 try {
80- const events = await searchAbsences ( ) ;
26+ const events = await getAbsenceEvents ( ) ;
8127 const file = await createCalendarFile ( events ) ;
8228 downloadFile ( file ) ;
8329 } catch ( error ) {
0 commit comments