diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index e93b00fe..af81da60 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -497,6 +497,15 @@ exports.addStore = async (request, reply) => { return result.seq; }; + const generatewaterlevelslavesensorId = async () => { + const result = await Counter.findOneAndUpdate( + { _id: 'waterlevelslavesensor_id' }, + { $inc: { seq: 1 } }, + { upsert: true, new: true } + ); + return result.seq; + }; + const moment = require('moment'); exports.createwaterlevelSensor = async (req, reply) => { try { @@ -560,4 +569,49 @@ exports.addStore = async (request, reply) => { throw boom.boomify(err); } }; - \ No newline at end of file + + + exports.addSlave = async (req, reply) => { + try { + const hardwareId = req.params.hardwareId; + const { tankhardwareId, type, indate, hardwareId_company } = req.body; + + // Find the main hardware by hardwareId + const mainHardware = await WaterLeverSensor.findOne({ hardwareId }); + + if (!mainHardware) { + reply.code(404).send({ message: "Main hardware not found" }); + return; + } + + // Check if the slave's hardwareId already exists + const existingSlave = mainHardware.slaves.tankhardware.find(slave => slave.tankhardwareId === tankhardwareId); + + if (existingSlave) { + reply.code(400).send({ message: "Slave hardware ID already exists for this main hardware" }); + return; + } + var slave_seq_id = await generatewaterlevelslavesensorId(); + const date = moment().format('MM-DD'); + const prefix = 'AS-' + date + '--SLAOV1-'; + var slaveId = `${prefix}${slave_seq_id}`; + // Create new slave + const newSlave = { + tankhardwareId, + slaveId: slaveId, + type, + indate, + hardwareId_company + }; + + // Add the new slave to the main hardware's slaves array + mainHardware.slaves.tankhardware.push(newSlave); + + // Save the updated main hardware + const updatedHardware = await mainHardware.save(); + + reply.code(200).send(updatedHardware); + } catch (err) { + reply.code(500).send(err); + } +}; diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index 584d8faf..ed56109c 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -213,5 +213,35 @@ fastify.get("/api/getHardware/:storeId", { }); + +fastify.post("/api/addSlave/:hardwareId", { + schema: { + description: "This is for adding a slave to the water level sensor", + tags: ["Store-Data"], + summary: "Add a slave to the water level sensor", + params: { + required: ["hardwareId"], + type: "object", + properties: { + hardwareId: { + type: "string", + description: "Main hardware ID", + }, + }, + }, + body: { + type: "object", + properties: { + tankhardwareId: { type: "string" }, + type: { type: "string" }, + indate: { type: "string" }, + hardwareId_company: { type: "string" } + }, + }, + }, + handler: storeController.addSlave, +}); + + next(); };