members.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import express from 'express';
  2. import passport from "passport";
  3. import {mongoose} from "mongoose";
  4. import Appointment from "../schemas/appointmentSchema.js";
  5. import Booking from "../schemas/bookingSchema.js";
  6. import {appointmentTimeSchema, isDueDatePassed, isValidAppointmentTimes, isValidCustomInput, validateDates} from "../utils.js";
  7. /**
  8. * Router for handling appointments.
  9. */
  10. const router = express.Router();
  11. /**
  12. * Middleware to authenticate with passport
  13. */
  14. router.use(passport.authenticate('jwt', { session: false }));
  15. /**
  16. * Middleware to pass user ID to req.userId if it exists in the request.
  17. */
  18. router.use((req, res, next) => {
  19. if (req.user && req.user.id) {
  20. req.userId = req.user.id; // Pass user ID to req.userId
  21. }
  22. next();
  23. });
  24. /**
  25. * Create a new appointment.
  26. */
  27. router.post('/create', function(req, res, next) {
  28. const user = req.userId;
  29. const { title, description, dueDate, place, duration, times, inputs, timeSpans, participants } = req.body;
  30. if (!title || title.length === 0 || !dueDate || !description || !duration || !place || !times || !inputs || !timeSpans || !participants) {
  31. res.status(400).json({ 'message': 'Empty parameter' });
  32. return;
  33. }
  34. ///
  35. if (isDueDatePassed(dueDate)) {
  36. res.status(400).json({ 'message': 'Due date is invalid or in the past' });
  37. return;
  38. }
  39. // validate times
  40. if (!isValidAppointmentTimes(times)) {
  41. res.status(400).json({ 'message': 'Appointment times are invalid' });
  42. return;
  43. }
  44. if (!isValidCustomInput(inputs)) {
  45. res.status(400).json({ 'message': 'Custom inputs are invalid' });
  46. return;
  47. }
  48. const newTask = new Appointment({ user, title, description, dueDate, place, duration, times, inputs, timeSpans, participants });
  49. newTask.save()
  50. .then(doc => res.json({ "id": doc._id }))
  51. .catch(err => res.status(500).json({ 'message': err }));
  52. });
  53. /**
  54. * Modify an existing appointment.
  55. */
  56. router.post('/modify', function (req, res, next) {
  57. const user = req.userId;
  58. const { appointmentId, title, description, dueDate, place, times, inputs, timeSpans, participants } = req.body;
  59. if (!title || !dueDate || !description || !times || !inputs || !timeSpans || !participants) {
  60. res.status(400).json({ 'error': 'Empty parameter' });
  61. return;
  62. }
  63. if (isDueDatePassed(dueDate)) {
  64. res.status(400).json({ 'error': 'Invalid due date' });
  65. return;
  66. }
  67. Appointment.updateOne(
  68. { _id: appointmentId, user: user },
  69. { $set: { title, description, dueDate, place, times, inputs, timeSpans, participants } }
  70. )
  71. .then(result => {
  72. if (result.modifiedCount === 1) {
  73. console.log("Successfully updated the document.");
  74. res.json({ "id": appointmentId });
  75. } else {
  76. console.log("Document not updated");
  77. res.status(500).json({ 'message': 'Document has not changed' });
  78. }
  79. })
  80. .catch(err => res.status(404).json({ 'message': 'Not found' }));
  81. });
  82. /**
  83. * Lock an existing appointment by modifying the due date.
  84. */
  85. router.post('/lock', function (req, res, next) {
  86. const user = req.userId;
  87. const { appointmentId } = req.body;
  88. if (!appointmentId) {
  89. res.status(400).json({ 'error': 'Empty parameter' });
  90. return;
  91. }
  92. const dueDate = new Date();
  93. Appointment.updateOne(
  94. { _id: appointmentId, user: user },
  95. { $set: { dueDate } }
  96. )
  97. .then(result => {
  98. if (result.modifiedCount === 1) {
  99. console.log("Successfully updated the document.");
  100. res.json({ "id": appointmentId });
  101. } else {
  102. console.log("Document not updated");
  103. res.status(500).json({ 'message': 'Document has not changed' });
  104. }
  105. })
  106. .catch(err => res.status(404).json({ 'message': 'Not found' }));
  107. });
  108. /**
  109. * Delete an appointment.
  110. */
  111. router.delete('/delete', function (req, res, next) {
  112. const user = req.userId;
  113. const {appointmentId} = req.body;
  114. console.log(req.body);
  115. if (!appointmentId) {
  116. res.status(400).json({ 'message': 'Invalid parameter' });
  117. return;
  118. }
  119. Booking.deleteMany({ appointment: appointmentId })
  120. .then(result => {})
  121. .catch(err => res.status(500).json({ 'message': err }));
  122. Appointment.deleteOne({ _id: appointmentId, user: user })
  123. .then(result => {
  124. if (result.deletedCount === 1) {
  125. res.json({ 'success': true });
  126. } else {
  127. res.status(404).json({ 'message': 'Not found' });
  128. }
  129. })
  130. .catch(err => res.status(500).json({ 'message': err }));
  131. });
  132. /**
  133. * Get all appointments for the authenticated user.
  134. */
  135. router.get('/appointments', function (req, res, next) {
  136. const user = req.userId;
  137. Appointment.find({ user: user })
  138. .then(appointments => {
  139. res.json(appointments);
  140. })
  141. .catch(err => {
  142. res.status(404).json({'message': "Appointments not found"});
  143. });
  144. });
  145. /**
  146. * Count the participants of an appointment
  147. */
  148. router.get('/bookings/count', async function (req, res, next) {
  149. const user = req.userId;
  150. let data = [];
  151. Appointment.find({ user: user })
  152. .then(async appointments => {
  153. console.log(appointments);
  154. for (const element of appointments) {
  155. const count = await Booking.countDocuments({appointment: element._id});
  156. console.log(count);
  157. data.push({appointmentId: element._id, count: count});
  158. }
  159. })
  160. .catch(err => {
  161. res.status(404).json({'message': "Appointments not found"});
  162. });
  163. res.json(data);
  164. });
  165. async function findAppointment(userId, appointmentId) {
  166. const resp = await Appointment.find({ user: userId, _id: appointmentId });
  167. return resp.length > 0;
  168. }
  169. /**
  170. * Get all bookings for a specific appointment.
  171. */
  172. router.get('/bookings', async function (req, res, next) {
  173. const user = req.userId;
  174. const { appointmentId } = req.query;
  175. if (!appointmentId) {
  176. res.status(400).json({ 'message': 'Empty parameter' });
  177. return;
  178. }
  179. if (!await findAppointment(user, appointmentId)) {
  180. return res.status(400).json({'message': 'Not your appointment'});
  181. }
  182. Booking.find({ appointment: appointmentId })
  183. .then(bookings => {
  184. if (bookings === null) {
  185. res.status(404).json({'message': "Appointment not found"});
  186. } else {
  187. res.json(bookings);
  188. }
  189. })
  190. .catch(err => {
  191. res.status(404).json({'message': "Appointment not found"});
  192. });
  193. });
  194. export { router };