Mahmoud7456 commited on
Commit
0330133
·
verified ·
1 Parent(s): c6a4aaf

Upload 72 files

Browse files
controller/authController.js CHANGED
@@ -107,6 +107,7 @@ const sanitizeTenant = (tenant) => {
107
  branchUtilizationPercent,
108
  availableBranchSlots:
109
  branchLimit === null ? null : Math.max(0, branchLimit - branchCount),
 
110
  };
111
  };
112
 
@@ -1214,6 +1215,20 @@ export const createTenantOwner = async (req, res) => {
1214
  const packageKey = normalizePackageKey(req.body.subscriptionPackage) || DEFAULT_SUBSCRIPTION_PACKAGE;
1215
  const packageDetails = getPackageDetails(packageKey);
1216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1217
  if (!companyName || !ownerName || !username || !password) {
1218
  return res.status(400).json({ message: "بيانات الشركة والمالك مطلوبة" });
1219
  }
@@ -1243,6 +1258,7 @@ export const createTenantOwner = async (req, res) => {
1243
  cashierAccountsCount: 0,
1244
  branchLimit: packageDetails.branchLimit,
1245
  branchCount: 1,
 
1246
  });
1247
 
1248
  const primaryBranch = await Branch.create({
 
107
  branchUtilizationPercent,
108
  availableBranchSlots:
109
  branchLimit === null ? null : Math.max(0, branchLimit - branchCount),
110
+ tenantTypes: Array.isArray(tenant.tenantTypes) ? tenant.tenantTypes : ["sales"],
111
  };
112
  };
113
 
 
1215
  const packageKey = normalizePackageKey(req.body.subscriptionPackage) || DEFAULT_SUBSCRIPTION_PACKAGE;
1216
  const packageDetails = getPackageDetails(packageKey);
1217
 
1218
+ // Handle tenantTypes - ensure it's an array and contains valid types
1219
+ let tenantTypes = req.body.tenantTypes || ["sales"];
1220
+ if (!Array.isArray(tenantTypes)) {
1221
+ tenantTypes = [tenantTypes];
1222
+ }
1223
+
1224
+ // Validate and deduplicate tenant types
1225
+ const validTypes = ["restaurant", "cafe", "sales"];
1226
+ tenantTypes = [...new Set(tenantTypes.filter(type => validTypes.includes(type)))];
1227
+
1228
+ if (tenantTypes.length === 0) {
1229
+ tenantTypes = ["sales"];
1230
+ }
1231
+
1232
  if (!companyName || !ownerName || !username || !password) {
1233
  return res.status(400).json({ message: "بيانات الشركة والمالك مطلوبة" });
1234
  }
 
1258
  cashierAccountsCount: 0,
1259
  branchLimit: packageDetails.branchLimit,
1260
  branchCount: 1,
1261
+ tenantTypes,
1262
  });
1263
 
1264
  const primaryBranch = await Branch.create({
controller/deliveryController.js ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Delivery from "../models/DeliveryModel.js";
2
+ import Invoice from "../models/InvoiceModel.js";
3
+ import User from "../models/UserModel.js";
4
+ import Driver from "../models/DriverModel.js";
5
+ import WhatsAppService from "../utils/whatsappService.js";
6
+ import { catchAsync } from "../utils/catchAsync.js";
7
+
8
+ // Assign delivery to invoice (formerly order)
9
+ export const assignDelivery = catchAsync(async (req, res) => {
10
+ const tenantId = req.user.tenant._id; // ✅ always from authenticated session
11
+ const { invoiceId, deliveryPersonId, estimatedDeliveryTime, address, phone, notes } = req.body;
12
+
13
+ // Validation
14
+ if (!invoiceId || !deliveryPersonId) {
15
+ return res.status(400).json({
16
+ status: "error",
17
+ message: "معرف الفاتورة والسائق مطلوب",
18
+ });
19
+ }
20
+
21
+ // Verify invoice exists and is delivery type
22
+ const invoice = await Invoice.findOne({
23
+ _id: invoiceId,
24
+ tenant: tenantId, // ✅ ensures tenant isolation
25
+ isDeleted: false,
26
+ });
27
+ if (!invoice) {
28
+ return res.status(404).json({ status: "error", message: "الفاتورة غير موجودة" });
29
+ }
30
+
31
+ if (invoice.restaurantData?.orderType !== "delivery") {
32
+ return res.status(400).json({
33
+ status: "error",
34
+ message: "هذه الفاتورة ليست فاتورة توصيل",
35
+ });
36
+ }
37
+
38
+ // Verify delivery person exists
39
+ const deliveryPerson = await User.findById(deliveryPersonId);
40
+ if (!deliveryPerson) {
41
+ return res.status(404).json({
42
+ status: "error",
43
+ message: "السائق غير موجود",
44
+ });
45
+ }
46
+
47
+ // Check if delivery already exists
48
+ const existingDelivery = await Delivery.findOne({ invoice: invoiceId });
49
+ if (existingDelivery) {
50
+ return res.status(400).json({
51
+ status: "error",
52
+ message: "تم تعيين توصيل لهذه الفاتورة بالفعل",
53
+ });
54
+ }
55
+
56
+ // Create delivery record
57
+ const delivery = await Delivery.create({
58
+ tenant: tenantId,
59
+ branch: invoice.branch,
60
+ invoice: invoiceId,
61
+ customer: invoice.customer || null,
62
+ deliveryPerson: deliveryPersonId,
63
+ deliveryAddress: {
64
+ street: address || invoice.restaurantData?.deliveryAddress,
65
+ phone: phone || invoice.restaurantData?.guestInfo?.phone,
66
+ notes: notes || "",
67
+ },
68
+ estimatedDeliveryTime: estimatedDeliveryTime || 30,
69
+ });
70
+
71
+ // Update invoice with delivery person
72
+ invoice.restaurantData.driver = {
73
+ driverId: null,
74
+ driverUserId: deliveryPersonId,
75
+ driverName: deliveryPerson.fullName,
76
+ driverPhone: deliveryPerson.phone,
77
+ };
78
+ await invoice.save();
79
+
80
+ res.status(201).json({
81
+ status: "success",
82
+ message: "تم تعيين السائق بنجاح",
83
+ data: delivery,
84
+ });
85
+ });
86
+
87
+ // Get all deliveries
88
+ export const getAllDeliveries = catchAsync(async (req, res) => {
89
+ const tenantId = req.user.tenant._id;
90
+ const { status, deliveryPersonId, page = 1, limit = 20 } = req.query;
91
+
92
+ const filter = { tenant: tenantId };
93
+ if (status) filter.status = status;
94
+ if (deliveryPersonId) filter.deliveryPerson = deliveryPersonId;
95
+
96
+ const skip = (page - 1) * limit;
97
+
98
+ const deliveries = await Delivery.find(filter)
99
+ .populate("invoice", "invoiceNumber totalAmount restaurantStatus")
100
+ .populate("deliveryPerson", "fullName phone")
101
+ .sort({ createdAt: -1 })
102
+ .skip(skip)
103
+ .limit(Number(limit));
104
+
105
+ const total = await Delivery.countDocuments(filter);
106
+
107
+ res.status(200).json({
108
+ status: "success",
109
+ data: deliveries,
110
+ pagination: {
111
+ total,
112
+ page: Number(page),
113
+ pages: Math.ceil(total / limit),
114
+ },
115
+ });
116
+ });
117
+
118
+ // Get delivery by ID
119
+ export const getDeliveryById = catchAsync(async (req, res) => {
120
+ const { id } = req.params;
121
+
122
+ const delivery = await Delivery.findById(id)
123
+ .populate("invoice")
124
+ .populate("deliveryPerson", "fullName phone");
125
+
126
+ if (!delivery) {
127
+ return res.status(404).json({
128
+ status: "error",
129
+ message: "التوصيل غير موجود",
130
+ });
131
+ }
132
+
133
+ res.status(200).json({
134
+ status: "success",
135
+ data: delivery,
136
+ });
137
+ });
138
+
139
+ // Update delivery status
140
+ export const updateDeliveryStatus = catchAsync(async (req, res) => {
141
+ const { id } = req.params;
142
+ const { status, note } = req.body;
143
+
144
+ const validStatuses = ["assigned", "confirmed", "in-transit", "delivered", "failed"];
145
+ if (!validStatuses.includes(status)) {
146
+ return res.status(400).json({
147
+ status: "error",
148
+ message: "حالة التوصيل غير صحيحة",
149
+ });
150
+ }
151
+
152
+ const delivery = await Delivery.findById(id);
153
+ if (!delivery) {
154
+ return res.status(404).json({
155
+ status: "error",
156
+ message: "التوصيل غير موجود",
157
+ });
158
+ }
159
+
160
+ // Update status and history
161
+ delivery.status = status;
162
+ delivery.statusHistory.push({
163
+ status,
164
+ timestamp: new Date(),
165
+ note: note || "",
166
+ });
167
+
168
+ if (status === "in-transit") {
169
+ delivery.startedAt = new Date();
170
+ } else if (status === "delivered") {
171
+ delivery.deliveredAt = new Date();
172
+ if (delivery.startedAt) {
173
+ delivery.actualDeliveryTime = Math.round(
174
+ (delivery.deliveredAt - delivery.startedAt) / 60000
175
+ ); // in minutes
176
+ }
177
+ }
178
+
179
+ await delivery.save();
180
+
181
+ // Send notification about delivery status
182
+ const invoice = await Invoice.findOne({
183
+ _id: delivery.invoice,
184
+ tenant: delivery.tenant,
185
+ }).populate("customer");
186
+
187
+ let phoneNumber = invoice.customer?.phone || invoice.restaurantData?.guestInfo?.phone;
188
+
189
+ if (phoneNumber && (status === "in-transit" || status === "delivered")) {
190
+ try {
191
+ const notificationType = status === "in-transit" ? "out-for-delivery" : "delivered";
192
+ const deliveryPerson = await User.findById(delivery.deliveryPerson);
193
+
194
+ await WhatsAppService.queueNotification({
195
+ tenant: delivery.tenant,
196
+ invoice: delivery.invoice,
197
+ customer: invoice.customer?._id,
198
+ phoneNumber,
199
+ notificationType,
200
+ orderNumber: invoice.invoiceNumber,
201
+ driverName: deliveryPerson?.fullName,
202
+ driverPhone: deliveryPerson?.phone,
203
+ language: "ar",
204
+ });
205
+ } catch (error) {
206
+ console.error("Failed to queue delivery notification:", error);
207
+ }
208
+ }
209
+
210
+ res.status(200).json({
211
+ status: "success",
212
+ message: `تم تحديث حالة التوصيل إلى ${status}`,
213
+ data: delivery,
214
+ });
215
+ });
216
+
217
+ // Get delivery person's active deliveries
218
+ export const getDeliveryPersonDeliveries = catchAsync(async (req, res) => {
219
+ const { deliveryPersonId } = req.params;
220
+
221
+ const deliveries = await Delivery.find({
222
+ deliveryPerson: deliveryPersonId,
223
+ status: { $in: ["assigned", "confirmed", "in-transit"] },
224
+ })
225
+ .populate("invoice", "invoiceNumber totalAmount restaurantData.deliveryAddress")
226
+ .sort({ createdAt: -1 });
227
+
228
+ res.status(200).json({
229
+ status: "success",
230
+ data: deliveries,
231
+ });
232
+ });
controller/driverController.js ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Driver from "../models/DriverModel.js";
2
+ import Invoice from "../models/InvoiceModel.js";
3
+ import { catchAsync } from "../utils/catchAsync.js";
4
+
5
+ // ─── GET ALL DRIVERS (with stats) ─────────────────────────────────────────────
6
+ export const getDrivers = catchAsync(async (req, res) => {
7
+ const tenantId = req.user?.tenant?._id;
8
+ const branchId = req.query.branchId || null;
9
+
10
+ const query = { tenant: tenantId, isActive: true };
11
+ if (branchId) query.branch = branchId;
12
+
13
+ const drivers = await Driver.find(query)
14
+ .populate("currentOrderIds", "invoiceNumber totalAmount restaurantStatus")
15
+ .sort({ createdAt: -1 });
16
+
17
+ const stats = {
18
+ total: drivers.length,
19
+ available: drivers.filter((d) => d.status === "available").length,
20
+ busy: drivers.filter((d) => d.status === "busy").length,
21
+ offDuty: drivers.filter((d) => d.status === "off-duty").length,
22
+ totalOrders: drivers.reduce((sum, d) => sum + d.currentOrders, 0),
23
+ };
24
+
25
+ res.status(200).json({
26
+ status: "success",
27
+ data: drivers,
28
+ stats,
29
+ });
30
+ });
31
+
32
+ // ─── DRIVER DASHBOARD (full detail per driver + their live orders) ─────────────
33
+ export const getDriverDashboard = catchAsync(async (req, res) => {
34
+ const tenantId = req.user?.tenant?._id;
35
+ const branchId = req.query.branchId || null;
36
+
37
+ const query = { tenant: tenantId, isActive: true };
38
+ if (branchId) query.branch = branchId;
39
+
40
+ const drivers = await Driver.find(query)
41
+ .populate({
42
+ path: "currentOrderIds",
43
+ select: "invoiceNumber totalAmount restaurantStatus createdAt restaurantData",
44
+ populate: {
45
+ path: "restaurantData.table",
46
+ select: "displayName tableNumber",
47
+ },
48
+ })
49
+ .lean();
50
+
51
+ const driverStats = drivers.map((driver) => ({
52
+ ...driver,
53
+ totalCurrentOrders: (driver.currentOrderIds || []).length,
54
+ isAvailable: driver.status === "available",
55
+ }));
56
+
57
+ const globalStats = {
58
+ total: drivers.length,
59
+ available: drivers.filter((d) => d.status === "available").length,
60
+ busy: drivers.filter((d) => d.status === "busy").length,
61
+ totalActiveOrders: drivers.reduce(
62
+ (sum, d) => sum + (d.currentOrderIds || []).length,
63
+ 0
64
+ ),
65
+ };
66
+
67
+ res.status(200).json({
68
+ status: "success",
69
+ data: driverStats,
70
+ stats: globalStats,
71
+ });
72
+ });
73
+
74
+ // ─── CREATE DRIVER ─────────────────────────────────────────────────────────────
75
+ export const createDriver = catchAsync(async (req, res) => {
76
+ const tenantId = req.user?.tenant?._id;
77
+ const { name, phone, branchId, notes, vehicleType, licensePlate, maxOrders } = req.body;
78
+
79
+ if (!name || !phone) {
80
+ return res
81
+ .status(400)
82
+ .json({ status: "error", message: "الاسم ورقم الهاتف مطلوبان" });
83
+ }
84
+
85
+ const driver = await Driver.create({
86
+ tenant: tenantId,
87
+ branch: branchId || null,
88
+ name: String(name).trim(),
89
+ phone: String(phone).trim(),
90
+ notes: notes ? String(notes) : "",
91
+ vehicleType: vehicleType || "motorcycle",
92
+ licensePlate: licensePlate ? String(licensePlate).trim() : undefined,
93
+ maxOrders: maxOrders ? Number(maxOrders) : 3,
94
+ });
95
+
96
+ res.status(201).json({ status: "success", data: driver });
97
+ });
98
+
99
+ // ─── UPDATE DRIVER ─────────────────────────────────────────────────────────────
100
+ export const updateDriver = catchAsync(async (req, res) => {
101
+ const tenantId = req.user?.tenant?._id;
102
+ const { id } = req.params;
103
+ const {
104
+ name,
105
+ phone,
106
+ isActive,
107
+ branchId,
108
+ notes,
109
+ vehicleType,
110
+ licensePlate,
111
+ maxOrders,
112
+ status,
113
+ currentOrders,
114
+ currentOrderIds,
115
+ } = req.body;
116
+
117
+ const driver = await Driver.findOne({ _id: id, tenant: tenantId });
118
+ if (!driver) {
119
+ return res
120
+ .status(404)
121
+ .json({ status: "error", message: "السائق غير موجود" });
122
+ }
123
+
124
+ if (name !== undefined) driver.name = String(name).trim();
125
+ if (phone !== undefined) driver.phone = String(phone).trim();
126
+ if (branchId !== undefined) driver.branch = branchId || null;
127
+ if (notes !== undefined) driver.notes = String(notes || "");
128
+ if (isActive !== undefined) driver.isActive = Boolean(isActive);
129
+ if (vehicleType !== undefined) driver.vehicleType = vehicleType;
130
+ if (licensePlate !== undefined) driver.licensePlate = String(licensePlate || "").trim();
131
+ if (maxOrders !== undefined) driver.maxOrders = Number(maxOrders);
132
+ if (status !== undefined && ["available", "busy", "off-duty"].includes(status)) {
133
+ driver.status = status;
134
+ }
135
+ if (Array.isArray(currentOrderIds)) {
136
+ driver.currentOrderIds = currentOrderIds;
137
+ driver.currentOrders = currentOrderIds.length; // always derived from array
138
+ }
139
+ if (driver.status === "available") {
140
+ driver.currentOrders = 0;
141
+ driver.currentOrderIds = [];
142
+ } else if (driver.currentOrders === 0 && driver.status === "busy") {
143
+ driver.status = "available";
144
+ }
145
+
146
+ await driver.save();
147
+ res.status(200).json({ status: "success", data: driver });
148
+ });
149
+
150
+ // ─── DELETE DRIVER (soft) ─────────────────────────────────────────────────────
151
+ export const deleteDriver = catchAsync(async (req, res) => {
152
+ const tenantId = req.user?.tenant?._id;
153
+ const { id } = req.params;
154
+
155
+ const driver = await Driver.findOne({ _id: id, tenant: tenantId });
156
+ if (!driver) {
157
+ return res
158
+ .status(404)
159
+ .json({ status: "error", message: "السائق غير موجود" });
160
+ }
161
+
162
+ driver.isActive = false;
163
+ await driver.save();
164
+
165
+ res.status(200).json({ status: "success", message: "تم حذف السائق بنجاح" });
166
+ });
167
+
168
+ // ─── ASSIGN ORDER TO DRIVER ────────────────────────────────────────────────────
169
+ // ✅ FIXED: now properly stores the invoice ID in currentOrderIds array
170
+ export const assignOrder = catchAsync(async (req, res) => {
171
+ const tenantId = req.user?.tenant?._id;
172
+ const { id } = req.params;
173
+ const requestedOrderIds = Array.isArray(req.body.orderIds)
174
+ ? req.body.orderIds
175
+ : [req.body.invoiceId || req.body.orderId].filter(Boolean);
176
+
177
+ if (!requestedOrderIds.length) {
178
+ return res
179
+ .status(400)
180
+ .json({ status: "error", message: "معرف الفاتورة مطلوب" });
181
+ }
182
+
183
+ const driver = await Driver.findOne({ _id: id, tenant: tenantId });
184
+ if (!driver) {
185
+ return res
186
+ .status(404)
187
+ .json({ status: "error", message: "السائق غير موجود" });
188
+ }
189
+
190
+ const uniqueOrderIds = [...new Set(requestedOrderIds.map((orderId) => orderId.toString()))];
191
+ const existingOrderIdSet = new Set(
192
+ (driver.currentOrderIds || []).map((orderId) => orderId.toString()),
193
+ );
194
+ const netNewAssignments = uniqueOrderIds.filter(
195
+ (orderId) => !existingOrderIdSet.has(orderId),
196
+ ).length;
197
+
198
+ if (driver.currentOrders + netNewAssignments > driver.maxOrders) {
199
+ return res.status(400).json({
200
+ status: "error",
201
+ message: `السائق وصل للحد الأقصى (${driver.maxOrders} أوردرات في نفس الوقت)`,
202
+ });
203
+ }
204
+
205
+ const invoices = await Invoice.find({
206
+ _id: { $in: uniqueOrderIds },
207
+ tenant: tenantId,
208
+ isDeleted: false,
209
+ });
210
+
211
+ if (invoices.length !== uniqueOrderIds.length) {
212
+ return res.status(404).json({
213
+ status: "error",
214
+ message: "بعض الطلبات غير موجودة",
215
+ });
216
+ }
217
+
218
+ for (const invoice of invoices) {
219
+ if (invoice.restaurantData?.orderType !== "delivery") {
220
+ return res.status(400).json({
221
+ status: "error",
222
+ message: "يمكن إسناد سائق فقط لطلبات التوصيل",
223
+ });
224
+ }
225
+
226
+ invoice.restaurantData = invoice.restaurantData || {};
227
+ invoice.restaurantData.driver = {
228
+ driverId: driver._id,
229
+ driverUserId: null,
230
+ driverName: driver.name || "",
231
+ driverPhone: driver.phone || "",
232
+ assignedAt: new Date(),
233
+ };
234
+ await invoice.save();
235
+ }
236
+
237
+ uniqueOrderIds.forEach((orderId) => existingOrderIdSet.add(orderId));
238
+ driver.currentOrderIds = [...existingOrderIdSet];
239
+ driver.currentOrders = driver.currentOrderIds.length;
240
+ driver.status = driver.currentOrders > 0 ? "busy" : "available";
241
+ await driver.save();
242
+
243
+ res.status(200).json({
244
+ status: "success",
245
+ message: "تم تعيين الأوردر للسائق بنجاح",
246
+ data: driver,
247
+ });
248
+ });
249
+
250
+ // ─── COMPLETE / REMOVE ORDER FROM DRIVER ──────────────────────────────────────
251
+ export const completeOrder = catchAsync(async (req, res) => {
252
+ const tenantId = req.user?.tenant?._id;
253
+ const { id } = req.params;
254
+ const invoiceId = req.body.invoiceId || req.body.orderId || null;
255
+
256
+ if (!invoiceId) {
257
+ return res.status(400).json({
258
+ status: "error",
259
+ message: "معرف الفاتورة مطلوب لإنهاء التوصيل",
260
+ });
261
+ }
262
+
263
+ const driver = await Driver.findOne({ _id: id, tenant: tenantId });
264
+ if (!driver) {
265
+ return res
266
+ .status(404)
267
+ .json({ status: "error", message: "السائق غير موجود" });
268
+ }
269
+
270
+ if (driver.currentOrders <= 0) {
271
+ return res
272
+ .status(400)
273
+ .json({ status: "error", message: "لا توجد أوردرات نشطة لإنهائها" });
274
+ }
275
+
276
+ driver.currentOrderIds = (driver.currentOrderIds || []).filter(
277
+ (oid) => oid.toString() !== invoiceId.toString()
278
+ );
279
+ driver.currentOrders = driver.currentOrderIds.length;
280
+
281
+ // Free driver if no more orders
282
+ if (driver.currentOrders === 0) {
283
+ driver.status = "available";
284
+ }
285
+
286
+ await driver.save();
287
+
288
+ if (invoiceId) {
289
+ await Invoice.findOneAndUpdate(
290
+ { _id: invoiceId, tenant: tenantId },
291
+ { $set: { restaurantStatus: "delivered" } },
292
+ );
293
+ }
294
+
295
+ res.status(200).json({
296
+ status: "success",
297
+ message: "تم إنهاء الأوردر بنجاح",
298
+ data: driver,
299
+ });
300
+ });
301
+
302
+ // ─── UPDATE DRIVER STATUS MANUALLY ────────────────────────────────────────────
303
+ export const updateDriverStatus = catchAsync(async (req, res) => {
304
+ const tenantId = req.user?.tenant?._id;
305
+ const { id } = req.params;
306
+ const { status } = req.body;
307
+
308
+ const validStatuses = ["available", "busy", "off-duty"];
309
+ if (!validStatuses.includes(status)) {
310
+ return res.status(400).json({ status: "error", message: "حالة غير صالحة" });
311
+ }
312
+
313
+ const driver = await Driver.findOne({ _id: id, tenant: tenantId });
314
+ if (!driver) {
315
+ return res
316
+ .status(404)
317
+ .json({ status: "error", message: "السائق غير موجود" });
318
+ }
319
+
320
+ // Clear orders if manually setting to available
321
+ if (status === "available") {
322
+ driver.currentOrders = 0;
323
+ driver.currentOrderIds = [];
324
+ }
325
+
326
+ driver.status = status;
327
+ await driver.save();
328
+
329
+ res.status(200).json({ status: "success", data: driver });
330
+ });
331
+
332
+ // ─── GET DELIVERY PENDING ORDERS (unassigned) ─────────────────────────────────
333
+ export const getDeliveryPendingOrders = catchAsync(async (req, res) => {
334
+ const tenantId = req.user?.tenant?._id;
335
+
336
+ const orders = await Invoice.find({
337
+ tenant: tenantId,
338
+ restaurantStatus: "ready_for_delivery",
339
+ isDeleted: false,
340
+ "restaurantData.driver.driverId": null,
341
+ })
342
+ .populate("customer", "name phone")
343
+ .populate("restaurantData.driver.driverId", "name phone")
344
+ .lean();
345
+
346
+ res.status(200).json({
347
+ status: "success",
348
+ data: orders,
349
+ });
350
+ });
controller/expenseController.js CHANGED
@@ -58,11 +58,16 @@ export const getExpenses = async (req, res) => {
58
  export const deleteExpense = async (req, res) => {
59
  try {
60
  const { branchFilter } = await resolveScopedBranch(req);
61
- await Expense.findOneAndDelete({
62
  _id: req.params.id,
63
  tenant: req.user.tenant._id,
64
  ...branchFilter,
65
  });
 
 
 
 
 
66
  res.status(200).json({ message: "تم حذف المصروف بنجاح" });
67
  } catch (error) {
68
  res.status(500).json({ message: error.message });
 
58
  export const deleteExpense = async (req, res) => {
59
  try {
60
  const { branchFilter } = await resolveScopedBranch(req);
61
+ const deleted = await Expense.findOneAndDelete({
62
  _id: req.params.id,
63
  tenant: req.user.tenant._id,
64
  ...branchFilter,
65
  });
66
+
67
+ if (!deleted) {
68
+ return res.status(404).json({ message: "المصروف غير موجود" });
69
+ }
70
+
71
  res.status(200).json({ message: "تم حذف المصروف بنجاح" });
72
  } catch (error) {
73
  res.status(500).json({ message: error.message });
controller/invoiceController.js CHANGED
@@ -4,858 +4,1730 @@ import Product from "../models/ProductModel.js";
4
  import CatalogItem from "../models/CatalogItemModel.js";
5
  import Counter from "../models/CounterModel.js";
6
  import Income from "../models/IncomeModel.js";
7
- import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
 
 
 
 
 
 
 
 
 
8
 
9
  const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";
10
 
11
  const INVOICE_ITEM_TYPES = ["product", "service", "catalog"];
12
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- async function generateInvoiceNumber(tenantId, branchId) {
15
- const counter = await Counter.findOneAndUpdate(
16
- { tenant: tenantId, branch: branchId },
17
- { $inc: { invoiceNumber: 1 } },
18
- {
19
- new: true,
20
- upsert: true,
21
- setDefaultsOnInsert: true
22
- }
23
- );
24
-
25
- const padded = String(counter.invoiceNumber).padStart(5, '0');
26
- return `INV-${padded}`;
27
- }
28
 
 
 
29
 
30
- const getOrCreateWalkInCustomer = async (tenantId, branchId, userId) => {
31
- let customer = await Customer.findOne({ tenant: tenantId, branch: branchId, isWalkIn: true });
32
-
33
- if (!customer) {
34
- customer = await Customer.create({
35
- tenant: tenantId,
36
- branch: branchId,
37
- name: WALK_IN_CUSTOMER_NAME,
38
- isWalkIn: true,
39
- notes: "System generated customer for walk-in cash sales.",
40
- createdBy: userId || null,
41
- });
42
- }
43
 
44
- return customer;
 
 
45
  };
46
 
47
- const ensureStockAvailability = async (items, tenantId, branchId) => {
48
- for (const item of items) {
49
- if (item.type !== "product" || !item.productId) {
50
- continue;
51
- }
 
 
 
 
 
 
 
 
 
52
 
53
- const product = await Product.findOne({ _id: item.productId, tenant: tenantId, branch: branchId });
54
- if (!product) {
55
- const error = new Error(`المنتج غير موجود: ${item.name}`);
56
- error.statusCode = 404;
57
- throw error;
58
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- if (product.stock < Number(item.quantity)) {
61
- const error = new Error(`المخزون غير كافٍ للصنف ${item.name}. المتاح: ${product.stock}`);
62
- error.statusCode = 400;
63
- throw error;
64
- }
65
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  };
67
 
68
  const validateCatalogItems = async (items, tenantId, branchId) => {
69
- for (const item of items) {
70
- if (item.type !== "catalog" || !item.catalogItemId) {
71
- continue;
72
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  const catalogItem = await CatalogItem.findOne({
75
- _id: item.catalogItemId,
76
- tenant: tenantId,
77
- branch: branchId,
78
- isActive: true,
79
- }).populate("category", "name");
80
 
81
  if (!catalogItem) {
82
- const error = new Error(`عنصر الكتالوج غير موجود: ${item.name}`);
83
- error.statusCode = 404;
84
- throw error;
85
  }
86
- }
87
- };
88
 
89
- const applyInvoiceItemsAndStock = async (invoice, items, tenantId, branchId) => {
90
- for (const item of items) {
91
- const quantity = Number(item.quantity || 0);
92
- const normalizedType = INVOICE_ITEM_TYPES.includes(item.type) ? item.type : item.productId ? "product" : "service";
93
- let resolvedName = item.name;
94
- let resolvedPrice = Number(item.price || 0);
95
-
96
- if (normalizedType === "catalog" && item.catalogItemId) {
97
- const catalogItem = await CatalogItem.findOne({
98
- _id: item.catalogItemId,
99
- tenant: tenantId,
100
- branch: branchId,
101
- });
102
-
103
- if (!catalogItem) {
104
- const error = new Error(`عنصر الكتالوج غير موجود: ${item.name}`);
105
- error.statusCode = 404;
106
- throw error;
107
- }
108
-
109
- resolvedName = catalogItem.name;
110
- resolvedPrice = Number(catalogItem.price || 0);
111
- }
112
-
113
- invoice.items.push({
114
- name: resolvedName,
115
- quantity,
116
- price: resolvedPrice,
117
- total: quantity * resolvedPrice,
118
- type: normalizedType,
119
- ...(item.productId ? { productId: item.productId } : {}),
120
- ...(item.serviceId ? { serviceId: item.serviceId } : {}),
121
- ...(item.catalogItemId ? { catalogItemId: item.catalogItemId } : {}),
122
- });
123
-
124
- if (normalizedType === "product" && item.productId) {
125
- await Product.findOneAndUpdate(
126
- { _id: item.productId, tenant: tenantId, branch: branchId },
127
- { $inc: { stock: -quantity } }
128
- );
129
- }
130
- }
131
  };
132
 
133
  const createIncomeForPayment = async ({
134
- tenantId,
135
- branchId,
136
- invoice,
137
- customer,
138
- amount,
139
- userId,
140
- date,
141
- notes,
142
- paymentMethod = "cash",
143
- transferType = null,
144
  }) => {
145
- if (!amount || amount <= 0) {
146
- return;
147
- }
148
-
149
- // If the invoice has services, calculate the ratio and split the income record
150
- const revenueBuckets = [
151
- {
152
- amount: Number(invoice.serviceRevenue || 0),
153
- category: "service_income",
154
- title: `Service Income - ${invoice.invoiceNumber}`,
155
- notesFallback: `Service portion for invoice ${invoice.invoiceNumber}`,
156
- },
157
- {
158
- amount: Number(invoice.catalogRevenue || 0),
159
- category: "catalog_sale",
160
- title: `Catalog Sale - ${invoice.invoiceNumber}`,
161
- notesFallback: `Catalog portion for invoice ${invoice.invoiceNumber}`,
162
- },
163
- {
164
- amount: Number(invoice.productRevenue || 0),
165
- category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment",
166
- title: `Invoice payment - ${invoice.invoiceNumber}`,
167
- notesFallback: `Product portion for invoice ${invoice.invoiceNumber}`,
168
- },
169
- ].filter((bucket) => bucket.amount > 0);
170
-
171
- const totalItemRevenue = revenueBuckets.reduce((sum, bucket) => sum + bucket.amount, 0);
172
-
173
- if (!totalItemRevenue) {
174
- return;
175
- }
176
-
177
- let remainingAmount = Number(amount);
178
- const incomesToCreate = revenueBuckets.map((bucket, index) => {
 
 
 
 
179
  const isLastBucket = index === revenueBuckets.length - 1;
180
  const allocatedAmount = isLastBucket
181
- ? Number(remainingAmount.toFixed(2))
182
- : Number(((Number(amount) * bucket.amount) / totalItemRevenue).toFixed(2));
 
 
183
 
184
  remainingAmount = Number((remainingAmount - allocatedAmount).toFixed(2));
185
 
186
  return {
187
- tenant: tenantId,
188
- branch: branchId,
189
- title: bucket.title,
190
- category: bucket.category,
191
- amount: allocatedAmount,
192
- paymentMethod,
193
- notes: notes || bucket.notesFallback,
194
- sourceType: "invoice_payment",
195
- relatedInvoice: invoice._id,
196
- relatedCustomer: customer?._id || null,
197
- date: date || new Date(),
198
- createdBy: userId || null,
199
  };
200
- }).filter((entry) => entry.amount > 0);
 
201
 
202
- if (incomesToCreate.length) {
203
- await Income.insertMany(incomesToCreate);
204
- }
205
  };
206
 
207
  export const addItemToInvoice = async (req, res) => {
208
- let createdCustomer = null;
209
- try {
210
- const { customerId } = req.params;
211
- const { items, customerName, notes = "", discount = 0, tax = 0 } = req.body;
212
- const tenantId = req.user.tenant?._id;
213
- const branch = await resolveBranchForWrite(req);
214
- const branchId = branch._id;
215
-
216
- if (!tenantId) {
217
- return res.status(403).json({ message: "لا يوجد مستأجر مرتبط بهذا الحساب" });
218
- }
219
- if (!Array.isArray(items) || items.length === 0) {
220
- return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  }
222
 
223
- let finalCustomerId = customerId;
224
- if (customerId === "new") {
225
- if (!customerName) return res.status(400).json({ message: "اسم العميل مطلوب لإنشاء حساب جديد" });
226
- createdCustomer = await Customer.create({
227
- name: customerName.trim(),
228
- tenant: tenantId,
229
- branch: branchId,
230
- createdBy: req.user._id,
231
- });
232
- finalCustomerId = createdCustomer._id;
233
- }
 
234
 
235
- const customer = await Customer.findOne({ _id: finalCustomerId, tenant: tenantId, branch: branchId });
236
- if (!customer) {
237
- if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
238
- return res.status(404).json({ message: "العميل غير موجود" });
239
- }
240
- if (customer.isWalkIn) {
241
- if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
242
- return res.status(400).json({ message: "استخدم مسار بيع الزائر النقدي لفواتير العملاء الزائرين" });
 
 
 
 
 
 
 
 
 
 
 
 
243
  }
244
 
245
- try {
246
- const invoice = new Invoice({
247
- tenant: tenantId,
248
- branch: branchId,
249
- customer: finalCustomerId,
250
- issuedBy: req.user._id,
251
- notes: notes.trim(),
252
- discount: Math.max(Number(discount) || 0, 0),
253
- taxAmount: Math.max(Number(tax) || 0, 0),
254
- });
255
-
256
- await validateCatalogItems(items, tenantId, branchId);
257
- await ensureStockAvailability(items, tenantId, branchId);
258
- await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);
259
-
260
- // Robust duplicate key retry logic for missing/corrupted counters
261
- let saved = false;
262
- for (let i = 0; i < 3; i++) {
263
- try {
264
- invoice.invoiceNumber = await generateInvoiceNumber(tenantId, branchId);
265
- invoice.calculateTotals();
266
- await invoice.save();
267
- saved = true;
268
- break;
269
- } catch (saveErr) {
270
- if (saveErr.code === 11000 && i < 2) continue; // Retry
271
- throw saveErr;
272
- }
273
- }
274
-
275
- if (!saved) throw new Error("تعذر حفظ الفاتورة لخطأ تزامن، حاول مجدداً");
276
-
277
- res.status(200).json(invoice);
278
- } catch (err) {
279
- if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
280
- throw err; // cascade to main catch block
281
  }
282
- } catch (err) {
283
- if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
284
- res.status(err.statusCode || 500).json({ message: err.message });
285
- }
 
 
 
 
 
 
286
  };
287
 
288
- export const createWalkInCashSale = async (req, res) => {
289
- let createdCustomer = null;
290
- try {
291
- const tenantId = req.user.tenant?._id;
292
- const branch = await resolveBranchForWrite(req);
293
- const branchId = branch._id;
294
- const { items, paidAmount, notes = "", customerId, customerName, discount = 0, tax = 0 } = req.body;
295
-
296
- if (!tenantId) {
297
- return res.status(403).json({ message: "لا يوجد مستأجر مرتبط بهذا الحساب" });
298
- }
299
- if (!Array.isArray(items) || items.length === 0) {
300
- return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
- let finalCustomerId = customerId;
304
- if (!finalCustomerId && customerName) {
305
- createdCustomer = await Customer.create({
306
- name: customerName.trim(),
307
- tenant: tenantId,
308
- branch: branchId,
309
- createdBy: req.user._id,
310
- });
311
- finalCustomerId = createdCustomer._id;
312
  }
313
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  try {
315
- await validateCatalogItems(items, tenantId, branchId);
316
- await ensureStockAvailability(items, tenantId, branchId);
317
-
318
- let customer;
319
- if (finalCustomerId) {
320
- customer = await Customer.findOne({ _id: finalCustomerId, tenant: tenantId, branch: branchId });
321
- if (!customer) throw new Error("العميل المحدد غير موجود");
322
- } else {
323
- customer = await getOrCreateWalkInCustomer(tenantId, branchId, req.user._id);
324
- }
325
-
326
- const invoice = new Invoice({
327
- tenant: tenantId,
328
- branch: branchId,
329
- customer: customer._id,
330
- issuedBy: req.user._id,
331
- notes: notes.trim(),
332
- discount: Math.max(Number(discount) || 0, 0),
333
- taxAmount: Math.max(Number(tax) || 0, 0),
334
- });
335
-
336
- await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);
337
-
338
- let saved = false;
339
- for (let i = 0; i < 3; i++) {
340
- try {
341
- invoice.invoiceNumber = await generateInvoiceNumber(tenantId, branchId);
342
- invoice.calculateTotals();
343
- await invoice.save();
344
- saved = true;
345
- break;
346
- } catch (saveErr) {
347
- if (saveErr.code === 11000 && i < 2) continue;
348
- throw saveErr;
349
- }
350
- }
351
- if (!saved) throw new Error("تعذر حفظ الفاتورة لخطأ تزامن بالرقم");
352
-
353
- const paymentAmount = Number(paidAmount);
354
- if (!paymentAmount || Number(paymentAmount.toFixed(2)) !== Number(invoice.totalAmount.toFixed(2))) {
355
- throw new Error("فاتورة الزائر يجب أن تكون نقدية بالكامل، ويجب أن يساوي المبلغ المدفوع إجمالي الفاتورة");
356
- }
357
-
358
- invoice.payments.push({
359
- amount: paymentAmount,
360
- method: "cash",
361
- receivedBy: req.user._id,
362
- });
363
-
364
- await invoice.save();
365
- await createIncomeForPayment({
366
- tenantId,
367
- branchId,
368
- invoice,
369
- customer,
370
- amount: paymentAmount,
371
- userId: req.user._id,
372
- notes: "Walk-in cash sale",
373
- paymentMethod: "cash",
374
- });
375
-
376
- const populatedInvoice = await Invoice.findById(invoice._id).populate("customer", "name isWalkIn");
377
- res.status(201).json(populatedInvoice);
378
  } catch (err) {
379
- if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
380
- throw err;
 
 
 
 
 
 
 
 
381
  }
382
- } catch (err) {
383
- if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
384
- res.status(err.statusCode || 500).json({ message: err.message });
385
- }
 
 
 
 
 
386
  };
387
 
388
- export const getInvoices = async (req, res) => {
389
- try {
390
- const page = parseInt(req.query.page) || 1;
391
- const limit = parseInt(req.query.limit) || 5;
392
- const skip = (page - 1) * limit;
393
- const search = req.query.search || "";
394
- const { tenantId, branchFilter } = await resolveScopedBranch(req);
395
-
396
- const query = { tenant: tenantId, ...branchFilter };
397
- if (search) {
398
- query.invoiceNumber = { $regex: search, $options: "i" };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
  }
400
- if (req.query.method) {
401
- query["payments.method"] = req.query.method;
 
 
 
 
 
 
 
 
 
402
  }
403
 
404
- const total = await Invoice.countDocuments(query);
405
- const invoices = await Invoice.find(query)
406
- .populate("customer")
407
- .sort({ createdAt: -1 })
408
- .skip(skip)
409
- .limit(limit);
410
-
411
- res.status(200).json({
412
- data: invoices,
413
- pagination: {
414
- total,
415
- page,
416
- limit,
417
- totalPages: Math.ceil(total / limit),
418
- },
419
- });
420
- } catch (err) {
421
- res.status(500).json({ message: err.message });
422
- }
423
- };
424
 
425
- export const getInvoicesByCustomer = async (req, res) => {
426
- try {
427
- const invoices = await Invoice.find({
428
- customer: req.params.customerId,
429
- tenant: req.user.tenant._id,
430
- ...(await resolveScopedBranch(req)).branchFilter,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431
  });
432
 
433
- res.json(invoices);
434
- } catch (err) {
435
- res.status(500).json({ message: err.message });
436
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  };
438
 
439
- export const getInvoiceById = async (req, res) => {
440
- try {
441
- const { id } = req.params;
442
- const { branchFilter } = await resolveScopedBranch(req);
443
-
444
- const invoice = await Invoice.findOne({
445
- _id: id,
446
- tenant: req.user.tenant._id,
447
- ...branchFilter,
448
- })
449
- .populate("customer", "name isWalkIn")
450
- .populate({
451
- path: "items.productId",
452
- select: "name price",
453
- })
454
- .populate({
455
- path: "items.catalogItemId",
456
- select: "name price",
457
- });
458
-
459
- if (!invoice) {
460
- return res.status(404).json({ message: "الفاتورة غير موجودة" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
 
463
- res.status(200).json(invoice);
464
- } catch (error) {
465
- res.status(500).json({ message: error.message });
466
- }
 
 
 
 
467
  };
468
 
469
- export const updateInvoiceItem = async (req, res) => {
470
- try {
471
- const { invoiceId, itemId } = req.params;
472
- const { name, quantity, price } = req.body;
473
- const { branchFilter } = await resolveScopedBranch(req);
474
-
475
- const invoice = await Invoice.findOne({
476
- _id: invoiceId,
477
- tenant: req.user.tenant._id,
478
- ...branchFilter,
479
- }).populate("customer", "isWalkIn");
480
-
481
- if (!invoice) {
482
- return res.status(404).json({ message: "الفاتورة غير موجودة" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  }
484
 
485
- const item = invoice.items.id(itemId);
486
- if (!item) {
487
- return res.status(404).json({ message: "بند الفاتورة غير موجود" });
488
- }
 
 
 
 
 
 
 
 
489
 
490
- const newQuantity = Number(quantity);
491
- const newPrice = Number(price);
492
 
493
- if (item.type === "catalog" && item.catalogItemId) {
494
- const catalogItem = await CatalogItem.findOne({
495
- _id: item.catalogItemId,
496
- tenant: req.user.tenant._id,
497
- ...branchFilter,
498
- });
499
-
500
- if (!catalogItem) {
501
- return res.status(404).json({ message: "عنصر الكتالوج المرتبط لم يعد موجودًا" });
502
- }
503
-
504
- item.name = catalogItem.name;
505
- item.quantity = newQuantity;
506
- item.price = Number(catalogItem.price || 0);
507
- item.total = item.quantity * item.price;
508
- await invoice.save();
509
-
510
- return res.status(200).json({
511
- message: "تم تحديث بند الكتالوج بنجاح",
512
- invoice,
513
- });
514
  }
515
-
516
- if (item.productId) {
517
- const quantityDifference = newQuantity - Number(item.quantity);
518
- const product = await Product.findOne({
519
- _id: item.productId,
520
- tenant: req.user.tenant._id,
521
- ...branchFilter,
522
- });
523
-
524
- if (!product) {
525
- return res.status(404).json({ message: "المنتج المرتبط لم يعد موجودًا" });
526
- }
527
-
528
- if (quantityDifference > 0 && product.stock < quantityDifference) {
529
- return res.status(400).json({ message: "المخزون الحالي غير كافٍ لهذا التعديل في الكمية" });
530
- }
531
-
532
- if (quantityDifference !== 0) {
533
- await Product.findOneAndUpdate(
534
- { _id: item.productId, tenant: req.user.tenant._id, ...branchFilter },
535
- { $inc: { stock: -quantityDifference } }
536
- );
537
- }
538
  }
539
 
540
- item.name = name;
541
- item.quantity = newQuantity;
542
- item.price = newPrice;
543
- item.total = newQuantity * newPrice;
 
 
 
 
 
 
 
544
 
545
  await invoice.save();
546
 
547
- res.status(200).json({
548
- message: "تم تحديث بند الفاتورة بنجاح",
549
- invoice,
550
- });
551
- } catch (error) {
552
- res.status(500).json({ message: error.message });
553
- }
554
- };
555
-
556
- export const deleteInvoiceItem = async (req, res) => {
557
- try {
558
- const { invoiceId, itemId } = req.params;
559
- const { branchFilter } = await resolveScopedBranch(req);
560
-
561
- const invoice = await Invoice.findOne({
562
- _id: invoiceId,
563
- tenant: req.user.tenant._id,
564
- ...branchFilter,
565
- }).populate("customer", "isWalkIn");
566
-
567
- if (!invoice) {
568
- return res.status(404).json({ message: "الفاتورة غير موجودة" });
569
  }
570
 
571
- const item = invoice.items.id(itemId);
572
- if (!item) {
573
- return res.status(404).json({ message: "المنتج المرتبط لم يعد موجودًا" });
 
 
 
 
 
 
574
  }
575
 
576
- if (item.productId) {
577
- await Product.findOneAndUpdate(
578
- { _id: item.productId, tenant: req.user.tenant._id, ...branchFilter },
579
- { $inc: { stock: Number(item.quantity) } }
580
- );
581
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
582
 
583
- item.deleteOne();
584
- await invoice.save();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
585
 
586
- res.json(invoice);
587
- } catch (error) {
588
- res.status(500).json({ message: error.message });
589
- }
 
 
 
 
 
 
 
 
590
  };
591
 
592
- export const payInvoice = async (req, res) => {
593
- try {
594
- const { customerId } = req.params;
595
- const amount = Number(req.body.amount);
596
- const { invoiceId, paymentMethod = "cash", transferType } = req.body;
597
- const { branchId, branchFilter } = await resolveScopedBranch(req);
598
-
599
- if (!amount || amount <= 0) {
600
- return res.status(400).json({ message: "يجب أن يكون مبلغ الدفع أكبر من صفر" });
601
- }
 
 
 
 
 
 
 
 
 
602
 
603
- if (paymentMethod === "transfer" && !transferType) {
604
- return res.status(400).json({ message: "نوع التحويل مطلوب للدفع بالتحويل" });
605
- }
606
 
607
- // ✅ FIX 2: If invoiceId is provided, target that exact invoice.
608
- // Otherwise fall back to the old behaviour (first open/partial invoice).
609
- const query = invoiceId
610
- ? {
611
- _id: invoiceId,
612
- customer: customerId,
613
- tenant: req.user.tenant._id,
614
- ...branchFilter,
615
- }
616
- : {
617
- customer: customerId,
618
- tenant: req.user.tenant._id,
619
- ...branchFilter,
620
- status: { $in: ["open", "partial"] },
621
- };
622
 
623
- const invoice = await Invoice.findOne(query).populate("customer", "name isWalkIn");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624
 
625
- if (!invoice || invoice.remainingAmount <= 0) {
626
- return res.status(404).json({ message: "لا توجد فاتورة غير مسددة لهذا العميل" });
627
  }
628
 
629
- if (invoice.customer?.isWalkIn) {
630
- return res.status(400).json({
631
- message: "فاتورة العميل الزائر يجب سدادها بالكامل وقت الإنشاء",
632
- });
633
- }
634
 
635
- if (amount > invoice.remainingAmount) {
636
- return res.status(400).json({ message: "لا يمكن أن يتجاوز مبلغ الدفع الرصيد المتبقي" });
637
- }
638
 
639
- invoice.payments.push({
640
- amount,
641
- method: paymentMethod,
642
- transferType: paymentMethod === "transfer" ? transferType : null,
643
- receivedBy: req.user._id,
644
- confirmed: paymentMethod === "cash" ? true : false,
 
 
 
 
 
 
 
 
 
 
 
645
  });
646
 
647
- await invoice.save();
 
 
648
 
649
- // Only create income for confirmed payments (cash is auto-confirmed).
650
- // Transfer payments remain pending until confirmed via confirmPayment.
651
- if (paymentMethod === "cash") {
652
- await createIncomeForPayment({
653
- tenantId: req.user.tenant._id,
654
- branchId: invoice.branch || branchId || null,
655
- invoice,
656
- customer: invoice.customer,
657
- amount,
658
- userId: req.user._id,
659
- paymentMethod,
660
- transferType,
661
- });
662
  }
663
 
664
- res.json(invoice);
665
- } catch (err) {
666
- res.status(500).json({ message: err.message });
667
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668
  };
669
 
670
- export const confirmPayment = async (req, res) => {
671
- try {
672
- const { invoiceId, paymentIndex } = req.params;
673
- const tenantId = req.user.tenant._id;
674
- const { branchFilter } = await resolveScopedBranch(req);
675
-
676
- const invoice = await Invoice.findOne({
677
- _id: invoiceId,
678
- tenant: tenantId,
679
- ...branchFilter,
680
- }).populate("customer", "name isWalkIn");
681
-
682
- if (!invoice) {
683
- return res.status(404).json({ message: "الفاتورة غير موجودة" });
684
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685
 
686
- const payment = invoice.payments[paymentIndex];
687
- if (!payment) {
688
- return res.status(404).json({ message: "الدفع غير موجود" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
689
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
690
 
691
- if (payment.method !== "transfer") {
692
- return res.status(400).json({ message: "فقط دفعات التحويل تحتاج إلى تأكيد" });
693
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
694
 
695
- payment.confirmed = !payment.confirmed;
696
- if (payment.confirmed) {
697
- payment.confirmedBy = req.user._id;
698
- payment.confirmedAt = new Date();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
699
 
700
- // Create income records now that the transfer is confirmed
701
- await createIncomeForPayment({
702
- tenantId,
703
- branchId: invoice.branch || null,
704
- invoice,
705
- customer: invoice.customer,
706
- amount: payment.amount,
707
- userId: req.user._id,
708
- paymentMethod: "transfer",
709
- transferType: payment.transferType,
710
- date: payment.confirmedAt,
711
- });
712
- } else {
713
- payment.confirmedBy = null;
714
- payment.confirmedAt = null;
715
-
716
- // Remove income records for this unconfirmed transfer
717
- await Income.deleteMany({
718
- tenant: tenantId,
719
- sourceType: "invoice_payment",
720
- relatedInvoice: invoice._id,
721
- paymentMethod: "transfer",
722
- amount: payment.amount,
723
- });
724
- }
725
 
726
- await invoice.save();
727
- res.json(invoice);
728
- } catch (err) {
729
- res.status(500).json({ message: err.message });
730
- }
731
  };
732
 
733
  export const updateInvoice = async (req, res) => {
734
- try {
735
- console.log("=== UPDATE INVOICE START ===");
736
- const { invoiceId } = req.params;
737
- const { items, discount, tax, notes } = req.body;
738
- console.log("Request data:", { invoiceId, items, discount, tax, notes });
739
- const tenantId = req.user.tenant._id;
740
- const { branchFilter } = await resolveScopedBranch(req);
741
-
742
- console.log("Finding invoice with query:", { _id: invoiceId, tenant: tenantId, ...branchFilter });
743
- const invoice = await Invoice.findOne({
744
- _id: invoiceId,
745
- tenant: tenantId,
746
- ...branchFilter,
747
- }).populate("customer", "isWalkIn");
748
-
749
- console.log("Found invoice:", invoice);
750
- if (!invoice) {
751
- console.log("Invoice not found!");
752
- return res.status(404).json({ message: "Invoice not found" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  }
 
754
 
755
- console.log("Current invoice items before update:", invoice.items);
756
-
757
- // Reverse stock for existing product items
758
- console.log("Reversing stock for existing items...");
759
- for (const oldItem of invoice.items) {
760
- if (oldItem.productId) {
761
- console.log(`Reversing stock for product ${oldItem.productId}: +${oldItem.quantity}`);
762
- await Product.findOneAndUpdate(
763
- { _id: oldItem.productId, tenant: tenantId, ...branchFilter },
764
- { $inc: { stock: Number(oldItem.quantity) } }
765
- );
766
- }
767
- }
768
 
769
- // Clear old items and add new items directly
770
- console.log("Clearing old items and adding new items...");
771
- invoice.items = [];
772
- for (const item of items) {
773
- const quantity = Number(item.quantity || 0);
774
- const price = Number(item.price || 0);
775
-
776
- console.log(`Processing item: ${item.name}, qty: ${quantity}, price: ${price}`);
777
-
778
- // Deduct stock for product items
779
- if (item.productId) {
780
- console.log(`Deducting stock for product ${item.productId}: -${quantity}`);
781
- await Product.findOneAndUpdate(
782
- { _id: item.productId, tenant: tenantId, ...branchFilter },
783
- { $inc: { stock: -quantity } }
784
- );
785
- }
786
-
787
- const newItem = {
788
- name: item.name,
789
- quantity,
790
- price,
791
- total: quantity * price,
792
- type: item.type || 'product',
793
- productId: item.productId || null,
794
- catalogItemId: item.catalogItemId || null,
795
- serviceId: item.serviceId || null,
796
- };
797
-
798
- console.log("Adding new item to invoice:", newItem);
799
- invoice.items.push(newItem);
800
  }
801
 
802
- console.log("Invoice items after update:", invoice.items);
 
 
 
 
 
 
 
 
 
 
 
 
 
803
 
804
- // Update discount, tax, notes
805
- console.log("Updating discount, tax, notes:", { discount, tax, notes });
806
- invoice.discount = Math.max(Number(discount) || 0, 0);
807
- invoice.taxAmount = Math.max(Number(tax) || 0, 0);
808
- if (notes !== undefined) invoice.notes = notes.trim();
809
 
810
- console.log("Calculating totals and saving...");
811
- invoice.calculateTotals();
812
- await invoice.save();
 
 
 
 
 
 
813
 
814
- console.log("Invoice saved successfully:", invoice);
815
- res.json(invoice);
816
- } catch (err) {
817
- res.status(err.statusCode || 500).json({ message: err.message });
818
- }
819
  };
820
 
821
  export const deleteInvoice = async (req, res) => {
822
- try {
823
- const { invoiceId } = req.params;
824
- const tenantId = req.user.tenant._id;
825
- const { branchFilter } = await resolveScopedBranch(req);
826
-
827
- const invoice = await Invoice.findOne({
828
- _id: invoiceId,
829
- tenant: tenantId,
830
- ...branchFilter,
831
- }).populate("customer", "isWalkIn");
832
-
833
- if (!invoice) {
834
- return res.status(404).json({ message: "Invoice not found" });
 
 
 
 
 
 
 
 
 
835
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
836
 
837
- // Restore stock for product items
838
- for (const item of invoice.items) {
839
- if (item.productId) {
840
- await Product.findOneAndUpdate(
841
- { _id: item.productId, tenant: tenantId, ...branchFilter },
842
- { $inc: { stock: Number(item.quantity) } }
843
- );
844
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
845
  }
846
 
847
- // Delete related income records
848
- await Income.deleteMany({
849
- tenant: tenantId,
850
- sourceType: "invoice_payment",
851
- relatedInvoice: invoice._id,
 
 
 
852
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
853
 
854
- // Delete the invoice
855
- await Invoice.findByIdAndDelete(invoiceId);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
856
 
857
- res.json({ message: "Invoice deleted successfully" });
858
- } catch (err) {
859
- res.status(err.statusCode || 500).json({ message: err.message });
860
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861
  };
 
4
  import CatalogItem from "../models/CatalogItemModel.js";
5
  import Counter from "../models/CounterModel.js";
6
  import Income from "../models/IncomeModel.js";
7
+ import Tenant from "../models/TenantModel.js";
8
+ import WhatsAppService from "../utils/whatsappService.js";
9
+ import User from "../models/UserModel.js";
10
+ import Driver from "../models/DriverModel.js";
11
+ import Table from "../models/TableModel.js"; // ✅ was missing — needed for table validation
12
+ import mongoose from "mongoose";
13
+ import {
14
+ resolveBranchForWrite,
15
+ resolveScopedBranch,
16
+ } from "../utils/branchContext.js";
17
 
18
  const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";
19
 
20
  const INVOICE_ITEM_TYPES = ["product", "service", "catalog"];
21
 
22
+ const buildOrderMessage = ({
23
+ status,
24
+ orderNumber,
25
+ restaurantName,
26
+ itemsList,
27
+ driverName,
28
+ driverPhone,
29
+ orderType,
30
+ }) => {
31
+ switch (status) {
32
+ case "pending":
33
+ return `🧾 تم استلام طلبك رقم #${orderNumber} في ${restaurantName}\n\nجاري المراجعة الآن.`;
34
 
35
+ case "preparing":
36
+ return `👨‍🍳 طلبك رقم #${orderNumber} قيد التحضير الآن في ${restaurantName}\n\n${itemsList}`;
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ case "ready_for_delivery":
39
+ return `🍽️ طلبك رقم #${orderNumber} جاهز الآن للاستلام من ${restaurantName}`;
40
 
41
+ case "shipped":
42
+ return orderType === "delivery"
43
+ ? `🚚 طلبك رقم #${orderNumber} في الطريق إليك\n\nالسائق: ${driverName}\nرقم الهاتف: ${driverPhone}`
44
+ : `🚶 طلبك رقم #${orderNumber} جاهز للاستلام`;
 
 
 
 
 
 
 
 
 
45
 
46
+ default:
47
+ return `📦 تحديث على طلبك رقم #${orderNumber}`;
48
+ }
49
  };
50
 
51
+ async function generateInvoiceNumber(tenantId, branchId) {
52
+ const counter = await Counter.findOneAndUpdate(
53
+ { tenant: tenantId, branch: branchId },
54
+ { $inc: { invoiceNumber: 1 } },
55
+ {
56
+ new: true,
57
+ upsert: true,
58
+ setDefaultsOnInsert: true,
59
+ },
60
+ );
61
+
62
+ const padded = String(counter.invoiceNumber).padStart(5, "0");
63
+ return `INV-${padded}`;
64
+ }
65
 
66
+ const getOrCreateWalkInCustomer = async (tenantId, branchId, userId) => {
67
+ let customer = await Customer.findOne({
68
+ tenant: tenantId,
69
+ branch: branchId,
70
+ isWalkIn: true,
71
+ });
72
+
73
+ if (!customer) {
74
+ customer = await Customer.create({
75
+ tenant: tenantId,
76
+ branch: branchId,
77
+ name: WALK_IN_CUSTOMER_NAME,
78
+ isWalkIn: true,
79
+ notes: "System generated customer for walk-in cash sales.",
80
+ createdBy: userId || null,
81
+ });
82
+ }
83
+
84
+ return customer;
85
+ };
86
 
87
+ const ensureStockAvailability = async (items, tenantId, branchId) => {
88
+ for (const item of items) {
89
+ if (item.type !== "product" || !item.productId) {
90
+ continue;
91
+ }
92
+
93
+ const product = await Product.findOne({
94
+ _id: item.productId,
95
+ tenant: tenantId,
96
+ branch: branchId,
97
+ });
98
+ if (!product) {
99
+ const error = new Error(`المنتج غير موجود: ${item.name}`);
100
+ error.statusCode = 404;
101
+ throw error;
102
+ }
103
+
104
+ if (product.stock < Number(item.quantity)) {
105
+ const error = new Error(
106
+ `المخ��ون غير كافٍ للصنف ${item.name}. المتاح: ${product.stock}`,
107
+ );
108
+ error.statusCode = 400;
109
+ throw error;
110
+ }
111
+ }
112
  };
113
 
114
  const validateCatalogItems = async (items, tenantId, branchId) => {
115
+ for (const item of items) {
116
+ if (item.type !== "catalog" || !item.catalogItemId) {
117
+ continue;
118
+ }
119
+
120
+ const catalogItem = await CatalogItem.findOne({
121
+ _id: item.catalogItemId,
122
+ tenant: tenantId,
123
+ branch: branchId,
124
+ isActive: true,
125
+ }).populate("category", "name");
126
+
127
+ if (!catalogItem) {
128
+ const error = new Error(`عنصر الكتالوج غير موجود: ${item.name}`);
129
+ error.statusCode = 404;
130
+ throw error;
131
+ }
132
+ }
133
+ };
134
 
135
+ const applyInvoiceItemsAndStock = async (
136
+ invoice,
137
+ items,
138
+ tenantId,
139
+ branchId,
140
+ ) => {
141
+ for (const item of items) {
142
+ const quantity = Number(item.quantity || 0);
143
+ const normalizedType = INVOICE_ITEM_TYPES.includes(item.type)
144
+ ? item.type
145
+ : item.productId
146
+ ? "product"
147
+ : "service";
148
+ let resolvedName = item.name;
149
+ let resolvedPrice = Number(item.price || 0);
150
+
151
+ if (normalizedType === "catalog" && item.catalogItemId) {
152
  const catalogItem = await CatalogItem.findOne({
153
+ _id: item.catalogItemId,
154
+ tenant: tenantId,
155
+ branch: branchId,
156
+ });
 
157
 
158
  if (!catalogItem) {
159
+ const error = new Error(`عنصر الكتالوج غير موجود: ${item.name}`);
160
+ error.statusCode = 404;
161
+ throw error;
162
  }
 
 
163
 
164
+ resolvedName = catalogItem.name;
165
+ resolvedPrice = Number(catalogItem.price || 0);
166
+ }
167
+
168
+ invoice.items.push({
169
+ name: resolvedName,
170
+ quantity,
171
+ price: resolvedPrice,
172
+ total: quantity * resolvedPrice,
173
+ type: normalizedType,
174
+ ...(item.productId ? { productId: item.productId } : {}),
175
+ ...(item.serviceId ? { serviceId: item.serviceId } : {}),
176
+ ...(item.catalogItemId ? { catalogItemId: item.catalogItemId } : {}),
177
+ });
178
+
179
+ if (normalizedType === "product" && item.productId) {
180
+ await Product.findOneAndUpdate(
181
+ { _id: item.productId, tenant: tenantId, branch: branchId },
182
+ { $inc: { stock: -quantity } },
183
+ );
184
+ }
185
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  };
187
 
188
  const createIncomeForPayment = async ({
189
+ tenantId,
190
+ branchId,
191
+ invoice,
192
+ customer,
193
+ amount,
194
+ userId,
195
+ date,
196
+ notes,
197
+ paymentMethod = "cash",
198
+ transferType = null,
199
  }) => {
200
+ if (!amount || amount <= 0) {
201
+ return;
202
+ }
203
+
204
+ // If the invoice has services, calculate the ratio and split the income record
205
+ const revenueBuckets = [
206
+ {
207
+ amount: Number(invoice.serviceRevenue || 0),
208
+ category: "service_income",
209
+ title: `Service Income - ${invoice.invoiceNumber}`,
210
+ notesFallback: `Service portion for invoice ${invoice.invoiceNumber}`,
211
+ },
212
+ {
213
+ amount: Number(invoice.catalogRevenue || 0),
214
+ category: "catalog_sale",
215
+ title: `Catalog Sale - ${invoice.invoiceNumber}`,
216
+ notesFallback: `Catalog portion for invoice ${invoice.invoiceNumber}`,
217
+ },
218
+ {
219
+ amount: Number(invoice.productRevenue || 0),
220
+ category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment",
221
+ title: `Invoice payment - ${invoice.invoiceNumber}`,
222
+ notesFallback: `Product portion for invoice ${invoice.invoiceNumber}`,
223
+ },
224
+ ].filter((bucket) => bucket.amount > 0);
225
+
226
+ const totalItemRevenue = revenueBuckets.reduce(
227
+ (sum, bucket) => sum + bucket.amount,
228
+ 0,
229
+ );
230
+
231
+ if (!totalItemRevenue) {
232
+ return;
233
+ }
234
+
235
+ let remainingAmount = Number(amount);
236
+ const incomesToCreate = revenueBuckets
237
+ .map((bucket, index) => {
238
  const isLastBucket = index === revenueBuckets.length - 1;
239
  const allocatedAmount = isLastBucket
240
+ ? Number(remainingAmount.toFixed(2))
241
+ : Number(
242
+ ((Number(amount) * bucket.amount) / totalItemRevenue).toFixed(2),
243
+ );
244
 
245
  remainingAmount = Number((remainingAmount - allocatedAmount).toFixed(2));
246
 
247
  return {
248
+ tenant: tenantId,
249
+ branch: branchId,
250
+ title: bucket.title,
251
+ category: bucket.category,
252
+ amount: allocatedAmount,
253
+ paymentMethod,
254
+ notes: notes || bucket.notesFallback,
255
+ sourceType: "invoice_payment",
256
+ relatedInvoice: invoice._id,
257
+ relatedCustomer: customer?._id || null,
258
+ date: date || new Date(),
259
+ createdBy: userId || null,
260
  };
261
+ })
262
+ .filter((entry) => entry.amount > 0);
263
 
264
+ if (incomesToCreate.length) {
265
+ await Income.insertMany(incomesToCreate);
266
+ }
267
  };
268
 
269
  export const addItemToInvoice = async (req, res) => {
270
+ let createdCustomer = null;
271
+ try {
272
+ const { customerId } = req.params;
273
+ const {
274
+ items,
275
+ customerName,
276
+ notes = "",
277
+ discount = 0,
278
+ tax = 0,
279
+ restaurantData,
280
+ serviceCharge = 0,
281
+ deliveryCharge = 0,
282
+ } = req.body;
283
+ const tenantId = req.user.tenant?._id;
284
+ const branch = await resolveBranchForWrite(req);
285
+ const branchId = branch._id;
286
+
287
+ if (!tenantId) {
288
+ return res
289
+ .status(403)
290
+ .json({ message: "لا يوجد مستأجر مرتبط بهذا الحساب" });
291
+ }
292
+ if (!Array.isArray(items) || items.length === 0) {
293
+ return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
294
+ }
295
+
296
+ let finalCustomerId = customerId;
297
+ if (customerId === "new") {
298
+ if (!customerName)
299
+ return res
300
+ .status(400)
301
+ .json({ message: "اسم العميل مطلوب لإنشاء حساب جديد" });
302
+ createdCustomer = await Customer.create({
303
+ name: customerName.trim(),
304
+ tenant: tenantId,
305
+ branch: branchId,
306
+ createdBy: req.user._id,
307
+ });
308
+ finalCustomerId = createdCustomer._id;
309
+ }
310
+
311
+ const customer = await Customer.findOne({
312
+ _id: finalCustomerId,
313
+ tenant: tenantId,
314
+ branch: branchId,
315
+ });
316
+ if (!customer) {
317
+ if (createdCustomer)
318
+ await Customer.deleteOne({ _id: createdCustomer._id });
319
+ return res.status(404).json({ message: "العميل غير موجود" });
320
+ }
321
+ if (customer.isWalkIn) {
322
+ if (createdCustomer)
323
+ await Customer.deleteOne({ _id: createdCustomer._id });
324
+ return res.status(400).json({
325
+ message: "استخدم مسار بيع الزائر النقدي لفواتير العملاء الزائرين",
326
+ });
327
+ }
328
+
329
+ try {
330
+ // ✅ Validate table availability BEFORE creating invoice
331
+ if (restaurantData?.orderType === "dine-in" && restaurantData?.table) {
332
+ const existingTable = await Table.findById(restaurantData.table);
333
+ if (!existingTable) {
334
+ return res.status(404).json({ message: "الطاولة المحددة غير موجودة" });
335
+ }
336
+ if (existingTable.status === "occupied") {
337
+ return res.status(400).json({
338
+ message: "هذه الطاولة مشغولة حالياً — يرجى إتمام الحساب أولاً أو اختيار طاولة أخرى",
339
+ });
340
+ }
341
  }
342
 
343
+ const invoice = new Invoice({
344
+ tenant: tenantId,
345
+ branch: branchId,
346
+ customer: finalCustomerId,
347
+ issuedBy: req.user._id,
348
+ notes: notes.trim(),
349
+ discount: Math.max(Number(discount) || 0, 0),
350
+ taxAmount: Math.max(Number(tax) || 0, 0),
351
+ serviceCharge: Math.max(Number(serviceCharge) || 0, 0),
352
+ deliveryCharge: Math.max(Number(deliveryCharge) || 0, 0),
353
+ restaurantData: restaurantData || null,
354
+ });
355
 
356
+ await validateCatalogItems(items, tenantId, branchId);
357
+ await ensureStockAvailability(items, tenantId, branchId);
358
+ await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);
359
+
360
+ // Robust duplicate key retry logic for missing/corrupted counters
361
+ let saved = false;
362
+ for (let i = 0; i < 3; i++) {
363
+ try {
364
+ invoice.invoiceNumber = await generateInvoiceNumber(
365
+ tenantId,
366
+ branchId,
367
+ );
368
+ invoice.calculateTotals();
369
+ await invoice.save();
370
+ saved = true;
371
+ break;
372
+ } catch (saveErr) {
373
+ if (saveErr.code === 11000 && i < 2) continue;
374
+ throw saveErr;
375
+ }
376
  }
377
 
378
+ if (!saved) throw new Error("تعذر حفظ الفاتورة لخطأ تزامن، حاول مجدداً");
379
+
380
+ // ✅ Lock table after successful invoice creation
381
+ if (restaurantData?.orderType === "dine-in" && restaurantData?.table) {
382
+ await Table.findByIdAndUpdate(restaurantData.table, {
383
+ status: "occupied",
384
+ currentOrderId: invoice._id,
385
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
  }
387
+ res.status(200).json(invoice);
388
+ } catch (err) {
389
+ if (createdCustomer)
390
+ await Customer.deleteOne({ _id: createdCustomer._id });
391
+ throw err; // cascade to main catch block
392
+ }
393
+ } catch (err) {
394
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
395
+ res.status(err.statusCode || 500).json({ message: err.message });
396
+ }
397
  };
398
 
399
+ export const updateRestaurantStatus = async (req, res) => {
400
+ try {
401
+ const { invoiceId } = req.params;
402
+ const { status } = req.body;
403
+
404
+ const allowedStatuses = [
405
+ "pending",
406
+ "preparing",
407
+ "ready_for_delivery",
408
+ "shipped",
409
+ ];
410
+
411
+ if (!allowedStatuses.includes(status)) {
412
+ return res.status(400).json({ message: "حالة غير صالحة" });
413
+ }
414
+
415
+ const invoice = await Invoice.findById(invoiceId);
416
+ if (!invoice) {
417
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
418
+ }
419
+
420
+ const currentStatus = invoice.restaurantStatus || "pending";
421
+ const currentIndex = allowedStatuses.indexOf(currentStatus);
422
+ const targetIndex = allowedStatuses.indexOf(status);
423
+
424
+ if (currentIndex !== -1 && targetIndex < currentIndex) {
425
+ return res.status(400).json({ message: "لا يمكن الرجوع لحالة سابقة" });
426
+ }
427
+
428
+ // DELIVERY VALIDATION BEFORE SHIPPING
429
+ if (
430
+ invoice.restaurantData?.orderType === "delivery" &&
431
+ status === "shipped"
432
+ ) {
433
+ const driver = invoice.restaurantData?.driver;
434
+
435
+ if (!driver?.driverId && !driver?.driverUserId) {
436
+ return res.status(400).json({
437
+ message: "يجب تعيين سائق قبل شحن طلب التوصيل",
438
+ });
439
  }
440
+ }
441
+
442
+ invoice.restaurantStatus = status;
443
+ await invoice.save();
444
+
445
+ if (
446
+ status === "shipped" &&
447
+ invoice.restaurantData?.orderType === "delivery" &&
448
+ invoice.restaurantData?.driver?.driverId
449
+ ) {
450
+ const assignedDriver = await Driver.findOne({
451
+ _id: invoice.restaurantData.driver.driverId,
452
+ tenant: invoice.tenant,
453
+ isActive: true,
454
+ });
455
 
456
+ if (assignedDriver) {
457
+ assignedDriver.currentOrderIds = (assignedDriver.currentOrderIds || []).filter(
458
+ (orderId) => orderId.toString() !== invoice._id.toString(),
459
+ );
460
+ assignedDriver.currentOrders = assignedDriver.currentOrderIds.length;
461
+ assignedDriver.status = assignedDriver.currentOrders > 0 ? "busy" : "available";
462
+ await assignedDriver.save();
 
 
463
  }
464
+ }
465
+
466
+ // RELEASE TABLE ONLY FOR NON-DINE-IN ORDERS.
467
+ // A dine-in table must ONLY be released computationally when remainingAmount reaches 0 during Payment!
468
+ const isDineIn = invoice.restaurantData?.orderType === "dine-in";
469
+ if (
470
+ invoice.restaurantData?.table && !isDineIn &&
471
+ (status === "shipped" || status === "ready_for_delivery")
472
+ ) {
473
+ await Table.findByIdAndUpdate(invoice.restaurantData.table, {
474
+ status: "available",
475
+ currentOrderId: null,
476
+ });
477
+ }
478
+
479
+ // WHATSAPP NOTIFICATION
480
+ // ✅ Fixed: dine-in orders now also get notifications for key status changes
481
+ const orderType = invoice.restaurantData?.orderType;
482
+ const isEligible =
483
+ orderType === "takeaway" ||
484
+ orderType === "delivery" ||
485
+ (isDineIn && (status === "preparing" || status === "ready_for_delivery"));
486
+ let phoneNumber = null
487
+ if (isEligible) {
488
  try {
489
+ phoneNumber = invoice.restaurantData?.guestInfo?.phone;
490
+ if (!phoneNumber && invoice.customer) {
491
+ const customer = await Customer.findById(invoice.customer);
492
+ phoneNumber = customer?.phone || null;
493
+ }
494
+
495
+ if (phoneNumber) {
496
+ const tenant = await Tenant.findById(invoice.tenant).select("name");
497
+
498
+ const restaurantName = tenant?.name || "";
499
+
500
+ const itemsList = (invoice.items || [])
501
+ .map((i) => `- ${i.name} × ${i.quantity}`)
502
+ .join("\n");
503
+
504
+ const driver = invoice.restaurantData?.driver || {};
505
+ const driverName = driver.driverName || "";
506
+ const driverPhone = driver.driverPhone || "";
507
+
508
+ // ✅ Use dine-in-ready for dine-in ready_for_delivery status
509
+ const notificationType =
510
+ isDineIn && status === "ready_for_delivery"
511
+ ? "dine-in-ready"
512
+ : status;
513
+
514
+ const totalFormatted = `${invoice.totalAmount?.toFixed(2) || ""} ${invoice.tenant?.currency || ""}`;
515
+
516
+ await WhatsAppService.queueNotification({
517
+ tenant: invoice.tenant,
518
+ order: invoice._id,
519
+ customer: invoice.customer || null,
520
+ phoneNumber,
521
+ notificationType,
522
+ orderNumber: invoice.invoiceNumber,
523
+ restaurantName,
524
+ total: totalFormatted,
525
+ itemsList,
526
+ driverName,
527
+ driverPhone,
528
+ language: "ar",
529
+ });
530
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  } catch (err) {
532
+ console.error("[WhatsApp] Notification failed:", {
533
+ error: err.message,
534
+ invoiceId,
535
+ status,
536
+
537
+ phoneNumber,
538
+ notificationType: status,
539
+ });
540
+ // Don't fail the status update - just log the error
541
+ // This ensures order status changes work even if WhatsApp fails
542
  }
543
+ }
544
+
545
+ return res.status(200).json({
546
+ message: "تم تحديث حالة الطلب بنجاح",
547
+ invoice,
548
+ });
549
+ } catch (error) {
550
+ return res.status(500).json({ message: error.message });
551
+ }
552
  };
553
 
554
+ export const assignRestaurantDriver = async (req, res) => {
555
+ try {
556
+ const { invoiceId } = req.params;
557
+ const { driverUserId, driverId } = req.body;
558
+
559
+ if (!driverUserId && !driverId) {
560
+ return res.status(400).json({ message: "معرف السائق مطلوب" });
561
+ }
562
+
563
+ const invoice = await Invoice.findById(invoiceId);
564
+ if (!invoice) {
565
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
566
+ }
567
+
568
+ if (invoice.restaurantData?.orderType !== "delivery") {
569
+ return res
570
+ .status(400)
571
+ .json({ message: "تعيين السائق متاح فقط لطلبات التوصيل" });
572
+ }
573
+
574
+ let resolvedDriver = null;
575
+ let resolvedDriverMode = "user";
576
+
577
+ // ✅ FIX 1: Check driver availability before assignment
578
+ if (driverId) {
579
+ resolvedDriver = await Driver.findOne({
580
+ _id: driverId,
581
+ tenant: invoice.tenant,
582
+ isActive: true,
583
+ });
584
+ if (!resolvedDriver)
585
+ return res.status(404).json({ message: "السائق غير موجود" });
586
+
587
+ // ✅ Check if driver is off-duty
588
+ if (resolvedDriver.status === "off-duty") {
589
+ return res.status(400).json({
590
+ message: "السائق خارج الخدمة حالياً - الحالة: خارج الخدمة"
591
+ });
592
  }
593
+
594
+ // ✅ Check if driver is at max orders capacity
595
+ if (
596
+ !resolvedDriver.currentOrderIds.some(
597
+ (orderId) => orderId.toString() === invoice._id.toString(),
598
+ ) &&
599
+ resolvedDriver.currentOrders >= resolvedDriver.maxOrders
600
+ ) {
601
+ return res.status(400).json({
602
+ message: `السائق وصل للحد الأقصى من الطلبات (${resolvedDriver.maxOrders} طلب)`
603
+ });
604
  }
605
 
606
+ // ✅ Only allow assignment if driver is available or busy (working)
607
+ // Optionally warn if driver is already busy
608
+ if (resolvedDriver.status === "busy") {
609
+ // Still allow assignment but log warning
610
+ console.warn(`⚠️ Driver ${driverId} is busy but assigning additional order`);
611
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612
 
613
+ resolvedDriverMode = "registry";
614
+ } else {
615
+ const userDriver = await User.findOne({
616
+ _id: driverUserId,
617
+ tenant: invoice.tenant,
618
+ status: "active",
619
+ });
620
+ if (!userDriver)
621
+ return res.status(404).json({ message: "السائق غير موجود" });
622
+ resolvedDriver = {
623
+ _id: null,
624
+ name: userDriver.fullName || userDriver.username || "",
625
+ phone: userDriver.phone || "",
626
+ };
627
+ }
628
+
629
+ const previousDriverId = invoice.restaurantData?.driver?.driverId;
630
+ if (
631
+ previousDriverId &&
632
+ (!driverId || previousDriverId.toString() !== driverId.toString())
633
+ ) {
634
+ const previousDriver = await Driver.findOne({
635
+ _id: previousDriverId,
636
+ tenant: invoice.tenant,
637
+ isActive: true,
638
  });
639
 
640
+ if (previousDriver) {
641
+ previousDriver.currentOrderIds = (previousDriver.currentOrderIds || []).filter(
642
+ (orderId) => orderId.toString() !== invoice._id.toString(),
643
+ );
644
+ previousDriver.currentOrders = previousDriver.currentOrderIds.length;
645
+ previousDriver.status = previousDriver.currentOrders > 0 ? "busy" : "available";
646
+ await previousDriver.save();
647
+ }
648
+ }
649
+
650
+ if (resolvedDriverMode === "registry") {
651
+ const alreadyAssigned = (resolvedDriver.currentOrderIds || []).some(
652
+ (orderId) => orderId.toString() === invoice._id.toString(),
653
+ );
654
+ if (!alreadyAssigned) {
655
+ resolvedDriver.currentOrderIds = [...(resolvedDriver.currentOrderIds || []), invoice._id];
656
+ }
657
+ resolvedDriver.currentOrders = resolvedDriver.currentOrderIds.length;
658
+ // ✅ Set status to busy when orders are assigned
659
+ resolvedDriver.status = resolvedDriver.currentOrders > 0 ? "busy" : "available";
660
+ await resolvedDriver.save();
661
+ }
662
+
663
+ invoice.restaurantData = invoice.restaurantData || {};
664
+ invoice.restaurantData.driver = {
665
+ driverId: driverId ? resolvedDriver._id : null,
666
+ driverUserId: driverId ? null : driverUserId,
667
+ driverName: resolvedDriver.name || "",
668
+ driverPhone: resolvedDriver.phone || "",
669
+ assignedAt: new Date(),
670
+ // ✅ Track driver status at assignment time
671
+ driverStatus: resolvedDriver.status || "available",
672
+ };
673
+
674
+ await invoice.save();
675
+
676
+ res.status(200).json({
677
+ message: "تم تعيين السائق بنجاح",
678
+ invoice,
679
+ driverInfo: {
680
+ name: resolvedDriver.name,
681
+ phone: resolvedDriver.phone,
682
+ status: resolvedDriver.status,
683
+ currentOrders: resolvedDriver.currentOrders,
684
+ maxOrders: resolvedDriver.maxOrders,
685
+ }
686
+ });
687
+ } catch (error) {
688
+ res.status(500).json({ message: error.message });
689
+ }
690
  };
691
 
692
+ export const autoAssignRestaurantDriver = async (req, res) => {
693
+ try {
694
+ const { invoiceId } = req.params;
695
+
696
+ const invoice = await Invoice.findById(invoiceId);
697
+ if (!invoice) {
698
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
699
+ }
700
+
701
+ if (invoice.restaurantData?.orderType !== "delivery") {
702
+ return res
703
+ .status(400)
704
+ .json({ message: "التعيين التلقائي متاح فقط لطلبات التوصيل" });
705
+ }
706
+
707
+ // Prefer Driver registry first (POS drivers), fallback to cashier-as-driver if none exist.
708
+ const driver =
709
+ (await Driver.findOne({
710
+ tenant: invoice.tenant,
711
+ isActive: true,
712
+ status: "available",
713
+ $expr: { $lt: ["$currentOrders", "$maxOrders"] },
714
+ ...(invoice.branch ? { branch: invoice.branch } : {}),
715
+ }).sort({ createdAt: 1 })) ||
716
+ (await User.findOne({
717
+ tenant: invoice.tenant,
718
+ status: "active",
719
+ role: "cashier",
720
+ ...(invoice.branch ? { assignedBranch: invoice.branch } : {}),
721
+ }).sort({ createdAt: 1 }));
722
+
723
+ if (!driver) {
724
+ return res
725
+ .status(404)
726
+ .json({ message: "لا يوجد سائق متاح للتعيين التلقائي" });
727
+ }
728
+
729
+ invoice.restaurantData = invoice.restaurantData || {};
730
+
731
+ if (driver instanceof Driver) {
732
+ const alreadyAssigned = (driver.currentOrderIds || []).some(
733
+ (orderId) => orderId.toString() === invoice._id.toString(),
734
+ );
735
+ if (!alreadyAssigned) {
736
+ driver.currentOrderIds = [...(driver.currentOrderIds || []), invoice._id];
737
  }
738
+ driver.currentOrders = driver.currentOrderIds.length;
739
+ driver.status = driver.currentOrders > 0 ? "busy" : "available";
740
+ await driver.save();
741
+
742
+ invoice.restaurantData.driver = {
743
+ driverId: driver._id,
744
+ driverUserId: null,
745
+ driverName: driver.name || "",
746
+ driverPhone: driver.phone || "",
747
+ assignedAt: new Date(),
748
+ };
749
+ } else {
750
+ invoice.restaurantData.driver = {
751
+ driverId: null,
752
+ driverUserId: driver._id,
753
+ driverName: driver.fullName || driver.username || "",
754
+ driverPhone: driver.phone || "",
755
+ assignedAt: new Date(),
756
+ };
757
+ }
758
 
759
+ await invoice.save();
760
+
761
+ res
762
+ .status(200)
763
+ .json({ message: "تم التعيين التلقائي للسائق بنجاح", invoice });
764
+ } catch (error) {
765
+ res.status(500).json({ message: error.message });
766
+ }
767
  };
768
 
769
+ export const createWalkInCashSale = async (req, res) => {
770
+ let createdCustomer = null;
771
+ try {
772
+ const tenantId = req.user.tenant?._id;
773
+ const branch = await resolveBranchForWrite(req);
774
+ const branchId = branch._id;
775
+ const {
776
+ items,
777
+ paidAmount,
778
+ notes = "",
779
+ customerId,
780
+ customerName,
781
+ discount = 0,
782
+ tax = 0,
783
+ restaurantData,
784
+ serviceCharge = 0,
785
+ deliveryCharge = 0,
786
+ } = req.body;
787
+
788
+ if (!tenantId) {
789
+ return res
790
+ .status(403)
791
+ .json({ message: "لا يوجد مستأجر مرتبط بهذا الحساب" });
792
+ }
793
+ if (!Array.isArray(items) || items.length === 0) {
794
+ return res.status(400).json({ message: "يجب إضافة صنف واحد على الأقل" });
795
+ }
796
+
797
+ let finalCustomerId = customerId;
798
+ if (!finalCustomerId && customerName) {
799
+ createdCustomer = await Customer.create({
800
+ name: customerName.trim(),
801
+ tenant: tenantId,
802
+ branch: branchId,
803
+ createdBy: req.user._id,
804
+ });
805
+ finalCustomerId = createdCustomer._id;
806
+ }
807
+
808
+ try {
809
+ await validateCatalogItems(items, tenantId, branchId);
810
+ await ensureStockAvailability(items, tenantId, branchId);
811
+
812
+ let customer;
813
+ if (finalCustomerId) {
814
+ customer = await Customer.findOne({
815
+ _id: finalCustomerId,
816
+ tenant: tenantId,
817
+ branch: branchId,
818
+ });
819
+ if (!customer) throw new Error("العميل المحدد غير موجود");
820
+ } else {
821
+ customer = await getOrCreateWalkInCustomer(
822
+ tenantId,
823
+ branchId,
824
+ req.user._id,
825
+ );
826
  }
827
 
828
+ const invoice = new Invoice({
829
+ tenant: tenantId,
830
+ branch: branchId,
831
+ customer: customer._id,
832
+ issuedBy: req.user._id,
833
+ notes: notes.trim(),
834
+ discount: Math.max(Number(discount) || 0, 0),
835
+ taxAmount: Math.max(Number(tax) || 0, 0),
836
+ serviceCharge: Math.max(Number(serviceCharge) || 0, 0),
837
+ deliveryCharge: Math.max(Number(deliveryCharge) || 0, 0),
838
+ restaurantData: restaurantData || null,
839
+ });
840
 
841
+ await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);
 
842
 
843
+ let saved = false;
844
+ for (let i = 0; i < 3; i++) {
845
+ try {
846
+ invoice.invoiceNumber = await generateInvoiceNumber(
847
+ tenantId,
848
+ branchId,
849
+ );
850
+ invoice.calculateTotals();
851
+ await invoice.save();
852
+ saved = true;
853
+ break;
854
+ } catch (saveErr) {
855
+ if (saveErr.code === 11000 && i < 2) continue;
856
+ throw saveErr;
857
+ }
 
 
 
 
 
 
858
  }
859
+ if (!saved) throw new Error("تعذر حفظ الفاتورة لخطأ تزامن بالرقم");
860
+
861
+ // ✅ Restaurant orders support flexible payment types (full/partial/unpaid/transfer)
862
+ // Sales-tenant walk-in must remain cash-in-full only
863
+ const isRestaurantOrder = !!restaurantData?.orderType;
864
+ const paymentType = req.body.paymentType || "full";
865
+ const paymentAmount = Number(paidAmount || 0);
866
+
867
+ if (!isRestaurantOrder) {
868
+ // Traditional walk-in: must pay full amount in cash
869
+ if (
870
+ !paymentAmount ||
871
+ Math.abs(paymentAmount - invoice.totalAmount) > 0.01
872
+ ) {
873
+ throw new Error(
874
+ "فاتورة الزائر يجب أن تكون نقدية بالكامل، ويجب أن يساوي المبلغ المدفوع إجمالي الفاتورة",
875
+ );
876
+ }
 
 
 
 
 
877
  }
878
 
879
+ // Record payment if amount > 0
880
+ if (paymentAmount > 0) {
881
+ const amountToRecord = Math.min(paymentAmount, invoice.totalAmount);
882
+ invoice.payments.push({
883
+ amount: amountToRecord,
884
+ method: paymentType === "transfer" ? "transfer" : "cash",
885
+ receivedBy: req.user._id,
886
+ confirmed: true,
887
+ });
888
+ }
889
+ // unpaid (آجل) = no payment recorded, invoice stays "open"
890
 
891
  await invoice.save();
892
 
893
+ // Record income only for cash/confirmed payments
894
+ if (paymentAmount > 0) {
895
+ await createIncomeForPayment({
896
+ tenantId,
897
+ branchId,
898
+ invoice,
899
+ customer,
900
+ amount: Math.min(paymentAmount, invoice.totalAmount),
901
+ userId: req.user._id,
902
+ notes: isRestaurantOrder ? "Restaurant sale" : "Walk-in cash sale",
903
+ paymentMethod: paymentType === "transfer" ? "transfer" : "cash",
904
+ });
 
 
 
 
 
 
 
 
 
 
905
  }
906
 
907
+ // ✅ Lock table if dine-in
908
+ if (restaurantData?.orderType === "dine-in" && restaurantData?.table) {
909
+ const tableCheck = await Table.findById(restaurantData.table);
910
+ if (tableCheck && tableCheck.status !== "occupied") {
911
+ await Table.findByIdAndUpdate(restaurantData.table, {
912
+ status: "occupied",
913
+ currentOrderId: invoice._id,
914
+ });
915
+ }
916
  }
917
 
918
+ const populatedInvoice = await Invoice.findById(invoice._id).populate(
919
+ "customer",
920
+ "name isWalkIn",
921
+ );
922
+
923
+ // ✅ Return changeDue so frontend can display it
924
+ const responseData = populatedInvoice.toObject();
925
+ responseData.changeDue = Math.max(
926
+ paymentAmount - Number(invoice.totalAmount),
927
+ 0
928
+ );
929
+ res.status(201).json(responseData);
930
+ } catch (err) {
931
+ if (createdCustomer)
932
+ await Customer.deleteOne({ _id: createdCustomer._id });
933
+ throw err;
934
+ }
935
+ } catch (err) {
936
+ if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
937
+ res.status(err.statusCode || 500).json({ message: err.message });
938
+ }
939
+ };
940
 
941
+ export const getInvoices = async (req, res) => {
942
+ try {
943
+ const page = parseInt(req.query.page) || 1;
944
+ const limit = parseInt(req.query.limit) || 5;
945
+ const skip = (page - 1) * limit;
946
+ const search = req.query.search || "";
947
+ const { tenantId, branchFilter } = await resolveScopedBranch(req);
948
+
949
+ const query = { tenant: tenantId, ...branchFilter };
950
+ if (search) {
951
+ query.invoiceNumber = { $regex: search, $options: "i" };
952
+ }
953
+ if (req.query.method) {
954
+ query["payments.method"] = req.query.method;
955
+ }
956
+
957
+ // Restaurant/Cafe filtering for restaurant management screens
958
+ // - isRestaurant=true => only invoices with restaurantData.orderType set
959
+ // - orderType=delivery|takeaway|dine-in => filter by restaurantData.orderType
960
+ // - restaurantStatus=pending|preparing|ready_for_delivery|shipped => filter by Invoice.restaurantStatus
961
+ const isRestaurant =
962
+ String(req.query.isRestaurant || "").toLowerCase() === "true";
963
+ if (isRestaurant) {
964
+ query["restaurantData.orderType"] = { $ne: null };
965
+ }
966
+
967
+ if (req.query.orderType) {
968
+ query["restaurantData.orderType"] = req.query.orderType;
969
+ }
970
+
971
+ if (req.query.restaurantStatus) {
972
+ query.restaurantStatus = req.query.restaurantStatus;
973
+ }
974
+ if (req.query.excludeStatus) {
975
+ const excluded = req.query.excludeStatus.split(",").map((s) => s.trim());
976
+ query.restaurantStatus = { $nin: excluded };
977
+ }
978
+
979
+ const total = await Invoice.countDocuments(query);
980
+ const invoices = await Invoice.find(query)
981
+ .populate("customer")
982
+ .sort({ createdAt: -1 })
983
+ .skip(skip)
984
+ .limit(limit);
985
+
986
+ res.status(200).json({
987
+ data: invoices,
988
+ pagination: {
989
+ total,
990
+ page,
991
+ limit,
992
+ totalPages: Math.ceil(total / limit),
993
+ },
994
+ });
995
+ } catch (err) {
996
+ res.status(500).json({ message: err.message });
997
+ }
998
+ };
999
 
1000
+ export const getInvoicesByCustomer = async (req, res) => {
1001
+ try {
1002
+ const invoices = await Invoice.find({
1003
+ customer: req.params.customerId,
1004
+ tenant: req.user.tenant._id,
1005
+ ...(await resolveScopedBranch(req)).branchFilter,
1006
+ });
1007
+
1008
+ res.json(invoices);
1009
+ } catch (err) {
1010
+ res.status(500).json({ message: err.message });
1011
+ }
1012
  };
1013
 
1014
+ export const getInvoiceById = async (req, res) => {
1015
+ try {
1016
+ const { id } = req.params;
1017
+ const { branchFilter } = await resolveScopedBranch(req);
1018
+
1019
+ const invoice = await Invoice.findOne({
1020
+ _id: id,
1021
+ tenant: req.user.tenant._id,
1022
+ ...branchFilter,
1023
+ })
1024
+ .populate("customer", "name isWalkIn")
1025
+ .populate({
1026
+ path: "items.productId",
1027
+ select: "name price",
1028
+ })
1029
+ .populate({
1030
+ path: "items.catalogItemId",
1031
+ select: "name price",
1032
+ });
1033
 
1034
+ if (!invoice) {
1035
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
1036
+ }
1037
 
1038
+ res.status(200).json(invoice);
1039
+ } catch (error) {
1040
+ res.status(500).json({ message: error.message });
1041
+ }
1042
+ };
 
 
 
 
 
 
 
 
 
 
1043
 
1044
+ export const updateInvoiceItem = async (req, res) => {
1045
+ try {
1046
+ const { invoiceId, itemId } = req.params;
1047
+ const { name, quantity, price } = req.body;
1048
+ const { branchFilter } = await resolveScopedBranch(req);
1049
+
1050
+ const invoice = await Invoice.findOne({
1051
+ _id: invoiceId,
1052
+ tenant: req.user.tenant._id,
1053
+ ...branchFilter,
1054
+ }).populate("customer", "isWalkIn");
1055
+
1056
+ if (!invoice) {
1057
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
1058
+ }
1059
+
1060
+ const item = invoice.items.id(itemId);
1061
+ if (!item) {
1062
+ return res.status(404).json({ message: "بند الفاتورة غير موجود" });
1063
+ }
1064
+
1065
+ const newQuantity = Number(quantity);
1066
+ const newPrice = Number(price);
1067
+
1068
+ if (!Number.isFinite(newQuantity) || newQuantity <= 0) {
1069
+ return res.status(400).json({ message: "الكمية غير صالحة" });
1070
+ }
1071
+
1072
+ if (!Number.isFinite(newPrice) || newPrice < 0) {
1073
+ return res.status(400).json({ message: "السعر غير صالح" });
1074
+ }
1075
+
1076
+ // =========================
1077
+ // HANDLE CATALOG ITEM
1078
+ // =========================
1079
+ if (item.type === "catalog" && item.catalogItemId) {
1080
+ const catalogItem = await CatalogItem.findOne({
1081
+ _id: item.catalogItemId,
1082
+ tenant: req.user.tenant._id,
1083
+ ...branchFilter,
1084
+ });
1085
 
1086
+ if (!catalogItem) {
1087
+ return res.status(404).json({ message: "عنصر الكتالوج غير موجود" });
1088
  }
1089
 
1090
+ item.name = catalogItem.name;
1091
+ item.quantity = newQuantity;
1092
+ item.price = Number(catalogItem.price || 0);
1093
+ item.total = item.quantity * item.price;
 
1094
 
1095
+ await invoice.save();
 
 
1096
 
1097
+ return res.status(200).json({
1098
+ message: "تم تحديث بند الكتالوج بنجاح",
1099
+ invoice,
1100
+ });
1101
+ }
1102
+
1103
+ // =========================
1104
+ // HANDLE PRODUCT ITEM
1105
+ // =========================
1106
+ if (item.productId) {
1107
+ const oldQuantity = Number(item.quantity);
1108
+ const diff = newQuantity - oldQuantity;
1109
+
1110
+ const product = await Product.findOne({
1111
+ _id: item.productId,
1112
+ tenant: req.user.tenant._id,
1113
+ ...branchFilter,
1114
  });
1115
 
1116
+ if (!product) {
1117
+ return res.status(404).json({ message: "المنتج المرتبط غير موجود" });
1118
+ }
1119
 
1120
+ // If increasing quantity → check stock
1121
+ if (diff > 0 && product.stock < diff) {
1122
+ return res.status(400).json({
1123
+ message: "المخزون غير كافي للتعديل",
1124
+ });
 
 
 
 
 
 
 
 
1125
  }
1126
 
1127
+ // FIXED STOCK UPDATE (IMPORTANT)
1128
+ if (diff !== 0) {
1129
+ await Product.findOneAndUpdate(
1130
+ {
1131
+ _id: item.productId,
1132
+ tenant: req.user.tenant._id,
1133
+ ...branchFilter,
1134
+ },
1135
+ { $inc: { stock: -diff } },
1136
+ );
1137
+ }
1138
+ }
1139
+
1140
+ // =========================
1141
+ // APPLY CHANGES
1142
+ // =========================
1143
+ item.name = name;
1144
+ item.quantity = newQuantity;
1145
+ item.price = newPrice;
1146
+ item.total = newQuantity * newPrice;
1147
+
1148
+ await invoice.save();
1149
+
1150
+ return res.status(200).json({
1151
+ message: "تم تحديث بند الفاتورة بنجاح",
1152
+ invoice,
1153
+ });
1154
+ } catch (error) {
1155
+ return res.status(500).json({ message: error.message });
1156
+ }
1157
  };
1158
 
1159
+ export const deleteInvoiceItem = async (req, res) => {
1160
+ try {
1161
+ const { invoiceId, itemId } = req.params;
1162
+ const { branchFilter } = await resolveScopedBranch(req);
1163
+
1164
+ const invoice = await Invoice.findOne({
1165
+ _id: invoiceId,
1166
+ tenant: req.user.tenant._id,
1167
+ ...branchFilter,
1168
+ }).populate("customer", "isWalkIn");
1169
+
1170
+ if (!invoice) {
1171
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
1172
+ }
1173
+
1174
+ const item = invoice.items.id(itemId);
1175
+ if (!item) {
1176
+ return res.status(404).json({ message: "المنتج غير موجود" });
1177
+ }
1178
+
1179
+ // restore stock only for product items
1180
+ if (item.productId) {
1181
+ await Product.findOneAndUpdate(
1182
+ { _id: item.productId, tenant: req.user.tenant._id, ...branchFilter },
1183
+ { $inc: { stock: Number(item.quantity) } },
1184
+ );
1185
+ }
1186
+
1187
+ // REMOVE TABLE LOGIC HERE (BUG FIX)
1188
+
1189
+ item.deleteOne();
1190
+ await invoice.save();
1191
+
1192
+ res.json(invoice);
1193
+ } catch (error) {
1194
+ res.status(500).json({ message: error.message });
1195
+ }
1196
+ };
1197
 
1198
+ export const payInvoice = async (req, res) => {
1199
+ const session = await mongoose.startSession();
1200
+ session.startTransaction();
1201
+
1202
+ try {
1203
+ const { invoiceId } = req.params; // Changed from customerId
1204
+
1205
+ const {
1206
+ paymentMethod = "cash",
1207
+ transferType,
1208
+ customerName,
1209
+ customerPhone,
1210
+ releaseTable = false,
1211
+ } = req.body;
1212
+
1213
+ const amount = Number(req.body.amount || 0);
1214
+ const { branchId, branchFilter } = await resolveScopedBranch(req);
1215
+
1216
+ // ─ PAYMENT TYPE CHECKS ─
1217
+ const isCash = paymentMethod === "cash";
1218
+ const isPartial = paymentMethod === "partial";
1219
+ const isDebt = paymentMethod === "unpaid";
1220
+ const isTransfer = paymentMethod === "transfer";
1221
+
1222
+ // ─ 1. BASIC VALIDATION ─
1223
+ if (!isDebt && amount <= 0) {
1224
+ return res.status(400).json({ message: "يجب إدخال مبلغ صحيح" });
1225
+ }
1226
+
1227
+ if (isTransfer && !["instapay", "vodafone_cash", "bank_transfer"].includes(transferType)) {
1228
+ return res.status(400).json({ message: "نوع التحويل غير صحيح" });
1229
+ }
1230
+
1231
+ // ─ 2. FIND INVOICE ─
1232
+ const invoice = await Invoice.findOne({
1233
+ _id: invoiceId,
1234
+ tenant: req.user.tenant._id,
1235
+ ...branchFilter,
1236
+ })
1237
+ .populate("customer", "name isWalkIn phone")
1238
+ .session(session);
1239
+
1240
+ if (!invoice) {
1241
+ return res.status(404).json({ message: "لا توجد فاتورة نشطة" });
1242
+ }
1243
+
1244
+ // ─ 3. BUSINESS RULES ─
1245
+ if (isCash && amount < invoice.remainingAmount) {
1246
+ return res.status(400).json({ message: "الدفع النقدي يجب أن يكون كاملاً" });
1247
+ }
1248
+
1249
+ if (isDebt && amount > 0) {
1250
+ return res.status(400).json({ message: "الآجل لا يسمح بأي مبلغ مدفوع" });
1251
+ }
1252
+
1253
+ if (isPartial && amount >= invoice.remainingAmount) {
1254
+ return res.status(400).json({ message: "المبلغ الجزئي يجب أن يكون أقل من الإجمالي" });
1255
+ }
1256
+
1257
+ // ─ 4. CUSTOMER BINDING VALIDATION ─
1258
+ const isWalkIn = invoice.customer?.isWalkIn === true;
1259
+
1260
+ if (isWalkIn && !isCash) {
1261
+ // Non-cash payments on walk-in REQUIRE customer data
1262
+ if (!customerName?.trim() || !customerPhone?.trim()) {
1263
+ return res.status(400).json({
1264
+ message: "يجب إدخال بيانات العميل للدفع الآجل أو التحويل"
1265
+ });
1266
  }
1267
+ }
1268
+
1269
+ // ─ 5. CUSTOMER BINDING (UPSERT) ─
1270
+ if (customerName?.trim() && customerPhone?.trim()) {
1271
+ const customer = await Customer.findOneAndUpdate(
1272
+ {
1273
+ tenant: req.user.tenant._id,
1274
+ phone: customerPhone.trim(),
1275
+ },
1276
+ {
1277
+ $set: {
1278
+ name: customerName.trim(),
1279
+ phone: customerPhone.trim(),
1280
+ },
1281
+ $setOnInsert: {
1282
+ tenant: req.user.tenant._id,
1283
+ branch: branchId || undefined,
1284
+ createdBy: req.user._id,
1285
+ }
1286
+ },
1287
+ { upsert: true, new: true, session }
1288
+ );
1289
 
1290
+ if (isWalkIn || !invoice.customer) {
1291
+ invoice.customer = customer._id;
1292
  }
1293
+ }
1294
+
1295
+ // ─ 6. REGISTER PAYMENT ─
1296
+ if (amount > 0) {
1297
+ invoice.payments.push({
1298
+ amount,
1299
+ method: paymentMethod,
1300
+ transferType: isTransfer ? transferType : null,
1301
+ receivedBy: req.user._id,
1302
+ settledBy: req.user._id, // ✓ NEW
1303
+ settledAt: new Date(), // ✓ NEW
1304
+ confirmed: isCash,
1305
+ branchId: branchId, // ✓ NEW
1306
+ });
1307
+ }
1308
+
1309
+ // ─ 7. SAVE INVOICE ─
1310
+ await invoice.save({ session });
1311
+
1312
+ // ─ 8. INCOME LOGIC ─
1313
+ if (isCash && amount > 0) {
1314
+ await createIncomeForPayment({
1315
+ tenantId: req.user.tenant._id,
1316
+ branchId: branchId,
1317
+ invoice,
1318
+ customer: invoice.customer,
1319
+ amount,
1320
+ userId: req.user._id,
1321
+ paymentMethod,
1322
+ transferType,
1323
+ });
1324
+ }
1325
+
1326
+ // ─ 9. TABLE RELEASE (TRANSACTIONAL) ─
1327
+ if ((invoice.remainingAmount <= 0 || releaseTable) &&
1328
+ invoice.restaurantData?.orderType === "dine-in") {
1329
+ await Table.findByIdAndUpdate(
1330
+ invoice.restaurantData.table,
1331
+ {
1332
+ status: "available",
1333
+ currentOrderId: null,
1334
+ freedAt: new Date(),
1335
+ freedBy: req.user._id,
1336
+ },
1337
+ { session }
1338
+ );
1339
+ }
1340
+
1341
+ // ─ 10. COMMIT ─
1342
+ await session.commitTransaction();
1343
+ res.json(invoice);
1344
+
1345
+ } catch (err) {
1346
+ await session.abortTransaction();
1347
+ res.status(500).json({ message: err.message });
1348
+ } finally {
1349
+ session.endSession();
1350
+ }
1351
+ };
1352
 
1353
+ export const confirmPayment = async (req, res) => {
1354
+ try {
1355
+ const { invoiceId, paymentIndex } = req.params;
1356
+ const tenantId = req.user.tenant._id;
1357
+ const { branchFilter } = await resolveScopedBranch(req);
1358
+
1359
+ const invoice = await Invoice.findOne({
1360
+ _id: invoiceId,
1361
+ tenant: tenantId,
1362
+ ...branchFilter,
1363
+ }).populate("customer", "name isWalkIn");
1364
+
1365
+ if (!invoice) {
1366
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
1367
+ }
1368
+
1369
+ const payment = invoice.payments[paymentIndex];
1370
+ if (!payment) {
1371
+ return res.status(404).json({ message: "الدفع غير موجود" });
1372
+ }
1373
+
1374
+ if (payment.method !== "transfer") {
1375
+ return res
1376
+ .status(400)
1377
+ .json({ message: "فقط دفعات التحويل تحتاج إلى تأكيد" });
1378
+ }
1379
+
1380
+ payment.confirmed = !payment.confirmed;
1381
+ if (payment.confirmed) {
1382
+ payment.confirmedBy = req.user._id;
1383
+ payment.confirmedAt = new Date();
1384
+
1385
+ // Create income records now that the transfer is confirmed
1386
+ await createIncomeForPayment({
1387
+ tenantId,
1388
+ branchId: invoice.branch || null,
1389
+ invoice,
1390
+ customer: invoice.customer,
1391
+ amount: payment.amount,
1392
+ userId: req.user._id,
1393
+ paymentMethod: "transfer",
1394
+ transferType: payment.transferType,
1395
+ date: payment.confirmedAt,
1396
+ });
1397
+ } else {
1398
+ payment.confirmedBy = null;
1399
+ payment.confirmedAt = null;
1400
 
1401
+ // Remove income records for this unconfirmed transfer
1402
+ await Income.deleteMany({
1403
+ tenant: tenantId,
1404
+ sourceType: "invoice_payment",
1405
+ relatedInvoice: invoice._id,
1406
+ paymentMethod: "transfer",
1407
+ amount: payment.amount,
1408
+ });
1409
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1410
 
1411
+ await invoice.save();
1412
+ res.json(invoice);
1413
+ } catch (err) {
1414
+ res.status(500).json({ message: err.message });
1415
+ }
1416
  };
1417
 
1418
  export const updateInvoice = async (req, res) => {
1419
+ try {
1420
+ console.log("=== UPDATE INVOICE START ===");
1421
+ const { invoiceId } = req.params;
1422
+ const { items, discount, tax, notes } = req.body;
1423
+ console.log("Request data:", { invoiceId, items, discount, tax, notes });
1424
+ const tenantId = req.user.tenant._id;
1425
+ const { branchFilter } = await resolveScopedBranch(req);
1426
+
1427
+ console.log("Finding invoice with query:", {
1428
+ _id: invoiceId,
1429
+ tenant: tenantId,
1430
+ ...branchFilter,
1431
+ });
1432
+ const invoice = await Invoice.findOne({
1433
+ _id: invoiceId,
1434
+ tenant: tenantId,
1435
+ ...branchFilter,
1436
+ }).populate("customer", "isWalkIn");
1437
+
1438
+ console.log("Found invoice:", invoice);
1439
+ if (!invoice) {
1440
+ console.log("Invoice not found!");
1441
+ return res.status(404).json({ message: "Invoice not found" });
1442
+ }
1443
+
1444
+ console.log("Current invoice items before update:", invoice.items);
1445
+
1446
+ // Reverse stock for existing product items
1447
+ console.log("Reversing stock for existing items...");
1448
+ for (const oldItem of invoice.items) {
1449
+ if (oldItem.productId) {
1450
+ console.log(
1451
+ `Reversing stock for product ${oldItem.productId}: +${oldItem.quantity}`,
1452
+ );
1453
+ await Product.findOneAndUpdate(
1454
+ { _id: oldItem.productId, tenant: tenantId, ...branchFilter },
1455
+ { $inc: { stock: Number(oldItem.quantity) } },
1456
+ );
1457
  }
1458
+ }
1459
 
1460
+ // Clear old items and add new items directly
1461
+ console.log("Clearing old items and adding new items...");
1462
+ invoice.items = [];
1463
+ for (const item of items) {
1464
+ const quantity = Number(item.quantity || 0);
1465
+ const price = Number(item.price || 0);
 
 
 
 
 
 
 
1466
 
1467
+ console.log(
1468
+ `Processing item: ${item.name}, qty: ${quantity}, price: ${price}`,
1469
+ );
1470
+
1471
+ // Deduct stock for product items
1472
+ if (item.productId) {
1473
+ console.log(
1474
+ `Deducting stock for product ${item.productId}: -${quantity}`,
1475
+ );
1476
+ await Product.findOneAndUpdate(
1477
+ { _id: item.productId, tenant: tenantId, ...branchFilter },
1478
+ { $inc: { stock: -quantity } },
1479
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1480
  }
1481
 
1482
+ const newItem = {
1483
+ name: item.name,
1484
+ quantity,
1485
+ price,
1486
+ total: quantity * price,
1487
+ type: item.type || "product",
1488
+ productId: item.productId || null,
1489
+ catalogItemId: item.catalogItemId || null,
1490
+ serviceId: item.serviceId || null,
1491
+ };
1492
+
1493
+ console.log("Adding new item to invoice:", newItem);
1494
+ invoice.items.push(newItem);
1495
+ }
1496
 
1497
+ console.log("Invoice items after update:", invoice.items);
 
 
 
 
1498
 
1499
+ // Update discount, tax, notes
1500
+ console.log("Updating discount, tax, notes:", { discount, tax, notes });
1501
+ invoice.discount = Math.max(Number(discount) || 0, 0);
1502
+ invoice.taxAmount = Math.max(Number(tax) || 0, 0);
1503
+ if (notes !== undefined) invoice.notes = notes.trim();
1504
+
1505
+ console.log("Calculating totals and saving...");
1506
+ invoice.calculateTotals();
1507
+ await invoice.save();
1508
 
1509
+ console.log("Invoice saved successfully:", invoice);
1510
+ res.json(invoice);
1511
+ } catch (err) {
1512
+ res.status(err.statusCode || 500).json({ message: err.message });
1513
+ }
1514
  };
1515
 
1516
  export const deleteInvoice = async (req, res) => {
1517
+ try {
1518
+ const { invoiceId } = req.params;
1519
+ const tenantId = req.user.tenant._id;
1520
+ const { branchFilter } = await resolveScopedBranch(req);
1521
+
1522
+ const invoice = await Invoice.findOne({
1523
+ _id: invoiceId,
1524
+ tenant: tenantId,
1525
+ ...branchFilter,
1526
+ }).populate("customer", "isWalkIn");
1527
+
1528
+ if (!invoice) {
1529
+ return res.status(404).json({ message: "Invoice not found" });
1530
+ }
1531
+
1532
+ // Restore stock for product items
1533
+ for (const item of invoice.items) {
1534
+ if (item.productId) {
1535
+ await Product.findOneAndUpdate(
1536
+ { _id: item.productId, tenant: tenantId, ...branchFilter },
1537
+ { $inc: { stock: Number(item.quantity) } },
1538
+ );
1539
  }
1540
+ }
1541
+
1542
+ // Delete related income records
1543
+ await Income.deleteMany({
1544
+ tenant: tenantId,
1545
+ sourceType: "invoice_payment",
1546
+ relatedInvoice: invoice._id,
1547
+ });
1548
+
1549
+ // Delete the invoice
1550
+ await Invoice.findByIdAndDelete(invoiceId);
1551
+
1552
+ res.json({ message: "Invoice deleted successfully" });
1553
+ } catch (err) {
1554
+ res.status(err.statusCode || 500).json({ message: err.message });
1555
+ }
1556
+ };
1557
+
1558
+ // ─── OPEN TAB: Add items to an existing open invoice ──────────────────────────
1559
+ // Feature #4: Restaurant Open Tab System
1560
+ // Allows a café/restaurant to add more items to an in-progress dine-in order
1561
+ // without creating a new invoice. Called from TableSettleModal > "Add Items" tab.
1562
+ export const addItemsToOpenTab = async (req, res) => {
1563
+ try {
1564
+ const { invoiceId } = req.params;
1565
+ const { items } = req.body;
1566
+ const tenantId = req.user?.tenant?._id;
1567
+ const { branchFilter } = await resolveScopedBranch(req);
1568
+
1569
+ if (!items || !Array.isArray(items) || items.length === 0) {
1570
+ return res.status(400).json({ message: "يجب إرسال قائمة الأصناف" });
1571
+ }
1572
+
1573
+ const invoice = await Invoice.findOne({
1574
+ _id: invoiceId,
1575
+ tenant: tenantId,
1576
+ ...branchFilter,
1577
+ });
1578
+
1579
+ if (!invoice) {
1580
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
1581
+ }
1582
+
1583
+ // Only open/partial invoices can receive more items, EXCEPT for active dine-in tables
1584
+ // A dine-in table might have been paid in advance, but the customer wants to add more items.
1585
+ const isDineIn = invoice.restaurantData?.orderType === "dine-in";
1586
+ if (!["open", "partial", "paid"].includes(invoice.status) && !isDineIn) {
1587
+ return res.status(400).json({
1588
+ message: "لا يمكن إضافة أصناف لفاتورة مغلقة",
1589
+ });
1590
+ }
1591
+
1592
+ // Process each new item — handle stock if productId is provided
1593
+ for (const item of items) {
1594
+ const quantity = Number(item.quantity || 1);
1595
+ const price = Number(item.price || 0);
1596
 
1597
+ if (!item.name || quantity <= 0) continue;
1598
+
1599
+ // Deduct stock for product items
1600
+ if (item.productId) {
1601
+ const product = await Product.findOne({
1602
+ _id: item.productId,
1603
+ tenant: tenantId,
1604
+ ...branchFilter,
1605
+ });
1606
+
1607
+ if (product && product.stock < quantity) {
1608
+ return res.status(400).json({
1609
+ message: `المخزون غير كافٍ للمنتج: ${item.name}`,
1610
+ });
1611
+ }
1612
+
1613
+ if (product) {
1614
+ await Product.findOneAndUpdate(
1615
+ { _id: item.productId, tenant: tenantId, ...branchFilter },
1616
+ { $inc: { stock: -quantity } }
1617
+ );
1618
+ }
1619
  }
1620
 
1621
+ invoice.items.push({
1622
+ name: String(item.name).trim(),
1623
+ quantity,
1624
+ price,
1625
+ total: quantity * price,
1626
+ type: item.type || "catalog",
1627
+ productId: item.productId || null,
1628
+ catalogItemId: item.catalogItemId || null,
1629
  });
1630
+ }
1631
+
1632
+ invoice.calculateTotals();
1633
+ await invoice.save();
1634
+
1635
+ res.status(200).json({
1636
+ message: "تم إضافة الأصناف للطلب القائم بنجاح",
1637
+ invoice,
1638
+ });
1639
+ } catch (err) {
1640
+ res.status(500).json({ message: err.message });
1641
+ }
1642
+ };
1643
 
1644
+ // ✅ NEW: Record payment received from driver for delivery orders
1645
+ // This ensures income is only recorded when driver actually brings the money
1646
+ export const recordDriverPayment = async (req, res) => {
1647
+ try {
1648
+ const { invoiceId } = req.params;
1649
+ const { amount, notes = "" } = req.body;
1650
+ const tenantId = req.user.tenant._id;
1651
+ const { branchId, branchFilter } = await resolveScopedBranch(req);
1652
+
1653
+ // Validate amount
1654
+ if (!amount || Number(amount) <= 0) {
1655
+ return res.status(400).json({
1656
+ message: "يجب إدخال مبلغ موجب",
1657
+ });
1658
+ }
1659
+
1660
+ // Find invoice
1661
+ const invoice = await Invoice.findOne({
1662
+ _id: invoiceId,
1663
+ tenant: tenantId,
1664
+ ...branchFilter,
1665
+ }).populate("customer", "isWalkIn");
1666
+
1667
+ if (!invoice) {
1668
+ return res.status(404).json({ message: "الفاتورة غير موجودة" });
1669
+ }
1670
+
1671
+ // Verify it's a delivery order
1672
+ if (invoice.restaurantData?.orderType !== "delivery") {
1673
+ return res.status(400).json({
1674
+ message: "تسجيل دفع السائق متاح فقط لطلبات التوصيل",
1675
+ });
1676
+ }
1677
 
1678
+ // Verify a driver is assigned
1679
+ if (!invoice.restaurantData?.driver?.driverId && !invoice.restaurantData?.driver?.driverUserId) {
1680
+ return res.status(400).json({
1681
+ message: "لا يوجد سائق معيّن لهذه الفاتورة",
1682
+ });
1683
+ }
1684
+
1685
+ const paymentAmount = Number(amount);
1686
+ if (paymentAmount > invoice.totalAmount) {
1687
+ return res.status(400).json({
1688
+ message: `لا يمكن أن يتجاوز المبلغ إجمالي الفاتورة (${invoice.totalAmount})`,
1689
+ });
1690
+ }
1691
+
1692
+ // ✅ Record driver payment in the driver payment field
1693
+ invoice.restaurantData.driver.paymentReceived = {
1694
+ amount: paymentAmount,
1695
+ receivedAt: new Date(),
1696
+ receivedBy: req.user._id,
1697
+ notes: notes.trim(),
1698
+ };
1699
+
1700
+ // ✅ Also add to invoice payments to track it
1701
+ invoice.payments.push({
1702
+ amount: paymentAmount,
1703
+ method: "cash",
1704
+ receivedBy: req.user._id,
1705
+ confirmed: true,
1706
+ date: new Date(),
1707
+ });
1708
+
1709
+ await invoice.save();
1710
+
1711
+ // ✅ NOW create income records (only when driver payment is actually received)
1712
+ await createIncomeForPayment({
1713
+ tenantId,
1714
+ branchId: invoice.branch || branchId || null,
1715
+ invoice,
1716
+ customer: invoice.customer,
1717
+ amount: paymentAmount,
1718
+ userId: req.user._id,
1719
+ notes: `دفع السائق - ${invoice.invoiceNumber} ${notes ? `- ${notes}` : ""}`,
1720
+ paymentMethod: "cash",
1721
+ date: new Date(),
1722
+ });
1723
+
1724
+ res.status(200).json({
1725
+ status: "success",
1726
+ message: `تم تسجيل دفع السائق بنجاح - ${paymentAmount} ريال`,
1727
+ invoice,
1728
+ driverPayment: invoice.restaurantData.driver.paymentReceived,
1729
+ });
1730
+ } catch (error) {
1731
+ res.status(500).json({ message: error.message });
1732
+ }
1733
  };
controller/menuController.js ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import MenuItem from "../models/MenuItemModel.js";
2
+ import { catchAsync } from "../utils/catchAsync.js";
3
+ import AppError from "../utils/appError.js";
4
+
5
+ // Get all menu items
6
+ export const getAllMenuItems = catchAsync(async (req, res) => {
7
+ const { tenantId } = req.params;
8
+ const { category, isAvailable } = req.query;
9
+
10
+ const filter = { tenant: tenantId };
11
+
12
+ if (category) filter.category = category;
13
+ if (isAvailable !== undefined) filter.isAvailable = isAvailable === "true";
14
+
15
+ const menuItems = await MenuItem.find(filter).sort({ category: 1, name: 1 });
16
+
17
+ res.status(200).json({
18
+ status: "success",
19
+ data: menuItems,
20
+ });
21
+ });
22
+
23
+ // Get menu item by ID
24
+ export const getMenuItemById = catchAsync(async (req, res) => {
25
+ const { id } = req.params;
26
+
27
+ const menuItem = await MenuItem.findById(id);
28
+
29
+ if (!menuItem) {
30
+ return res.status(404).json({
31
+ status: "error",
32
+ message: "عنصر القائمة غير موجود",
33
+ });
34
+ }
35
+
36
+ res.status(200).json({
37
+ status: "success",
38
+ data: menuItem,
39
+ });
40
+ });
41
+
42
+ // Create menu item
43
+ export const createMenuItem = catchAsync(async (req, res) => {
44
+ const { tenantId } = req.params;
45
+ const { name, nameAr, description, descriptionAr, price, category, categoryAr, preparationTime } = req.body;
46
+
47
+ // Validation
48
+ if (!name || !nameAr || !price || !category || !categoryAr) {
49
+ return res.status(400).json({
50
+ status: "error",
51
+ message: "الرجاء ملء جميع الحقول المطلوبة",
52
+ });
53
+ }
54
+
55
+ if (price < 0) {
56
+ return res.status(400).json({
57
+ status: "error",
58
+ message: "السعر لا يمكن أن يكون سالباً",
59
+ });
60
+ }
61
+
62
+ const menuItem = await MenuItem.create({
63
+ tenant: tenantId,
64
+ name,
65
+ nameAr,
66
+ description,
67
+ descriptionAr,
68
+ price,
69
+ category,
70
+ categoryAr,
71
+ preparationTime: preparationTime || 15,
72
+ });
73
+
74
+ res.status(201).json({
75
+ status: "success",
76
+ message: "تم إضافة عنصر القائمة بنجاح",
77
+ data: menuItem,
78
+ });
79
+ });
80
+
81
+ // Update menu item
82
+ export const updateMenuItem = catchAsync(async (req, res) => {
83
+ const { id } = req.params;
84
+ const updates = req.body;
85
+
86
+ // Validate price if provided
87
+ if (updates.price !== undefined && updates.price < 0) {
88
+ return res.status(400).json({
89
+ status: "error",
90
+ message: "السعر لا يمكن أن يكون سالباً",
91
+ });
92
+ }
93
+
94
+ const menuItem = await MenuItem.findByIdAndUpdate(id, updates, {
95
+ new: true,
96
+ runValidators: true,
97
+ });
98
+
99
+ if (!menuItem) {
100
+ return res.status(404).json({
101
+ status: "error",
102
+ message: "عنصر القائمة غير موجود",
103
+ });
104
+ }
105
+
106
+ res.status(200).json({
107
+ status: "success",
108
+ message: "تم تحديث عنصر القائمة بنجاح",
109
+ data: menuItem,
110
+ });
111
+ });
112
+
113
+ // Delete menu item
114
+ export const deleteMenuItem = catchAsync(async (req, res) => {
115
+ const { id } = req.params;
116
+
117
+ const menuItem = await MenuItem.findByIdAndDelete(id);
118
+
119
+ if (!menuItem) {
120
+ return res.status(404).json({
121
+ status: "error",
122
+ message: "عنصر القائمة غير موجود",
123
+ });
124
+ }
125
+
126
+ res.status(200).json({
127
+ status: "success",
128
+ message: "تم حذف عنصر القائمة بنجاح",
129
+ });
130
+ });
131
+
132
+ // Toggle item availability
133
+ export const toggleItemAvailability = catchAsync(async (req, res) => {
134
+ const { id } = req.params;
135
+
136
+ const menuItem = await MenuItem.findById(id);
137
+
138
+ if (!menuItem) {
139
+ return res.status(404).json({
140
+ status: "error",
141
+ message: "عنصر القائمة غير موجود",
142
+ });
143
+ }
144
+
145
+ menuItem.isAvailable = !menuItem.isAvailable;
146
+ await menuItem.save();
147
+
148
+ res.status(200).json({
149
+ status: "success",
150
+ message: menuItem.isAvailable ? "تم تفعيل العنصر" : "تم تعطيل العنصر",
151
+ data: menuItem,
152
+ });
153
+ });
154
+
155
+ // Get menu categories
156
+ export const getCategories = catchAsync(async (req, res) => {
157
+ const { tenantId } = req.params;
158
+
159
+ const categories = await MenuItem.distinct("category", { tenant: tenantId });
160
+ const categoriesAr = await MenuItem.distinct("categoryAr", { tenant: tenantId });
161
+
162
+ const categoryList = categories.map((cat, idx) => ({
163
+ en: cat,
164
+ ar: categoriesAr[idx] || cat,
165
+ }));
166
+
167
+ res.status(200).json({
168
+ status: "success",
169
+ data: categoryList,
170
+ });
171
+ });
controller/notificationController.js ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Notification from "../models/NotificationModel.js";
2
+ import WhatsAppService from "../utils/whatsappService.js";
3
+ import { catchAsync } from "../utils/catchAsync.js";
4
+
5
+ // Get all notifications
6
+ export const getAllNotifications = catchAsync(async (req, res) => {
7
+ const { tenantId } = req.params;
8
+ const { status, invoiceId, page = 1, limit = 20 } = req.query;
9
+
10
+ const filter = { tenant: tenantId };
11
+ if (status) filter.status = status;
12
+ if (invoiceId) filter.invoice = invoiceId;
13
+
14
+ const skip = (page - 1) * limit;
15
+
16
+ const notifications = await Notification.find(filter)
17
+ .populate("invoice", "invoiceNumber totalAmount status")
18
+ .sort({ createdAt: -1 })
19
+ .skip(skip)
20
+ .limit(Number(limit));
21
+
22
+ const total = await Notification.countDocuments(filter);
23
+
24
+ res.status(200).json({
25
+ status: "success",
26
+ data: notifications,
27
+ pagination: {
28
+ total,
29
+ page: Number(page),
30
+ pages: Math.ceil(total / limit),
31
+ },
32
+ });
33
+ });
34
+
35
+ // Get notification by ID
36
+ export const getNotificationById = catchAsync(async (req, res) => {
37
+ const { id } = req.params;
38
+
39
+ const notification = await Notification.findById(id).populate("invoice");
40
+
41
+ if (!notification) {
42
+ return res.status(404).json({
43
+ status: "error",
44
+ message: "الإشعار غير موجود",
45
+ });
46
+ }
47
+
48
+ res.status(200).json({
49
+ status: "success",
50
+ data: notification,
51
+ });
52
+ });
53
+
54
+ // Send notification manually
55
+ export const sendNotification = catchAsync(async (req, res) => {
56
+ const { id } = req.params;
57
+
58
+ const notification = await Notification.findById(id);
59
+
60
+ if (!notification) {
61
+ return res.status(404).json({
62
+ status: "error",
63
+ message: "الإشعار غير موجود",
64
+ });
65
+ }
66
+
67
+ if (notification.status !== "queued") {
68
+ return res.status(400).json({
69
+ status: "error",
70
+ message: "يمكن فقط إرسال الإشعارات المعلقة",
71
+ });
72
+ }
73
+
74
+ try {
75
+ await WhatsAppService.sendWhatsAppMessage(notification);
76
+
77
+ res.status(200).json({
78
+ status: "success",
79
+ message: "تم إرسال الإشعار بنجاح",
80
+ data: notification,
81
+ });
82
+ } catch (error) {
83
+ console.error("Send notification error:", error);
84
+ res.status(500).json({
85
+ status: "error",
86
+ message: "فشل إرسال الإشعار",
87
+ });
88
+ }
89
+ });
90
+
91
+ // Send all queued notifications
92
+ export const sendQueuedNotifications = catchAsync(async (req, res) => {
93
+ try {
94
+ const result = await WhatsAppService.sendQueuedNotifications();
95
+
96
+ res.status(200).json({
97
+ status: "success",
98
+ message: `تم معالجة ${result.processed} إشعار`,
99
+ data: result,
100
+ });
101
+ } catch (error) {
102
+ console.error("Send queued notifications error:", error);
103
+ res.status(500).json({
104
+ status: "error",
105
+ message: "فشلت معالجة الإشعارات",
106
+ });
107
+ }
108
+ });
109
+
110
+ // Get order notifications
111
+ export const getInvoiceNotifications = catchAsync(async (req, res) => {
112
+ const { tenantId, invoiceId } = req.params;
113
+
114
+ const notifications = await Notification.find({
115
+ tenant: tenantId,
116
+ invoice: invoiceId,
117
+ }).sort({ createdAt: -1 });
118
+
119
+ res.status(200).json({
120
+ status: "success",
121
+ data: notifications,
122
+ });
123
+ });
124
+
125
+ // Delete notification
126
+ export const deleteNotification = catchAsync(async (req, res) => {
127
+ const { id } = req.params;
128
+
129
+ const notification = await Notification.findByIdAndDelete(id);
130
+
131
+ if (!notification) {
132
+ return res.status(404).json({
133
+ status: "error",
134
+ message: "الإشعار غير موجود",
135
+ });
136
+ }
137
+
138
+ res.status(200).json({
139
+ status: "success",
140
+ message: "تم حذف الإشعار بنجاح",
141
+ });
142
+ });
143
+
144
+ // Retry failed notification
145
+ export const retryNotification = catchAsync(async (req, res) => {
146
+ const { id } = req.params;
147
+
148
+ const notification = await Notification.findById(id);
149
+
150
+ if (!notification) {
151
+ return res.status(404).json({
152
+ status: "error",
153
+ message: "الإشعار غير موجود",
154
+ });
155
+ }
156
+
157
+ if (notification.status !== "failed") {
158
+ return res.status(400).json({
159
+ status: "error",
160
+ message: "يمكن فقط إعادة محاولة الإشعارات الفاشلة",
161
+ });
162
+ }
163
+
164
+ // Reset for retry
165
+ notification.status = "queued";
166
+ notification.retryCount = 0;
167
+ notification.errorMessage = null;
168
+ await notification.save();
169
+
170
+ try {
171
+ await WhatsAppService.sendWhatsAppMessage(notification);
172
+
173
+ res.status(200).json({
174
+ status: "success",
175
+ message: "تم إعادة محاولة الإشعار",
176
+ data: notification,
177
+ });
178
+ } catch (error) {
179
+ console.error("Retry notification error:", error);
180
+ res.status(500).json({
181
+ status: "error",
182
+ message: "فشلت إعادة المحاولة",
183
+ });
184
+ }
185
+ });
186
+
187
+ // Get notification statistics
188
+ export const getNotificationStats = catchAsync(async (req, res) => {
189
+ const { tenantId } = req.params;
190
+
191
+ const stats = await Notification.aggregate([
192
+ { $match: { tenant: tenantId } },
193
+ {
194
+ $group: {
195
+ _id: "$status",
196
+ count: { $sum: 1 },
197
+ },
198
+ },
199
+ ]);
200
+
201
+ const formattedStats = {
202
+ queued: 0,
203
+ sent: 0,
204
+ delivered: 0,
205
+ failed: 0,
206
+ };
207
+
208
+ stats.forEach((stat) => {
209
+ formattedStats[stat._id] = stat.count;
210
+ });
211
+
212
+ res.status(200).json({
213
+ status: "success",
214
+ data: formattedStats,
215
+ });
216
+ });
controller/orderController.js ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Order from "../models/OrderModel.js";
2
+ import Table from "../models/TableModel.js";
3
+ import MenuItem from "../models/MenuItemModel.js";
4
+ import Customer from "../models/CustomerModel.js";
5
+ import WhatsAppService from "../utils/whatsappService.js";
6
+ import eventEmitter from "../events/eventEmitter.js";
7
+ import { catchAsync } from "../utils/catchAsync.js";
8
+
9
+ /**
10
+ * =========================================
11
+ * ORDER NUMBER GENERATOR
12
+ * =========================================
13
+ */
14
+ const generateOrderNumber = async (tenantId) => {
15
+ const today = new Date();
16
+
17
+ const start = new Date(today);
18
+ start.setHours(0, 0, 0, 0);
19
+
20
+ const end = new Date(today);
21
+ end.setHours(23, 59, 59, 999);
22
+
23
+ const count = await Order.countDocuments({
24
+ tenant: tenantId,
25
+ createdAt: { $gte: start, $lte: end },
26
+ });
27
+
28
+ const dateStr = `${today.getFullYear()}${String(
29
+ today.getMonth() + 1,
30
+ ).padStart(2, "0")}${String(today.getDate()).padStart(2, "0")}`;
31
+
32
+ return `ORD-${dateStr}-${String(count + 1).padStart(4, "0")}`;
33
+ };
34
+
35
+ /**
36
+ * =========================================
37
+ * CREATE ORDER
38
+ * =========================================
39
+ */
40
+ export const createOrder = catchAsync(async (req, res) => {
41
+ const { tenantId, branchId } = req.params;
42
+
43
+ const {
44
+ orderType,
45
+ customerId,
46
+ guestInfo,
47
+ tableId,
48
+ items,
49
+ deliveryInfo,
50
+ notes,
51
+ } = req.body;
52
+
53
+ if (!orderType || !items || items.length === 0) {
54
+ return res.status(400).json({
55
+ status: "error",
56
+ message: "Order type and items are required",
57
+ });
58
+ }
59
+
60
+ if (!["dine-in", "takeaway", "delivery"].includes(orderType)) {
61
+ return res.status(400).json({
62
+ status: "error",
63
+ message: "Invalid order type",
64
+ });
65
+ }
66
+
67
+ if (orderType === "dine-in" && !tableId) {
68
+ return res.status(400).json({
69
+ status: "error",
70
+ message: "Table is required for dine-in orders",
71
+ });
72
+ }
73
+
74
+ if (orderType === "delivery" && !deliveryInfo?.address) {
75
+ return res.status(400).json({
76
+ status: "error",
77
+ message: "Delivery address is required",
78
+ });
79
+ }
80
+
81
+ let subtotal = 0;
82
+ const orderItems = [];
83
+
84
+ for (const item of items) {
85
+ const menuItem = await MenuItem.findById(item.menuItemId);
86
+
87
+ if (!menuItem) {
88
+ return res.status(404).json({
89
+ status: "error",
90
+ message: `Menu item not found: ${item.menuItemId}`,
91
+ });
92
+ }
93
+
94
+ const quantity = item.quantity || 1;
95
+ const itemTotal = menuItem.price * quantity;
96
+
97
+ subtotal += itemTotal;
98
+
99
+ orderItems.push({
100
+ menuItem: menuItem._id,
101
+ name: menuItem.nameAr || menuItem.name,
102
+ quantity,
103
+ price: menuItem.price,
104
+ notes: item.notes || "",
105
+ itemTotal,
106
+ });
107
+ }
108
+
109
+ const taxRate =
110
+ req.branch?.settings?.taxRate ?? req.tenant?.settings?.taxRate ?? 0;
111
+
112
+ // tax calculation
113
+ const tax = subtotal * taxRate;
114
+ const total = subtotal + tax;
115
+
116
+ const orderNumber = await generateOrderNumber(tenantId);
117
+
118
+ const order = await Order.create({
119
+ tenant: tenantId,
120
+ branch: branchId,
121
+ orderNumber,
122
+ customer: customerId || null,
123
+ guestInfo: !customerId ? guestInfo : null,
124
+ orderType,
125
+ table: orderType === "dine-in" ? tableId : null,
126
+ items: orderItems,
127
+ subtotal,
128
+ tax,
129
+ total,
130
+ deliveryInfo: orderType === "delivery" ? deliveryInfo : null,
131
+ notes,
132
+ });
133
+
134
+ // TABLE LOCK
135
+ if (orderType === "dine-in" && tableId) {
136
+ await Table.findByIdAndUpdate(tableId, {
137
+ status: "occupied",
138
+ currentOrderId: order._id,
139
+ });
140
+ }
141
+
142
+ // EVENTS
143
+ eventEmitter.emit("order.created", order);
144
+
145
+ // WhatsApp notify (order created)
146
+ let phone = null;
147
+
148
+ if (customerId) {
149
+ const customer = await Customer.findById(customerId);
150
+ phone = customer?.phone;
151
+ } else {
152
+ phone = guestInfo?.phone;
153
+ }
154
+
155
+ if (phone) {
156
+ try {
157
+ await WhatsAppService.queueNotification({
158
+ tenant: tenantId,
159
+ order: order._id,
160
+ phoneNumber: phone,
161
+ notificationType: "order-confirmed",
162
+ orderNumber: order.orderNumber,
163
+ language: "ar",
164
+ });
165
+ } catch (err) {
166
+ console.error("WhatsApp error:", err);
167
+ }
168
+ }
169
+
170
+ res.status(201).json({
171
+ status: "success",
172
+ data: order,
173
+ });
174
+ });
175
+
176
+ /**
177
+ * =========================================
178
+ * GET ALL ORDERS
179
+ * =========================================
180
+ */
181
+ export const getAllOrders = catchAsync(async (req, res) => {
182
+ const { tenantId, branchId } = req.params;
183
+ const { status, orderType, page = 1, limit = 20 } = req.query;
184
+
185
+ const filter = {
186
+ tenant: tenantId,
187
+ branch: branchId,
188
+ };
189
+
190
+ if (status) filter.status = status;
191
+ if (orderType) filter.orderType = orderType;
192
+
193
+ const skip = (page - 1) * limit;
194
+
195
+ const orders = await Order.find(filter)
196
+ .populate("customer", "name phone")
197
+ .populate("table", "displayName")
198
+ .sort({ createdAt: -1 })
199
+ .skip(skip)
200
+ .limit(Number(limit));
201
+
202
+ const total = await Order.countDocuments(filter);
203
+
204
+ res.status(200).json({
205
+ status: "success",
206
+ data: orders,
207
+ pagination: {
208
+ total,
209
+ page: Number(page),
210
+ pages: Math.ceil(total / limit),
211
+ },
212
+ });
213
+ });
214
+
215
+ /**
216
+ * =========================================
217
+ * GET ORDER BY ID
218
+ * =========================================
219
+ */
220
+ export const getOrderById = catchAsync(async (req, res) => {
221
+ const { id } = req.params;
222
+
223
+ const order = await Order.findById(id)
224
+ .populate("customer")
225
+ .populate("table")
226
+ .populate("items.menuItem");
227
+
228
+ if (!order) {
229
+ return res.status(404).json({
230
+ status: "error",
231
+ message: "Order not found",
232
+ });
233
+ }
234
+
235
+ res.status(200).json({
236
+ status: "success",
237
+ data: order,
238
+ });
239
+ });
240
+
241
+ /**
242
+ * =========================================
243
+ * UPDATE ORDER STATUS
244
+ * =========================================
245
+ */
246
+ export const updateOrderStatus = catchAsync(async (req, res) => {
247
+ const { id } = req.params;
248
+ const { status } = req.body;
249
+
250
+ const valid = ["pending", "preparing", "ready", "completed", "cancelled"];
251
+
252
+ if (!valid.includes(status)) {
253
+ return res.status(400).json({
254
+ status: "error",
255
+ message: "Invalid status",
256
+ });
257
+ }
258
+
259
+ const order = await Order.findByIdAndUpdate(id, { status }, { new: true });
260
+
261
+ if (!order) {
262
+ return res.status(404).json({
263
+ status: "error",
264
+ message: "Order not found",
265
+ });
266
+ }
267
+
268
+ // EVENT SYSTEM (MAIN ARCHITECTURE)
269
+ eventEmitter.emit("order.status.changed", order);
270
+
271
+ res.status(200).json({
272
+ status: "success",
273
+ message: "Status updated",
274
+ data: order,
275
+ });
276
+ });
277
+
278
+ /**
279
+ * =========================================
280
+ * COMPLETE ORDER (FREE TABLE)
281
+ * =========================================
282
+ */
283
+ export const completeOrder = catchAsync(async (req, res) => {
284
+ const { id } = req.params;
285
+
286
+ const order = await Order.findByIdAndUpdate(
287
+ id,
288
+ {
289
+ status: "completed",
290
+ completedAt: new Date(),
291
+ },
292
+ { new: true },
293
+ );
294
+
295
+ if (!order) {
296
+ return res.status(404).json({
297
+ status: "error",
298
+ message: "Order not found",
299
+ });
300
+ }
301
+
302
+ if (order.orderType === "dine-in" && order.table) {
303
+ await Table.findByIdAndUpdate(order.table, {
304
+ status: "available",
305
+ currentOrderId: null,
306
+ });
307
+ }
308
+
309
+ eventEmitter.emit("order.status.changed", order);
310
+
311
+ res.status(200).json({
312
+ status: "success",
313
+ message: "Order completed",
314
+ data: order,
315
+ });
316
+ });
317
+
318
+ /**
319
+ * =========================================
320
+ * DELETE ORDER
321
+ * =========================================
322
+ */
323
+ export const deleteOrder = catchAsync(async (req, res) => {
324
+ const { id } = req.params;
325
+
326
+ const order = await Order.findById(id);
327
+
328
+ if (!order) {
329
+ return res.status(404).json({
330
+ status: "error",
331
+ message: "Order not found",
332
+ });
333
+ }
334
+
335
+ // FREE TABLE IF EXISTS
336
+ if (order.orderType === "dine-in" && order.table) {
337
+ await Table.findByIdAndUpdate(order.table, {
338
+ status: "available",
339
+ currentOrderId: null,
340
+ });
341
+ }
342
+
343
+ await Order.findByIdAndDelete(id);
344
+
345
+ eventEmitter.emit("order.deleted", order);
346
+
347
+ res.status(200).json({
348
+ status: "success",
349
+ message: "Order deleted",
350
+ });
351
+ });
controller/productController.js CHANGED
@@ -141,7 +141,7 @@ export const deleteProduct = async (req, res) => {
141
  });
142
 
143
  if (!product) {
144
- return res.status(404).json({ message: "المنج غير موجودلهف" });
145
  }
146
 
147
  res.status(200).json({ message: "تم حذف المنتج بنجاح" });
 
141
  });
142
 
143
  if (!product) {
144
+ return res.status(404).json({ message: "المنتج غير موجود" });
145
  }
146
 
147
  res.status(200).json({ message: "تم حذف المنتج بنجاح" });
controller/superAdminController.js CHANGED
@@ -381,3 +381,111 @@ export const getUsageTrends = async (req, res) => {
381
  res.status(500).json({ message: 'Failed to generate usage trends' });
382
  }
383
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  res.status(500).json({ message: 'Failed to generate usage trends' });
382
  }
383
  };
384
+
385
+ // Update tenant business types (multi-select: restaurant, cafe, sales)
386
+ export const updateTenantType = async (req, res) => {
387
+ try {
388
+ // Validate super admin access
389
+ if (req.user.role !== 'super_admin') {
390
+ return res.status(403).json({
391
+ status: 'error',
392
+ message: 'رفع الوصول. مدير النظام فقط'
393
+ });
394
+ }
395
+
396
+ const { tenantId } = req.params;
397
+ const { tenantTypes } = req.body;
398
+
399
+ // Validate tenant types (must be array)
400
+ if (!tenantTypes || !Array.isArray(tenantTypes) || tenantTypes.length === 0) {
401
+ return res.status(400).json({
402
+ status: 'error',
403
+ message: 'يجب تحديد نوع عمل واحد على الأقل. أرسل مصفوفة: ["restaurant", "cafe", "sales"]'
404
+ });
405
+ }
406
+
407
+ // Validate each type
408
+ const validTypes = ['restaurant', 'cafe', 'sales'];
409
+ for (const type of tenantTypes) {
410
+ if (!validTypes.includes(type)) {
411
+ return res.status(400).json({
412
+ status: 'error',
413
+ message: `نوع عمل غير صحيح: ${type}. الأنواع الصحيحة: restaurant أو cafe أو sales`
414
+ });
415
+ }
416
+ }
417
+
418
+ // Remove duplicates
419
+ const uniqueTypes = [...new Set(tenantTypes)];
420
+
421
+ // Check if tenant exists
422
+ const tenant = await Tenant.findById(tenantId);
423
+ if (!tenant) {
424
+ return res.status(404).json({
425
+ status: 'error',
426
+ message: 'لم يتم العثور على حساب العمل'
427
+ });
428
+ }
429
+
430
+ // Update tenant types
431
+ const updatedTenant = await Tenant.findByIdAndUpdate(
432
+ tenantId,
433
+ { tenantTypes: uniqueTypes },
434
+ { new: true, runValidators: true }
435
+ );
436
+
437
+ res.status(200).json({
438
+ status: 'success',
439
+ message: 'تم تحديث أنواع العمل بنجاح',
440
+ data: {
441
+ tenantId: updatedTenant._id,
442
+ tenantName: updatedTenant.name,
443
+ tenantTypes: updatedTenant.tenantTypes,
444
+ updatedAt: updatedTenant.updatedAt
445
+ }
446
+ });
447
+
448
+ } catch (error) {
449
+ console.error('Update tenant types error:', error);
450
+ res.status(500).json({
451
+ status: 'error',
452
+ message: 'فشل تحديث أنواع العمل'
453
+ });
454
+ }
455
+ };
456
+
457
+ // Get all tenants with features
458
+ export const getAllTenants = async (req, res) => {
459
+ try {
460
+ // Validate super admin access
461
+ if (req.user.role !== 'super_admin') {
462
+ return res.status(403).json({
463
+ status: 'error',
464
+ message: 'رفع الوصول. مدير النظام فقط'
465
+ });
466
+ }
467
+
468
+ const { status, type } = req.query;
469
+ const filter = {};
470
+
471
+ if (status) filter.status = status;
472
+ if (type) filter.tenantType = type;
473
+
474
+ const tenants = await Tenant.find(filter)
475
+ .select('_id name slug tenantTypes status subscriptionPackage createdAt monthlyFee ownerName ownerEmail')
476
+ .sort({ createdAt: -1 });
477
+
478
+ res.status(200).json({
479
+ status: 'success',
480
+ data: tenants,
481
+ total: tenants.length
482
+ });
483
+
484
+ } catch (error) {
485
+ console.error('Get tenants error:', error);
486
+ res.status(500).json({
487
+ status: 'error',
488
+ message: 'فشل جلب قائمة العملاء'
489
+ });
490
+ }
491
+ };
controller/tableController.js ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Table from "../models/TableModel.js";
2
+ import Invoice from "../models/InvoiceModel.js";
3
+ import { catchAsync } from "../utils/catchAsync.js";
4
+
5
+ // Get all tables for a branch
6
+ export const getAllTables = catchAsync(async (req, res) => {
7
+ const { tenantId, branchId } = req.params;
8
+
9
+ const tables = await Table.find({
10
+ tenant: tenantId,
11
+ branch: branchId,
12
+ isActive: true,
13
+ })
14
+ .populate("currentOrderId", "invoiceNumber totalAmount restaurantStatus")
15
+ .sort({ floor: 1, section: 1, tableNumber: 1 });
16
+
17
+ res.status(200).json({
18
+ status: "success",
19
+ data: tables,
20
+ });
21
+ });
22
+
23
+ // Get floor plan (all tables with positions)
24
+ export const getFloorPlan = catchAsync(async (req, res) => {
25
+ const { tenantId, branchId } = req.params;
26
+
27
+ const tables = await Table.find({
28
+ tenant: tenantId,
29
+ branch: branchId,
30
+ isActive: true,
31
+ }).populate("currentOrderId", "invoiceNumber totalAmount restaurantStatus");
32
+
33
+ // Group by floor
34
+ const floorPlan = {};
35
+ tables.forEach((table) => {
36
+ if (!floorPlan[table.floor]) {
37
+ floorPlan[table.floor] = [];
38
+ }
39
+ floorPlan[table.floor].push(table);
40
+ });
41
+
42
+ res.status(200).json({
43
+ status: "success",
44
+ data: floorPlan,
45
+ });
46
+ });
47
+
48
+ // Create table
49
+ export const createTable = catchAsync(async (req, res) => {
50
+ const { tenantId, branchId } = req.params;
51
+ const { tableNumber, displayName, capacity, floor, section, shape } = req.body;
52
+
53
+ // Validation
54
+ if (!tableNumber || !displayName || !capacity) {
55
+ return res.status(400).json({
56
+ status: "error",
57
+ message: "الرجاء ملء جميع الحقول المطلوبة",
58
+ });
59
+ }
60
+
61
+ if (capacity < 1) {
62
+ return res.status(400).json({
63
+ status: "error",
64
+ message: "السعة يجب أن تكون 1 على الأقل",
65
+ });
66
+ }
67
+
68
+ // Check if table number already exists
69
+ const existingTable = await Table.findOne({
70
+ tenant: tenantId,
71
+ branch: branchId,
72
+ tableNumber,
73
+ });
74
+
75
+ if (existingTable) {
76
+ return res.status(400).json({
77
+ status: "error",
78
+ message: "رقم الطاولة موجود بالفعل",
79
+ });
80
+ }
81
+
82
+ const table = await Table.create({
83
+ tenant: tenantId,
84
+ branch: branchId,
85
+ tableNumber,
86
+ displayName,
87
+ capacity,
88
+ floor: floor || "الطابق الأول",
89
+ section: section || "الرئيسية",
90
+ shape: shape || "square",
91
+ });
92
+
93
+ res.status(201).json({
94
+ status: "success",
95
+ message: "تم إضافة الطاولة بنجاح",
96
+ data: table,
97
+ });
98
+ });
99
+
100
+ // Update table
101
+ export const updateTable = catchAsync(async (req, res) => {
102
+ const { id } = req.params;
103
+ const updates = req.body;
104
+
105
+ // Prevent manually overriding occupied status without an order
106
+ if (updates.status === "available") {
107
+ updates.currentOrderId = null;
108
+ }
109
+
110
+ const table = await Table.findByIdAndUpdate(id, updates, {
111
+ new: true,
112
+ runValidators: true,
113
+ });
114
+
115
+ if (!table) {
116
+ return res.status(404).json({
117
+ status: "error",
118
+ message: "الطاولة غير موجودة",
119
+ });
120
+ }
121
+
122
+ res.status(200).json({
123
+ status: "success",
124
+ message: "تم تحديث الطاولة بنجاح",
125
+ data: table,
126
+ });
127
+ });
128
+
129
+ // Delete table (soft)
130
+ export const deleteTable = catchAsync(async (req, res) => {
131
+ const { id } = req.params;
132
+
133
+ const table = await Table.findById(id);
134
+
135
+ if (!table) {
136
+ return res.status(404).json({
137
+ status: "error",
138
+ message: "الطاولة غير موجودة",
139
+ });
140
+ }
141
+
142
+ // Check if table has active order
143
+ if (table.currentOrderId) {
144
+ return res.status(400).json({
145
+ status: "error",
146
+ message: "لا يمكن حذف طاولة بها طلب نشط",
147
+ });
148
+ }
149
+
150
+ // table.isActive = false;
151
+ // await table.save();
152
+
153
+ await Table.findByIdAndDelete(id);
154
+
155
+
156
+ res.status(200).json({
157
+ status: "success",
158
+ message: "تم حذف الطاولة بنجاح",
159
+ });
160
+ });
161
+
162
+ // Update table position on floor plan
163
+ export const updateTablePosition = catchAsync(async (req, res) => {
164
+ const { id } = req.params;
165
+ const { x, y } = req.body;
166
+
167
+ if (x === undefined || y === undefined) {
168
+ return res.status(400).json({
169
+ status: "error",
170
+ message: "الموضع المطلوب غير صحيح",
171
+ });
172
+ }
173
+
174
+ const table = await Table.findByIdAndUpdate(
175
+ id,
176
+ { position: { x, y } },
177
+ { new: true }
178
+ );
179
+
180
+ if (!table) {
181
+ return res.status(404).json({
182
+ status: "error",
183
+ message: "الطاولة غير موجودة",
184
+ });
185
+ }
186
+
187
+ res.status(200).json({
188
+ status: "success",
189
+ message: "تم تحديث موضع الطاولة",
190
+ data: table,
191
+ });
192
+ });
193
+
194
+ // Get table status
195
+ export const getTableStatus = catchAsync(async (req, res) => {
196
+ const { id } = req.params;
197
+
198
+ const table = await Table.findById(id).populate(
199
+ "currentOrderId",
200
+ "invoiceNumber totalAmount restaurantStatus"
201
+ );
202
+
203
+ if (!table) {
204
+ return res.status(404).json({
205
+ status: "error",
206
+ message: "الطاولة غير موجودة",
207
+ });
208
+ }
209
+
210
+ res.status(200).json({
211
+ status: "success",
212
+ data: {
213
+ id: table._id,
214
+ status: table.status,
215
+ displayName: table.displayName,
216
+ currentOrder: table.currentOrderId,
217
+ },
218
+ });
219
+ });
220
+
221
+ // ✅ FIXED: was calling undefined TableService — now direct DB logic
222
+ export const updateTableStatus = catchAsync(async (req, res) => {
223
+ const { status, currentOrderId } = req.body;
224
+ const { id } = req.params;
225
+
226
+ const validStatuses = ["available", "occupied", "reserved", "maintenance"];
227
+ if (!validStatuses.includes(status)) {
228
+ return res.status(400).json({
229
+ status: "error",
230
+ message: "حالة غير صالحة",
231
+ });
232
+ }
233
+
234
+ const table = await Table.findById(id);
235
+ if (!table) {
236
+ return res.status(404).json({
237
+ status: "error",
238
+ message: "الطاولة غير موجودة",
239
+ });
240
+ }
241
+
242
+ // ✅ Business rule: prevent occupying an already-occupied table by a different order
243
+ if (status === "occupied" && table.status === "occupied") {
244
+ const existingOrderId = table.currentOrderId?.toString();
245
+ const incomingOrderId = currentOrderId?.toString();
246
+ if (existingOrderId && incomingOrderId && existingOrderId !== incomingOrderId) {
247
+ return res.status(400).json({
248
+ status: "error",
249
+ message: "الطاولة مشغولة بطلب آخر — يجب إتمام الحساب أولاً",
250
+ });
251
+ }
252
+ }
253
+
254
+ table.status = status;
255
+ if (status === "available") {
256
+ table.currentOrderId = null;
257
+ } else if (currentOrderId) {
258
+ table.currentOrderId = currentOrderId;
259
+ }
260
+
261
+ await table.save();
262
+
263
+ res.status(200).json({
264
+ status: "success",
265
+ message: "تم تحديث حالة الطاولة",
266
+ data: table,
267
+ });
268
+ });
events/eventEmitter.js ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import EventEmitter from "events";
2
+
3
+ const eventEmitter = new EventEmitter();
4
+
5
+ export default eventEmitter;
index.js CHANGED
@@ -15,6 +15,11 @@ import authRoutes from "./routes/authRoutes.js";
15
  import catalogRoutes from "./routes/catalogRoutes.js";
16
  import aiAnalyticsRoutes from "./routes/aiAnalyticsRoutes.js";
17
  import superAdminRoutes from "./routes/superAdminRoutes.js";
 
 
 
 
 
18
  import { dbConnection } from './config/database.js';
19
 
20
  dotenv.config();
@@ -33,32 +38,24 @@ const allowedOrigins = [
33
 
34
  app.use(cors({
35
  origin: (origin, callback) => {
36
- // Allow known origins, missing origins (server-to-server/Postman), or any local development origin
37
  if (!origin || allowedOrigins.includes(origin) || /localhost|127\.0\.0\.1|192\.168\./.test(origin)) {
38
  callback(null, true);
39
  } else {
40
- console.warn(`CORS blocked request from origin: ${origin}`);
41
  callback(new Error(`Not allowed by CORS: ${origin}`));
42
  }
43
  },
44
- credentials: true
45
  }));
46
 
47
- // Enhanced compression for better throughput with large datasets
48
- app.use(compression({
49
- level: 6, // Default level, good balance
50
- threshold: 1024, // Compress responses larger than 1KB
51
- }));
52
 
53
- // Increased payload limits to handle larger requests (50MB for JSON, 50MB for URL-encoded)
54
- // This supports edge cases with large data imports or bulk operations
55
- app.use(express.urlencoded({ extended: true, limit: '50mb', parameterLimit: 10000 }));
56
- app.use(express.json({ limit: '50mb' }));
57
 
58
- // Request logging with custom format to avoid log bloat
59
  app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
60
 
61
- // Health check endpoint for load balancers
62
  app.get('/health', (req, res) => {
63
  res.status(200).json({ status: 'healthy', timestamp: new Date().toISOString() });
64
  });
@@ -75,21 +72,27 @@ app.use('/catalog', catalogRoutes);
75
  app.use('/auth', authRoutes);
76
  app.use('/ai-analytics', aiAnalyticsRoutes);
77
  app.use('/super-admin', superAdminRoutes);
 
 
 
 
 
 
78
  app.get('/', (req, res) => {
79
- res.status(200).json({ message: 'App Is running' });
80
  });
81
 
82
- // Error handling middleware
83
  app.use((err, req, res, next) => {
84
- console.error('Error:', err);
85
- res.status(err.status || 500).json({
 
86
  message: err.message || 'Internal Server Error',
87
- status: err.status || 500
88
  });
89
  });
90
 
91
  const PORT = process.env.PORT || 5000;
92
  app.listen(PORT, () => {
93
  console.log(`Server running on port ${PORT}`);
94
- console.log(`Health check endpoint: http://localhost:${PORT}/health`);
95
- });
 
15
  import catalogRoutes from "./routes/catalogRoutes.js";
16
  import aiAnalyticsRoutes from "./routes/aiAnalyticsRoutes.js";
17
  import superAdminRoutes from "./routes/superAdminRoutes.js";
18
+ import menuRoutes from "./routes/menuRoutes.js";
19
+ import tableRoutes from "./routes/orderRoutesRestaurant.js";
20
+ import deliveryRoutes from "./routes/deliveryRoutes.js";
21
+ import notificationRoutes from "./routes/notificationRoutes.js";
22
+ import driverRoutes from "./routes/driverRoutes.js";
23
  import { dbConnection } from './config/database.js';
24
 
25
  dotenv.config();
 
38
 
39
  app.use(cors({
40
  origin: (origin, callback) => {
 
41
  if (!origin || allowedOrigins.includes(origin) || /localhost|127\.0\.0\.1|192\.168\./.test(origin)) {
42
  callback(null, true);
43
  } else {
44
+ console.warn(`CORS blocked: ${origin}`);
45
  callback(new Error(`Not allowed by CORS: ${origin}`));
46
  }
47
  },
48
+ credentials: true,
49
  }));
50
 
51
+ app.use(compression({ level: 6, threshold: 1024 }));
 
 
 
 
52
 
53
+ // ✅ Reduced from 50mb — a POS system never needs 50MB request bodies
54
+ app.use(express.urlencoded({ extended: true, limit: '2mb', parameterLimit: 1000 }));
55
+ app.use(express.json({ limit: '2mb' }));
 
56
 
 
57
  app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
58
 
 
59
  app.get('/health', (req, res) => {
60
  res.status(200).json({ status: 'healthy', timestamp: new Date().toISOString() });
61
  });
 
72
  app.use('/auth', authRoutes);
73
  app.use('/ai-analytics', aiAnalyticsRoutes);
74
  app.use('/super-admin', superAdminRoutes);
75
+ app.use('/menu', menuRoutes);
76
+ app.use('/table', tableRoutes);
77
+ app.use('/delivery', deliveryRoutes);
78
+ app.use('/notification', notificationRoutes);
79
+ app.use('/drivers', driverRoutes);
80
+
81
  app.get('/', (req, res) => {
82
+ res.status(200).json({ message: 'App is running' });
83
  });
84
 
85
+ // ✅ Fixed: use statusCode (AppError) with fallback to status (other errors)
86
  app.use((err, req, res, next) => {
87
+ const statusCode = err.statusCode || err.status || 500;
88
+ console.error(`[${statusCode}] ${err.message}`);
89
+ res.status(statusCode).json({
90
  message: err.message || 'Internal Server Error',
91
+ status: statusCode,
92
  });
93
  });
94
 
95
  const PORT = process.env.PORT || 5000;
96
  app.listen(PORT, () => {
97
  console.log(`Server running on port ${PORT}`);
98
+ });
 
middleware/tenantFeatureMiddleware.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const requireRestaurantTenant = (req, res, next) => {
2
+ const tenantTypes = req.user?.tenant?.tenantTypes;
3
+ const types = Array.isArray(tenantTypes) ? tenantTypes : [];
4
+
5
+ if (!types.includes("restaurant")) {
6
+ return res.status(403).json({
7
+ message: "هذه الميزة متاحة فقط لحسابات المطاعم",
8
+ code: "RESTAURANT_ONLY",
9
+ });
10
+ }
11
+
12
+ next();
13
+ };
14
+
models/BranchModel.js CHANGED
@@ -29,6 +29,14 @@ const branchSchema = new mongoose.Schema(
29
  trim: true,
30
  default: "",
31
  },
 
 
 
 
 
 
 
 
32
  isPrimary: {
33
  type: Boolean,
34
  default: false,
 
29
  trim: true,
30
  default: "",
31
  },
32
+ settings: {
33
+ taxRate: {
34
+ type: Number,
35
+ default: null, // null = inherit from tenant settings
36
+ min: 0,
37
+ max: 1,
38
+ },
39
+ },
40
  isPrimary: {
41
  type: Boolean,
42
  default: false,
models/CustomerModel.js CHANGED
@@ -48,12 +48,12 @@ const customerSchema = new mongoose.Schema(
48
  ref: "User",
49
  default: null,
50
  },
51
- invoices: [
52
- {
53
- type: mongoose.Schema.Types.ObjectId,
54
- ref: "Invoice",
55
- },
56
- ],
57
  isDeleted: {
58
  type: Boolean,
59
  default: false,
 
48
  ref: "User",
49
  default: null,
50
  },
51
+ // invoices: [
52
+ // {
53
+ // type: mongoose.Schema.Types.ObjectId,
54
+ // ref: "Invoice",
55
+ // },
56
+ // ],
57
  isDeleted: {
58
  type: Boolean,
59
  default: false,
models/DeliveryModel.js ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const deliverySchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ branch: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Branch",
14
+ required: true,
15
+ index: true,
16
+ },
17
+ invoice: {
18
+ type: mongoose.Schema.Types.ObjectId,
19
+ ref: "Invoice",
20
+ required: true,
21
+ unique: true,
22
+ },
23
+ customer: {
24
+ type: mongoose.Schema.Types.ObjectId,
25
+ ref: "Customer",
26
+ default: null,
27
+ },
28
+ deliveryPerson: {
29
+ type: mongoose.Schema.Types.ObjectId,
30
+ ref: "User",
31
+ required: true,
32
+ },
33
+ deliveryAddress: {
34
+ street: String,
35
+ city: String,
36
+ phone: String,
37
+ notes: String,
38
+ coordinates: {
39
+ latitude: Number,
40
+ longitude: Number,
41
+ },
42
+ },
43
+ status: {
44
+ type: String,
45
+ enum: ["assigned", "confirmed", "in-transit", "delivered", "failed"],
46
+ default: "assigned",
47
+ index: true,
48
+ },
49
+ statusHistory: [
50
+ {
51
+ status: String,
52
+ timestamp: { type: Date, default: Date.now },
53
+ note: String,
54
+ },
55
+ ],
56
+ assignedAt: {
57
+ type: Date,
58
+ default: Date.now,
59
+ },
60
+ startedAt: {
61
+ type: Date,
62
+ default: null,
63
+ },
64
+ deliveredAt: {
65
+ type: Date,
66
+ default: null,
67
+ },
68
+ estimatedDeliveryTime: {
69
+ type: Number,
70
+ default: 30,
71
+ description: "Estimated delivery time in minutes",
72
+ },
73
+ actualDeliveryTime: {
74
+ type: Number,
75
+ default: null,
76
+ },
77
+ notes: {
78
+ type: String,
79
+ default: "",
80
+ }
81
+ },
82
+ { timestamps: true }
83
+ );
84
+
85
+ // Index for faster queries
86
+ deliverySchema.index({ tenant: 1, branch: 1 });
87
+ deliverySchema.index({ tenant: 1, status: 1 });
88
+ deliverySchema.index({ tenant: 1, deliveryPerson: 1 });
89
+ deliverySchema.index({ createdAt: -1 });
90
+
91
+ const Delivery = mongoose.model("Delivery", deliverySchema);
92
+
93
+ export default Delivery;
models/DriverModel.js ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const driverSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ branch: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Branch",
14
+ default: null,
15
+ index: true,
16
+ },
17
+ name: {
18
+ type: String,
19
+ required: true,
20
+ trim: true,
21
+ },
22
+ phone: {
23
+ type: String,
24
+ required: true,
25
+ trim: true,
26
+ },
27
+ status: {
28
+ type: String,
29
+ enum: ["available", "busy", "off-duty"],
30
+ default: "available",
31
+ },
32
+ currentOrders: {
33
+ type: Number,
34
+ default: 0,
35
+ },
36
+ // ✅ Track actual invoice IDs assigned to this driver
37
+ currentOrderIds: [
38
+ {
39
+ type: mongoose.Schema.Types.ObjectId,
40
+ ref: "Invoice",
41
+ },
42
+ ],
43
+ maxOrders: {
44
+ type: Number,
45
+ default: 3,
46
+ },
47
+ vehicleType: {
48
+ type: String,
49
+ enum: ["motorcycle", "car", "bicycle"],
50
+ default: "motorcycle",
51
+ },
52
+ licensePlate: {
53
+ type: String,
54
+ trim: true,
55
+ },
56
+ notes: {
57
+ type: String,
58
+ trim: true,
59
+ },
60
+ isActive: {
61
+ type: Boolean,
62
+ default: true,
63
+ index: true,
64
+ },
65
+ },
66
+ { timestamps: true }
67
+ );
68
+
69
+ driverSchema.index({ tenant: 1, phone: 1 });
70
+
71
+ const Driver = mongoose.model("Driver", driverSchema);
72
+
73
+ export default Driver;
models/InvoiceModel.js CHANGED
@@ -69,11 +69,11 @@ const invoiceSchema = new mongoose.Schema(
69
  method: {
70
  type: String,
71
  default: "cash",
72
- enum: ["cash", "transfer"]
73
  },
74
  transferType: {
75
  type: String,
76
- enum: ["instapay", "vodafone_cash", "bank_transfer"],
77
  default: null
78
  },
79
  receivedBy: {
@@ -126,6 +126,69 @@ const invoiceSchema = new mongoose.Schema(
126
  type: Boolean,
127
  default: false,
128
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  isDeleted: {
130
  type: Boolean,
131
  default: false,
@@ -134,8 +197,12 @@ const invoiceSchema = new mongoose.Schema(
134
  { timestamps: true }
135
  );
136
 
 
 
 
137
  invoiceSchema.index({ tenant: 1, branch: 1, invoiceNumber: 1 }, { unique: true });
138
 
 
139
  invoiceSchema.methods.calculateTotals = function () {
140
  this.serviceRevenue = 0;
141
  this.productRevenue = 0;
@@ -143,7 +210,7 @@ invoiceSchema.methods.calculateTotals = function () {
143
  this.hasServices = false;
144
 
145
  this.items.forEach((item) => {
146
- item.total = Number(item.price || 0) * Number(item.quantity || 0);
147
 
148
  // Track granular revenue
149
  if (item.type === "service") {
@@ -156,29 +223,37 @@ invoiceSchema.methods.calculateTotals = function () {
156
  }
157
  });
158
 
159
- this.subtotal = this.items.reduce((sum, item) => sum + Number(item.total || 0), 0);
160
- this.totalAmount = Math.max(this.subtotal - Number(this.discount || 0) + Number(this.taxAmount || 0), 0);
 
 
 
 
 
 
 
 
 
 
161
 
162
  if (this.payments?.length || this.isModified("payments")) {
163
- this.paidAmount = this.payments.reduce(
164
- (sum, payment) => sum + (payment.confirmed !== false ? Number(payment.amount || 0) : 0),
165
- 0
 
 
166
  );
167
  }
168
 
169
- this.remainingAmount = Math.max(this.totalAmount - Number(this.paidAmount || 0), 0);
 
 
170
 
171
- if (this.status === "cancelled") {
172
- return;
173
- }
174
 
175
- if (this.remainingAmount <= 0) {
176
- this.status = "paid";
177
- } else if (this.paidAmount > 0) {
178
- this.status = "partial";
179
- } else {
180
- this.status = "open";
181
- }
182
  };
183
 
184
  invoiceSchema.pre("save", function () {
 
69
  method: {
70
  type: String,
71
  default: "cash",
72
+ enum: ["cash", "transfer", "partial", "unpaid"]
73
  },
74
  transferType: {
75
  type: String,
76
+ enum: ["instapay", "vodafone_cash", "bank_transfer", "wallet"],
77
  default: null
78
  },
79
  receivedBy: {
 
126
  type: Boolean,
127
  default: false,
128
  },
129
+ // Restaurant/Cafe Specific Data
130
+ restaurantData: {
131
+ orderType: {
132
+ type: String,
133
+ enum: ["dine-in", "takeaway", "delivery"],
134
+ default: null,
135
+ },
136
+ table: {
137
+ type: mongoose.Schema.Types.ObjectId,
138
+ ref: "Table",
139
+ default: null,
140
+ },
141
+ guestInfo: {
142
+ name: String,
143
+ phone: String,
144
+ },
145
+ deliveryAddress: String,
146
+ driver: {
147
+ driverId: {
148
+ type: mongoose.Schema.Types.ObjectId,
149
+ ref: "Driver",
150
+ default: null,
151
+ },
152
+ driverUserId: {
153
+ type: mongoose.Schema.Types.ObjectId,
154
+ ref: "User",
155
+ default: null,
156
+ },
157
+ driverName: { type: String, default: "" },
158
+ driverPhone: { type: String, default: "" },
159
+ assignedAt: { type: Date, default: null },
160
+ // ✅ NEW: Track actual payment received from driver
161
+ paymentReceived: {
162
+ amount: { type: Number, default: 0 },
163
+ receivedAt: { type: Date, default: null },
164
+ receivedBy: {
165
+ type: mongoose.Schema.Types.ObjectId,
166
+ ref: "User",
167
+ default: null,
168
+ },
169
+ notes: { type: String, default: "" },
170
+ },
171
+ // ✅ NEW: Track driver status when assigned
172
+ driverStatus: {
173
+ type: String,
174
+ enum: ["pending_assignment", "available", "busy", "off-duty"],
175
+ default: "pending_assignment",
176
+ },
177
+ },
178
+ },
179
+ serviceCharge: {
180
+ type: Number,
181
+ default: 0,
182
+ },
183
+ deliveryCharge: {
184
+ type: Number,
185
+ default: 0,
186
+ },
187
+ restaurantStatus: {
188
+ type: String,
189
+ enum: ["pending", "preparing", "ready_for_delivery", "shipped", "delivered"],
190
+ default: "pending",
191
+ },
192
  isDeleted: {
193
  type: Boolean,
194
  default: false,
 
197
  { timestamps: true }
198
  );
199
 
200
+ const round2 = (n) => Math.round((n + Number.EPSILON) * 100) / 100;
201
+
202
+
203
  invoiceSchema.index({ tenant: 1, branch: 1, invoiceNumber: 1 }, { unique: true });
204
 
205
+
206
  invoiceSchema.methods.calculateTotals = function () {
207
  this.serviceRevenue = 0;
208
  this.productRevenue = 0;
 
210
  this.hasServices = false;
211
 
212
  this.items.forEach((item) => {
213
+ item.total = round2(Number(item.price || 0) * Number(item.quantity || 0));
214
 
215
  // Track granular revenue
216
  if (item.type === "service") {
 
223
  }
224
  });
225
 
226
+ this.subtotal = round2(
227
+ this.items.reduce((sum, item) => sum + Number(item.total || 0), 0)
228
+ );
229
+
230
+ const discount = round2(Number(this.discount || 0));
231
+ const tax = round2(Number(this.taxAmount || 0));
232
+ const serviceCharge = round2(Number(this.serviceCharge || 0));
233
+ const deliveryCharge = round2(Number(this.deliveryCharge || 0));
234
+
235
+ this.totalAmount = round2(
236
+ Math.max(this.subtotal - discount + tax + serviceCharge + deliveryCharge, 0)
237
+ );
238
 
239
  if (this.payments?.length || this.isModified("payments")) {
240
+ this.paidAmount = round2(
241
+ this.payments.reduce((sum, payment) => {
242
+ if (payment.method === "cash") return sum + Number(payment.amount || 0);
243
+ return sum + (payment.confirmed === true ? Number(payment.amount || 0) : 0);
244
+ }, 0)
245
  );
246
  }
247
 
248
+ this.remainingAmount = round2(
249
+ Math.max(this.totalAmount - Number(this.paidAmount || 0), 0)
250
+ );
251
 
252
+ if (this.status === "cancelled") return;
 
 
253
 
254
+ if (this.remainingAmount <= 0) this.status = "paid";
255
+ else if (this.paidAmount > 0) this.status = "partial";
256
+ else this.status = "open";
 
 
 
 
257
  };
258
 
259
  invoiceSchema.pre("save", function () {
models/MenuItemModel.js ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const menuItemSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ branch: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Branch",
14
+ default: null,
15
+ index: true,
16
+ },
17
+ name: {
18
+ type: String,
19
+ required: true,
20
+ trim: true,
21
+ },
22
+ nameAr: {
23
+ type: String,
24
+ required: true,
25
+ trim: true,
26
+ },
27
+ description: {
28
+ type: String,
29
+ default: "",
30
+ },
31
+ descriptionAr: {
32
+ type: String,
33
+ default: "",
34
+ },
35
+ price: {
36
+ type: Number,
37
+ required: true,
38
+ min: 0,
39
+ },
40
+ category: {
41
+ type: String,
42
+ enum: ["appetizer", "main", "dessert", "beverage", "other"],
43
+ required: true,
44
+ },
45
+ categoryAr: {
46
+ type: String,
47
+ enum: ["مقبلات", "أطباق رئيسية", "حلويات", "مشروبات", "أخرى"],
48
+ required: true,
49
+ },
50
+ isAvailable: {
51
+ type: Boolean,
52
+ default: true,
53
+ },
54
+ preparationTime: {
55
+ type: Number,
56
+ default: 15,
57
+ description: "Preparation time in minutes",
58
+ },
59
+ image: {
60
+ type: String,
61
+ default: null,
62
+ },
63
+ notes: {
64
+ type: String,
65
+ default: "",
66
+ }
67
+ },
68
+ { timestamps: true }
69
+ );
70
+
71
+ // Index for faster queries
72
+ menuItemSchema.index({ tenant: 1, category: 1 });
73
+ menuItemSchema.index({ tenant: 1, isAvailable: 1 });
74
+
75
+ const MenuItem = mongoose.model("MenuItem", menuItemSchema);
76
+
77
+ export default MenuItem;
models/NotificationModel.js ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const notificationSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ invoice: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Invoice",
14
+ required: true,
15
+ },
16
+
17
+ customer: {
18
+ type: mongoose.Schema.Types.ObjectId,
19
+ ref: "Customer",
20
+ default: null,
21
+ },
22
+
23
+ // Phone number for WhatsApp (may not be linked to customer)
24
+ phoneNumber: {
25
+ type: String,
26
+ required: true,
27
+ trim: true,
28
+ },
29
+
30
+ notificationType: {
31
+ type: String,
32
+ enum: [
33
+ "order-confirmed",
34
+ "pending",
35
+ "preparing",
36
+ "ready_for_delivery", // ✅ match invoiceController status strings
37
+ "shipped",
38
+ "out_for_delivery", // ✅ underscore consistency
39
+ "delivered",
40
+ "dine-in-ready", // ✅ for dine-in table-ready notifications
41
+ ],
42
+ required: true,
43
+ },
44
+
45
+ messageTemplate: {
46
+ type: String,
47
+ required: true,
48
+ },
49
+
50
+ channel: {
51
+ type: String,
52
+ enum: ["whatsapp", "sms", "email"],
53
+ default: "whatsapp",
54
+ },
55
+
56
+ status: {
57
+ type: String,
58
+ enum: ["queued", "sent", "delivered", "failed"],
59
+ default: "queued",
60
+ index: true,
61
+ },
62
+
63
+ retryCount: {
64
+ type: Number,
65
+ default: 0,
66
+ },
67
+
68
+ maxRetries: {
69
+ type: Number,
70
+ default: 3,
71
+ },
72
+
73
+ externalId: {
74
+ type: String,
75
+ default: null,
76
+ },
77
+
78
+ errorMessage: {
79
+ type: String,
80
+ default: null,
81
+ },
82
+
83
+ sentAt: {
84
+ type: Date,
85
+ default: null,
86
+ },
87
+
88
+ scheduledFor: {
89
+ type: Date,
90
+ default: null,
91
+ },
92
+ },
93
+ {
94
+ timestamps: true,
95
+ }
96
+ );
97
+
98
+ // Indexes for performance optimization
99
+ notificationSchema.index({ tenant: 1, status: 1 });
100
+ notificationSchema.index({ tenant: 1, order: 1 });
101
+ notificationSchema.index({ status: 1, scheduledFor: 1 });
102
+
103
+
104
+ const Notification = mongoose.model("Notification", notificationSchema);
105
+
106
+ export default Notification;
models/OrderModel.js ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const orderSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+
12
+ branch: {
13
+ type: mongoose.Schema.Types.ObjectId,
14
+ ref: "Branch",
15
+ required: true,
16
+ index: true,
17
+ },
18
+
19
+ // 🔥 FIX: remove global unique
20
+ orderNumber: {
21
+ type: String,
22
+ required: true,
23
+ trim: true,
24
+ },
25
+
26
+ customer: {
27
+ type: mongoose.Schema.Types.ObjectId,
28
+ ref: "Customer",
29
+ default: null,
30
+ },
31
+
32
+ guestInfo: {
33
+ name: String,
34
+ phone: String,
35
+ email: String,
36
+ },
37
+
38
+ orderType: {
39
+ type: String,
40
+ enum: ["dine-in", "takeaway", "delivery"],
41
+ required: true,
42
+ },
43
+
44
+ table: {
45
+ type: mongoose.Schema.Types.ObjectId,
46
+ ref: "Table",
47
+ default: null,
48
+ },
49
+
50
+ // 🔥 Items
51
+ items: [
52
+ {
53
+ menuItem: {
54
+ type: mongoose.Schema.Types.ObjectId,
55
+ ref: "MenuItem",
56
+ required: true,
57
+ },
58
+ name: String,
59
+ quantity: {
60
+ type: Number,
61
+ default: 1,
62
+ min: 1,
63
+ },
64
+ price: {
65
+ type: Number,
66
+ required: true,
67
+ },
68
+ notes: String,
69
+ itemTotal: {
70
+ type: Number,
71
+ default: function () {
72
+ return this.quantity * this.price;
73
+ },
74
+ },
75
+ },
76
+ ],
77
+
78
+ // 🔥 Financials
79
+ subtotal: {
80
+ type: Number,
81
+ default: 0,
82
+ },
83
+
84
+ tax: {
85
+ type: Number,
86
+ default: 0,
87
+ },
88
+
89
+ discount: {
90
+ type: Number,
91
+ default: 0,
92
+ },
93
+
94
+ total: {
95
+ type: Number,
96
+ required: true,
97
+ },
98
+
99
+ paidAmount: {
100
+ type: Number,
101
+ default: 0,
102
+ },
103
+
104
+ remainingAmount: {
105
+ type: Number,
106
+ default: function () {
107
+ return this.total;
108
+ },
109
+ },
110
+
111
+ paymentStatus: {
112
+ type: String,
113
+ enum: ["pending", "partial", "paid"],
114
+ default: "pending",
115
+ },
116
+
117
+ // 🔥 Order Status (Improved)
118
+ status: {
119
+ type: String,
120
+ enum: [
121
+ "pending",
122
+ "preparing",
123
+ "ready",
124
+ "ready_for_delivery",
125
+ "shipped",
126
+ "completed",
127
+ "cancelled",
128
+ ],
129
+ default: "pending",
130
+ index: true,
131
+ },
132
+
133
+ // 🔥 Driver (IMPORTANT)
134
+ driver: {
135
+ type: mongoose.Schema.Types.ObjectId,
136
+ ref: "Driver",
137
+ default: null,
138
+ },
139
+
140
+ deliveryInfo: {
141
+ address: String,
142
+ phone: String,
143
+ notes: String,
144
+ estimatedTime: Number,
145
+ },
146
+
147
+ issuedBy: {
148
+ type: mongoose.Schema.Types.ObjectId,
149
+ ref: "User",
150
+ default: null,
151
+ },
152
+
153
+ notes: {
154
+ type: String,
155
+ default: "",
156
+ },
157
+
158
+ // 🔥 Split Payments / Orders
159
+ splitInfo: {
160
+ isSplit: {
161
+ type: Boolean,
162
+ default: false,
163
+ },
164
+ splitCount: Number,
165
+ splitGroups: [
166
+ {
167
+ groupId: String,
168
+ items: [String],
169
+ total: Number,
170
+ },
171
+ ],
172
+ },
173
+
174
+ completedAt: {
175
+ type: Date,
176
+ default: null,
177
+ },
178
+ },
179
+ {
180
+ timestamps: true, // ✅ correct usage
181
+ }
182
+ );
183
+
184
+
185
+ // 🔥 ================= INDEXES =================
186
+
187
+ // ✅ Multi-tenant safe unique
188
+ orderSchema.index(
189
+ { tenant: 1, branch: 1, orderNumber: 1 },
190
+ { unique: true }
191
+ );
192
+
193
+ // ✅ Performance indexes
194
+ orderSchema.index({ tenant: 1, status: 1 });
195
+ orderSchema.index({ tenant: 1, orderType: 1 });
196
+ orderSchema.index({ tenant: 1, createdAt: -1 });
197
+ orderSchema.index({ tenant: 1, paymentStatus: 1 });
198
+ orderSchema.index({ tenant: 1, driver: 1 });
199
+
200
+
201
+ // 🔥 ================= VALIDATION =================
202
+
203
+ orderSchema.pre("validate", function (next) {
204
+ // dine-in لازم table
205
+ if (this.orderType === "dine-in" && !this.table) {
206
+ return next(new Error("Table is required for dine-in orders"));
207
+ }
208
+
209
+ // delivery لازم address
210
+ if (this.orderType === "delivery" && !this.deliveryInfo?.address) {
211
+ return next(new Error("Address is required for delivery orders"));
212
+ }
213
+
214
+ next();
215
+ });
216
+
217
+
218
+
219
+ orderSchema.pre("save", function (next) {
220
+ // حساب subtotal
221
+ this.subtotal = this.items.reduce(
222
+ (sum, item) => sum + item.quantity * item.price,
223
+ 0
224
+ );
225
+
226
+ // حساب total
227
+ this.total = this.subtotal + this.tax - this.discount;
228
+
229
+ // remaining
230
+ this.remainingAmount = this.total - this.paidAmount;
231
+
232
+ // payment status
233
+ if (this.paidAmount === 0) {
234
+ this.paymentStatus = "pending";
235
+ } else if (this.paidAmount < this.total) {
236
+ this.paymentStatus = "partial";
237
+ } else {
238
+ this.paymentStatus = "paid";
239
+ }
240
+
241
+ next();
242
+ });
243
+
244
+
245
+ const Order = mongoose.model("Order", orderSchema);
246
+
247
+ export default Order;
models/SupplierInvoiceModel.js CHANGED
@@ -56,8 +56,7 @@ const supplierInvoiceSchema = new mongoose.Schema(
56
  { timestamps: true }
57
  );
58
 
59
- supplierInvoiceSchema.index({ tenant: 1, branch: 1, supplier: 1 });
60
-
61
  supplierInvoiceSchema.pre("save", function () {
62
  this.totalAmount = this.items.reduce((sum, item) => sum + Number(item.total || 0), 0);
63
  this.paidAmount = this.payments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
 
56
  { timestamps: true }
57
  );
58
 
59
+ supplierInvoiceSchema.index({ tenant: 1, branch: 1, supplier: 1 }, { unique: true });
 
60
  supplierInvoiceSchema.pre("save", function () {
61
  this.totalAmount = this.items.reduce((sum, item) => sum + Number(item.total || 0), 0);
62
  this.paidAmount = this.payments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
models/TableModel.js ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const tableSchema = new mongoose.Schema(
4
+ {
5
+ tenant: {
6
+ type: mongoose.Schema.Types.ObjectId,
7
+ ref: "Tenant",
8
+ required: true,
9
+ index: true,
10
+ },
11
+ branch: {
12
+ type: mongoose.Schema.Types.ObjectId,
13
+ ref: "Branch",
14
+ required: true,
15
+ index: true,
16
+ },
17
+ tableNumber: {
18
+ type: String,
19
+ required: true,
20
+ trim: true,
21
+ },
22
+ displayName: {
23
+ type: String,
24
+ required: true,
25
+ trim: true,
26
+ },
27
+ capacity: {
28
+ type: Number,
29
+ required: true,
30
+ min: 1,
31
+ },
32
+ floor: {
33
+ type: String,
34
+ default: "الطابق الأول",
35
+ },
36
+ section: {
37
+ type: String,
38
+ default: "الرئيسية",
39
+ },
40
+ status: {
41
+ type: String,
42
+ enum: ["available", "occupied", "reserved", "maintenance"],
43
+ default: "available",
44
+ },
45
+ currentOrderId: {
46
+ type: mongoose.Schema.Types.ObjectId,
47
+ ref: "Invoice",
48
+ default: null,
49
+ },
50
+ // Position on floor plan
51
+ position: {
52
+ x: { type: Number, default: 0 },
53
+ y: { type: Number, default: 0 },
54
+ },
55
+ shape: {
56
+ type: String,
57
+ enum: ["round", "square", "rectangular"],
58
+ default: "square",
59
+ },
60
+ isActive: {
61
+ type: Boolean,
62
+ default: true,
63
+ },
64
+ notes: {
65
+ type: String,
66
+ default: "",
67
+ }
68
+ },
69
+ { timestamps: true }
70
+ );
71
+
72
+ // Index for faster queries
73
+ tableSchema.index(
74
+ { tenant: 1, branch: 1, tableNumber: 1 },
75
+ { unique: true }
76
+ );
77
+ tableSchema.index({ tenant: 1, status: 1 });
78
+ tableSchema.index({ createdAt: -1 });
79
+
80
+ const Table = mongoose.model("Table", tableSchema);
81
+
82
+ export default Table;
models/TenantModel.js CHANGED
@@ -55,6 +55,12 @@ const tenantSchema = new mongoose.Schema(
55
  type: Number,
56
  default: 5,
57
  },
 
 
 
 
 
 
58
  },
59
  monthlyFeeAmount: {
60
  type: Number,
@@ -119,6 +125,12 @@ const tenantSchema = new mongoose.Schema(
119
  default: 1,
120
  min: 0,
121
  },
 
 
 
 
 
 
122
  },
123
  { timestamps: true }
124
  );
 
55
  type: Number,
56
  default: 5,
57
  },
58
+ taxRate: {
59
+ type: Number,
60
+ default: 0,
61
+ min: 0,
62
+ max: 1, // stored as decimal: 0.14 = 14%
63
+ },
64
  },
65
  monthlyFeeAmount: {
66
  type: Number,
 
125
  default: 1,
126
  min: 0,
127
  },
128
+ tenantTypes: {
129
+ type: [String],
130
+ enum: ["restaurant", "cafe", "sales"],
131
+ default: ["sales"],
132
+ index: true,
133
+ },
134
  },
135
  { timestamps: true }
136
  );
models/UserModel.js CHANGED
@@ -76,19 +76,22 @@ const userSchema = new mongoose.Schema(
76
  userSchema.index({ tenant: 1, role: 1 });
77
  userSchema.index({ tenant: 1, username: 1 }, { unique: true });
78
  userSchema.index({ tenant: 1, assignedBranch: 1, role: 1 });
 
 
 
79
 
80
  userSchema.pre("save", async function () {
81
  if (!this.isModified("password")) return;
82
 
83
  const salt = crypto.randomBytes(16).toString("hex");
84
- const hash = crypto.pbkdf2Sync(this.password, salt, 1000, 64, "sha512").toString("hex");
85
  this.password = `${salt}:${hash}`;
86
  });
87
 
88
  userSchema.methods.matchPassword = function (enteredPassword) {
89
  try {
90
  const [salt, originalHash] = this.password.split(":");
91
- const attemptHash = crypto.pbkdf2Sync(enteredPassword, salt, 1000, 64, "sha512").toString("hex");
92
  return originalHash === attemptHash;
93
  } catch (err) {
94
  return false;
 
76
  userSchema.index({ tenant: 1, role: 1 });
77
  userSchema.index({ tenant: 1, username: 1 }, { unique: true });
78
  userSchema.index({ tenant: 1, assignedBranch: 1, role: 1 });
79
+ userSchema.index({ sessionToken: 1 }, { sparse: true }); // protect() runs this query on EVERY request
80
+
81
+ const PBKDF2_ITERATIONS = 100000; // OWASP minimum for PBKDF2-SHA512
82
 
83
  userSchema.pre("save", async function () {
84
  if (!this.isModified("password")) return;
85
 
86
  const salt = crypto.randomBytes(16).toString("hex");
87
+ const hash = crypto.pbkdf2Sync(this.password, salt, PBKDF2_ITERATIONS, 64, "sha512").toString("hex");
88
  this.password = `${salt}:${hash}`;
89
  });
90
 
91
  userSchema.methods.matchPassword = function (enteredPassword) {
92
  try {
93
  const [salt, originalHash] = this.password.split(":");
94
+ const attemptHash = crypto.pbkdf2Sync(enteredPassword, salt, PBKDF2_ITERATIONS, 64, "sha512").toString("hex");
95
  return originalHash === attemptHash;
96
  } catch (err) {
97
  return false;
routes/deliveryRoutes.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import * as deliveryController from "../controller/deliveryController.js";
3
+
4
+ const router = express.Router();
5
+
6
+ // Get all deliveries
7
+ router.get("/:tenantId/deliveries", deliveryController.getAllDeliveries);
8
+
9
+ // Get delivery by ID
10
+ router.get("/:tenantId/deliveries/:id", deliveryController.getDeliveryById);
11
+
12
+ // Assign delivery
13
+ router.post("/:tenantId/deliveries/assign", deliveryController.assignDelivery);
14
+
15
+ // Update delivery status
16
+ router.patch("/:tenantId/deliveries/:id/status", deliveryController.updateDeliveryStatus);
17
+
18
+ // Get delivery person's deliveries
19
+ router.get("/person/:deliveryPersonId/active", deliveryController.getDeliveryPersonDeliveries);
20
+
21
+ export default router;
routes/driverRoutes.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import * as driverController from "../controller/driverController.js";
3
+ import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
4
+ import { requireRestaurantTenant } from "../middleware/tenantFeatureMiddleware.js";
5
+
6
+ const router = express.Router();
7
+
8
+ router.use(protect, requireTenantUser, requireRestaurantTenant);
9
+
10
+ router.get("/", driverController.getDrivers);
11
+ router.get("/dashboard", driverController.getDriverDashboard); // ✅ new: full driver view with orders
12
+ router.get("/delivery-pending", driverController.getDeliveryPendingOrders);
13
+ router.post("/", driverController.createDriver);
14
+ router.patch("/:id", driverController.updateDriver);
15
+ router.delete("/:id", driverController.deleteDriver);
16
+ router.post("/:id/assign-order", driverController.assignOrder);
17
+ router.post("/:id/complete-order", driverController.completeOrder);
18
+ router.put("/:id/status", driverController.updateDriverStatus);
19
+
20
+ export default router;
21
+
routes/invoiceRoutes.js CHANGED
@@ -1,6 +1,9 @@
1
  import { Router } from "express";
2
  import {
3
  addItemToInvoice,
 
 
 
4
  confirmPayment,
5
  createWalkInCashSale,
6
  deleteInvoice,
@@ -9,10 +12,13 @@ import {
9
  getInvoices,
10
  getInvoicesByCustomer,
11
  payInvoice,
 
12
  updateInvoice,
13
  updateInvoiceItem,
 
14
  } from "../controller/invoiceController.js";
15
  import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
 
16
 
17
  const router = Router();
18
 
@@ -29,5 +35,12 @@ router.put("/:invoiceId", updateInvoice);
29
  router.delete("/:invoiceId", deleteInvoice);
30
  router.post("/:customerId/pay", payInvoice);
31
  router.post("/:invoiceId/confirm-payment/:paymentIndex", confirmPayment);
 
 
 
 
 
 
 
32
 
33
  export default router;
 
1
  import { Router } from "express";
2
  import {
3
  addItemToInvoice,
4
+ addItemsToOpenTab, // ✅ Feature #4: Open Tab
5
+ assignRestaurantDriver,
6
+ autoAssignRestaurantDriver,
7
  confirmPayment,
8
  createWalkInCashSale,
9
  deleteInvoice,
 
12
  getInvoices,
13
  getInvoicesByCustomer,
14
  payInvoice,
15
+ recordDriverPayment, // ✅ NEW: Record driver payment
16
  updateInvoice,
17
  updateInvoiceItem,
18
+ updateRestaurantStatus,
19
  } from "../controller/invoiceController.js";
20
  import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
21
+ import { requireRestaurantTenant } from "../middleware/tenantFeatureMiddleware.js";
22
 
23
  const router = Router();
24
 
 
35
  router.delete("/:invoiceId", deleteInvoice);
36
  router.post("/:customerId/pay", payInvoice);
37
  router.post("/:invoiceId/confirm-payment/:paymentIndex", confirmPayment);
38
+ router.post("/:invoiceId/record-driver-payment", requireRestaurantTenant, recordDriverPayment); // ✅ NEW
39
+ router.patch("/:invoiceId/restaurant-status", requireRestaurantTenant, updateRestaurantStatus);
40
+ router.patch("/:invoiceId/restaurant/assign-driver", requireRestaurantTenant, assignRestaurantDriver);
41
+ router.patch("/:invoiceId/restaurant/auto-assign-driver", requireRestaurantTenant, autoAssignRestaurantDriver);
42
+
43
+ // ✅ Feature #4: Open Tab — add items to an existing open invoice (dine-in)
44
+ router.post("/:invoiceId/open-tab/items", requireRestaurantTenant, addItemsToOpenTab);
45
 
46
  export default router;
routes/menuRoutes.js ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import * as menuController from "../controller/menuController.js";
3
+ import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
4
+ import { requireRestaurantTenant } from "../middleware/tenantFeatureMiddleware.js";
5
+
6
+ const router = express.Router();
7
+
8
+ router.use(protect, requireTenantUser, requireRestaurantTenant);
9
+
10
+ // Get all menu items
11
+ router.get("/:tenantId/menu", menuController.getAllMenuItems);
12
+
13
+ // Get categories
14
+ router.get("/:tenantId/menu/categories", menuController.getCategories);
15
+
16
+ // Get menu item by ID
17
+ router.get("/:tenantId/menu/:id", menuController.getMenuItemById);
18
+
19
+ // Create menu item
20
+ router.post("/:tenantId/menu", menuController.createMenuItem);
21
+
22
+ // Update menu item
23
+ router.put("/:tenantId/menu/:id", menuController.updateMenuItem);
24
+
25
+ // Delete menu item
26
+ router.delete("/:tenantId/menu/:id", menuController.deleteMenuItem);
27
+
28
+ // Toggle item availability
29
+ router.patch("/:tenantId/menu/:id/toggle-availability", menuController.toggleItemAvailability);
30
+
31
+ export default router;
routes/notificationRoutes.js ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import * as notificationController from "../controller/notificationController.js";
3
+
4
+ const router = express.Router();
5
+
6
+ // Get all notifications
7
+ router.get("/:tenantId/notifications", notificationController.getAllNotifications);
8
+
9
+ // Get notification statistics
10
+ router.get("/:tenantId/notifications/stats", notificationController.getNotificationStats);
11
+
12
+ // Get notification by ID
13
+ router.get("/:tenantId/notifications/:id", notificationController.getNotificationById);
14
+
15
+ // Get order notifications
16
+ router.get("/:tenantId/notifications/order/:invoiceId", notificationController.getInvoiceNotifications);
17
+
18
+ // Send notification manually
19
+ router.post("/:tenantId/notifications/:id/send", notificationController.sendNotification);
20
+
21
+ // Send all queued notifications
22
+ router.post("/:tenantId/notifications/send-queue", notificationController.sendQueuedNotifications);
23
+
24
+ // Retry failed notification
25
+ router.post("/:tenantId/notifications/:id/retry", notificationController.retryNotification);
26
+
27
+ // Delete notification
28
+ router.delete("/:tenantId/notifications/:id", notificationController.deleteNotification);
29
+
30
+ export default router;
routes/orderRoutesRestaurant.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import * as tableController from "../controller/tableController.js";
3
+ import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
4
+ import { requireRestaurantTenant } from "../middleware/tenantFeatureMiddleware.js";
5
+
6
+ const router = express.Router();
7
+
8
+ router.use(protect, requireTenantUser, requireRestaurantTenant);
9
+
10
+ // Get all tables (with populated currentOrderId for live status)
11
+ router.get("/:tenantId/:branchId/tables", tableController.getAllTables);
12
+
13
+ // Get floor plan
14
+ router.get("/:tenantId/:branchId/tables/floor-plan", tableController.getFloorPlan);
15
+
16
+ // Get single table status
17
+ router.get("/:tenantId/tables/:id/status", tableController.getTableStatus);
18
+
19
+ // Create table
20
+ router.post("/:tenantId/:branchId/tables", tableController.createTable);
21
+
22
+ // Update table details (name, capacity etc.)
23
+ router.put("/:tenantId/tables/:id", tableController.updateTable);
24
+
25
+ // ✅ Update table status (available / occupied / reserved / maintenance)
26
+ // Used by RestaurantTablesWorkspace reserve/free button
27
+ router.patch("/:tenantId/:branchId/tables/:id/status", tableController.updateTableStatus);
28
+
29
+ // Update table position on floor plan
30
+ router.patch("/:tenantId/tables/:id/position", tableController.updateTablePosition);
31
+
32
+ // Delete table (soft delete)
33
+ router.delete("/:tenantId/tables/:id", tableController.deleteTable);
34
+
35
+ export default router;
routes/ordersRoutes.js ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import * as orderController from "../controller/orderController.js";
3
+
4
+ const router = express.Router();
5
+
6
+ // Get all orders
7
+ router.get("/:tenantId/:branchId/orders", orderController.getAllOrders);
8
+
9
+ // Get order by ID
10
+ router.get("/:tenantId/orders/:id", orderController.getOrderById);
11
+
12
+ // Create order
13
+ router.post("/:tenantId/:branchId/orders", orderController.createOrder);
14
+
15
+ // Update order status
16
+ router.patch("/:tenantId/orders/:id/status", orderController.updateOrderStatus);
17
+
18
+ // Complete order
19
+ router.patch("/:tenantId/orders/:id/complete", orderController.completeOrder);
20
+
21
+ // Delete order
22
+ router.delete("/:tenantId/orders/:id", orderController.deleteOrder);
23
+
24
+ export default router;
routes/superAdminRoutes.js CHANGED
@@ -1,5 +1,5 @@
1
  import express from 'express';
2
- import { resetTenantPassword, getTenantAnalytics, getUsageTrends } from '../controller/superAdminController.js';
3
 
4
 
5
  const router = express.Router();
@@ -9,6 +9,16 @@ router.patch('/tenants/:tenantId/users/:userId/reset-password',
9
  resetTenantPassword
10
  );
11
 
 
 
 
 
 
 
 
 
 
 
12
  // Get comprehensive tenant analytics
13
  router.get('/analytics/tenants',
14
  getTenantAnalytics
 
1
  import express from 'express';
2
+ import { resetTenantPassword, getTenantAnalytics, getUsageTrends, updateTenantType, getAllTenants } from '../controller/superAdminController.js';
3
 
4
 
5
  const router = express.Router();
 
9
  resetTenantPassword
10
  );
11
 
12
+ // Get all tenants
13
+ router.get('/tenants',
14
+ getAllTenants
15
+ );
16
+
17
+ // Update tenant business type
18
+ router.patch('/tenants/:tenantId/type',
19
+ updateTenantType
20
+ );
21
+
22
  // Get comprehensive tenant analytics
23
  router.get('/analytics/tenants',
24
  getTenantAnalytics
services/driverService.js ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const DriverService = {
2
+ setAvailable: async (Driver, id) =>
3
+ Driver.findByIdAndUpdate(id, {
4
+ status: "available",
5
+ currentOrders: 0,
6
+ currentOrderIds: [],
7
+ }),
8
+
9
+ setBusy: async (Driver, id) =>
10
+ Driver.findByIdAndUpdate(id, { status: "busy" }),
11
+
12
+ assignOrders: async (Driver, id, invoiceIds) => {
13
+ return Driver.findByIdAndUpdate(
14
+ id,
15
+ {
16
+ $addToSet: { currentOrderIds: { $each: invoiceIds } }, //correct field, no duplicates
17
+ status: "busy",
18
+ },
19
+ { new: true }
20
+ ).then((driver) => {
21
+ if (driver) {
22
+ driver.currentOrders = driver.currentOrderIds.length; // keep count in sync
23
+ return driver.save();
24
+ }
25
+ });
26
+ },
27
+ };
services/tableService.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const TableService = {
2
+ occupy: async (TableModel, tableId, invoiceId) => {
3
+ return TableModel.findByIdAndUpdate(
4
+ tableId,
5
+ {
6
+ status: "occupied",
7
+ currentOrderId: invoiceId || null, // ✅ track which invoice owns this table
8
+ },
9
+ { new: true, runValidators: true }
10
+ );
11
+ },
12
+
13
+ free: async (TableModel, tableId) => {
14
+ return TableModel.findByIdAndUpdate(
15
+ tableId,
16
+ {
17
+ status: "available",
18
+ currentOrderId: null, // ✅ always clear the invoice ref when freeing
19
+ },
20
+ { new: true, runValidators: true }
21
+ );
22
+ },
23
+ };
utils/appError.js ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Custom error class for API responses
3
+ */
4
+ export class AppError extends Error {
5
+ constructor(message, statusCode = 500) {
6
+ super(message);
7
+ this.statusCode = statusCode;
8
+ Error.captureStackTrace(this, this.constructor);
9
+ }
10
+ }
11
+
12
+ export default AppError;
utils/catchAsync.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Error handling wrapper for async route handlers
3
+ * Catches errors and passes them to Express error middleware
4
+ */
5
+ export const catchAsync = (fn) => {
6
+ return (req, res, next) => {
7
+ fn(req, res, next).catch(next);
8
+ };
9
+ };
10
+
11
+ export default catchAsync;
utils/invoiceService.js CHANGED
@@ -18,48 +18,38 @@ export const validateInvoiceItems = async (items, tenantId, branchId) => {
18
  }
19
 
20
  if (item.type === "service" && item.serviceId) {
21
- // Validate service
22
  const service = await Service.findOne({
23
  _id: item.serviceId,
24
  tenant: tenantId,
25
  isDeleted: false,
26
  });
27
-
28
- if (!service) {
29
- throw new Error(`الخدمة غير موجودة: ${item.name}`);
30
- }
31
-
32
  hasServices = true;
33
- processedItems.push({
34
- ...item,
35
- type: "service",
36
- serviceId: item.serviceId,
37
- });
38
  } else if (item.type === "product" && item.productId) {
39
- // Validate product
40
  const product = await Product.findOne({
41
  _id: item.productId,
42
  tenant: tenantId,
43
  branch: branchId,
44
  });
45
-
46
- if (!product) {
47
- throw new Error(`المنتج غير موجود: ${item.name}`);
48
- }
49
-
50
  if (product.stock < Number(item.quantity)) {
51
- throw new Error(
52
- `المخزون غير كافٍ للصنف ${item.name}. المتاح: ${product.stock}`
53
- );
54
  }
 
55
 
56
- processedItems.push({
57
- ...item,
58
- type: "product",
59
- productId: item.productId,
 
60
  });
 
 
 
61
  } else {
62
- throw new Error("كل صنف يجب أن يحتوي على معرف منتج أو خدمة");
63
  }
64
  }
65
 
@@ -69,14 +59,10 @@ export const validateInvoiceItems = async (items, tenantId, branchId) => {
69
  /**
70
  * Apply items to invoice and update stock for products
71
  */
72
- export const applyInvoiceItemsAndStock = async (
73
- invoice,
74
- items,
75
- tenantId,
76
- branchId
77
- ) => {
78
  let serviceRevenue = 0;
79
  let productRevenue = 0;
 
80
 
81
  for (const item of items) {
82
  const quantity = Number(item.quantity || 1);
@@ -95,15 +81,18 @@ export const applyInvoiceItemsAndStock = async (
95
  if (item.type === "service" && item.serviceId) {
96
  invoiceItem.serviceId = item.serviceId;
97
  serviceRevenue += total;
 
98
  } else if (item.type === "product" && item.productId) {
99
  invoiceItem.productId = item.productId;
100
  productRevenue += total;
101
-
102
- // Deduct from stock
103
  await Product.findOneAndUpdate(
104
  { _id: item.productId, tenant: tenantId, branch: branchId },
105
  { $inc: { stock: -quantity } }
106
  );
 
 
 
 
107
  }
108
 
109
  invoice.items.push(invoiceItem);
@@ -111,6 +100,7 @@ export const applyInvoiceItemsAndStock = async (
111
 
112
  invoice.serviceRevenue = serviceRevenue;
113
  invoice.productRevenue = productRevenue;
 
114
  invoice.hasServices = serviceRevenue > 0;
115
  };
116
 
@@ -160,6 +150,22 @@ export const createIncomeRecords = async ({
160
  createdBy: userId || null,
161
  });
162
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
  return incomeRecords;
165
  };
 
18
  }
19
 
20
  if (item.type === "service" && item.serviceId) {
 
21
  const service = await Service.findOne({
22
  _id: item.serviceId,
23
  tenant: tenantId,
24
  isDeleted: false,
25
  });
26
+ if (!service) throw new Error(`الخدمة غير موجودة: ${item.name}`);
 
 
 
 
27
  hasServices = true;
28
+ processedItems.push({ ...item, type: "service", serviceId: item.serviceId });
29
+
 
 
 
30
  } else if (item.type === "product" && item.productId) {
 
31
  const product = await Product.findOne({
32
  _id: item.productId,
33
  tenant: tenantId,
34
  branch: branchId,
35
  });
36
+ if (!product) throw new Error(`المنتج غير موجود: ${item.name}`);
 
 
 
 
37
  if (product.stock < Number(item.quantity)) {
38
+ throw new Error(`المخزون غير كافٍ للصنف ${item.name}. المتاح: ${product.stock}`);
 
 
39
  }
40
+ processedItems.push({ ...item, type: "product", productId: item.productId });
41
 
42
+ } else if (item.type === "catalog" && item.catalogItemId) { // ✅ new branch
43
+ const catalogItem = await CatalogItem.findOne({
44
+ _id: item.catalogItemId,
45
+ tenant: tenantId,
46
+ isActive: true,
47
  });
48
+ if (!catalogItem) throw new Error(`عنصر الكتالوج غير موجود: ${item.name}`);
49
+ processedItems.push({ ...item, type: "catalog", catalogItemId: item.catalogItemId });
50
+
51
  } else {
52
+ throw new Error(`نوع الصنف غير صحيح أو معرف مفقود: ${item.name}`);
53
  }
54
  }
55
 
 
59
  /**
60
  * Apply items to invoice and update stock for products
61
  */
62
+ export const applyInvoiceItemsAndStock = async (invoice, items, tenantId, branchId) => {
 
 
 
 
 
63
  let serviceRevenue = 0;
64
  let productRevenue = 0;
65
+ let catalogRevenue = 0; // ✅ add catalog tracking
66
 
67
  for (const item of items) {
68
  const quantity = Number(item.quantity || 1);
 
81
  if (item.type === "service" && item.serviceId) {
82
  invoiceItem.serviceId = item.serviceId;
83
  serviceRevenue += total;
84
+
85
  } else if (item.type === "product" && item.productId) {
86
  invoiceItem.productId = item.productId;
87
  productRevenue += total;
 
 
88
  await Product.findOneAndUpdate(
89
  { _id: item.productId, tenant: tenantId, branch: branchId },
90
  { $inc: { stock: -quantity } }
91
  );
92
+
93
+ } else if (item.type === "catalog" && item.catalogItemId) { // ✅ new branch
94
+ invoiceItem.catalogItemId = item.catalogItemId;
95
+ catalogRevenue += total;
96
  }
97
 
98
  invoice.items.push(invoiceItem);
 
100
 
101
  invoice.serviceRevenue = serviceRevenue;
102
  invoice.productRevenue = productRevenue;
103
+ invoice.catalogRevenue = catalogRevenue; // ✅ now tracked
104
  invoice.hasServices = serviceRevenue > 0;
105
  };
106
 
 
150
  createdBy: userId || null,
151
  });
152
  }
153
+ if (invoice.catalogRevenue > 0) {
154
+ incomeRecords.push({
155
+ tenant: tenantId,
156
+ branch: branchId,
157
+ title: `Catalog sales - ${invoice.invoiceNumber}`,
158
+ category: "catalog_sale",
159
+ amount: invoice.catalogRevenue,
160
+ paymentMethod: "cash",
161
+ notes: `Catalog revenue from invoice ${invoice.invoiceNumber}`,
162
+ sourceType: "invoice_payment",
163
+ relatedInvoice: invoice._id,
164
+ relatedCustomer: customer?._id || null,
165
+ date,
166
+ createdBy: userId || null,
167
+ });
168
+ }
169
 
170
  return incomeRecords;
171
  };
utils/whatsappService.js ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Notification from "../models/NotificationModel.js";
2
+
3
+ // ─── Templates ────────────────────────────────────────────────────────────────
4
+ // Keys must match InvoiceModel.restaurantStatus values exactly
5
+ const WHATSAPP_TEMPLATES = {
6
+ "order-confirmed": {
7
+ ar: "✅ تم تأكيد طلبك رقم #{orderNumber} في {restaurantName}.\nسيتم تحضيره خلال {estimatedTime} دقيقة. شكراً لاختيارك!",
8
+ },
9
+ "pending": {
10
+ ar: "📋 تم استلام طلبك رقم #{orderNumber} في {restaurantName}.\nجاري المراجعة الآن.",
11
+ },
12
+ "preparing": {
13
+ ar: "👨‍🍳 طلبك رقم #{orderNumber} قيد التحضير الآن!\n\n🧾 الأصناف:\n{itemsList}",
14
+ },
15
+ "ready_for_delivery": {
16
+ ar: "🍽️ طلبك رقم #{orderNumber} جاهز للاستلام من {restaurantName}!",
17
+ },
18
+ "dine-in-ready": {
19
+ ar: "🔔 طلبك رقم #{orderNumber} جاهز على طاولتك في {restaurantName}!",
20
+ },
21
+ "shipped": {
22
+ ar: "🚚 طلبك رقم #{orderNumber} في الطريق إليك!\n\n🧾 الأصناف:\n{itemsList}\n\n💰 الإجمالي: {total}\n\n🏍️ السائق: {driverName}\n📞 هاتف السائق: {driverPhone}",
23
+ },
24
+ "out_for_delivery": {
25
+ ar: "🏎️ طلبك في الطريق إليك الآن!\nالسائق: {driverName} — رقم: {driverPhone}",
26
+ },
27
+ "delivered": {
28
+ ar: "✅ تم تسليم طلبك رقم #{orderNumber} بنجاح.\nشكراً لتعاملك مع {restaurantName} 🙏",
29
+ },
30
+ };
31
+
32
+ // ─── Meta Cloud API Config ────────────────────────────────────────────────────
33
+ // Set these environment variables in your .env file:
34
+ //
35
+ // WHATSAPP_PHONE_NUMBER_ID=<your Meta phone number ID>
36
+ // WHATSAPP_ACCESS_TOKEN=<your Meta Graph API access token>
37
+ // WHATSAPP_API_VERSION=v20.0 (optional, defaults to v20.0)
38
+ //
39
+ // Get credentials from: https://developers.facebook.com > WhatsApp Business > API Setup
40
+ const META_PHONE_NUMBER_ID = process.env.WHATSAPP_PHONE_NUMBER_ID;
41
+ const META_ACCESS_TOKEN = process.env.WHATSAPP_ACCESS_TOKEN;
42
+ const META_API_VERSION = process.env.WHATSAPP_API_VERSION || "v20.0";
43
+ const META_API_URL = `https://graph.facebook.com/${META_API_VERSION}/${META_PHONE_NUMBER_ID}/messages`;
44
+
45
+ // ─── Helper: normalize phone number to E.164 format ──────────────────────────
46
+ // Examples: "01012345678" → "+201012345678"
47
+ // "+20 101 234 5678" → "+201012345678"
48
+ const normalizePhone = (phone, defaultCountryCode = "20") => {
49
+ if (!phone) return null;
50
+
51
+ // Remove all non-digit characters
52
+ let digits = phone.replace(/\D/g, "");
53
+
54
+ // Egyptian numbers starting with 0: strip and prepend country code
55
+ if (digits.startsWith("0") && digits.length === 11) {
56
+ digits = defaultCountryCode + digits.slice(1);
57
+ }
58
+
59
+ // Already has country code without +
60
+ if (digits.length >= 12) {
61
+ return "+" + digits;
62
+ }
63
+
64
+ return "+" + defaultCountryCode + digits;
65
+ };
66
+
67
+ class WhatsAppService {
68
+ /**
69
+ * Queue a WhatsApp notification in the database
70
+ */
71
+ static async queueNotification({
72
+ tenant,
73
+ invoice,
74
+ customer,
75
+ phoneNumber,
76
+ notificationType,
77
+ orderNumber,
78
+ estimatedTime,
79
+ deliveryNote,
80
+ driverName,
81
+ driverPhone,
82
+ restaurantName,
83
+ itemsList,
84
+ total,
85
+ language = "ar",
86
+ }) {
87
+ try {
88
+ if (!tenant || !invoice || !phoneNumber || !notificationType) {
89
+ console.error("[WhatsApp] Missing required params:", {
90
+ tenant: !!tenant, invoice: !!invoice, phoneNumber: !!phoneNumber, notificationType,
91
+ });
92
+ throw new Error("Missing required notification parameters");
93
+ }
94
+
95
+ const template = WHATSAPP_TEMPLATES[notificationType];
96
+ if (!template) {
97
+ console.error("[WhatsApp] Unknown type:", notificationType, "| Available:", Object.keys(WHATSAPP_TEMPLATES));
98
+ throw new Error(`Unknown notification type: ${notificationType}`);
99
+ }
100
+
101
+ // Build message
102
+ let message = template[language] || template.ar;
103
+ message = message
104
+ .replace(/{orderNumber}/g, orderNumber || "")
105
+ .replace(/{estimatedTime}/g, estimatedTime || "30")
106
+ .replace(/{deliveryNote}/g, deliveryNote || "")
107
+ .replace(/{driverName}/g, driverName || "—")
108
+ .replace(/{driverPhone}/g, driverPhone || "—")
109
+ .replace(/{restaurantName}/g, restaurantName || "")
110
+ .replace(/{itemsList}/g, itemsList || "")
111
+ .replace(/{total}/g, total || "");
112
+
113
+ const notification = new Notification({
114
+ tenant,
115
+ invoice,
116
+ customer: customer || null,
117
+ phoneNumber,
118
+ notificationType,
119
+ messageTemplate: message,
120
+ channel: "whatsapp",
121
+ status: "queued",
122
+ });
123
+
124
+ await notification.save();
125
+
126
+ // ✅ Attempt immediate send (non-blocking — failure just updates status to retry later)
127
+ WhatsAppService.sendWhatsAppMessage(notification).catch((err) => {
128
+ console.warn("[WhatsApp] Background send failed — will retry via queue:", err.message);
129
+ });
130
+
131
+ return notification;
132
+ } catch (error) {
133
+ console.error("[WhatsApp] Queue error:", error.message);
134
+ throw error;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Send pending queued messages (call via cron job or manual trigger)
140
+ * ✅ Fixed: was using string "$maxRetries" — now uses $expr for field comparison
141
+ */
142
+ static async sendQueuedNotifications() {
143
+ try {
144
+ const pendingNotifications = await Notification.find({
145
+ status: "queued",
146
+ $expr: { $lt: ["$retryCount", "$maxRetries"] }, // ✅ correct field-to-field comparison
147
+ })
148
+ .limit(10)
149
+ .populate("order", "invoiceNumber")
150
+ .populate("tenant", "name");
151
+
152
+ for (const n of pendingNotifications) {
153
+ await WhatsAppService.sendWhatsAppMessage(n);
154
+ }
155
+
156
+ return { processed: pendingNotifications.length };
157
+ } catch (error) {
158
+ console.error("[WhatsApp] Send queue error:", error.message);
159
+ throw error;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * ✅ Feature #5: Send a WhatsApp message via Meta Cloud API
165
+ * Falls back to console log in dev mode (when credentials not set)
166
+ */
167
+ static async sendWhatsAppMessage(notification) {
168
+ try {
169
+ const normalizedPhone = normalizePhone(notification.phoneNumber);
170
+
171
+ if (!normalizedPhone) {
172
+ throw new Error(`Invalid phone number: ${notification.phoneNumber}`);
173
+ }
174
+
175
+ if (!META_PHONE_NUMBER_ID || !META_ACCESS_TOKEN) {
176
+ // Dev mode: log instead of sending
177
+ console.log(`[WhatsApp DEV] Would send to ${normalizedPhone}:`);
178
+ console.log(notification.messageTemplate);
179
+
180
+ notification.status = "sent";
181
+ notification.sentAt = new Date();
182
+ notification.externalId = `dev-${Date.now()}`;
183
+ await notification.save();
184
+ return notification;
185
+ }
186
+
187
+ // ✅ Meta Cloud API — send free-form text message
188
+ const response = await fetch(META_API_URL, {
189
+ method: "POST",
190
+ headers: {
191
+ "Authorization": `Bearer ${META_ACCESS_TOKEN}`,
192
+ "Content-Type": "application/json",
193
+ },
194
+ body: JSON.stringify({
195
+ messaging_product: "whatsapp",
196
+ recipient_type: "individual",
197
+ to: normalizedPhone,
198
+ type: "text",
199
+ text: {
200
+ preview_url: false,
201
+ body: notification.messageTemplate,
202
+ },
203
+ }),
204
+ });
205
+
206
+ const responseData = await response.json();
207
+
208
+ if (!response.ok) {
209
+ throw new Error(
210
+ responseData?.error?.message || `API error ${response.status}`
211
+ );
212
+ }
213
+
214
+ // Mark as sent
215
+ notification.status = "sent";
216
+ notification.sentAt = new Date();
217
+ notification.externalId = responseData?.messages?.[0]?.id || null;
218
+ await notification.save();
219
+
220
+ console.log(`[WhatsApp] ✅ Sent to ${normalizedPhone} [${notification.notificationType}]`);
221
+ return notification;
222
+ } catch (error) {
223
+ console.error(`[WhatsApp] ❌ Send error for ${notification.phoneNumber}:`, error.message);
224
+
225
+ notification.retryCount += 1;
226
+ notification.errorMessage = error.message;
227
+
228
+ if (notification.retryCount >= notification.maxRetries) {
229
+ notification.status = "failed";
230
+ }
231
+
232
+ await notification.save();
233
+ throw error;
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Get notification history for a specific order
239
+ */
240
+ static async getOrderNotifications(tenantId, orderId) {
241
+ return await Notification.find({
242
+ invoice: invoiceId,
243
+ order: orderId,
244
+ }).sort({ createdAt: -1 });
245
+ }
246
+ }
247
+
248
+ export default WhatsAppService;