added repair to store

master^2
Varun 3 months ago
parent 3cc6ae44fd
commit 9d59f0c266

@ -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') const { User,Counter, generateBookingId,resetCounter,generateCustomerId,ProfilePicture} = require('../models/User')
@ -2670,3 +2670,158 @@ exports.getallocatedsensorstouser= async (req, reply) => {
return reply.status(500).send({ error: "Internal server error" }); 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" });
}
};

@ -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 Iotprice = mongoose.model('Iotprice', iotpriceSchema);
const Insensors = mongoose.model('Insensors', insensorsSchema); const Insensors = mongoose.model('Insensors', insensorsSchema);
const MasterSlaveData = mongoose.model('MasterSlaveData', masterSlaveDataSchema); 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};

@ -2012,5 +2012,75 @@ fastify.get("/api/getallocatedsensors/:customerId", {
handler: storeController.getallocatedsensorstouser, 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(); next();
}; };

Loading…
Cancel
Save