ashok 5 months ago
commit c65e152ccd

@ -2515,34 +2515,44 @@ exports.getOrdersByInstallationId = async (req, reply) => {
return reply.status(400).send({ error: "installationId is required" }); return reply.status(400).send({ error: "installationId is required" });
} }
// Fetch orders with the matching installationId // Fetch all orders by installationId
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 installation", message: "No orders found for this installation",
data: [], data: {
customers: [],
orders: []
}
}); });
} }
// Fetch customer details & allocated sensors for each order // Get unique customerIds from orders
const ordersWithDetails = await Promise.all( const uniqueCustomerIds = [...new Set(orders.map(order => order.customerId))];
orders.map(async (order) => {
// Fetch customer details
const customer = await User.findOne({ customerId: order.customerId }).lean();
// Fetch allocated sensors for this customer // Fetch all customers in a single query
const customers = await User.find({ customerId: { $in: uniqueCustomerIds } }).lean();
// Map customerId -> customer object
const customerMap = {};
customers.forEach(c => {
customerMap[c.customerId] = c;
});
// For each order, attach allocated sensors only
const ordersWithSensors = await Promise.all(
orders.map(async (order) => {
const allocatedSensors = await Insensors.find({ const allocatedSensors = await Insensors.find({
storeId: order.storeId, storeId: order.storeId,
customerId: order.customerId, // Match only sensors allocated to this customer customerId: order.customerId,
status: "blocked", // Only fetch sensors that are allocated (blocked) status: "blocked"
}).lean(); }).lean();
return { return {
...order.toObject(), ...order.toObject(),
customer: customer || null, // Include customer details or null if not found allocated_sensors: allocatedSensors
allocated_sensors: allocatedSensors, // List of allocated sensors
}; };
}) })
); );
@ -2550,8 +2560,12 @@ exports.getOrdersByInstallationId = async (req, reply) => {
return reply.send({ return reply.send({
status_code: 200, status_code: 200,
message: "Orders fetched successfully", message: "Orders fetched successfully",
data: ordersWithDetails, data: {
customers,
orders: ordersWithSensors
}
}); });
} 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" });

Loading…
Cancel
Save