send notification particular user name passed

master^2
Bhaskar 9 months ago
parent d4fdd3101a
commit b1d98b88da

@ -1768,60 +1768,173 @@ admin.initializeApp({
// }
// );
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;
eventEmitter.on(
"motorStart",
async (customerId, fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater, hw_Id, phoneNumber) => {
try {
console.log("Motor Start Event Triggered for:", customerId);
// Fetch user or staff based on customerId
const user = await User.findOne({ customerId });
if (!user) {
console.log(`No user found for customerId: ${customerId}`);
return;
}
// Identify who started the motor
let startedBy = "Unknown"; // Default value
if (user.phone === phoneNumber) {
startedBy = user.username; // Customer's name
} else {
const staffMember = user.staff.staff.find(staff => staff.phone === phoneNumber);
if (staffMember) {
startedBy = staffMember.name; // Staff's name
}
}
if (startedBy === "Unknown") {
console.log("User not found. Cannot proceed with motorStart event.");
return;
}
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: ${startedBy}\n` + // Only name is displayed
`📱 Mode: '${startMethod}'\n` +
`🕒 Pump started at: ${startTime} \n` +
`Will stop after: '${manual_threshold_time}' mins`;
await sendNotification(hw_Id, customerId, fcmTokens, "Arminta Water Management", message);
} catch (error) {
console.error("Error in motorStart event:", error);
}
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;
eventEmitter.on(
"motorStop",
async (
customerId,
fcmTokens,
tankName,
blockName,
stopTime,
motorOnType,
totalWaterPumped,
typeOfWater,
hw_Id,
phoneNumber
) => {
try {
console.log("Motor Stop Event Triggered for:", customerId);
// Fetch user or staff based on customerId
const user = await User.findOne({ customerId });
if (!user) {
console.log(`No user found for customerId: ${customerId}`);
return;
}
// Identify who stopped the motor
let stoppedBy = "Unknown"; // Default value
if (user.phone === phoneNumber) {
stoppedBy = user.username; // Customer's name
} else if (user.staff && user.staff.staff) {
const staffMember = user.staff.staff.find((staff) => staff.phone === phoneNumber);
if (staffMember) {
stoppedBy = staffMember.name; // Staff's name
}
}
if (stoppedBy === "Unknown") {
console.log("User not found. Cannot proceed with motorStop event.");
return;
}
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: ${stoppedBy}\n` + // Only name is displayed
`📱 Mode: '${stopMethod}'\n` +
`🕒 Pump stopped at: ${stopTime}\n` +
`💧 Total water pumped: ${totalWaterPumped} liters\n`;
await sendNotification(hw_Id, customerId, fcmTokens, "Arminta Water Management", message);
} catch (error) {
console.error("Error in motorStop event:", error);
}
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);
}
});
);
//important
// 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 important
// 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",
@ -3333,8 +3446,30 @@ exports.motorAction = async (req, reply) => {
}
// Get user FCM tokens
const users = await User.find({ customerId });
const fcmToken = users.map(user => user.fcmIds).filter(fcmIds => fcmIds);
const users = await User.findOne({ customerId });
console.log("users",users)
let loggedInUser = null;
if (users) {
if (users.phone === req.body.phone) {
loggedInUser = { role: "Customer", name: user.username, phone: user.phone };
} else if (users.staff && users.staff.staff) {
const staffMember = users.staff.staff.find(staff => staff.phone === req.body.phone);
if (staffMember) {
loggedInUser = { role: "Staff", name: staffMember.name, phone: staffMember.phone };
}
}
}
if (!loggedInUser) {
console.log("User not found. Cannot proceed with motorStart event.");
return reply.status(404).send({ error: "User not found" }); // ✅ FIX: Ensure a response is returned
}
const fcmToken = users.fcmIds ? users.fcmIds.filter(fcmIds => fcmIds) : [];
// const fcmToken = users.map(user => user.fcmIds).filter(fcmIds => fcmIds);
console.log(fcmToken)
const receiverTank = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
console.log(receiverTank)
@ -3376,7 +3511,20 @@ exports.motorAction = async (req, reply) => {
// return reply.code(400).send({ error: "Missing required fields" });
// }
eventEmitter.emit("motorStart", customerId, fcmToken, tankName, blockName, startTime, "Mobile APP", manual_threshold_time, typeOfWater);
// eventEmitter.emit("motorStart", customerId, fcmToken, tankName, blockName, startTime, "Mobile APP", manual_threshold_time, typeOfWater);
eventEmitter.emit(
"motorStart",
customerId,
fcmToken,
tankName,
blockName,
startTime,
"Mobile APP",
manual_threshold_time,
typeOfWater,
motorId,
loggedInUser.phone,
);
reply.code(200).send({ message: "Motor started successfully." });
} catch (error) {
@ -3384,24 +3532,6 @@ exports.motorAction = async (req, reply) => {
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
if (!waterLevelCheckInterval) {
waterLevelCheckInterval = setInterval(async () => {
@ -3422,14 +3552,12 @@ exports.motorAction = async (req, reply) => {
motorStopStatus = "1"; // If action is stop, set stop status to "1"
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);
eventEmitter.emit("motorStop", customerId, fcmToken, tankName, blockName, stopTime, "Mobile APP", totalWaterPumped, typeOfWater, motorId,
loggedInUser.phone,);
reply.code(200).send({ message: "Motor stopped successfully." });
} catch (error) {
@ -3437,23 +3565,7 @@ exports.motorAction = async (req, reply) => {
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 },
{

@ -353,6 +353,8 @@ module.exports = function (fastify, opts, next) {
stopTime:{type:"string"},
start_instance_id:{type:"string"},
motor_id:{type:"string"},
phone:{type:"string"},
},
},
security: [

Loading…
Cancel
Save