Spaces:
Running
Running
File size: 38,655 Bytes
634b9bb | 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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 | const Order = require('../models/orderModel');
const Product = require('../models/productModel');
const ShippingPrice = require('../models/shippingPriceModel');
const Capital = require('../models/capitalModel');
const Promo = require('../models/promoCodeModel');
const User = require('../models/userModel');
const {
sendOrderConfirmationEmail,
sendOrderStatusUpdateEmail,
sendAdminNewOrderEmail,
} = require('../utils/emailService');
const { PERMISSIONS } = require('../utils/permissions');
const {
notifyOrderCreated,
notifyOrderProcessing,
notifyOrderShipped,
notifyOrderCompleted,
notifyOrderCancelled,
notifyVendorNewOrder,
notifyProductOutOfStock,
notifyAdminsNewOrder,
notifyAdminsProductOutOfStock,
emitOrderUpdate,
} = require('../utils/notificationService');
const { restoreOrderStock, deductOrderStock } = require('../utils/orderUtils');
const { appendOrderToSheet } = require('../utils/googleSheetsService');
exports.getAllOrders = async (req, res) => {
try {
const orders = await Order.find()
.populate('user', 'name email address mobile')
.populate({
path: 'items.product',
select: 'nameAr nameEn imageCover price provider',
populate: {
path: 'provider',
select: 'storeName name',
},
})
.sort({ createdAt: -1 })
.lean();
res.status(200).json({
status: 'success',
results: orders.length,
data: { orders },
});
} catch (err) {
res.status(500).json({
status: 'error',
message: err.message,
});
}
};
// Get orders for the authenticated user only
exports.getMyOrders = async (req, res) => {
try {
if (!req.user) {
return res.status(401).json({
status: 'fail',
message: 'You must be logged in to view your orders',
});
}
const orders = await Order.find({ user: req.user._id })
.populate('items.product', 'nameAr nameEn imageCover price')
.sort({ createdAt: -1 })
.lean();
res.status(200).json({
status: 'success',
results: orders.length,
data: { orders },
});
} catch (err) {
res.status(500).json({
status: 'error',
message: err.message,
});
}
};
exports.getOrder = async (req, res) => {
try {
const order = await Order.findById(req.params.id)
.populate({
path: 'items.product',
populate: {
path: 'provider',
model: 'Provider',
},
})
.populate('user', 'name email mobile address')
.lean();
if (!order) {
return res.status(404).json({
status: 'fail',
message: 'No order found',
});
}
// Authorization check
let isAuthorized = false;
if (req.user) {
// 1) Admins and employees with manage_orders permission can see any order
const isAdmin = req.user.role === 'admin';
const isEmployee =
req.user.role === 'employee' &&
req.user.permissions.includes(PERMISSIONS.MANAGE_ORDERS);
// 2) Users can see their own orders
const orderUserId = (order.user && order.user._id) || order.user;
const isOwner =
orderUserId && String(orderUserId) === String(req.user._id);
// 3) Vendors can see the order if it contains one of their products
let isVendorOfThisOrder = false;
if (req.user.role === 'vendor' && req.user.provider) {
const vendorProviderId = String(
req.user.provider._id || req.user.provider,
);
isVendorOfThisOrder =
order.items &&
order.items.some((item) => {
if (!item.product) return false;
const itemProviderId = String(
(item.product &&
item.product.provider &&
item.product.provider._id) ||
(item.product && item.product.provider) ||
'',
);
return itemProviderId === vendorProviderId;
});
}
if (isAdmin || isEmployee || isOwner || isVendorOfThisOrder) {
isAuthorized = true;
}
} else {
// Guest Access:
// If the order has NO user attached, we assume it's a guest order and allow access (since they have the ID)
if (!order.user) {
isAuthorized = true;
}
}
if (!isAuthorized) {
return res.status(403).json({
status: 'fail',
message: 'You are not authorized to view this order',
});
}
res.status(200).json({
status: 'success',
data: { order },
});
} catch (err) {
res.status(500).json({
status: 'error',
message: err.message,
});
}
};
exports.updateOrder = async (req, res) => {
try {
// Get the old order to check if status changed
const oldOrder = await Order.findById(req.params.id);
if (!oldOrder) {
return res
.status(404)
.json({ status: 'fail', message: 'No order found' });
}
// Prevent moving order away from 'cancelled' if any items are cancelled
if (req.body.orderStatus && req.body.orderStatus !== 'cancelled') {
const hasCancelledItems = oldOrder.items.some(
(item) => item.fulfillmentStatus === 'cancelled',
);
if (hasCancelledItems) {
// If it's an admin, we allow it BUT we must reset the items and handle stock
if (req.user && req.user.role === 'admin') {
// Reset all cancelled items to pending
const updatedItems = oldOrder.items.map((item) => {
if (item.fulfillmentStatus === 'cancelled') {
return { ...item.toObject(), fulfillmentStatus: 'pending' };
}
return item.toObject();
});
req.body.items = updatedItems;
// If moving from 'cancelled' order status, deduct stock again
if (oldOrder.orderStatus === 'cancelled') {
await deductOrderStock(oldOrder.items);
}
} else {
return res.status(400).json({
status: 'fail',
message:
'نعتذر، لا يمكن تغيير حالة الطلب بينما توجد منتجات ملغاة. يجب معالجة المنتجات الملغاة أولاً.',
});
}
}
}
// Handle moving TO cancelled status - propagate to all items
if (
req.body.orderStatus === 'cancelled' &&
oldOrder.orderStatus !== 'cancelled'
) {
const updatedItems = oldOrder.items.map((item) => ({
...item.toObject(),
fulfillmentStatus: 'cancelled',
}));
req.body.items = updatedItems;
}
// Check if status is being changed to shipped or completed and all items are ready
if (
req.body.orderStatus &&
['shipped', 'completed'].includes(req.body.orderStatus)
) {
const allReady = oldOrder.items.every(
(item) => item.fulfillmentStatus === 'ready',
);
if (!allReady) {
return res.status(400).json({
status: 'fail',
message:
'Cannot change order status to shipped/completed until all items are marked as ready.',
});
}
}
const updatedOrder = await Order.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true },
)
.populate({
path: 'items.product',
populate: {
path: 'provider',
model: 'Provider',
},
})
.populate('user', 'name email');
// Check if order status changed and send email + notification
if (
req.body.orderStatus &&
req.body.orderStatus !== oldOrder.orderStatus &&
updatedOrder.user
) {
// If status changed to cancelled, restore stock
if (req.body.orderStatus === 'cancelled') {
await restoreOrderStock(updatedOrder.items);
// ── Capital: Reverse profit if order was previously completed ──
if (oldOrder.orderStatus === 'completed') {
try {
const populatedForReversal = await Order.findById(
updatedOrder._id,
).populate({
path: 'items.product',
select: 'costPrice',
});
let reversedProfit = 0;
for (const item of populatedForReversal.items) {
if (!item.product) continue;
const costPrice = item.product.costPrice || 0;
const sellingPrice = item.unitPrice;
reversedProfit += (sellingPrice - costPrice) * item.quantity;
}
if (reversedProfit > 0) {
const capital = await Capital.getCapital();
capital.currentCapital -= reversedProfit;
capital.logs.push({
type: 'adjustment',
amount: -reversedProfit,
balanceAfter: capital.currentCapital,
reference: updatedOrder._id,
referenceModel: 'Order',
description: `Reversed profit — completed order #${updatedOrder._id.toString().slice(-8).toUpperCase()} was cancelled`,
date: new Date(),
createdBy: req.user._id,
});
await capital.save();
}
} catch (capitalErr) {
console.error(
'Failed to reverse capital on order cancellation:',
capitalErr.message,
);
}
}
}
// Prepare order data for email
const emailOrderData = {
orderNumber: updatedOrder._id.toString().slice(-8).toUpperCase(),
total: updatedOrder.totalPrice,
};
// Send status update email (don't wait for it)
sendOrderStatusUpdateEmail(
emailOrderData,
updatedOrder.user,
req.body.orderStatus,
).catch(() => { });
// Send notification based on status
const userId = updatedOrder.user._id || updatedOrder.user;
try {
switch (req.body.orderStatus) {
case 'created':
await notifyOrderCreated(updatedOrder, userId);
break;
case 'processing':
await notifyOrderProcessing(updatedOrder, userId);
break;
case 'shipped':
await notifyOrderShipped(updatedOrder, userId);
break;
case 'completed':
await notifyOrderCompleted(updatedOrder, userId);
break;
case 'cancelled':
await notifyOrderCancelled(updatedOrder, userId);
break;
default:
break;
}
} catch (notifErr) {
// Silent fail
}
// ── Capital: Add profit when order is marked completed ──
if (req.body.orderStatus === 'completed') {
try {
const populatedForProfit = await Order.findById(
updatedOrder._id,
).populate({
path: 'items.product',
select: 'costPrice purchasePrice',
});
let orderProfit = 0;
for (const item of populatedForProfit.items) {
if (!item.product) continue;
const costPrice = item.product.costPrice || 0;
const sellingPrice = item.unitPrice;
orderProfit += (sellingPrice - costPrice) * item.quantity;
}
if (orderProfit > 0) {
const capital = await Capital.getCapital();
capital.currentCapital += orderProfit;
capital.logs.push({
type: 'profit',
amount: orderProfit,
balanceAfter: capital.currentCapital,
reference: updatedOrder._id,
referenceModel: 'Order',
description: `Profit from completed order #${updatedOrder._id.toString().slice(-8).toUpperCase()}`,
date: new Date(),
createdBy: req.user._id,
});
await capital.save();
}
} catch (capitalErr) {
// Silent fail — don't block order update
console.error(
'Failed to update capital on order completion:',
capitalErr.message,
);
}
}
// Explicitly broadcast order update for the dashboard (ONLY ONCE)
emitOrderUpdate(updatedOrder, req.body.orderStatus);
}
res.status(200).json({ status: 'success', data: { order: updatedOrder } });
} catch (err) {
res.status(500).json({ status: 'error', message: err.message });
}
};
exports.cancelOrder = async (req, res) => {
try {
const { id } = req.params;
const order = await Order.findById(id);
if (!order)
return res
.status(404)
.json({ status: 'fail', message: 'Order not found' });
if (!req.user)
return res.status(401).json({
status: 'fail',
message: 'You must be logged in to cancel an order',
});
const orderUserId = (order.user && order.user._id) || order.user;
const isOwner = orderUserId && String(orderUserId) === String(req.user._id);
const isAdmin = req.user.role === 'admin';
if (!isOwner && !isAdmin)
return res.status(403).json({
status: 'fail',
message: 'Not authorized to cancel this order',
});
if (order.orderStatus === 'cancelled') {
return res
.status(400)
.json({ status: 'fail', message: 'Order is already cancelled' });
}
await restoreOrderStock(order.items);
if (order.promo) {
try {
await Promo.findByIdAndUpdate(order.promo, { $inc: { usedCount: -1 } });
} catch (promoErr) {
console.error('Failed to restore promo usage:', promoErr);
}
}
order.orderStatus = 'cancelled';
order.canceledAt = new Date();
if (order.payment && order.payment.status !== 'failed') {
order.payment.status = 'failed';
}
await order.save();
// Send cancellation notification
try {
const userId = order.user;
await notifyOrderCancelled(order, userId, 'Order cancelled as requested');
} catch (notifErr) {
// Silent fail
}
// Explicitly broadcast order update for the dashboard (ONLY ONCE)
emitOrderUpdate(order, 'order_cancelled');
// Populate product details before returning
await order.populate('items.product', 'nameAr nameEn imageCover price');
res.status(200).json({ status: 'success', data: { order } });
} catch (err) {
res.status(500).json({ status: 'error', message: err.message });
}
};
exports.deleteOrder = async (req, res) => {
try {
const order = await Order.findByIdAndDelete(req.params.id);
if (!order) {
return res.status(404).json({
status: 'fail',
message: 'No order found',
});
}
// Explicitly broadcast order update for the dashboard
emitOrderUpdate({ _id: req.params.id }, 'order_deleted');
res.status(204).json({
status: 'success',
data: null,
});
} catch (err) {
res.status(500).json({
status: 'error',
message: err.message,
});
}
};
exports.getOrderSuccessPage = async (req, res) => {
try {
const { id } = req.params;
const order = await Order.findById(id).populate('items.product').lean();
if (!order)
return res
.status(404)
.json({ status: 'fail', message: 'Order not found' });
res.status(200).json({
status: 'success',
data: {
message: 'Order placed successfully',
order,
},
});
} catch (err) {
res.status(500).json({ status: 'error', message: err.message });
}
};
function computeDiscountAmount(type, value, base) {
const numericBase = Number(base) || 0;
const numericValue = Number(value) || 0;
if (type === 'shipping') return 0; // Does not affect subtotal base
if (type === 'percentage')
return Math.max(0, (numericBase * numericValue) / 100);
return Math.max(0, numericValue);
}
const SiteSettings = require('../models/siteSettingsModel');
exports.createOrder = async (req, res) => {
try {
const { name, mobile, address, payment, items, promoCode, source } = req.body;
// Check guest checkout settings
if (!req.user) {
const settings = await SiteSettings.getSettings();
if (!settings.checkout.allowGuestCheckout) {
return res.status(401).json({
status: 'fail',
message:
'Guest checkout is disabled. Please log in or create an account to place an order.',
});
}
}
if (!items || !Array.isArray(items) || items.length === 0) {
return res
.status(400)
.json({ status: 'fail', message: 'Cart items are required' });
}
if (payment && payment.method === 'visa' && !req.user) {
return res.status(400).json({
status: 'fail',
message: 'You must be logged in to pay with Visa',
});
}
const productIds = items.map((i) => i.productId);
const products = await Product.find({ _id: { $in: productIds } });
const productMap = new Map(products.map((p) => [String(p._id), p]));
const missingIds = productIds.filter((id) => !productMap.has(String(id)));
if (missingIds.length > 0) {
return res.status(400).json({
status: 'fail',
message: 'Some products were not found',
missingProductIds: missingIds,
});
}
// Decrease stock for each product and track out-of-stock items
// Decrease stock for each product in bulk
const bulkOps = items.map((i) => ({
updateOne: {
filter: { _id: i.productId },
update: { $inc: { stock: -(Number(i.quantity) || 1) } },
},
}));
await Product.bulkWrite(bulkOps);
// Identify products that went out of stock
const outOfStockItems = await Product.find({
_id: { $in: productIds },
stock: { $lte: 0 },
});
let subtotal = 0;
const orderItems = [];
for (const i of items) {
const prod = productMap.get(String(i.productId));
const quantity = Number(i.quantity) || 1;
const unitPrice =
prod.salePrice && prod.salePrice < prod.price
? prod.salePrice
: prod.price;
subtotal += unitPrice * quantity;
orderItems.push({
product: prod._id,
name: prod.nameAr || prod.nameEn || prod.barCode,
quantity,
unitPrice,
});
}
// Dynamic Shipping Calculation:
// Strictly find price for the governorate level
const govPrice = await ShippingPrice.findOne({
$or: [
{ areaNameAr: address.governorate },
{
areaNameEn: {
$regex: new RegExp(`^${address.governorate.trim()}$`, 'i'),
},
},
],
type: 'city',
});
const SHIPPING_COST = govPrice ? govPrice.fees : 300;
const deliveryDays = govPrice ? govPrice.deliveryDays : 3;
// Calculate estimated delivery date
const estimatedDeliveryDate = new Date();
estimatedDeliveryDate.setDate(
estimatedDeliveryDate.getDate() + deliveryDays,
);
let totalPrice = subtotal + SHIPPING_COST;
let appliedPromo = null;
let discountAmountApplied = 0;
if (promoCode) {
const upper = String(promoCode).trim().toUpperCase();
const now = new Date();
const promo = await Promo.findOne({
code: upper,
active: true,
$and: [
{ $or: [{ startsAt: null }, { startsAt: { $lte: now } }] },
{ $or: [{ expiresAt: null }, { expiresAt: { $gt: now } }] },
],
minOrderValue: { $lte: subtotal },
});
if (!promo)
return res
.status(400)
.json({ status: 'fail', message: 'Invalid or expired promo code' });
if (promo.perUserLimit && promo.perUserLimit > 0) {
if (!req.user)
return res.status(400).json({
status: 'fail',
message: 'You must be logged in to use this promo code',
});
const userUses = await Order.countDocuments({
user: req.user._id,
promo: promo._id,
});
if (userUses >= promo.perUserLimit)
return res.status(400).json({
status: 'fail',
message: 'Promo code usage limit reached for this user',
});
}
if (promo.usageLimit != null && promo.usedCount >= promo.usageLimit)
return res
.status(400)
.json({ status: 'fail', message: 'Promo code has been fully used' });
await Promo.findByIdAndUpdate(promo._id, { $inc: { usedCount: 1 } });
appliedPromo = promo;
const discount = computeDiscountAmount(promo.type, promo.value, subtotal);
discountAmountApplied = discount;
if (promo.type === 'shipping') {
totalPrice = subtotal; // Shipping is free
discountAmountApplied = SHIPPING_COST; // Record the shipping saving as the discount
} else {
totalPrice = Math.max(0, subtotal - discount) + SHIPPING_COST;
}
}
const normalizedPayment = { ...payment };
// Don't automatically mark visa payments as paid - wait for Paymob callback
if (!normalizedPayment || !normalizedPayment.status) {
normalizedPayment.status = 'pending';
}
let promoData = {};
if (promoCode && appliedPromo) {
const discountAmount = Number(discountAmountApplied.toFixed(2));
promoData = {
promo: appliedPromo._id,
promoCode: appliedPromo.code,
discountAmount,
discountType: appliedPromo.type,
};
}
const orderData = {
name,
mobile,
address,
items: orderItems,
payment: normalizedPayment,
totalPrice,
estimatedDeliveryDate,
shippingPrice: SHIPPING_COST,
source: source || 'direct',
...promoData,
};
if (req.user) orderData.user = req.user._id;
let newOrder;
try {
newOrder = await Order.create(orderData);
} catch (err) {
// Rollback: Restore stock if order creation fails
try {
await restoreOrderStock(orderItems);
} catch (restoreErr) {
console.error(
'Failed to restore stock after order creation error:',
restoreErr,
);
}
if (appliedPromo) {
try {
await Promo.findByIdAndUpdate(appliedPromo._id, {
$inc: { usedCount: -1 },
});
} catch (err2) {
// Silent fail or use a proper logger
}
}
throw err;
}
// Send notifications (ONLY for CASH orders)
// For Visa, we notify only after successful payment confirmation in paymentController
if (newOrder.payment.method === 'cash') {
try {
if (req.user) {
notifyOrderCreated(newOrder, req.user._id).catch(() => { });
}
const vendorIds = new Set();
products.forEach((p) => {
if (p.provider) vendorIds.add(p.provider.toString());
});
vendorIds.forEach((vId) => {
notifyVendorNewOrder(newOrder, vId).catch(() => { });
});
notifyAdminsNewOrder(newOrder).catch(() => { });
} catch (notifErr) {
// Silent fail
}
}
// Out-of-stock notifications should happen regardless of payment method
// because stock IS deducted from the DB now
try {
outOfStockItems.forEach((prod) => {
if (prod.provider) {
notifyProductOutOfStock(prod, prod.provider).catch(() => { });
}
notifyAdminsProductOutOfStock(prod).catch(() => { });
});
} catch (vendorNotifErr) {
// Silent fail
}
// Explicitly broadcast order update for the dashboard (ONLY ONCE)
emitOrderUpdate(newOrder, 'order_created');
res.status(201).json({
status: 'success',
data: { order: newOrder },
});
// Append to Google Sheet (fire-and-forget — never blocks the response)
appendOrderToSheet(newOrder).catch(() => { });
// Send order confirmation email (non-blocking - after response)
// ONLY for cash orders. Visa orders will send once payment is confirmed.
if (req.user && newOrder.payment.method === 'cash') {
// Populate order with product details and provider for email
const populatedOrder = await Order.findById(newOrder._id).populate({
path: 'items.product',
select: 'nameAr price imageCover',
populate: {
path: 'provider',
select: 'storeName',
},
});
// Prepare order data for email template
const emailOrderData = {
orderNumber: newOrder._id.toString().slice(-8).toUpperCase(), // Last 8 chars of ID
items: populatedOrder.items.map((item) => ({
product: {
nameAr:
item.product && item.product.nameAr
? item.product.nameAr
: item.name,
imageCover:
item.product && item.product.imageCover
? item.product.imageCover
: null,
provider:
item.product && item.product.provider
? item.product.provider
: null,
},
quantity: item.quantity,
price: item.unitPrice,
})),
subtotal: subtotal,
discount: discountAmountApplied,
shippingCost: SHIPPING_COST,
total: totalPrice,
paymentMethod: newOrder.payment.method,
shippingAddress: {
street: newOrder.address.street,
city: newOrder.address.city,
governorate: newOrder.address.governorate,
phone: newOrder.mobile,
},
};
sendOrderConfirmationEmail(emailOrderData, req.user).catch(() => { });
}
// Notify all admin users by email about the new order
User.find({ role: 'admin' })
.select('email name')
.lean()
.then((admins) => {
if (!admins || admins.length === 0) return;
// Reuse emailOrderData if already built (cash orders), otherwise build a minimal version
const adminOrderData = {
orderNumber: newOrder._id.toString().slice(-8).toUpperCase(),
items: newOrder.items.map((item) => ({
product: { nameAr: item.name, imageCover: null, provider: null },
quantity: item.quantity,
price: item.unitPrice,
})),
subtotal,
discount: discountAmountApplied,
shippingCost: SHIPPING_COST,
total: totalPrice,
paymentMethod: newOrder.payment.method,
shippingAddress: {
street: newOrder.address.street,
city: newOrder.address.city,
governorate: newOrder.address.governorate,
phone: newOrder.mobile,
},
};
const customer = req.user
? { name: req.user.name, email: req.user.email }
: { name: 'عميل غير مسجل', email: '-' };
admins.forEach((admin) => {
sendAdminNewOrderEmail(adminOrderData, customer, admin.email).catch(
() => { },
);
});
})
.catch(() => { });
} catch (err) {
res.status(500).json({
status: 'error',
message: err.message,
});
}
};
exports.updateOrderItemFulfillment = async (req, res) => {
try {
const { orderId, productId } = req.params;
const { fulfillmentStatus } = req.body;
// Validate fulfillment status
const validStatuses = ['pending', 'preparing', 'ready', 'cancelled'];
if (!validStatuses.includes(fulfillmentStatus)) {
return res
.status(400)
.json({ status: 'fail', message: 'Invalid fulfillment status' });
}
const order = await Order.findById(orderId).populate('items.product');
if (!order) {
return res
.status(404)
.json({ status: 'fail', message: 'Order not found' });
}
// Find the item
const item = order.items.find(
(it) => it.product && it.product._id.toString() === productId,
);
if (!item) {
return res
.status(404)
.json({ status: 'fail', message: 'Product not found in this order' });
}
// Authorization check
// Admins and employees with manage_orders can update anything
const isAdmin = req.user.role === 'admin';
const isEmployee =
req.user.role === 'employee' &&
req.user.permissions.includes(PERMISSIONS.MANAGE_ORDERS);
// For vendors, check if they own the product
if (!isAdmin && !isEmployee) {
if (req.user.role !== 'vendor' || !req.user.provider) {
return res
.status(403)
.json({ status: 'fail', message: 'Not authorized' });
}
const providerId = req.user.provider._id || req.user.provider;
if (item.product.provider.toString() !== providerId.toString()) {
return res.status(403).json({
status: 'fail',
message: 'You can only update your own items',
});
}
}
item.fulfillmentStatus = fulfillmentStatus;
// Handle cancellation
if (fulfillmentStatus === 'cancelled') {
order.orderStatus = 'cancelled';
// Restore stock for all items in the order
await restoreOrderStock(order.items);
} else if (
// Auto-revert order status to processing if an item is moved back from 'ready'
// when the order was already shipped or completed
fulfillmentStatus !== 'ready' &&
['shipped', 'completed'].includes(order.orderStatus)
) {
order.orderStatus = 'processing';
}
await order.save();
// Broadcast update
emitOrderUpdate(order, 'order_item_updated');
res.status(200).json({
status: 'success',
data: { order },
});
} catch (err) {
res.status(500).json({ status: 'error', message: err.message });
}
};
exports.updateOrderItemQuantity = async (req, res) => {
try {
const { orderId, productId } = req.params;
const { quantity } = req.body;
if (!quantity || quantity < 1) {
return res.status(400).json({
status: 'fail',
message: 'Quantity must be at least 1',
});
}
const order = await Order.findById(orderId).populate('items.product');
if (!order) {
return res.status(404).json({
status: 'fail',
message: 'Order not found',
});
}
// Authorization check: Only admins or authorized employees can edit quantities
const isAdmin = req.user.role === 'admin';
const isEmployee =
req.user.role === 'employee' &&
req.user.permissions.includes(PERMISSIONS.MANAGE_ORDERS);
if (!isAdmin && !isEmployee) {
return res.status(403).json({
status: 'fail',
message: 'Not authorized to change quantities',
});
}
// Find the item
const item = order.items.find(
(it) => it.product && it.product._id.toString() === productId,
);
if (!item) {
return res.status(404).json({
status: 'fail',
message: 'Product not found in this order',
});
}
const oldQuantity = item.quantity;
const quantityDiff = quantity - oldQuantity;
// Update product stock
if (quantityDiff !== 0) {
const product = await Product.findById(productId);
if (product) {
// If increasing quantity, check if there's enough stock
if (quantityDiff > 0 && product.stock < quantityDiff) {
return res.status(400).json({
status: 'fail',
message: `Insufficient stock for ${product.nameAr || product.nameEn}. Available: ${product.stock}`,
});
}
product.stock -= quantityDiff;
await product.save();
}
}
// Update item quantity
item.quantity = quantity;
// Recalculate totals
let newSubtotal = 0;
order.items.forEach((it) => {
newSubtotal += it.unitPrice * it.quantity;
});
// Handle discount recalculation if there was a promo code
if (order.promo) {
const promo = await Promo.findById(order.promo);
if (promo) {
const newDiscount = computeDiscountAmount(
promo.type,
promo.value,
newSubtotal,
);
order.discountAmount = newDiscount;
if (promo.type === 'shipping') {
order.totalPrice = newSubtotal;
} else {
order.totalPrice =
Math.max(0, newSubtotal - newDiscount) + order.shippingPrice;
}
} else {
// Promo not found, keep old shipping logic but update total
order.totalPrice =
newSubtotal + order.shippingPrice - order.discountAmount;
}
} else {
order.totalPrice =
newSubtotal + order.shippingPrice - order.discountAmount;
}
await order.save();
// Broadcast update
emitOrderUpdate(order, 'order_quantity_updated');
res.status(200).json({
status: 'success',
data: { order },
});
} catch (err) {
res.status(500).json({ status: 'error', message: err.message });
}
};
exports.addOrderItem = async (req, res) => {
try {
const { id: orderId } = req.params;
const { productId, quantity } = req.body;
if (!quantity || quantity < 1) {
return res.status(400).json({
status: 'fail',
message: 'Quantity must be at least 1',
});
}
const order = await Order.findById(orderId).populate('items.product');
if (!order) {
return res.status(404).json({
status: 'fail',
message: 'Order not found',
});
}
const product = await Product.findById(productId);
if (!product) {
return res.status(404).json({
status: 'fail',
message: 'Product not found',
});
}
if (product.stock < quantity) {
return res.status(400).json({
status: 'fail',
message: `Insufficient stock for ${product.nameAr || product.nameEn}. Available: ${product.stock}`,
});
}
// Authorization check
const isAdmin = req.user.role === 'admin';
const isEmployee =
req.user.role === 'employee' &&
req.user.permissions.includes(PERMISSIONS.MANAGE_ORDERS);
if (!isAdmin && !isEmployee) {
return res.status(403).json({
status: 'fail',
message: 'Not authorized to add items to orders',
});
}
// Check if product already exists in order
const existingItem = order.items.find(
(item) => item.product && item.product._id.toString() === productId,
);
if (existingItem) {
existingItem.quantity += quantity;
existingItem.fulfillmentStatus = 'pending';
} else {
order.items.push({
product: productId,
name: product.nameAr || product.nameEn,
quantity,
unitPrice:
product.salePrice && product.salePrice < product.price
? product.salePrice
: product.price,
});
}
// Deduct stock
product.stock -= quantity;
await product.save();
// Recalculate totals
let newSubtotal = 0;
order.items.forEach((it) => {
newSubtotal += it.unitPrice * it.quantity;
});
if (order.promo) {
const promo = await Promo.findById(order.promo);
if (promo) {
const newDiscount = computeDiscountAmount(
promo.type,
promo.value,
newSubtotal,
);
order.discountAmount = newDiscount;
if (promo.type === 'shipping') {
order.totalPrice = newSubtotal;
} else {
order.totalPrice =
Math.max(0, newSubtotal - newDiscount) + order.shippingPrice;
}
} else {
order.totalPrice =
newSubtotal + order.shippingPrice - order.discountAmount;
}
} else {
order.totalPrice =
newSubtotal + order.shippingPrice - order.discountAmount;
}
await order.save();
// Broadcast update
emitOrderUpdate(order, 'order_item_added');
res.status(200).json({
status: 'success',
data: { order },
});
} catch (err) {
res.status(500).json({ status: 'error', message: err.message });
}
};
exports.removeOrderItem = async (req, res) => {
try {
const { orderId, productId } = req.params;
const order = await Order.findById(orderId);
if (!order) {
return res.status(404).json({
status: 'fail',
message: 'Order not found',
});
}
// Authorization check
const isAdmin = req.user.role === 'admin';
const isEmployee =
req.user.role === 'employee' &&
req.user.permissions.includes(PERMISSIONS.MANAGE_ORDERS);
if (!isAdmin && !isEmployee) {
return res.status(403).json({
status: 'fail',
message: 'Not authorized to remove items from orders',
});
}
// Find the item index
const itemIndex = order.items.findIndex(
(it) => it.product && it.product.toString() === productId,
);
if (itemIndex === -1) {
return res.status(404).json({
status: 'fail',
message: 'Product not found in this order',
});
}
// Prevent removing the last item (order must have at least one item)
if (order.items.length <= 1) {
return res.status(400).json({
status: 'fail',
message: 'Cannot remove the last item. Use "Delete Order" instead.',
});
}
const itemToRemove = order.items[itemIndex];
// Restore stock
const product = await Product.findById(productId);
if (product) {
product.stock += itemToRemove.quantity;
await product.save();
}
// Remove the item
order.items.splice(itemIndex, 1);
// Recalculate totals
let newSubtotal = 0;
order.items.forEach((it) => {
newSubtotal += it.unitPrice * it.quantity;
});
if (order.promo) {
const promo = await Promo.findById(order.promo);
if (promo) {
const newDiscount = computeDiscountAmount(
promo.type,
promo.value,
newSubtotal,
);
order.discountAmount = newDiscount;
if (promo.type === 'shipping') {
order.totalPrice = newSubtotal;
} else {
order.totalPrice =
Math.max(0, newSubtotal - newDiscount) + order.shippingPrice;
}
} else {
order.totalPrice =
newSubtotal + order.shippingPrice - order.discountAmount;
}
} else {
order.totalPrice =
newSubtotal + order.shippingPrice - order.discountAmount;
}
await order.save();
// Broadcast update
emitOrderUpdate(order, 'order_item_removed');
res.status(200).json({
status: 'success',
data: { order },
});
} catch (err) {
res.status(500).json({ status: 'error', message: err.message });
}
};
|