diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 82b0d8fc..2f86acf4 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2105,61 +2105,87 @@ eventEmitter.on('sendThresholdTimeNotification', async (fcmTokens, message) => { // ); eventEmitter.on( - 'sendMotorStartNotification', + "sendMotorStartNotification", async ( + customerId, fcmTokens, + waterLevel, blockName, tankName, motorOnType, stopCriteria, typeOfWater, - highThreshold // Add the high threshold as a parameter + manualThresholdTime ) => { try { // Get the latest timestamp const currentDateTime = new Date(); - const startTime = currentDateTime.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }); - const formattedDate = currentDateTime.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata' }); - const formattedTime = currentDateTime.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata' }); + const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" }); + const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); - // Retrieve the user information - const users = await User.find({ fcmIds: { $in: fcmTokens } }); - const userNames = users.map(user => user.username).join(', '); + // 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" + const startMethod = motorOnType === "forced_manual" ? "Physically" : "Manually"; - // Dynamically generate the motor name + // Generate the motor name dynamically const motorName = `${tankName}-${blockName}-${typeOfWater}`; - // Determine the stop condition message + // Determine stop condition message let stopConditionMessage = ""; if (stopCriteria === "manual") { - stopConditionMessage = `Will stop at Manually \n`; - } else if (stopCriteria === "highThreshold") { - stopConditionMessage = `🚨 Pump will stop when the water level reaches the high threshold of ${highThreshold}%.\n`; + stopConditionMessage = `âš ī¸ Pump will stop **manually**.\n`; + } else if (stopCriteria === "threshold") { + stopConditionMessage = `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.\n`; } // Prepare the notification message const message = - `🚰 Motor Name: ${motorName}\n` + - `đŸ›ĸī¸ Tank Name: '${tankName}'\n` + - `đŸĸ Block Name: '${blockName}'\n` + - `👤 Started by: ${userNames}\n` + - `📱 Mode: '${startMethod}'\n` + - `🕒 Pump started at: ${startTime} \n` + - stopConditionMessage; // Add only the relevant stop condition + `🚰 **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; // Send the notification - await sendNotification(fcmTokens, 'Motor Started 🚀', message); - console.log('Motor start notification with stop criteria sent successfully!'); + await sendNotification(customerId, validTokens, "Motor Started 🚀", message); + + console.log(`Motor start notification sent successfully to customer ID: ${customerId}`); + } catch (error) { - console.error('Error in sendMotorStartNotification event:', error); + console.error(`Error in sendMotorStartNotification event for customer ID: ${customerId}`, error); } } ); + // eventEmitter.on( // 'sendMotorStartNotification', // async (fcmTokens, motorId, waterLevel, blockName, tankName, motorOnType, stopCriteria, manual_threshold_time, typeOfWater) => { @@ -2203,84 +2229,59 @@ eventEmitter.on( // ); -// eventEmitter.on( -// 'sendMotorStopNotification', -// async (fcmTokens, motorId, waterLevel, blockName, tankName, motorOnType) => { -// try { -// // Get the latest timestamp -// const stopTime = new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }); - -// // Retrieve the user information -// const users = await User.find({ fcmIds: { $in: fcmTokens } }); -// const userNames = users.map(user => user.username).join(', '); -// const stopMethod = motorOnType.toUpperCase() === "Forced Manual"; - -// // Prepare the message -// const message = -// `🚰 Tank Name: '${tankName}'\n` + -// `🕒 Pump stopped at: '${stopTime}'\n` + -// `👤 Initiated by: ${userNames}\n` + -// `🔄 Pump stopped by: '${stopMethod}'\n`; - -// // Send the notification -// await sendNotification(fcmTokens, 'Motor Stopped 🛑', message); -// console.log('Motor stop notification sent successfully!'); -// } catch (error) { -// console.error('Error in sendMotorStopNotification event:', error); -// } -// } -// ); - eventEmitter.on( - 'sendMotorStopNotification', - async ( - fcmTokens, - blockName, - tankName, - motorOnType, - typeOfWater - ) => { + "sendMotorStopNotification", + async (customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType,typeOfWater) => { try { // Get the latest timestamp const currentDateTime = new Date(); - const stopTime = currentDateTime.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }); - const formattedDate = currentDateTime.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata' }); - const formattedTime = currentDateTime.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata' }); + const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" }); + const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" }); - // Retrieve the user information - const users = await User.find({ fcmIds: { $in: fcmTokens } }); - const userNames = users.map(user => user.username).join(', '); + // 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(", "); - // Determine the pump stop method - const stopMethod = motorOnType === "Forced Manual" ? "Physically" : "Manually"; + // Filter valid FCM tokens for the specific customer + const validTokens = users.flatMap(user => user.fcmIds).filter(token => fcmTokens.includes(token)); - // Dynamically generate the motor name + if (validTokens.length === 0) { + console.log(`No valid FCM tokens found for customer ID: ${customerId}`); + return; + } + + // Generate the motor name dynamically const motorName = `${tankName}-${blockName}-${typeOfWater}`; - // Determine the stop condition message - let stopConditionMessage = ""; - if (stopCriteria === "manual") { - stopConditionMessage = `Stopped at Manually \n`; - } else if (stopCriteria === "highThreshold") { - stopConditionMessage = `🚨 Pump will stop when the water level reaches the high threshold of ${highThreshold}%.\n`; - } + // Prepare the notification message const message = - `🚰 Motor Name: ${motorName}\n` + - `đŸ›ĸī¸ Tank Name: '${tankName}'\n` + - `đŸĸ Block Name: '${blockName}'\n` + - `📱 Mode: '${stopMethod}'\n` + - `🕒 Pump stopped at: ${stopTime}\n` + - stopConditionMessage; + `âšī¸ **Motor Stopped** 🛑\n` + + `🔹 **Motor Name:** ${motorName}\n` + + `đŸ›ĸī¸ **Tank Name:** ${tankName}\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(fcmTokens, 'Motor Stopped 🛑', message); - console.log('Motor stop notification sent successfully!'); + await sendNotification(customerId, validTokens, "Motor Stopped 🛑", message); + + console.log(`Motor stop notification sent successfully to customer ID: ${customerId}`); + } catch (error) { - console.error('Error in sendMotorStopNotification event:', error); + console.error(`Error in sendMotorStopNotification event for customer ID: ${customerId}`, error); } } ); + // eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => { // const notificationMessage = `Warning: Water level is low in the tank. // Tank Name: ${tankName}, @@ -6257,139 +6258,105 @@ client.on('message', async (topic, message) => { if (topic === 'water/iot-data') { try { const data = JSON.parse(message.toString()); - const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format + const { hw_Id, Motor_status, tanks } = data.objects; - // Get the current date and time in the required format const currentDate = new Date(); - const date = currentDate.toISOString(); // ISO string for date - const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS' - - // Create array of tank documents with current date and time - const tankDocuments = tanks.map(tank => ({ - tankhardwareId: tank.Id, // Updated to match the new format - tankHeight: tank.level, // Updated to match the new format - date, - time - })); - - - - // Save IoT data for the received tanks - const iotTankData = new IotData({ - hardwareId: hw_Id, // Updated variable name - Motor_status, - tanks: tankDocuments, - date, - time - }); - await iotTankData.save(); - - // Delete excess records (keep only the latest three records) - const recordsToKeep = 3; - const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name - .sort({ date: -1, time: -1 }) - .skip(recordsToKeep); - - for (const record of recordsToDelete) { - await record.remove(); - } + const date = currentDate.toISOString(); + const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Process each tank to update water level and connections for (const tank of tanks) { - const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format - // Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId - const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name + const { Id: tankhardwareId, level: tankHeight } = tank; + const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); + if (!existingTank) continue; const customerId = existingTank.customerId; - const tank_name = existingTank.tankName; + const tankName = existingTank.tankName; + + // 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 + + if (!fcmTokens.length) { + console.log(`No valid FCM tokens found for customer ID: ${customerId}`); + } - // Calculate water level using tank height and capacity - const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm + // Calculate water level + const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); const waterLevelHeight = tank_height - tankHeight; const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); + const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); - const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level - - // Update water level in the existing tank - console.log(tankHeight,"this is located in tank controllers at iot-data mqtt sub ") - if (tankHeight>0 && waterLevel >= 0) { + if (tankHeight > 0 && waterLevel >= 0) { existingTank.waterlevel = waterLevel; await existingTank.save(); - - // Update linked tanks (input/output connections) - for (const outputConnection of existingTank.connections.outputConnections) { - const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type }); - if (linkedTank) { - for (const inputConnection of linkedTank.connections.inputConnections) { - if (inputConnection.inputConnections === tank_name) { - inputConnection.water_level = waterLevel; // Update water level for linked tank - await linkedTank.save(); // Save updated linked tank - } - } - } - } } } - // Update motor status + // Motor Status Processing const status = Motor_status; - const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name + const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); if (!motorTank) { console.log('Motor not found for the specified motor_id'); return; } - // Find the inputConnection for the motor and update motor status - const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name - const user = await User.findOne({ customerId: motorTank.customerId }); // Fetch user by customerId - const allowNotifications = user?.manualStartAndStopNotify ?? true; // Default to true if not set + const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); + const user = await User.findOne({ customerId: motorTank.customerId }); + const allowNotifications = user?.manualStartAndStopNotify ?? true; if (inputConnection) { - inputConnection.motor_status = status; // Update motor status + inputConnection.motor_status = status; const tankName = motorTank.tankName; + 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'); + 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; - eventEmitter.emit( - "sendMotorStartNotification", - fcmToken, // 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 - "threshold", // Stop criteria - manual_threshold_time // Threshold time in mins - ); + // 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) + ); + } - + if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) { - const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); + const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); inputConnection.motor_stop_status = "1"; inputConnection.stopTime = currentTime; eventEmitter.emit( "sendMotorStopNotification", - fcmToken, // FCM tokens + 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 + inputConnection.water_level || 0, + motorTank.blockName || "N/A", + tankName, + inputConnection.motor_on_type ); } - - await motorTank.save(); // Save the updated tank - } - console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name + await motorTank.save(); + } + console.log('Data processed successfully for hardwareId:', hw_Id); } catch (err) { console.error('Error processing message:', err.message); }