MultiUsersSalesSystem / controller /driverController.js
Mahmoud7456's picture
Upload 72 files
0330133 verified
Raw History Blame Contribute Delete
12.3 kB
import Driver from "../models/DriverModel.js";
import Invoice from "../models/InvoiceModel.js";
import { catchAsync } from "../utils/catchAsync.js";
// ─── GET ALL DRIVERS (with stats) ─────────────────────────────────────────────
export const getDrivers = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const branchId = req.query.branchId || null;
const query = { tenant: tenantId, isActive: true };
if (branchId) query.branch = branchId;
const drivers = await Driver.find(query)
.populate("currentOrderIds", "invoiceNumber totalAmount restaurantStatus")
.sort({ createdAt: -1 });
const stats = {
total: drivers.length,
available: drivers.filter((d) => d.status === "available").length,
busy: drivers.filter((d) => d.status === "busy").length,
offDuty: drivers.filter((d) => d.status === "off-duty").length,
totalOrders: drivers.reduce((sum, d) => sum + d.currentOrders, 0),
};
res.status(200).json({
status: "success",
data: drivers,
stats,
});
});
// ─── DRIVER DASHBOARD (full detail per driver + their live orders) ─────────────
export const getDriverDashboard = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const branchId = req.query.branchId || null;
const query = { tenant: tenantId, isActive: true };
if (branchId) query.branch = branchId;
const drivers = await Driver.find(query)
.populate({
path: "currentOrderIds",
select: "invoiceNumber totalAmount restaurantStatus createdAt restaurantData",
populate: {
path: "restaurantData.table",
select: "displayName tableNumber",
},
})
.lean();
const driverStats = drivers.map((driver) => ({
...driver,
totalCurrentOrders: (driver.currentOrderIds || []).length,
isAvailable: driver.status === "available",
}));
const globalStats = {
total: drivers.length,
available: drivers.filter((d) => d.status === "available").length,
busy: drivers.filter((d) => d.status === "busy").length,
totalActiveOrders: drivers.reduce(
(sum, d) => sum + (d.currentOrderIds || []).length,
0
),
};
res.status(200).json({
status: "success",
data: driverStats,
stats: globalStats,
});
});
// ─── CREATE DRIVER ─────────────────────────────────────────────────────────────
export const createDriver = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const { name, phone, branchId, notes, vehicleType, licensePlate, maxOrders } = req.body;
if (!name || !phone) {
return res
.status(400)
.json({ status: "error", message: "Ψ§Ω„Ψ§Ψ³Ω… ΩˆΨ±Ω‚Ω… Ψ§Ω„Ω‡Ψ§Ψͺف Ω…Ψ·Ω„ΩˆΨ¨Ψ§Ω†" });
}
const driver = await Driver.create({
tenant: tenantId,
branch: branchId || null,
name: String(name).trim(),
phone: String(phone).trim(),
notes: notes ? String(notes) : "",
vehicleType: vehicleType || "motorcycle",
licensePlate: licensePlate ? String(licensePlate).trim() : undefined,
maxOrders: maxOrders ? Number(maxOrders) : 3,
});
res.status(201).json({ status: "success", data: driver });
});
// ─── UPDATE DRIVER ─────────────────────────────────────────────────────────────
export const updateDriver = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const { id } = req.params;
const {
name,
phone,
isActive,
branchId,
notes,
vehicleType,
licensePlate,
maxOrders,
status,
currentOrders,
currentOrderIds,
} = req.body;
const driver = await Driver.findOne({ _id: id, tenant: tenantId });
if (!driver) {
return res
.status(404)
.json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
}
if (name !== undefined) driver.name = String(name).trim();
if (phone !== undefined) driver.phone = String(phone).trim();
if (branchId !== undefined) driver.branch = branchId || null;
if (notes !== undefined) driver.notes = String(notes || "");
if (isActive !== undefined) driver.isActive = Boolean(isActive);
if (vehicleType !== undefined) driver.vehicleType = vehicleType;
if (licensePlate !== undefined) driver.licensePlate = String(licensePlate || "").trim();
if (maxOrders !== undefined) driver.maxOrders = Number(maxOrders);
if (status !== undefined && ["available", "busy", "off-duty"].includes(status)) {
driver.status = status;
}
if (Array.isArray(currentOrderIds)) {
driver.currentOrderIds = currentOrderIds;
driver.currentOrders = currentOrderIds.length; // always derived from array
}
if (driver.status === "available") {
driver.currentOrders = 0;
driver.currentOrderIds = [];
} else if (driver.currentOrders === 0 && driver.status === "busy") {
driver.status = "available";
}
await driver.save();
res.status(200).json({ status: "success", data: driver });
});
// ─── DELETE DRIVER (soft) ─────────────────────────────────────────────────────
export const deleteDriver = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const { id } = req.params;
const driver = await Driver.findOne({ _id: id, tenant: tenantId });
if (!driver) {
return res
.status(404)
.json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
}
driver.isActive = false;
await driver.save();
res.status(200).json({ status: "success", message: "ΨͺΩ… حذف Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ Ψ¨Ω†Ψ¬Ψ§Ψ­" });
});
// ─── ASSIGN ORDER TO DRIVER ────────────────────────────────────────────────────
// βœ… FIXED: now properly stores the invoice ID in currentOrderIds array
export const assignOrder = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const { id } = req.params;
const requestedOrderIds = Array.isArray(req.body.orderIds)
? req.body.orderIds
: [req.body.invoiceId || req.body.orderId].filter(Boolean);
if (!requestedOrderIds.length) {
return res
.status(400)
.json({ status: "error", message: "معرف الفاΨͺورة Ω…Ψ·Ω„ΩˆΨ¨" });
}
const driver = await Driver.findOne({ _id: id, tenant: tenantId });
if (!driver) {
return res
.status(404)
.json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
}
const uniqueOrderIds = [...new Set(requestedOrderIds.map((orderId) => orderId.toString()))];
const existingOrderIdSet = new Set(
(driver.currentOrderIds || []).map((orderId) => orderId.toString()),
);
const netNewAssignments = uniqueOrderIds.filter(
(orderId) => !existingOrderIdSet.has(orderId),
).length;
if (driver.currentOrders + netNewAssignments > driver.maxOrders) {
return res.status(400).json({
status: "error",
message: `Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ ΩˆΨ΅Ω„ Ω„Ω„Ψ­Ψ― Ψ§Ω„Ψ£Ω‚Ψ΅Ω‰ (${driver.maxOrders} أوردراΨͺ في نفس Ψ§Ω„ΩˆΩ‚Ψͺ)`,
});
}
const invoices = await Invoice.find({
_id: { $in: uniqueOrderIds },
tenant: tenantId,
isDeleted: false,
});
if (invoices.length !== uniqueOrderIds.length) {
return res.status(404).json({
status: "error",
message: "Ψ¨ΨΉΨΆ Ψ§Ω„Ψ·Ω„Ψ¨Ψ§Ψͺ غير Ω…ΩˆΨ¬ΩˆΨ―Ψ©",
});
}
for (const invoice of invoices) {
if (invoice.restaurantData?.orderType !== "delivery") {
return res.status(400).json({
status: "error",
message: "ΩŠΩ…ΩƒΩ† Ψ₯Ψ³Ω†Ψ§Ψ― Ψ³Ψ§Ψ¦Ω‚ فقط Ω„Ψ·Ω„Ψ¨Ψ§Ψͺ Ψ§Ω„ΨͺΩˆΨ΅ΩŠΩ„",
});
}
invoice.restaurantData = invoice.restaurantData || {};
invoice.restaurantData.driver = {
driverId: driver._id,
driverUserId: null,
driverName: driver.name || "",
driverPhone: driver.phone || "",
assignedAt: new Date(),
};
await invoice.save();
}
uniqueOrderIds.forEach((orderId) => existingOrderIdSet.add(orderId));
driver.currentOrderIds = [...existingOrderIdSet];
driver.currentOrders = driver.currentOrderIds.length;
driver.status = driver.currentOrders > 0 ? "busy" : "available";
await driver.save();
res.status(200).json({
status: "success",
message: "ΨͺΩ… ΨͺΨΉΩŠΩŠΩ† Ψ§Ω„Ψ£ΩˆΨ±Ψ―Ψ± Ω„Ω„Ψ³Ψ§Ψ¦Ω‚ Ψ¨Ω†Ψ¬Ψ§Ψ­",
data: driver,
});
});
// ─── COMPLETE / REMOVE ORDER FROM DRIVER ──────────────────────────────────────
export const completeOrder = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const { id } = req.params;
const invoiceId = req.body.invoiceId || req.body.orderId || null;
if (!invoiceId) {
return res.status(400).json({
status: "error",
message: "معرف الفاΨͺورة Ω…Ψ·Ω„ΩˆΨ¨ Ω„Ψ₯Ω†Ω‡Ψ§Ψ‘ Ψ§Ω„ΨͺΩˆΨ΅ΩŠΩ„",
});
}
const driver = await Driver.findOne({ _id: id, tenant: tenantId });
if (!driver) {
return res
.status(404)
.json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
}
if (driver.currentOrders <= 0) {
return res
.status(400)
.json({ status: "error", message: "Ω„Ψ§ Ψͺوجد أوردراΨͺ Ω†Ψ΄Ψ·Ψ© Ω„Ψ₯Ω†Ω‡Ψ§Ψ¦Ω‡Ψ§" });
}
driver.currentOrderIds = (driver.currentOrderIds || []).filter(
(oid) => oid.toString() !== invoiceId.toString()
);
driver.currentOrders = driver.currentOrderIds.length;
// Free driver if no more orders
if (driver.currentOrders === 0) {
driver.status = "available";
}
await driver.save();
if (invoiceId) {
await Invoice.findOneAndUpdate(
{ _id: invoiceId, tenant: tenantId },
{ $set: { restaurantStatus: "delivered" } },
);
}
res.status(200).json({
status: "success",
message: "ΨͺΩ… Ψ₯Ω†Ω‡Ψ§Ψ‘ Ψ§Ω„Ψ£ΩˆΨ±Ψ―Ψ± Ψ¨Ω†Ψ¬Ψ§Ψ­",
data: driver,
});
});
// ─── UPDATE DRIVER STATUS MANUALLY ────────────────────────────────────────────
export const updateDriverStatus = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const { id } = req.params;
const { status } = req.body;
const validStatuses = ["available", "busy", "off-duty"];
if (!validStatuses.includes(status)) {
return res.status(400).json({ status: "error", message: "Ψ­Ψ§Ω„Ψ© غير Ψ΅Ψ§Ω„Ψ­Ψ©" });
}
const driver = await Driver.findOne({ _id: id, tenant: tenantId });
if (!driver) {
return res
.status(404)
.json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
}
// Clear orders if manually setting to available
if (status === "available") {
driver.currentOrders = 0;
driver.currentOrderIds = [];
}
driver.status = status;
await driver.save();
res.status(200).json({ status: "success", data: driver });
});
// ─── GET DELIVERY PENDING ORDERS (unassigned) ─────────────────────────────────
export const getDeliveryPendingOrders = catchAsync(async (req, res) => {
const tenantId = req.user?.tenant?._id;
const orders = await Invoice.find({
tenant: tenantId,
restaurantStatus: "ready_for_delivery",
isDeleted: false,
"restaurantData.driver.driverId": null,
})
.populate("customer", "name phone")
.populate("restaurantData.driver.driverId", "name phone")
.lean();
res.status(200).json({
status: "success",
data: orders,
});
});