Bhaskar 9 months ago
commit 870e531dc9

@ -1173,12 +1173,69 @@ exports.installmotorswitch = async (request, reply) => {
}; };
exports.generateHardwareMasterId = async (req, reply) => {
try {
const storeId = req.params.storeId
const { from, to, type, quantity } = req.body;
const sensorType = type.toLowerCase();
const fromInt = parseInt(from, 10);
const toInt = parseInt(to, 10);
if (isNaN(fromInt) || isNaN(toInt) || fromInt > toInt) {
return reply.code(400).send({ message: 'Invalid from/to values' });
}
// Fetch pending sensors of the given type and storeId whose hardwareId is null
const pendingSensors = await Insensors.find({ status: 'pending', type: sensorType, storeId, hardwareId: null });
if (!pendingSensors.length) {
return reply.code(404).send({ message: 'No pending sensors found for the given type and storeId' });
}
if (quantity > pendingSensors.length) {
return reply.code(400).send({ message: `Available quantity is less than requested: ${pendingSensors.length} available.` });
}
let hardwareIdSequence = fromInt;
const date = moment().format('MM-DD');
for (let i = 0; i < quantity && i < pendingSensors.length; i++) {
let sensor = pendingSensors[i];
if (hardwareIdSequence > toInt) break;
sensor.hardwareId = hardwareIdSequence.toString().padStart(8, '0');
let mater_seq_id;
if (sensorType === 'master') {
mater_seq_id = await generatewaterlevelsensorId();
sensor.masterId = `AS${date}MALOV1${mater_seq_id}`;
} else if (sensorType === 'slave') {
mater_seq_id = await generatewaterlevelslavesensorId();
sensor.masterId = `AS${date}SLLOV1${mater_seq_id}`;
} else if (sensorType === 'sensor') {
mater_seq_id = await generatewaterlevelheightsensorId();
sensor.masterId = `AS${date}SELOV1${mater_seq_id}`;
}
await sensor.save(); // Save updated sensor in the database
hardwareIdSequence++;
}
return reply.code(200).send({ message: 'HardwareId and MasterId assigned successfully' });
} catch (error) {
console.error('Error generating IDs:', error);
return reply.code(500).send({ message: 'Internal Server Error' });
}
};
exports.updateSensorById = async (req, reply) => { exports.updateSensorById = async (req, reply) => {
try { try {
const { _id } = req.params; const { _id } = req.params;
let updateData = req.body; let updateData = req.body;
const allowedFields = ["model", "type", "hardwareId_company", "hardwareId"]; const allowedFields = ["model", "type", "hardwareId_company", "hardwareId","masterId"];
// Filter out unwanted fields and convert type to lowercase if present // Filter out unwanted fields and convert type to lowercase if present
const filteredUpdateData = Object.keys(updateData) const filteredUpdateData = Object.keys(updateData)
@ -1188,23 +1245,6 @@ exports.updateSensorById = async (req, reply) => {
return obj; return obj;
}, {}); }, {});
// Generate masterId if type is provided
if (filteredUpdateData.type) {
let mater_seq_id;
const date = moment().format("MM-DD");
if (filteredUpdateData.type === "master") {
mater_seq_id = await generatewaterlevelsensorId();
filteredUpdateData.masterId = `AS${date}MALOV1${mater_seq_id}`;
} else if (filteredUpdateData.type === "slave") {
mater_seq_id = await generatewaterlevelslavesensorId();
filteredUpdateData.masterId = `AS${date}SLLOV1${mater_seq_id}`;
} else if (filteredUpdateData.type === "sensor") {
mater_seq_id = await generatewaterlevelheightsensorId();
filteredUpdateData.masterId = `AS${date}SELOV1${mater_seq_id}`;
}
}
const updatedSensor = await Insensors.findByIdAndUpdate(_id, filteredUpdateData, { new: true }); const updatedSensor = await Insensors.findByIdAndUpdate(_id, filteredUpdateData, { new: true });
if (!updatedSensor) { if (!updatedSensor) {
@ -2300,41 +2340,37 @@ exports.getOrdersByInstallationId = async (req, reply) => {
const { installationId } = req.params; const { installationId } = req.params;
if (!installationId) { if (!installationId) {
return reply.status(400).send({ error: "installationId is required" }); return reply.status(400).send({ error: "storeId is required" });
} }
// Fetch orders with the matching storeId
const orders = await Order.find({ installationId }); const orders = await Order.find({ installationId });
if (!orders.length) { if (!orders.length) {
return reply.send({ return reply.send({
status_code: 200, status_code: 200,
message: "No orders found for this installationId", message: "No orders found for this store",
data: [], data: [],
}); });
} }
// Fetch customer details & allocated sensors for each order
const ordersWithDetails = await Promise.all( const ordersWithDetails = await Promise.all(
orders.map(async (order) => { orders.map(async (order) => {
// Fetch customer details
const customer = await User.findOne({ customerId: order.customerId }).lean(); const customer = await User.findOne({ customerId: order.customerId }).lean();
console.log("Fetching allocated sensors for:", { // Fetch allocated sensors for this customer
storeId: order.storeId,
customerId: order.customerId,
status: "blocked",
});
const allocatedSensors = await Insensors.find({ const allocatedSensors = await Insensors.find({
storeId: order.storeId, installationId,
customerId: order.customerId, customerId: order.customerId, // Match only sensors allocated to this customer
status: "blocked", status: "blocked", // Only fetch sensors that are allocated (blocked)
}).lean(); }).lean();
console.log("✅ Found Sensors:", allocatedSensors);
return { return {
...order.toObject(), ...order.toObject(),
customer: customer || null, customer: customer || null, // Include customer details or null if not found
allocated_sensors: allocatedSensors, // Now it should return the correct sensors allocated_sensors: allocatedSensors, // List of allocated sensors
}; };
}) })
); );
@ -2345,12 +2381,11 @@ exports.getOrdersByInstallationId = async (req, reply) => {
data: ordersWithDetails, data: ordersWithDetails,
}); });
} catch (err) { } catch (err) {
console.error("Error fetching orders:", err); console.error("Error fetching orders:", err);
return reply.status(500).send({ error: "Internal server error" }); return reply.status(500).send({ error: "Internal server error" });
} }
}; };
exports.getallocatedsensorstouser= async (req, reply) => { exports.getallocatedsensorstouser= async (req, reply) => {
try { try {
const { customerId } = req.params; const { customerId } = req.params;

@ -4542,7 +4542,7 @@ exports.IotDeviceforstandalonedevice = async (req, reply) => {
} }
const status = req.body.Motor_status; const status = req.body.Motor_status;
console.log(status,"status")
// Find the tank that contains the specified motor_id in its inputConnections // Find the tank that contains the specified motor_id in its inputConnections
const tank = await Tank.findOne({ "connections.inputConnections.motor_id": hardwareId }); const tank = await Tank.findOne({ "connections.inputConnections.motor_id": hardwareId });

@ -1128,6 +1128,35 @@ fastify.delete("/api/deleteSensorById/:_id", {
handler: storeController.deleteSensorById, handler: storeController.deleteSensorById,
}); });
fastify.post('/api/generateHardwareMasterId/:storeId', {
schema: {
description: 'Generate hardwareId and masterId dynamically for pending sensors',
tags: ['Store-Data'],
summary: 'Assign hardwareId and masterId to pending sensors dynamically',
params: {
required: ["storeId"],
type: "object",
properties: {
storeId: {
type: "string",
description: "storeId",
},
},
},
body: {
type: 'object',
required: ['from', 'to', 'type'],
properties: {
from: { type: 'string', description: 'Starting hardwareId (e.g., 00000020)' },
to: { type: 'string', description: 'Ending hardwareId (e.g., 00000030)' },
type: { type: 'string', description: 'Type of sensor' },
quantity: { type: 'string' },
},
},
},
handler: storeController.generateHardwareMasterId,
});
fastify.post("/api/updateSensorById/:_id", { fastify.post("/api/updateSensorById/:_id", {
schema: { schema: {
@ -1149,7 +1178,7 @@ fastify.post("/api/updateSensorById/:_id", {
properties: { properties: {
model: { type: "string", description: "Model of the sensor" }, model: { type: "string", description: "Model of the sensor" },
type: { type: "string", description: "Type of sensor" }, type: { type: "string", description: "Type of sensor" },
masterId: { type: "string"},
hardwareId_company: { type: "string", description: "Company name of hardware ID" }, hardwareId_company: { type: "string", description: "Company name of hardware ID" },
hardwareId: { type: "string", nullable: true, description: "Hardware ID (if applicable)" }, hardwareId: { type: "string", nullable: true, description: "Hardware ID (if applicable)" },
@ -1771,7 +1800,7 @@ fastify.post("/api/acceptquotation/:quotationId", {
}, },
required: ["action"], required: ["action"],
}, },
security: [ security: [
{ {
basicAuth: [], basicAuth: [],
}, },

Loading…
Cancel
Save