| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import express from 'express';
- import Appointment from "../schemas/appointmentSchema.js";
- import Booking from "../schemas/bookingSchema.js";
- import {isDueDatePassed, isValidEmail} from "../utils.js";
- import {app} from "../app.js";
- const router = express.Router();
- router.post('/create', async function(req, res, next) {
- const { appointment, email, firstname, lastname } = req.body;
- const appointmentId = appointment;
- if (!appointmentId || !firstname || !lastname || !email) {
- res.status(400).json({ 'message': 'Parameters are incomplete' });
- return;
- }
- if (!isValidEmail(email)) {
- res.status(400).json({ 'message': 'Email is invalid' });
- return;
- }
- try {
- const existingAppointment = await Appointment.findOne({ _id: appointmentId });
- if (!existingAppointment) {
- return res.status(404).json({ message: 'appointment does not exist' });
- }
- if (isDueDatePassed(existingAppointment["dueDate"])) {
- return res.status(401).json({ message: 'appointment registration is closed' });
- }
- const duplicateBooking = await Booking.findOne({ appointment: appointmentId, email: email })
- .catch(err => {
- console.log(err);
- });
- if (duplicateBooking) {
- return res.status(404).json({ message: 'already registered' });
- }
- const newBooking = new Booking({ appointment, email, firstname, lastname });
- newBooking.save()
- .then(doc => res.json({ "success": true }))
- .catch(err => res.status(500).json({ 'error': err }));
- } catch (err) {
- // Handle errors
- console.error(err);
- return res.status(500).json({ error: 'Internal Server Error' });
- }
- });
- router.get('/', function (req, res, next) {
- const {appointmentId, isUser} = req.query;
- Appointment.findOne({ _id: appointmentId })
- .then(appointment => {
- if (appointment === null) {
- res.status(404).json({'message': "Appointment not found"});
- } else {
- // TODO check if a registered user accesses this / move the endpoint
- if (isDueDatePassed(appointment["dueDate"]) && !isUser) {
- return res.status(410).json({ message: 'appointment registration is closed' });
- } else {
- res.json(appointment);
- }
- }
- })
- .catch(err => {
- res.status(404).json({'message': "Appointment not found"});
- });
- });
- export { router };
|