Spaces:
Sleeping
Sleeping
Download controller/deliveryController.js from Mahmoud7456/MultiUsersSalesSystem: direct link, hf CLI and curl.
- Browser
- Download file 7.02 kB
-
https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/controller/deliveryController.js
- Command line
-
hf download hf://spaces/Mahmoud7456/MultiUsersSalesSystem/controller/deliveryController.js
-
curl -L -o deliveryController.js https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/controller/deliveryController.js
7.02 kB
| import Delivery from "../models/DeliveryModel.js"; | |
| import Invoice from "../models/InvoiceModel.js"; | |
| import User from "../models/UserModel.js"; | |
| import Driver from "../models/DriverModel.js"; | |
| import WhatsAppService from "../utils/whatsappService.js"; | |
| import { catchAsync } from "../utils/catchAsync.js"; | |
| // Assign delivery to invoice (formerly order) | |
| export const assignDelivery = catchAsync(async (req, res) => { | |
| const tenantId = req.user.tenant._id; // ✅ always from authenticated session | |
| const { invoiceId, deliveryPersonId, estimatedDeliveryTime, address, phone, notes } = req.body; | |
| // Validation | |
| if (!invoiceId || !deliveryPersonId) { | |
| return res.status(400).json({ | |
| status: "error", | |
| message: "معرف الفاتورة والسائق مطلوب", | |
| }); | |
| } | |
| // Verify invoice exists and is delivery type | |
| const invoice = await Invoice.findOne({ | |
| _id: invoiceId, | |
| tenant: tenantId, // ✅ ensures tenant isolation | |
| isDeleted: false, | |
| }); | |
| if (!invoice) { | |
| return res.status(404).json({ status: "error", message: "الفاتورة غير موجودة" }); | |
| } | |
| if (invoice.restaurantData?.orderType !== "delivery") { | |
| return res.status(400).json({ | |
| status: "error", | |
| message: "هذه الفاتورة ليست فاتورة توصيل", | |
| }); | |
| } | |
| // Verify delivery person exists | |
| const deliveryPerson = await User.findById(deliveryPersonId); | |
| if (!deliveryPerson) { | |
| return res.status(404).json({ | |
| status: "error", | |
| message: "السائق غير موجود", | |
| }); | |
| } | |
| // Check if delivery already exists | |
| const existingDelivery = await Delivery.findOne({ invoice: invoiceId }); | |
| if (existingDelivery) { | |
| return res.status(400).json({ | |
| status: "error", | |
| message: "تم تعيين توصيل لهذه الفاتورة بالفعل", | |
| }); | |
| } | |
| // Create delivery record | |
| const delivery = await Delivery.create({ | |
| tenant: tenantId, | |
| branch: invoice.branch, | |
| invoice: invoiceId, | |
| customer: invoice.customer || null, | |
| deliveryPerson: deliveryPersonId, | |
| deliveryAddress: { | |
| street: address || invoice.restaurantData?.deliveryAddress, | |
| phone: phone || invoice.restaurantData?.guestInfo?.phone, | |
| notes: notes || "", | |
| }, | |
| estimatedDeliveryTime: estimatedDeliveryTime || 30, | |
| }); | |
| // Update invoice with delivery person | |
| invoice.restaurantData.driver = { | |
| driverId: null, | |
| driverUserId: deliveryPersonId, | |
| driverName: deliveryPerson.fullName, | |
| driverPhone: deliveryPerson.phone, | |
| }; | |
| await invoice.save(); | |
| res.status(201).json({ | |
| status: "success", | |
| message: "تم تعيين السائق بنجاح", | |
| data: delivery, | |
| }); | |
| }); | |
| // Get all deliveries | |
| export const getAllDeliveries = catchAsync(async (req, res) => { | |
| const tenantId = req.user.tenant._id; | |
| const { status, deliveryPersonId, page = 1, limit = 20 } = req.query; | |
| const filter = { tenant: tenantId }; | |
| if (status) filter.status = status; | |
| if (deliveryPersonId) filter.deliveryPerson = deliveryPersonId; | |
| const skip = (page - 1) * limit; | |
| const deliveries = await Delivery.find(filter) | |
| .populate("invoice", "invoiceNumber totalAmount restaurantStatus") | |
| .populate("deliveryPerson", "fullName phone") | |
| .sort({ createdAt: -1 }) | |
| .skip(skip) | |
| .limit(Number(limit)); | |
| const total = await Delivery.countDocuments(filter); | |
| res.status(200).json({ | |
| status: "success", | |
| data: deliveries, | |
| pagination: { | |
| total, | |
| page: Number(page), | |
| pages: Math.ceil(total / limit), | |
| }, | |
| }); | |
| }); | |
| // Get delivery by ID | |
| export const getDeliveryById = catchAsync(async (req, res) => { | |
| const { id } = req.params; | |
| const delivery = await Delivery.findById(id) | |
| .populate("invoice") | |
| .populate("deliveryPerson", "fullName phone"); | |
| if (!delivery) { | |
| return res.status(404).json({ | |
| status: "error", | |
| message: "التوصيل غير موجود", | |
| }); | |
| } | |
| res.status(200).json({ | |
| status: "success", | |
| data: delivery, | |
| }); | |
| }); | |
| // Update delivery status | |
| export const updateDeliveryStatus = catchAsync(async (req, res) => { | |
| const { id } = req.params; | |
| const { status, note } = req.body; | |
| const validStatuses = ["assigned", "confirmed", "in-transit", "delivered", "failed"]; | |
| if (!validStatuses.includes(status)) { | |
| return res.status(400).json({ | |
| status: "error", | |
| message: "حالة التوصيل غير صحيحة", | |
| }); | |
| } | |
| const delivery = await Delivery.findById(id); | |
| if (!delivery) { | |
| return res.status(404).json({ | |
| status: "error", | |
| message: "التوصيل غير موجود", | |
| }); | |
| } | |
| // Update status and history | |
| delivery.status = status; | |
| delivery.statusHistory.push({ | |
| status, | |
| timestamp: new Date(), | |
| note: note || "", | |
| }); | |
| if (status === "in-transit") { | |
| delivery.startedAt = new Date(); | |
| } else if (status === "delivered") { | |
| delivery.deliveredAt = new Date(); | |
| if (delivery.startedAt) { | |
| delivery.actualDeliveryTime = Math.round( | |
| (delivery.deliveredAt - delivery.startedAt) / 60000 | |
| ); // in minutes | |
| } | |
| } | |
| await delivery.save(); | |
| // Send notification about delivery status | |
| const invoice = await Invoice.findOne({ | |
| _id: delivery.invoice, | |
| tenant: delivery.tenant, | |
| }).populate("customer"); | |
| let phoneNumber = invoice.customer?.phone || invoice.restaurantData?.guestInfo?.phone; | |
| if (phoneNumber && (status === "in-transit" || status === "delivered")) { | |
| try { | |
| const notificationType = status === "in-transit" ? "out-for-delivery" : "delivered"; | |
| const deliveryPerson = await User.findById(delivery.deliveryPerson); | |
| await WhatsAppService.queueNotification({ | |
| tenant: delivery.tenant, | |
| invoice: delivery.invoice, | |
| customer: invoice.customer?._id, | |
| phoneNumber, | |
| notificationType, | |
| orderNumber: invoice.invoiceNumber, | |
| driverName: deliveryPerson?.fullName, | |
| driverPhone: deliveryPerson?.phone, | |
| language: "ar", | |
| }); | |
| } catch (error) { | |
| console.error("Failed to queue delivery notification:", error); | |
| } | |
| } | |
| res.status(200).json({ | |
| status: "success", | |
| message: `تم تحديث حالة التوصيل إلى ${status}`, | |
| data: delivery, | |
| }); | |
| }); | |
| // Get delivery person's active deliveries | |
| export const getDeliveryPersonDeliveries = catchAsync(async (req, res) => { | |
| const { deliveryPersonId } = req.params; | |
| const deliveries = await Delivery.find({ | |
| deliveryPerson: deliveryPersonId, | |
| status: { $in: ["assigned", "confirmed", "in-transit"] }, | |
| }) | |
| .populate("invoice", "invoiceNumber totalAmount restaurantData.deliveryAddress") | |
| .sort({ createdAt: -1 }); | |
| res.status(200).json({ | |
| status: "success", | |
| data: deliveries, | |
| }); | |
| }); | |