diff --git a/src/handlers/supplierHandler.js b/src/handlers/supplierHandler.js index c6e5832f..4a2a3c2f 100644 --- a/src/handlers/supplierHandler.js +++ b/src/handlers/supplierHandler.js @@ -973,22 +973,30 @@ exports.getSuppliers = async (req, reply) => { tankerBookings.map(booking => `${booking.supplierId}_${booking.tankerName}`) ); - // 1️⃣ Filter tankers by typeofwater first - let tankers = await Tanker.find({ typeofwater: type_of_water }); + // 🟢 Initial tanker query condition + const tankerQuery = {}; - // 2️⃣ Filter by price range - tankers = tankers.filter(tanker => { - const tankerPrice = parsePrice(tanker.price); - return tankerPrice >= priceFrom && tankerPrice <= priceTo; - }); + if (type_of_water && type_of_water.trim() !== "") { + tankerQuery.typeofwater = type_of_water; + } - // 3️⃣ Exclude booked tankers + let tankers = await Tanker.find(tankerQuery); + + // 🟢 Apply price filter only if both price_from and price_to are given + if (price_from && price_to) { + tankers = tankers.filter(tanker => { + const tankerPrice = parsePrice(tanker.price); + return tankerPrice >= priceFrom && tankerPrice <= priceTo; + }); + } + + // 🟢 Exclude booked tankers tankers = tankers.filter(tanker => { const key = `${tanker.supplierId}_${tanker.tankerName}`; return !bookedTankerSet.has(key); }); - // 4️⃣ Group tankers by supplierId + // 🟢 Group tankers by supplierId const supplierTankerMap = {}; for (let tanker of tankers) { if (!supplierTankerMap[tanker.supplierId]) { @@ -997,17 +1005,23 @@ exports.getSuppliers = async (req, reply) => { supplierTankerMap[tanker.supplierId].push(tanker); } - // 5️⃣ Aggregate supplier capacities const qualifiedSuppliers = []; + for (let [supplierId, supplierTankers] of Object.entries(supplierTankerMap)) { + const totalAvailableCapacity = supplierTankers.reduce( (sum, t) => sum + parseCapacity(t.capacity), 0 ); - if (totalAvailableCapacity >= totalRequiredCapacity) { - qualifiedSuppliers.push({ supplierId, tankers: supplierTankers }); + // 🟢 Capacity filtering: apply only if both capacity & quantity are given + if (requestedCapacity > 0 && requestedQuantity > 0) { + if (totalAvailableCapacity < totalRequiredCapacity) { + continue; // skip this supplier + } } + + qualifiedSuppliers.push({ supplierId, tankers: supplierTankers }); } const suppliers = []; diff --git a/src/routes/supplierRoute.js b/src/routes/supplierRoute.js index 71e9fded..2f9bcab1 100644 --- a/src/routes/supplierRoute.js +++ b/src/routes/supplierRoute.js @@ -52,6 +52,10 @@ module.exports = function (fastify, opts, next) { }); + + + + fastify.get("/api/connectedSuppliers/:customerId", { schema: { tags: ["Supplier-Data"],