From ce4cce0f12f13cc8433f34aefd0f64e48ae38bb3 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Fri, 21 Feb 2025 16:46:48 +0530 Subject: [PATCH] paused notifications --- src/controllers/tanksController.js | 265 +++++++++++++++-------------- 1 file changed, 133 insertions(+), 132 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index aac0c4c8..91a9e0e6 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2515,176 +2515,177 @@ const emitWithTimestamp = (eventName, fcmTokens, motorId, waterLevel) => { // } // }; -const sendNotification = async (customerId, fcmIds, title, body) => { - try { - if (!customerId) { - throw new Error("Customer ID is required."); - } +// important +// const sendNotification = async (customerId, fcmIds, title, body) => { +// try { +// if (!customerId) { +// throw new Error("Customer ID is required."); +// } - if (!Array.isArray(fcmIds) || fcmIds.length === 0) { - console.log("No valid FCM tokens provided."); - return; - } +// if (!Array.isArray(fcmIds) || fcmIds.length === 0) { +// console.log("No valid FCM tokens provided."); +// return; +// } - // Flatten nested arrays - const flatFcmIds = fcmIds.flat(); +// // Flatten nested arrays +// const flatFcmIds = fcmIds.flat(); - // Fetch user from database - const user = await User.findOne({ customerId }).select("fcmIds"); - if (!user || !Array.isArray(user.fcmIds)) { - console.log(`No valid FCM tokens found for customer ID: ${customerId}`); - return; - } +// // Fetch user from database +// const user = await User.findOne({ customerId }).select("fcmIds"); +// if (!user || !Array.isArray(user.fcmIds)) { +// console.log(`No valid FCM tokens found for customer ID: ${customerId}`); +// return; +// } - console.log("User's stored FCM tokens:", user.fcmIds); - console.log("FCM tokens passed to function:", flatFcmIds); +// console.log("User's stored FCM tokens:", user.fcmIds); +// console.log("FCM tokens passed to function:", flatFcmIds); - // Proper token filtering - const validTokens = user.fcmIds.filter(token => flatFcmIds.some(t => t.trim() === token.trim())); +// // Proper token filtering +// const validTokens = user.fcmIds.filter(token => flatFcmIds.some(t => t.trim() === token.trim())); - console.log("Valid tokens for notification:", validTokens); +// console.log("Valid tokens for notification:", validTokens); - if (validTokens.length === 0) { - console.log(`No matching FCM tokens for customer ID: ${customerId}`); - return; - } +// if (validTokens.length === 0) { +// console.log(`No matching FCM tokens for customer ID: ${customerId}`); +// return; +// } - const promises = validTokens.map(async (token) => { - try { - console.log(`Sending notification to token: ${token}`); +// const promises = validTokens.map(async (token) => { +// try { +// console.log(`Sending notification to token: ${token}`); - const response = await admin.messaging().send({ - notification: { title, body }, - token, - data: { target: "/tank_levels" }, - }); +// const response = await admin.messaging().send({ +// notification: { title, body }, +// token, +// data: { target: "/tank_levels" }, +// }); - console.log(`Notification sent successfully:`, response); - console.log(`title:`, title); - console.log(`body:`, body); +// console.log(`Notification sent successfully:`, response); +// console.log(`title:`, title); +// console.log(`body:`, body); - } catch (error) { - console.error(`Failed to send notification to token: ${token}`, error); +// } catch (error) { +// console.error(`Failed to send notification to token: ${token}`, error); - if (error?.errorInfo?.code === "messaging/registration-token-not-registered") { - await User.updateOne({ customerId }, { $pull: { fcmIds: token } }); - console.log(`Removed invalid token: ${token}`); - } - } - }); - - await Promise.all(promises); - } catch (error) { - console.error("Error sending notifications:", error); - } -}; +// if (error?.errorInfo?.code === "messaging/registration-token-not-registered") { +// await User.updateOne({ customerId }, { $pull: { fcmIds: token } }); +// console.log(`Removed invalid token: ${token}`); +// } +// } +// }); +// await Promise.all(promises); +// } catch (error) { +// console.error("Error sending notifications:", error); +// } +// }; -// const sendNotification = async (customerId, fcmIds, title, body) => { -// try { -// if (!customerId) { -// throw new Error("Customer ID is required."); -// } -// if (!Array.isArray(fcmIds) || fcmIds.length === 0) { -// throw new Error("No FCM tokens provided or invalid format."); -// } +const sendNotification = async (customerId, fcmIds, title, body) => { + try { + if (!customerId) { + throw new Error("Customer ID is required."); + } -// const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds; -// if (flatTokens.length === 0) { -// throw new Error("Flattened FCM token list is empty."); -// } + if (!Array.isArray(fcmIds) || fcmIds.length === 0) { + throw new Error("No FCM tokens provided or invalid format."); + } -// // Fetch users based on customerId -// const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent"); + const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds; + if (flatTokens.length === 0) { + throw new Error("Flattened FCM token list is empty."); + } -// const promises = users.map(async (user) => { -// const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user; + // Fetch users based on customerId + const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent"); -// if (!Array.isArray(userFcmIds)) { -// console.log(`Invalid fcmIds for customer ID: ${customerId}`); -// return; -// } + const promises = users.map(async (user) => { + const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user; -// const validTokens = flatTokens.filter(token => userFcmIds.includes(token)); + if (!Array.isArray(userFcmIds)) { + console.log(`Invalid fcmIds for customer ID: ${customerId}`); + return; + } -// if (validTokens.length === 0) { -// console.log(`No matching FCM tokens for customer ID: ${customerId}`); -// return; -// } + const validTokens = flatTokens.filter(token => userFcmIds.includes(token)); -// // Handle notification preferences -// if (notificationPreference === "never") { -// console.log(`Notifications disabled for customer ID: ${customerId}`); -// return; -// } + if (validTokens.length === 0) { + console.log(`No matching FCM tokens for customer ID: ${customerId}`); + return; + } -// const now = new Date(); -// const lastSent = new Date(lastNotificationSent || 0); + // Handle notification preferences + if (notificationPreference === "never") { + console.log(`Notifications disabled for customer ID: ${customerId}`); + return; + } -// let minInterval = 0; -// switch (notificationPreference) { -// case "6_hours": -// minInterval = 6 * 60 * 60 * 1000; // 6 hours -// break; -// case "8_hours": -// minInterval = 8 * 60 * 60 * 1000; // 8 hours -// break; -// case "1_month": -// minInterval = 30 * 24 * 60 * 60 * 1000; // 1 month -// break; -// } + const now = new Date(); + const lastSent = new Date(lastNotificationSent || 0); + + let minInterval = 0; + switch (notificationPreference) { + case "6_hours": + minInterval = 6 * 60 * 60 * 1000; // 6 hours + break; + case "8_hours": + minInterval = 8 * 60 * 60 * 1000; // 8 hours + break; + case "1_month": + minInterval = 30 * 24 * 60 * 60 * 1000; // 1 month + break; + } -// // Check if enough time has passed for non-"always" preferences -// if (notificationPreference !== "always" && now - lastSent < minInterval) { -// console.log(`Skipping notification for customer ID: ${customerId} due to preference (${notificationPreference}).`); -// return; -// } + // Check if enough time has passed for non-"always" preferences + if (notificationPreference !== "always" && now - lastSent < minInterval) { + console.log(`Skipping notification for customer ID: ${customerId} due to preference (${notificationPreference}).`); + return; + } -// // Send notifications -// const notificationPromises = validTokens.map(async (token) => { -// try { -// const response = await admin.messaging().send({ -// notification: { title, body }, -// token, -// data: { target: "/tank_levels" }, -// }); + // Send notifications + const notificationPromises = validTokens.map(async (token) => { + try { + const response = await admin.messaging().send({ + notification: { title, body }, + token, + data: { target: "/tank_levels" }, + }); -// console.log(`Notification sent successfully to token: ${token}`); -// console.log("FCM Response:", response); -// console.log("Titel:", title); -// console.log("Body:", body); -// console.log("Data:", data); + console.log(`Notification sent successfully to token: ${token}`); + console.log("FCM Response:", response); + console.log("Titel:", title); + console.log("Body:", body); + console.log("Data:", data); -// } catch (error) { -// console.error(`Failed to send notification to token: ${token}`, error); + } 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}`); -// } -// } -// }); + if (error.code === "messaging/registration-token-not-registered") { + await User.updateOne({ customerId }, { $pull: { fcmIds: token } }); + console.log(`Removed invalid token: ${token}`); + } + } + }); -// await Promise.all(notificationPromises); + await Promise.all(notificationPromises); -// // Update lastNotificationSent timestamp if preference is not "always" -// if (notificationPreference !== "always") { -// await User.updateOne({ customerId }, { $set: { lastNotificationSent: now } }); -// } -// }); + // Update lastNotificationSent timestamp if preference is not "always" + if (notificationPreference !== "always") { + await User.updateOne({ customerId }, { $set: { lastNotificationSent: now } }); + } + }); -// await Promise.all(promises); + await Promise.all(promises); -// } catch (error) { -// console.error("Error sending notifications:", error); -// } -// }; + } catch (error) { + console.error("Error sending notifications:", error); + } +};