File size: 12,251 Bytes
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import Driver from "../models/DriverModel.js";
import Invoice from "../models/InvoiceModel.js";
import { catchAsync } from "../utils/catchAsync.js";

// ─── GET ALL DRIVERS (with stats) ─────────────────────────────────────────────
export const getDrivers = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const branchId = req.query.branchId || null;

  const query = { tenant: tenantId, isActive: true };
  if (branchId) query.branch = branchId;

  const drivers = await Driver.find(query)
    .populate("currentOrderIds", "invoiceNumber totalAmount restaurantStatus")
    .sort({ createdAt: -1 });

  const stats = {
    total: drivers.length,
    available: drivers.filter((d) => d.status === "available").length,
    busy: drivers.filter((d) => d.status === "busy").length,
    offDuty: drivers.filter((d) => d.status === "off-duty").length,
    totalOrders: drivers.reduce((sum, d) => sum + d.currentOrders, 0),
  };

  res.status(200).json({
    status: "success",
    data: drivers,
    stats,
  });
});

// ─── DRIVER DASHBOARD (full detail per driver + their live orders) ─────────────
export const getDriverDashboard = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const branchId = req.query.branchId || null;

  const query = { tenant: tenantId, isActive: true };
  if (branchId) query.branch = branchId;

  const drivers = await Driver.find(query)
    .populate({
      path: "currentOrderIds",
      select: "invoiceNumber totalAmount restaurantStatus createdAt restaurantData",
      populate: {
        path: "restaurantData.table",
        select: "displayName tableNumber",
      },
    })
    .lean();

  const driverStats = drivers.map((driver) => ({
    ...driver,
    totalCurrentOrders: (driver.currentOrderIds || []).length,
    isAvailable: driver.status === "available",
  }));

  const globalStats = {
    total: drivers.length,
    available: drivers.filter((d) => d.status === "available").length,
    busy: drivers.filter((d) => d.status === "busy").length,
    totalActiveOrders: drivers.reduce(
      (sum, d) => sum + (d.currentOrderIds || []).length,
      0
    ),
  };

  res.status(200).json({
    status: "success",
    data: driverStats,
    stats: globalStats,
  });
});

// ─── CREATE DRIVER ─────────────────────────────────────────────────────────────
export const createDriver = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const { name, phone, branchId, notes, vehicleType, licensePlate, maxOrders } = req.body;

  if (!name || !phone) {
    return res
      .status(400)
      .json({ status: "error", message: "Ψ§Ω„Ψ§Ψ³Ω… ΩˆΨ±Ω‚Ω… Ψ§Ω„Ω‡Ψ§Ψͺف Ω…Ψ·Ω„ΩˆΨ¨Ψ§Ω†" });
  }

  const driver = await Driver.create({
    tenant: tenantId,
    branch: branchId || null,
    name: String(name).trim(),
    phone: String(phone).trim(),
    notes: notes ? String(notes) : "",
    vehicleType: vehicleType || "motorcycle",
    licensePlate: licensePlate ? String(licensePlate).trim() : undefined,
    maxOrders: maxOrders ? Number(maxOrders) : 3,
  });

  res.status(201).json({ status: "success", data: driver });
});

// ─── UPDATE DRIVER ─────────────────────────────────────────────────────────────
export const updateDriver = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const { id } = req.params;
  const {
    name,
    phone,
    isActive,
    branchId,
    notes,
    vehicleType,
    licensePlate,
    maxOrders,
    status,
    currentOrders,
    currentOrderIds,
  } = req.body;

  const driver = await Driver.findOne({ _id: id, tenant: tenantId });
  if (!driver) {
    return res
      .status(404)
      .json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
  }

  if (name !== undefined) driver.name = String(name).trim();
  if (phone !== undefined) driver.phone = String(phone).trim();
  if (branchId !== undefined) driver.branch = branchId || null;
  if (notes !== undefined) driver.notes = String(notes || "");
  if (isActive !== undefined) driver.isActive = Boolean(isActive);
  if (vehicleType !== undefined) driver.vehicleType = vehicleType;
  if (licensePlate !== undefined) driver.licensePlate = String(licensePlate || "").trim();
  if (maxOrders !== undefined) driver.maxOrders = Number(maxOrders);
  if (status !== undefined && ["available", "busy", "off-duty"].includes(status)) {
    driver.status = status;
  }
  if (Array.isArray(currentOrderIds)) {
    driver.currentOrderIds = currentOrderIds;
    driver.currentOrders = currentOrderIds.length;   //  always derived from array
  }
  if (driver.status === "available") {
    driver.currentOrders = 0;
    driver.currentOrderIds = [];
  } else if (driver.currentOrders === 0 && driver.status === "busy") {
    driver.status = "available";
  }

  await driver.save();
  res.status(200).json({ status: "success", data: driver });
});

// ─── DELETE DRIVER (soft) ─────────────────────────────────────────────────────
export const deleteDriver = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const { id } = req.params;

  const driver = await Driver.findOne({ _id: id, tenant: tenantId });
  if (!driver) {
    return res
      .status(404)
      .json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
  }

  driver.isActive = false;
  await driver.save();

  res.status(200).json({ status: "success", message: "ΨͺΩ… حذف Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ Ψ¨Ω†Ψ¬Ψ§Ψ­" });
});

// ─── ASSIGN ORDER TO DRIVER ────────────────────────────────────────────────────
// βœ… FIXED: now properly stores the invoice ID in currentOrderIds array
export const assignOrder = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const { id } = req.params;
  const requestedOrderIds = Array.isArray(req.body.orderIds)
    ? req.body.orderIds
    : [req.body.invoiceId || req.body.orderId].filter(Boolean);

  if (!requestedOrderIds.length) {
    return res
      .status(400)
      .json({ status: "error", message: "معرف الفاΨͺورة Ω…Ψ·Ω„ΩˆΨ¨" });
  }

  const driver = await Driver.findOne({ _id: id, tenant: tenantId });
  if (!driver) {
    return res
      .status(404)
      .json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
  }

  const uniqueOrderIds = [...new Set(requestedOrderIds.map((orderId) => orderId.toString()))];
  const existingOrderIdSet = new Set(
    (driver.currentOrderIds || []).map((orderId) => orderId.toString()),
  );
  const netNewAssignments = uniqueOrderIds.filter(
    (orderId) => !existingOrderIdSet.has(orderId),
  ).length;

  if (driver.currentOrders + netNewAssignments > driver.maxOrders) {
    return res.status(400).json({
      status: "error",
      message: `Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ ΩˆΨ΅Ω„ Ω„Ω„Ψ­Ψ― Ψ§Ω„Ψ£Ω‚Ψ΅Ω‰ (${driver.maxOrders} أوردراΨͺ في نفس Ψ§Ω„ΩˆΩ‚Ψͺ)`,
    });
  }

  const invoices = await Invoice.find({
    _id: { $in: uniqueOrderIds },
    tenant: tenantId,
    isDeleted: false,
  });

  if (invoices.length !== uniqueOrderIds.length) {
    return res.status(404).json({
      status: "error",
      message: "Ψ¨ΨΉΨΆ Ψ§Ω„Ψ·Ω„Ψ¨Ψ§Ψͺ غير Ω…ΩˆΨ¬ΩˆΨ―Ψ©",
    });
  }

  for (const invoice of invoices) {
    if (invoice.restaurantData?.orderType !== "delivery") {
      return res.status(400).json({
        status: "error",
        message: "ΩŠΩ…ΩƒΩ† Ψ₯Ψ³Ω†Ψ§Ψ― Ψ³Ψ§Ψ¦Ω‚ فقط Ω„Ψ·Ω„Ψ¨Ψ§Ψͺ Ψ§Ω„ΨͺΩˆΨ΅ΩŠΩ„",
      });
    }

    invoice.restaurantData = invoice.restaurantData || {};
    invoice.restaurantData.driver = {
      driverId: driver._id,
      driverUserId: null,
      driverName: driver.name || "",
      driverPhone: driver.phone || "",
      assignedAt: new Date(),
    };
    await invoice.save();
  }

  uniqueOrderIds.forEach((orderId) => existingOrderIdSet.add(orderId));
  driver.currentOrderIds = [...existingOrderIdSet];
  driver.currentOrders = driver.currentOrderIds.length;
  driver.status = driver.currentOrders > 0 ? "busy" : "available";
  await driver.save();

  res.status(200).json({
    status: "success",
    message: "ΨͺΩ… ΨͺΨΉΩŠΩŠΩ† Ψ§Ω„Ψ£ΩˆΨ±Ψ―Ψ± Ω„Ω„Ψ³Ψ§Ψ¦Ω‚ Ψ¨Ω†Ψ¬Ψ§Ψ­",
    data: driver,
  });
});

// ─── COMPLETE / REMOVE ORDER FROM DRIVER ──────────────────────────────────────
export const completeOrder = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const { id } = req.params;
  const invoiceId = req.body.invoiceId || req.body.orderId || null;

  if (!invoiceId) {
    return res.status(400).json({
      status: "error",
      message: "معرف الفاΨͺورة Ω…Ψ·Ω„ΩˆΨ¨ Ω„Ψ₯Ω†Ω‡Ψ§Ψ‘ Ψ§Ω„ΨͺΩˆΨ΅ΩŠΩ„",
    });
  }

  const driver = await Driver.findOne({ _id: id, tenant: tenantId });
  if (!driver) {
    return res
      .status(404)
      .json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
  }

  if (driver.currentOrders <= 0) {
    return res
      .status(400)
      .json({ status: "error", message: "Ω„Ψ§ Ψͺوجد أوردراΨͺ Ω†Ψ΄Ψ·Ψ© Ω„Ψ₯Ω†Ω‡Ψ§Ψ¦Ω‡Ψ§" });
  }

  driver.currentOrderIds = (driver.currentOrderIds || []).filter(
    (oid) => oid.toString() !== invoiceId.toString()
  );
  driver.currentOrders = driver.currentOrderIds.length;

  // Free driver if no more orders
  if (driver.currentOrders === 0) {
    driver.status = "available";
  }

  await driver.save();

  if (invoiceId) {
    await Invoice.findOneAndUpdate(
      { _id: invoiceId, tenant: tenantId },
      { $set: { restaurantStatus: "delivered" } },
    );
  }

  res.status(200).json({
    status: "success",
    message: "ΨͺΩ… Ψ₯Ω†Ω‡Ψ§Ψ‘ Ψ§Ω„Ψ£ΩˆΨ±Ψ―Ψ± Ψ¨Ω†Ψ¬Ψ§Ψ­",
    data: driver,
  });
});

// ─── UPDATE DRIVER STATUS MANUALLY ────────────────────────────────────────────
export const updateDriverStatus = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;
  const { id } = req.params;
  const { status } = req.body;

  const validStatuses = ["available", "busy", "off-duty"];
  if (!validStatuses.includes(status)) {
    return res.status(400).json({ status: "error", message: "Ψ­Ψ§Ω„Ψ© غير Ψ΅Ψ§Ω„Ψ­Ψ©" });
  }

  const driver = await Driver.findOne({ _id: id, tenant: tenantId });
  if (!driver) {
    return res
      .status(404)
      .json({ status: "error", message: "Ψ§Ω„Ψ³Ψ§Ψ¦Ω‚ غير Ω…ΩˆΨ¬ΩˆΨ―" });
  }

  // Clear orders if manually setting to available
  if (status === "available") {
    driver.currentOrders = 0;
    driver.currentOrderIds = [];
  }

  driver.status = status;
  await driver.save();

  res.status(200).json({ status: "success", data: driver });
});

// ─── GET DELIVERY PENDING ORDERS (unassigned) ─────────────────────────────────
export const getDeliveryPendingOrders = catchAsync(async (req, res) => {
  const tenantId = req.user?.tenant?._id;

  const orders = await Invoice.find({
    tenant: tenantId,
    restaurantStatus: "ready_for_delivery",
    isDeleted: false,
    "restaurantData.driver.driverId": null,
  })
    .populate("customer", "name phone")
    .populate("restaurantData.driver.driverId", "name phone")
    .lean();

  res.status(200).json({
    status: "success",
    data: orders,
  });
});