ashok 9 months ago
commit 6cdb42ac60

@ -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) => { const sendNotification = async (customerId, fcmIds, title, body) => {
try { try {
if (!customerId) { if (!customerId) {
@ -2358,26 +2472,22 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
throw new Error("No FCM tokens provided or invalid format."); throw new Error("No FCM tokens provided or invalid format.");
} }
// Safely flatten the tokens const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds;
const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds; // Use flat() if available
if (flatTokens.length === 0) { if (flatTokens.length === 0) {
throw new Error("Flattened FCM token list is empty."); 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"); 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 promises = users.map(async (user) => {
const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user; const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user;
// Check if userFcmIds is an array
if (!Array.isArray(userFcmIds)) { if (!Array.isArray(userFcmIds)) {
console.log(`Invalid fcmIds for customer ID: ${customerId}`); console.log(`Invalid fcmIds for customer ID: ${customerId}`);
return; return;
} }
// Filter tokens that belong to the user
const validTokens = flatTokens.filter(token => userFcmIds.includes(token)); const validTokens = flatTokens.filter(token => userFcmIds.includes(token));
if (validTokens.length === 0) { if (validTokens.length === 0) {
@ -2385,40 +2495,36 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
return; return;
} }
// // Handle notification preference // Handle notification preferences
// if (notificationPreference === "never") { if (notificationPreference === "never") {
// console.log(`Notifications disabled for customer ID: ${customerId}`); console.log(`Notifications disabled for customer ID: ${customerId}`);
// return; return;
// } }
const now = new Date(); const now = new Date();
const lastSent = new Date(lastNotificationSent || 0); const lastSent = new Date(lastNotificationSent || 0);
// If preference is not "always", check the timing let minInterval = 0;
// if (notificationPreference !== "always") { switch (notificationPreference) {
// let minInterval = 0; case "6_hours":
minInterval = 6 * 60 * 60 * 1000; // 6 hours
// switch (notificationPreference) { break;
// case "6_hours": case "8_hours":
// minInterval = 6 * 60 * 60 * 1000; // 6 hours minInterval = 8 * 60 * 60 * 1000; // 8 hours
// break; break;
// case "8_hours": case "1_month":
// minInterval = 8 * 60 * 60 * 1000; // 8 hours minInterval = 30 * 24 * 60 * 60 * 1000; // 1 month
// break; 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}).`);
// // Skip sending if the time restriction hasn't passed return;
// if (now - lastSent < minInterval) { }
// console.log(`Skipping notification for customer ID: ${customerId} due to time restriction.`);
// return;
// }
// }
// Send notifications // Send notifications
const notificationPromises = flatTokens.map(async (token) => { const notificationPromises = validTokens.map(async (token) => {
try { try {
const response = await admin.messaging().send({ const response = await admin.messaging().send({
notification: { title, body }, notification: { title, body },
@ -2427,19 +2533,13 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
}); });
console.log(`Notification sent successfully to token: ${token}`); console.log(`Notification sent successfully to token: ${token}`);
console.log("FCM Response:", response); // Log the full response console.log("FCM Response:", response);
console.log(`Title: ${title}, Body: ${body}`); // Log title and body before sending
} catch (error) { } catch (error) {
console.error(`Failed to send notification to token: ${token}`, error); console.error(`Failed to send notification to token: ${token}`, error);
// Handle token errors
if (error.code === "messaging/registration-token-not-registered") { if (error.code === "messaging/registration-token-not-registered") {
await User.updateOne( await User.updateOne({ customerId }, { $pull: { fcmIds: token } });
{ customerId },
{ $pull: { fcmIds: token } } // Remove invalid token
);
console.log(`Removed invalid token: ${token}`); console.log(`Removed invalid token: ${token}`);
} }
} }
@ -2447,9 +2547,9 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
await Promise.all(notificationPromises); await Promise.all(notificationPromises);
// Update lastNotificationSent timestamp if not "always" // Update lastNotificationSent timestamp if preference is not "always"
if (notificationPreference !== "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 sendPushNotification = async (registrationToken, title, body) => {
// const message = { // const message = {
// notification: { // notification: {

Loading…
Cancel
Save