diff --git a/src/controllers/installationController.js b/src/controllers/installationController.js index 693d33e6..375c5a1c 100644 --- a/src/controllers/installationController.js +++ b/src/controllers/installationController.js @@ -647,49 +647,64 @@ exports.assignTeamMemberToQuotation = async (request, reply) => { return reply.status(400).send({ error: "Both hardwareId and tankhardwareId are required" }); } - console.log("Fetching details for:", { hardwareId, tankhardwareId }); + console.log("Fetching tank data for:", { hardwareId, tankhardwareId }); - // Query with projection to match the specific tank - const data = await IotData.findOne( - { hardwareId, tanks: { $elemMatch: { tankhardwareId } } }, - { "tanks.$": 1, hardwareId: 1, mode: 1, date: 1, time: 1 } - ).lean(); + // Get the latest record for the given hardwareId + const latestData = await IotData.findOne({ hardwareId }) + .sort({ date: -1 }) // Get the latest one + .lean(); + + if (!latestData || !Array.isArray(latestData.tanks)) { + return reply.code(404).send({ message: "No data found for given hardwareId and tankhardwareId" }); + } - if (!data) { - return reply.send({ status_code: 404, message: "Data not found", data: null }); + // Find the matching tank from the array + const matchedTank = latestData.tanks.find(tank => tank.tankhardwareId === tankhardwareId); + + if (!matchedTank) { + return reply.code(404).send({ message: "Tank not found in latest record" }); } - // Use the IotData's date/time if available, otherwise fallback to now - const now = new Date(data.date || Date.now()); - const connected_lora_date = now.toISOString().split("T")[0]; // yyyy-mm-dd - const connected_lora_time = now.toTimeString().split(" ")[0]; // hh:mm:ss + const connected_lora_date = new Date(matchedTank.date).toISOString().split("T")[0]; + const connected_lora_time = matchedTank.time || new Date(matchedTank.date).toTimeString().split(" ")[0]; - // Update the related insensor with LoRa connected time and date - await Insensors.findOneAndUpdate( + // Update the Insensors collection where: + // - connected_to = master hardwareId + // - hardwareId = tankhardwareId + const updateResult = await Insensors.findOneAndUpdate( { connected_to: hardwareId, hardwareId: tankhardwareId }, { - connected_lora_date, - connected_lora_time + $set: { + connected_lora_date, + connected_lora_time + } }, { new: true } ); + if (!updateResult) { + console.log("No Insensor found for update."); + } else { + console.log("Updated Insensor:", updateResult._id); + } + return reply.send({ status_code: 200, message: "Success", - data, + data: matchedTank, connected_lora_date, connected_lora_time }); } catch (err) { - console.error("Error:", err); + console.error("Error in getByHardwareAndTankId:", err); return reply.status(500).send({ error: "Internal Server Error" }); } }; + exports.getAllocatedSensorsByTank = async (req, reply) => { try { let { customerId, tankName } = req.params;