all notifications committed

master^2
Varun 8 months ago
parent 777d1f045d
commit 8650905cb8

@ -2820,7 +2820,7 @@ const monitorWaterLevels = async () => {
}; };
// Schedule the task to run every 30 minutes // Schedule the task to run every 30 minutes
setInterval(monitorWaterLevels, 30 * 60 * 1000); // setInterval(monitorWaterLevels, 30 * 60 * 1000);
const motorIntervals = {}; const motorIntervals = {};
async function calculateTotalPumpedWater(customerId, motorId, start_instance_id) { async function calculateTotalPumpedWater(customerId, motorId, start_instance_id) {
@ -4958,38 +4958,38 @@ exports.totalwaterLevelSum = async (request, reply) => {
} }
exports.startUpdateLoop = async (request, reply) => { // exports.startUpdateLoop = async (request, reply) => {
const updateInterval = 5000; // const updateInterval = 5000;
setInterval(async () => { // setInterval(async () => {
try { // try {
const iotTank = await IotData.findOne({ hardwareId: request.body.hardwareId }); // const iotTank = await IotData.findOne({ hardwareId: request.body.hardwareId });
if (!iotTank) { // if (!iotTank) {
console.log(`IOTtank not found for hardwareId ${request.body.hardwareId}`); // console.log(`IOTtank not found for hardwareId ${request.body.hardwareId}`);
return; // return;
} // }
const currentWaterlevel = Number(iotTank.tankHeight) * 200; // const currentWaterlevel = Number(iotTank.tankHeight) * 200;
const tank = await Tank.findOne({ hardwareId: iotTank.hardwareId }); // const tank = await Tank.findOne({ hardwareId: iotTank.hardwareId });
let combinedWaterlevel; // let combinedWaterlevel;
if (tank) { // if (tank) {
combinedWaterlevel = currentWaterlevel + Number(tank.waterlevel); // combinedWaterlevel = currentWaterlevel + Number(tank.waterlevel);
} else { // } else {
combinedWaterlevel = currentWaterlevel; // combinedWaterlevel = currentWaterlevel;
} // }
await Tank.updateOne({ hardwareId: iotTank.hardwareId }, { $set: { waterlevel: combinedWaterlevel } }); // await Tank.updateOne({ hardwareId: iotTank.hardwareId }, { $set: { waterlevel: combinedWaterlevel } });
console.log(`Waterlevel updated successfully for hardwareId ${iotTank.hardwareId}`); // console.log(`Waterlevel updated successfully for hardwareId ${iotTank.hardwareId}`);
console.log(`Previous waterlevel: ${tank ? tank.waterlevel : 0}`); // console.log(`Previous waterlevel: ${tank ? tank.waterlevel : 0}`);
console.log(`Current waterlevel: ${currentWaterlevel}`); // console.log(`Current waterlevel: ${currentWaterlevel}`);
console.log(`Combined waterlevel: ${combinedWaterlevel}`); // console.log(`Combined waterlevel: ${combinedWaterlevel}`);
} catch (err) { // } catch (err) {
console.error(err); // console.error(err);
} // }
}, updateInterval); // }, updateInterval);
}; // };
@ -6792,72 +6792,72 @@ exports.sendUserAutomaticStartAndStop = async (request, reply) => {
// } // }
// }; // };
const calculateWaterLevelAndNotify = async () => { // const calculateWaterLevelAndNotify = async () => {
try { // try {
const now = moment(); // const now = moment();
const currentTime = now.format("HH:mm"); // Current time in HH:mm format // const currentTime = now.format("HH:mm"); // Current time in HH:mm format
console.log(`Current time: ${currentTime}`); // console.log(`Current time: ${currentTime}`);
// Get all users who have allowed notifications and have set a notification time // // Get all users who have allowed notifications and have set a notification time
const users = await User.find({ allowNotifications: true, notificationTime: currentTime }); // const users = await User.find({ allowNotifications: true, notificationTime: currentTime });
if (users.length === 0) { // if (users.length === 0) {
console.log("No users to notify at this time."); // console.log("No users to notify at this time.");
return; // return;
} // }
for (const user of users) { // for (const user of users) {
const { customerId, fcmIds } = user; // const { customerId, fcmIds } = user;
if (!Array.isArray(fcmIds) || fcmIds.length === 0) { // if (!Array.isArray(fcmIds) || fcmIds.length === 0) {
console.log(`No valid FCM tokens for customer ID: ${customerId}`); // console.log(`No valid FCM tokens for customer ID: ${customerId}`);
continue; // continue;
} // }
// // Get tanks associated with the user
// const tanks = await Tank.find({ customerId });
// for (const tank of tanks) {
// const {
// tankName,
// tankLocation,
// typeOfWater,
// capacity,
// waterlevel,
// waterlevel_at_midnight,
// } = tank;
// Get tanks associated with the user // // Remove commas before parsing numbers
const tanks = await Tank.find({ customerId }); // const tankCapacity = parseFloat(capacity.replace(/,/g, '')) || 0;
// const currentWaterLevel = parseFloat(waterlevel.replace(/,/g, '')) || 0;
// const midnightWaterLevel = parseFloat(waterlevel_at_midnight.replace(/,/g, '')) || 0;
for (const tank of tanks) { // if (tankCapacity === 0) {
const { // console.log(`Skipping tank ${tankName} due to zero capacity`);
tankName, // continue;
tankLocation, // }
typeOfWater,
capacity,
waterlevel,
waterlevel_at_midnight,
} = tank;
// 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 currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2);
const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel; // const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel;
const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2); // const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2);
let notificationBody = // let notificationBody =
`🛢️ Tank Name: ${tankName}\n` + // `🛢️ Tank Name: ${tankName}\n` +
`🏢 Location: ${tankLocation}\n` + // `🏢 Location: ${tankLocation}\n` +
`💧 Type of Water: ${typeOfWater}\n` + // `💧 Type of Water: ${typeOfWater}\n` +
`Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`; // `Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`;
await sendNotification(customerId, fcmIds, "Water Level Update", notificationBody); // await sendNotification(customerId, fcmIds, "Water Level Update", notificationBody);
console.log("Notification sent for tank:", tankName); // console.log("Notification sent for tank:", tankName);
} // }
} // }
console.log("Water level notifications processed."); // console.log("Water level notifications processed.");
} catch (err) { // } catch (err) {
console.error("Error in water level calculation:", err); // console.error("Error in water level calculation:", err);
} // }
}; // };
// const calculateLowWaterLevelAndNotify = async () => { // const calculateLowWaterLevelAndNotify = async () => {
// try { // try {
// const now = moment(); // const now = moment();
@ -7161,14 +7161,14 @@ exports.listofactiveandinactivetankstatus = async (req, reply) => {
}; };
exports.notificationTiming = async (req, reply) => { // exports.notificationTiming = async (req, reply) => {
const { customerId, notificationPreference } = req.body; // const { customerId, notificationPreference } = req.body;
if (!["never", "always", "6_hours", "8_hours", "1_month"].includes(notificationPreference)) { // if (!["never", "always", "6_hours", "8_hours", "1_month"].includes(notificationPreference)) {
return reply.status(400).send({ message: "Invalid preference" }); // return reply.status(400).send({ message: "Invalid preference" });
} // }
await User.updateOne({ customerId }, { notificationPreference }); // await User.updateOne({ customerId }, { notificationPreference });
return reply.send({ message: "Preference updated successfully" }); // return reply.send({ message: "Preference updated successfully" });
} // }

@ -742,48 +742,48 @@ module.exports = function (fastify, opts, next) {
}); });
fastify.route({ // fastify.route({
method: 'POST', // method: 'POST',
url: '/update-waterlevel', // url: '/update-waterlevel',
schema: { // schema: {
tags: ['Tank'], // tags: ['Tank'],
description: 'This is for updating waterlevel of a tank based on its IOTtank document', // description: 'This is for updating waterlevel of a tank based on its IOTtank document',
summary: 'This is for updating waterlevel of a tank', // summary: 'This is for updating waterlevel of a tank',
body: { // body: {
type: 'object', // type: 'object',
properties: { // properties: {
hardwareId: { type: 'string' }, // hardwareId: { type: 'string' },
}, // },
required: ['hardwareId'], // required: ['hardwareId'],
}, // },
response: { // response: {
200: { // 200: {
type: 'object', // type: 'object',
properties: { // properties: {
message: { type: 'string' }, // message: { type: 'string' },
}, // },
}, // },
404: { // 404: {
type: 'object', // type: 'object',
properties: { // properties: {
message: { type: 'string' }, // message: { type: 'string' },
}, // },
}, // },
500: { // 500: {
type: 'object', // type: 'object',
properties: { // properties: {
message: { type: 'string' }, // message: { type: 'string' },
}, // },
}, // },
}, // },
security: [ // security: [
{ // {
basicAuth: [], // basicAuth: [],
}, // },
], // ],
}, // },
handler: tanksController.startUpdateLoop, // handler: tanksController.startUpdateLoop,
}); // });
// fastify.get("/api/updatewaterlevelsatmidnight", { // fastify.get("/api/updatewaterlevelsatmidnight", {
// schema: { // schema: {
@ -1419,36 +1419,36 @@ module.exports = function (fastify, opts, next) {
handler: tanksController.sendUserAutomaticStartAndStop, handler: tanksController.sendUserAutomaticStartAndStop,
}); });
fastify.route({ // fastify.route({
method: "POST", // method: "POST",
url: "/api/sendNotificationDailyPreference", // url: "/api/sendNotificationDailyPreference",
schema: { // schema: {
tags: ["Tank"], // tags: ["Tank"],
summary: "This is for time based notification preferences", // summary: "This is for time based notification preferences",
body: { // body: {
type: "object", // type: "object",
properties: { // properties: {
customerId: { // customerId: {
type: "string", // type: "string",
}, // },
notificationPreference: { // notificationPreference: {
type: "string", // type: "string",
}, // },
// allowNotifications: { // // allowNotifications: {
// type: "boolean" // // type: "boolean"
// } // // }
}, // },
}, // },
security: [ // security: [
{ // {
basicAuth: [], // basicAuth: [],
}, // },
], // ],
}, // },
//preHandler: fastify.auth([fastify.authenticate]), // //preHandler: fastify.auth([fastify.authenticate]),
handler: tanksController.notificationTiming, // handler: tanksController.notificationTiming,
}); // });
fastify.route({ fastify.route({

Loading…
Cancel
Save