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 **manually**.`;
const message = `🚰 **Motor Started** 🚀\n` +
`👤 **Customer ID:** ${customerId}\n` +
`🔹 **Motor Name:** ${tankName} - ${blockName}\n` +
`💧 **Water Level:** ${waterLevel}\n` +
`📱 **Mode:** **Forced Manual**\n` +
`🕒 **Pump started at:** ${formattedTime}\n`
const message = `🚰 Motor Started 🚀\n` +
`👤 Customer ID: ${customerId}\n` +
`🔹 Motor Name: ${tankName} - ${blockName}\n` +
`💧 Water Level: ${waterLevel}\n` +
`📱 Mode: Manually Started\n` +
`🕒 Pump started at: ${formattedTime}\n`
await sendNotification(hw_Id, customerId, fcmTokens, "Motor Started 🚀", message);
@ -2254,12 +2254,12 @@ eventEmitter.on("sendMotorStopNotification", async (hw_Id, customerId, fcmTokens
return;
}
const message = `🛑 **Motor Stopped**\n` +
`👤 **Customer ID:** ${customerId}\n` +
`🔹 **Motor Name:** ${tankName} - ${blockName}\n` +
`💧 **Water Level:** ${waterLevel}\n` +
`📱 **Mode:** **Forced Manual**\n` +
`🕒 **Pump stopped at:** ${formattedTime}`;
const message = `🛑 Motor Stopped ❌\n` +
`👤 Customer ID: ${customerId}\n` +
`🔹 Motor Name: ${tankName} - ${blockName}\n` +
`💧 Water Level: ${waterLevel}\n` +
`📱 Mode: Manually Stopped\n` +
`🕒 Pump stopped at: ${formattedTime}`;
await sendNotification(hw_Id, customerId, fcmTokens, "Motor Stopped ❌", message);
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 () => {
try {
const now = new Date();
@ -2671,23 +2672,38 @@ const sendDailyConsumptionNotification = async () => {
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({
allowNotifications: true,
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.");
return;
}
for (const user of users) {
const { customerId, fcmIds } = user;
for (const user of uniqueUsers) {
const { customerId, fcmIds, lastNotificationSent } = user;
// Ensure user has valid FCM tokens
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;
}
@ -2745,19 +2761,25 @@ const sendDailyConsumptionNotification = async () => {
console.log(`📩 Preparing notification for ${customerId}:`, notificationBody);
// Update lastNotificationSent before sending
await User.updateOne(
{ customerId },
{ $set: { lastNotificationSent: new Date() } }
);
// Send notification to FCM tokens
const notificationPromises = fcmIds.map(async (token) => {
const notificationPromises = uniqueTokens.map(async (token) => {
try {
const response = await admin.messaging().send({
await admin.messaging().send({
notification: { title: "Daily Water Consumption Report", body: notificationBody },
token,
data: { target: "/tank_levels" },
});
console.log(`✅ Notification sent to token: ${token}`);
console.log("FCM Response:", response);
} catch (error) {
console.error(`❌ Failed to send notification to token: ${token}`, error);
if (error.code === "messaging/registration-token-not-registered") {
await User.updateOne({ customerId }, { $pull: { fcmIds: 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 () => {
console.log("🔄 Running daily consumption notification check...");
await sendDailyConsumptionNotification();
@ -6695,14 +6715,15 @@ client.on('message', async (topic, message) => {
const customerId = motorTank.customerId;
console.log("tankName",tankName)
console.log("customerId", customerId)
console.log("status", status)
// Ensure fcmTokens are fetched before emitting
// const user = await User.findOne({ customerId: motorTank.customerId }).select("fcmIds manualStartAndStopNotify");
// const fcmTokens = user?.fcmIds || []; // Ensure fcmTokens is an array
// console.log("fcmTokens", fcmTokens)
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);
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) {
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}`);
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);
if (status === 2 && inputConnection.motor_stop_status === "1") {
// Only update if motor_stop_status is still 1 (motor was previously OFF)
inputConnection.motor_stop_status = 2;
inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = new Date().toISOString();
// status = 1;
// inputConnection.motor_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)
// inputConnection.motor_stop_status ="2";
// inputConnection.motor_on_type = "forced_manual";
// inputConnection.startTime = new Date().toISOString();
// // status = 1;
// // inputConnection.motor_status = "1";
console.log("🛠️ IN inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
console.log("🛠️ Motor_status:", status);
console.log("🛠inputConnection.motor_status:", inputConnection.motor_status);
// console.log("🛠️ IN inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
// console.log("🛠️In Motor_status:", status);
// console.log("🛠️In inputConnection.motor_status:", inputConnection.motor_status);
console.log("🚀 Motor started. Updating motor_stop_status to 2.");
console.log("📢 Emitting sendMotorStartNotification event...");
// console.log("🚀 Motor started. Updating motor_stop_status to 2.");
// console.log("📢 Emitting sendMotorStartNotification event...");
await motorTank.markModified("connections.inputConnections");
await motorTank.save();
console.log("💾 motorTank saved successfully after start.");
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save();
// console.log("💾 motorTank saved successfully after start.");
eventEmitter.emit(
"sendMotorStartNotification",
hw_Id,
customerId,
fcmTokens,
inputConnection.water_level || 0,
blockName,
tankName,
"forced_manual",
inputConnection.stop_criteria,
inputConnection.typeOfWater,
inputConnection.manual_threshold_time
);
// eventEmitter.emit(
// "sendMotorStartNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.stop_criteria,
// inputConnection.typeOfWater,
// 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) {
// const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
// inputConnection.motor_stop_status = "1";
// inputConnection.stopTime = currentTime;
// console.log("📢 Emitting sendMotorStopNotification event...");
// console.log(`🔍 Checking stop condition: status=${status}, motor_stop_status=${inputConnection.motor_stop_status}`);
// if (status === 1 && inputConnection.motor_stop_status === "2") {
// console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
// 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(
// "sendMotorStopNotification",
// hw_Id,
@ -6844,53 +6803,59 @@ client.on('message', async (topic, message) => {
// inputConnection.typeOfWater
// );
// }
// if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) {
// const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
// inputConnection.motor_stop_status = "1";
// inputConnection.stopTime = currentTime;
// console.log("📢 Emitting sendMotorStopNotification event...");
// eventEmitter.emit(
// "sendMotorStopNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.typeOfWater
// );
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save();
// }
console.log(`🔍 Checking stop condition: status=${status}, motor_stop_status=${inputConnection.motor_stop_status}`);
if (status === 2 && inputConnection.motor_stop_status === "2") {
console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
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(
"sendMotorStopNotification",
hw_Id,
customerId,
fcmTokens,
inputConnection.water_level || 0,
blockName,
tankName,
"forced_manual",
inputConnection.typeOfWater
);
}
// if (status === 2 && inputConnection.motor_stop_status === "1" && inputConnection.motor_on_type !== "forced_manual") {
// // Motor is starting (only execute this block)
// inputConnection.motor_stop_status = "2"; // Motor is now running
// inputConnection.motor_on_type = "forced_manual";
// inputConnection.startTime = new Date().toISOString();
// console.log("🚀 Motor started. Updating motor_stop_status to 2.");
// console.log("📢 Emitting sendMotorStartNotification event...");
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save();
// console.log("💾 motorTank saved successfully after start.");
// eventEmitter.emit(
// "sendMotorStartNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.stop_criteria,
// inputConnection.typeOfWater,
// inputConnection.manual_threshold_time
// );
// } else if (status === 1 && inputConnection.motor_stop_status === "2") {
// // Motor is stopping (only execute this block)
// console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
// inputConnection.motor_stop_status = "1"; // Motor is now OFF
// 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(
// "sendMotorStopNotification",
// hw_Id,
// customerId,
// fcmTokens,
// 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
}

Loading…
Cancel
Save