i-darrshan's picture
initial push of the update
8b105ad
const { runSelectQuery } = require('../utils/queries');
const generalSlots = [
`10:00 - 10:30`, `10:45 - 11:15`, `11:30 - 12:00`, `12:15 - 12:45`, `13:00 - 13:30`,
`13:45 - 14:15`, `14:30 - 15:00`, `15:15 - 15:45`, `16:00 - 16:30`, `16:45 - 17:15`, `17:30 - 18:00`
];
//async function to get list of booked slots for a given date
async function getBookedSlots(date) {
if (!date) {
throw new Error('Date is required');
}
// Ensure the date is in the correct format (YYYY-MM-DD)
const isValidDate = /^\d{4}-\d{2}-\d{2}$/.test(date);
if (!isValidDate) {
throw new Error('Invalid date format. Expected YYYY-MM-DD');
}
try {
const query = `
SELECT slot FROM demo_requests WHERE demo_date = ?;
`;
const results = await runSelectQuery(query, date);
console.log(`Fetched ${results.length} slots for date: ${date}`);
// Check if results are empty
if (!results || results.length === 0) {
console.log(`No slots found for date: ${date}`);
return []; // Return an empty array if no slots are found
}
// Extract slots, with checks to ensure each result contains a 'slot' property
const slots = results.map(result => {
if (!result.slot) {
console.warn(`No slot found for record: ${JSON.stringify(result)}`);
return null; // Handle cases where slot is undefined or null
}
return result.slot;
}).filter(slot => slot !== null); // Remove any null values (in case of missing slots)
return slots;
} catch (error) {
console.error('Error fetching booked slots:', error.message);
throw error; // Re-throw the error after logging it
}
}
//async function to get available slots for a given date
async function getAvailableSlots(date) {
if (!date) {
throw new Error('Date is required');
}
// Ensure the date is in the correct format (YYYY-MM-DD)
const isValidDate = /^\d{4}-\d{2}-\d{2}$/.test(date);
if (!isValidDate) {
throw new Error('Invalid date format. Expected YYYY-MM-DD');
}
try {
// Fetch the booked slots for the given date
const bookedSlots = await getBookedSlots(date);
console.log('Booked slots:', bookedSlots);
// If no booked slots, all general slots are available
if (bookedSlots.length === 0) {
return generalSlots;
}
// Check if generalSlots exists and is an array
if (!Array.isArray(generalSlots) || generalSlots.length === 0) {
throw new Error('General slots are not properly defined');
}
// Filter the general slots to remove any booked slots
const availableSlots = generalSlots.filter(slot => !bookedSlots.includes(slot));
// Return the available slots
return availableSlots;
} catch (error) {
console.error('Error fetching available slots:', error.message);
throw error; // Re-throw the error after logging it
}
}
module.exports = { getAvailableSlots, getBookedSlots};