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) => {
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;
}
// important
// const sendNotification = async (customerId, fcmIds, title, body) => {
// try {
// if (!customerId) {
// throw new Error("Customer ID is required.");
// }
// Flatten nested arrays
const flatFcmIds = fcmIds.flat();
// if (!Array.isArray(fcmIds) || fcmIds.length === 0) {
// console.log("No valid FCM tokens provided.");
// 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;
}
// // Flatten nested arrays
// const flatFcmIds = fcmIds.flat();
console.log("User's stored FCM tokens:", user.fcmIds);
console.log("FCM tokens passed to function:", flatFcmIds);
// // 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;
// }
// Proper token filtering
const validTokens = user.fcmIds.filter(token => flatFcmIds.some(t => t.trim() === token.trim()));
// console.log("User's stored FCM tokens:", user.fcmIds);
// console.log("FCM tokens passed to function:", flatFcmIds);
console.log("Valid tokens for notification:", validTokens);
// // Proper token filtering
// const validTokens = user.fcmIds.filter(token => flatFcmIds.some(t => t.trim() === token.trim()));
if (validTokens.length === 0) {
console.log(`No matching FCM tokens for customer ID: ${customerId}`);
return;
}
// console.log("Valid tokens for notification:", validTokens);
const promises = validTokens.map(async (token) => {
try {
console.log(`Sending notification to token: ${token}`);
// if (validTokens.length === 0) {
// console.log(`No matching FCM tokens for customer ID: ${customerId}`);
// return;
// }
const response = await admin.messaging().send({
notification: { title, body },
token,
data: { target: "/tank_levels" },
});
// const promises = validTokens.map(async (token) => {
// try {
// console.log(`Sending notification to token: ${token}`);
console.log(`Notification sent successfully:`, response);
console.log(`title:`, title);
console.log(`body:`, body);
// 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);
} 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}`);
}
}
});
// } catch (error) {
// console.error(`Failed to send notification to token: ${token}`, error);
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);
}
};

Loading…
Cancel
Save