removed notification preference

master^2
Bhaskar 8 months ago
parent 69daf00e55
commit 01584d0f1e

@ -1736,9 +1736,9 @@ eventEmitter.on(
// Retrieve the user information
const users = await User.find({ customerId: customerId, fcmIds: { $in: fcmTokens } });
console.log("users", users);
// console.log("users", users);
const userNames = users.map(user => user.username).join(', ');
console.log("userNames", userNames);
// console.log("userNames", userNames);
const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
@ -2460,8 +2460,6 @@ const emitWithTimestamp = (eventName, fcmTokens, motorId, waterLevel) => {
// }
// };
const sendNotification = async (customerId, fcmIds, title, body) => {
try {
if (!customerId) {
@ -2472,84 +2470,50 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
throw new Error("No FCM tokens provided or invalid format.");
}
// Flatten tokens safely
const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds;
if (flatTokens.length === 0) {
throw new Error("Flattened FCM token list is empty.");
}
// Fetch users based on customerId
const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent");
// Fetch the user based on customerId
const user = await User.findOne({ customerId }).select("fcmIds");
const promises = users.map(async (user) => {
const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user;
if (!Array.isArray(userFcmIds)) {
console.log(`Invalid fcmIds for customer ID: ${customerId}`);
return;
}
const validTokens = flatTokens.filter(token => userFcmIds.includes(token));
if (validTokens.length === 0) {
console.log(`No matching FCM tokens for customer ID: ${customerId}`);
return;
}
if (!user || !Array.isArray(user.fcmIds)) {
console.log(`No valid user or FCM tokens found for customer ID: ${customerId}`);
return;
}
// Handle notification preferences
if (notificationPreference === "never") {
console.log(`Notifications disabled for customer ID: ${customerId}`);
return;
}
// Match provided fcmIds with those stored for the customerId
const validTokens = flatTokens.filter(token => user.fcmIds.includes(token));
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;
}
if (validTokens.length === 0) {
console.log(`No matching FCM tokens for customer ID: ${customerId}`);
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 to matching tokens
const promises = 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}`, response);
console.log(`Title: `, title);
console.log(`Body: `, body);
console.log(`Notification sent successfully to token: ${token}`);
console.log("FCM Response:", response);
} 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}`);
}
// Handle invalid tokens
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);
// Update lastNotificationSent timestamp if preference is not "always"
if (notificationPreference !== "always") {
await User.updateOne({ customerId }, { $set: { lastNotificationSent: now } });
}
});
@ -2562,6 +2526,110 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
// 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 flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds;
// if (flatTokens.length === 0) {
// throw new Error("Flattened FCM token list is empty.");
// }
// // Fetch users based on customerId
// const users = await User.find({ customerId }).select("fcmIds notificationPreference lastNotificationSent");
// const promises = users.map(async (user) => {
// const { fcmIds: userFcmIds, notificationPreference, lastNotificationSent } = user;
// if (!Array.isArray(userFcmIds)) {
// console.log(`Invalid fcmIds for customer ID: ${customerId}`);
// return;
// }
// 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 preferences
// if (notificationPreference === "never") {
// console.log(`Notifications disabled for customer ID: ${customerId}`);
// return;
// }
// 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;
// }
// // 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);
// } 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}`);
// }
// }
// });
// await Promise.all(notificationPromises);
// // Update lastNotificationSent timestamp if preference is not "always"
// if (notificationPreference !== "always") {
// await User.updateOne({ customerId }, { $set: { lastNotificationSent: now } });
// }
// });
// await Promise.all(promises);
// } catch (error) {
// console.error("Error sending notifications:", error);
// }
// };
// const sendPushNotification = async (registrationToken, title, body) => {
// const message = {

Loading…
Cancel
Save