import Table from "../models/TableModel.js"; import Invoice from "../models/InvoiceModel.js"; import { catchAsync } from "../utils/catchAsync.js"; // Get all tables for a branch export const getAllTables = catchAsync(async (req, res) => { const { tenantId, branchId } = req.params; const tables = await Table.find({ tenant: tenantId, branch: branchId, isActive: true, }) .populate("currentOrderId", "invoiceNumber totalAmount restaurantStatus") .sort({ floor: 1, section: 1, tableNumber: 1 }); res.status(200).json({ status: "success", data: tables, }); }); // Get floor plan (all tables with positions) export const getFloorPlan = catchAsync(async (req, res) => { const { tenantId, branchId } = req.params; const tables = await Table.find({ tenant: tenantId, branch: branchId, isActive: true, }).populate("currentOrderId", "invoiceNumber totalAmount restaurantStatus"); // Group by floor const floorPlan = {}; tables.forEach((table) => { if (!floorPlan[table.floor]) { floorPlan[table.floor] = []; } floorPlan[table.floor].push(table); }); res.status(200).json({ status: "success", data: floorPlan, }); }); // Create table export const createTable = catchAsync(async (req, res) => { const { tenantId, branchId } = req.params; const { tableNumber, displayName, capacity, floor, section, shape } = req.body; // Validation if (!tableNumber || !displayName || !capacity) { return res.status(400).json({ status: "error", message: "الرجاء ملء جميع الحقول المطلوبة", }); } if (capacity < 1) { return res.status(400).json({ status: "error", message: "السعة يجب أن تكون 1 على الأقل", }); } // Check if table number already exists const existingTable = await Table.findOne({ tenant: tenantId, branch: branchId, tableNumber, }); if (existingTable) { return res.status(400).json({ status: "error", message: "رقم الطاولة موجود بالفعل", }); } const table = await Table.create({ tenant: tenantId, branch: branchId, tableNumber, displayName, capacity, floor: floor || "الطابق الأول", section: section || "الرئيسية", shape: shape || "square", }); res.status(201).json({ status: "success", message: "تم إضافة الطاولة بنجاح", data: table, }); }); // Update table export const updateTable = catchAsync(async (req, res) => { const { id } = req.params; const updates = req.body; // Prevent manually overriding occupied status without an order if (updates.status === "available") { updates.currentOrderId = null; } const table = await Table.findByIdAndUpdate(id, updates, { new: true, runValidators: true, }); if (!table) { return res.status(404).json({ status: "error", message: "الطاولة غير موجودة", }); } res.status(200).json({ status: "success", message: "تم تحديث الطاولة بنجاح", data: table, }); }); // Delete table (soft) export const deleteTable = catchAsync(async (req, res) => { const { id } = req.params; const table = await Table.findById(id); if (!table) { return res.status(404).json({ status: "error", message: "الطاولة غير موجودة", }); } // Check if table has active order if (table.currentOrderId) { return res.status(400).json({ status: "error", message: "لا يمكن حذف طاولة بها طلب نشط", }); } // table.isActive = false; // await table.save(); await Table.findByIdAndDelete(id); res.status(200).json({ status: "success", message: "تم حذف الطاولة بنجاح", }); }); // Update table position on floor plan export const updateTablePosition = catchAsync(async (req, res) => { const { id } = req.params; const { x, y } = req.body; if (x === undefined || y === undefined) { return res.status(400).json({ status: "error", message: "الموضع المطلوب غير صحيح", }); } const table = await Table.findByIdAndUpdate( id, { position: { x, y } }, { new: true } ); if (!table) { return res.status(404).json({ status: "error", message: "الطاولة غير موجودة", }); } res.status(200).json({ status: "success", message: "تم تحديث موضع الطاولة", data: table, }); }); // Get table status export const getTableStatus = catchAsync(async (req, res) => { const { id } = req.params; const table = await Table.findById(id).populate( "currentOrderId", "invoiceNumber totalAmount restaurantStatus" ); if (!table) { return res.status(404).json({ status: "error", message: "الطاولة غير موجودة", }); } res.status(200).json({ status: "success", data: { id: table._id, status: table.status, displayName: table.displayName, currentOrder: table.currentOrderId, }, }); }); // ✅ FIXED: was calling undefined TableService — now direct DB logic export const updateTableStatus = catchAsync(async (req, res) => { const { status, currentOrderId } = req.body; const { id } = req.params; const validStatuses = ["available", "occupied", "reserved", "maintenance"]; if (!validStatuses.includes(status)) { return res.status(400).json({ status: "error", message: "حالة غير صالحة", }); } const table = await Table.findById(id); if (!table) { return res.status(404).json({ status: "error", message: "الطاولة غير موجودة", }); } // ✅ Business rule: prevent occupying an already-occupied table by a different order if (status === "occupied" && table.status === "occupied") { const existingOrderId = table.currentOrderId?.toString(); const incomingOrderId = currentOrderId?.toString(); if (existingOrderId && incomingOrderId && existingOrderId !== incomingOrderId) { return res.status(400).json({ status: "error", message: "الطاولة مشغولة بطلب آخر — يجب إتمام الحساب أولاً", }); } } table.status = status; if (status === "available") { table.currentOrderId = null; } else if (currentOrderId) { table.currentOrderId = currentOrderId; } await table.save(); res.status(200).json({ status: "success", message: "تم تحديث حالة الطاولة", data: table, }); });