Varun 10 months ago
commit d5e27ef501

@ -6281,19 +6281,76 @@ const calculateConsumptionAndNotify = async () => {
} }
}; };
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 // Schedule notifications at 6 AM, 12 PM, 6 PM, and 12 AM
cron.schedule( cron.schedule(
"0 6,12,18,0 * * *", // Cron expression for the required times "0 6,12,18,0 * * *", // Cron expression for the required times
async () => { async () => {
console.log("Starting scheduled consumption notification task..."); console.log("Starting scheduled consumption notification task...");
await calculateConsumptionAndNotify(); //await calculateConsumptionAndNotify();
await calculateWaterLevelAndNotify();
}, },
{ {
timezone: "Asia/Kolkata", // Specify the timezone timezone: "Asia/Kolkata", // Specify the timezone
} }
); );
// const updateStopTimeFormat = async () => { // const updateStopTimeFormat = async () => {
// try { // try {
// // Find records where stopTime is null or not in the required format // // Find records where stopTime is null or not in the required format

Loading…
Cancel
Save