Bhaskar 3 months ago
commit b726ccd0c5

@ -249,76 +249,49 @@ exports.loginDeliveryBoy = async (req) => {
}; };
exports.acceptRequestedBooking = async (req, reply) => {
const { supplierId } = req.params;
const { action, _id } = req.body;
if (action !== 'accept') {
return reply.code(400).send({ message: "Invalid action. Only 'accept' is allowed." });
}
const mongoose = require('mongoose');
exports.respondToRequestedBooking = async (req, reply) => {
const { _id } = req.params;
const { action, supplierId } = req.body;
try { if (!mongoose.Types.ObjectId.isValid(_id)) {
const requestedBooking = await RequestedBooking.findOne({ return reply.code(400).send({ message: "Invalid requested booking ID" });
_id, }
'requested_suppliers.supplierId': supplierId,
status: 'pending'
});
if (!requestedBooking) { if (!["accept", "reject"].includes(action)) {
return reply.code(404).send({ message: "No matching pending request for given ID and supplier" }); return reply.code(400).send({ message: "Action must be 'accept' or 'reject'" });
} }
requestedBooking.status = 'accepted'; try {
await requestedBooking.save(); const booking = await RequestedBooking.findById(_id);
const customer = await User.findOne({ customerId: requestedBooking.customerId }).lean(); if (!booking) {
if (!customer) return reply.code(404).send({ message: "Customer not found" }); return reply.code(404).send({ message: "Requested booking not found" });
}
const supplier = await Supplier.findOne({ supplierId }).lean(); const supplierEntry = booking.requested_suppliers.find(s => s.supplierId === supplierId);
if (!supplier) return reply.code(404).send({ message: "Supplier not found" });
const matchedSupplier = requestedBooking.requested_suppliers.find(s => s.supplierId === supplierId); if (!supplierEntry) {
if (!matchedSupplier || !matchedSupplier.quoted_amount) { return reply.code(404).send({ message: "Supplier not found in this booking" });
return reply.code(400).send({ message: "Quoted amount missing for this supplier" });
} }
const newBooking = new Tankerbooking({ // Update custom_field (status) for that supplier
customerId: customer.customerId, supplierEntry.status = action === "accept" ? "accepted_by_supplier" : "rejected_by_supplier";
customerName: customer.profile.firstName,
customerPhone: customer.phone,
address: customer.address1,
latitude: customer.latitude,
longitude: customer.longitude,
supplierId: supplier.supplierId,
supplierName: supplier.suppliername,
supplierPhone: supplier.phone,
supplierAddress: customer.address,
type_of_water: requestedBooking.type_of_water,
capacity: requestedBooking.capacity,
quantity: requestedBooking.quantity,
total_required_capacity: requestedBooking.total_required_capacity,
expectedDateOfDelivery: requestedBooking.date,
time: requestedBooking.time,
price: matchedSupplier.quoted_amount,
status: 'pending'
});
await newBooking.save(); await booking.save();
reply.code(200).send({ return reply.code(200).send({
status_code: 200, status_code: 200,
message: "Booking accepted and moved to tanker bookings", message: `Booking ${action}ed by supplier successfully`,
data: newBooking data: booking
}); });
} catch (err) { } catch (err) {
console.error(err); console.error(err);
throw boom.internal("Failed to accept booking", err); throw boom.internal("Failed to update supplier response", err);
} }
}; };

@ -1297,3 +1297,149 @@ exports.getuserOrders = async (req, reply) => {
} }
}; };
exports.getuserRequestbookings = async (req, reply) => {
try {
const { customerId } = req.params;
// 1. Get all bookings
const bookings = await RequestedBooking.find({ customerId }).sort({ createdAt: -1 }).lean();
// 2. Collect all supplierIds used
const allSupplierIds = new Set();
bookings.forEach(booking => {
booking.requested_suppliers?.forEach(s => {
if (s.supplierId) allSupplierIds.add(s.supplierId);
});
});
// 3. Query all supplier details at once
const supplierList = await Supplier.find({
supplierId: { $in: [...allSupplierIds] }
}).lean();
const supplierMap = {};
supplierList.forEach(s => {
supplierMap[s.supplierId] = {
supplierId: s.supplierId,
supplierName: s.suppliername,
phone: s.phone,
longitude: s.longitude,
latitude: s.latitude,
address: s.profile?.office_address,
status: s.status
};
});
// 4. Attach supplier_details inside each requested_suppliers[] object
const enrichedBookings = bookings.map(booking => {
booking.requested_suppliers = booking.requested_suppliers.map(supplier => ({
...supplier,
supplier_details: supplierMap[supplier.supplierId] || null
}));
return booking;
});
// 5. Send final response
return reply.send({
status_code: 200,
message: `Orders for customer ${customerId} fetched successfully`,
data: enrichedBookings
});
} catch (err) {
console.error(err);
throw boom.boomify(err);
}
};
exports.acceptRequestedBooking = async (req, reply) => {
const { supplierId } = req.params;
const { action, _id } = req.body;
if (!["accept", "reject"].includes(action)) {
return reply.code(400).send({ message: "Invalid action. Must be 'accept' or 'reject'." });
}
try {
const requestedBooking = await RequestedBooking.findOne({
_id: new mongoose.Types.ObjectId(_id),
'requested_suppliers.supplierId': supplierId
});
if (!requestedBooking) {
return reply.code(404).send({ message: "No matching request for given ID and supplier" });
}
const matchedSupplier = requestedBooking.requested_suppliers.find(s => s.supplierId === supplierId);
if (!matchedSupplier) {
return reply.code(404).send({ message: "Supplier not found in requested_suppliers array" });
}
if (action === "reject") {
matchedSupplier.status = "rejected_by_user";
await requestedBooking.save();
return reply.code(200).send({
status_code: 200,
message: "Supplier request rejected by user",
data: requestedBooking
});
}
// Accept path
requestedBooking.status = 'accepted';
await requestedBooking.save();
const customer = await User.findOne({ customerId: requestedBooking.customerId }).lean();
if (!customer) return reply.code(404).send({ message: "Customer not found" });
const supplier = await Supplier.findOne({ supplierId }).lean();
if (!supplier) return reply.code(404).send({ message: "Supplier not found" });
if (!matchedSupplier.quoted_amount) {
return reply.code(400).send({ message: "Quoted amount missing for this supplier" });
}
const newBooking = new Tankerbooking({
customerId: customer.customerId,
customerName: customer.profile.firstName,
customerPhone: customer.phone,
address: customer.address1,
latitude: customer.latitude,
longitude: customer.longitude,
supplierId: supplier.supplierId,
supplierName: supplier.suppliername,
supplierPhone: supplier.phone,
supplierAddress: customer.address,
type_of_water: requestedBooking.type_of_water,
capacity: requestedBooking.capacity,
quantity: requestedBooking.quantity,
total_required_capacity: requestedBooking.total_required_capacity,
expectedDateOfDelivery: requestedBooking.date,
time: requestedBooking.time,
price: matchedSupplier.quoted_amount,
status: 'pending'
});
await newBooking.save();
reply.code(200).send({
status_code: 200,
message: "Booking accepted and moved to tanker bookings",
data: newBooking
});
} catch (err) {
console.error(err);
throw boom.internal("Failed to handle booking action", err);
}
};

@ -159,7 +159,8 @@ const supplierSchema = new mongoose.Schema(
const requestedSupplierSchema = new mongoose.Schema({ const requestedSupplierSchema = new mongoose.Schema({
supplierId: String, supplierId: String,
quoted_amount: Number, quoted_amount: Number,
custom_field: String // ✅ New field added here time: {type:String,default:null}, // ✅ New field added here
status:{type:String,default: "pending" },
}, { _id: false }); }, { _id: false });
const requestedBookingSchema = new mongoose.Schema({ const requestedBookingSchema = new mongoose.Schema({

@ -597,27 +597,33 @@ fastify.post("/api/requestedbookings", {
handler: supplierController.editCuurentSupplierInfo, handler: supplierController.editCuurentSupplierInfo,
}); });
fastify.route({ fastify.route({
method: "POST", method: "POST",
url: "/api/booking/accept/:supplierId", url: "/api/supplier/booking/respond/:_id",
schema: { schema: {
description: "Accept a requested booking by supplier", description: "Supplier accepts or rejects a requested booking",
tags: ["Supplier-Data"], tags: ["Supplier-Data"],
summary: "Accept booking and move to tanker bookings", summary: "Supplier action on requested booking",
params: { params: {
type: "object", type: "object",
properties: { properties: {
supplierId: { type: "string", description: "Supplier ID" } _id: { type: "string", description: "Requested Booking ID" }
}, },
required: ["supplierId"] required: ["_id"]
}, },
body: { body: {
type: "object", type: "object",
properties: { properties: {
_id: { type: "string", description: "Requested booking ID" }, supplierId: { type: "string", description: "Supplier ID" },
action: { type: "string", enum: ["accept"], description: "Action to perform" } action: {
type: "string",
enum: ["accept", "reject"],
description: "Action to perform by supplier"
}
}, },
required: ["_id", "action"] required: ["supplierId", "action"]
}, },
security: [ security: [
{ {
@ -625,9 +631,12 @@ fastify.route({
}, },
], ],
}, },
//preHandler: fastify.auth([fastify.authenticate]), // preHandler: fastify.auth([fastify.authenticate]), // Uncomment if auth is needed
handler: supplierController.acceptRequestedBooking handler: supplierController.respondToRequestedBooking
}); });
next(); next();
} }

@ -1124,20 +1124,21 @@ fastify.get("/api/cart/:customerId", {
fastify.route({ fastify.route({
method: "POST", method: "GET",
url: "/api/getuserOrders/:customerId", url: "/api/getuserOrders/:customerId",
schema: { schema: {
description: "To Get orders of customer", description: "To Get orders of customer",
tags: ["User"], tags: ["User"],
summary: "This is for Geting orders of customer", summary: "This is for getting orders of a customer",
params: { params: {
type: "object", type: "object",
properties: { properties: {
customerId: { customerId: {
type: "string", type: "string",
description: "customerId", description: "Customer ID",
}, },
}, },
required: ["customerId"]
}, },
security: [ security: [
{ {
@ -1150,5 +1151,67 @@ fastify.get("/api/cart/:customerId", {
}); });
fastify.route({
method: "GET",
url: "/api/getuserRequestbookings/:customerId",
schema: {
description: "To Get requestbookings of customer",
tags: ["User"],
summary: "This is for getting requestbookings of a customer",
params: {
type: "object",
properties: {
customerId: {
type: "string",
description: "Customer ID",
},
},
required: ["customerId"]
},
security: [
{
basicAuth: [],
},
],
},
// preHandler: fastify.auth([fastify.authenticate]),
handler: userController.getuserRequestbookings,
});
fastify.route({
method: "POST",
url: "/api/booking/accept/:supplierId",
schema: {
description: "Accept a requested booking by supplier",
tags: ["Supplier-Data"],
summary: "Accept booking and move to tanker bookings",
params: {
type: "object",
properties: {
supplierId: { type: "string", description: "Supplier ID" }
},
required: ["supplierId"]
},
body: {
type: "object",
properties: {
_id: { type: "string", description: "Requested booking ID" },
action: { type: "string", enum: ["accept","reject"], description: "Action to perform" }
},
required: ["_id", "action"]
},
security: [
{
basicAuth: [],
},
],
},
//preHandler: fastify.auth([fastify.authenticate]),
handler: userController.acceptRequestedBooking
});
next(); next();
}; };

Loading…
Cancel
Save