From cc6ed915c2a83557de227e4ccfabba22d8962a57 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Tue, 25 Feb 2025 10:50:06 +0530 Subject: [PATCH] low and critical low notification --- src/controllers/tanksController.js | 242 +++++++++++++++-------------- 1 file changed, 123 insertions(+), 119 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 9b3a9bef..f422b7c3 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -7154,140 +7154,144 @@ const calculateWaterLevelAndNotify = async () => { console.error("Error in water level calculation:", err); } }; +const calculateLowWaterLevelAndNotify = async () => { + try { + const now = moment(); + const currentTime = now.format("HH:mm"); // Current time in HH:mm format -// const calculateLowWaterLevelAndNotify = async () => { -// try { -// const now = moment(); -// const currentTime = now.format("HH:mm"); // Current time in HH:mm format + console.log(`Current time: ${currentTime}`); -// console.log(`Current time: ${currentTime}`); + // Get all users who have allowed notifications and have set a notification time + const users = await User.find({ lowWaterAlert: true }); -// // Get all users who have allowed notifications and have set a notification time -// const users = await User.find({ lowWaterAlert: true}); + if (users.length === 0) { + console.log("No users to notify at this time."); + return; + } -// if (users.length === 0) { -// console.log("No users to notify at this time."); -// return; -// } + for (const user of users) { + const { customerId, fcmIds } = user; -// for (const user of users) { -// const { customerId, fcmIds } = user; + if (!Array.isArray(fcmIds) || fcmIds.length === 0) { + console.log(`No valid FCM tokens for customer ID: ${customerId}`); + continue; + } -// if (!Array.isArray(fcmIds) || fcmIds.length === 0) { -// console.log(`No valid FCM tokens for customer ID: ${customerId}`); -// continue; -// } + // Get tanks associated with the user + const tanks = await Tank.find({ customerId }); -// // Get tanks associated with the user -// const tanks = await Tank.find({ customerId }); - -// for (const tank of tanks) { -// const { -// tankName, -// tankLocation, -// typeOfWater, -// capacity, -// waterlevel, -// waterlevel_at_midnight, -// } = tank; - -// // Remove commas before parsing numbers -// const tankCapacity = parseFloat(capacity.replace(/,/g, '')) || 0; -// const currentWaterLevel = parseFloat(waterlevel.replace(/,/g, '')) || 0; -// const midnightWaterLevel = parseFloat(waterlevel_at_midnight.replace(/,/g, '')) || 0; - -// if (tankCapacity === 0) { -// console.log(`Skipping tank ${tankName} due to zero capacity`); -// continue; -// } + for (const tank of tanks) { + const { + tankName, + tankLocation, + typeOfWater, + capacity, + waterlevel, + waterlevel_at_midnight, + } = tank; -// const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); -// const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel; -// const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2); + // Remove commas before parsing numbers + const tankCapacity = parseFloat(capacity.replace(/,/g, '')) || 0; + const currentWaterLevel = parseFloat(waterlevel.replace(/,/g, '')) || 0; -// let notificationBody = -// `🛢️ Tank Name: ${tankName}\n` + -// `🏢 Location: ${tankLocation}\n` + -// `💧 Type of Water: ${typeOfWater}\n` + -// `Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`; + if (tankCapacity === 0) { + console.log(`Skipping tank ${tankName} due to zero capacity`); + continue; + } -// await sendNotification(customerId, fcmIds, "Low Water Level Update", notificationBody); -// console.log("Notification sent for tank:", tankName); -// } -// } + const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); -// console.log("Water level notifications processed."); -// } catch (err) { -// console.error("Error in water level calculation:", err); -// } -// }; + // Send notification only if water level is below 15% + if (currentWaterLevelPercentage < 15) { + let notificationBody = + `🛢️ Tank Name: ${tankName}\n` + + `🏢 Location: ${tankLocation}\n` + + `💧 Type of Water: ${typeOfWater}\n` + + `Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`; -// const calculateCriticalLowWaterLevelAndNotify = async () => { -// try { -// const now = moment(); -// const currentTime = now.format("HH:mm"); // Current time in HH:mm format + await sendNotification(customerId, fcmIds, "Low Water Level Alert", notificationBody); + console.log("Notification sent for tank:", tankName); + } else { + console.log(`Skipping notification for tank ${tankName}, water level is above 15%`); + } + } + } -// console.log(`Current time: ${currentTime}`); + console.log("Water level notifications processed."); + } catch (err) { + console.error("Error in water level calculation:", err); + } +}; +const calculateCriticalLowWaterLevelAndNotify = async () => { + try { + const now = moment(); + const currentTime = now.format("HH:mm"); // Current time in HH:mm format -// // Get all users who have allowed notifications and have set a notification time -// const users = await User.find({ criticalLowWaterAlert: true}); + console.log(`Current time: ${currentTime}`); -// if (users.length === 0) { -// console.log("No users to notify at this time."); -// return; -// } + // Get all users who have allowed critical low water notifications + const users = await User.find({ criticalLowWaterAlert: true }); -// for (const user of users) { -// const { customerId, fcmIds } = user; + if (users.length === 0) { + console.log("No users to notify at this time."); + return; + } -// if (!Array.isArray(fcmIds) || fcmIds.length === 0) { -// console.log(`No valid FCM tokens for customer ID: ${customerId}`); -// continue; -// } + for (const user of users) { + const { customerId, fcmIds } = user; -// // Get tanks associated with the user -// const tanks = await Tank.find({ customerId }); - -// for (const tank of tanks) { -// const { -// tankName, -// tankLocation, -// typeOfWater, -// capacity, -// waterlevel, -// waterlevel_at_midnight, -// } = tank; - -// // Remove commas before parsing numbers -// const tankCapacity = parseFloat(capacity.replace(/,/g, '')) || 0; -// const currentWaterLevel = parseFloat(waterlevel.replace(/,/g, '')) || 0; -// const midnightWaterLevel = parseFloat(waterlevel_at_midnight.replace(/,/g, '')) || 0; - -// if (tankCapacity === 0) { -// console.log(`Skipping tank ${tankName} due to zero capacity`); -// continue; -// } + if (!Array.isArray(fcmIds) || fcmIds.length === 0) { + console.log(`No valid FCM tokens for customer ID: ${customerId}`); + continue; + } -// const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); -// const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel; -// const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2); + // Get tanks associated with the user + const tanks = await Tank.find({ customerId }); -// let notificationBody = -// `🛢️ Tank Name: ${tankName}\n` + -// `🏢 Location: ${tankLocation}\n` + -// `💧 Type of Water: ${typeOfWater}\n` + -// `Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`; + for (const tank of tanks) { + const { + tankName, + tankLocation, + typeOfWater, + capacity, + waterlevel, + } = tank; -// await sendNotification(customerId, fcmIds, "Critical Low Water Level Update", notificationBody); -// console.log("Notification sent for tank:", tankName); -// } -// } + // Remove commas before parsing numbers + const tankCapacity = parseFloat(capacity.replace(/,/g, '')) || 0; + const currentWaterLevel = parseFloat(waterlevel.replace(/,/g, '')) || 0; + + if (tankCapacity === 0) { + console.log(`Skipping tank ${tankName} due to zero capacity`); + continue; + } + + const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); + + // Send notification only if water level is below 10% + if (currentWaterLevelPercentage < 10) { + let notificationBody = + `🚨 *Critical Low Water Alert!*\n\n` + + `🛢️ *Tank Name:* ${tankName}\n` + + `🏢 *Location:* ${tankLocation}\n` + + `💧 *Type of Water:* ${typeOfWater}\n` + + `🔴 *Current Water Level:* ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n\n` + + `⚠️ Immediate action is recommended to avoid water shortage.`; + + await sendNotification(customerId, fcmIds, "Critical Low Water Level Alert", notificationBody); + console.log(`Critical low water level notification sent for tank: ${tankName}`); + } else { + console.log(`Skipping tank ${tankName}, water level is above 10%`); + } + } + } + + console.log("Critical low water level notifications processed."); + } catch (err) { + console.error("Error in critical water level calculation:", err); + } +}; -// console.log("Water level notifications processed."); -// } catch (err) { -// console.error("Error in water level calculation:", err); -// } -// }; // Run the function every minute to check if any user needs a notification @@ -7299,13 +7303,13 @@ cron.schedule('* * * * *', async () => { }); //run the every one hour -// cron.schedule('0 * * * *', async () => { -// console.log("Checking for user notification times..."); -// await calculateLowWaterLevelAndNotify(); -// await calculateCriticalLowWaterLevelAndNotify(); -// }, { -// timezone: "Asia/Kolkata", -// }); +cron.schedule('0 * * * *', async () => { + console.log("Checking for user notification times..."); + await calculateLowWaterLevelAndNotify(); + await calculateCriticalLowWaterLevelAndNotify(); +}, { + timezone: "Asia/Kolkata", +}); // Schedule notifications at 6 AM, 12 PM, 6 PM, and 12 AM // cron.schedule(