| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- /**
- * Import required dependencies.
- */
- import express from 'express';
- import Appointment from "../schemas/appointmentSchema.js";
- import Booking from "../schemas/bookingSchema.js";
- import {isDueDatePassed, isValidEmail} from "../utils.js";
- /**
- * Create an Express router for handling appointment-related routes.
- */
- const router = express.Router();
- /**
- * Create a new appointment and associate it with a booking.
- */
- 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' });
- }
- });
- /**
- * Retrieve an appointment by ID.
- */
- 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 {
- // Check if a registered user accesses this 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 };
|