Mahmoud7456 commited on
Commit
df049d2
ยท
verified ยท
1 Parent(s): 1e65df5

Upload 38 files

Browse files
Files changed (1) hide show
  1. controller/invoiceController.js +88 -34
controller/invoiceController.js CHANGED
@@ -124,7 +124,7 @@ async function generateInvoiceNumber(tenantId, branchId) {
124
  },
125
  );
126
 
127
- const padded = String(counter.invoiceNumber).padStart(5, "0");
128
  return `INV-${padded}`;
129
  }
130
 
@@ -639,12 +639,14 @@ export const updateRestaurantStatus = async (req, res) => {
639
  }
640
 
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) {
@@ -1122,7 +1124,7 @@ export const createWalkInCashSale = async (req, res) => {
1122
 
1123
  const populatedInvoice = await Invoice.findById(invoice._id).populate(
1124
  "customer",
1125
- "name isWalkIn",
1126
  );
1127
 
1128
  // โœ… Return changeDue so frontend can display it
@@ -1226,7 +1228,7 @@ export const getInvoiceById = async (req, res) => {
1226
  tenant: req.user.tenant._id,
1227
  ...branchFilter,
1228
  })
1229
- .populate("customer", "name isWalkIn")
1230
  .populate({
1231
  path: "items.productId",
1232
  select: "name price",
@@ -1801,15 +1803,36 @@ export const addItemsToOpenTab = async (req, res) => {
1801
  }
1802
  }
1803
 
1804
- invoice.items.push({
1805
- name: String(item.name).trim(),
1806
- quantity,
1807
- price,
1808
- total: quantity * price,
1809
- type: item.type || "catalog",
1810
- productId: item.productId || null,
1811
- catalogItemId: item.catalogItemId || null,
 
 
 
 
 
 
1812
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1813
  }
1814
 
1815
  // โœ… Recalculate tax using dynamic rate AFTER all items are added
@@ -1975,13 +1998,53 @@ export const splitPayItems = async (req, res) => {
1975
  return res.status(400).json({ message: "ู„ุง ูŠู…ูƒู† ุงู„ุฏูุน ู„ูุงุชูˆุฑุฉ ู…ู„ุบุงุฉ" });
1976
  }
1977
 
1978
- // โ”€โ”€ Identify selected items โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1979
- const itemIdSet = new Set(itemIds.map(String));
1980
- const selectedItems = invoice.items.filter((item) =>
1981
- itemIdSet.has(item._id.toString())
1982
- );
 
 
 
 
1983
 
1984
- if (selectedItems.length === 0) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1985
  await session.abortTransaction();
1986
  return res.status(400).json({ message: "ุงู„ุฃุตู†ุงู ุงู„ู…ุญุฏุฏุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ ููŠ ุงู„ูุงุชูˆุฑุฉ" });
1987
  }
@@ -1991,9 +2054,9 @@ export const splitPayItems = async (req, res) => {
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);
@@ -2046,16 +2109,7 @@ export const splitPayItems = async (req, res) => {
2046
  customer: settlementCustomer?._id || invoice.customer,
2047
  issuedBy: req.user._id,
2048
  invoiceNumber: newInvoiceNumber,
2049
- items: selectedItems.map(item => ({
2050
- name: item.name,
2051
- price: item.price,
2052
- quantity: item.quantity,
2053
- total: item.total,
2054
- type: item.type,
2055
- productId: item.productId,
2056
- serviceId: item.serviceId,
2057
- catalogItemId: item.catalogItemId
2058
- })),
2059
  taxAmount: splitTax,
2060
  discount: 0,
2061
  serviceCharge: 0,
 
124
  },
125
  );
126
 
127
+ const padded = String(counter.invoiceNumber).padStart(8, "0");
128
  return `INV-${padded}`;
129
  }
130
 
 
639
  }
640
 
641
  // WHATSAPP NOTIFICATION
642
+ // Delivery orders: only send "preparing" and "shipped" โ€” skip "ready_for_delivery"
643
+ // because that message implies the customer should come pick up, which is wrong for delivery.
644
+ // Takeaway orders: send "preparing", "ready_for_delivery", "shipped"
645
+ // Dine-in orders: send "preparing" and "ready_for_delivery" (dine-in-ready template)
646
  const orderType = invoice.restaurantData?.orderType;
 
647
  const isEligible =
648
+ (orderType === "delivery" && (status === "preparing" || status === "shipped")) ||
649
+ (orderType === "takeaway" && (status === "preparing" || status === "ready_for_delivery" || status === "shipped")) ||
650
  (isDineIn && (status === "preparing" || status === "ready_for_delivery"));
651
  let phoneNumber = null
652
  if (isEligible) {
 
1124
 
1125
  const populatedInvoice = await Invoice.findById(invoice._id).populate(
1126
  "customer",
1127
+ "name isWalkIn phone",
1128
  );
1129
 
1130
  // โœ… Return changeDue so frontend can display it
 
1228
  tenant: req.user.tenant._id,
1229
  ...branchFilter,
1230
  })
1231
+ .populate("customer", "name isWalkIn phone")
1232
  .populate({
1233
  path: "items.productId",
1234
  select: "name price",
 
1803
  }
1804
  }
1805
 
1806
+ // โ”€โ”€ Merge with existing item if same identity, otherwise push new โ”€โ”€
1807
+ const normalizedType = item.type || "catalog";
1808
+ const existingItem = invoice.items.find((existing) => {
1809
+ if (item.catalogItemId && existing.catalogItemId) {
1810
+ return existing.catalogItemId?.toString() === item.catalogItemId?.toString();
1811
+ }
1812
+ if (item.productId && existing.productId) {
1813
+ return existing.productId?.toString() === item.productId?.toString();
1814
+ }
1815
+ // Fallback: match by name + type for manual/service items
1816
+ return (
1817
+ existing.name === String(item.name).trim() &&
1818
+ existing.type === normalizedType
1819
+ );
1820
  });
1821
+
1822
+ if (existingItem) {
1823
+ existingItem.quantity += quantity;
1824
+ existingItem.total = existingItem.quantity * existingItem.price;
1825
+ } else {
1826
+ invoice.items.push({
1827
+ name: String(item.name).trim(),
1828
+ quantity,
1829
+ price,
1830
+ total: quantity * price,
1831
+ type: normalizedType,
1832
+ productId: item.productId || null,
1833
+ catalogItemId: item.catalogItemId || null,
1834
+ });
1835
+ }
1836
  }
1837
 
1838
  // โœ… Recalculate tax using dynamic rate AFTER all items are added
 
1998
  return res.status(400).json({ message: "ู„ุง ูŠู…ูƒู† ุงู„ุฏูุน ู„ูุงุชูˆุฑุฉ ู…ู„ุบุงุฉ" });
1999
  }
2000
 
2001
+ // โ”€โ”€ Identify items and quantities to split โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
2002
+ let itemsToSplit = [];
2003
+ if (req.body.splitItems && Array.isArray(req.body.splitItems)) {
2004
+ // New format: [{ itemId, quantity }]
2005
+ itemsToSplit = req.body.splitItems;
2006
+ } else if (itemIds && Array.isArray(itemIds)) {
2007
+ // Legacy/Full-split format: [itemId, itemId]
2008
+ itemsToSplit = itemIds.map(id => ({ itemId: id, quantity: null })); // null means "take all"
2009
+ }
2010
 
2011
+ if (itemsToSplit.length === 0) {
2012
+ await session.abortTransaction();
2013
+ return res.status(400).json({ message: "ูŠุฌุจ ุชุญุฏูŠุฏ ุตู†ู ูˆุงุญุฏ ุนู„ู‰ ุงู„ุฃู‚ู„ ู„ู„ุฏูุน" });
2014
+ }
2015
+
2016
+ const selectedItemsForNewInvoice = [];
2017
+
2018
+ for (const splitEntry of itemsToSplit) {
2019
+ const itemInOriginal = invoice.items.id(splitEntry.itemId);
2020
+ if (!itemInOriginal) continue;
2021
+
2022
+ const qtyToSplit = splitEntry.quantity !== null && splitEntry.quantity !== undefined
2023
+ ? Math.min(Number(splitEntry.quantity), itemInOriginal.quantity)
2024
+ : itemInOriginal.quantity;
2025
+
2026
+ if (qtyToSplit <= 0) continue;
2027
+
2028
+ // Add to the list for the NEW invoice
2029
+ selectedItemsForNewInvoice.push({
2030
+ ...itemInOriginal.toObject(),
2031
+ quantity: qtyToSplit,
2032
+ total: roundMoney(qtyToSplit * itemInOriginal.price),
2033
+ _id: new mongoose.Types.ObjectId(), // New ID for the split item
2034
+ });
2035
+
2036
+ // Update the ORIGINAL invoice item
2037
+ if (qtyToSplit >= itemInOriginal.quantity) {
2038
+ // Remove entirely
2039
+ itemInOriginal.deleteOne();
2040
+ } else {
2041
+ // Decrement quantity
2042
+ itemInOriginal.quantity -= qtyToSplit;
2043
+ itemInOriginal.total = roundMoney(itemInOriginal.quantity * itemInOriginal.price);
2044
+ }
2045
+ }
2046
+
2047
+ if (selectedItemsForNewInvoice.length === 0) {
2048
  await session.abortTransaction();
2049
  return res.status(400).json({ message: "ุงู„ุฃุตู†ุงู ุงู„ู…ุญุฏุฏุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ ููŠ ุงู„ูุงุชูˆุฑุฉ" });
2050
  }
 
2054
  const isTransfer = paymentMethod === "transfer";
2055
  const effectiveTaxRate = isDineIn ? Math.max(0, Number(taxRate) || 0) : 0;
2056
 
2057
+ const splitSubtotalRaw = selectedItemsForNewInvoice.reduce(
2058
+ (sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0),
2059
+ 0
2060
  );
2061
  const splitSubtotal = roundMoney(splitSubtotalRaw);
2062
  const splitTax = roundMoney((splitSubtotalRaw * effectiveTaxRate) / 100);
 
2109
  customer: settlementCustomer?._id || invoice.customer,
2110
  issuedBy: req.user._id,
2111
  invoiceNumber: newInvoiceNumber,
2112
+ items: selectedItemsForNewInvoice,
 
 
 
 
 
 
 
 
 
2113
  taxAmount: splitTax,
2114
  discount: 0,
2115
  serviceCharge: 0,