import express from 'express'; import passport from "passport"; import {mongoose} from "mongoose"; import Appointment from "../schemas/appointmentSchema.js"; import Booking from "../schemas/bookingSchema.js"; import {appointmentTimeSchema, isDueDatePassed, isValidAppointmentTimes, isValidCustomInput, validateDates} from "../utils.js"; /** * Router for handling appointments. */ const router = express.Router(); /** * Middleware to authenticate with passport */ router.use(passport.authenticate('jwt', { session: false })); /** * Middleware to pass user ID to req.userId if it exists in the request. */ router.use((req, res, next) => { if (req.user && req.user.id) { req.userId = req.user.id; // Pass user ID to req.userId } next(); }); /** * Create a new appointment. */ router.post('/create', function(req, res, next) { const user = req.userId; const { title, description, dueDate, place, duration, times, inputs, timeSpans, participants } = req.body; if (!title || title.length === 0 || !dueDate || !description || !duration || !place || !times || !inputs || !timeSpans || !participants) { res.status(400).json({ 'message': 'Empty parameter' }); return; } /// if (isDueDatePassed(dueDate)) { res.status(400).json({ 'message': 'Due date is invalid or in the past' }); return; } // validate times if (!isValidAppointmentTimes(times)) { res.status(400).json({ 'message': 'Appointment times are invalid' }); return; } if (!isValidCustomInput(inputs)) { res.status(400).json({ 'message': 'Custom inputs are invalid' }); return; } const newTask = new Appointment({ user, title, description, dueDate, place, duration, times, inputs, timeSpans, participants }); newTask.save() .then(doc => res.json({ "id": doc._id })) .catch(err => res.status(500).json({ 'message': err })); }); /** * Modify an existing appointment. */ router.post('/modify', function (req, res, next) { const user = req.userId; const { appointmentId, title, description, dueDate, place, times, inputs, timeSpans, participants } = req.body; if (!title || !dueDate || !description || !times || !inputs || !timeSpans || !participants) { res.status(400).json({ 'error': 'Empty parameter' }); return; } if (isDueDatePassed(dueDate)) { res.status(400).json({ 'error': 'Invalid due date' }); return; } Appointment.updateOne( { _id: appointmentId, user: user }, { $set: { title, description, dueDate, place, times, inputs, timeSpans, participants } } ) .then(result => { if (result.modifiedCount === 1) { console.log("Successfully updated the document."); res.json({ "id": appointmentId }); } else { console.log("Document not updated"); res.status(500).json({ 'message': 'Document has not changed' }); } }) .catch(err => res.status(404).json({ 'message': 'Not found' })); }); /** * Lock an existing appointment by modifying the due date. */ router.post('/lock', function (req, res, next) { const user = req.userId; const { appointmentId } = req.body; if (!appointmentId) { res.status(400).json({ 'error': 'Empty parameter' }); return; } const dueDate = new Date(); Appointment.updateOne( { _id: appointmentId, user: user }, { $set: { dueDate } } ) .then(result => { if (result.modifiedCount === 1) { console.log("Successfully updated the document."); res.json({ "id": appointmentId }); } else { console.log("Document not updated"); res.status(500).json({ 'message': 'Document has not changed' }); } }) .catch(err => res.status(404).json({ 'message': 'Not found' })); }); /** * Delete an appointment. */ router.delete('/delete', function (req, res, next) { const user = req.userId; const {appointmentId} = req.body; console.log(req.body); if (!appointmentId) { res.status(400).json({ 'message': 'Invalid parameter' }); return; } Booking.deleteMany({ appointment: appointmentId }) .then(result => {}) .catch(err => res.status(500).json({ 'message': err })); Appointment.deleteOne({ _id: appointmentId, user: user }) .then(result => { if (result.deletedCount === 1) { res.json({ 'success': true }); } else { res.status(404).json({ 'message': 'Not found' }); } }) .catch(err => res.status(500).json({ 'message': err })); }); /** * Get all appointments for the authenticated user. */ router.get('/appointments', function (req, res, next) { const user = req.userId; Appointment.find({ user: user }) .then(appointments => { res.json(appointments); }) .catch(err => { res.status(404).json({'message': "Appointments not found"}); }); }); /** * Count the participants of an appointment */ router.get('/bookings/count', async function (req, res, next) { const user = req.userId; let data = []; Appointment.find({ user: user }) .then(async appointments => { console.log(appointments); for (const element of appointments) { const count = await Booking.countDocuments({appointment: element._id}); console.log(count); data.push({appointmentId: element._id, count: count}); } }) .catch(err => { res.status(404).json({'message': "Appointments not found"}); }); res.json(data); }); async function findAppointment(userId, appointmentId) { const resp = await Appointment.find({ user: userId, _id: appointmentId }); return resp.length > 0; } /** * Get all bookings for a specific appointment. */ router.get('/bookings', async function (req, res, next) { const user = req.userId; const { appointmentId } = req.query; if (!appointmentId) { res.status(400).json({ 'message': 'Empty parameter' }); return; } if (!await findAppointment(user, appointmentId)) { return res.status(400).json({'message': 'Not your appointment'}); } Booking.find({ appointment: appointmentId }) .then(bookings => { if (bookings === null) { res.status(404).json({'message': "Appointment not found"}); } else { res.json(bookings); } }) .catch(err => { res.status(404).json({'message': "Appointment not found"}); }); }); export { router };