From d588dee0a27fc341d0d2b004081773e7c16fdd26 Mon Sep 17 00:00:00 2001 From: Varun Date: Wed, 10 Sep 2025 17:12:31 +0530 Subject: [PATCH] get supplier details with get recurring plans of particular customer --- src/controllers/userController.js | 65 +++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/src/controllers/userController.js b/src/controllers/userController.js index 6e6e79ec..bcd8fec1 100644 --- a/src/controllers/userController.js +++ b/src/controllers/userController.js @@ -1645,6 +1645,11 @@ exports.getuserRequestbookingsforplansforsupplier = async (req, reply) => { } }; + +// Assuming you have these models imported somewhere above: +// const RecurringRequestedBooking = require("..."); +// const Supplier = require("..."); + exports.getuserRequestbookingsforplansforcustomer = async (req, reply) => { try { const { customerId } = req.params; @@ -1656,27 +1661,71 @@ exports.getuserRequestbookingsforplansforcustomer = async (req, reply) => { }); } - // 1) Find all bookings that include this supplier - const bookings = await RecurringRequestedBooking.find({ - customerId: customerId, - }) + // 1) Get bookings + const bookings = await RecurringRequestedBooking.find({ customerId }) .sort({ createdAt: -1 }) .lean(); - // 2) For each booking, expose only this supplier's subdocument - + if (!bookings.length) { + return reply.send({ + status_code: 200, + message: `Orders for customer ${customerId} fetched successfully`, + data: [], + }); + } + + // 2) Collect unique supplierIds from requested_suppliers + const supplierIdSet = new Set(); + for (const b of bookings) { + const rs = Array.isArray(b.requested_suppliers) ? b.requested_suppliers : []; + for (const s of rs) { + if (s && typeof s.supplierId === "string" && s.supplierId.trim() && s.supplierId !== "string") { + supplierIdSet.add(s.supplierId.trim()); + } + } + } + const supplierIds = Array.from(supplierIdSet); + + // 3) Fetch suppliers and index by supplierId + const suppliers = supplierIds.length + ? await Supplier.find({ supplierId: { $in: supplierIds } }) + .select("-__v") // tweak projection as you like + .lean() + : []; + + const supplierById = new Map(); + for (const s of suppliers) { + // Key is Supplier.supplierId (string), not _id + supplierById.set(s.supplierId, s); + } + + // 4) Attach supplier details into each requested_suppliers entry + const data = bookings.map((b) => { + const rs = Array.isArray(b.requested_suppliers) ? b.requested_suppliers : []; + const enriched = rs.map((item) => ({ + ...item, + supplier: supplierById.get(item?.supplierId) || null, // attach or null if not found + })); + return { + ...b, + requested_suppliers: enriched, + }; + }); - return reply.send({ status_code: 200, message: `Orders for customer ${customerId} fetched successfully`, - data:bookings, + data, }); } catch (err) { console.error(err); throw boom.boomify(err); } }; + + + + const mongoose = require('mongoose');