diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 251bd0f6..44c8ceab 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -160,53 +160,23 @@ exports.updateTanksInfo = async (req, reply) => { } }; - - - - +//delete selected tank exports.deleteTanksInfo = async (req, reply) => { try { - const { customerId } = req.params; - const { tankName } = req.query; + const customerId = req.params.customerId; + + const tankName = req.query.tankName; const tankLocation = req.body.tankLocation.toLowerCase(); - if (!tankName || !tankLocation) { - return reply.code(400).send({ message: "Tank name and location are required" }); - } - - // Convert tankLocation to lowercase (for case-insensitive match) - const normalizedTankLocation = tankLocation.toLowerCase(); - - // Find and delete the main tank - const deletedTank = await Tank.findOneAndDelete({ - customerId, - tankName, - tankLocation: normalizedTankLocation - }); - - if (!deletedTank) { - return reply.code(404).send({ message: "Tank not found" }); - } + const tank = await Tank.findOneAndDelete({ tankName: tankName,customerId:customerId,tankLocation:tankLocation }); - // Remove the deleted tank from inputConnections and outputConnections in all other tanks - await Tank.updateMany( - { customerId }, - { - $pull: { - "connections.inputConnections": { inputConnections: tankName }, - "connections.outputConnections": { outputConnections: tankName } - } - } - ); - - return reply.send({ message: "Tank deleted successfully" }); - } catch (error) { - console.error("Error deleting tank:", error); - return reply.code(500).send({ message: "Internal Server Error" }); + reply.send({ status_code: 200, data: tank}); + // return tank; + } catch (err) { + throw boom.boomify(err); } }; - exports.getConnectionsInfoOfParticularTank = async (req, reply) => { try { const customerId = req.params.customerId; @@ -379,68 +349,24 @@ exports.getTanksofParticularInstaller = async (req, reply) => { // throw boom.boomify(err); // } //}; -// const boom = require("@hapi/boom"); // Assuming you are using boom for error handling - - exports.getTankmotordata = async (req, reply) => { try { - const { startDate, stopDate } = req.body; - const { customerId } = req.params; - - // Validate and format the input dates - if (!moment(startDate, "DD-MMM-YYYY - HH:mm", true).isValid() || !moment(stopDate, "DD-MMM-YYYY - HH:mm", true).isValid()) { - return reply.send({ status_code: 400, message: "Invalid date format" }); - } - - // Convert input dates to ISO 8601 format for Date comparison - const startISODate = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate(); - const stopISODate = moment(stopDate, "DD-MMM-YYYY - HH:mm").toDate(); - - // Convert input dates to string format for string-based comparison - const startStringDate = moment(startDate, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm"); - const stopStringDate = moment(stopDate, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm"); - - // Fetch the username based on customerId - const user = await User.findOne({ customerId }).select("username"); - - if (user) { - const userName = user.username || "N/A"; - - // Query the MotorData collection - const motorDataDocs = await MotorData.find({ - customerId, - $or: [ - { - startTime: { $gte: startISODate, $lte: stopISODate }, // Date-based comparison - }, - { - startTime: { $gte: startStringDate, $lte: stopStringDate }, // String-based comparison - }, - ], - }).exec(); - - reply.send({ - status_code: 200, - data: motorDataDocs, - count: motorDataDocs.length, - customerName: userName, + await MotorData.find({customerId: req.query.customerId}) + .exec() + .then((docs) => { + reply.send({ status_code: 200, data: docs, count: docs.length }); + }) + .catch((err) => { + console.log(err); + reply.send({ error: err }); }); - } else { - reply.send({ status_code: 404, message: "User not found" }); - } } catch (err) { - console.error("Error in getTankmotordata:", err); throw boom.boomify(err); } }; - - - - - exports.updateTanklevels = async (req, reply) => { try { const customerId = req.params.customerId; @@ -450,7 +376,7 @@ exports.updateTanklevels = async (req, reply) => { for (const tank of tanks) { const tankId = tank._id; - const tank_name = tank.tankName + const tank_name = tank.tankName let capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); //let waterLevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10); @@ -1125,52 +1051,50 @@ let supplier_tanks = []; - exports.consumption = async (request, reply) => { try { const { customerId } = request.params; const { startDate, stopDate, block } = request.body; let { typeofwater } = request.body; - + + // Convert typeofwater to lowercase typeofwater = typeofwater.toLowerCase(); const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate(); const end = moment(stopDate, "DD-MMM-YYYY - HH:mm").toDate(); - // Construct the query object + // Construct the query object based on block and typeofwater inputs const tankQuery = { customerId, tankLocation: "overhead" }; - if (block !== "All") tankQuery.blockName = block; - // Add typeofwater filter - if (typeofwater === "bore") { - tankQuery.typeOfWater = { $in: ["bore", "Bore Water"] }; - } else if (typeofwater === "drinking") { - tankQuery.typeOfWater = { $in: ["drinking", "Drinking Water"] }; + if (block !== "All") { + tankQuery.blockName = block; // Filter by specific block if not "all" + } + + if (typeofwater !== "all") { + tankQuery.typeOfWater = typeofwater; // Filter by specific type of water if not "all" } const tanks = await Tank.find(tankQuery); const tankData = []; const tankconsumptionData = []; + // Variable to track total consumption for the selected block and typeofwater let totalConsumptionForSelectedBlockAndTypeOfWater = 0; - let totalBoreConsumptionForSelectedBlockAndTypeOfWater = 0; - let totalBoreCapacityForSelectedBlockAndTypeOfWater = 0; - let totalDrinkingConsumptionForSelectedBlockAndTypeOfWater = 0; - let totalDrinkingCapacityForSelectedBlockAndTypeOfWater = 0; + let totalCapacityForSelectedBlockAndTypeOfWater=0; for (const tank of tanks) { const waterlevel_at_midnight = parseInt(tank.waterlevel_at_midnight.replace(/,/g, ''), 10); const total_water_added_from_midnight = parseInt(tank.total_water_added_from_midnight.replace(/,/g, ''), 10); const waterlevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10); const tankname = tank.tankName; - const capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); + const capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); const tankConsumptions = await TankConsumptionOriginalSchema.find({ customerId, tankName: tank.tankName, tankLocation: tank.tankLocation, - ...(block !== "All" && { block: tank.blockName }), - ...(typeofwater === "bore" && { typeofwater: { $in: ["bore", "Bore Water"] } }), - ...(typeofwater === "drinking" && { typeofwater: { $in: ["drinking", "Drinking Water"] } }), + + ...(block !== "All" && { block: tank.blockName }), // Ensure correct field names + ...(typeofwater !== "all" && { typeofwater: tank.typeOfWater }) // Ensure correct field names }); const filteredConsumptions = tankConsumptions.filter((record) => { @@ -1181,75 +1105,36 @@ exports.consumption = async (request, reply) => { const total_consumption_from_records = filteredConsumptions.reduce((acc, record) => { return acc + parseInt(record.consumption, 10); }, 0); + tankconsumptionData.push({ + tankname, + consumptionRecordsdatewise: filteredConsumptions + }) const consumption = (waterlevel_at_midnight + total_water_added_from_midnight) - waterlevel + total_consumption_from_records; + + // Add to the total consumption for the selected block and typeofwater totalConsumptionForSelectedBlockAndTypeOfWater += consumption; - - // Add to the total consumption and capacities based on water type - if (tank.typeOfWater === "bore" || tank.typeOfWater === "Bore Water") { - totalBoreConsumptionForSelectedBlockAndTypeOfWater += consumption; - totalBoreCapacityForSelectedBlockAndTypeOfWater += capacity; - } else if (tank.typeOfWater === "drinking" || tank.typeOfWater === "Drinking Water") { - totalDrinkingConsumptionForSelectedBlockAndTypeOfWater += consumption; - totalDrinkingCapacityForSelectedBlockAndTypeOfWater += capacity; - } + totalCapacityForSelectedBlockAndTypeOfWater += capacity; tankData.push({ tankname, + totalConsumption: consumption, block: tank.blockName, TypeofWater: tank.typeOfWater, location: tank.tankLocation, capacity: tank.capacity, - waterlevel: tank.waterlevel, - }); - - tankconsumptionData.push({ - tankname, - consumptionRecordsdatewise: filteredConsumptions, + waterlevel: tank.waterlevel }); } - - // Calculate total consumption percentages - const boreConsumptionPercentage = totalBoreCapacityForSelectedBlockAndTypeOfWater - ? ((totalBoreConsumptionForSelectedBlockAndTypeOfWater / totalBoreCapacityForSelectedBlockAndTypeOfWater) * 100).toFixed(2) - : 0; - - const drinkingConsumptionPercentage = totalDrinkingCapacityForSelectedBlockAndTypeOfWater - ? ((totalDrinkingConsumptionForSelectedBlockAndTypeOfWater / totalDrinkingCapacityForSelectedBlockAndTypeOfWater) * 100).toFixed(2) - : 0; - - const totalConsumptionPercentage = - typeofwater === "bore" - ? boreConsumptionPercentage - : typeofwater === "drinking" - ? drinkingConsumptionPercentage - : ((totalBoreConsumptionForSelectedBlockAndTypeOfWater + totalDrinkingConsumptionForSelectedBlockAndTypeOfWater) / - (totalBoreCapacityForSelectedBlockAndTypeOfWater + totalDrinkingCapacityForSelectedBlockAndTypeOfWater) * - 100 - ).toFixed(2); + const totalConsumptionPercentage = ((totalConsumptionForSelectedBlockAndTypeOfWater / totalCapacityForSelectedBlockAndTypeOfWater) * 100).toFixed(2) ; // Include the total consumption in the response const response = { status_code: 200, - tankData, - consumptiorecordsdatewise: tankconsumptionData, - totalConsumptionPercentage, - ...(typeofwater === "all" - ? { - totalConsumptionPercentageForBore: boreConsumptionPercentage, - totalConsumptionPercentageForDrinking: drinkingConsumptionPercentage, - totalConsumptionForBore: totalBoreConsumptionForSelectedBlockAndTypeOfWater, - totalConsumptionForDrinking: totalDrinkingConsumptionForSelectedBlockAndTypeOfWater, - } - : { - [`total consumption of ${typeofwater} and selected block`]: - typeofwater === "bore" - ? totalBoreConsumptionForSelectedBlockAndTypeOfWater - : totalDrinkingConsumptionForSelectedBlockAndTypeOfWater, - } - ), - [`total consumption of ${typeofwater} and selected block`]: totalConsumptionForSelectedBlockAndTypeOfWater + tankData,consumptiorecordsdatewise:tankconsumptionData, + totalConsumptionPercentage:totalConsumptionPercentage, + [`total consumption of ${typeofwater} and selected block`]: totalConsumptionForSelectedBlockAndTypeOfWater }; reply.send(response); @@ -1258,8 +1143,6 @@ exports.consumption = async (request, reply) => { } }; - - exports.consumptiondatewiseofalltanks = async (request, reply) => { try { const { customerId } = request.params; @@ -1692,64 +1575,25 @@ 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, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => { + 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 === "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 + const startMethod = motorOnType.toUpperCase() === "APP" ? "via the App" : "Manual"; // Prepare the 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` + - `Will stop after: '${manual_threshold_time}' mins`; + `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`; // Send the notification await sendNotification(fcmTokens, 'Arminta Water Management', message); @@ -1759,108 +1603,33 @@ 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"; - - // 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 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}\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( - 'motorStartAutomatic', - async (fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater,threshold) => { - 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 === "Automatic" ? "Automatic" : "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` + - `🏢 Block Name: '${blockName}'\n` + - `👤 Started by: '${startMethod}' \n` + - `📱 Mode: "Atomatic System" \n` + - `🕒 Pump started at: ${startTime} \n` + - `Will stop after: '${threshold}' `; - - // Send the notification - await sendNotification(fcmTokens, 'Arminta Water Management', message); - } catch (error) { - console.error('Error in motorStart 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}'`; +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.toUpperCase() === "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); -// } -// }); + // 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) => { @@ -1869,39 +1638,39 @@ eventEmitter.on( // }); // Event listener to handle notification -// eventEmitter.on('sendLowWaterNotification', async (fcmToken, tankInfo) => { -// const message = formatWaterLevelMessage(tankInfo, 'low'); -// sendNotification(fcmToken, message); -// }); +eventEmitter.on('sendLowWaterNotification', async (fcmToken, tankInfo) => { + const message = formatWaterLevelMessage(tankInfo, 'low'); + sendNotification(fcmToken, message); +}); -// eventEmitter.on('sendVeryLowWaterNotification', async (fcmToken, tankInfo) => { -// const message = formatWaterLevelMessage(tankInfo, 'very low'); -// sendNotification(fcmToken, message); -// }); +eventEmitter.on('sendVeryLowWaterNotification', async (fcmToken, tankInfo) => { + const message = formatWaterLevelMessage(tankInfo, 'very low'); + sendNotification(fcmToken, message); +}); -// eventEmitter.on('sendCriticalLowWaterNotification', async (fcmToken, tankInfo) => { -// const message = formatWaterLevelMessage(tankInfo, 'critically low'); -// sendNotification(fcmToken, message); -// }); +eventEmitter.on('sendCriticalLowWaterNotification', async (fcmToken, tankInfo) => { + const message = formatWaterLevelMessage(tankInfo, 'critically low'); + sendNotification(fcmToken, message); +}); -// const formatWaterLevelMessage = (tankInfo, levelType) => { -// const tankName = tankInfo.tankName; -// const tankLocation = tankInfo.tankLocation; -// const waterLevel = parseInt(tankInfo.waterlevel, 10); -// const capacity = parseInt(tankInfo.capacity, 10); -// const volumeInLitres = (capacity * waterLevel) / 100; // assuming the capacity is in litres - -// let levelDescription = ''; -// if (levelType === 'low') { -// levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`; -// } else if (levelType === 'very low') { -// levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`; -// } else if (levelType === 'critically low') { -// levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`; -// } +const formatWaterLevelMessage = (tankInfo, levelType) => { + const tankName = tankInfo.tankName; + const tankLocation = tankInfo.tankLocation; + const waterLevel = parseInt(tankInfo.waterlevel, 10); + const capacity = parseInt(tankInfo.capacity, 10); + const volumeInLitres = (capacity * waterLevel) / 100; // assuming the capacity is in litres + + let levelDescription = ''; + if (levelType === 'low') { + levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`; + } else if (levelType === 'very low') { + levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`; + } else if (levelType === 'critically low') { + levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`; + } -// return `Water level in '${tankName}', located at '${tankLocation}', type of water: ${tankInfo.waterType} is ${levelType} at ${levelDescription}. Action: start motor now.`; -// }; + return `Water level in '${tankName}', located at '${tankLocation}', type of water: ${tankInfo.waterType} is ${levelType} at ${levelDescription}. Action: start motor now.`; +}; // Emit low water level event with motorId // eventEmitter.on('lowWaterLevel', async (fcmTokens, timestamp, motorId, waterLevel) => { @@ -1938,257 +1707,26 @@ eventEmitter.on('sendThresholdTimeNotification', async (fcmTokens, message) => { } }); -// eventEmitter.on( -// 'sendMotorStartNotification', -// async (fcmTokens, motorId, waterLevel, blockName, tankName, motorOnType, stopCriteria, manual_threshold_time) => { -// try { -// // Get the latest timestamp -// const startTime = 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 startMethod = motorOnType.toUpperCase() === "Forced Manual"; - -// // Prepare the message -// const message = -// `🚰 Tank Name: '${tankName}'\n` + -// `🕒 Pump started at: '${startTime}'\n` + -// `👤 Initiated by: ${userNames}\n` + -// `🔄 Pump started by: '${startMethod}'`; - -// // Send the notification -// await sendNotification(fcmTokens, 'Motor Started 🚀', message); -// console.log('Motor start notification sent successfully!'); -// } catch (error) { -// console.error('Error in sendMotorStartNotification event:', error); -// } -// } -// ); - -eventEmitter.on( - 'sendMotorStartNotification', - async ( - fcmTokens, - blockName, - tankName, - motorOnType, - stopCriteria, - typeOfWater, - highThreshold // Add the high threshold as a parameter - ) => { - 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' }); - - // Retrieve the user information - const users = await User.find({ fcmIds: { $in: fcmTokens } }); - const userNames = users.map(user => user.username).join(', '); - - // Determine the pump initiation method - const startMethod = motorOnType === "Forced Manual" ? "Physically" : "Manually" - - // Dynamically generate the motor name - const motorName = `${tankName}-${blockName}-${typeOfWater}`; - - // Determine the 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`; - } - - // 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 - - // Send the notification - await sendNotification(fcmTokens, 'Motor Started 🚀', message); - console.log('Motor start notification with stop criteria sent successfully!'); - } catch (error) { - console.error('Error in sendMotorStartNotification event:', error); - } - } -); - - -// eventEmitter.on( -// 'sendMotorStartNotification', -// async (fcmTokens, motorId, waterLevel, blockName, tankName, motorOnType, stopCriteria, manual_threshold_time, typeOfWater) => { -// 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' }); - -// // Retrieve the user information -// const users = await User.find({ fcmIds: { $in: fcmTokens } }); -// const userNames = users.map(user => user.username).join(', '); - -// // Determine the pump initiation method -// const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual"; - -// // Dynamically generate the motor name -// const motorName = `${tankName}-${blockName}-${typeOfWater}`; - -// // Prepare the notification message -// const message = -// `🚰 Motor Name: '${motorName}'\n` + -// `🚰 Tank Name: '${tankName}'\n` + -// `🏢 Block Name: '${blockName}'\n` + -// `💧 Water Level: '${waterLevel}%'\n` + -// `👤 Initiated by: ${userNames}\n` + -// `📱 Pump started by: '${startMethod}'\n` + -// `🕒 Start Time: '${startTime}'\n` + -// `⏳ Will stop after: '${manual_threshold_time}' mins\n` + -// `📅 Date: '${formattedDate}'\n` + -// `⏰ Time: '${formattedTime}'`; - -// // Send the notification -// await sendNotification(fcmTokens, 'Motor Started 🚀', message); -// console.log('Motor start notification sent successfully!'); -// } catch (error) { -// console.error('Error in sendMotorStartNotification event:', error); -// } -// } -// ); - - -// 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 - ) => { - 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' }); - - // Retrieve the user information - const users = await User.find({ fcmIds: { $in: fcmTokens } }); - const userNames = users.map(user => user.username).join(', '); - - // Determine the pump stop method - const stopMethod = motorOnType === "Forced Manual" ? "Physically" : "Manually"; - - // Dynamically generate the motor name - 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; - - // 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('sendMotorStartNotification', async (fcmTokens, message) => { + try { + await sendNotification(fcmTokens, "Motor Started", message); + console.log("Manual method time notification sent successfully."); + } catch (error) { + console.error("Error sending thresmanual method time notification:", error); } -); - -eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => { - const notificationMessage = `Warning: Water level is low in the tank. - Tank Name: ${tankName}, - Location: ${receiverTank.location}, - Type of Water: ${receiverTank.typeOfWater}, - Current Water Level: ${currentWaterLevel} liters (${currentWaterPercentage.toFixed(2)}%), - Date & Time: ${new Date().toLocaleString()}`; - - // Send notifications using the provided FCM tokens - sendNotification(fcmTokens, notificationMessage); }); -eventEmitter.on('sendCriticalLowWaterNotification', (fcmTokens, message) => { - const notificationMessage = `Critical Alert: Water level is critically low in the tank. - Tank Name: ${tankName}, - Location: ${receiverTank.location}, - Type of Water: ${receiverTank.typeOfWater}, - Current Water Level: ${currentWaterLevel} liters (${currentWaterPercentage.toFixed(2)}%), - Date & Time: ${new Date().toLocaleString()}`; - - // Send notifications using the provided FCM tokens - sendNotification(fcmTokens, notificationMessage); +eventEmitter.on('sendMotorStopNotification', async (fcmTokens, message) => { + try { + await sendNotification(fcmTokens, "Motor Stopped", message); + console.log("Manual method time notification sent successfully."); + } catch (error) { + console.error("Error sending thresmanual method time notification:", error); + } }); -// eventEmitter.on('sendMotorStartNotification', async (fcmTokens, message) => { -// try { -// await sendNotification(fcmTokens, "Motor Started", message); -// console.log("Manual method time notification sent successfully."); -// } catch (error) { -// console.error("Error sending thresmanual method time notification:", error); -// } -// }); - -// eventEmitter.on('sendMotorStopNotification', async (fcmTokens, message) => { -// try { -// await sendNotification(fcmTokens, "Motor Stopped", message); -// console.log("Manual method time notification sent successfully."); -// } catch (error) { -// console.error("Error sending thresmanual method time notification:", error); -// } -// }); - - - // Function to emit events with timestamps const emitWithTimestamp = (eventName, fcmTokens, motorId, waterLevel) => { const timestamp = moment().format('HH:mm:ss YYYY-MM-DD '); @@ -2241,21 +1779,12 @@ const sendNotification = async (fcmIds, title, body) => { notification: { title, body }, token, data: { - 'target': '/screen', + 'target': '/route_navigation', }, }); console.log(`Notification sent successfully to token: ${token}`, response); } catch (error) { console.error(`Failed to send notification to token: ${token}`, error); - // Check for specific error indicating an invalid token - if (error.code === 'messaging/registration-token-not-registered') { - // Remove the invalid token from the database - await User.updateOne( - { fcmIds: token }, // Ensure you're targeting the right user with the invalid token - { $pull: { fcmIds: token } } // Remove the invalid token - ); - console.log(`Removed invalid token: ${token}`); - } } }); @@ -2607,90 +2136,71 @@ const notificationSentStatus = { criticallyHighWater: false, }; -let waterLevelCheckInterval; // To hold the interval ID +const checkWaterLevelsAndNotify = async (customerId, tankName, tankLocation, fcmTokens) => { + try { + // Fetch the tank details from the database + const tank = await Tank.findOne({ customerId, tankName, tankLocation }); -const checkWaterLevel = async (customerId, motorId, fcmToken, receiverTank) => { - const currentWaterLevel = parseInt(receiverTank.waterlevel, 10); - const tankCapacity = parseInt(receiverTank.capacity.replace(/,/g, ''), 10); - const currentWaterPercentage = (currentWaterLevel / tankCapacity) * 100; + if (!tank) { + console.error(`Tank not found: ${tankName} at location ${tankLocation}`); + return; + } - // Check for low water levels - if (currentWaterPercentage <= 20 && !notificationSentStatus.lowWater) { - eventEmitter.emit('sendLowWaterNotification', fcmToken, `Water level has dropped below 20%.`); - notificationSentStatus.lowWater = true; - } + // Extract the current water level and capacity + const currentWaterLevel = parseInt(tank.waterlevel, 10); + const capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); + + // Calculate the water level percentage + const waterLevelPercentage = (currentWaterLevel / capacity) * 100; + + // Thresholds for notifications + const thresholds = { + criticallyLow: 10, + veryLow: 20, + low: 30, + high: 70, + veryHigh: 80, + criticallyHigh: 85, + }; - // Check for critically low water levels - if (currentWaterPercentage <= 10 && !notificationSentStatus.criticallyLowWater) { - eventEmitter.emit('sendCriticalLowWaterNotification', fcmToken, `Water level has dropped below 10%.`); - notificationSentStatus.criticallyLowWater = true; + // Check water levels and send notifications + if (waterLevelPercentage <= thresholds.criticallyLow && !notificationSentStatus.criticallyLowWater) { + eventEmitter.emit('sendCriticalLowWaterNotification', fcmTokens, tank); + notificationSentStatus.criticallyLowWater = true; + await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentCritical: true } }); + } else if (waterLevelPercentage <= thresholds.veryLow && !notificationSentStatus.veryLowWater) { + eventEmitter.emit('sendVeryLowWaterNotification', fcmTokens, tank); + notificationSentStatus.veryLowWater = true; + await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentVeryLow: true } }); + } else if (waterLevelPercentage <= thresholds.low && !notificationSentStatus.lowWater) { + eventEmitter.emit('sendLowWaterNotification', fcmTokens, tank); + notificationSentStatus.lowWater = true; + await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentLow: true } }); + } + // if (waterLevelPercentage <= thresholds.criticallyLow) { + // eventEmitter.emit('sendCriticalLowWaterNotification', fcmTokens, tank); + // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentCritical: true } }); + // } else if (waterLevelPercentage <= thresholds.veryLow) { + // eventEmitter.emit('sendVeryLowWaterNotification', fcmTokens, tank); + // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentVeryLow: true } }); + // } else if (waterLevelPercentage <= thresholds.low) { + // eventEmitter.emit('sendLowWaterNotification', fcmTokens, tank); + // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentLow: true } }); + // } + // else if (waterLevelPercentage >= thresholds.criticallyHigh) { + // eventEmitter.emit('sendCriticalHighWaterNotification', fcmTokens, tank); + // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentCriticalHigh: true } }); + // } else if (waterLevelPercentage >= thresholds.veryHigh) { + // eventEmitter.emit('sendVeryHighWaterNotification', fcmTokens, tank); + // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentVeryHigh: true } }); + // } else if (waterLevelPercentage >= thresholds.high) { + // eventEmitter.emit('sendHighWaterNotification', fcmTokens, tank); + // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentHigh: true } }); + // } + } catch (error) { + console.error(`Error checking water levels for tank ${tankName}:`, error); } }; -// const checkWaterLevelsAndNotify = async (customerId, tankName, tankLocation, fcmTokens) => { -// try { -// // Fetch the tank details from the database -// const tank = await Tank.findOne({ customerId, tankName, tankLocation }); - -// if (!tank) { -// console.error(`Tank not found: ${tankName} at location ${tankLocation}`); -// return; -// } - -// // Extract the current water level and capacity -// const currentWaterLevel = parseInt(tank.waterlevel, 10); -// const capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); - -// // Calculate the water level percentage -// const waterLevelPercentage = (currentWaterLevel / capacity) * 100; - -// // Thresholds for notifications -// const thresholds = { -// criticallyLow: 10, -// veryLow: 20, -// low: 30, -// high: 70, -// veryHigh: 80, -// criticallyHigh: 85, -// }; - -// // Check water levels and send notifications -// if (waterLevelPercentage <= thresholds.criticallyLow && !notificationSentStatus.criticallyLowWater) { -// eventEmitter.emit('sendCriticalLowWaterNotification', fcmTokens, tank); -// notificationSentStatus.criticallyLowWater = true; -// await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentCritical: true } }); -// } else if (waterLevelPercentage <= thresholds.veryLow && !notificationSentStatus.veryLowWater) { -// eventEmitter.emit('sendVeryLowWaterNotification', fcmTokens, tank); -// notificationSentStatus.veryLowWater = true; -// await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentVeryLow: true } }); -// } else if (waterLevelPercentage <= thresholds.low && !notificationSentStatus.lowWater) { -// eventEmitter.emit('sendLowWaterNotification', fcmTokens, tank); -// notificationSentStatus.lowWater = true; -// await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentLow: true } }); -// } -// // if (waterLevelPercentage <= thresholds.criticallyLow) { -// // eventEmitter.emit('sendCriticalLowWaterNotification', fcmTokens, tank); -// // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentCritical: true } }); -// // } else if (waterLevelPercentage <= thresholds.veryLow) { -// // eventEmitter.emit('sendVeryLowWaterNotification', fcmTokens, tank); -// // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentVeryLow: true } }); -// // } else if (waterLevelPercentage <= thresholds.low) { -// // eventEmitter.emit('sendLowWaterNotification', fcmTokens, tank); -// // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentLow: true } }); -// // } -// // else if (waterLevelPercentage >= thresholds.criticallyHigh) { -// // eventEmitter.emit('sendCriticalHighWaterNotification', fcmTokens, tank); -// // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentCriticalHigh: true } }); -// // } else if (waterLevelPercentage >= thresholds.veryHigh) { -// // eventEmitter.emit('sendVeryHighWaterNotification', fcmTokens, tank); -// // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentVeryHigh: true } }); -// // } else if (waterLevelPercentage >= thresholds.high) { -// // eventEmitter.emit('sendHighWaterNotification', fcmTokens, tank); -// // await Tank.updateOne({ customerId, tankName: tank.tankName }, { $set: { notificationSentHigh: true } }); -// // } -// } catch (error) { -// console.error(`Error checking water levels for tank ${tankName}:`, error); -// } -// }; const monitorWaterLevels = async () => { @@ -2713,7 +2223,7 @@ const monitorWaterLevels = async () => { const tankLocation = tank.tankLocation; // Assuming tank has a 'location' field // Call the function to check water levels and send notifications - //await checkWaterLevelsAndNotify(customerId, tankName, tankLocation, fcmTokens); + await checkWaterLevelsAndNotify(customerId, tankName, tankLocation, fcmTokens); } else { //console.log(`No FCM tokens found for customerId ${tank.customerId}`); } @@ -2727,17 +2237,6 @@ 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; @@ -2746,7 +2245,7 @@ exports.motorAction = async (req, reply) => { const start_instance_id = req.body.start_instance_id; // Define thresholds for water levels - const lowWaterThreshold = 5; // Low water level percentage threshold + const lowWaterThreshold = 20; // Low water level percentage threshold //const highWaterThreshold = 90; // High water level percentage threshold const highWaterThreshold = 70; // High water level percentage threshold const veryHighWaterThreshold = 80; // Very High water level percentage threshold @@ -2764,15 +2263,14 @@ 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; const blockName = req.body.from || "Unknown Block"; // Provide a fallback if `from` is missing const tankName = req.body.to || "Unknown Tank"; // Provide a fallback if `to` is missing const stopTime = req.body.stopTime - const motorOnType = "manual"; + const motorOnType = req.body.motor_on_type || "APP"; const manual_threshold_time = req.body.manual_threshold_time; let hasNotifiedStart = false; let hasNotifiedStop = false; @@ -2787,59 +2285,85 @@ 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); - + 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, - tankName, - blockName, - startTime, - "Mobile APP", - manual_threshold_time, - typeOfWater + "motorStart", + fcmToken, + new Date().toISOString(), + motorId, + currentWaterLevel, + blockName, + tankName, + startTime, + motorOnType, + manual_threshold_time ); - notificationSentStatus.motorStart = true; // Set flag to true to prevent duplicate notifications - } - // Start checking water level every 30 minutes - if (!waterLevelCheckInterval) { - waterLevelCheckInterval = setInterval(async () => { - await checkWaterLevel(customerId, motorId, fcmToken, receiverTank); - }, 30 * 60 * 1000); // 30 minutes } await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, { $set: { "connections.inputConnections.$.motor_stop_status": "2", "connections.inputConnections.$.manual_threshold_time": manual_threshold_time, "connections.inputConnections.$.threshold_type": "time", - "connections.inputConnections.$.motor_on_type": "manual" } } + "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") { motorStopStatus = "1"; // If action is stop, set stop status to "1" + + await checkWaterLevelsAndNotify(customerId, tankName, receiverTank.tankLocation, fcmToken); + + // eventEmitter.emit( + // "motorStop", + // fcmToken, + // // motorId, + // // currentWaterLevel, + // // blockName, + // tankName, + // stopTime, + // motorOnType + // ); if (!notificationSentStatus.motorStop) { - - // Emit motorStop event - const totalWaterPumped = await calculateTotalPumpedWater(customerId, motorId, start_instance_id); // A function to calculate total water pumped eventEmitter.emit( - 'motorStop', - fcmToken, - tankName, - blockName, - stopTime, - "Mobile APP", - totalWaterPumped, // Include total water pumped - typeOfWater + "motorStop", + fcmToken, + tankName, + stopTime, + motorOnType ); notificationSentStatus.motorStop = true; // Set flag to true to prevent duplicate notifications } @@ -2851,11 +2375,7 @@ exports.motorAction = async (req, reply) => { "connections.inputConnections.$.motor_on_type": motorOnType } } ); - // Clear the interval when the motor is stopped - if (waterLevelCheckInterval) { - clearInterval(waterLevelCheckInterval); - waterLevelCheckInterval = null; // Reset the interval ID - } + } else { throw new Error("Invalid action provided."); } @@ -2888,11 +2408,10 @@ exports.motorAction = async (req, reply) => { // Perform stop operations in the background (async () => { - - console.log(start_instance_id,"start_instance_id",customerId,"customerId",motorId,"motorId") + await delay(300000); + const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id }); if (motorData) { - console.log("entered if in stop") 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); @@ -2948,7 +2467,6 @@ exports.motorAction = async (req, reply) => { this.publishMotorStopStatus(motorId, motorStopStatus); for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) { const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId); - if (index !== -1) { await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, @@ -2975,12 +2493,12 @@ exports.motorAction = async (req, reply) => { console.log(thresholdTime,"thresholdTime") console.log("motor stopping because it entered this condition") // Emit the threshold time notification - // eventEmitter.emit( - // "sendThresholdTimeNotification", - // fcmToken, - // `Motor has reached its time threshold of ${req.body.manual_threshold_time} minutes and will stop.` - // ); - const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); + eventEmitter.emit( + "sendThresholdTimeNotification", + fcmToken, + `Motor has reached its time threshold of ${req.body.manual_threshold_time} minutes and will stop.` + ); + await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, { @@ -2989,8 +2507,7 @@ exports.motorAction = async (req, reply) => { "connections.inputConnections.$.threshold_type": null, "connections.inputConnections.$.manual_threshold_time": null, - "connections.inputConnections.$.manual_threshold_percentage": null, - "connections.inputConnections.$.stopTime": currentTime, + "connections.inputConnections.$.manual_threshold_percentage": null } } ); @@ -2999,7 +2516,7 @@ exports.motorAction = async (req, reply) => { // clearInterval(motorIntervals[motorId]); // Clear interval // delete motorIntervals[motorId]; - // await checkWaterLevelsAndNotify(customerId, tankName, supplierTank.tankLocation, fcmToken); + await checkWaterLevelsAndNotify(customerId, tankName, supplierTank.tankLocation, fcmToken); // if (currentWaterPercentage >= highWaterThreshold && !notificationSentStatus.highWater) { // eventEmitter.emit('sendHighWaterNotification', fcmToken, `Water level has reached high levels.`); // notificationSentStatus.highWater = true; // Set flag to true to prevent duplicate notifications @@ -3018,12 +2535,9 @@ exports.motorAction = async (req, reply) => { delete motorIntervals[motorId]; // Remove from interval object this.publishMotorStopStatus(motorId, "1"); - console.log(start_instance_id,"start_instance_id",customerId,"customerId",motorId,"motorId") - + await delay(300000); const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id }); - console.log(motorData,"motorData") if (motorData) { - console.log("got into if") 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); @@ -3039,7 +2553,7 @@ exports.motorAction = async (req, reply) => { { customerId, motor_id: motorId, start_instance_id: start_instance_id }, { $set: { - stopTime: currentTime, + stopTime: req.body.stopTime, receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), quantity_delivered: quantityDelivered.toString() } @@ -3773,23 +3287,12 @@ const motorActionAuto = async (req, reply) => { const action = req.body.action; const motorId = req.body.motor_id; const motor_on_type = req.body.motor_on_type - const startTime = req.body.startTime; - const stopTime = req.body.stopTime; - const threshold = req.body.threshold || "unknown"; if (!motorId) { throw new Error("Motor ID is required."); } let motorStopStatus; - const tank = await Tank.findOne({ customerId, "connections.inputConnections.motor_id": motorId }); - - if (!tank) { - throw new Error("Tank not found for the provided motor ID."); - } - - const { tankName, blockName, typeOfWater, fcmTokens } = tank; // Extracting necessary details - if (action === "start") { await Tank.updateOne( @@ -3804,17 +3307,7 @@ const motorActionAuto = async (req, reply) => { } ); - eventEmitter.emit( - "motorStartAutomatic", - fcmTokens, - tankName, - blockName, - startTime, - "Automatic", - typeOfWater, - threshold - ); - + ; } if (action === "stop") { @@ -3828,21 +3321,6 @@ const motorActionAuto = async (req, reply) => { } } ); - - const currentDateTime = new Date(); - const formattedDate = currentDateTime.toLocaleDateString(); - const formattedTime = currentDateTime.toLocaleTimeString(); - - const stopMessage = - `🚰 Motor Name: ${tankName}-${blockName}-${typeOfWater}\n` + - `🛢️ Tank Name: '${tankName}'\n` + - `🏢 Block Name: '${blockName}'\n` + - `🕒 Pump stopped at: ${stopTime}\n` + - `⏳ Operation Duration: ${threshold} `; - - // Send stop notification - await sendNotification(fcmTokens, "Arminta Water Management", stopMessage); - } @@ -5328,25 +4806,18 @@ exports.update_auto_mode = async (req, reply) => { exports.update_auto_percentage = async (req, reply) => { try { const customerId = req.params.customerId; - const { tankName, tankLocation, auto_min_percentage, auto_max_percentage, auto_mode_type } = req.body; + const { tankName,tankLocation, auto_min_percentage, auto_max_percentage } = req.body; - // Build the query filter - const filter = { customerId: customerId }; - if (tankName !== "all") { - filter.tankName = tankName; - } - if (tankLocation) { - filter.tankLocation = tankLocation; - } + // Update inputConnections' auto_mode + - // Update auto_min_percentage, auto_max_percentage, and auto_mode_type - await Tank.updateMany( - filter, + // Update auto_min_percentage and auto_max_percentage + await Tank.updateOne( + { customerId: customerId,tankLocation, tankName}, { $set: { "auto_min_percentage": auto_min_percentage, - "auto_max_percentage": auto_max_percentage, - "auto_mode_type": auto_mode_type + "auto_max_percentage": auto_max_percentage } } ); @@ -5358,7 +4829,6 @@ exports.update_auto_percentage = async (req, reply) => { }; - //storing water level for every 15 minutes const getFormattedISTTime = () => { @@ -5586,6 +5056,7 @@ exports.getBlockData = async (req, reply) => { // } // }); + const mqtt = require('mqtt'); const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker @@ -5696,45 +5167,15 @@ client.on('message', async (topic, message) => { const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name if (inputConnection) { inputConnection.motor_status = status; // Update motor status - - const tankName = motorTank.tankName; - console.log(tankName,"tankName") if (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; - // Emit motor start notification with tankName - // 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 - // ); - } if (inputConnection.motor_stop_status === "2" && status === 1) { inputConnection.motor_stop_status = "1"; - const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); - inputConnection.stoptTime = currentTime; - - // Emit motor stop notification with tankName - // eventEmitter.emit( - // "sendMotorStopNotification", - // 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 - // ); } await motorTank.save(); // Save the updated tank @@ -5984,160 +5425,13 @@ console.log("this is for testing autopush,line located in tankscontroller") -// const calculateDailyConsumptionAndNotify = async () => { -// try { -// const today = moment().startOf("day"); -// const yesterday = moment(today).subtract(1, "days"); - -// // Fetch all active users -// const activeUsers = await User.find({ }); - -// for (const user of activeUsers) { -// const { customerId, fcmIds } = user; - -// // Fetch daily consumption for the customer -// const consumptions = await TankConsumptionOriginalSchema.find({ -// customerId, -// time: { -// $gte: yesterday.format("DD-MMM-YYYY - HH:mm"), -// $lt: today.format("DD-MMM-YYYY - HH:mm"), -// }, -// }); - -// // Calculate total consumption -// const totalConsumption = consumptions.reduce((total, record) => { -// return total + parseInt(record.consumption, 10); -// }, 0); - -// // Prepare tank-wise consumption details -// const tankDetails = consumptions.map((record) => ({ -// tankName: record.tankName, -// consumption: record.consumption, -// })); - -// // Send notification -// const notificationTitle = "Daily Water Consumption Report"; -// const notificationBody = ` -// Total Consumption: ${totalConsumption} liters -// Tank Details: ${tankDetails -// .map((tank) => `${tank.tankName}: ${tank.consumption} liters`) -// .join(", ")} -// `; - -// if (fcmIds && fcmIds.length > 0) { -// await sendNotification(fcmIds, notificationTitle, notificationBody); -// } -// } - -// console.log("Daily consumption notifications sent successfully."); -// } catch (err) { -// console.error("Error sending daily consumption notifications:", err); -// } -// }; - - -// cron.schedule("0 11:57 * * *", async () => { -// console.log("Starting daily consumption notification task..."); -// await calculateDailyConsumptionAndNotify(); -// }); - -// cron.schedule( -// "0 9 * * *", -// async () => { -// console.log("Starting daily consumption notification task..."); -// await calculateDailyConsumptionAndNotify(); -// }, -// { -// timezone: "Asia/Kolkata", // Specify the timezone -// } -// ); - -// const calculateDailyConsumptionAndNotify = async () => { -// try { -// const today = moment().startOf("day"); -// const yesterday = moment(today).subtract(1, "days"); - -// // Fetch all active users -// const activeUsers = await User.find({}); - -// for (const user of activeUsers) { -// const { customerId, fcmIds } = user; - -// // Fetch daily consumption for the customer -// const consumptions = await TankConsumptionOriginalSchema.find({ -// customerId, -// time: { -// $gte: yesterday.format("DD-MMM-YYYY - HH:mm"), -// $lt: today.format("DD-MMM-YYYY - HH:mm"), -// }, -// }); - -// // Calculate total consumption by type of water and the water level percentage -// const consumptionSummary = consumptions.reduce((acc, record) => { -// const typeOfWater = record.typeOfWater; // Assuming this field exists -// const consumption = parseInt(record.consumption, 10); -// const waterLevel = parseInt(record.waterLevel, 10); // Assuming waterLevel is in percentage - -// if (!acc[typeOfWater]) { -// acc[typeOfWater] = { -// totalConsumption: 0, -// tankDetails: [], -// totalWaterLevel: 0, -// count: 0, -// }; -// } - -// acc[typeOfWater].totalConsumption += consumption; -// acc[typeOfWater].totalWaterLevel += waterLevel; -// acc[typeOfWater].count += 1; -// acc[typeOfWater].tankDetails.push({ -// tankName: record.tankName, -// consumption, -// waterLevel, -// }); - -// return acc; -// }, {}); - -// // Prepare notification body -// let notificationBody = "Daily Water Consumption Report:\n"; -// for (const type in consumptionSummary) { -// const { totalConsumption, tankDetails, totalWaterLevel, count } = consumptionSummary[type]; -// const averageWaterLevel = (totalWaterLevel / count).toFixed(2); // Calculate average water level -// console.log("averageWaterLevel",averageWaterLevel) -// console.log("totalConsumption",totalConsumption) - -// notificationBody += ` -// Type of Water: ${type} -// Total Consumption: ${totalConsumption} liters -// Average Water Level: ${averageWaterLevel}% -// `; -// console.log("noti---" ,notificationBody += ` -// Type of Water: ${type} -// Total Consumption: ${totalConsumption} liters -// Average Water Level: ${averageWaterLevel}% -// `) -// } - -// if (fcmIds && fcmIds.length > 0) { -// await sendNotification(fcmIds, "Daily Water Consumption Report", notificationBody); -// } -// } - -// console.log("Daily consumption notifications sent successfully."); -// } catch (err) { -// console.error("Error sending daily consumption notifications:", err); -// } -// }; - - const calculateDailyConsumptionAndNotify = async () => { try { const today = moment().startOf("day"); const yesterday = moment(today).subtract(1, "days"); // Fetch all active users - const activeUsers = await User.find({}); + const activeUsers = await User.find({ }); for (const user of activeUsers) { const { customerId, fcmIds } = user; @@ -6151,46 +5445,28 @@ const calculateDailyConsumptionAndNotify = async () => { }, }); - // Calculate total consumption and capacities based on water type - let totalBoreConsumption = 0; - let totalDrinkingConsumption = 0; - let totalBoreCapacity = 0; - let totalDrinkingCapacity = 0; - - for (const record of consumptions) { - const typeOfWater = record.typeOfWater; // Assuming this field exists - const consumption = parseInt(record.consumption, 10); - const capacity = parseInt(record.capacity, 10); // Assuming capacity field exists - - if (typeOfWater === "bore" || typeOfWater === "Bore Water") { - totalBoreConsumption += consumption; - totalBoreCapacity += capacity; - } else if (typeOfWater === "drinking" || typeOfWater === "Drinking Water") { - totalDrinkingConsumption += consumption; - totalDrinkingCapacity += capacity; - } - } - - // Calculate percentages - const boreConsumptionPercentage = totalBoreCapacity - ? ((totalBoreConsumption / totalBoreCapacity) * 100).toFixed(2) - : 0; + // Calculate total consumption + const totalConsumption = consumptions.reduce((total, record) => { + return total + parseInt(record.consumption, 10); + }, 0); - const drinkingConsumptionPercentage = totalDrinkingCapacity - ? ((totalDrinkingConsumption / totalDrinkingCapacity) * 100).toFixed(2) - : 0; + // Prepare tank-wise consumption details + const tankDetails = consumptions.map((record) => ({ + tankName: record.tankName, + consumption: record.consumption, + })); - // Prepare notification body - const reportDate = yesterday.format("DD-MMM-YYYY"); - let notificationBody = `Daily Water Consumption Report for ${reportDate}:\n`; - notificationBody += `Total Bore Consumption: ${totalBoreConsumption} liters\n`; - notificationBody += `Bore Water Consumption Percentage: ${boreConsumptionPercentage}%\n`; - notificationBody += `Total Drinking Consumption: ${totalDrinkingConsumption} liters\n`; - notificationBody += `Drinking Water Consumption Percentage: ${drinkingConsumptionPercentage}%\n`; + // Send notification + const notificationTitle = "Daily Water Consumption Report"; + const notificationBody = ` + Total Consumption: ${totalConsumption} liters + Tank Details: ${tankDetails + .map((tank) => `${tank.tankName}: ${tank.consumption} liters`) + .join(", ")} + `; - // Send notification if FCM IDs are present if (fcmIds && fcmIds.length > 0) { - await sendNotification(fcmIds, "Daily Water Consumption Report", notificationBody); + await sendNotification(fcmIds, notificationTitle, notificationBody); } } @@ -6200,7 +5476,12 @@ const calculateDailyConsumptionAndNotify = async () => { } }; -// Schedule the cron job to run daily at 9 AM + +// cron.schedule("0 11:57 * * *", async () => { +// console.log("Starting daily consumption notification task..."); +// await calculateDailyConsumptionAndNotify(); +// }); + cron.schedule( "0 9 * * *", async () => { @@ -6210,274 +5491,4 @@ cron.schedule( { timezone: "Asia/Kolkata", // Specify the timezone } -); - - -const calculateConsumptionAndNotify = async () => { - try { - const now = moment(); // Current time - const sixHoursAgo = moment(now).subtract(6, 'hours').startOf('hour'); // 6 hours ago - - // Fetch all active users - const activeUsers = await User.find({}); - - for (const user of activeUsers) { - const { customerId, fcmIds } = user; - - // Fetch consumption records for the last 6 hours - const consumptions = await TankConsumptionOriginalSchema.find({ - customerId, - time: { - $gte: sixHoursAgo.format("DD-MMM-YYYY - HH:mm"), - $lt: now.format("DD-MMM-YYYY - HH:mm"), - }, - }); - - // Prepare notification body - let notificationBody = `Water Consumption Report (From ${sixHoursAgo.format( - "hh:mm A" - )} to ${now.format("hh:mm A")}):\n`; - const tankDetails = {}; - - // Aggregate consumption data by tank - for (const record of consumptions) { - const tankName = record.tankName; // Assuming this field exists - const tankLocation = record.tankLocation; // Assuming this field exists - const consumption = parseInt(record.consumption, 10); // Liters consumed - const typeOfWater = record.typeOfWater; // Type of water (e.g., bore, drinking) - const tankCapacity = parseInt(record.capacity, 10); // Tank capacity in liters - - if (!tankDetails[tankName]) { - tankDetails[tankName] = { - tankLocation, - totalConsumption: 0, - typeOfWater, - tankCapacity, - }; - } - tankDetails[tankName].totalConsumption += consumption; - } - - // Format tank details for the notification - for (const tankName in tankDetails) { - const { - tankLocation, - totalConsumption, - typeOfWater, - tankCapacity, - } = tankDetails[tankName]; - const consumptionPercentage = tankCapacity - ? ((totalConsumption / tankCapacity) * 100).toFixed(2) - : 0; - - notificationBody += - `Tank Name: ${tankName} \n`+ - `Location: ${tankLocation} \n`+ - `Total Consumption: ${totalConsumption} liters ${consumptionPercentage}% \n`+ - `Type of Water: ${typeOfWater}`; - } - - // Send notification if FCM IDs are present - if (fcmIds && fcmIds.length > 0) { - await sendNotification(fcmIds, "Water Consumption Report", notificationBody); - } - } - - console.log("Consumption notifications sent successfully."); - } catch (err) { - console.error("Error sending consumption notifications:", err); - } -}; - - - -const calculateWaterLevelAndNotify = async () => { - try { - const now = moment(); - const sixHoursAgo = moment().subtract(6, "hours"); - - console.log(`Calculating water level between ${sixHoursAgo.format("HH:mm A")} and ${now.format("HH:mm A")}`); - - const tanks = await Tank.find({}); - - for (const tank of tanks) { - const { - customerId, - tankName, - tankLocation, - typeOfWater, - capacity, - waterlevel, - waterlevel_at_midnight, - } = tank; - - // ✅ Fix: 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; - } - - const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); - const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel; - const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2); - - const user = await User.findOne({ customerId }); - if (!user || !user.fcmIds || user.fcmIds.length === 0) { - console.log(`No FCM tokens for customer: ${customerId}`); - continue; - } - - let notificationBody = - `🛢️ Tank Name: ${tankName}\n` + - `🏢 Location: ${tankLocation}\n` + - `💧 Type of Water: ${typeOfWater}\n` + - `Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`; - - await sendNotification(user.fcmIds, "Water Level Update", notificationBody); - } - - console.log("Water level notifications sent successfully."); - } catch (err) { - console.error("Error in water level calculation:", err); - } -}; - -// Schedule notifications at 6 AM, 12 PM, 6 PM, and 12 AM -cron.schedule( - "0 6,12,18,0 * * *", // Cron expression for the required times - async () => { - console.log("Starting scheduled consumption notification task..."); - //await calculateConsumptionAndNotify(); - await calculateWaterLevelAndNotify(); - }, - { - timezone: "Asia/Kolkata", // Specify the timezone - } -); - -// const updateStopTimeFormat = async () => { -// try { -// // Find records where stopTime is null or not in the required format -// const motorDataDocs = await MotorData.find(); - -// for (const doc of motorDataDocs) { -// // Parse and validate startTime -// const startTime = moment(doc.startTime, "DD-MMM-YYYY - HH:mm", true); -// if (!startTime.isValid()) { -// console.log(`Invalid startTime for record ID: ${doc._id}`); -// continue; -// } - -// // Format startTime if it's not already formatted -// const formattedStartTime = startTime.format("DD-MMM-YYYY - HH:mm"); - -// // Check if stopTime is valid or calculate it -// let formattedStopTime = null; -// const stopTime = moment(doc.stopTime, "DD-MMM-YYYY - HH:mm", true); - -// if (!stopTime.isValid()) { -// // Calculate stopTime by adding 30 minutes to startTime -// formattedStopTime = startTime.clone().add(30, "minutes").format("DD-MMM-YYYY - HH:mm"); -// } else { -// // Format the existing stopTime -// formattedStopTime = stopTime.format("DD-MMM-YYYY - HH:mm"); -// } - -// // Update the document if startTime or stopTime is not correctly formatted -// if (doc.startTime !== formattedStartTime || doc.stopTime !== formattedStopTime) { -// await MotorData.updateOne( -// { _id: doc._id }, -// { -// $set: { -// startTime: formattedStartTime, -// stopTime: formattedStopTime, -// }, -// } -// ); -// console.log(`Updated record ID: ${doc._id}`); -// } -// } - -// console.log("StopTime format update completed."); -// } catch (err) { -// console.error("Error updating stopTime format:", err); -// } -// }; - -// // Call the function to update stopTime -// updateStopTimeFormat(); - - - -exports.updatetankstatus = async (req, reply) => { - try { - const { customerId } = req.params; - const { tankName, tankLocation, status } = req.body; - - if (!["active", "inactive"].includes(status)) { - return reply.code(400).send({ message: "Invalid status value" }); - } - - // Find the main tank - const mainTank = await Tank.findOneAndUpdate( - { customerId, tankName, tankLocation }, - { $set: { status } }, - { new: true } - ); - - if (!mainTank) { - return reply.code(404).send({ message: "Tank not found" }); - } - - // Update status in related outputConnections tanks - await Tank.updateMany( - { - customerId, - "connections.outputConnections.outputConnections": tankName, - }, - { $set: { "connections.outputConnections.$.status": status } } - ); - - // Update status in related inputConnections tanks - await Tank.updateMany( - { - customerId, - "connections.inputConnections.inputConnections": tankName, - }, - { $set: { "connections.inputConnections.$.status": status } } - ); - - return reply.send({ message: "Tank status updated successfully" }); - } catch (error) { - console.error("Error updating tank status:", error); - return reply.code(500).send({ message: "Internal Server Error" }); - } -}; - - - - - - -// exports.listofactiveandinactivetankstatus = async (req, reply) => { -// try { -// const { customerId } = req.params; -// const status = req.query.status.toLowerCase(); - -// if (!["active", "inactive"].includes(status)) { -// return reply.code(400).send({ message: "Invalid status value" }); -// } - -// // Find tanks based on customerId and status -// const tanks = await Tank.find({ customerId, status }); - -// return reply.send({ tanks }); -// } catch (error) { -// console.error("Error fetching tank list:", error); -// return reply.code(500).send({ message: "Internal Server Error" }); -// } -// }; +); \ No newline at end of file diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 189afd65..c3df81c2 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -821,54 +821,13 @@ module.exports = function (fastify, opts, next) { handler: tanksController.deletemotordatarecordsbefore7days, }); - // fastify.get("/api/getTankmotordata", { - // schema: { - // tags: ["Tank"], - // description: "This is for Get Tank Motor Data", - // summary: "This is for to Get Tank Motor Data", - // querystring: { - // customerId: {type: 'string'} - // }, - // security: [ - // { - // basicAuth: [], - // }, - // ], - // }, - // preHandler: fastify.auth([fastify.authenticate]), - // handler: tanksController.getTankmotordata, - // }); - - - - fastify.route({ - method: "PUT", - url: "/api/getTankmotordata/:customerId", + fastify.get("/api/getTankmotordata", { schema: { tags: ["Tank"], - summary: "This is for Get Tank Motor Data", - params: { - required: ["customerId"], - type: "object", - properties: { - customerId: { - type: "string", - description: "customerId", - }, - }, - }, - - body: { - type: "object", - // required: ['phone'], - properties: { - startDate:{ type: "string" }, - stopDate:{type:"string"}, - block:{type:"string"}, - - - - }, + description: "This is for Get Tank Motor Data", + summary: "This is for to Get Tank Motor Data", + querystring: { + customerId: {type: 'string'} }, security: [ { @@ -876,7 +835,7 @@ module.exports = function (fastify, opts, next) { }, ], }, - //preHandler: fastify.auth([fastify.authenticate]), + preHandler: fastify.auth([fastify.authenticate]), handler: tanksController.getTankmotordata, }); @@ -884,7 +843,6 @@ module.exports = function (fastify, opts, next) { - fastify.post('/api/motor/write', { schema: { tags: ["Tank"], @@ -1112,7 +1070,6 @@ module.exports = function (fastify, opts, next) { auto_min_percentage: { type: "string", default: null }, auto_max_percentage: { type: "string", default: null }, tankLocation: { type: "string", default: null }, - auto_mode_type: { type: "string", default: "default" }, }, }, @@ -1231,71 +1188,6 @@ module.exports = function (fastify, opts, next) { }); - fastify.route({ - method: "PUT", - url: "/api/updatetankstatus/:customerId", - schema: { - tags: ["Tank"], - summary: "This is for updating tank status to active or inactive", - params: { - required: ["customerId"], - type: "object", - properties: { - customerId: { - type: "string", - description: "customerId", - }, - }, - }, - - body: { - type: "object", - // required: ['phone'], - properties: { - tankName:{ type: "string" }, - tankLocation:{type:"string"}, - status:{type:"string"}, - - - }, - }, - security: [ - { - basicAuth: [], - }, - ], - }, - //preHandler: fastify.auth([fastify.authenticate]), - handler: tanksController.updatetankstatus, - }); - - - // fastify.route({ - // method: "GET", - // url: "/api/listofactiveandinactivetankstatus/:customerId", - // schema: { - // tags: ["Tank"], - // summary: "Get list of active or inactive tanks", - // params: { - // required: ["customerId"], - // type: "object", - // properties: { - // customerId: { type: "string", description: "Customer ID" }, - // }, - // }, - // querystring: { - // type: "object", - // properties: { - // status: { type: "string"}, - // }, - // }, - // security: [{ basicAuth: [] }], - // }, - // handler: tanksController.listofactiveandinactivetankstatus, - // }); - - next(); } -