diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index a3801708..38620081 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -5328,37 +5328,68 @@ exports.update_auto_mode = async (req, reply) => { exports.update_auto_percentage = async (req, reply) => { try { const customerId = req.params.customerId; - const { tankName, tankLocation, auto_min_percentage, auto_max_percentage, auto_mode_type } = req.body; + let { tankName, tankLocation, auto_min_percentage, auto_max_percentage, auto_mode_type } = req.body; - // Build the query filter - const filter = { customerId: customerId }; - if (tankName !== "all") { + // Handle the optional parameters + tankName = tankName ? tankName : null; + tankLocation = tankLocation ? tankLocation.toLowerCase() : null; + + const filter = { customerId }; + + // If tankName is not 'all', add it to the filter + if (tankName && tankName !== "all") { filter.tankName = tankName; } - if (tankLocation) { + + // Only add tankLocation to the filter if tankName is not 'all' + if (tankLocation && tankName !== "all") { filter.tankLocation = tankLocation; } - // Update auto_min_percentage, auto_max_percentage, and auto_mode_type - await Tank.updateMany( - filter, - { - $set: { - "auto_min_percentage": auto_min_percentage, - "auto_max_percentage": auto_max_percentage, - "auto_mode_type": auto_mode_type - } - } - ); + console.log("Update filter:", JSON.stringify(filter, null, 2)); - reply.send({ status_code: 200, message: "Auto mode and percentages updated successfully." }); + // Check if tanks exist + const matchingTanks = await Tank.find(filter); + console.log("Matching tanks:", matchingTanks); + + if (matchingTanks.length === 0) { + return reply.send({ status_code: 400, message: "No matching records found." }); + } + + // Define the update fields + const updateData = { + auto_min_percentage: String(auto_min_percentage || "20"), + auto_max_percentage: String(auto_max_percentage || "80"), + auto_mode_type: auto_mode_type || "default", + }; + + let result; + if (tankName && tankName !== "all") { + // Update only one tank if tankName is specified and not "all" + result = await Tank.updateOne(filter, { $set: updateData }); + } else { + // Update all tanks of the particular customer if tankName is "all" + result = await Tank.updateMany(filter, { $set: updateData }); + } + + console.log("Update result:", result); + + if (result.modifiedCount > 0) { + reply.send({ status_code: 200, message: "Auto mode and percentages updated successfully." }); + } else { + reply.send({ status_code: 400, message: "Values were already up-to-date." }); + } } catch (error) { - throw boom.boomify(error); + console.error(error); + reply.send({ status_code: 500, message: "Internal server error." }); } }; + + + //storing water level for every 15 minutes const getFormattedISTTime = () => {