From 5b2c4aac477f8826ef69efcac1ae65b4fc0333d1 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Fri, 21 Feb 2025 16:58:45 +0530 Subject: [PATCH] daily based notifications --- src/controllers/tanksController.js | 116 ++++++++++++++++------------- src/routes/tanksRoute.js | 24 ++---- 2 files changed, 70 insertions(+), 70 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 91a9e0e6..c77cc39f 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -6908,27 +6908,23 @@ const calculateConsumptionAndNotify = async () => { exports.sendUserSetNotifications = async (request, reply) => { - const { customerId, notificationTime } = request.body; + const { customerId, notificationTime, allowNotifications } = request.body; try { const user = await User.findOneAndUpdate( { customerId }, - { notificationTime }, - { new: true, upsert: true } // Create if not exists + { notificationTime, allowNotifications }, + { new: true, upsert: true } // Create user if not exists ); - await calculateWaterLevelAndNotify(); // This will only notify if notifications are allowed - // Optionally, call the notification calculation function after setting the time - // if (allowNotifications) { - // await calculateWaterLevelAndNotify(); // This will only notify if notifications are allowed - // } + console.log(`User ${customerId} updated: Notification Time - ${notificationTime}, Allowed - ${allowNotifications}`); return reply.send({ success: true, user }); } catch (error) { console.error("Error setting notification time:", error); return reply.status(500).send({ success: false, message: "Internal server error" }); } -} +}; // const calculateWaterLevelAndNotify = async () => { // try { @@ -6984,6 +6980,7 @@ exports.sendUserSetNotifications = async (request, reply) => { // console.error("Error in water level calculation:", err); // } // }; + const calculateWaterLevelAndNotify = async () => { try { const now = moment(); @@ -6991,51 +6988,57 @@ const calculateWaterLevelAndNotify = async () => { console.log(`Current time: ${currentTime}`); - // Get all users who have allowed notifications - const users = await User.find({ }); + // Get all users who have allowed notifications and have set a notification time + const users = await User.find({ allowNotifications: true, notificationTime: currentTime }); + + if (users.length === 0) { + console.log("No users to notify at this time."); + return; + } - // Iterate over each user for (const user of users) { - const { customerId, notificationTime, fcmIds } = user; + const { customerId, fcmIds } = user; - // Check if the user's notification time matches the current time - if (currentTime === notificationTime) { - // Get tanks associated with the user - const tanks = await Tank.find({ customerId }); + if (!Array.isArray(fcmIds) || fcmIds.length === 0) { + console.log(`No valid FCM tokens for customer ID: ${customerId}`); + continue; + } - 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; - } + // Get tanks associated with the user + const tanks = await Tank.find({ customerId }); - const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); - const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel; - const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2); + 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; + } - let notificationBody = - `🛢️ Tank Name: ${tankName}\n` + - `🏢 Location: ${tankLocation}\n` + - `💧 Type of Water: ${typeOfWater}\n` + - `Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`; + const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); + const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel; + const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2); - await sendNotification(customerId, fcmIds, "Water Level Update", notificationBody); - console.log("Notification sent for tank:", tankName); - } + let notificationBody = + `🛢️ Tank Name: ${tankName}\n` + + `🏢 Location: ${tankLocation}\n` + + `💧 Type of Water: ${typeOfWater}\n` + + `Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`; + + await sendNotification(customerId, fcmIds, "Water Level Update", notificationBody); + console.log("Notification sent for tank:", tankName); } } @@ -7045,6 +7048,13 @@ const calculateWaterLevelAndNotify = async () => { } }; +// Run the function every minute to check if any user needs a notification +cron.schedule('* * * * *', async () => { + console.log("Checking for user notification times..."); + await calculateWaterLevelAndNotify(); +}, { + timezone: "Asia/Kolkata", +}); @@ -7062,12 +7072,12 @@ const calculateWaterLevelAndNotify = async () => { // ); // Schedule a function to run every minute -cron.schedule('* * * * *', async () => { - console.log("Checking for user notification times..."); - await calculateWaterLevelAndNotify(); -}, { - timezone: "Asia/Kolkata", // Specify the timezone -}); +// cron.schedule('* * * * *', async () => { +// console.log("Checking for user notification times..."); +// await calculateWaterLevelAndNotify(); +// }, { +// timezone: "Asia/Kolkata", // Specify the timezone +// }); // const updateStopTimeFormat = async () => { // try { diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 41bfde44..1e4611d5 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -1328,31 +1328,21 @@ module.exports = function (fastify, opts, next) { url: "/api/sendNotificationDaily", schema: { tags: ["Tank"], - summary: "This is for time based notification", + summary: "This is for time-based notification", body: { type: "object", properties: { - customerId: { - type: "string", - - }, - notificationTime: { - type: "string", - }, - // allowNotifications: { - // type: "boolean" - // } + customerId: { type: "string" }, + notificationTime: { type: "string" }, + allowNotifications: { type: "boolean" }, }, + required: ["customerId", "notificationTime", "allowNotifications"], // Ensures all fields are required }, - security: [ - { - basicAuth: [], - }, - ], + security: [{ basicAuth: [] }], }, - //preHandler: fastify.auth([fastify.authenticate]), handler: tanksController.sendUserSetNotifications, }); + fastify.route({ method: "POST",