File size: 2,593 Bytes
62c3fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const express = require('express');
const {DateTime} = require('luxon');
const { getAvailableDates } = require('../controller/dateAvailability');
const { getAvailableSlots } = require('../controller/slots');
const { createDateTimeSlotMapping, slotsInUserZone, getDatesSlots } = require('../controller/utils');
const { isHoliday } = require('../controller/holidays');

// This is the part where the route is defined.
const router = express.Router();

router.post('/get-available-dates-and-slots', async (req, res) => {
    const { requiredMinDate, timezone } = req.body;
    console.log('Received request to get available dates:', req.body);

    if (!requiredMinDate) {
        console.log("Minimum date is required");
        return res.status(400).send({ error: 'Minimum date is required' });
    }

    try {
        // Convert requiredMinDate to Asia/Kolkata timezone (starting of the day in Asia/Kolkata)
        const currentDate = DateTime.fromISO(requiredMinDate).setZone('Asia/Kolkata').startOf('day');
        console.log('Converted start date in Asia/Kolkata:', currentDate);

        // Initialize the availableDates array
        const availableDates = await getAvailableDates(currentDate);

        console.log('Available dates:', availableDates);
        if (availableDates){
            //create an arrow function that creates an array of objects, where each object key is the availableDate and the value is the one returned by getAvailableSlots(availableDate)
            const datesAndSlots = await Promise.all(availableDates.map(async availableDate => {
                const slots = await getAvailableSlots(availableDate);
                return { [availableDate]: slots };
            }));

            const inter = createDateTimeSlotMapping(datesAndSlots);
            console.log(inter);
            
            const userSlots = await slotsInUserZone(inter, timezone);
            console.log(userSlots);

            const finalDateSlots = await getDatesSlots(userSlots);
            console.log(finalDateSlots);

            const finalDates = Object.keys(finalDateSlots);
            console.log(finalDates);

            const response = {
                finalDateSlots: finalDateSlots,
                finalDates: finalDates
              };
            res.json(response);
        }
        
    } catch (error) {
        console.error('Error fetching available dates:', error.message);
        res.status(500).send({ error: 'Failed to fetch available dates' });
    }
});

// Export the router so it can be used in the server.js file.
module.exports = router;