diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 6e429ad1..368abcfd 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -422,6 +422,11 @@ exports.getTanklevels = async (req, reply) => { try { const customerId = req.params.customerId; let sumSumpDrinkingWater = 0; + let totalavailableDrinkingwater = 0; + let totalDrinkingcapacity = 0; + let totalavailableBorewater = 0; + let totalBorewatercapacity = 0; + let sumOverheadDrinkingWater = 0; let sumSumpBoreWater = 0; let sumOverheadBoreWater = 0; @@ -498,6 +503,15 @@ exports.getTanklevels = async (req, reply) => { sumOverheadBoreWater += waterlevel; sumOverheadBoreWaterCapacity += capacity; } + else if ( tank.typeOfWater === 'drinking') { + totalavailableDrinkingwater += waterlevel; + totalDrinkingcapacity += capacity; + } + + else if ( tank.typeOfWater === 'bore') { + totalavailableBorewater += waterlevel; + totalBorewatercapacity += capacity; + } }); const user = await User.findOne({ customerId: customerId }); @@ -1146,11 +1160,10 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { const tanks = await Tank.find(tankQuery); const tankconsumptionData = {}; let totalConsumptionForSelectedBlockAndTypeOfWater = 0; + let totalAvailableCapacity = 0; + let totalConsumed = 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 tankConsumptions = await TankConsumptionOriginalSchema.find({ @@ -1166,12 +1179,10 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { return recordTime >= start && recordTime <= end; }); - const total_consumption_from_records = filteredConsumptions.reduce((acc, record) => { - return acc + parseInt(record.consumption, 10); - }, 0); - - const consumption = (waterlevel_at_midnight + total_water_added_from_midnight) - waterlevel + total_consumption_from_records; - totalConsumptionForSelectedBlockAndTypeOfWater += consumption; + filteredConsumptions.forEach(record => { + totalConsumed += parseInt(record.consumption, 10); + totalAvailableCapacity += parseInt(record.available_capacity, 10); + }); for (const record of filteredConsumptions) { const recordTime = moment(record.time, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm"); @@ -1190,6 +1201,7 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { tankconsumptionData[recordTime].consumptionRecordsdatewise.push({ tankName: record.tankName, consumption: record.consumption, + available_capacity: record.available_capacity, time: record.time }); tankconsumptionData[recordTime].count++; @@ -1197,36 +1209,14 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { } } - // Fetch all tanks in the customerId and block (or all blocks if block is set to "All") - const allTanksInBlock = await Tank.find({ - customerId, - ...(block !== "All" && { blockName: block }), - tankLocation: "overhead" - }); - - // Ensure each tank has records for each date - const dates = Object.keys(tankconsumptionData); - for (const date of dates) { - for (const tank of allTanksInBlock) { - const recordExists = tankconsumptionData[date].consumptionRecordsdatewise.some(record => record.tankName === tank.tankName); - if (!recordExists) { - const randomConsumption = Math.floor(Math.random() * (7000 - 3000 + 1)) + 3000; - tankconsumptionData[date].consumptionRecordsdatewise.push({ - tankName: tank.tankName, - consumption: randomConsumption.toString(), - time: date - }); - tankconsumptionData[date].count++; - } - } - } - const responseData = Object.values(tankconsumptionData); + const totalConsumptionPercentage = totalAvailableCapacity > 0 ? ((totalConsumed / totalAvailableCapacity) * 100).toFixed(2) : "0"; const response = { status_code: 200, consumptiorecordsdatewise: responseData, - [`total consumption of ${typeofwater} and selected block`]: totalConsumptionForSelectedBlockAndTypeOfWater + [`total consumption of ${typeofwater} and selected block`]: totalConsumptionForSelectedBlockAndTypeOfWater, + totalConsumptionPercentage: `${totalConsumptionPercentage}%` }; reply.send(response); @@ -1244,6 +1234,8 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { + + const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); //const moment = require('moment'); // Import moment.js for date/time operations @@ -2134,7 +2126,7 @@ exports.motorAction = async (req, reply) => { // Get user FCM tokens const users = await User.find({ customerId }); const fcmToken = users.map(user => user.fcmIds).filter(fcmIds => fcmIds); -console.log(fcmToken) + console.log(fcmToken) const receiverTank = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); console.log(receiverTank) const currentWaterLevel = parseInt(receiverTank.waterlevel, 10); @@ -4381,36 +4373,6 @@ exports.startUpdateLoop = async (request, reply) => { }; -// exports.updatewaterlevelsatmidnight = async (req, reply) => { -// try { -// // Schedule the task to run every day at 10 seconds past the minute -// cron.schedule('0 0 * * *', async () => { -// try { -// const tanks = await Tank.find({ customerId: req.query.customerId }); -// for (const tank of tanks) { -// tank.waterlevel_at_midnight = tank.waterlevel; -// console.log(tank.waterlevel_at_midnight) -// await tank.save(); -// } -// console.log('Waterlevel noted in waterlevel_at_midnight'); -// } catch (error) { -// console.error('Error occurred:', error); -// } -// }); - -// await Tank.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 }); -// }); -// } catch (err) { -// throw boom.boomify(err); -// } -// }; const updatewaterlevelsatmidnight = async () => { @@ -4456,8 +4418,11 @@ const updatetotalConsumptiontillmidnight = async () => { 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 capacity = parseInt((tank.capacity).replace(/,/g, ''), 10); console.log(waterlevel_at_midnight,total_water_added_from_midnight,waterlevel) const totalconsumption = (waterlevel_at_midnight + total_water_added_from_midnight) - waterlevel; + // const available_capacity = total_water_added_from_midnight + waterlevel; + const consumed_percentage = ((totalconsumption / capacity) * 100).toFixed(2); console.log(totalconsumption,tank.tankName) // Format the date in the desired format @@ -4477,7 +4442,9 @@ const updatetotalConsumptiontillmidnight = async () => { customerId: tank.customerId, tankName: tank.tankName, tankLocation: tank.tankLocation, + available_capacity: (tank.capacity).toString(), consumption: totalconsumption.toString(), + consumed_percentage: consumed_percentage.toString(), time: formattedDate, // Save the formatted date block:tank.blockName, typeofwater:tank.typeOfWater @@ -4508,43 +4475,6 @@ console.log('Scheduled task to update total consumption till midnight.'); -// const updatetotalConsumptiontillmidnight = async () => { -// console.log('Cron job triggered at:', moment().tz('Asia/Kolkata').format()); - -// try { -// const tanks = await Tank.find({}); -// 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 totalconsumption = (waterlevel_at_midnight + total_water_added_from_midnight) - waterlevel; - -// // Format the date in the desired format -// const formattedDate = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); - -// const newTankConsumption = new TankConsumptionOriginalSchema({ -// customerId: tank.customerId, -// tankName: tank.tankName, -// tankLocation: tank.tankLocation, -// consumption: totalconsumption.toString(), -// time: formattedDate // Save the formatted date -// }); - -// // Save the new document -// await newTankConsumption.save(); - -// } -// console.log('Waterlevel noted in waterlevel_at_midnight'); -// } catch (error) { -// console.error('Error occurred:', error); -// } -// }; - -// Schedule the task to run every day at 23:55 IST (11:55 PM IST) -// cron.schedule('55 23 * * *', updatetotalConsumptiontillmidnight, { -// timezone: "Asia/Kolkata" -// }); - @@ -4677,38 +4607,6 @@ exports.readMotorStatusFromIot = async (req, reply) => { - -// exports.writeMotorStatus = async (req, reply) => { -// try { -// const motor_id = req.body.motor_id; - -// // Perform any necessary logic to handle motor status update from the device - -// // For example, update a database with the new status, current, and temp values -// const existingRecord = await Tank.findOne({ motor_id: motor_id }); - -// if (existingRecord && (existingRecord.motor_stop_status === '1' || existingRecord.motor_stop_status === '2')) { -// const newMotorStatus = existingRecord.motor_stop_status; - -// if (existingRecord.motor_status !== newMotorStatus) { -// const result = await Tank.findOneAndUpdate( -// { motor_id: motor_id }, -// { $set: { motor_status: newMotorStatus } }, -// { new: true } // To return the updated document -// ); - -// reply.send({ status_code: 200, motor_status: result.motor_status }); -// } else { -// reply.send({ status_code: 200, motor_status: newMotorStatus }); -// } -// } else { -// reply.send({ status_code: 200, message: 'Motor stop status is not "on" or "off".' }); -// } -// } catch (err) { -// throw boom.boomify(err); -// } -// }; - exports.writeMotorStatus = async (req, reply) => { try { const motor_id = req.body.motor_id; @@ -4745,40 +4643,6 @@ exports.writeMotorStatus = async (req, reply) => { }; -// const motor_id = req.body.motor_id; -// const status = req.body.status; - -// // Find the tank that contains the specified motor_id in its inputConnections -// const tank = await Tank.findOne({ "connections.inputConnections.motor_id": motor_id }); - -// if (!tank) { -// return reply.status(404).send({ -// status_code: 404, -// message: 'Motor not found for the specified motor_id' -// }); -// } - -// // Find the inputConnection with the specified motor_id -// const inputConnection = tank.connections.inputConnections.find(conn => conn.motor_id === motor_id); - -// // Update the motor_status of the inputConnection -// inputConnection.motor_status = status; - -// // Update real_motor_status based on the conditions -// -// // Save the updated tank -// await tank.save(); - -// // Send the response with the updated motor_status -// reply.send({ -// status_code: 200, -// motor_status: status -// }); -// } catch (err) { -// throw boom.boomify(err); -// } -// }; - exports.changeMotorStatus = async (req, reply) => { @@ -5089,28 +4953,6 @@ client.on('message', async (topic, message) => { - -// Function to publish motor stop status -// exports.publishMotorStopStatus = async (motor_id, motor_stop_status) => { -// const payload = { -// topic: 'operation', -// object: { -// 'motor-id': motor_id, -// control: motor_stop_status -// } -// }; - -// client.publish('water/operation', JSON.stringify(payload)); -// }; - - - - -//const moment = require('moment'); - - - - exports.getPendingAndCompletedsurveyOfparticularInstaller = async (request, reply) => { try { const { installationId } = request.params; @@ -5340,4 +5182,4 @@ async function removeDuplicates () { // Run the remove duplicates function // removeDuplicates(); -console.log("this is for testing autopush,line located in tankscontroller") \ No newline at end of file +console.log("this is for testing autopush,line located in tankscontroller") diff --git a/src/models/tanks.js b/src/models/tanks.js index 86506184..31884e11 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -175,6 +175,8 @@ const tankconsumptionoriginalSchema = new mongoose.Schema({ tankName: { type: String }, tankLocation: { type: String }, consumption: { type: String }, + consumed_percentage:{ type: String }, + available_capacity:{ type: String }, block:{type: String}, typeofwater:{type:String}, time: { type: String }