diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 3306b2f1..25a490ad 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1,5 +1,5 @@ //const Tank = require("../models/tanks"); -const { Tank, MotorData, IotData,MotorIot,TankWaterLevel } = require('../models/tanks') +const { Tank, MotorData, IotData,MotorIot,TankWaterLevel,TankConsumptionSchema } = require('../models/tanks') const User = require("../models/User"); const boom = require("boom"); @@ -824,64 +824,112 @@ let supplier_tanks = []; // }; -exports.consumption = async (request, reply) => { - // try { - // const customerId = req.params.customerId; - // const tanks = await Tank.find({ customerId,tankLocation:"overhead"}); - // const tankData = []; - // for (const tank of tanks) { - // const tankId = tank._id; - // 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); +// exports.consumption = async (request, reply) => { +// try { +// const customerId = req.params.customerId; +// const tanks = await Tank.find({ customerId,tankLocation:"overhead"}); +// const tankData = []; +// for (const tank of tanks) { +// const tankId = tank._id; +// 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 consumption = (waterlevel_at_midnight+total_water_added_from_midnight)-waterlevel - - // const newWaterLevel1 = Math.floor(consumption); - // const newWaterLevel=Math.abs(newWaterLevel1) - // tankData.push({ tankname, waterLevel: newWaterLevel }); +// const tankname = tank.tankName +// const consumption = (waterlevel_at_midnight+total_water_added_from_midnight)-waterlevel + +// tankData.push({ tankname, waterLevel: consumption }); - // // console.log(newWaterLevel); +// // console.log(newWaterLevel); + +// } +// reply.send({ status_code: 200, tankData }); + +// return { message: 'Water level updates started' }; +// } catch (err) { +// throw boom.boomify(err); +// } + + + - // } - // reply.send({ status_code: 200, tankData }); - // return { message: 'Water level updates started' }; - // } catch (err) { - // throw boom.boomify(err); - // } +function parseDateTime(dateTimeStr) { + const [datePart, timePart] = dateTimeStr.split(' - '); + const [day, month, year] = datePart.split('-'); + const monthIndex = new Date(Date.parse(month +" 1, 2024")).getMonth(); // Parse the month name to get its index + const [hours, minutes] = timePart.split(':'); + return new Date(year, monthIndex, day, hours, minutes); +} +exports.consumption = async (request, reply) => { try { + const { customerId } = request.params; + const { startDate, stopDate } = request.body; - const tank = await Tank.find({ customerId, tankLocation:"overhead" }); + const start = parseDateTime(startDate); + const end = parseDateTime(stopDate); + const tanks = await Tank.find({ customerId, tankLocation: "overhead" }); + const tankData = []; - if (!tank) { - return reply.status(404).send({ error: 'Tank not found' }); + for (const tank of tanks) { + const tankId = tank._id; + 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; + console.log(waterlevel_at_midnight,total_water_added_from_midnight,waterlevel) + const tankConsumptions = await TankConsumptionSchema.find({ + customerId, + tankName: tank.tankName, + tankLocation: tank.tankLocation, + time: { + $gte: start, + $lte: end + } + }); + + const total_consumption_from_records = tankConsumptions.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; + + tankData.push({ tankname, totalConsumption: consumption }); } - // Here you can process and return the consumption data as needed - return reply.send(tank); - } catch (error) { - request.log.error(error); - return reply.status(500).send({ error: 'Internal Server Error' }); + reply.send({ status_code: 200, tankData }); + } catch (err) { + throw boom.boomify(err); } - }; + +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); + //const moment = require('moment'); // Import moment.js for date/time operations +const formatDate = (date) => { + const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + const day = String(date.getDate()).padStart(2, '0'); + const month = months[date.getMonth()]; + const year = date.getFullYear(); + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + return `${day}-${month}-${year} - ${hours}:${minutes}`; +}; exports.motorAction = async (req, reply) => { try { const customerId = req.params.customerId; const action = req.body.action; const motorId = req.body.motor_id; + const start_instance_id = req.body.start_instance_id console.log(req.body.startTime) // Ensure motor_id is provided if (!motorId) { @@ -912,6 +960,30 @@ exports.motorAction = async (req, reply) => { } } ); + + await delay(300000); + + // Update the existing motor data entry with stop details + 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 water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10); + const totalwaterpumped = quantityDelivered + water_pumped_till_now + await Tank.findOneAndUpdate({customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase()}, { $set: { total_water_added_from_midnight: totalwaterpumped } }) + + await MotorData.updateOne( + { customerId, motor_id: motorId, start_instance_id: start_instance_id }, + { + $set: { + stopTime: req.body.stopTime, + receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), + quantity_delivered: quantityDelivered.toString() + } + } + ); + } @@ -931,14 +1003,27 @@ exports.motorAction = async (req, reply) => { // { customerId, "connections.inputConnections.motor_id": motorId }, // { $set: { "connections.inputConnections.$.manual_threshold_time": req.body.manual_threshold_time,startTime:req.body.startTime } } // ); - + const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); + + const newMotorData = new MotorData({ + customerId: customerId, + motor_id: motorId, + start_instance_id: start_instance_id, + supplierTank: req.body.from, + receiverTank: req.body.to, + supplier_type: req.body.from_type, + receiver_type: req.body.to_type, + startTime: req.body.startTime, + receiverInitialwaterlevel:parseInt(receiver_tank_info7.waterlevel, 10) + }); + await newMotorData.save(); 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 }, - { $set: { [`connections.inputConnections.${index}.manual_threshold_time`]: req.body.manual_threshold_time, [`connections.inputConnections.${index}.startTime`]: req.body.startTime } } + { $set: { [`connections.inputConnections.${index}.manual_threshold_time`]: req.body.manual_threshold_time, [`connections.inputConnections.${index}.startTime`]: req.body.startTime,[`connections.inputConnections.${index}.start_instance_id`]: start_instance_id } } ); } } @@ -949,28 +1034,65 @@ exports.motorAction = async (req, reply) => { const intervalId = setInterval(async () => { const splr_tank_info3 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); const splr_tank_info3_waterlevel = parseInt(splr_tank_info3.waterlevel, 10); - const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity, 10); + const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity, 10); const splr_tank_info3_percentage = (splr_tank_info3_waterlevel / splr_tank_info3_capacity) * 100; - console.log(splr_tank_info3_percentage,"percentage for less than 20") + console.log(splr_tank_info3_percentage, "percentage for less than 20"); - if (new Date() >= thresholdTime || splr_tank_info3_percentage<=20) { - // Stop the motor pump + if (new Date() >= thresholdTime || splr_tank_info3_percentage <= 20) { await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, - { - $set: { + { + $set: { "connections.inputConnections.$.motor_stop_status": "1", - "connections.inputConnections.$.threshold_type": null, "connections.inputConnections.$.manual_threshold_time": null, "connections.inputConnections.$.manual_threshold_percentage": null } } ); - clearInterval(intervalId); // Stop monitoring water level + clearInterval(intervalId); + + await delay(300000); + + 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 water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10); + const totalwaterpumped = quantityDelivered + water_pumped_till_now + await Tank.findOneAndUpdate({customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase()}, { $set: { total_water_added_from_midnight: totalwaterpumped } }) + + const stopTime = formatDate(new Date()); + + await MotorData.updateOne( + { customerId, motor_id: motorId, start_instance_id: start_instance_id }, + { + $set: { + stopTime:stopTime, + receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), + quantity_delivered: quantityDelivered.toString() + } + } + ); + } } - }, 60000); // Check water level every minute + }, 60000); } else if (req.body.threshold_type === "litres") { + const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); + + const newMotorData = new MotorData({ + customerId: customerId, + motor_id: motor_id, + start_instance_id: start_instance_id, + supplierTank: req.body.from, + receiverTank: req.body.to, + supplier_type: req.body.from_type, + receiver_type: req.body.to_type, + startTime: req.body.startTime, + receiverwaterlevel:parseInt(receiver_tank_info7.waterlevel, 10) + }); + await newMotorData.save(); // If threshold type is percentage, calculate percentage threshold const receiver_tank_info = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); const supplier_tank_info = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); @@ -1026,6 +1148,28 @@ exports.motorAction = async (req, reply) => { } ); clearInterval(intervalId); // Stop monitoring water level + await delay(300000); + + 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 stopTime = formatDate(new Date()); + + await MotorData.updateOne( + { customerId, motor_id: motorId, start_instance_id: start_instance_id }, + { + $set: { + stopTime:stopTime, + receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), + quantity_delivered: quantityDelivered.toString() + } + } + ); + } } }, 20000); // Check water level every minute } @@ -2030,37 +2174,102 @@ exports.startUpdateLoop = async (request, reply) => { }; -exports.updatewaterlevelsatmidnight = async (req, 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 () => { + console.log('Cron job triggered at:', moment().tz('Asia/Kolkata').format()); + 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); - } - }); + const tanks = await Tank.find({}); + for (const tank of tanks) { + tank.waterlevel_at_midnight = tank.waterlevel; + tank.total_water_added_from_midnight = "0"; + await tank.save(); + console.log(`Updated tank ${tank._id} waterlevel_at_midnight to ${tank.waterlevel}`); + } + 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 }); +// Schedule the task to run every day at 13:49 IST (1:49 PM IST) +cron.schedule('0 0 * * *', updatewaterlevelsatmidnight, { + timezone: "Asia/Kolkata" +}); + + + + + + + +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 + const newTankConsumption = new TankConsumptionSchema({ + customerId: tank.customerId, + tankName: tank.tankName, + tankLocation: tank.tankLocation, + consumption: totalconsumption.toString(), + time: new Date().toISOString() }); - } catch (err) { - throw boom.boomify(err); + + // 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 13:49 IST (1:49 PM IST) +cron.schedule('55 23 * * *', updatetotalConsumptiontillmidnight, { + timezone: "Asia/Kolkata" +}); + + + + exports.deletemotordatarecordsbefore7days = async (req, reply) => { try { @@ -2416,18 +2625,6 @@ const storeWaterLevels = async () => { setInterval(storeWaterLevels, 15 * 60 * 1000); -const updateWaterLevelAtMidnight = async () => { - try { - await Tank.updateMany({}, { $set: { waterlevel_at_midnight: '$waterlevel' } }); - console.log('Water levels updated at midnight'); - } catch (error) { - console.error('Error updating water levels:', error); - } -}; -// Schedule the job to run at midnight every day -cron.schedule('0 0 * * *', async () => { - await updateWaterLevelAtMidnight(); -}); console.log('Cron job scheduled to update water levels at midnight'); \ No newline at end of file diff --git a/src/models/tanks.js b/src/models/tanks.js index a1cc2b34..4c4dae84 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -45,19 +45,12 @@ const tanksSchema = new mongoose.Schema({ waterCapacityPerCm:{ type: String, default: "0" }, typeOfWater: { type: String, default: null }, waterlevel: { type: String, default: "0" }, - tankLocation: { type: String, default: null }, - motor_status: { type: String, default: "1" }, - motor_stop_status: { type: String, default: "1" }, - motor_speed: { type: String, default: "100" }, - motor_temperature: { type: String, default: "0" }, waterlevel_at_midnight:{ type: String,default:"0" }, total_water_added_from_midnight:{ type: String,default:"0" }, auto_min_percentage :{ type: String, default: "20" }, reserved_percentage:{type: String,default:"20"}, auto_max_percentage :{ type: String, default: "80" }, - - - + connections: { source: { type: String }, inputConnections: [ @@ -104,8 +97,12 @@ const tanksSchema = new mongoose.Schema({ const motordataSchema = new mongoose.Schema({ customerId: { type: String, default: null }, + motor_id: { type: String, default: null }, + start_instance_id:{type:String,default:null}, supplierTank: { type: String, default: null }, receiverTank: { type: String, default: null }, + receiverInitialwaterlevel: { type: String, default: "0" }, + receiverfinalwaterlevel: { type: String, default: "0" }, startTime: { type: String, default: null }, stopTime: { type: String, default: null }, supplier_type: { type: String, default: null }, @@ -142,14 +139,23 @@ const tankWaterLevelSchema = new mongoose.Schema({ time: { type: String } }); - +const tankconsumptionSchema = new mongoose.Schema({ + customerId: { type: String }, + tankName: { type: String }, + tankLocation: { type: String }, + consumption: { type: String }, + time: { type: String } +}); + const Tank = mongoose.model("Tank", tanksSchema); const MotorData = mongoose.model("MotorData", motordataSchema); const TankWaterLevel = mongoose.model("TankWaterLevel", tankWaterLevelSchema); const IotData = mongoose.model("IotData", IOttankSchema); +const TankConsumptionSchema = mongoose.model("TankConsumptionSchema", tankconsumptionSchema); + module.exports = { - Tank, MotorData,IotData,TankWaterLevel + Tank, MotorData,IotData,TankWaterLevel,TankConsumptionSchema } diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index fa4bccbf..7cf084b2 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -308,8 +308,45 @@ module.exports = function (fastify, opts, next) { }); + // fastify.route({ + // method: "PUT", + // url: "/api/consumption/:customerId", + // schema: { + // tags: ["Tank"], + // summary: "This is for getting consumption", + // params: { + // required: ["customerId"], + // type: "object", + // properties: { + // customerId: { + // type: "string", + // description: "customerId", + // }, + // }, + // }, + + // body: { + // type: "object", + + // properties: { + + // startDate:{ type: "string" }, + // stopDate:{type:"string"}, + + // }, + // }, + // security: [ + // { + // basicAuth: [], + // }, + // ], + // }, + // //preHandler: fastify.auth([fastify.authenticate]), + // handler: tanksController.consumption, + // }); + fastify.route({ - method: "GET", + method: "PUT", url: "/api/consumption/:customerId", schema: { tags: ["Tank"], @@ -324,9 +361,17 @@ module.exports = function (fastify, opts, next) { }, }, }, - // querystring: { - // tankName: {type: 'string'} - // }, + + body: { + type: "object", + // required: ['phone'], + properties: { + startDate:{ type: "string" }, + stopDate:{type:"string"}, + + + }, + }, security: [ { basicAuth: [], @@ -337,6 +382,12 @@ module.exports = function (fastify, opts, next) { handler: tanksController.consumption, }); + + + + + + fastify.route({ method: "PUT", url: "/api/calculateCapacity", @@ -558,23 +609,23 @@ module.exports = function (fastify, opts, next) { handler: tanksController.startUpdateLoop, }); - fastify.get("/api/updatewaterlevelsatmidnight", { - schema: { - tags: ["Tank"], - description: "This is for storing waterlevels in tank at midnight", - summary: "This is for storing waterlevels in tank at midnight", - querystring: { - customerId: {type: 'string'} - }, - security: [ - { - basicAuth: [], - }, - ], - }, - preHandler: fastify.auth([fastify.authenticate]), - handler: tanksController.updatewaterlevelsatmidnight, - }); + // fastify.get("/api/updatewaterlevelsatmidnight", { + // schema: { + // tags: ["Tank"], + // description: "This is for storing waterlevels in tank at midnight", + // summary: "This is for storing waterlevels in tank at midnight", + // querystring: { + // customerId: {type: 'string'} + // }, + // security: [ + // { + // basicAuth: [], + // }, + // ], + // }, + // preHandler: fastify.auth([fastify.authenticate]), + // handler: tanksController.updatewaterlevelsatmidnight, + // });