schedule time based notifications to send all tanks details

master^2
Bhaskar 9 months ago
parent 539bb63044
commit 2d8e1e21d7

6
node_modules/.package-lock.json generated vendored

@ -9243,9 +9243,9 @@
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="
},
"node_modules/node-cron": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.2.tgz",
"integrity": "sha512-iP8l0yGlNpE0e6q1o185yOApANRe47UPbLf4YxfbiNHt/RU5eBcGB/e0oudruheSf+LQeDMezqC5BVAb5wwRcQ==",
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",
"integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",
"dependencies": {
"uuid": "8.3.2"
},

14
package-lock.json generated

@ -55,7 +55,7 @@
"mqtt": "^5.10.1",
"multer": "^1.4.5-lts.1",
"mv": "^2.1.1",
"node-cron": "^3.0.2",
"node-cron": "^3.0.3",
"node-schedule": "^2.1.1",
"nodemon": "^2.0.20",
"nunjucks": "^3.2.3",
@ -9321,9 +9321,9 @@
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="
},
"node_modules/node-cron": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.2.tgz",
"integrity": "sha512-iP8l0yGlNpE0e6q1o185yOApANRe47UPbLf4YxfbiNHt/RU5eBcGB/e0oudruheSf+LQeDMezqC5BVAb5wwRcQ==",
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",
"integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",
"dependencies": {
"uuid": "8.3.2"
},
@ -20052,9 +20052,9 @@
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="
},
"node-cron": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.2.tgz",
"integrity": "sha512-iP8l0yGlNpE0e6q1o185yOApANRe47UPbLf4YxfbiNHt/RU5eBcGB/e0oudruheSf+LQeDMezqC5BVAb5wwRcQ==",
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",
"integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",
"requires": {
"uuid": "8.3.2"
}

@ -56,7 +56,7 @@
"mqtt": "^5.10.1",
"multer": "^1.4.5-lts.1",
"mv": "^2.1.1",
"node-cron": "^3.0.2",
"node-cron": "^3.0.3",
"node-schedule": "^2.1.1",
"nodemon": "^2.0.20",
"nunjucks": "^3.2.3",

@ -2203,20 +2203,20 @@ console.log(fcmToken)
// Schedule a task to send a notification when the threshold time is reached
motorIntervals[motorId] = setTimeout(async () => {
try {
// Perform threshold time logic (e.g., notification, motor stop)
console.log(`Threshold time of ${manual_threshold_time} minutes reached for motor ${motorId}`);
await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId },
{ $set: { "connections.inputConnections.$.motor_stop_status": "1" } }
);
clearTimeout(motorIntervals[motorId]); // Clear timeout
delete motorIntervals[motorId];
} catch (error) {
console.error("Error in threshold time handling:", error);
}
}, thresholdTimeMs);
// motorIntervals[motorId] = setTimeout(async () => {
// try {
// // Perform threshold time logic (e.g., notification, motor stop)
// console.log(`Threshold time of ${manual_threshold_time} minutes reached for motor ${motorId}`);
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// { $set: { "connections.inputConnections.$.motor_stop_status": "1" } }
// );
// clearTimeout(motorIntervals[motorId]); // Clear timeout
// delete motorIntervals[motorId];
// } catch (error) {
// console.error("Error in threshold time handling:", error);
// }
// }, thresholdTimeMs);
const stopCriteria =
motorOnType === "time"
? `${req.body.manual_threshold_time} minutes`
@ -2258,27 +2258,27 @@ console.log(fcmToken)
// Schedule threshold check
// const thresholdTimeMs = manual_threshold_time * 60 * 1000;
motorIntervals[motorId] = setTimeout(async () => {
try {
// const stopMessage = `Threshold time of ${manual_threshold_time} minutes reached for motor supplying water to '${tankName}' in block '${blockName}'.`;
// eventEmitter.emit('sendThresholdTimeNotification', fcmToken, stopMessage);
// motorIntervals[motorId] = setTimeout(async () => {
// try {
// // const stopMessage = `Threshold time of ${manual_threshold_time} minutes reached for motor supplying water to '${tankName}' in block '${blockName}'.`;
// // eventEmitter.emit('sendThresholdTimeNotification', fcmToken, stopMessage);
await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId },
{
$set: {
"connections.inputConnections.$.motor_stop_status": "1",
"connections.inputConnections.$.manual_threshold_time": null,
"connections.inputConnections.$.threshold_type": null,
}
}
);
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $set: {
// "connections.inputConnections.$.motor_stop_status": "1",
// "connections.inputConnections.$.manual_threshold_time": null,
// "connections.inputConnections.$.threshold_type": null,
// }
// }
// );
delete motorIntervals[motorId];
} catch (error) {
console.error("Error during threshold handling:", error);
}
}, thresholdTimeMs);
// delete motorIntervals[motorId];
// } catch (error) {
// console.error("Error during threshold handling:", error);
// }
// }, thresholdTimeMs);
reply.code(200).send({ message: "Motor started successfully." });
// Schedule water level checks after motor start
@ -2317,23 +2317,23 @@ console.log(fcmToken)
motorOnType
);
await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId },
{
$set: {
"connections.inputConnections.$.motor_stop_status": "1",
"connections.inputConnections.$.motor_on_type": "manual",
}
}
);
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $set: {
// "connections.inputConnections.$.motor_stop_status": "1",
// "connections.inputConnections.$.motor_on_type": "manual",
// }
// }
// );
// const stopMessage = `Motor supplying water to '${tankName}' in block '${blockName}' stopped manually at ${stopTime}.`;
// eventEmitter.emit('sendMotorStopNotification', fcmToken, stopMessage);
if (motorIntervals[motorId]) {
clearTimeout(motorIntervals[motorId]);
delete motorIntervals[motorId];
}
// if (motorIntervals[motorId]) {
// clearTimeout(motorIntervals[motorId]);
// delete motorIntervals[motorId];
// }
} else {
throw new Error("Invalid action provided.");
@ -5341,3 +5341,73 @@ async function removeDuplicates () {
// Run the remove duplicates function
// removeDuplicates();
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
}
);
Loading…
Cancel
Save