changes in get motordata

master^2
Varun 9 months ago
parent fb7b4e8751
commit bc8c5e750c

@ -349,6 +349,7 @@ exports.getTanksofParticularInstaller = async (req, reply) => {
// throw boom.boomify(err);
// }
//};
// const boom = require("@hapi/boom"); // Assuming you are using boom for error handling
@ -356,46 +357,50 @@ exports.getTankmotordata = async (req, reply) => {
try {
const { startDate, stopDate } = req.body;
const { customerId } = req.params;
// Parse the input startDate and stopDate using the desired format
// const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate();
// const end = moment(stopDate, "DD-MMM-YYYY - HH:mm").toDate();
// console.log(start,"start",end,"end")
// Check if the parsed dates are valid
// Convert the dates to the correct format for storage or querying (still in UTC)
// This gives a native JS Date object for querying
// Fetch the name from the User collection based on customerId, only from profile
const user = await User.findOne({ customerId })
.select("username");
// Validate and format the input dates
if (!moment(startDate, "DD-MMM-YYYY - HH:mm", true).isValid() || !moment(stopDate, "DD-MMM-YYYY - HH:mm", true).isValid()) {
return reply.send({ status_code: 400, message: "Invalid date format" });
}
if (user) {
// Get the full name (combine firstName and lastName if available)
const userName = user.username
? `${user.username}`
: "N/A"; // Fallback if no name is found
// Convert input dates to ISO 8601 format for Date comparison
const startISODate = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate();
const stopISODate = moment(stopDate, "DD-MMM-YYYY - HH:mm").toDate();
// Construct the query object for motor data based on customerId
const motorQuery = { customerId };
// Convert input dates to string format for string-based comparison
const startStringDate = moment(startDate, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm");
const stopStringDate = moment(stopDate, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm");
// Fetch motor data for the customerId within the time range
const motorDataDocs = await MotorData.find(motorQuery)
.where("startTime")
.gte(startDate) // Greater than or equal to startDate
.lte(stopDate) // Less than or equal to stopDate
.exec();
// Fetch the username based on customerId
const user = await User.findOne({ customerId }).select("username");
if (user) {
const userName = user.username || "N/A";
// Query the MotorData collection
const motorDataDocs = await MotorData.find({
customerId,
$or: [
{
startTime: { $gte: startISODate, $lte: stopISODate }, // Date-based comparison
},
{
startTime: { $gte: startStringDate, $lte: stopStringDate }, // String-based comparison
},
],
}).exec();
reply.send({
status_code: 200,
data: motorDataDocs,
count: motorDataDocs.length,
customerName: userName, // Add the username to the response
customerName: userName,
});
} else {
reply.send({ status_code: 404, message: "User not found" });
}
} catch (err) {
console.error("Error in getTankmotordata:", err);
throw boom.boomify(err);
}
};
@ -415,7 +420,7 @@ exports.updateTanklevels = async (req, reply) => {
for (const tank of tanks) {
const tankId = tank._id;
const tank_name = tank.tankName
const tank_name = tank.tankName
let capacity = parseInt(tank.capacity.replace(/,/g, ''), 10);
//let waterLevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10);
@ -5665,17 +5670,17 @@ client.on('message', async (topic, message) => {
inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime;
// Emit motor start notification with tankName
eventEmitter.emit(
"sendMotorStartNotification",
fcmToken, // 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
"threshold", // Stop criteria
manual_threshold_time // Threshold time in mins
);
// eventEmitter.emit(
// "sendMotorStartNotification",
// fcmToken, // 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
// "threshold", // Stop criteria
// manual_threshold_time // Threshold time in mins
// );
}
@ -5683,15 +5688,15 @@ client.on('message', async (topic, message) => {
inputConnection.motor_stop_status = "1";
// Emit motor stop notification with tankName
eventEmitter.emit(
"sendMotorStopNotification",
fcmToken, // 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
);
// eventEmitter.emit(
// "sendMotorStopNotification",
// fcmToken, // 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
// );
}
await motorTank.save(); // Save the updated tank
@ -6257,3 +6262,56 @@ cron.schedule(
timezone: "Asia/Kolkata", // Specify the timezone
}
);
// const updateStopTimeFormat = async () => {
// try {
// // Find records where stopTime is null or not in the required format
// const motorDataDocs = await MotorData.find();
// for (const doc of motorDataDocs) {
// // Parse and validate startTime
// const startTime = moment(doc.startTime, "DD-MMM-YYYY - HH:mm", true);
// if (!startTime.isValid()) {
// console.log(`Invalid startTime for record ID: ${doc._id}`);
// continue;
// }
// // Format startTime if it's not already formatted
// const formattedStartTime = startTime.format("DD-MMM-YYYY - HH:mm");
// // Check if stopTime is valid or calculate it
// let formattedStopTime = null;
// const stopTime = moment(doc.stopTime, "DD-MMM-YYYY - HH:mm", true);
// if (!stopTime.isValid()) {
// // Calculate stopTime by adding 30 minutes to startTime
// formattedStopTime = startTime.clone().add(30, "minutes").format("DD-MMM-YYYY - HH:mm");
// } else {
// // Format the existing stopTime
// formattedStopTime = stopTime.format("DD-MMM-YYYY - HH:mm");
// }
// // Update the document if startTime or stopTime is not correctly formatted
// if (doc.startTime !== formattedStartTime || doc.stopTime !== formattedStopTime) {
// await MotorData.updateOne(
// { _id: doc._id },
// {
// $set: {
// startTime: formattedStartTime,
// stopTime: formattedStopTime,
// },
// }
// );
// console.log(`Updated record ID: ${doc._id}`);
// }
// }
// console.log("StopTime format update completed.");
// } catch (err) {
// console.error("Error updating stopTime format:", err);
// }
// };
// // Call the function to update stopTime
// updateStopTimeFormat();

Loading…
Cancel
Save