comment code notifications

master^2
Bhaskar 3 weeks ago
parent edc48b738e
commit f9ea6a414e

@ -2310,142 +2310,142 @@ const sendNotification = async (hw_Id, customerId, fcmIds, title, body) => {
// Function to send notifications // Function to send notifications
const sendDailyConsumptionNotification = async () => { // const sendDailyConsumptionNotification = async () => {
try { // try {
const now = new Date(); // const now = new Date();
const currentTime = moment(now).format("HH:mm"); // e.g., "09:30" // const currentTime = moment(now).format("HH:mm"); // e.g., "09:30"
const currentDate = moment(now).format("DD-MMM-YYYY"); // e.g., "28-Feb-2025" // const currentDate = moment(now).format("DD-MMM-YYYY"); // e.g., "28-Feb-2025"
console.log(`🕒 Checking users for scheduled notifications at ${currentTime}`); // console.log(`🕒 Checking users for scheduled notifications at ${currentTime}`);
// Fetch unique users who have enabled notifications for the current time // // Fetch unique users who have enabled notifications for the current time
const users = await User.find({ // const users = await User.find({
allowNotifications: true, // allowNotifications: true,
notificationTime: currentTime, // notificationTime: currentTime,
}).select("customerId fcmIds lastNotificationSent").lean(); // }).select("customerId fcmIds lastNotificationSent").lean();
// Ensure unique customers only // // Ensure unique customers only
const uniqueUsers = users.filter((user, index, self) => // const uniqueUsers = users.filter((user, index, self) =>
index === self.findIndex((u) => u.customerId === user.customerId) // index === self.findIndex((u) => u.customerId === user.customerId)
); // );
if (uniqueUsers.length === 0) { // if (uniqueUsers.length === 0) {
console.log("⏳ No users have notifications scheduled for this time."); // console.log("⏳ No users have notifications scheduled for this time.");
return; // return;
} // }
for (const user of uniqueUsers) { // for (const user of uniqueUsers) {
const { customerId, fcmIds, lastNotificationSent } = user; // const { customerId, fcmIds, lastNotificationSent } = user;
// Ensure user has valid FCM tokens // // Ensure user has valid FCM tokens
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;
} // }
// Remove duplicate and trim tokens // // Remove duplicate and trim tokens
const uniqueTokens = [...new Set(fcmIds.map(token => token.trim()))]; // const uniqueTokens = [...new Set(fcmIds.map(token => token.trim()))];
// Check if notification should be sent based on lastNotificationSent // // Check if notification should be sent based on lastNotificationSent
const lastSent = new Date(lastNotificationSent || 0); // const lastSent = new Date(lastNotificationSent || 0);
if (now - lastSent < 24 * 60 * 60 * 1000) { // if (now - lastSent < 24 * 60 * 60 * 1000) {
console.log(`⏳ Skipping notification for ${customerId}, already sent in the last 24 hours.`); // console.log(`⏳ Skipping notification for ${customerId}, already sent in the last 24 hours.`);
continue; // continue;
} // }
// Fetch last 24-hour consumption data // // Fetch last 24-hour consumption data
const startTime = moment(now).subtract(1, "days").format("DD-MMM-YYYY - HH:mm"); // const startTime = moment(now).subtract(1, "days").format("DD-MMM-YYYY - HH:mm");
const endTime = moment(now).format("DD-MMM-YYYY - HH:mm"); // const endTime = moment(now).format("DD-MMM-YYYY - HH:mm");
console.log(`📅 Fetching consumption for ${customerId} from ${startTime} to ${endTime}`); // console.log(`📅 Fetching consumption for ${customerId} from ${startTime} to ${endTime}`);
const consumptions = await TankConsumptionOriginalSchema.find({ // const consumptions = await TankConsumptionOriginalSchema.find({
customerId, // customerId,
time: { $gte: startTime, $lt: endTime }, // time: { $gte: startTime, $lt: endTime },
}); // });
if (consumptions.length === 0) { // if (consumptions.length === 0) {
console.log(`❌ No consumption data found for ${customerId}`); // console.log(`❌ No consumption data found for ${customerId}`);
continue; // continue;
} // }
// Standardized mapping for water types // // Standardized mapping for water types
const typeMapping = { // const typeMapping = {
"bore water": "Bore Water", // "bore water": "Bore Water",
"bore": "Bore Water", // "bore": "Bore Water",
"drinking": "Drinking Water", // "drinking": "Drinking Water",
"drink": "Drinking Water", // "drink": "Drinking Water",
"DRINK": "Drinking Water" // "DRINK": "Drinking Water"
}; // };
// Calculate consumption per water type // // Calculate consumption per water type
let totalConsumption = 0; // let totalConsumption = 0;
let consumptionByType = {}; // let consumptionByType = {};
for (const record of consumptions) { // for (const record of consumptions) {
let { typeofwater, consumption } = record; // let { typeofwater, consumption } = record;
typeofwater = (typeofwater || "").trim().toLowerCase(); // Normalize case // typeofwater = (typeofwater || "").trim().toLowerCase(); // Normalize case
const standardType = typeMapping[typeofwater] || typeofwater; // Use mapped name or original // const standardType = typeMapping[typeofwater] || typeofwater; // Use mapped name or original
const consumptionValue = parseInt(consumption, 10) || 0; // const consumptionValue = parseInt(consumption, 10) || 0;
if (!consumptionByType[standardType]) { // if (!consumptionByType[standardType]) {
consumptionByType[standardType] = 0; // consumptionByType[standardType] = 0;
} // }
consumptionByType[standardType] += consumptionValue; // consumptionByType[standardType] += consumptionValue;
totalConsumption += consumptionValue; // totalConsumption += consumptionValue;
} // }
// Prepare notification message // // Prepare notification message
let notificationBody = `🚰 Water Consumption Report for ${currentDate}:\n`; // let notificationBody = `🚰 Water Consumption Report for ${currentDate}:\n`;
for (const type in consumptionByType) { // for (const type in consumptionByType) {
const percentage = totalConsumption ? ((consumptionByType[type] / totalConsumption) * 100).toFixed(2) : 0; // const percentage = totalConsumption ? ((consumptionByType[type] / totalConsumption) * 100).toFixed(2) : 0;
notificationBody += `\n💧 Type: ${type}\n` + // notificationBody += `\n💧 Type: ${type}\n` +
`Total Consumption: ${consumptionByType[type]} liters (${percentage}%)\n`; // `Total Consumption: ${consumptionByType[type]} liters (${percentage}%)\n`;
} // }
console.log(`📩 Preparing notification for ${customerId}:`, notificationBody); // console.log(`📩 Preparing notification for ${customerId}:`, notificationBody);
// Update lastNotificationSent before sending // // Update lastNotificationSent before sending
await User.updateOne( // await User.updateOne(
{ customerId }, // { customerId },
{ $set: { lastNotificationSent: new Date() } } // { $set: { lastNotificationSent: new Date() } }
); // );
// Send notification to FCM tokens // // Send notification to FCM tokens
const notificationPromises = uniqueTokens.map(async (token) => { // const notificationPromises = uniqueTokens.map(async (token) => {
try { // try {
await admin.messaging().send({ // await admin.messaging().send({
notification: { title: "Daily Water Consumption Report", body: notificationBody }, // notification: { title: "Daily Water Consumption Report", body: notificationBody },
token, // token,
data: { target: "/tank_levels" }, // data: { target: "/tank_levels" },
}); // });
console.log(`✅ Notification sent to token: ${token}`); // console.log(`✅ Notification sent to token: ${token}`);
} catch (error) { // } catch (error) {
console.error(`❌ Failed to send notification to token: ${token}`, error); // console.error(`❌ Failed to send notification to token: ${token}`, error);
if (error.code === "messaging/registration-token-not-registered") { // if (error.code === "messaging/registration-token-not-registered") {
await User.updateOne({ customerId }, { $pull: { fcmIds: token } }); // await User.updateOne({ customerId }, { $pull: { fcmIds: token } });
console.log(`🚫 Removed invalid token: ${token}`); // console.log(`🚫 Removed invalid token: ${token}`);
} // }
} // }
}); // });
await Promise.all(notificationPromises); // await Promise.all(notificationPromises);
} // }
} catch (error) { // } catch (error) {
console.error("❌ Error sending daily consumption notifications:", error); // console.error("❌ Error sending daily consumption notifications:", error);
} // }
}; // };
cron.schedule("* * * * *", async () => { // cron.schedule("* * * * *", async () => {
console.log("🔄 Running daily consumption notification check..."); // console.log("🔄 Running daily consumption notification check...");
await sendDailyConsumptionNotification(); // await sendDailyConsumptionNotification();
}, { // }, {
timezone: "Asia/Kolkata", // timezone: "Asia/Kolkata",
}); // });
@ -7012,74 +7012,74 @@ console.log("this is for testing autopush,line located in tankscontroller")
// }; // };
const calculateDailyConsumptionAndNotify = async () => { // const calculateDailyConsumptionAndNotify = async () => {
try { // try {
const today = moment().startOf("day"); // const today = moment().startOf("day");
const yesterday = moment(today).subtract(1, "days"); // const yesterday = moment(today).subtract(1, "days");
// Fetch all active users
const activeUsers = await User.find({});
for (const user of activeUsers) { // // Fetch all active users
const { customerId, fcmIds } = user; // const activeUsers = await User.find({});
// Fetch daily consumption for the customer // for (const user of activeUsers) {
const consumptions = await TankConsumptionOriginalSchema.find({ // const { customerId, fcmIds } = user;
customerId,
time: {
$gte: yesterday.format("DD-MMM-YYYY - HH:mm"),
$lt: today.format("DD-MMM-YYYY - HH:mm"),
},
});
// Calculate total consumption and capacities based on water type // // Fetch daily consumption for the customer
let totalBoreConsumption = 0; // const consumptions = await TankConsumptionOriginalSchema.find({
let totalDrinkingConsumption = 0; // customerId,
let totalBoreCapacity = 0; // time: {
let totalDrinkingCapacity = 0; // $gte: yesterday.format("DD-MMM-YYYY - HH:mm"),
// $lt: today.format("DD-MMM-YYYY - HH:mm"),
// },
// });
for (const record of consumptions) { // // Calculate total consumption and capacities based on water type
const typeOfWater = record.typeOfWater; // Assuming this field exists // let totalBoreConsumption = 0;
const consumption = parseInt(record.consumption, 10); // let totalDrinkingConsumption = 0;
const capacity = parseInt(record.capacity, 10); // Assuming capacity field exists // let totalBoreCapacity = 0;
// let totalDrinkingCapacity = 0;
if (typeOfWater === "bore" || typeOfWater === "Bore Water") { // for (const record of consumptions) {
totalBoreConsumption += consumption; // const typeOfWater = record.typeOfWater; // Assuming this field exists
totalBoreCapacity += capacity; // const consumption = parseInt(record.consumption, 10);
} else if (typeOfWater === "drinking" || typeOfWater === "Drinking Water") { // const capacity = parseInt(record.capacity, 10); // Assuming capacity field exists
totalDrinkingConsumption += consumption;
totalDrinkingCapacity += capacity;
}
}
// Calculate percentages // if (typeOfWater === "bore" || typeOfWater === "Bore Water") {
const boreConsumptionPercentage = totalBoreCapacity // totalBoreConsumption += consumption;
? ((totalBoreConsumption / totalBoreCapacity) * 100).toFixed(2) // totalBoreCapacity += capacity;
: 0; // } else if (typeOfWater === "drinking" || typeOfWater === "Drinking Water") {
// totalDrinkingConsumption += consumption;
// totalDrinkingCapacity += capacity;
// }
// }
const drinkingConsumptionPercentage = totalDrinkingCapacity // // Calculate percentages
? ((totalDrinkingConsumption / totalDrinkingCapacity) * 100).toFixed(2) // const boreConsumptionPercentage = totalBoreCapacity
: 0; // ? ((totalBoreConsumption / totalBoreCapacity) * 100).toFixed(2)
// : 0;
// Prepare notification body // const drinkingConsumptionPercentage = totalDrinkingCapacity
const reportDate = yesterday.format("DD-MMM-YYYY"); // ? ((totalDrinkingConsumption / totalDrinkingCapacity) * 100).toFixed(2)
let notificationBody = `Daily Water Consumption Report for ${reportDate}:\n`; // : 0;
notificationBody += `Total Bore Consumption: ${totalBoreConsumption} liters\n`;
notificationBody += `Bore Water Consumption Percentage: ${boreConsumptionPercentage}%\n`;
notificationBody += `Total Drinking Consumption: ${totalDrinkingConsumption} liters\n`;
notificationBody += `Drinking Water Consumption Percentage: ${drinkingConsumptionPercentage}%\n`;
// Send notification if FCM IDs are present // // Prepare notification body
if (fcmIds && fcmIds.length > 0) { // const reportDate = yesterday.format("DD-MMM-YYYY");
await sendNotification(fcmIds, "Daily Water Consumption Report", notificationBody); // let notificationBody = `Daily Water Consumption Report for ${reportDate}:\n`;
} // notificationBody += `Total Bore Consumption: ${totalBoreConsumption} liters\n`;
} // notificationBody += `Bore Water Consumption Percentage: ${boreConsumptionPercentage}%\n`;
// notificationBody += `Total Drinking Consumption: ${totalDrinkingConsumption} liters\n`;
// notificationBody += `Drinking Water Consumption Percentage: ${drinkingConsumptionPercentage}%\n`;
// // Send notification if FCM IDs are present
// if (fcmIds && fcmIds.length > 0) {
// await sendNotification(fcmIds, "Daily Water Consumption Report", notificationBody);
// }
// }
console.log("Daily consumption notifications sent successfully."); // console.log("Daily consumption notifications sent successfully.");
} catch (err) { // } catch (err) {
console.error("Error sending daily consumption notifications:", err); // console.error("Error sending daily consumption notifications:", err);
} // }
}; // };
// Schedule the cron job to run daily at 9 AM // Schedule the cron job to run daily at 9 AM
// cron.schedule( // cron.schedule(

Loading…
Cancel
Save