diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index 097253a1..986160d0 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -2644,7 +2644,7 @@ exports.getOrdersByInstallationId = async (req, reply) => { return reply.status(400).send({ error: "installationId is required" }); } - // Fetch orders with the matching installationId + // Step 1: Fetch orders by installationId const orders = await Order.find({ installationId }); if (!orders.length) { @@ -2655,53 +2655,33 @@ exports.getOrdersByInstallationId = async (req, reply) => { }); } - const uniqueCustomersMap = new Map(); + const ordersWithActiveMasters = []; - // Build unique customerId-based map + // Step 2: Process each order for (const order of orders) { - if (!uniqueCustomersMap.has(order.customerId)) { - uniqueCustomersMap.set(order.customerId, order); - } - } - - // Only keep one order per customerId - let uniqueOrders = Array.from(uniqueCustomersMap.values()); - - // ✅ Filter: keep only orders where work_status is 'active' - uniqueOrders = uniqueOrders.filter(order => order.work_status === 'active'); - - // If no orders left after filtering, return empty list - if (!uniqueOrders.length) { - return reply.send({ - status_code: 200, - message: "No active orders found for this installation", - data: [], - }); - } + // Filter master_connections to keep only those where work_status is 'active' or empty/null + const activeMasters = (order.master_connections || []).filter(mc => + mc.work_status === 'active' || mc.work_status === '' || mc.work_status == null + ); - // Enrich with customer and sensor info - const ordersWithDetails = await Promise.all( - uniqueOrders.map(async (order) => { + if (activeMasters.length) { + // Fetch customer details const customer = await User.findOne({ customerId: order.customerId }).lean(); - const allocatedSensors = await Insensors.find({ - storeId: order.storeId, - customerId: order.customerId, - status: "blocked", - }).lean(); - - return { + // Build response object + ordersWithActiveMasters.push({ ...order.toObject(), + master_connections: activeMasters, // only active master_connections customer: customer || null, - allocated_sensors: allocatedSensors, - }; - }) - ); + }); + } + } + // Step 3: Return response return reply.send({ status_code: 200, - message: "Active orders fetched successfully", - data: ordersWithDetails, + message: "Orders with active master connections fetched successfully", + data: ordersWithActiveMasters, }); } catch (err) { @@ -2711,6 +2691,10 @@ exports.getOrdersByInstallationId = async (req, reply) => { }; + + + + exports.getPendingOrdersByInstallationAndTeamMember = async (req, reply) => { try { const { installationId, teamMemberId } = req.params;