manual notification

master^2
Bhaskar 7 months ago
parent 95fd3cd1d6
commit dd70847b04

@ -2104,85 +2104,37 @@ eventEmitter.on('sendThresholdTimeNotification', async (fcmTokens, message) => {
// } // }
// ); // );
eventEmitter.on( // eventEmitter.on(
"sendMotorStartNotification", // "sendMotorStartNotification",
async ( // async (hw_Id, fcmTokens, waterLevel, blockName, tankName, motorOnType, stopCriteria, typeOfWater, manualThresholdTime) => {
customerId, // try {
fcmTokens, // const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
waterLevel,
blockName,
tankName,
motorOnType,
stopCriteria,
typeOfWater,
manualThresholdTime
) => {
try {
// Get the latest timestamp
const currentDateTime = new Date();
const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" });
const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
// Fetch users based on the customerId
const users = await User.find({ customerId }).select("username fcmIds notificationPreference lastNotificationSent");
if (!users || users.length === 0) {
console.log(`No users found for customer ID: ${customerId}`);
return;
}
const userNames = users.map(user => user.username).join(", ");
// Filter valid FCM tokens for the specific customer
const validTokens = users.flatMap(user => user.fcmIds).filter(token => fcmTokens.includes(token));
if (validTokens.length === 0) {
console.log(`No valid FCM tokens found for customer ID: ${customerId}`);
return;
}
// Check if the motor was started manually (forced manual)
if (motorOnType !== "forced_manual") {
console.log(`Skipping notification: Motor was started in ${motorOnType} mode.`);
return;
}
// Determine the pump initiation method
const startMethod = motorOnType === "forced_manual" ? "Physically" : "Manually";
// Generate the motor name dynamically
const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// Determine stop condition message // if (motorOnType !== "forced_manual") {
let stopConditionMessage = ""; // console.log(`Skipping notification: Motor was started in ${motorOnType} mode.`);
if (stopCriteria === "manual") { // return;
stopConditionMessage = `⚠️ Pump will stop **manually**.\n`; // }
} else if (stopCriteria === "threshold") {
stopConditionMessage = `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.\n`;
}
// Prepare the notification message // const stopConditionMessage = stopCriteria === "manual"
const message = // ? `⚠️ Pump will stop **manually**.`
`🚰 **Motor Started** 🚀\n` + // : `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.`;
`🔹 **Motor Name:** ${motorName}\n` +
`🛢️ **Tank Name:** ${tankName}\n` +
`🏢 **Block Name:** ${blockName}\n` +
`💧 **Water Level:** ${waterLevel}%\n` +
`👤 **Started by:** ${userNames}\n` +
`📱 **Mode:** ${startMethod}\n` +
`🕒 **Pump started at:** ${formattedTime}\n` +
stopConditionMessage;
// Send the notification // const message = `🚰 **Motor Started** 🚀\n` +
await sendNotification(customerId, validTokens, "Motor Started 🚀", message); // `🔹 **Motor Name:** ${tankName}-${blockName}-${typeOfWater}\n` +
// `🏢 **Block Name:** ${blockName}\n` +
// `💧 **Water Level:** ${waterLevel}%\n` +
// `📱 **Mode:** Physically Started\n` +
// `🕒 **Pump started at:** ${formattedTime}\n` +
// stopConditionMessage;
console.log(`Motor start notification sent successfully to customer ID: ${customerId}`); // await sendNotification(hw_Id, fcmTokens, "Motor Started 🚀", message);
// console.log(`✅ Motor start notification sent for Motor ID: ${hw_Id}`);
} catch (error) { // } catch (error) {
console.error(`Error in sendMotorStartNotification event for customer ID: ${customerId}`, error); // console.error(`❌ Error in sendMotorStartNotification for Motor ID: ${hw_Id}`, error);
} // }
} // }
); // );
@ -2229,58 +2181,86 @@ eventEmitter.on(
// ); // );
eventEmitter.on( // eventEmitter.on(
"sendMotorStopNotification", // "sendMotorStopNotification",
async (customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType,typeOfWater) => { // async (hw_Id, fcmTokens, waterLevel, blockName, tankName, motorOnType, typeOfWater) => {
try { // try {
// Get the latest timestamp // const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
const currentDateTime = new Date();
const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" });
const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
// Fetch users based on the customerId // const message = `⏹️ **Motor Stopped** 🛑\n` +
const users = await User.find({ customerId }).select("username fcmIds notificationPreference lastNotificationSent"); // `🔹 **Motor Name:** ${tankName}-${blockName}-${typeOfWater}\n` +
// `🏢 **Block Name:** ${blockName}\n` +
// `💧 **Water Level:** ${waterLevel}%\n` +
// `📱 **Mode:** Forced Manual\n` +
// `🕒 **Pump stopped at:** ${formattedTime}`;
if (!users || users.length === 0) { // await sendNotification(hw_Id, fcmTokens, "Motor Stopped 🛑", message);
console.log(`No users found for customer ID: ${customerId}`); // console.log(`✅ Motor stop notification sent for Motor ID: ${hw_Id}`);
return;
}
const userNames = users.map(user => user.username).join(", "); // } catch (error) {
// console.error(`❌ Error in sendMotorStopNotification for Motor ID: ${hw_Id}`, error);
// }
// }
// );
// Filter valid FCM tokens for the specific customer
const validTokens = users.flatMap(user => user.fcmIds).filter(token => fcmTokens.includes(token));
if (validTokens.length === 0) { // 🚀 Motor Start Notification
console.log(`No valid FCM tokens found for customer ID: ${customerId}`); eventEmitter.on(
"sendMotorStartNotification",
async (hw_Id, customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType, stopCriteria, typeOfWater, manualThresholdTime) => {
try {
const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
if (motorOnType !== "forced_manual") {
console.log(`⚠️ Skipping notification: Motor was started in **${motorOnType}** mode.`);
return; return;
} }
// Generate the motor name dynamically const stopConditionMessage = stopCriteria === "manual"
const motorName = `${tankName}-${blockName}-${typeOfWater}`; ? `⚠️ Pump will stop **manually**.`
: `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.`;
// Prepare the notification message const message = `🚰 **Motor Started** 🚀\n` +
const message = `👤 **Customer ID:** ${customerId}\n` +
`⏹️ **Motor Stopped** 🛑\n` + `🔹 **Motor Name:** ${tankName} - ${blockName} - ${typeOfWater}\n` +
`🔹 **Motor Name:** ${motorName}\n` +
`🛢️ **Tank Name:** ${tankName}\n` +
`🏢 **Block Name:** ${blockName}\n` + `🏢 **Block Name:** ${blockName}\n` +
`💧 **Water Level:** ${waterLevel}%\n` + `💧 **Water Level:** ${waterLevel}%\n` +
`👤 **Stopped by:** ${userNames}\n` + `📱 **Mode:** **Physically Started**\n` +
`📱 **Mode:** ${motorOnType}\n` + `🕒 **Pump started at:** ${formattedTime}\n` +
`🕒 **Pump stopped at:** ${formattedTime}\n`; stopConditionMessage;
// Send the notification
await sendNotification(customerId, validTokens, "Motor Stopped 🛑", message);
console.log(`Motor stop notification sent successfully to customer ID: ${customerId}`); await sendNotification(hw_Id, customerId, fcmTokens, "Motor Started 🚀", message);
console.log(`✅ Motor start notification sent for Customer ID: ${customerId}`);
} catch (error) { } catch (error) {
console.error(`Error in sendMotorStopNotification event for customer ID: ${customerId}`, error); console.error(`❌ Error in sendMotorStartNotification for Customer ID: ${customerId}`, error);
} }
} }
); );
// 🛑 Motor Stop Notification
eventEmitter.on(
"sendMotorStopNotification",
async (hw_Id, customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType, typeOfWater) => {
try {
const formattedTime = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
const message = `🛑 **Motor Stopped** ❌\n` +
`👤 **Customer ID:** ${customerId}\n` +
`🔹 **Motor Name:** ${tankName} - ${blockName} - ${typeOfWater}\n` +
`🏢 **Block Name:** ${blockName}\n` +
`💧 **Water Level:** ${waterLevel}%\n` +
`📱 **Mode:** **Physically Stopped**\n` +
`🕒 **Pump stopped at:** ${formattedTime}`;
await sendNotification(hw_Id, customerId, fcmTokens, "Motor Stopped ❌", message);
console.log(`✅ Motor stop notification sent for Customer ID: ${customerId}`);
} catch (error) {
console.error(`❌ Error in sendMotorStopNotification for Customer ID: ${customerId}`, error);
}
}
);
// eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => { // eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => {
// const notificationMessage = `Warning: Water level is low in the tank. // const notificationMessage = `Warning: Water level is low in the tank.
@ -6358,7 +6338,7 @@ client.on('connect', () => {
// Handling incoming MQTT messages // Handling incoming MQTT messages
client.on('message', async (topic, message) => { client.on('message', async (topic, message) => {
console.log(`Message received on topic ${topic}:`, message.toString()); console.log(`📩 Message received on topic ${topic}:`, message.toString());
if (topic === 'water/iot-data') { if (topic === 'water/iot-data') {
try { try {
@ -6369,7 +6349,7 @@ client.on('message', async (topic, message) => {
const date = currentDate.toISOString(); const date = currentDate.toISOString();
const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' });
// Process each tank to update water level and connections // Process each tank to update water level
for (const tank of tanks) { for (const tank of tanks) {
const { Id: tankhardwareId, level: tankHeight } = tank; const { Id: tankhardwareId, level: tankHeight } = tank;
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
@ -6381,10 +6361,10 @@ client.on('message', async (topic, message) => {
// Fetch FCM tokens of users linked to this customer // Fetch FCM tokens of users linked to this customer
const users = await User.find({ customerId }).select("fcmIds"); const users = await User.find({ customerId }).select("fcmIds");
const fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token); // Get valid FCM tokens const fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token);
if (!fcmTokens.length) { if (!fcmTokens.length) {
console.log(`No valid FCM tokens found for customer ID: ${customerId}`); console.log(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`);
} }
// Calculate water level // Calculate water level
@ -6400,12 +6380,12 @@ client.on('message', async (topic, message) => {
} }
} }
// Motor Status Processing // 🔹 Motor Status Processing
const status = Motor_status; const status = Motor_status;
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
if (!motorTank) { if (!motorTank) {
console.log('Motor not found for the specified motor_id'); console.log(`⚠️ Motor not found for motor_id: ${hw_Id}`);
return; return;
} }
@ -6416,61 +6396,68 @@ client.on('message', async (topic, message) => {
if (inputConnection) { if (inputConnection) {
inputConnection.motor_status = status; inputConnection.motor_status = status;
const tankName = motorTank.tankName; const tankName = motorTank.tankName;
const blockName = motorTank.blockName || "N/A";
// ✅ Motor Start Notification
if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") { if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "2"; inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "forced_manual"; inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime; inputConnection.startTime = currentTime;
// // Determine stop criteria dynamically console.log(`🚀 Motor started in FORCED_MANUAL mode.`);
const stopCriteria = inputConnection.motor_stop_status === "1" ? "manual" : "threshold";
eventEmitter.emit(
"sendMotorStartNotification",
customerId, // Pass customerId
fcmTokens, // Pass FCM tokens
hw_Id, // Motor ID
inputConnection.water_level || 0, // Water level
motorTank.blockName || "N/A", // Block name
tankName, // Tank name
inputConnection.motor_on_type, // Motor on type
stopCriteria, // Stop criteria (manual/threshold)
manual_threshold_time // Threshold time (only used for threshold stop)
);
// Determine stop criteria
const stopCriteria = inputConnection.motor_stop_status === "1" ? "manual" : "threshold";
eventEmitter.emit(
"sendMotorStartNotification",
hw_Id, // Motor ID
customerId, // Customer ID
fcmTokens, // Valid tokens
inputConnection.water_level || 0,
blockName,
tankName,
"forced_manual", // Forced manual start
stopCriteria,
inputConnection.typeOfWater,
inputConnection.manual_threshold_time
);
} }
// 🛑 Motor Stop Notification
if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) { if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "1"; inputConnection.motor_stop_status = "1";
inputConnection.stopTime = currentTime; inputConnection.stopTime = currentTime;
console.log(`🛑 Motor stopped manually.`);
eventEmitter.emit( eventEmitter.emit(
"sendMotorStopNotification", "sendMotorStopNotification",
customerId, // Pass customerId hw_Id, // Motor ID
fcmTokens, // Pass FCM tokens customerId, // Customer ID
hw_Id, // Motor ID fcmTokens, // Valid tokens
inputConnection.water_level || 0, inputConnection.water_level || 0,
motorTank.blockName || "N/A", blockName,
tankName, tankName,
inputConnection.motor_on_type "forced_manual", // Forced manual stop
inputConnection.typeOfWater
); );
} }
await motorTank.save(); await motorTank.save();
} }
console.log('Data processed successfully for hardwareId:', hw_Id); console.log(`✅ Data processed successfully for hardwareId: ${hw_Id}`);
} catch (err) { } catch (err) {
console.error('Error processing message:', err.message); console.error(`❌ Error processing message: ${err.message}`);
} }
} }
}); });
exports.getPendingAndCompletedsurveyOfparticularInstaller = async (request, reply) => { exports.getPendingAndCompletedsurveyOfparticularInstaller = async (request, reply) => {
try { try {
const { installationId } = request.params; const { installationId } = request.params;

Loading…
Cancel
Save