ashok 4 months ago
commit 735afa79ea

@ -1,6 +1,6 @@
//Get the data models //Get the data models
const { Supplier, DeliveryBoy, profilePictureSupplier } = require("../models/supplier"); const { Supplier, DeliveryBoy, profilePictureSupplier } = require("../models/supplier");
const { FriendRequest } = require("../models/supplier"); const { FriendRequest,RequestedBooking } = require("../models/supplier");
const { Tanker,Tankerbooking } = require("../models/tankers"); const { Tanker,Tankerbooking } = require("../models/tankers");
const { ProfilePicture, User } = require("../models/User"); const { ProfilePicture, User } = require("../models/User");
const supplierController = require("../controllers/supplierController"); const supplierController = require("../controllers/supplierController");
@ -951,7 +951,11 @@ exports.getSuppliers = async (req, reply) => {
date, date,
time, time,
price_from, price_from,
price_to price_to,
radius_from, // even if sent we will not apply now
radius_to,
rating_from,
rating_to
} = req.body; } = req.body;
const parseCapacity = (value) => parseFloat((value || "0").toString().replace(/,/g, "")); const parseCapacity = (value) => parseFloat((value || "0").toString().replace(/,/g, ""));
@ -973,22 +977,30 @@ exports.getSuppliers = async (req, reply) => {
tankerBookings.map(booking => `${booking.supplierId}_${booking.tankerName}`) tankerBookings.map(booking => `${booking.supplierId}_${booking.tankerName}`)
); );
// 1⃣ Filter tankers by typeofwater first // 🟢 Initial tanker query condition
let tankers = await Tanker.find({ typeofwater: type_of_water }); const tankerQuery = {};
// 2⃣ Filter by price range if (type_of_water && type_of_water.trim() !== "") {
tankers = tankers.filter(tanker => { tankerQuery.typeofwater = type_of_water;
const tankerPrice = parsePrice(tanker.price); }
return tankerPrice >= priceFrom && tankerPrice <= priceTo;
});
// 3⃣ Exclude booked tankers let tankers = await Tanker.find(tankerQuery);
// 🟢 Apply price filter only if both price_from and price_to are given (not empty)
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 => { tankers = tankers.filter(tanker => {
const key = `${tanker.supplierId}_${tanker.tankerName}`; const key = `${tanker.supplierId}_${tanker.tankerName}`;
return !bookedTankerSet.has(key); return !bookedTankerSet.has(key);
}); });
// 4⃣ Group tankers by supplierId // 🟢 Group tankers by supplierId
const supplierTankerMap = {}; const supplierTankerMap = {};
for (let tanker of tankers) { for (let tanker of tankers) {
if (!supplierTankerMap[tanker.supplierId]) { if (!supplierTankerMap[tanker.supplierId]) {
@ -997,17 +1009,22 @@ exports.getSuppliers = async (req, reply) => {
supplierTankerMap[tanker.supplierId].push(tanker); supplierTankerMap[tanker.supplierId].push(tanker);
} }
// 5⃣ Aggregate supplier capacities
const qualifiedSuppliers = []; const qualifiedSuppliers = [];
for (let [supplierId, supplierTankers] of Object.entries(supplierTankerMap)) { for (let [supplierId, supplierTankers] of Object.entries(supplierTankerMap)) {
const totalAvailableCapacity = supplierTankers.reduce( const totalAvailableCapacity = supplierTankers.reduce(
(sum, t) => sum + parseCapacity(t.capacity), (sum, t) => sum + parseCapacity(t.capacity),
0 0
); );
if (totalAvailableCapacity >= totalRequiredCapacity) { // 🟢 Apply capacity filtering only if both are given
qualifiedSuppliers.push({ supplierId, tankers: supplierTankers }); if (requestedCapacity > 0 && requestedQuantity > 0) {
if (totalAvailableCapacity < totalRequiredCapacity) {
continue;
}
} }
qualifiedSuppliers.push({ supplierId, tankers: supplierTankers });
} }
const suppliers = []; const suppliers = [];
@ -1049,6 +1066,53 @@ exports.getSuppliers = async (req, reply) => {
exports.createRequestedBooking = async (req, reply) => {
const {
customerId,
type_of_water,
capacity,
quantity,
date,
time,
requested_suppliers
} = req.body;
const parseCapacity = (value) => parseFloat((value || "0").toString().replace(/,/g, ""));
const requestedCapacity = parseCapacity(capacity);
const requestedQuantity = parseInt(quantity || "0");
const totalRequiredCapacity = requestedCapacity * requestedQuantity;
try {
const requestedBooking = new RequestedBooking({
customerId,
type_of_water,
capacity,
quantity,
total_required_capacity: totalRequiredCapacity,
date,
time,
requested_suppliers, // ✅ already contains supplierId, quoted_amount, custom_field
status: "pending"
});
await requestedBooking.save();
reply.send({
status_code: 200,
message: "Requested booking created successfully",
data: requestedBooking
});
} catch (err) {
console.error(err);
reply.send({
status_code: 500,
message: "Something went wrong while saving",
error: err.message
});
}
}

@ -155,12 +155,34 @@ const supplierSchema = new mongoose.Schema(
}); });
const requestedSupplierSchema = new mongoose.Schema({
supplierId: String,
quoted_amount: Number,
custom_field: String // ✅ New field added here
}, { _id: false });
const requestedBookingSchema = new mongoose.Schema({
customerId: { type: String, required: true },
type_of_water: String,
capacity: String,
quantity: String,
total_required_capacity: Number,
date: String,
time: String,
requested_suppliers: [requestedSupplierSchema],
status: { type: String, default: "pending" },
}, { timestamps: true });
const RequestedBooking = mongoose.model('RequestedBooking', requestedBookingSchema);
const Supplier = mongoose.model("Supplier", supplierSchema); const Supplier = mongoose.model("Supplier", supplierSchema);
//const DeliveryAgent = mongoose.model("DeliveryAgent", deliveryAgent); //const DeliveryAgent = mongoose.model("DeliveryAgent", deliveryAgent);
const FriendRequest = mongoose.model('FriendRequest', friendRequestSchema); const FriendRequest = mongoose.model('FriendRequest', friendRequestSchema);
const DeliveryBoy = mongoose.model('DeliveryBoy', deliveryBoySchema); const DeliveryBoy = mongoose.model('DeliveryBoy', deliveryBoySchema);
const profilePictureSupplier = mongoose.model('ProfilePictureSupplier', profilePictureSupplierSchema); const profilePictureSupplier = mongoose.model('ProfilePictureSupplier', profilePictureSupplierSchema);
module.exports = { Supplier, generateSupplierId, FriendRequest,DeliveryBoy, profilePictureSupplier} module.exports = { Supplier, generateSupplierId, FriendRequest,DeliveryBoy, profilePictureSupplier,RequestedBooking}

@ -52,6 +52,43 @@ module.exports = function (fastify, opts, next) {
}); });
fastify.post("/api/requestedbookings", {
schema: {
tags: ["Supplier-Data"],
description: "API to create requested bookings and send to suppliers",
summary: "Create requested booking",
body: {
type: "object",
required: ["customerId", "type_of_water", "capacity", "quantity", "date", "time", "requested_suppliers"],
properties: {
customerId: { type: "string" },
type_of_water: { type: "string" },
capacity: { type: "string" },
quantity: { type: "string" },
date: { type: "string" },
time: { type: "string" },
requested_suppliers: {
type: "array",
items: {
type: "object",
required: ["supplierId", "quoted_amount", "custom_field"],
properties: {
supplierId: { type: "string" },
quoted_amount: { type: "number" },
custom_field: { type: "string" } // ✅ New field
}
}
}
}
},
security: [{ basicAuth: [] }]
},
handler: validationHandler.createRequestedBooking
});
fastify.get("/api/connectedSuppliers/:customerId", { fastify.get("/api/connectedSuppliers/:customerId", {
schema: { schema: {
tags: ["Supplier-Data"], tags: ["Supplier-Data"],

Loading…
Cancel
Save