master^2
Bhaskar 7 months ago
parent d73fef94fa
commit cfaa1a5e0e

@ -2223,12 +2223,12 @@ eventEmitter.on("sendMotorStartNotification", async (hw_Id, customerId, fcmToken
? `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.` ? `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.`
: `⚠️ Pump will stop **manually**.`; : `⚠️ Pump will stop **manually**.`;
const message = `🚰 **Motor Started** 🚀\n` + const message = `🚰 Motor Started 🚀\n` +
`👤 **Customer ID:** ${customerId}\n` + `👤 Customer ID: ${customerId}\n` +
`🔹 **Motor Name:** ${tankName} - ${blockName}\n` + `🔹 Motor Name: ${tankName} - ${blockName}\n` +
`💧 **Water Level:** ${waterLevel}\n` + `💧 Water Level: ${waterLevel}\n` +
`📱 **Mode:** **Forced Manual**\n` + `📱 Mode: Manually Started\n` +
`🕒 **Pump started at:** ${formattedTime}\n` `🕒 Pump started at: ${formattedTime}\n`
await sendNotification(hw_Id, customerId, fcmTokens, "Motor Started 🚀", message); await sendNotification(hw_Id, customerId, fcmTokens, "Motor Started 🚀", message);
@ -2254,12 +2254,12 @@ eventEmitter.on("sendMotorStopNotification", async (hw_Id, customerId, fcmTokens
return; return;
} }
const message = `🛑 **Motor Stopped**\n` + const message = `🛑 Motor Stopped ❌\n` +
`👤 **Customer ID:** ${customerId}\n` + `👤 Customer ID: ${customerId}\n` +
`🔹 **Motor Name:** ${tankName} - ${blockName}\n` + `🔹 Motor Name: ${tankName} - ${blockName}\n` +
`💧 **Water Level:** ${waterLevel}\n` + `💧 Water Level: ${waterLevel}\n` +
`📱 **Mode:** **Forced Manual**\n` + `📱 Mode: Manually Stopped\n` +
`🕒 **Pump stopped at:** ${formattedTime}`; `🕒 Pump stopped at: ${formattedTime}`;
await sendNotification(hw_Id, customerId, fcmTokens, "Motor Stopped ❌", message); await sendNotification(hw_Id, customerId, fcmTokens, "Motor Stopped ❌", message);
console.log(`✅ Motor stop notification sent for Customer ID: ${customerId}`); console.log(`✅ Motor stop notification sent for Customer ID: ${customerId}`);
@ -2663,6 +2663,7 @@ const sendNotification = async (hw_Id, customerId, fcmIds, title, body) => {
// Function to send notifications
const sendDailyConsumptionNotification = async () => { const sendDailyConsumptionNotification = async () => {
try { try {
const now = new Date(); const now = new Date();
@ -2671,23 +2672,38 @@ const sendDailyConsumptionNotification = async () => {
console.log(`🕒 Checking users for scheduled notifications at ${currentTime}`); console.log(`🕒 Checking users for scheduled notifications at ${currentTime}`);
// Fetch users who have set 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"); }).select("customerId fcmIds lastNotificationSent").lean();
if (users.length === 0) { // Ensure unique customers only
const uniqueUsers = users.filter((user, index, self) =>
index === self.findIndex((u) => u.customerId === user.customerId)
);
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 users) { for (const user of uniqueUsers) {
const { customerId, fcmIds } = 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 found for customer ID: ${customerId}`); console.log(`⚠️ No valid FCM tokens for customer ID: ${customerId}`);
continue;
}
// Remove duplicate and trim tokens
const uniqueTokens = [...new Set(fcmIds.map(token => token.trim()))];
// Check if notification should be sent based on lastNotificationSent
const lastSent = new Date(lastNotificationSent || 0);
if (now - lastSent < 24 * 60 * 60 * 1000) {
console.log(`⏳ Skipping notification for ${customerId}, already sent in the last 24 hours.`);
continue; continue;
} }
@ -2745,19 +2761,25 @@ const sendDailyConsumptionNotification = async () => {
console.log(`📩 Preparing notification for ${customerId}:`, notificationBody); console.log(`📩 Preparing notification for ${customerId}:`, notificationBody);
// Update lastNotificationSent before sending
await User.updateOne(
{ customerId },
{ $set: { lastNotificationSent: new Date() } }
);
// Send notification to FCM tokens // Send notification to FCM tokens
const notificationPromises = fcmIds.map(async (token) => { const notificationPromises = uniqueTokens.map(async (token) => {
try { try {
const response = 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}`);
console.log("FCM Response:", response);
} 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}`);
@ -2772,8 +2794,6 @@ const sendDailyConsumptionNotification = async () => {
} }
}; };
// Schedule the function to run every minute to check for user notification times
cron.schedule("* * * * *", async () => { cron.schedule("* * * * *", async () => {
console.log("🔄 Running daily consumption notification check..."); console.log("🔄 Running daily consumption notification check...");
await sendDailyConsumptionNotification(); await sendDailyConsumptionNotification();
@ -6695,14 +6715,15 @@ client.on('message', async (topic, message) => {
const customerId = motorTank.customerId; const customerId = motorTank.customerId;
console.log("tankName",tankName) console.log("tankName",tankName)
console.log("customerId", customerId) console.log("customerId", customerId)
console.log("status", status)
// Ensure fcmTokens are fetched before emitting // Ensure fcmTokens are fetched before emitting
// const user = await User.findOne({ customerId: motorTank.customerId }).select("fcmIds manualStartAndStopNotify"); // const user = await User.findOne({ customerId: motorTank.customerId }).select("fcmIds manualStartAndStopNotify");
// const fcmTokens = user?.fcmIds || []; // Ensure fcmTokens is an array // const fcmTokens = user?.fcmIds || []; // Ensure fcmTokens is an array
// console.log("fcmTokens", fcmTokens) // console.log("fcmTokens", fcmTokens)
const users = await User.findOne({ customerId : motorTank.customerId}).select("fcmIds"); const users = await User.findOne({ customerId : motorTank.customerId}).select("fcmIds");
// console.log("users", users)
// let fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token);
let fcmTokens = users.fcmIds.filter(token => token); let fcmTokens = users.fcmIds.filter(token => token);
console.log(`📡 Found ${fcmTokens.length} FCM tokens for Customer ID: ${customerId}`); console.log(`📡 Found ${fcmTokens.length} FCM tokens for Customer ID: ${customerId}`);
@ -6710,14 +6731,6 @@ client.on('message', async (topic, message) => {
if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) { if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) {
console.warn(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`); console.warn(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`);
} }
// const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
// const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
console.log(`📢 Processing motor logic for hw_Id: ${hw_Id}`); console.log(`📢 Processing motor logic for hw_Id: ${hw_Id}`);
const blockName = motorTank.blockName || "N/A"; const blockName = motorTank.blockName || "N/A";
@ -6729,109 +6742,55 @@ client.on('message', async (topic, message) => {
console.log("🛠️ inputConnection.motor_on_type:", inputConnection.motor_on_type); console.log("🛠️ inputConnection.motor_on_type:", inputConnection.motor_on_type);
if (status === 2 && inputConnection.motor_stop_status === "1") { // if (status === 2 && inputConnection.motor_stop_status === "1" && inputConnection.motor_on_type !== "forced_manual") {
// Only update if motor_stop_status is still 1 (motor was previously OFF) // // Only update if motor_stop_status is still 1 (motor was previously OFF)
inputConnection.motor_stop_status = 2; // inputConnection.motor_stop_status ="2";
inputConnection.motor_on_type = "forced_manual"; // inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = new Date().toISOString(); // inputConnection.startTime = new Date().toISOString();
// status = 1; // // status = 1;
// inputConnection.motor_status = 1; // // inputConnection.motor_status = "1";
console.log("🛠️ IN inputConnection.motor_stop_status:", inputConnection.motor_stop_status); // console.log("🛠️ IN inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
console.log("🛠️ Motor_status:", status); // console.log("🛠️In Motor_status:", status);
console.log("🛠inputConnection.motor_status:", inputConnection.motor_status); // console.log("🛠️In inputConnection.motor_status:", inputConnection.motor_status);
console.log("🚀 Motor started. Updating motor_stop_status to 2."); // console.log("🚀 Motor started. Updating motor_stop_status to 2.");
console.log("📢 Emitting sendMotorStartNotification event..."); // console.log("📢 Emitting sendMotorStartNotification event...");
await motorTank.markModified("connections.inputConnections"); // await motorTank.markModified("connections.inputConnections");
await motorTank.save(); // await motorTank.save();
console.log("💾 motorTank saved successfully after start."); // console.log("💾 motorTank saved successfully after start.");
eventEmitter.emit( // eventEmitter.emit(
"sendMotorStartNotification", // "sendMotorStartNotification",
hw_Id, // hw_Id,
customerId, // customerId,
fcmTokens, // fcmTokens,
inputConnection.water_level || 0, // inputConnection.water_level || 0,
blockName, // blockName,
tankName, // tankName,
"forced_manual", // "forced_manual",
inputConnection.stop_criteria, // inputConnection.stop_criteria,
inputConnection.typeOfWater, // inputConnection.typeOfWater,
inputConnection.manual_threshold_time // inputConnection.manual_threshold_time
); // );
} // }
// if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") {
// const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
// inputConnection.motor_stop_status = "2";
// inputConnection.motor_on_type = "forced_manual";
// inputConnection.startTime = currentTime;
// console.log("📢 Emitting sendMotorStartNotification event...");
// eventEmitter.emit(
// "sendMotorStartNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.stop_criteria,
// inputConnection.typeOfWater,
// inputConnection.manual_threshold_time
// );
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save();
// console.log("💾 motorTank saved successfully.");
// }
// if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") {
// const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
// inputConnection.motor_stop_status = "2";
// inputConnection.motor_on_type = "forced_manual";
// inputConnection.startTime = currentTime;
// console.log("🚀 Motor started in FORCED_MANUAL mode.");
// console.log("📢 Emitting sendMotorStartNotification event...");
// eventEmitter.emit(
// "sendMotorStartNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.stop_criteria,
// inputConnection.typeOfWater,
// inputConnection.manual_threshold_time
// );
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save(); // Ensure the change is saved
// console.log("💾 motorTank saved successfully.");
// }
// if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) { // console.log(`🔍 Checking stop condition: status=${status}, motor_stop_status=${inputConnection.motor_stop_status}`);
// const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); // if (status === 1 && inputConnection.motor_stop_status === "2") {
// inputConnection.motor_stop_status = "1"; // console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
// inputConnection.stopTime = currentTime;
// console.log("📢 Emitting sendMotorStopNotification event...");
// inputConnection.motor_stop_status = "1";
// inputConnection.stopTime = new Date().toISOString();
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save(); // Ensure data is saved before emitting
// console.log("📢 Emitting sendMotorStopNotification event...");
// eventEmitter.emit( // eventEmitter.emit(
// "sendMotorStopNotification", // "sendMotorStopNotification",
// hw_Id, // hw_Id,
@ -6844,53 +6803,59 @@ client.on('message', async (topic, message) => {
// inputConnection.typeOfWater // inputConnection.typeOfWater
// ); // );
// } // }
// if (status === 2 && inputConnection.motor_stop_status === "1" && inputConnection.motor_on_type !== "forced_manual") {
// if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) { // // Motor is starting (only execute this block)
// const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); // inputConnection.motor_stop_status = "2"; // Motor is now running
// inputConnection.motor_stop_status = "1"; // inputConnection.motor_on_type = "forced_manual";
// inputConnection.stopTime = currentTime; // inputConnection.startTime = new Date().toISOString();
// console.log("📢 Emitting sendMotorStopNotification event..."); // console.log("🚀 Motor started. Updating motor_stop_status to 2.");
// console.log("📢 Emitting sendMotorStartNotification event...");
// eventEmitter.emit(
// "sendMotorStopNotification", // await motorTank.markModified("connections.inputConnections");
// hw_Id, // await motorTank.save();
// customerId, // console.log("💾 motorTank saved successfully after start.");
// fcmTokens,
// inputConnection.water_level || 0, // eventEmitter.emit(
// blockName, // "sendMotorStartNotification",
// tankName, // hw_Id,
// "forced_manual", // customerId,
// inputConnection.typeOfWater // fcmTokens,
// ); // inputConnection.water_level || 0,
// blockName,
// await motorTank.markModified("connections.inputConnections"); // tankName,
// await motorTank.save(); // "forced_manual",
// } // inputConnection.stop_criteria,
console.log(`🔍 Checking stop condition: status=${status}, motor_stop_status=${inputConnection.motor_stop_status}`); // inputConnection.typeOfWater,
if (status === 2 && inputConnection.motor_stop_status === "2") { // inputConnection.manual_threshold_time
console.log("🛑 Motor stopping... Updating motor_stop_status to 1."); // );
inputConnection.motor_stop_status = "1"; // } else if (status === 1 && inputConnection.motor_stop_status === "2") {
inputConnection.stopTime = new Date().toISOString(); // // Motor is stopping (only execute this block)
// console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
await motorTank.markModified("connections.inputConnections");
await motorTank.save(); // Ensure data is saved before emitting // inputConnection.motor_stop_status = "1"; // Motor is now OFF
// inputConnection.stopTime = new Date().toISOString();
console.log("📢 Emitting sendMotorStopNotification event...");
eventEmitter.emit( // await motorTank.markModified("connections.inputConnections");
"sendMotorStopNotification", // await motorTank.save(); // Ensure data is saved before emitting
hw_Id,
customerId, // console.log("📢 Emitting sendMotorStopNotification event...");
fcmTokens, // eventEmitter.emit(
inputConnection.water_level || 0, // "sendMotorStopNotification",
blockName, // hw_Id,
tankName, // customerId,
"forced_manual", // fcmTokens,
inputConnection.typeOfWater // inputConnection.water_level || 0,
); // blockName,
} // tankName,
// "forced_manual",
// inputConnection.typeOfWater
// );
// }
console.log(`🔍 Final condition: status=${status}, motor_stop_status=${inputConnection.motor_stop_status}`);
await motorTank.save(); // Save the updated tank await motorTank.save(); // Save the updated tank
} }

Loading…
Cancel
Save