paused notifications

master^2
Bhaskar 8 months ago
parent 29ee4665de
commit ce4cce0f12

@ -2515,176 +2515,177 @@ const emitWithTimestamp = (eventName, fcmTokens, motorId, waterLevel) => {
// } // }
// }; // };
const sendNotification = async (customerId, fcmIds, title, body) => { // important
try { // const sendNotification = async (customerId, fcmIds, title, body) => {
if (!customerId) { // try {
throw new Error("Customer ID is required."); // if (!customerId) {
} // throw new Error("Customer ID is required.");
// }
if (!Array.isArray(fcmIds) || fcmIds.length === 0) { // if (!Array.isArray(fcmIds) || fcmIds.length === 0) {
console.log("No valid FCM tokens provided."); // console.log("No valid FCM tokens provided.");
return; // return;
} // }
// Flatten nested arrays // // Flatten nested arrays
const flatFcmIds = fcmIds.flat(); // const flatFcmIds = fcmIds.flat();
// Fetch user from database // // Fetch user from database
const user = await User.findOne({ customerId }).select("fcmIds"); // const user = await User.findOne({ customerId }).select("fcmIds");
if (!user || !Array.isArray(user.fcmIds)) { // if (!user || !Array.isArray(user.fcmIds)) {
console.log(`No valid FCM tokens found for customer ID: ${customerId}`); // console.log(`No valid FCM tokens found for customer ID: ${customerId}`);
return; // return;
} // }
console.log("User's stored FCM tokens:", user.fcmIds); // console.log("User's stored FCM tokens:", user.fcmIds);
console.log("FCM tokens passed to function:", flatFcmIds); // console.log("FCM tokens passed to function:", flatFcmIds);
// Proper token filtering // // Proper token filtering
const validTokens = user.fcmIds.filter(token => flatFcmIds.some(t => t.trim() === token.trim())); // 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) { // if (validTokens.length === 0) {
console.log(`No matching FCM tokens for customer ID: ${customerId}`); // console.log(`No matching FCM tokens for customer ID: ${customerId}`);
return; // return;
} // }
const promises = validTokens.map(async (token) => { // const promises = validTokens.map(async (token) => {
try { // try {
console.log(`Sending notification to token: ${token}`); // console.log(`Sending notification to token: ${token}`);
const response = await admin.messaging().send({ // const response = await admin.messaging().send({
notification: { title, body }, // notification: { title, body },
token, // token,
data: { target: "/tank_levels" }, // data: { target: "/tank_levels" },
}); // });
console.log(`Notification sent successfully:`, response); // console.log(`Notification sent successfully:`, response);
console.log(`title:`, title); // console.log(`title:`, title);
console.log(`body:`, body); // console.log(`body:`, body);
} 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?.errorInfo?.code === "messaging/registration-token-not-registered") { // if (error?.errorInfo?.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}`);
} // }
} // }
}); // });
await Promise.all(promises);
} catch (error) {
console.error("Error sending notifications:", error);
}
};
// 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) { const sendNotification = async (customerId, fcmIds, title, body) => {
// throw new Error("No FCM tokens provided or invalid format."); try {
// } if (!customerId) {
throw new Error("Customer ID is required.");
}
// const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds; if (!Array.isArray(fcmIds) || fcmIds.length === 0) {
// if (flatTokens.length === 0) { throw new Error("No FCM tokens provided or invalid format.");
// throw new Error("Flattened FCM token list is empty."); }
// }
// // Fetch users based on customerId const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds;
// const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent"); if (flatTokens.length === 0) {
throw new Error("Flattened FCM token list is empty.");
}
// const promises = users.map(async (user) => { // Fetch users based on customerId
// const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user; const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent");
// if (!Array.isArray(userFcmIds)) { const promises = users.map(async (user) => {
// console.log(`Invalid fcmIds for customer ID: ${customerId}`); const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user;
// return;
// }
// 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) { const validTokens = flatTokens.filter(token => userFcmIds.includes(token));
// console.log(`No matching FCM tokens for customer ID: ${customerId}`);
// return;
// }
// // Handle notification preferences if (validTokens.length === 0) {
// if (notificationPreference === "never") { console.log(`No matching FCM tokens for customer ID: ${customerId}`);
// console.log(`Notifications disabled for customer ID: ${customerId}`); return;
// return; }
// }
// const now = new Date(); // Handle notification preferences
// const lastSent = new Date(lastNotificationSent || 0); if (notificationPreference === "never") {
console.log(`Notifications disabled for customer ID: ${customerId}`);
return;
}
// let minInterval = 0; const now = new Date();
// switch (notificationPreference) { const lastSent = new Date(lastNotificationSent || 0);
// case "6_hours":
// minInterval = 6 * 60 * 60 * 1000; // 6 hours let minInterval = 0;
// break; switch (notificationPreference) {
// case "8_hours": case "6_hours":
// minInterval = 8 * 60 * 60 * 1000; // 8 hours minInterval = 6 * 60 * 60 * 1000; // 6 hours
// break; break;
// case "1_month": case "8_hours":
// minInterval = 30 * 24 * 60 * 60 * 1000; // 1 month minInterval = 8 * 60 * 60 * 1000; // 8 hours
// break; break;
// } case "1_month":
minInterval = 30 * 24 * 60 * 60 * 1000; // 1 month
break;
}
// // Check if enough time has passed for non-"always" preferences // Check if enough time has passed for non-"always" preferences
// if (notificationPreference !== "always" && now - lastSent < minInterval) { if (notificationPreference !== "always" && now - lastSent < minInterval) {
// console.log(`Skipping notification for customer ID: ${customerId} due to preference (${notificationPreference}).`); console.log(`Skipping notification for customer ID: ${customerId} due to preference (${notificationPreference}).`);
// return; return;
// } }
// // Send notifications // Send notifications
// const notificationPromises = validTokens.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 },
// token, token,
// data: { target: "/tank_levels" }, data: { target: "/tank_levels" },
// }); });
// console.log(`Notification sent successfully to token: ${token}`); console.log(`Notification sent successfully to token: ${token}`);
// console.log("FCM Response:", response); console.log("FCM Response:", response);
// console.log("Titel:", title); console.log("Titel:", title);
// console.log("Body:", body); console.log("Body:", body);
// console.log("Data:", data); console.log("Data:", data);
// } 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}`);
// } }
// } }
// }); });
// await Promise.all(notificationPromises); await Promise.all(notificationPromises);
// // Update lastNotificationSent timestamp if preference is not "always" // Update lastNotificationSent timestamp if preference is not "always"
// if (notificationPreference !== "always") { if (notificationPreference !== "always") {
// await User.updateOne({ customerId }, { $set: { lastNotificationSent: now } }); await User.updateOne({ customerId }, { $set: { lastNotificationSent: now } });
// } }
// }); });
// await Promise.all(promises); await Promise.all(promises);
// } catch (error) { } catch (error) {
// console.error("Error sending notifications:", error); console.error("Error sending notifications:", error);
// } }
// }; };

Loading…
Cancel
Save