diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 194d438d..b5f79fe5 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2348,6 +2348,120 @@ const emitWithTimestamp = (eventName, fcmTokens, motorId, waterLevel) => { // } // }; +// 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."); +// } + +// // Safely flatten the tokens +// const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds; // Use flat() if available +// if (flatTokens.length === 0) { +// throw new Error("Flattened FCM token list is empty."); +// } + +// // Fetch user notification settings +// const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent"); + +// // Iterate over users to send notifications based on their preferences +// const promises = users.map(async (user) => { +// const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user; + +// // Check if userFcmIds is an array +// if (!Array.isArray(userFcmIds)) { +// console.log(`Invalid fcmIds for customer ID: ${customerId}`); +// return; +// } + +// // Filter tokens that belong to the user +// const validTokens = flatTokens.filter(token => userFcmIds.includes(token)); + +// if (validTokens.length === 0) { +// console.log(`No matching FCM tokens for customer ID: ${customerId}`); +// return; +// } + +// // // Handle notification preference +// // if (notificationPreference === "never") { +// // console.log(`Notifications disabled for customer ID: ${customerId}`); +// // return; +// // } + +// const now = new Date(); +// const lastSent = new Date(lastNotificationSent || 0); + +// // If preference is not "always", check the timing +// // if (notificationPreference !== "always") { +// // 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; +// // } + +// // // Skip sending if the time restriction hasn't passed +// // if (now - lastSent < minInterval) { +// // console.log(`Skipping notification for customer ID: ${customerId} due to time restriction.`); +// // return; +// // } +// // } + +// // Send notifications +// const notificationPromises = flatTokens.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); // Log the full response +// console.log(`Title: ${title}, Body: ${body}`); // Log title and body before sending + + +// } catch (error) { +// console.error(`Failed to send notification to token: ${token}`, error); + +// // Handle token errors +// if (error.code === "messaging/registration-token-not-registered") { +// await User.updateOne( +// { customerId }, +// { $pull: { fcmIds: token } } // Remove invalid token +// ); +// console.log(`Removed invalid token: ${token}`); +// } +// } +// }); + +// await Promise.all(notificationPromises); + +// // Update lastNotificationSent timestamp if not "always" +// if (notificationPreference !== "always") { +// await User.updateOne({ customerId }, { lastNotificationSent: now }); +// } +// }); + +// await Promise.all(promises); + +// } catch (error) { +// console.error("Error sending notifications:", error); +// } +// }; + + + const sendNotification = async (customerId, fcmIds, title, body) => { try { if (!customerId) { @@ -2358,26 +2472,22 @@ const sendNotification = async (customerId, fcmIds, title, body) => { throw new Error("No FCM tokens provided or invalid format."); } - // Safely flatten the tokens - const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds; // Use flat() if available + const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds; if (flatTokens.length === 0) { throw new Error("Flattened FCM token list is empty."); } - // Fetch user notification settings + // Fetch users based on customerId const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent"); - // Iterate over users to send notifications based on their preferences const promises = users.map(async (user) => { const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user; - // Check if userFcmIds is an array if (!Array.isArray(userFcmIds)) { console.log(`Invalid fcmIds for customer ID: ${customerId}`); return; } - // Filter tokens that belong to the user const validTokens = flatTokens.filter(token => userFcmIds.includes(token)); if (validTokens.length === 0) { @@ -2385,40 +2495,36 @@ const sendNotification = async (customerId, fcmIds, title, body) => { return; } - // // Handle notification preference - // if (notificationPreference === "never") { - // console.log(`Notifications disabled for customer ID: ${customerId}`); - // return; - // } + // Handle notification preferences + if (notificationPreference === "never") { + console.log(`Notifications disabled for customer ID: ${customerId}`); + return; + } const now = new Date(); const lastSent = new Date(lastNotificationSent || 0); - // If preference is not "always", check the timing - // if (notificationPreference !== "always") { - // 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; - // } - - // // Skip sending if the time restriction hasn't passed - // if (now - lastSent < minInterval) { - // console.log(`Skipping notification for customer ID: ${customerId} due to time restriction.`); - // 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; + } + + // 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 = flatTokens.map(async (token) => { + const notificationPromises = validTokens.map(async (token) => { try { const response = await admin.messaging().send({ notification: { title, body }, @@ -2427,19 +2533,13 @@ const sendNotification = async (customerId, fcmIds, title, body) => { }); console.log(`Notification sent successfully to token: ${token}`); - console.log("FCM Response:", response); // Log the full response - console.log(`Title: ${title}, Body: ${body}`); // Log title and body before sending - + console.log("FCM Response:", response); } catch (error) { console.error(`Failed to send notification to token: ${token}`, error); - // Handle token errors if (error.code === "messaging/registration-token-not-registered") { - await User.updateOne( - { customerId }, - { $pull: { fcmIds: token } } // Remove invalid token - ); + await User.updateOne({ customerId }, { $pull: { fcmIds: token } }); console.log(`Removed invalid token: ${token}`); } } @@ -2447,9 +2547,9 @@ const sendNotification = async (customerId, fcmIds, title, body) => { await Promise.all(notificationPromises); - // Update lastNotificationSent timestamp if not "always" + // Update lastNotificationSent timestamp if preference is not "always" if (notificationPreference !== "always") { - await User.updateOne({ customerId }, { lastNotificationSent: now }); + await User.updateOne({ customerId }, { $set: { lastNotificationSent: now } }); } }); @@ -2463,9 +2563,6 @@ const sendNotification = async (customerId, fcmIds, title, body) => { - - - // const sendPushNotification = async (registrationToken, title, body) => { // const message = { // notification: {