From dd70847b0481c4438000a70720c944fa45e010cd Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Fri, 28 Feb 2025 12:40:48 +0530 Subject: [PATCH] manual notification --- src/controllers/tanksController.js | 261 ++++++++++++++--------------- 1 file changed, 124 insertions(+), 137 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index c4a0e7cc..d137eade 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2104,85 +2104,37 @@ eventEmitter.on('sendThresholdTimeNotification', async (fcmTokens, message) => { // } // ); -eventEmitter.on( - "sendMotorStartNotification", - async ( - customerId, - fcmTokens, - waterLevel, - blockName, - tankName, - motorOnType, - stopCriteria, - typeOfWater, - manualThresholdTime - ) => { - try { - // Get the latest timestamp - const currentDateTime = new Date(); - const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" }); - const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); - - // Fetch users based on the customerId - const users = await User.find({ customerId }).select("username fcmIds notificationPreference lastNotificationSent"); - - if (!users || users.length === 0) { - console.log(`No users found for customer ID: ${customerId}`); - return; - } - - const userNames = users.map(user => user.username).join(", "); - - // Filter valid FCM tokens for the specific customer - const validTokens = users.flatMap(user => user.fcmIds).filter(token => fcmTokens.includes(token)); - - if (validTokens.length === 0) { - console.log(`No valid FCM tokens found for customer ID: ${customerId}`); - return; - } - - // Check if the motor was started manually (forced manual) - if (motorOnType !== "forced_manual") { - console.log(`Skipping notification: Motor was started in ${motorOnType} mode.`); - return; - } - - // Determine the pump initiation method - const startMethod = motorOnType === "forced_manual" ? "Physically" : "Manually"; - - // Generate the motor name dynamically - const motorName = `${tankName}-${blockName}-${typeOfWater}`; +// eventEmitter.on( +// "sendMotorStartNotification", +// async (hw_Id, fcmTokens, waterLevel, blockName, tankName, motorOnType, stopCriteria, typeOfWater, manualThresholdTime) => { +// try { +// const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); - // Determine stop condition message - let stopConditionMessage = ""; - if (stopCriteria === "manual") { - stopConditionMessage = `âš ī¸ Pump will stop **manually**.\n`; - } else if (stopCriteria === "threshold") { - stopConditionMessage = `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.\n`; - } +// if (motorOnType !== "forced_manual") { +// console.log(`Skipping notification: Motor was started in ${motorOnType} mode.`); +// return; +// } - // Prepare the notification message - const message = - `🚰 **Motor Started** 🚀\n` + - `🔹 **Motor Name:** ${motorName}\n` + - `đŸ›ĸī¸ **Tank Name:** ${tankName}\n` + - `đŸĸ **Block Name:** ${blockName}\n` + - `💧 **Water Level:** ${waterLevel}%\n` + - `👤 **Started by:** ${userNames}\n` + - `📱 **Mode:** ${startMethod}\n` + - `🕒 **Pump started at:** ${formattedTime}\n` + - stopConditionMessage; +// const stopConditionMessage = stopCriteria === "manual" +// ? `âš ī¸ Pump will stop **manually**.` +// : `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.`; - // Send the notification - await sendNotification(customerId, validTokens, "Motor Started 🚀", message); +// const message = `🚰 **Motor Started** 🚀\n` + +// `🔹 **Motor Name:** ${tankName}-${blockName}-${typeOfWater}\n` + +// `đŸĸ **Block Name:** ${blockName}\n` + +// `💧 **Water Level:** ${waterLevel}%\n` + +// `📱 **Mode:** Physically Started\n` + +// `🕒 **Pump started at:** ${formattedTime}\n` + +// stopConditionMessage; - console.log(`Motor start notification sent successfully to customer ID: ${customerId}`); +// await sendNotification(hw_Id, fcmTokens, "Motor Started 🚀", message); +// console.log(`✅ Motor start notification sent for Motor ID: ${hw_Id}`); - } catch (error) { - console.error(`Error in sendMotorStartNotification event for customer ID: ${customerId}`, error); - } - } -); +// } catch (error) { +// console.error(`❌ Error in sendMotorStartNotification for Motor ID: ${hw_Id}`, error); +// } +// } +// ); @@ -2229,58 +2181,86 @@ eventEmitter.on( // ); -eventEmitter.on( - "sendMotorStopNotification", - async (customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType,typeOfWater) => { - try { - // Get the latest timestamp - const currentDateTime = new Date(); - const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" }); - const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); +// eventEmitter.on( +// "sendMotorStopNotification", +// async (hw_Id, fcmTokens, waterLevel, blockName, tankName, motorOnType, typeOfWater) => { +// try { +// const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); - // Fetch users based on the customerId - const users = await User.find({ customerId }).select("username fcmIds notificationPreference lastNotificationSent"); +// const message = `âšī¸ **Motor Stopped** 🛑\n` + +// `🔹 **Motor Name:** ${tankName}-${blockName}-${typeOfWater}\n` + +// `đŸĸ **Block Name:** ${blockName}\n` + +// `💧 **Water Level:** ${waterLevel}%\n` + +// `📱 **Mode:** Forced Manual\n` + +// `🕒 **Pump stopped at:** ${formattedTime}`; - if (!users || users.length === 0) { - console.log(`No users found for customer ID: ${customerId}`); - return; - } +// await sendNotification(hw_Id, fcmTokens, "Motor Stopped 🛑", message); +// console.log(`✅ Motor stop notification sent for Motor ID: ${hw_Id}`); - const userNames = users.map(user => user.username).join(", "); +// } catch (error) { +// console.error(`❌ Error in sendMotorStopNotification for Motor ID: ${hw_Id}`, error); +// } +// } +// ); - // Filter valid FCM tokens for the specific customer - const validTokens = users.flatMap(user => user.fcmIds).filter(token => fcmTokens.includes(token)); - if (validTokens.length === 0) { - console.log(`No valid FCM tokens found for customer ID: ${customerId}`); +// 🚀 Motor Start Notification +eventEmitter.on( + "sendMotorStartNotification", + async (hw_Id, customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType, stopCriteria, typeOfWater, manualThresholdTime) => { + try { + const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); + + if (motorOnType !== "forced_manual") { + console.log(`âš ī¸ Skipping notification: Motor was started in **${motorOnType}** mode.`); return; } - // Generate the motor name dynamically - const motorName = `${tankName}-${blockName}-${typeOfWater}`; + const stopConditionMessage = stopCriteria === "manual" + ? `âš ī¸ Pump will stop **manually**.` + : `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.`; - // Prepare the notification message - const message = - `âšī¸ **Motor Stopped** 🛑\n` + - `🔹 **Motor Name:** ${motorName}\n` + - `đŸ›ĸī¸ **Tank Name:** ${tankName}\n` + + const message = `🚰 **Motor Started** 🚀\n` + + `👤 **Customer ID:** ${customerId}\n` + + `🔹 **Motor Name:** ${tankName} - ${blockName} - ${typeOfWater}\n` + `đŸĸ **Block Name:** ${blockName}\n` + `💧 **Water Level:** ${waterLevel}%\n` + - `👤 **Stopped by:** ${userNames}\n` + - `📱 **Mode:** ${motorOnType}\n` + - `🕒 **Pump stopped at:** ${formattedTime}\n`; - - // Send the notification - await sendNotification(customerId, validTokens, "Motor Stopped 🛑", message); + `📱 **Mode:** **Physically Started**\n` + + `🕒 **Pump started at:** ${formattedTime}\n` + + stopConditionMessage; - console.log(`Motor stop notification sent successfully to customer ID: ${customerId}`); + await sendNotification(hw_Id, customerId, fcmTokens, "Motor Started 🚀", message); + console.log(`✅ Motor start notification sent for Customer ID: ${customerId}`); } catch (error) { - console.error(`Error in sendMotorStopNotification event for customer ID: ${customerId}`, error); + console.error(`❌ Error in sendMotorStartNotification for Customer ID: ${customerId}`, error); } } ); +// 🛑 Motor Stop Notification +eventEmitter.on( + "sendMotorStopNotification", + async (hw_Id, customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType, typeOfWater) => { + try { + const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); + + const message = `🛑 **Motor Stopped** ❌\n` + + `👤 **Customer ID:** ${customerId}\n` + + `🔹 **Motor Name:** ${tankName} - ${blockName} - ${typeOfWater}\n` + + `đŸĸ **Block Name:** ${blockName}\n` + + `💧 **Water Level:** ${waterLevel}%\n` + + `📱 **Mode:** **Physically Stopped**\n` + + `🕒 **Pump stopped at:** ${formattedTime}`; + + await sendNotification(hw_Id, customerId, fcmTokens, "Motor Stopped ❌", message); + console.log(`✅ Motor stop notification sent for Customer ID: ${customerId}`); + + } catch (error) { + console.error(`❌ Error in sendMotorStopNotification for Customer ID: ${customerId}`, error); + } + } +); // eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => { // const notificationMessage = `Warning: Water level is low in the tank. @@ -6358,7 +6338,7 @@ client.on('connect', () => { // Handling incoming MQTT messages client.on('message', async (topic, message) => { - console.log(`Message received on topic ${topic}:`, message.toString()); + console.log(`📩 Message received on topic ${topic}:`, message.toString()); if (topic === 'water/iot-data') { try { @@ -6369,7 +6349,7 @@ client.on('message', async (topic, message) => { const date = currentDate.toISOString(); const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); - // Process each tank to update water level and connections + // Process each tank to update water level for (const tank of tanks) { const { Id: tankhardwareId, level: tankHeight } = tank; const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); @@ -6381,10 +6361,10 @@ client.on('message', async (topic, message) => { // Fetch FCM tokens of users linked to this customer const users = await User.find({ customerId }).select("fcmIds"); - const fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token); // Get valid FCM tokens + const fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token); if (!fcmTokens.length) { - console.log(`No valid FCM tokens found for customer ID: ${customerId}`); + console.log(`âš ī¸ No valid FCM tokens found for Customer ID: ${customerId}`); } // Calculate water level @@ -6400,12 +6380,12 @@ client.on('message', async (topic, message) => { } } - // Motor Status Processing + // 🔹 Motor Status Processing const status = Motor_status; const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); if (!motorTank) { - console.log('Motor not found for the specified motor_id'); + console.log(`âš ī¸ Motor not found for motor_id: ${hw_Id}`); return; } @@ -6416,61 +6396,68 @@ client.on('message', async (topic, message) => { if (inputConnection) { inputConnection.motor_status = status; const tankName = motorTank.tankName; + const blockName = motorTank.blockName || "N/A"; + // ✅ Motor Start Notification if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") { const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); inputConnection.motor_stop_status = "2"; inputConnection.motor_on_type = "forced_manual"; inputConnection.startTime = currentTime; - // // Determine stop criteria dynamically - const stopCriteria = inputConnection.motor_stop_status === "1" ? "manual" : "threshold"; - - eventEmitter.emit( - "sendMotorStartNotification", - customerId, // Pass customerId - fcmTokens, // Pass FCM tokens - hw_Id, // Motor ID - inputConnection.water_level || 0, // Water level - motorTank.blockName || "N/A", // Block name - tankName, // Tank name - inputConnection.motor_on_type, // Motor on type - stopCriteria, // Stop criteria (manual/threshold) - manual_threshold_time // Threshold time (only used for threshold stop) - ); + console.log(`🚀 Motor started in FORCED_MANUAL mode.`); + // Determine stop criteria + const stopCriteria = inputConnection.motor_stop_status === "1" ? "manual" : "threshold"; + + eventEmitter.emit( + "sendMotorStartNotification", + hw_Id, // Motor ID + customerId, // Customer ID + fcmTokens, // Valid tokens + inputConnection.water_level || 0, + blockName, + tankName, + "forced_manual", // Forced manual start + stopCriteria, + inputConnection.typeOfWater, + inputConnection.manual_threshold_time + ); } + // 🛑 Motor Stop Notification if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) { const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); inputConnection.motor_stop_status = "1"; inputConnection.stopTime = currentTime; + console.log(`🛑 Motor stopped manually.`); + eventEmitter.emit( "sendMotorStopNotification", - customerId, // Pass customerId - fcmTokens, // Pass FCM tokens - hw_Id, // Motor ID + hw_Id, // Motor ID + customerId, // Customer ID + fcmTokens, // Valid tokens inputConnection.water_level || 0, - motorTank.blockName || "N/A", + blockName, tankName, - inputConnection.motor_on_type + "forced_manual", // Forced manual stop + inputConnection.typeOfWater ); } await motorTank.save(); } - console.log('Data processed successfully for hardwareId:', hw_Id); + console.log(`✅ Data processed successfully for hardwareId: ${hw_Id}`); } catch (err) { - console.error('Error processing message:', err.message); + console.error(`❌ Error processing message: ${err.message}`); } } }); - exports.getPendingAndCompletedsurveyOfparticularInstaller = async (request, reply) => { try { const { installationId } = request.params;