Browse Source

delete bookings when removing an appointment

liontix 9 months ago
parent
commit
2ba262c6d4
3 changed files with 90 additions and 11 deletions
  1. 29 4
      routes/appointments.js
  2. 42 6
      routes/members.js
  3. 19 1
      schemas/appointmentSchema.js

+ 29 - 4
routes/appointments.js

@@ -38,10 +38,11 @@ router.post('/create', async function(req, res, next) {
             return res.status(404).json({ message: 'appointment does not exist' });
         }
         
-        console.log(existingAppointment.times);
-        // existingAppointment.times.find(input => input.date === "2025-01-27T06:00:00.000Z")
-        if (existingAppointment.times.find(input => input.date === "2025-01-27T06:00:00.000Z")) {
-            console.log("done");
+        const bookingDate = new Date(Date.parse(time));
+
+        if (!existingAppointment.times.find(input => input.date.toString() === bookingDate.toString() && input.available === true)) {
+            res.status(400).json({ 'message': 'This appointment time is not available' });
+            return;
         }
 
 
@@ -63,6 +64,30 @@ router.post('/create', async function(req, res, next) {
             return res.status(404).json({ message: 'already registered' });
         }
 
+        let times = existingAppointment.times;
+        const index = times.findIndex(element => element.date.toString() === bookingDate.toString());
+        if (index === -1) {
+            return res.status(404).json({ message: 'registration time not found' });
+        }
+
+        times[index].available = false;
+
+        await Appointment.updateOne(
+            { _id: appointmentId },
+            { $set: { times } }
+        )
+            .then(result => {
+                if (result.modifiedCount === 1) {
+                    console.log("Successfully updated the document.");
+                } else {
+                    console.log("Document not updated");
+                    return res.status(500).json({ 'message': 'Document has not changed' });
+                }
+            })
+            .catch(err => {
+                return res.status(404).json({ 'message': 'Not found' })
+            });
+
         const newBooking = new Booking({ appointment: appointmentId, time, inputs });
 
         newBooking.save()

+ 42 - 6
routes/members.js

@@ -30,9 +30,9 @@ router.use((req, res, next) => {
  */
 router.post('/create', function(req, res, next) {
     const user = req.userId;
-    const { title, description, dueDate, place, duration, times, inputs } = req.body;
+    const { title, description, dueDate, place, duration, times, inputs, timeSpans } = req.body;
 
-    if (!title || title.length === 0 || !dueDate || !description || !duration || !place || !times || !inputs) {
+    if (!title || title.length === 0 || !dueDate || !description || !duration || !place || !times || !inputs || !timeSpans) {
         res.status(400).json({ 'message': 'Empty parameter' });
         return;
     }
@@ -53,7 +53,7 @@ router.post('/create', function(req, res, next) {
         return;
     }
 
-    const newTask = new Appointment({ user, title, description, dueDate, place, duration, times, inputs });
+    const newTask = new Appointment({ user, title, description, dueDate, place, duration, times, inputs, timeSpans });
 
     newTask.save()
         .then(doc => res.json({ "id": doc._id }))
@@ -66,8 +66,8 @@ router.post('/create', function(req, res, next) {
 router.post('/modify', function (req, res, next) {
     const user = req.userId;
 
-    const { appointmentId, title, description, dueDate, place, times, inputs } = req.body;
-    if (!title || !dueDate || !description || !startDate || !endDate || !times || !inputs) {
+    const { appointmentId, title, description, dueDate, place, times, inputs, timeSpans } = req.body;
+    if (!title || !dueDate || !description || !times || !inputs || !timeSpans) {
         res.status(400).json({ 'error': 'Empty parameter' });
         return;
     }
@@ -79,7 +79,7 @@ router.post('/modify', function (req, res, next) {
 
     Appointment.updateOne(
         { _id: appointmentId, user: user },
-        { $set: { title, description, dueDate, place, times, inputs } }
+        { $set: { title, description, dueDate, place, times, inputs, timeSpans } }
     )
         .then(result => {
             if (result.modifiedCount === 1) {
@@ -93,17 +93,53 @@ router.post('/modify', function (req, res, next) {
         .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) {

+ 19 - 1
schemas/appointmentSchema.js

@@ -26,6 +26,23 @@ const customTimesSchema = new mongoose.Schema({
 },
 {_id: false});
 
+const AppointmentTimeRangeSchema = new mongoose.Schema({
+    start: { type: String, required: true }, // Example: "09:00"
+    end: { type: String, required: true }   // Example: "10:00"
+}, {_id: false});
+
+const WeekdayAppointmentSchema = new mongoose.Schema({
+    name: { type: String, required: true },
+    active: { type: Boolean, default: true },
+    date: { type: String, required: true }, // Stored as YYYY-MM-DD
+    times: { type: [AppointmentTimeRangeSchema], default: [] } // Array of time ranges
+}, {_id: false});
+
+const customTimeSpanSchema = new mongoose.Schema({
+    week: { type: Number, required: true }, // YYYYWW format (year + week number)
+    appointments: { type: [WeekdayAppointmentSchema], default: [] } // Array of appointments
+}, {_id: false});
+
 /**
  * Define a schema for an appointment using mongoose.
  *
@@ -69,7 +86,8 @@ const appointmentSchema = new mongoose.Schema({
         required: true
     },
     times: [customTimesSchema],
-    inputs: [customInputSchema]
+    inputs: [customInputSchema],
+    timeSpans: [customTimeSpanSchema]
 });