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

Refactor code for calendar event retrieval and ICS generation #59

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
72 changes: 72 additions & 0 deletions app/api/getAbsences/absences.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { prisma } from '@utils/prisma';

export interface AbsenceWithRelations {
lessonDate: Date;
lessonPlan: string | null;
reasonOfAbsence: string;
notes: string | null;
absentTeacher: {
firstName: string;
lastName: string;
email: string;
};
substituteTeacher: {
firstName: string;
lastName: string;
email: string;
} | null;
location: {
name: string;
abbreviation: string;
};
subject: {
name: string;
abbreviation: string;
};
}

export const getAbsencesFromDatabase = async (): Promise<
AbsenceWithRelations[]
> => {
try {
const absences: AbsenceWithRelations[] = await prisma.absence.findMany({
select: {
lessonDate: true,
subject: {
select: {
name: true,
abbreviation: true,
},
},
lessonPlan: true,
reasonOfAbsence: true,
notes: true,
absentTeacher: {
select: {
firstName: true,
lastName: true,
email: true,
},
},
substituteTeacher: {
select: {
firstName: true,
lastName: true,
email: true,
},
},
location: {
select: {
name: true,
abbreviation: true,
},
},
},
});

return absences;
} catch (err) {
console.error('Error fetching absences:', err);
throw err;
}
};
62 changes: 2 additions & 60 deletions app/api/getAbsences/route.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,9 @@
import { prisma } from '@utils/prisma';
import { NextResponse } from 'next/server';

export interface AbsenceWithRelations {
lessonDate: Date;
lessonPlan: string | null;
reasonOfAbsence: string;
notes: string | null;
absentTeacher: {
firstName: string;
lastName: string;
email: string;
};
substituteTeacher: {
firstName: string;
lastName: string;
email: string;
} | null;
location: {
name: string;
abbreviation: string;
};
subject: {
name: string;
abbreviation: string;
};
}
import { AbsenceWithRelations, getAbsencesFromDatabase } from './absences';

export async function GET() {
try {
const absences: AbsenceWithRelations[] = await prisma.absence.findMany({
select: {
lessonDate: true,
subject: {
select: {
name: true,
abbreviation: true,
},
},
lessonPlan: true,
reasonOfAbsence: true,
notes: true,
absentTeacher: {
select: {
firstName: true,
lastName: true,
email: true,
},
},
substituteTeacher: {
select: {
firstName: true,
lastName: true,
email: true,
},
},
location: {
select: {
name: true,
abbreviation: true,
},
},
},
});
const absences: AbsenceWithRelations[] = await getAbsencesFromDatabase();

if (!absences.length) {
return NextResponse.json({ events: [] }, { status: 200 });
Expand Down
45 changes: 45 additions & 0 deletions app/api/ics/[id]/ics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { EventAttributes, createEvents } from 'ics';
import { AbsenceWithRelations } from '../../getAbsences/absences';

export const convertAbsenceToICSEvent = (
absence: AbsenceWithRelations,
calendarName: string
): EventAttributes => {
const substituteTeacherString = absence.substituteTeacher
? `(${absence.substituteTeacher.firstName} ${absence.substituteTeacher.lastName[0]})`
: '';
const lessonString = absence.lessonPlan || 'Lesson Plan Not Submitted';
const notesLine = absence.notes ? `\nNotes: ${absence.notes}` : '';

const startDate = new Date(absence.lessonDate);
const endDate = new Date(absence.lessonDate);
endDate.setDate(startDate.getDate() + 1);

return {
start: [
startDate.getFullYear(),
startDate.getMonth() + 1,
startDate.getDate(),
],
end: [endDate.getFullYear(), endDate.getMonth() + 1, endDate.getDate()],
title: `${absence.subject.name}: ${absence.absentTeacher.firstName} ${absence.absentTeacher.lastName[0]}${substituteTeacherString}`,
description: `Subject: ${absence.subject.name}\nLesson Plan: ${lessonString}${notesLine}`,
location: absence.location.name,
calName: calendarName,
};
};

export const createCalendarFile = (
events: EventAttributes[]
): Promise<File> => {
return new Promise((resolve, reject) => {
createEvents(events, (error, value) => {
if (error) {
console.error('Error creating events:', error);
reject(error);
} else {
resolve(new File([value], 'Absences.ics', { type: 'text/calendar' }));
}
});
});
};
2 changes: 1 addition & 1 deletion src/pages/calendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';
import { Box, Flex, useToast, useTheme } from '@chakra-ui/react';
import { EventInput, EventContentArg } from '@fullcalendar/core';
import { AbsenceWithRelations } from '../../app/api/getAbsences/route';
import { AbsenceWithRelations } from '../../app/api/getAbsences/absences';
import Sidebar from '../components/CalendarSidebar';
import CalendarHeader from '../components/CalendarHeader';
import { Global } from '@emotion/react';
Expand Down
78 changes: 19 additions & 59 deletions src/pages/ics.tsx
Original file line number Diff line number Diff line change
@@ -1,65 +1,12 @@
import { EventAttributes, createEvents } from 'ics';
import React, { useState } from 'react';
import { AbsenceWithRelations } from '../../app/api/getAbsences/route';
import { createCalendarFile } from '../../app/api/ics/[id]/ics';
import { AbsenceWithRelations } from '../../app/api/getAbsences/absences';
import { convertAbsenceToICSEvent } from '../../app/api/ics/[id]/ics';

export default function CalendarDownload() {
const [error, setError] = useState<string | null>(null);

const searchAbsences = async (): Promise<EventAttributes[]> => {
try {
const res = await fetch('/api/getAbsences/');
if (!res.ok) {
throw new Error(`Failed to fetch: ${res.statusText}`);
}
const data = await res.json();
if (!data.events || !Array.isArray(data.events)) {
throw new Error('Invalid data format.');
}
return data.events.map((absence: AbsenceWithRelations) => {
const substituteTeacherString = absence.substituteTeacher
? `(${absence.substituteTeacher.firstName} ${absence.substituteTeacher.lastName[0]})`
: '';
const lessonString = absence.lessonPlan || 'Lesson Plan Not Submitted';
const notesLine = absence.notes ? `\nNotes: ${absence.notes}` : '';

const startDate = new Date(absence.lessonDate);
const endDate = new Date(absence.lessonDate);
endDate.setDate(startDate.getDate() + 1);

return {
start: [
startDate.getFullYear(),
startDate.getMonth() + 1,
startDate.getDate(),
],
end: [
endDate.getFullYear(),
endDate.getMonth() + 1,
endDate.getDate(),
],
title: `${absence.subject.name}: ${absence.absentTeacher.firstName} ${absence.absentTeacher.lastName[0]}${substituteTeacherString}`,
description: `Subject: ${absence.subject.name}\nLesson Plan: ${lessonString}${notesLine}`,
location: absence.location.name,
};
});
} catch (err) {
console.error('Error fetching absences:', err);
throw err;
}
};

const createCalendarFile = (events: EventAttributes[]): Promise<File> => {
return new Promise((resolve, reject) => {
createEvents(events, (error, value) => {
if (error) {
console.error('Error creating events:', error);
reject(error);
} else {
resolve(new File([value], 'Absences.ics', { type: 'text/calendar' }));
}
});
});
};
const CALENDAR_NAME: string = 'Sistema Absences';

const downloadFile = (file: File) => {
const url = URL.createObjectURL(file);
Expand All @@ -77,8 +24,21 @@ export default function CalendarDownload() {
setError(null);

try {
const events = await searchAbsences();
const file = await createCalendarFile(events);
const res = await fetch('/api/getAbsences/');

if (!res.ok) {
throw new Error(`Failed to fetch: ${res.statusText}`);
}
const data = await res.json();
if (!data.events || !Array.isArray(data.events)) {
throw new Error('Invalid data format.');
}

const icsEvents = data.events.map((eventData: AbsenceWithRelations) =>
convertAbsenceToICSEvent(eventData, CALENDAR_NAME)
);

const file = await createCalendarFile(icsEvents);
downloadFile(file);
} catch (error) {
console.error('Error during download process:', error);
Expand Down