Mahmoud7456 commited on
Commit
1e65df5
·
verified ·
1 Parent(s): 2698900

Upload 71 files

Browse files
controller/customerController.js CHANGED
@@ -1,12 +1,15 @@
1
  import Customer from "../models/CustomerModel.js";
2
  import Invoice from "../models/InvoiceModel.js";
3
  import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
 
4
 
5
  export const createCustomer = async (req, res) => {
6
  try {
7
  const tenantId = req.user.tenant._id;
8
  const branch = await resolveBranchForWrite(req);
9
  const name = req.body.name?.trim();
 
 
10
 
11
  if (!name) {
12
  return res.status(400).json({ message: "اسم العميل مطلوب" });
@@ -19,7 +22,9 @@ export const createCustomer = async (req, res) => {
19
  const exists = await Customer.findOne({
20
  tenant: tenantId,
21
  branch: branch._id,
22
- name: new RegExp(`^${name}$`, "i"),
 
 
23
  isDeleted: false,
24
  isWalkIn: { $ne: true },
25
  });
@@ -32,7 +37,7 @@ export const createCustomer = async (req, res) => {
32
  tenant: tenantId,
33
  branch: branch._id,
34
  name,
35
- phone: req.body.phone?.trim() || "",
36
  email: req.body.email?.trim()?.toLowerCase() || "",
37
  address: req.body.address?.trim() || "",
38
  notes: req.body.notes?.trim() || "",
@@ -68,7 +73,11 @@ export const getCustomers = async (req, res) => {
68
  };
69
 
70
  if (search) {
71
- matchQuery.name = { $regex: search, $options: "i" };
 
 
 
 
72
  }
73
 
74
  const results = await Customer.aggregate([
 
1
  import Customer from "../models/CustomerModel.js";
2
  import Invoice from "../models/InvoiceModel.js";
3
  import { resolveBranchForWrite, resolveScopedBranch } from "../utils/branchContext.js";
4
+ import { normalizeCustomerName, normalizeCustomerPhone } from "../utils/customerNormalization.js";
5
 
6
  export const createCustomer = async (req, res) => {
7
  try {
8
  const tenantId = req.user.tenant._id;
9
  const branch = await resolveBranchForWrite(req);
10
  const name = req.body.name?.trim();
11
+ const normalizedName = normalizeCustomerName(name);
12
+ const normalizedPhone = normalizeCustomerPhone(req.body.phone);
13
 
14
  if (!name) {
15
  return res.status(400).json({ message: "اسم العميل مطلوب" });
 
22
  const exists = await Customer.findOne({
23
  tenant: tenantId,
24
  branch: branch._id,
25
+ ...(normalizedPhone
26
+ ? { phone: normalizedPhone }
27
+ : { normalizedName }),
28
  isDeleted: false,
29
  isWalkIn: { $ne: true },
30
  });
 
37
  tenant: tenantId,
38
  branch: branch._id,
39
  name,
40
+ phone: normalizedPhone || "",
41
  email: req.body.email?.trim()?.toLowerCase() || "",
42
  address: req.body.address?.trim() || "",
43
  notes: req.body.notes?.trim() || "",
 
73
  };
74
 
75
  if (search) {
76
+ const normalizedSearch = normalizeCustomerName(search);
77
+ matchQuery.$or = [
78
+ { name: { $regex: search, $options: "i" } },
79
+ { normalizedName: { $regex: normalizedSearch, $options: "i" } },
80
+ ];
81
  }
82
 
83
  const results = await Customer.aggregate([
controller/invoiceController.js CHANGED
@@ -14,10 +14,75 @@ 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,
@@ -352,6 +417,8 @@ export const addItemToInvoice = async (req, res) => {
352
 
353
  let finalCustomerId = customerId;
354
  if (customerId === "new") {
 
 
355
  // ✅ PREVENT DUPLICATES: Check if phone exists first or use upsert
356
  const customerUpdate = {
357
  name: customerName.trim(),
@@ -359,12 +426,21 @@ export const addItemToInvoice = async (req, res) => {
359
  branch: branchId,
360
  createdBy: req.user._id,
361
  };
362
- if (customerPhone?.trim()) customerUpdate.phone = customerPhone.trim();
363
 
364
  createdCustomer = await Customer.findOneAndUpdate(
365
- {
366
- tenant: tenantId,
367
- ...(customerPhone?.trim() ? { phone: customerPhone.trim() } : { name: customerName.trim(), branch: branchId, isWalkIn: false })
 
 
 
 
 
 
 
 
 
368
  },
369
  { $setOnInsert: customerUpdate },
370
  { upsert: true, new: true, runValidators: true }
@@ -372,10 +448,12 @@ export const addItemToInvoice = async (req, res) => {
372
  finalCustomerId = createdCustomer._id;
373
  }
374
 
 
 
375
  const customer = await Customer.findOne({
376
  _id: finalCustomerId,
377
  tenant: tenantId,
378
- branch: branchId,
379
  });
380
  if (!customer) {
381
  if (createdCustomer)
@@ -392,7 +470,7 @@ export const addItemToInvoice = async (req, res) => {
392
 
393
  // ✅ NEW: Update existing customer phone if it's missing but provided in request
394
  if (customer && !customer.phone && customerPhone?.trim()) {
395
- customer.phone = customerPhone.trim();
396
  await customer.save();
397
  }
398
 
@@ -563,9 +641,10 @@ export const updateRestaurantStatus = async (req, res) => {
563
  // WHATSAPP NOTIFICATION
564
  // ✅ Fixed: dine-in orders now also get notifications for key status changes
565
  const orderType = invoice.restaurantData?.orderType;
 
566
  const isEligible =
567
  orderType === "takeaway" ||
568
- orderType === "delivery" ||
569
  (isDineIn && (status === "preparing" || status === "ready_for_delivery"));
570
  let phoneNumber = null
571
  if (isEligible) {
@@ -885,18 +964,29 @@ export const createWalkInCashSale = async (req, res) => {
885
 
886
  let finalCustomerId = customerId;
887
  if (!finalCustomerId && customerName) {
 
 
888
  const customerUpdate = {
889
  name: customerName.trim(),
890
  tenant: tenantId,
891
  branch: branchId,
892
  createdBy: req.user._id,
893
  };
894
- if (customerPhone?.trim()) customerUpdate.phone = customerPhone.trim();
895
 
896
  createdCustomer = await Customer.findOneAndUpdate(
897
- {
898
- tenant: tenantId,
899
- ...(customerPhone?.trim() ? { phone: customerPhone.trim() } : { name: customerName.trim(), branch: branchId, isWalkIn: false })
 
 
 
 
 
 
 
 
 
900
  },
901
  { $setOnInsert: customerUpdate },
902
  { upsert: true, new: true, runValidators: true }
@@ -1311,7 +1401,6 @@ export const deleteInvoiceItem = async (req, res) => {
1311
  };
1312
 
1313
  export const payInvoice = async (req, res) => {
1314
- const round2 = (n) => Math.round((n));
1315
  const session = await mongoose.startSession();
1316
  session.startTransaction();
1317
 
@@ -1327,7 +1416,7 @@ export const payInvoice = async (req, res) => {
1327
  } = req.body;
1328
 
1329
  let amount = Number(req.body.amount || 0);
1330
- amount = round2(amount);
1331
  const { branchId, branchFilter } = await resolveScopedBranch(req);
1332
 
1333
  // ─ PAYMENT TYPE CHECKS ─
@@ -1341,7 +1430,7 @@ export const payInvoice = async (req, res) => {
1341
  return res.status(400).json({ message: "يجب إدخال مبلغ صحيح" });
1342
  }
1343
 
1344
- if (isTransfer && !["instapay", "vodafone_cash", "bank_transfer"].includes(transferType)) {
1345
  return res.status(400).json({ message: "نوع التحويل غير صحيح" });
1346
  }
1347
 
@@ -1385,38 +1474,19 @@ export const payInvoice = async (req, res) => {
1385
  }
1386
 
1387
  // ─ 5. CUSTOMER BINDING (UPSERT/LINK) ─
1388
- if (customerName?.trim() && customerPhone?.trim()) {
1389
- const customer = await Customer.findOneAndUpdate(
1390
- {
1391
- tenant: req.user.tenant._id,
1392
- phone: customerPhone.trim(),
1393
- },
1394
- {
1395
- $set: {
1396
- name: customerName.trim(),
1397
- phone: customerPhone.trim(),
1398
- isWalkIn: false, // Ensure they are now a real customer
1399
- },
1400
- $setOnInsert: {
1401
- tenant: req.user.tenant._id,
1402
- branch: branchId || undefined,
1403
- createdBy: req.user._id,
1404
- }
1405
- },
1406
- { upsert: true, new: true, session }
1407
- );
1408
 
1409
- // If the invoice was anonymous/walk-in, or linked to a different customer by name, update it to this phone-matched one
1410
- if (!invoice.customer || (invoice.customer.isWalkIn) || (invoice.customer && invoice.customer._id.toString() !== customer._id.toString())) {
1411
- invoice.customer = customer._id;
1412
- }
1413
- } else if (invoice.customer && customerPhone?.trim()) {
1414
- // ✅ Case where only phone is provided but customer is already linked
1415
- const existingCustomer = await Customer.findById(invoice.customer);
1416
- if (existingCustomer && !existingCustomer.phone) {
1417
- existingCustomer.phone = customerPhone.trim();
1418
- await existingCustomer.save({ session });
1419
- }
1420
  }
1421
 
1422
  // ─ 6. REGISTER PAYMENT ─
@@ -1873,6 +1943,8 @@ export const splitPayItems = async (req, res) => {
1873
  itemIds,
1874
  paymentMethod = "cash",
1875
  transferType = null,
 
 
1876
  amount,
1877
  taxRate = 14,
1878
  } = req.body;
@@ -1916,28 +1988,51 @@ export const splitPayItems = async (req, res) => {
1916
 
1917
  // ── Calculate amounts for the split ──────────────────────────────
1918
  const isDineIn = invoice.restaurantData?.orderType === "dine-in";
 
1919
  const effectiveTaxRate = isDineIn ? Math.max(0, Number(taxRate) || 0) : 0;
1920
 
1921
- const splitSubtotal = selectedItems.reduce(
1922
  (sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0),
1923
  0
1924
  );
1925
- const splitTax = Math.round((splitSubtotal * effectiveTaxRate) / 100 * 100) / 100;
1926
- const splitTotal = splitSubtotal + splitTax;
 
 
 
 
 
 
1927
 
1928
  // ── Validate payment amount ───────────────────────────────────────
1929
  const isUnpaid = paymentMethod === "unpaid";
1930
- const paymentAmount = isUnpaid ? 0 : Number(amount);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1931
 
1932
  if (!isUnpaid) {
1933
  if (!paymentAmount || paymentAmount <= 0) {
1934
  await session.abortTransaction();
1935
  return res.status(400).json({ message: "يجب إدخال مبلغ صحيح" });
1936
  }
1937
- if (paymentMethod === "cash" && paymentAmount < splitTotal - 0.01) {
1938
  await session.abortTransaction();
1939
  return res.status(400).json({
1940
- message: `المبلغ المدفوع (${paymentAmount}) أقل من إجمالي الأصناف المحددة (${splitTotal.toFixed(2)})`,
1941
  });
1942
  }
1943
  }
@@ -1948,7 +2043,7 @@ export const splitPayItems = async (req, res) => {
1948
  const splitInvoice = new Invoice({
1949
  tenant: tenantId,
1950
  branch: invoice.branch,
1951
- customer: invoice.customer,
1952
  issuedBy: req.user._id,
1953
  invoiceNumber: newInvoiceNumber,
1954
  items: selectedItems.map(item => ({
@@ -1977,7 +2072,7 @@ export const splitPayItems = async (req, res) => {
1977
  splitInvoice.payments.push({
1978
  amount: paymentAmount,
1979
  method: paymentMethod,
1980
- transferType: transferType || null,
1981
  receivedBy: req.user._id,
1982
  confirmed: true,
1983
  date: new Date(),
@@ -1998,10 +2093,16 @@ export const splitPayItems = async (req, res) => {
1998
  (sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0),
1999
  0
2000
  );
2001
- invoice.taxAmount = Math.round((remainingSubtotal * effectiveTaxRate) / 100 * 100) / 100;
2002
  }
2003
 
2004
  invoice.calculateTotals();
 
 
 
 
 
 
2005
  await invoice.save({ session });
2006
 
2007
  // ── 3. Create income record for the payment ──────────────────────
@@ -2010,7 +2111,7 @@ export const splitPayItems = async (req, res) => {
2010
  tenantId,
2011
  branchId: invoice.branch || branchId || null,
2012
  invoice: splitInvoice, // Point to the new split invoice
2013
- customer: invoice.customer,
2014
  amount: paymentAmount,
2015
  userId: req.user._id,
2016
  notes: `دفع جزئي (تقسيم الحساب) �� ${invoice.invoiceNumber}`,
@@ -2051,4 +2152,4 @@ export const splitPayItems = async (req, res) => {
2051
  } finally {
2052
  session.endSession();
2053
  }
2054
- };
 
14
  resolveBranchForWrite,
15
  resolveScopedBranch,
16
  } from "../utils/branchContext.js";
17
+ import { normalizeCustomerName, normalizeCustomerPhone } from "../utils/customerNormalization.js";
18
 
19
  const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";
20
 
21
  const INVOICE_ITEM_TYPES = ["product", "service", "catalog"];
22
+ const ALLOWED_TRANSFER_TYPES = ["instapay", "vodafone_cash", "bank_transfer", "wallet"];
23
+ const roundMoney = (value) => Math.round(Number(value || 0));
24
+
25
+ const escapeRegExp = (value = "") => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26
+
27
+ const bindSettlementCustomer = async ({
28
+ tenantId,
29
+ branchId,
30
+ userId,
31
+ customerName,
32
+ customerPhone,
33
+ fallbackCustomerId = null,
34
+ session = null,
35
+ }) => {
36
+ const displayName = String(customerName || "").trim();
37
+ const normalizedName = normalizeCustomerName(customerName);
38
+ const normalizedPhone = normalizeCustomerPhone(customerPhone);
39
+ let resolvedCustomer = null;
40
+
41
+ if (normalizedPhone) {
42
+ resolvedCustomer = await Customer.findOneAndUpdate(
43
+ { tenant: tenantId, phone: normalizedPhone },
44
+ {
45
+ $set: {
46
+ ...(displayName ? { name: displayName } : {}),
47
+ phone: normalizedPhone,
48
+ isWalkIn: false,
49
+ },
50
+ $setOnInsert: {
51
+ tenant: tenantId,
52
+ branch: branchId || undefined,
53
+ createdBy: userId || null,
54
+ },
55
+ },
56
+ { upsert: true, new: true, session }
57
+ );
58
+ } else if (normalizedName) {
59
+ const nameRegex = new RegExp(`^${escapeRegExp(displayName)}$`, "i");
60
+ resolvedCustomer = await Customer.findOne({
61
+ tenant: tenantId,
62
+ isWalkIn: false,
63
+ $or: [
64
+ { normalizedName },
65
+ { name: nameRegex },
66
+ ],
67
+ }).session(session);
68
+ }
69
+
70
+ if (!resolvedCustomer && fallbackCustomerId) {
71
+ resolvedCustomer = await Customer.findById(fallbackCustomerId).session(session);
72
+ if (resolvedCustomer && normalizedPhone && resolvedCustomer.phone !== normalizedPhone) {
73
+ resolvedCustomer.phone = normalizedPhone;
74
+ }
75
+ if (resolvedCustomer && displayName) {
76
+ resolvedCustomer.name = displayName;
77
+ resolvedCustomer.isWalkIn = false;
78
+ }
79
+ if (resolvedCustomer && (normalizedPhone || normalizedName)) {
80
+ await resolvedCustomer.save({ session });
81
+ }
82
+ }
83
+
84
+ return resolvedCustomer;
85
+ };
86
 
87
  const buildOrderMessage = ({
88
  status,
 
417
 
418
  let finalCustomerId = customerId;
419
  if (customerId === "new") {
420
+ const normalizedCustomerPhone = normalizeCustomerPhone(customerPhone);
421
+ const normalizedCustomerName = normalizeCustomerName(customerName);
422
  // ✅ PREVENT DUPLICATES: Check if phone exists first or use upsert
423
  const customerUpdate = {
424
  name: customerName.trim(),
 
426
  branch: branchId,
427
  createdBy: req.user._id,
428
  };
429
+ if (normalizedCustomerPhone) customerUpdate.phone = normalizedCustomerPhone;
430
 
431
  createdCustomer = await Customer.findOneAndUpdate(
432
+ {
433
+ tenant: tenantId,
434
+ ...(normalizedCustomerPhone
435
+ ? { phone: normalizedCustomerPhone }
436
+ : {
437
+ branch: branchId,
438
+ isWalkIn: false,
439
+ $or: [
440
+ { normalizedName: normalizedCustomerName },
441
+ { name: customerName.trim() },
442
+ ],
443
+ }),
444
  },
445
  { $setOnInsert: customerUpdate },
446
  { upsert: true, new: true, runValidators: true }
 
448
  finalCustomerId = createdCustomer._id;
449
  }
450
 
451
+ // Existing customers may belong to another branch when management users
452
+ // work in all-branches mode, so resolve by tenant-wide identity.
453
  const customer = await Customer.findOne({
454
  _id: finalCustomerId,
455
  tenant: tenantId,
456
+ isDeleted: false,
457
  });
458
  if (!customer) {
459
  if (createdCustomer)
 
470
 
471
  // ✅ NEW: Update existing customer phone if it's missing but provided in request
472
  if (customer && !customer.phone && customerPhone?.trim()) {
473
+ customer.phone = normalizeCustomerPhone(customerPhone);
474
  await customer.save();
475
  }
476
 
 
641
  // WHATSAPP NOTIFICATION
642
  // ✅ Fixed: dine-in orders now also get notifications for key status changes
643
  const orderType = invoice.restaurantData?.orderType;
644
+ const isDeliveryReadyStatus = orderType === "delivery" && status === "ready_for_delivery";
645
  const isEligible =
646
  orderType === "takeaway" ||
647
+ (orderType === "delivery" && !isDeliveryReadyStatus) ||
648
  (isDineIn && (status === "preparing" || status === "ready_for_delivery"));
649
  let phoneNumber = null
650
  if (isEligible) {
 
964
 
965
  let finalCustomerId = customerId;
966
  if (!finalCustomerId && customerName) {
967
+ const normalizedCustomerPhone = normalizeCustomerPhone(customerPhone);
968
+ const normalizedCustomerName = normalizeCustomerName(customerName);
969
  const customerUpdate = {
970
  name: customerName.trim(),
971
  tenant: tenantId,
972
  branch: branchId,
973
  createdBy: req.user._id,
974
  };
975
+ if (normalizedCustomerPhone) customerUpdate.phone = normalizedCustomerPhone;
976
 
977
  createdCustomer = await Customer.findOneAndUpdate(
978
+ {
979
+ tenant: tenantId,
980
+ ...(normalizedCustomerPhone
981
+ ? { phone: normalizedCustomerPhone }
982
+ : {
983
+ branch: branchId,
984
+ isWalkIn: false,
985
+ $or: [
986
+ { normalizedName: normalizedCustomerName },
987
+ { name: customerName.trim() },
988
+ ],
989
+ }),
990
  },
991
  { $setOnInsert: customerUpdate },
992
  { upsert: true, new: true, runValidators: true }
 
1401
  };
1402
 
1403
  export const payInvoice = async (req, res) => {
 
1404
  const session = await mongoose.startSession();
1405
  session.startTransaction();
1406
 
 
1416
  } = req.body;
1417
 
1418
  let amount = Number(req.body.amount || 0);
1419
+ amount = roundMoney(amount);
1420
  const { branchId, branchFilter } = await resolveScopedBranch(req);
1421
 
1422
  // ─ PAYMENT TYPE CHECKS ─
 
1430
  return res.status(400).json({ message: "يجب إدخال مبلغ صحيح" });
1431
  }
1432
 
1433
+ if (isTransfer && !ALLOWED_TRANSFER_TYPES.includes(transferType)) {
1434
  return res.status(400).json({ message: "نوع التحويل غير صحيح" });
1435
  }
1436
 
 
1474
  }
1475
 
1476
  // ─ 5. CUSTOMER BINDING (UPSERT/LINK) ─
1477
+ const settlementCustomer = await bindSettlementCustomer({
1478
+ tenantId: req.user.tenant._id,
1479
+ branchId,
1480
+ userId: req.user._id,
1481
+ customerName,
1482
+ customerPhone,
1483
+ fallbackCustomerId: invoice.customer?._id || invoice.customer || null,
1484
+ session,
1485
+ });
 
 
 
 
 
 
 
 
 
 
 
1486
 
1487
+ if (settlementCustomer && (!invoice.customer ||
1488
+ (invoice.customer._id?.toString?.() || invoice.customer.toString()) !== settlementCustomer._id.toString())) {
1489
+ invoice.customer = settlementCustomer._id;
 
 
 
 
 
 
 
 
1490
  }
1491
 
1492
  // ─ 6. REGISTER PAYMENT ─
 
1943
  itemIds,
1944
  paymentMethod = "cash",
1945
  transferType = null,
1946
+ customerName,
1947
+ customerPhone,
1948
  amount,
1949
  taxRate = 14,
1950
  } = req.body;
 
1988
 
1989
  // ── Calculate amounts for the split ──────────────────────────────
1990
  const isDineIn = invoice.restaurantData?.orderType === "dine-in";
1991
+ const isTransfer = paymentMethod === "transfer";
1992
  const effectiveTaxRate = isDineIn ? Math.max(0, Number(taxRate) || 0) : 0;
1993
 
1994
+ const splitSubtotalRaw = selectedItems.reduce(
1995
  (sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0),
1996
  0
1997
  );
1998
+ const splitSubtotal = roundMoney(splitSubtotalRaw);
1999
+ const splitTax = roundMoney((splitSubtotalRaw * effectiveTaxRate) / 100);
2000
+ const splitTotal = roundMoney(splitSubtotal + splitTax);
2001
+
2002
+ if (isTransfer && !ALLOWED_TRANSFER_TYPES.includes(transferType)) {
2003
+ await session.abortTransaction();
2004
+ return res.status(400).json({ message: "نوع التحويل غير صحيح" });
2005
+ }
2006
 
2007
  // ── Validate payment amount ───────────────────────────────────────
2008
  const isUnpaid = paymentMethod === "unpaid";
2009
+ const paymentAmount = isUnpaid ? 0 : roundMoney(amount);
2010
+ const customerRequired = paymentMethod === "unpaid" || paymentMethod === "transfer";
2011
+
2012
+ if (customerRequired && (!customerName?.trim() || !customerPhone?.trim())) {
2013
+ await session.abortTransaction();
2014
+ return res.status(400).json({ message: "يجب إدخال اسم العميل ورقم الهاتف" });
2015
+ }
2016
+
2017
+ const settlementCustomer = await bindSettlementCustomer({
2018
+ tenantId,
2019
+ branchId: invoice.branch || branchId || null,
2020
+ userId: req.user._id,
2021
+ customerName,
2022
+ customerPhone,
2023
+ fallbackCustomerId: invoice.customer?._id || invoice.customer || null,
2024
+ session,
2025
+ });
2026
 
2027
  if (!isUnpaid) {
2028
  if (!paymentAmount || paymentAmount <= 0) {
2029
  await session.abortTransaction();
2030
  return res.status(400).json({ message: "يجب إدخال مبلغ صحيح" });
2031
  }
2032
+ if (paymentMethod === "cash" && paymentAmount < splitTotal) {
2033
  await session.abortTransaction();
2034
  return res.status(400).json({
2035
+ message: `المبلغ المدفوع (${paymentAmount}) أقل من إجمالي الأصناف المحددة (${splitTotal})`,
2036
  });
2037
  }
2038
  }
 
2043
  const splitInvoice = new Invoice({
2044
  tenant: tenantId,
2045
  branch: invoice.branch,
2046
+ customer: settlementCustomer?._id || invoice.customer,
2047
  issuedBy: req.user._id,
2048
  invoiceNumber: newInvoiceNumber,
2049
  items: selectedItems.map(item => ({
 
2072
  splitInvoice.payments.push({
2073
  amount: paymentAmount,
2074
  method: paymentMethod,
2075
+ transferType: isTransfer ? transferType : null,
2076
  receivedBy: req.user._id,
2077
  confirmed: true,
2078
  date: new Date(),
 
2093
  (sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0),
2094
  0
2095
  );
2096
+ invoice.taxAmount = roundMoney((remainingSubtotal * effectiveTaxRate) / 100);
2097
  }
2098
 
2099
  invoice.calculateTotals();
2100
+
2101
+ if (settlementCustomer && (!invoice.customer ||
2102
+ (invoice.customer._id?.toString?.() || invoice.customer.toString()) !== settlementCustomer._id.toString())) {
2103
+ invoice.customer = settlementCustomer._id;
2104
+ }
2105
+
2106
  await invoice.save({ session });
2107
 
2108
  // ── 3. Create income record for the payment ──────────────────────
 
2111
  tenantId,
2112
  branchId: invoice.branch || branchId || null,
2113
  invoice: splitInvoice, // Point to the new split invoice
2114
+ customer: settlementCustomer || invoice.customer,
2115
  amount: paymentAmount,
2116
  userId: req.user._id,
2117
  notes: `دفع جزئي (تقسيم الحساب) �� ${invoice.invoiceNumber}`,
 
2152
  } finally {
2153
  session.endSession();
2154
  }
2155
+ };
models/CustomerModel.js CHANGED
@@ -1,4 +1,5 @@
1
  import mongoose from "mongoose";
 
2
 
3
  const customerSchema = new mongoose.Schema(
4
  {
@@ -21,6 +22,11 @@ const customerSchema = new mongoose.Schema(
21
  maxlength: [20, "Customer max 20"],
22
  trim: true,
23
  },
 
 
 
 
 
24
  phone: {
25
  type: String,
26
  default: "",
@@ -69,6 +75,11 @@ const customerSchema = new mongoose.Schema(
69
  );
70
 
71
  customerSchema.index({ tenant: 1, branch: 1, name: 1 });
 
72
  customerSchema.index({ tenant: 1, branch: 1, isWalkIn: 1 });
73
 
 
 
 
 
74
  export default mongoose.model("Customer", customerSchema);
 
1
  import mongoose from "mongoose";
2
+ import { normalizeCustomerName } from "../utils/customerNormalization.js";
3
 
4
  const customerSchema = new mongoose.Schema(
5
  {
 
22
  maxlength: [20, "Customer max 20"],
23
  trim: true,
24
  },
25
+ normalizedName: {
26
+ type: String,
27
+ default: "",
28
+ index: true,
29
+ },
30
  phone: {
31
  type: String,
32
  default: "",
 
75
  );
76
 
77
  customerSchema.index({ tenant: 1, branch: 1, name: 1 });
78
+ customerSchema.index({ tenant: 1, branch: 1, normalizedName: 1 });
79
  customerSchema.index({ tenant: 1, branch: 1, isWalkIn: 1 });
80
 
81
+ customerSchema.pre("validate", function () {
82
+ this.normalizedName = normalizeCustomerName(this.name || "");
83
+ });
84
+
85
  export default mongoose.model("Customer", customerSchema);
models/OrderModel.js CHANGED
@@ -200,23 +200,21 @@ orderSchema.index({ tenant: 1, driver: 1 });
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,
@@ -237,11 +235,9 @@ orderSchema.pre("save", function (next) {
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;
 
200
 
201
  // 🔥 ================= VALIDATION =================
202
 
203
+ orderSchema.pre("validate", function () {
204
  // dine-in لازم table
205
  if (this.orderType === "dine-in" && !this.table) {
206
+ throw new Error("Table is required for dine-in orders");
207
  }
208
 
209
  // delivery لازم address
210
  if (this.orderType === "delivery" && !this.deliveryInfo?.address) {
211
+ throw new Error("Address is required for delivery orders");
212
  }
 
 
213
  });
214
 
215
 
216
 
217
+ orderSchema.pre("save", function () {
218
  // حساب subtotal
219
  this.subtotal = this.items.reduce(
220
  (sum, item) => sum + item.quantity * item.price,
 
235
  } else {
236
  this.paymentStatus = "paid";
237
  }
 
 
238
  });
239
 
240
 
241
  const Order = mongoose.model("Order", orderSchema);
242
 
243
+ export default Order;
utils/customerNormalization.js ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const normalizeCustomerName = (value = "") => {
2
+ return String(value || "")
3
+ .trim()
4
+ .replace(/\s+/g, " ")
5
+ .replace(/[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06ED]/g, "")
6
+ .replace(/ـ/g, "")
7
+ .replace(/[أإآٱ]/g, "ا")
8
+ .replace(/ؤ/g, "و")
9
+ .replace(/ئ/g, "ي")
10
+ .replace(/ى/g, "ي")
11
+ .toLowerCase();
12
+ };
13
+
14
+ export const normalizeCustomerPhone = (value = "") => {
15
+ let digits = String(value || "").replace(/\D/g, "");
16
+ if (!digits) return "";
17
+
18
+ if (digits.startsWith("0") && digits.length === 11) {
19
+ digits = `20${digits.slice(1)}`;
20
+ } else if (digits.length === 10 && digits.startsWith("1")) {
21
+ digits = `20${digits}`;
22
+ }
23
+
24
+ return digits;
25
+ };
26
+