From d7cb4f45b70b7ad5a787f3c9b5b2acdb3297937b Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Tue, 20 May 2025 15:26:51 +0530 Subject: [PATCH] changes --- src/controllers/storeController.js | 42 ++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index 586dbfaf..989a6b31 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -2515,34 +2515,44 @@ exports.getOrdersByInstallationId = async (req, reply) => { 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 }); if (!orders.length) { return reply.send({ status_code: 200, message: "No orders found for this installation", - data: [], + data: { + customers: [], + orders: [] + } }); } - // Fetch customer details & allocated sensors for each order - const ordersWithDetails = await Promise.all( - orders.map(async (order) => { - // Fetch customer details - const customer = await User.findOne({ customerId: order.customerId }).lean(); + // Get unique customerIds from orders + const uniqueCustomerIds = [...new Set(orders.map(order => order.customerId))]; - // 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({ - storeId: order.storeId, - customerId: order.customerId, // Match only sensors allocated to this customer - status: "blocked", // Only fetch sensors that are allocated (blocked) + storeId: order.storeId, + customerId: order.customerId, + status: "blocked" }).lean(); return { ...order.toObject(), - customer: customer || null, // Include customer details or null if not found - allocated_sensors: allocatedSensors, // List of allocated sensors + allocated_sensors: allocatedSensors }; }) ); @@ -2550,8 +2560,12 @@ exports.getOrdersByInstallationId = async (req, reply) => { return reply.send({ status_code: 200, message: "Orders fetched successfully", - data: ordersWithDetails, + data: { + customers, + orders: ordersWithSensors + } }); + } catch (err) { console.error("Error fetching orders:", err); return reply.status(500).send({ error: "Internal server error" });