diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 8487c018..bec633d9 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1595,25 +1595,64 @@ admin.initializeApp({ // await sendNotification(fcmTokens, 'Motor Started', `Motor ID: ${motorId} started successfully at ${timestamp}. Current Water Level: ${waterLevel} Ltrs`); // }); +// eventEmitter.on( +// 'motorStart', +// async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName, startTime, motorOnType, stopCriteria, manual_threshold_time) => { +// try { +// // Retrieve the user information +// const users = await User.find({ fcmIds: { $in: fcmTokens } }); +// console.log("users", users); +// const userNames = users.map(user => user.username).join(', '); +// console.log("userNames", userNames); +// const startMethod = motorOnType === "APP" ? "via the App" : "Manual"; + +// // Prepare the message +// const message = +// `🚰 Tank Name: '${tankName}'\n` + +// `🕒 Pump started at: '${startTime}'\n` + +// `👤 Started by : ${userNames}\n` + +// // `Pump started by: '${motorOnType.toUpperCase()}'\n` + +// `Mode : '${startMethod}'\n` + +// `Will stop at after: '${manual_threshold_time}' mins`; + +// // Send the notification +// await sendNotification(fcmTokens, 'Arminta Water Management', message); +// } catch (error) { +// console.error('Error in motorStart event:', error); +// } +// } +// ); + +// Event listener for motorStart eventEmitter.on( 'motorStart', - async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName, startTime, motorOnType, stopCriteria, manual_threshold_time) => { + async (fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => { try { // Retrieve the user information const users = await User.find({ fcmIds: { $in: fcmTokens } }); console.log("users", users); const userNames = users.map(user => user.username).join(', '); console.log("userNames", userNames); - const startMethod = motorOnType === "APP" ? "via the App" : "Manual"; + + const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual"; + + // Generate motor name dynamically based on tank name, block name, and type of water + const motorName = `${tankName}-${blockName}-${typeOfWater}`; + + // Get current date and time for the motor start time + const currentDateTime = new Date(); + const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed + const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed // Prepare the message const message = + `🚰 Motor Name: ${motorName}\n` + `🚰 Tank Name: '${tankName}'\n` + - `🕒 Pump started at: '${startTime}'\n` + - `👤 Initiated by : ${userNames}\n` + - // `Pump started by: '${motorOnType.toUpperCase()}'\n` + - `🔄 Pump started by: '${startMethod}'\n` + - `Will stop at after: '${manual_threshold_time}' mins`; + `🚰 Block Name: '${blockName}'\n` + + `👤 Started by: ${userNames}\n` + + `📱 Mode: '${startMethod}'\n` + + `🕒 Pump started at: ${startTime} (Time: ${formattedTime} on ${formattedDate})\n` + + `Will stop after: '${manual_threshold_time}' mins`; // Send the notification await sendNotification(fcmTokens, 'Arminta Water Management', message); @@ -1623,33 +1662,71 @@ eventEmitter.on( } ); +// Event listener for motorStop +eventEmitter.on( + 'motorStop', + async (fcmTokens, tankName, blockName, stopTime, motorOnType, totalWaterPumped, typeOfWater) => { + try { + // Retrieve the user information + const users = await User.find({ fcmIds: { $in: fcmTokens } }); + const userNames = users.map(user => user.username).join(', '); + + const stopMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual"; -eventEmitter.on('motorStop', async (fcmTokens, tankName,stopTime, motorOnType) => { - try { - // Retrieve the user information - const users = await User.find({ fcmIds: { $in: fcmTokens } }); - console.log("users",users) - const userNames = users.map(user => user.username).join(', '); - console.log("userNames",userNames) - - const stopMethod = motorOnType === "APP" ? "via the App" : "manual"; - - // Prepare the message - // const message = `Tank Name: '${tankName}', Pump stopped at '${stopTime}' by Initiated by user(s): ${userNames} '${motorOnType}'`; - const message = - `🚰 Tank Name: '${tankName}'\n` + - `🕒 Pump stopped at: '${stopTime}'\n` + - `👤 Initiated by : ${userNames}\n` + - // `Motor Off Type: '${motorOnType}'`; - `Motor Off Type: '${stopMethod}'`; + // Generate motor name dynamically based on tank name, block name, and type of water + const motorName = `${tankName}-${blockName}-${typeOfWater}`; - - // Send the notification - await sendNotification(fcmTokens, 'Arminta Water Management', message); - } catch (error) { - console.error('Error in motorStart event:', error); + // Get current date and time for the motor stop time + const currentDateTime = new Date(); + const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed + const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed + + // Prepare the message + const message = + `🚰 Motor Name: ${motorName}\n` + + `🚰 Tank Name: '${tankName}'\n` + + `🚰 Block Name: '${blockName}'\n` + + `👤 Stopped by: ${userNames}\n` + + `📱 Mode: '${stopMethod}'\n` + + `🕒 Pump stopped at: ${stopTime} (Time: ${formattedTime} on ${formattedDate})\n` + + `💧 Total water pumped: ${totalWaterPumped} liters\n`; // Ensure this line is properly terminated + + // Send the notification + await sendNotification(fcmTokens, 'Arminta Water Management', message); + } catch (error) { + console.error('Error in motorStop event:', error); + } } -}); +); + + + +// eventEmitter.on('motorStop', async (fcmTokens, tankName,stopTime, motorOnType) => { +// try { +// // Retrieve the user information +// const users = await User.find({ fcmIds: { $in: fcmTokens } }); +// console.log("users",users) +// const userNames = users.map(user => user.username).join(', '); +// console.log("userNames",userNames) + +// const stopMethod = motorOnType === "Mobile APP" ? "via the App" : "manual"; + +// // Prepare the message +// // const message = `Tank Name: '${tankName}', Pump stopped at '${stopTime}' by Initiated by user(s): ${userNames} '${motorOnType}'`; +// const message = +// `🚰 Tank Name: '${tankName}'\n` + +// `🕒 Pump stopped at: '${stopTime}'\n` + +// `👤 Initiated by : ${userNames}\n` + +// // `Motor Off Type: '${motorOnType}'`; +// `Motor Off Type: '${stopMethod}'`; + + +// // Send the notification +// await sendNotification(fcmTokens, 'Arminta Water Management', message); +// } catch (error) { +// console.error('Error in motorStart event:', error); +// } +// }); // Emit motor stop event with motorId // eventEmitter.on('motorStop', async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName,stopTime,motorOnType) => { @@ -2314,6 +2391,17 @@ const monitorWaterLevels = async () => { setInterval(monitorWaterLevels, 30 * 60 * 1000); const motorIntervals = {}; +async function calculateTotalPumpedWater(customerId, motorId, start_instance_id) { + const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id }); + if (motorData) { + const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() }); + const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel, 10); + const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10); + const waterPumpedTillNow = parseInt(receiverTank.total_water_added_from_midnight, 10); + return quantityDelivered + waterPumpedTillNow; // Total water pumped + } + return 0; // Return 0 if no data found +} exports.motorAction = async (req, reply) => { try { const customerId = req.params.customerId; @@ -2340,7 +2428,8 @@ exports.motorAction = async (req, reply) => { console.log(receiverTank) const currentWaterLevel = parseInt(receiverTank.waterlevel, 10); const waterLevelThresholds = { low: 30, veryLow: 20, criticallyLow: 10 }; - + const typeOfWater = receiverTank.typeOfWater; + console.log(typeOfWater,"typeOfWater") // Determine the motor stop status based on the action let motorStopStatus; @@ -2362,39 +2451,25 @@ exports.motorAction = async (req, reply) => { ); const thresholdTimeMs = req.body.manual_threshold_time * 60 * 1000; // Convert minutes to milliseconds - const stopCriteria = + const stopCriteria = motorOnType === "time" ? `${req.body.manual_threshold_time} minutes` : `${req.body.manual_threshold_litres} litres`; await checkWaterLevelsAndNotify(customerId, tankName, receiverTank.tankLocation, fcmToken); - - // eventEmitter.emit( - // "motorStart", - // fcmToken, - // new Date().toISOString(), - // motorId, - // currentWaterLevel, - // blockName, // Block Name - // tankName, // Tank Name - // startTime, - // motorOnType, - // stopCriteria, - // manual_threshold_time - // ); + if (!notificationSentStatus.motorStart) { eventEmitter.emit( - "motorStart", - fcmToken, - new Date().toISOString(), - motorId, - currentWaterLevel, - blockName, - tankName, - startTime, - "APP", - manual_threshold_time + 'motorStart', + fcmToken, + tankName, + blockName, + startTime, + "Mobile APP", + manual_threshold_time, + typeOfWater ); + notificationSentStatus.motorStart = true; // Set flag to true to prevent duplicate notifications } await Tank.updateOne( @@ -2405,17 +2480,6 @@ exports.motorAction = async (req, reply) => { "connections.inputConnections.$.motor_on_type": motorOnType } } ); - // await Tank.updateOne( - // { customerId, "connections.inputConnections.motor_id": motorId }, - // { - // $set: { - // "connections.inputConnections.$.motor_stop_status": "2", - // "connections.inputConnections.$.motor_on_type": "manual", - // } - // } - // ); - - reply.code(200).send({ message: "Motor started successfully." }); } else if (action === "stop") { @@ -2434,13 +2498,28 @@ exports.motorAction = async (req, reply) => { // stopTime, // motorOnType // ); + + if (!notificationSentStatus.motorStop) { + // eventEmitter.emit( + // "motorStop", + // fcmToken, + // tankName, + // stopTime, + // "APP" + // ); + + // Emit motorStop event + const totalWaterPumped = await calculateTotalPumpedWater(customerId, motorId, start_instance_id); // A function to calculate total water pumped eventEmitter.emit( - "motorStop", - fcmToken, - tankName, - stopTime, - "APP" + 'motorStop', + fcmToken, + tankName, + blockName, + stopTime, + "Mobile APP", + totalWaterPumped, // Include total water pumped + typeOfWater ); notificationSentStatus.motorStop = true; // Set flag to true to prevent duplicate notifications }