appointments.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. /**
  2. * Import required dependencies.
  3. */
  4. import express from 'express';
  5. import Appointment from "../schemas/appointmentSchema.js";
  6. import Booking from "../schemas/bookingSchema.js";
  7. import {isDueDatePassed, isInputValid, isValidEmail} from "../utils.js";
  8. /**
  9. * Create an Express router for handling appointment-related routes.
  10. */
  11. const router = express.Router();
  12. /**
  13. * Create a new appointment and associate it with a booking.
  14. */
  15. router.post('/create', async function(req, res, next) {
  16. const { appointmentId, time, inputs } = req.body;
  17. if (!appointmentId || !time || !inputs) {
  18. console.log(appointmentId);
  19. console.log(time);
  20. console.log(inputs);
  21. res.status(400).json({ 'message': 'Parameters are incomplete' });
  22. return;
  23. }
  24. // TODO validate times
  25. // advanced input validation
  26. // get constraints from database
  27. try {
  28. const existingAppointment = await Appointment.findOne({ _id: appointmentId });
  29. if (!existingAppointment) {
  30. return res.status(404).json({ message: 'appointment does not exist' });
  31. }
  32. const bookingDate = new Date(Date.parse(time));
  33. if (!existingAppointment.times.find(input => input.date.toString() === bookingDate.toString() && input.available === true)) {
  34. res.status(400).json({ 'message': 'This appointment time is not available' });
  35. return;
  36. }
  37. if (!isInputValid(inputs, existingAppointment.inputs)) {
  38. res.status(400).json({ 'message': 'Custom inputs are invalid' });
  39. return;
  40. }
  41. if (isDueDatePassed(existingAppointment["dueDate"])) {
  42. return res.status(401).json({ message: 'appointment registration is closed' });
  43. }
  44. const duplicateBooking = await Booking.findOne({ appointment: appointmentId, time, inputs: inputs })
  45. .catch(err => {
  46. console.log(err);
  47. });
  48. if (duplicateBooking) {
  49. return res.status(404).json({ message: 'already registered' });
  50. }
  51. let times = existingAppointment.times;
  52. const index = times.findIndex(element => element.date.toString() === bookingDate.toString());
  53. if (index === -1) {
  54. return res.status(404).json({ message: 'registration time not found' });
  55. }
  56. times[index].available = false;
  57. await Appointment.updateOne(
  58. { _id: appointmentId },
  59. { $set: { times } }
  60. )
  61. .then(result => {
  62. if (result.modifiedCount === 1) {
  63. console.log("Successfully updated the document.");
  64. } else {
  65. console.log("Document not updated");
  66. return res.status(500).json({ 'message': 'Document has not changed' });
  67. }
  68. })
  69. .catch(err => {
  70. return res.status(404).json({ 'message': 'Not found' })
  71. });
  72. const newBooking = new Booking({ appointment: appointmentId, time, inputs });
  73. newBooking.save()
  74. .then(doc => res.json({ "success": true }))
  75. .catch(err => res.status(500).json({ 'error': err }));
  76. } catch (err) {
  77. // Handle errors
  78. console.error(err);
  79. return res.status(500).json({ error: 'Internal Server Error' });
  80. }
  81. });
  82. /**
  83. * Retrieve an appointment by ID.
  84. */
  85. router.get('/', function (req, res, next) {
  86. const {appointmentId, isUser} = req.query;
  87. Appointment.findOne({ _id: appointmentId })
  88. .then(appointment => {
  89. if (appointment === null) {
  90. res.status(404).json({'message': "Appointment not found"});
  91. } else {
  92. // Check if a registered user accesses this endpoint
  93. if (isDueDatePassed(appointment["dueDate"]) && !isUser) {
  94. return res.status(410).json({ message: 'appointment registration is closed' });
  95. } else {
  96. res.json(appointment);
  97. }
  98. }
  99. })
  100. .catch(err => {
  101. res.status(404).json({'message': "Appointment not found"});
  102. });
  103. });
  104. export { router };