manual notification

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

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

Loading…
Cancel
Save