diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index f838858b..b9a6f63a 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -11,7 +11,7 @@ const fastify = require("fastify")({ }, }); -const {SensorStock,Order,EstimationOrder,Iotprice, Install, ProfilePictureInstall, SensorQuotation,generateinstallationId,Store,WaterLeverSensor,MotorSwitchSenso,Insensors,generatequatationId, HardwareCart, ServiceCart, Sales} = require("../models/store"); +const {Repairorder,SensorStock,Order,EstimationOrder,Iotprice, Install, ProfilePictureInstall, SensorQuotation,generateinstallationId,Store,WaterLeverSensor,MotorSwitchSenso,Insensors,generatequatationId, HardwareCart, ServiceCart, Sales} = require("../models/store"); const { User,Counter, generateBookingId,resetCounter,generateCustomerId,ProfilePicture} = require('../models/User') @@ -2669,4 +2669,159 @@ exports.getallocatedsensorstouser= async (req, reply) => { console.error("Error fetching iots:", err); return reply.status(500).send({ error: "Internal server error" }); } +}; + + + +const crypto = require("crypto"); + + + +exports.replaceAndRepair = async (req, reply) => { + try { + const { customerId } = req.params; + const { items } = req.body; + + if (!customerId || !Array.isArray(items) || items.length === 0) { + return reply.code(400).send({ error: "customerId and items[] are required" }); + } + + const replacements = []; + + for (const item of items) { + const { type, hardwareId } = item; + console.log(`๐Ÿ” Processing ${type} with hardwareId: ${hardwareId}`); + + const existing = await Insensors.findOne({ hardwareId, type, customerId }); + + if (!existing) { + console.warn(`โš ๏ธ No existing ${type} found for hardwareId: ${hardwareId}`); + continue; + } + + // Mark existing as repair + await Insensors.updateOne( + { _id: existing._id }, + { $set: { status: "repair", outforrepairdate: new Date().toISOString() } } + ); + console.log(`๐Ÿ›  Marked old ${type} ${hardwareId} as repair`); + + // Find replacement + const replacement = await Insensors.findOne({ + type, + status: "available", + storeId: existing.storeId + }); + + if (!replacement) { + console.warn(`โš ๏ธ No available replacement found for ${type} at store ${existing.storeId}`); + continue; + } + + console.log(`โœ… Found replacement ${replacement.hardwareId} for ${type}`); + + const updateData = { + status: "blocked", + customerId: existing.customerId, + tankName: existing.tankName, + tankLocation: existing.tankLocation, + storeId: existing.storeId, + model: existing.model, + tankhardwareId: existing.tankhardwareId, + masterId: existing.masterId, + masterName: existing.masterName, + location: existing.location + }; + + await Insensors.updateOne({ _id: replacement._id }, { $set: updateData }); + console.log(`โœ… Updated replacement ${type} ${replacement.hardwareId} with previous config`); + + // === Cascade updates === + if (type === "master") { + const connectedSlaves = await Insensors.find({ + type: "slave", + connected_to: hardwareId, + customerId + }); + + for (const slave of connectedSlaves) { + await Insensors.updateOne( + { _id: slave._id }, + { $set: { connected_to: replacement.hardwareId } } + ); + console.log(`๐Ÿ” Updated slave ${slave.hardwareId} โ†’ connected_to: ${replacement.hardwareId}`); + } + } + + if (type === "slave") { + await Insensors.updateOne( + { _id: replacement._id }, + { $set: { connected_to: existing.connected_to } } + ); + console.log(`๐Ÿ” New slave ${replacement.hardwareId} โ†’ connected_to: ${existing.connected_to}`); + + const connectedSensors = await Insensors.find({ + type: "sensor", + connected_to: hardwareId, + customerId + }); + + for (const sensor of connectedSensors) { + await Insensors.updateOne( + { _id: sensor._id }, + { $set: { connected_to: replacement.hardwareId } } + ); + console.log(`๐Ÿ” Updated sensor ${sensor.hardwareId} โ†’ connected_to: ${replacement.hardwareId}`); + } + } + + if (type === "sensor") { + await Insensors.updateOne( + { _id: replacement._id }, + { $set: { connected_to: existing.connected_to } } + ); + console.log(`๐Ÿ” Sensor ${replacement.hardwareId} connected to same slave: ${existing.connected_to}`); + } + + // Log replacement + replacements.push({ + type, + oldHardwareId: hardwareId, + newHardwareId: replacement.hardwareId + }); + + console.log(`๐Ÿ“ฆ Logged replacement: ${type} ${hardwareId} โžœ ${replacement.hardwareId}`); + } + + console.log("๐Ÿงพ Final replacements:", replacements); + + // Create repair log + const packageId = "PKG-" + crypto.randomBytes(4).toString("hex").toUpperCase(); + const otp = Math.floor(100000 + Math.random() * 900000).toString(); + + const repairLog = new Repairorder({ + customerId, + packageId, + otp, + replacements, + createdAt: new Date() + }); + + await repairLog.save(); + console.log("โœ… RepairLog saved"); + + return reply.send({ + status_code: 200, + message: "Repaired and replaced successfully", + data: { + packageId, + otp, + replacements, + createdAt: repairLog.createdAt + } + }); + } catch (err) { + console.error("โŒ Error during replacement:", err); + return reply.code(500).send({ error: "Internal Server Error" }); + } }; \ No newline at end of file diff --git a/src/models/store.js b/src/models/store.js index 6d9ce7ce..4d71e225 100644 --- a/src/models/store.js +++ b/src/models/store.js @@ -1077,6 +1077,31 @@ const materialRecievedPicturesSchema = new Schema({ } }); +const RepairorderSchema = new mongoose.Schema({ + customerId: { type: String, required: true }, + packageId: { type: String, required: true }, + otp: { type: String, required: true }, + replacements: [ + { + type: { + type: String, + enum: ["master", "slave", "sensor"], + required: true + }, + oldHardwareId: { type: String, required: true }, + newHardwareId: { type: String, required: true } + } + ], + createdAt: { type: Date, default: Date.now } +}); + + + + +const Repairorder = mongoose.model('Repairorder', RepairorderSchema); + + + const Iotprice = mongoose.model('Iotprice', iotpriceSchema); const Insensors = mongoose.model('Insensors', insensorsSchema); const MasterSlaveData = mongoose.model('MasterSlaveData', masterSlaveDataSchema); @@ -1106,4 +1131,4 @@ const Iotprice = mongoose.model('Iotprice', iotpriceSchema); - module.exports = {Support,MaterialRecievedPictures,PlumbingWorkPictures,ElectrictyWorkPictures,MasterSlaveData,SensorStock,Order,EstimationOrder,Iotprice,Sales, Install,Survey, ProfilePictureInstall, SensorQuotation,generateinstallationId,Store,ProfilePictureStore,WaterLeverSensor,MotorSwitchSensor,Insensors,generatequatationId, HardwareCart, ServiceCart}; + module.exports = {Repairorder,Support,MaterialRecievedPictures,PlumbingWorkPictures,ElectrictyWorkPictures,MasterSlaveData,SensorStock,Order,EstimationOrder,Iotprice,Sales, Install,Survey, ProfilePictureInstall, SensorQuotation,generateinstallationId,Store,ProfilePictureStore,WaterLeverSensor,MotorSwitchSensor,Insensors,generatequatationId, HardwareCart, ServiceCart}; diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index 59881457..b4d8b85b 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -2012,5 +2012,75 @@ fastify.get("/api/getallocatedsensors/:customerId", { handler: storeController.getallocatedsensorstouser, }); + + +fastify.post("/api/repair/replace/:customerId", { + schema: { + tags: ["Install"], + summary: "Mark old sensors as repair and replace them with available ones", + description: "This API replaces sensors (master/slave/sensor) with available ones and logs the repair action", + params: { + type: "object", + properties: { + customerId: { type: "string", description: "Customer ID" }, + }, + required: ["customerId"] + }, + body: { + type: "object", + properties: { + items: { + type: "array", + items: { + type: "object", + properties: { + type: { type: "string", enum: ["master", "slave", "sensor"] }, + hardwareId: { type: "string" } + }, + required: ["type", "hardwareId"] + } + } + }, + required: ["items"] + }, + response: { + 200: { + description: "Successful replacement and repair log creation", + type: "object", + properties: { + status_code: { type: "integer" }, + message: { type: "string" }, + data: { + type: "object", + properties: { + packageId: { type: "string" }, + otp: { type: "string" }, + replacements: { + type: "array", + items: { + type: "object", + properties: { + type: { type: "string" }, + oldHardwareId: { type: "string" }, + newHardwareId: { type: "string" }, + } + } + }, + createdAt: { type: "string" } + } + } + } + } + }, + security: [ + { + basicAuth: [] + } + ] + }, + handler: storeController.replaceAndRepair + }); + + next(); };