Advertisement
Shad3yz

Untitled

Jul 11th, 2020
1,288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const makeAnOrder = async (
  2.   userId,
  3.   shopId,
  4.   items,
  5.   notes,
  6.   payment_method,
  7.   address,
  8.   name,
  9.   phoneNumber,
  10.   deliveryArea
  11. ) => {
  12.   // VALIDATIONS
  13.  
  14.   if (!userId && !(name && phoneNumber))
  15.     // If user id not sent AND name and phoneNumber not sent
  16.     throw new AppError('Missing parameters in the request', 400);
  17.  
  18.   if (!shopId || !address || !deliveryArea)
  19.     throw new AppError('Missing parameters in the request', 400);
  20.  
  21.   if (!payment_method || !['Visa', 'Cash'].includes(payment_method))
  22.     throw new AppError('Missing payment method or invalid payment method');
  23.  
  24.   if (!items || !Array.isArray(items))
  25.     throw new AppError('Missing items argument or it is not an array');
  26.  
  27.   // CHECK USER
  28.  
  29.   if (userId) {
  30.     const user = await User.findById(userId);
  31.     if (!user) throw new AppError('Invalid user id', 400);
  32.  
  33.     name = user.name;
  34.     phoneNumber = user.phoneNumber;
  35.   }
  36.  
  37.   // GET BRANCH ID
  38.  
  39.   const deliveryAreas = (
  40.     await Shop.findById(shopId).select('delivery_areas')
  41.   ).toObject().delivery_areas;
  42.  
  43.   let deliveryPrice = -1;
  44.  
  45.   for (let el of deliveryAreas) {
  46.     if (el.area === deliveryArea) {
  47.       if (deliveryPrice === -1 || el.price < deliveryPrice) {
  48.         branchId = el.branch;
  49.         deliveryPrice = el.price;
  50.         break;
  51.       }
  52.     }
  53.   }
  54.  
  55.   if (!branchId)
  56.     throw new AppError('Delivery area not found in the given shop', 404);
  57.  
  58.   // HANDLE ITEMS
  59.  
  60.   const itemsIds = items.map((el) => mongoose.Types.ObjectId(el.id));
  61.  
  62.   let itemsObjects = (
  63.     await Item.find({ _id: { $in: itemsIds }, active: true }).select(
  64.       '_id addons price'
  65.     )
  66.   ).map((el) => el.toObject());
  67.  
  68.   if (!itemsObjects || itemsObjects.length === 0)
  69.     throw new AppError('The requested items do not exist', 400);
  70.  
  71.   itemsObjects.forEach((item) => {
  72.     item.addons.forEach((addon) => {
  73.       addon.options = convertArrayToObject(addon.options, '_id');
  74.     });
  75.     item.addons = convertArrayToObject(item.addons, '_id');
  76.   });
  77.  
  78.   itemsObjects = convertArrayToObject(itemsObjects, '_id');
  79.  
  80.   let totalPrice = 0;
  81.  
  82.   itemsToBeInserted = [];
  83.  
  84.   items.forEach((item) => {
  85.     const itemToBeInserted = {
  86.       item: item.id,
  87.       addons: [],
  88.       qty: item.qty,
  89.     };
  90.  
  91.     totalPrice += itemsObjects[item.id].price * item.qty;
  92.  
  93.     if (item.addons && Array.isArray(item.addons)) {
  94.       item.addons.forEach((addon) => {
  95.         if (!itemsObjects[item.id])
  96.           throw new AppError("The shop doesn't have this addon", 400);
  97.  
  98.         const originalAddon = itemsObjects[item.id].addons[addon.id];
  99.         if (!originalAddon)
  100.           throw new AppError('Addon not found for an item', 400);
  101.  
  102.         if (!addon.options || addon.options.length === 0)
  103.           throw new AppError('A requested item does not have any addons', 400);
  104.  
  105.         addon.options.forEach((option) => {
  106.           if (!originalAddon.options[option])
  107.             throw new AppError(
  108.               'A requested option does not belong to its addon',
  109.               400
  110.             );
  111.         });
  112.  
  113.         if (originalAddon.multiple === false) {
  114.           if (addon.options.length > 1)
  115.             throw new AppError(
  116.               'A requested addon can only contain one option but you requested more than one option'
  117.             );
  118.         }
  119.  
  120.         const addonToBeInserted = {
  121.           name: originalAddon.name,
  122.           multiple: originalAddon.multiple,
  123.           options: [],
  124.         };
  125.  
  126.         addon.options.forEach((option) => {
  127.           const originalOption = originalAddon.options[option];
  128.  
  129.           totalPrice += originalOption.price * item.qty;
  130.  
  131.           addonToBeInserted.options.push({
  132.             name: originalOption.name,
  133.             price: originalOption.price,
  134.           });
  135.         });
  136.  
  137.         itemToBeInserted.addons.push(addonToBeInserted);
  138.       });
  139.     } else {
  140.       throw new AppError('Invalid addons parameter in an item', 400);
  141.     }
  142.  
  143.     itemsToBeInserted.push(itemToBeInserted);
  144.   });
  145.  
  146.   totalPrice += deliveryPrice;
  147.  
  148.   const order = await Order.create({
  149.     shop: shopId,
  150.     ...(userId && { user: userId }),
  151.     branch: branchId,
  152.     items: itemsToBeInserted,
  153.     notes: notes,
  154.     payment_method: payment_method,
  155.     user_address: address,
  156.     total_price: totalPrice,
  157.     name: name,
  158.     phoneNumber: phoneNumber,
  159.     delivery_area: deliveryArea,
  160.   });
  161.  
  162.   order.__v = undefined;
  163.  
  164.   return order;
  165. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement