chnages in notifications

master^2
Bhaskar 8 months ago
parent 01584d0f1e
commit 29ee4665de

@ -1727,46 +1727,101 @@ admin.initializeApp({
// );
// Event listener for motorStart
eventEmitter.on(
'motorStart',
async (customerId, fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => {
try {
// Log the FCM tokens to check their format
console.log("FCM Tokens:", fcmTokens);
// eventEmitter.on(
// 'motorStart',
// async (customerId, fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => {
// try {
// // Log the FCM tokens to check their format
// console.log("FCM Tokens:", fcmTokens);
// Retrieve the user information
const users = await User.find({ customerId: customerId, fcmIds: { $in: fcmTokens } });
// console.log("users", users);
const userNames = users.map(user => user.username).join(', ');
// console.log("userNames", userNames);
// // Retrieve the user information
// const users = await User.find({ customerId: customerId, fcmIds: { $in: fcmTokens } });
// // console.log("users", users);
// const userNames = users.map(user => user.username).join(', ');
// // console.log("userNames", userNames);
const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// Generate motor name dynamically based on tank name, block name, and type of water
const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// // Generate motor name dynamically based on tank name, block name, and type of water
// const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// Get current date and time for the motor start time
const currentDateTime = new Date();
const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed
const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed
// // Get current date and time for the motor start time
// const currentDateTime = new Date();
// const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed
// const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed
// Prepare the message
const message =
`🚰 Motor Name: ${motorName}\n` +
`🚰 Tank Name: '${tankName}'\n` +
`🏢 Block Name: '${blockName}'\n` +
`👤 Started by: ${userNames}\n` +
`📱 Mode: '${startMethod}'\n` +
`🕒 Pump started at: ${startTime} \n` +
`Will stop after: '${manual_threshold_time}' mins`;
// // Prepare the message
// const message =
// `🚰 Motor Name: ${motorName}\n` +
// `🚰 Tank Name: '${tankName}'\n` +
// `🏢 Block Name: '${blockName}'\n` +
// `👤 Started by: ${userNames}\n` +
// `📱 Mode: '${startMethod}'\n` +
// `🕒 Pump started at: ${startTime} \n` +
// `Will stop after: '${manual_threshold_time}' mins`;
// Send the notification
await sendNotification(customerId, fcmTokens, 'Arminta Water Management', message);
} catch (error) {
console.error('Error in motorStart event:', error);
// // Send the notification
// await sendNotification(customerId, fcmTokens, 'Arminta Water Management', message);
// } catch (error) {
// console.error('Error in motorStart event:', error);
// }
// }
// );
eventEmitter.on("motorStart", async (customerId, fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => {
try {
console.log("Motor Start Event Triggered for:", customerId);
const users = await User.find({ customerId, fcmIds: { $in: fcmTokens } });
if (users.length === 0) {
console.log(`No users found for customerId: ${customerId}`);
return;
}
const userNames = users.map(user => user.username).join(", ");
const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
const motorName = `${tankName}-${blockName}-${typeOfWater}`;
const message =
`🚰 Motor Name: ${motorName}\n` +
`🚰 Tank Name: '${tankName}'\n` +
`🏢 Block Name: '${blockName}'\n` +
`👤 Started by: ${userNames}\n` +
`📱 Mode: '${startMethod}'\n` +
`🕒 Pump started at: ${startTime} \n` +
`Will stop after: '${manual_threshold_time}' mins`;
await sendNotification(customerId, fcmTokens, "Arminta Water Management", message);
} catch (error) {
console.error("Error in motorStart event:", error);
}
);
});
// Motor Stop Event
eventEmitter.on("motorStop", async (customerId, fcmTokens, tankName, blockName, stopTime, motorOnType, totalWaterPumped, typeOfWater) => {
try {
console.log("Motor Stop Event Triggered for:", customerId);
const users = await User.find({ customerId, fcmIds: { $in: fcmTokens } });
if (users.length === 0) {
console.log(`No users found for customerId: ${customerId}`);
return;
}
const userNames = users.map(user => user.username).join(", ");
const stopMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
const motorName = `${tankName}-${blockName}-${typeOfWater}`;
const message =
`🚰 Motor Name: ${motorName}\n` +
`🛢️ Tank Name: '${tankName}'\n` +
`🏢 Block Name: '${blockName}'\n` +
`👤 Stopped by: ${userNames}\n` +
`📱 Mode: '${stopMethod}'\n` +
`🕒 Pump stopped at: ${stopTime}\n` +
`💧 Total water pumped: ${totalWaterPumped} liters\n`;
await sendNotification(customerId, fcmTokens, "Arminta Water Management", message);
} catch (error) {
console.error("Error in motorStop event:", error);
}
});
// eventEmitter.on(
// "motorStart",
@ -1831,52 +1886,52 @@ eventEmitter.on(
// Event listener for motorStop
// Event listener for motorStop
eventEmitter.on(
'motorStop',
async (customerId, fcmTokens, tankName, blockName, stopTime, motorOnType, totalWaterPumped, typeOfWater) => {
try {
// Log the FCM tokens to check their format
console.log("FCM Tokens:", fcmTokens);
// eventEmitter.on(
// 'motorStop',
// async (customerId, fcmTokens, tankName, blockName, stopTime, motorOnType, totalWaterPumped, typeOfWater) => {
// try {
// // Log the FCM tokens to check their format
// console.log("FCM Tokens:", fcmTokens);
// Retrieve the user information based on customerId
const users = await User.find({ customerId: customerId, fcmIds: { $in: fcmTokens } });
console.log("users", users);
// // Retrieve the user information based on customerId
// const users = await User.find({ customerId: customerId, fcmIds: { $in: fcmTokens } });
// console.log("users", users);
// If no users are found, log a message and return
if (users.length === 0) {
console.log(`No users found for customerId: ${customerId}`);
return;
}
// // If no users are found, log a message and return
// if (users.length === 0) {
// console.log(`No users found for customerId: ${customerId}`);
// return;
// }
const userNames = users.map(user => user.username).join(', ');
// const userNames = users.map(user => user.username).join(', ');
const stopMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// const stopMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// Generate motor name dynamically based on tank name, block name, and type of water
const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// // Generate motor name dynamically based on tank name, block name, and type of water
// const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// Get current date and time for the motor stop time
const currentDateTime = new Date();
const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed
const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed
// // Get current date and time for the motor stop time
// const currentDateTime = new Date();
// const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed
// const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed
// Prepare the message
const message =
`🚰 Motor Name: ${motorName}\n` +
`🛢️ Tank Name: '${tankName}'\n` +
`🏢 Block Name: '${blockName}'\n` +
`👤 Stopped by: ${userNames}\n` +
`📱 Mode: '${stopMethod}'\n` +
`🕒 Pump stopped at: ${stopTime}\n` +
`💧 Total water pumped: ${totalWaterPumped} liters\n`;
// // Prepare the message
// const message =
// `🚰 Motor Name: ${motorName}\n` +
// `🛢️ Tank Name: '${tankName}'\n` +
// `🏢 Block Name: '${blockName}'\n` +
// `👤 Stopped by: ${userNames}\n` +
// `📱 Mode: '${stopMethod}'\n` +
// `🕒 Pump stopped at: ${stopTime}\n` +
// `💧 Total water pumped: ${totalWaterPumped} liters\n`;
// Send the notification
await sendNotification(customerId, fcmTokens, 'Arminta Water Management', message);
} catch (error) {
console.error('Error in motorStop event:', error);
}
}
);
// // Send the notification
// await sendNotification(customerId, fcmTokens, 'Arminta Water Management', message);
// } catch (error) {
// console.error('Error in motorStop event:', error);
// }
// }
// );
eventEmitter.on(
@ -2467,50 +2522,52 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
}
if (!Array.isArray(fcmIds) || fcmIds.length === 0) {
throw new Error("No FCM tokens provided or invalid format.");
console.log("No valid FCM tokens provided.");
return;
}
// Flatten tokens safely
const flatTokens = fcmIds.flat ? fcmIds.flat() : fcmIds;
if (flatTokens.length === 0) {
throw new Error("Flattened FCM token list is empty.");
}
// Flatten nested arrays
const flatFcmIds = fcmIds.flat();
// Fetch the user based on customerId
// Fetch user from database
const user = await User.findOne({ customerId }).select("fcmIds");
if (!user || !Array.isArray(user.fcmIds)) {
console.log(`No valid user or FCM tokens found for customer ID: ${customerId}`);
console.log(`No valid FCM tokens found for customer ID: ${customerId}`);
return;
}
// Match provided fcmIds with those stored for the customerId
const validTokens = flatTokens.filter(token => user.fcmIds.includes(token));
console.log("User's stored FCM tokens:", user.fcmIds);
console.log("FCM tokens passed to function:", flatFcmIds);
// Proper token filtering
const validTokens = user.fcmIds.filter(token => flatFcmIds.some(t => t.trim() === token.trim()));
console.log("Valid tokens for notification:", validTokens);
if (validTokens.length === 0) {
console.log(`No matching FCM tokens for customer ID: ${customerId}`);
return;
}
// Send notifications to matching tokens
const promises = validTokens.map(async (token) => {
try {
console.log(`Sending notification to token: ${token}`);
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:`, response);
console.log(`title:`, title);
console.log(`body:`, body);
} catch (error) {
console.error(`Failed to send notification to token: ${token}`, error);
// Handle invalid tokens
if (error.code === "messaging/registration-token-not-registered") {
if (error?.errorInfo?.code === "messaging/registration-token-not-registered") {
await User.updateOne({ customerId }, { $pull: { fcmIds: token } });
console.log(`Removed invalid token: ${token}`);
}
@ -2518,7 +2575,6 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
});
await Promise.all(promises);
} catch (error) {
console.error("Error sending notifications:", error);
}
@ -2526,6 +2582,8 @@ const sendNotification = async (customerId, fcmIds, title, body) => {
// const sendNotification = async (customerId, fcmIds, title, body) => {
// try {
// if (!customerId) {
@ -3198,22 +3256,36 @@ exports.motorAction = async (req, reply) => {
// await checkWaterLevelsAndNotify(customerId, tankName, receiverTank.tankLocation, fcmToken);
if (!notificationSentStatus.motorStart) {
console.log("Emitting motorStart event for customer:", customerId);
eventEmitter.emit(
"motorStart",
customerId,
fcmToken, // Ensure this is an array of tokens
tankName,
blockName,
startTime,
"Mobile APP",
manual_threshold_time,
typeOfWater
);
notificationSentStatus.motorStart = true; // Prevent duplicate notifications
try {
// const { customerId, fcmToken, motorId, tankName, blockName, startTime, manual_threshold_time, typeOfWater } = req.body;
// if (!customerId || !fcmToken) {
// return reply.code(400).send({ error: "Missing required fields" });
// }
eventEmitter.emit("motorStart", customerId, fcmToken, tankName, blockName, startTime, "Mobile APP", manual_threshold_time, typeOfWater);
reply.code(200).send({ message: "Motor started successfully." });
} catch (error) {
console.error("Error in handleMotorStart:", error);
reply.code(500).send({ error: "Internal Server Error" });
}
// if (!notificationSentStatus.motorStart) {
// console.log("Emitting motorStart event for customer:", customerId);
// eventEmitter.emit(
// "motorStart",
// customerId,
// fcmToken, // Ensure this is an array of tokens
// tankName,
// blockName,
// startTime,
// "Mobile APP",
// manual_threshold_time,
// typeOfWater
// );
// notificationSentStatus.motorStart = true; // Prevent duplicate notifications
// }
// Start checking water level every 30 minutes
@ -3235,23 +3307,39 @@ exports.motorAction = async (req, reply) => {
} else if (action === "stop") {
motorStopStatus = "1"; // If action is stop, set stop status to "1"
if (!notificationSentStatus.motorStop) {
// Emit motorStop event
const totalWaterPumped = await calculateTotalPumpedWater(customerId, motorId, start_instance_id); // A function to calculate total water pumped
eventEmitter.emit(
'motorStop',
customerId,
fcmToken,
tankName,
blockName,
stopTime,
"Mobile APP",
totalWaterPumped, // Include total water pumped
typeOfWater
);
notificationSentStatus.motorStop = true; // Set flag to true to prevent duplicate notifications
try {
// const { customerId, fcmToken, motorId, tankName, blockName, stopTime, start_instance_id, typeOfWater } = req.body;
// if (!customerId || !fcmToken) {
// return reply.code(400).send({ error: "Missing required fields" });
// }
const totalWaterPumped = await calculateTotalPumpedWater(customerId, motorId, start_instance_id);
eventEmitter.emit("motorStop", customerId, fcmToken, tankName, blockName, stopTime, "Mobile APP", totalWaterPumped, typeOfWater);
reply.code(200).send({ message: "Motor stopped successfully." });
} catch (error) {
console.error("Error in handleMotorStop:", error);
reply.code(500).send({ error: "Internal Server Error" });
}
// if (!notificationSentStatus.motorStop) {
// // Emit motorStop event
// const totalWaterPumped = await calculateTotalPumpedWater(customerId, motorId, start_instance_id); // A function to calculate total water pumped
// eventEmitter.emit(
// 'motorStop',
// customerId,
// fcmToken,
// tankName,
// blockName,
// stopTime,
// "Mobile APP",
// totalWaterPumped, // Include total water pumped
// typeOfWater
// );
// notificationSentStatus.motorStop = true; // Set flag to true to prevent duplicate notifications
// }
await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId },
{

Loading…
Cancel
Save