Beispiel #1
0
        public bool Add(AddItemModel item, int userId)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            var itemExists = basketItemRepository.Exists(b => item.ItemId == b.Id);

            if (!itemExists)
            {
                throw new ShoppingBasketException("Unexpected item in the shopping basket!");
            }

            var userItems = new List <IUserBasketItem>();

            for (var i = 0; i < item.Quantity; i++)
            {
                userItems.Add(new UserBasketItem()
                {
                    ItemId = item.ItemId,
                    UserId = userId
                });
            }

            var basketItems = userBasketRepository.AddRange(userItems);

            return(basketItems?.Count() == item.Quantity);
        }
Beispiel #2
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = this.MerchelloServices.ProductService.GetByKey(model.Product.Key);

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = this.MerchelloServices.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);
                this.Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                this.Basket.AddItem(product, product.Name, 1, extendedData);
            }

            this.Basket.Save();

            return(this.RedirectToUmbracoPage(model.BasketPageId));
        }
Beispiel #3
0
        public ActionResult AddItem(string submit, AddItemModel itm)
        {
            try
            {
                UnityContainer UC = new UnityContainer();
                UC.RegisterType <AddStock>();
                UC.RegisterType <AddItem>();

                UC.RegisterType <IAddItem, AddItem>();

                AddStock addstocks = UC.Resolve <AddStock>();

                bool flag = addstocks.addItems(itm);

                if (flag == true)
                {
                    ViewBag.Message = "Item added successfully";
                }

                return(RedirectToAction("AddItemView", "StockReport"));
            }

            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                throw;
            }
        }
Beispiel #4
0
        public async void AddItemOk()
        {
            Item newitem = new Item()
            {
                Name     = "Iphone 7",
                Category = "Телефоны",
                Price    = 45000,
                Code     = "111-222-333-444"
            };

            var unitofworkMock = GetUnitOfWorkMock();

            unitofworkMock.Setup(unit => unit.Items.CreateAsync(It.IsAny <Item>()));

            AdminController adminController = new AdminController(
                GetUserManagerMock <Customer>().Object,
                unitofworkMock.Object);

            AddItemModel model = new AddItemModel()
            {
                Category = newitem.Category,
                Price    = newitem.Price,
                Code     = newitem.Code,
                Name     = newitem.Name
            };

            //Act
            await adminController.AddItem(model);

            //Assert
            unitofworkMock.Verify(u => u.Items.CreateAsync(It.IsAny <Item>()));
        }
        public async Task <IActionResult> Item(string id, AddItemModel addItem)
        {
            _Logger.LogInformation($"starting to add item to cart {id}");

            Activity activity = new Activity("cart.put.item");

            activity.Start();

            if (string.IsNullOrEmpty(id))
            {
                id = _IdGenerator.New();
            }

            string actorType = "ShoppingCartActor";

            ActorId actorId = new ActorId(id);

            IShoppingCart cart = ActorProxy.Create <IShoppingCart>(actorId, actorType);

            await cart.Add(addItem.Id, addItem.Name, addItem.Quantity);

            activity.Stop();

            return(Ok());
        }
Beispiel #6
0
        public void AddItems()
        {
            userBasketRepo.Setup(x => x.AddRange(It.IsAny <List <IUserBasketItem> >()))
            .Returns(() =>
            {
                return(new List <IUserBasketItem>
                {
                    new UserBasketItem
                    {
                        ItemId = 1,
                        UserId = USER_ID
                    }
                });
            });

            basketItemRepo.Setup(x => x.Exists(It.IsAny <Func <IBasketItem, bool> >()))
            .Returns(true);

            var service = new ShoppingBasketService(userBasketRepo.Object, basketItemRepo.Object, discountRepo.Object);

            var newItem = new AddItemModel(1, 1);

            var hasAddedItem = service.Add(newItem, USER_ID);

            Assert.IsTrue(hasAddedItem);
        }
Beispiel #7
0
        public ActionResult Add(AddItemModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                var item = new Item
                {
                    Name       = model.Description,
                    Cost       = model.Cost.Value,
                    UserId     = CurrentUserId,
                    Date       = DateTime.UtcNow,
                    CategoryId = model.CategoryId,
                    Type       = model.Type
                };

                moneyRepository.AddItem(item);

                return(Ok());
            }
            catch
            {
                ModelState.AddModelError("", "Hiba történt. Bocsi");
                return(new StatusCodeResult(500));
            }
        }
        public ActionResult GoCheckout(ShoppingCart cart)
        {
            HandleCart(cart);
            BizInfo      bi  = BizInfoRepository.GetBizInfoById(cart.BizId);
            AddItemModel aim = new AddItemModel();

            SharedShoppingCart ssc = new SharedShoppingCart();

            if (string.IsNullOrEmpty(cart.CartKey) == false)
            {
                ssc = GetGroupShoppingCart(cart.CartKey);
            }
            decimal partysubtotal = ssc.PartySubTotal();

            ViewBag.okcheckout = "show";
            bool isBoss = (string.IsNullOrEmpty(cart.PersonName) == false && cart.PersonName == GroupCart.GroupCarts[cart.CartKey].PartyBossName);

            if (!isBoss || GroupCart.GroupCarts[cart.CartKey].PartyTotalItems == 0 || (GroupCart.GroupCarts[cart.CartKey].PartyOrderMinimum() > GroupCart.GroupCarts[cart.CartKey].PartySubTotal() && GroupCart.GroupCarts[cart.CartKey].IsPartyDelivery) || (GroupCart.GroupCarts[cart.CartKey].PartyCart[cart.BossName].IsBizDelivery == false && GroupCart.GroupCarts[cart.CartKey].IsPartyDelivery))
            {
                ViewBag.okcheckout = "off";
            }
            ssc.IsSharedCartLocked = true;
            aim.SharedCart         = ssc;
            aim.Cart = cart;
            return(PartialView(aim));
        }
Beispiel #9
0
        public ActionResult EditItem(int id = 0)
        {
            AddItemModel model = new AddItemModel();

            if (id > 0)
            {
                var data = (from p in db.tblItems where p.ItemId == id select p).SingleOrDefault();

                model.ItemCategoryId  = data.CategoryId;
                model.DepartmentId    = data.DepartmentId;
                model.Description     = data.Description;
                model.ItemCode        = data.ItemCode;
                model.ItemId          = data.ItemId;
                model.ItemImage       = data.ItemImage;
                model.Name            = data.Name;
                model.lstofCategory   = obj.GetListofcategory();
                model.lstofDepartment = obj.GetListofDepartment();
                model.Active          = data.Active;
                return(View(model));
            }
            else
            {
                //IEnumerable<SelectListItem> CategoryList = (from m in db.tblCategories where m.Active == true select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.Name, Value = m.CategoryId.ToString() });
                //ViewBag.categoryLIsts = new SelectList(CategoryList, "Value", "Text", "CategoryId");
                //ViewBag.lstofCategory = new AddItemRepository().GetListofcategory();
                model.lstofCategory   = obj.GetListofcategory();
                model.lstofDepartment = obj.GetListofDepartment();
                return(View(model));
            }
        }
Beispiel #10
0
 public ActionResult AddItem(AddItemModel addItemModel)
 {
     if (!ModelState.IsValid)
     {
         return(View(addItemModel));
     }
     return(View(addItemModel));
 }
Beispiel #11
0
        public async Task <IActionResult> AddItem([FromBody] AddItemModel model)
        {
            // TODO: get product price and name from api
            var useCase = new AddItemToBasket(model.BasketId, model.ProductId, model.ProductName, model.Price, model.Quantity);
            var cmd     = new Command <AddItemToBasket>(useCase);

            var basket = await _commandHandler.Execute <PendingBasket>(cmd);

            return(Ok(BasketModel.FromAggregateRoot(basket)));
        }
        public ActionResult RemoveFromCart(ShoppingCart cart, string itemId)
        {
            HandleCart(cart);

            AddItemModel model = new AddItemModel();

            ViewBag.cando = string.IsNullOrEmpty(cart.CartKey) ? "n" : "y";
            model.BizInfo = BizInfoRepository.GetBizInfoById(cart.BizId);

            if (model.BizInfo == null)
            {
                return(Redirect("~/Home"));
            }
            SharedShoppingCart ssc = new SharedShoppingCart();

            if (string.IsNullOrEmpty(cart.CartKey))
            {
                model.SharedCart      = ssc;
                model.Cart            = cart;
                ViewBag.canremoveitem = "n";
                return(PartialView(model));
            }
            ssc = GetGroupShoppingCart(cart.CartKey);
            bool bl = (string.IsNullOrEmpty(itemId) == false && !ssc.IsSharedCartLocked);

            if (bl)
            {
                cart.DeleteProduct(itemId);
            }

            ViewBag.canremoveitem  = bl?"y":"n";
            ViewBag.itemid         = itemId;
            ViewBag.subtotal       = cart.SubTotal().ToString("N2");
            ViewBag.tax            = GroupCart.GroupCarts[cart.CartKey].PartyTax().ToString("N2");
            ViewBag.globalsubtotal = GroupCart.GroupCarts[cart.CartKey].PartySubTotal().ToString("N2");
            ViewBag.drivertip      = GroupCart.GroupCarts[cart.CartKey].PartyDriverTip().ToString("N2");
            ViewBag.globaltotal    = GroupCart.GroupCarts[cart.CartKey].PartyTotal().ToString("N2");

            string btnShow = "show";
            bool   isBoss  = (string.IsNullOrEmpty(cart.PersonName) == false && cart.PersonName == GroupCart.GroupCarts[cart.CartKey].PartyBossName);

            if (isBoss)
            {
                btnShow = "off";
            }
            else if (GroupCart.GroupCarts[cart.CartKey].PartyTotalItems == 0 || (GroupCart.GroupCarts[cart.CartKey].PartyOrderMinimum() > GroupCart.GroupCarts[cart.CartKey].PartySubTotal() && GroupCart.GroupCarts[cart.CartKey].IsPartyDelivery) || (GroupCart.GroupCarts[cart.CartKey].PartyCart[cart.BossName].IsBizDelivery == false && GroupCart.GroupCarts[cart.CartKey].IsPartyDelivery))
            {
                btnShow = "off";
            }
            ViewBag.btnshow  = btnShow;
            model.SharedCart = ssc;
            model.Cart       = cart;
            return(PartialView(model));
        }
Beispiel #13
0
        public void AddItemsThrowsShoppingBasketException()
        {
            basketItemRepo.Setup(b => b.Exists(It.IsAny <Func <IBasketItem, bool> >()))
            .Returns(false);

            var service = new ShoppingBasketService(userBasketRepo.Object, basketItemRepo.Object, discountRepo.Object);

            var newItem = new AddItemModel(1, 1);

            Assert.Throws <ShoppingBasketException>(delegate { service.Add(newItem, USER_ID); });
        }
        public ActionResult AddToSharedCart(int id, ShoppingCart cart)
        {
            AddItemModel model = new AddItemModel();

            ViewBag.canAdd  = string.IsNullOrEmpty(cart.CartKey) ? "n" : "y";
            model.Product   = ProductRepository.GetProductById(id);
            model.ProductID = id;
            List <ProductSize> lps = ProductSizeRepository.GetProductSizesByProductId(true, id);

            model.SizeAssistances = new List <SelectListItem>();
            foreach (var s in lps)
            {
                model.SizeAssistances.Add(new SelectListItem {
                    Text = s.Title + string.Format(" {0}{1}", s.Size > 0 ? " " + s.Size + "\"" : "", " ($" + s.Price.ToString("N2") + ")"), Value = s.ProductSizeId.ToString()
                });
            }
            List <ProductTopping> lpt = new List <ProductTopping>();

            lpt = ProductToppingRepository.GetProductToppingsByProductId(true, id);
            foreach (var t in lpt)
            {
                model.ToppingAssistances.Add(new CheckBoxViewModel {
                    BoxName = t.ToppingTitle, BoxPrice = t.ExtraToppingPrice, Checked = false
                });
            }
            if (model.Product.MaxNumOfFreeTopping > 0)
            {
                foreach (var t in lpt)
                {
                    model.FreeToppingAssistances.Add(new CheckBoxViewModel {
                        BoxName = t.ToppingTitle, BoxPrice = t.ExtraToppingPrice, Checked = false
                    });
                }
            }
            List <AddSide> las = new List <AddSide>();

            las = model.Product.AddSides.Where(e => e.Active == true).ToList();
            foreach (var a in las)
            {
                model.AddSideAssistances.Add(new AddSideCheckBoxModel {
                    BoxName = a.Title, BoxPrice = a.Price, BoxBizPrice = a.BizPrice, Checked = false
                });
            }
            SharedShoppingCart ssc = new SharedShoppingCart();

            if (string.IsNullOrEmpty(cart.CartKey) == false)
            {
                ssc = GetGroupShoppingCart(cart.CartKey);
            }
            model.SharedCart = ssc;
            model.Cart       = cart;
            return(PartialView(model));
        }
Beispiel #15
0
        public ActionResult RenderAddToCart(ProductDisplay product)
        {
            var contentId = UmbracoContext.PageId != null ? UmbracoContext.PageId.Value : 0;

            var model = new AddItemModel()
            {
                ProductKey = product.Key,
                ContentId  = contentId
            };

            return(PartialView("RosettaAddToCart", model));
        }
Beispiel #16
0
        public bool addItems(AddItemModel itm)
        {
            try
            {
                return(_additems.addItem(itm));
            }

            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                throw;
            }
        }
Beispiel #17
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            // NEW IN 1.9.1
            // We've added some data modifiers that can handle such things as including taxes in product
            // pricing.  The data modifiers can either get executed when the item is added to the basket or
            // as a result from a MerchelloHelper query - you just don't want them to execute twice.

            // Calls directly to the ProductService are not modified
            // var product = this.MerchelloServices.ProductService.GetByKey(model.Product.Key);

            // Calls to using the MerchelloHelper WILL be modified
            // var merchello = new MerchelloHelper();
            //
            // if you want to do this you should tell the basket not to modify the data again when adding the item
            //this.Basket.EnableDataModifiers = false;

            // In this case we want to get the product without any data modification
            var merchello = new MerchelloHelper(false);

            var product = merchello.Query.Product.GetByKey(model.Product.Key);

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                // NEW in 1.9.1
                // ProductDisplay and ProductVariantDisplay classes can be added directly to the Basket
                // so you don't have to query the service.
                var variant = product.GetProductVariantDisplayWithAttributes(model.OptionChoices);
                this.Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                this.Basket.AddItem(product, product.Name, 1, extendedData);
            }

            this.Basket.Save();

            return(this.RedirectToUmbracoPage(model.BasketPageId));
        }
Beispiel #18
0
        public ActionResult RenderAddToBasket(ProductModel model)
        {
            var addItemModel = new AddItemModel()
            {
                Product        = model.ProductData,
                ContentId      = model.Id,
                BasketPageId   = BazaarContentHelper.GetBasketContent().Id,
                ShowWishList   = model.ShowWishList,
                WishListPageId = BazaarContentHelper.GetWishListContent().Id,
                Currency       = model.Currency
            };

            return(RenderAddItem(addItemModel));
        }
Beispiel #19
0
        public ActionResult RenderAddToBasket(ProductModel model)
        {
            var addItemModel = new AddItemModel()
            {
                Product        = model.ProductData,
                ContentId      = model.Id,
                BasketPageId   = model.BasketPage.Id,
                ShowWishList   = model.ShowWishList,
                WishListPageId = model.WishListPage.Id,
                Currency       = model.Currency
            };

            return(this.PartialView(model.ThemePartialViewPath("AddToCart"), addItemModel));
        }
Beispiel #20
0
        public async Task <IActionResult> AddToNextAvailable(AddItemModel model)
        {
            FishTank tank = await NextAvailableFishTankWithCapacity(model.Decoration.Size);

            if (tank == null)
            {
                return(BadRequest("No Tank found that can hold this fish, please add a new tank"));
            }

            tank.AddItem(model.Decoration);

            await _context.SaveChangesAsync();

            return(Ok(tank));
        }
Beispiel #21
0
        public async Task <IActionResult> AddItem(AddItemModel item)
        {
            if (ModelState.IsValid)
            {
                Stream stream = new MemoryStream();
                await item.Image.CopyToAsync(stream);

                string imagePath = await _saveFile.SaveImage(_env.WebRootPath, "Images", item.Image.FileName, stream);

                await _itemRepository.AddAsync(new Item(item.Title, item.Description, imagePath, item.Price, true));

                return(RedirectToAction("Index", "Home"));
            }
            return(View());
        }
Beispiel #22
0
        public async Task <IActionResult> Add(AddItemModel model)
        {
            if (ModelState.IsValid)
            {
                Item item = new Item {
                    name = model.name, description = model.description, type_item = model.type_item, is_avalible = model.is_avalible, cost = model.cost, image = model.image
                };
                await _context.Items.AddAsync(item);

                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Home"));
            }
            return(View(model));
        }
Beispiel #23
0
        public async Task <IActionResult> AddItem([FromBody] AddItemModel model)
        {
            try
            {
                model.UsesrId = CurrentUserId;

                var result = await itemLib.AddItemAsync(model);

                return(CustomResult(result));
            }
            catch (System.Exception exp)
            {
                return(CustomError(exp));
            }
        }
Beispiel #24
0
        public async Task <ItemModel> AddItemAsync(AddItemModel model)
        {
            var entity = new Item
            {
                CreatedDate = DateTime.Now,
                ListId      = model.ListId,
                Name        = model.Name,
                UserId      = model.UsesrId
            };

            await itemRepo.AddAsync(entity);

            await unitOfWork.CommitAsync();

            return(ConvertItemToItemModel(entity));
        }
        public IActionResult Add([FromBody] AddItemModel model)
        {
            var currentUserId = int.Parse(User.Identity.Name);
            var item          = _mapper.Map <ToDoItem>(model);

            item.UserId = currentUserId;
            try
            {
                _ToDoItemService.Add(item);
                return(Ok());
            }
            catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Beispiel #26
0
        public ActionResult AddItem(AddItemModel model)
        {
            tblItem tb        = new tblItem();
            var     itemcheck = (from p in db.tblItems where p.Name == model.Name && p.Active == true && p.CategoryId == model.ItemCategoryId select p).SingleOrDefault();

            if (itemcheck == null)
            {
                try
                {
                    if (model.ItemId > 0)
                    {
                        tb = (from p in db.tblItems where p.ItemId == model.ItemId select p).SingleOrDefault();
                    }
                    tb.CategoryId   = model.ItemCategoryId;
                    tb.Description  = model.Description;
                    tb.ItemCode     = model.ItemCode;
                    tb.ItemImage    = Image();
                    tb.Name         = model.Name;
                    tb.Active       = model.Active;
                    tb.DepartmentId = model.DepartmentId;
                    if (model.ItemId > 0)
                    {
                        db.SaveChanges();
                        TempData["item"] = "Edit Successfully..!";
                        return(RedirectToAction("ItemDetails"));
                    }
                    else
                    {
                        db.tblItems.Add(tb);
                        db.SaveChanges();
                        TempData["item"] = "Record Insert Successfully..!";
                        return(RedirectToAction("ItemDetails"));
                    }
                }
                catch (Exception ex)
                {
                    TempData["item"] = ex.Message;
                    return(RedirectToAction("ItemDetails"));
                }
            }
            else
            {
                TempData["itemCreate"] = "This Item is already exist in this Category..";
                return(RedirectToAction("AddItem"));
            }
        }
Beispiel #27
0
        public async Task <ActionResult> Add([FromBody] AddItemModel addItemModel)
        {
            if (ModelState.IsValid)
            {
                var itemDto = new ItemDto
                {
                    Name         = addItemModel.Name,
                    ParentItemId = addItemModel.ParentItemId
                };

                await _itemService.Add(itemDto, GetUserId());

                return(Ok());
            }

            return(BadRequest());
        }
        public ActionResult AddToCart(int id)
        {
            AddItemModel model = new AddItemModel();

            model.Product   = ProductRepository.GetProductById(id);
            model.ProductID = id;
            List <ProductSize> lps = ProductSizeRepository.GetProductSizesByProductId(true, id);

            model.SizeAssistances = new List <SelectListItem>();
            foreach (var s in lps)
            {
                model.SizeAssistances.Add(new SelectListItem {
                    Text = s.Title + string.Format(" {0}{1}", s.Size > 0 ? " " + s.Size + "\"" : "", " ($" + s.Price.ToString("N2") + ")"), Value = s.ProductSizeId.ToString()
                });
            }
            List <ProductTopping> lpt = new List <ProductTopping>();

            lpt = ProductToppingRepository.GetProductToppingsByProductId(true, id);
            foreach (var t in lpt)
            {
                model.ToppingAssistances.Add(new CheckBoxViewModel {
                    BoxName = t.ToppingTitle, BoxPrice = t.ExtraToppingPrice, BoxIncrementValue = t.Increment, Checked = false
                });
            }
            if (model.Product.MaxNumOfFreeTopping > 0)
            {
                foreach (var t in lpt)
                {
                    model.FreeToppingAssistances.Add(new CheckBoxViewModel {
                        BoxName = t.ToppingTitle, BoxPrice = t.ExtraToppingPrice, Checked = false
                    });
                }
            }
            List <AddSide> las = new List <AddSide>();

            las = model.Product.AddSides.Where(e => e.Active == true).ToList();
            foreach (var a in las)
            {
                model.AddSideAssistances.Add(new AddSideCheckBoxModel {
                    BoxName = a.Title, BoxPrice = a.Price, BoxBizPrice = a.BizPrice, Checked = false
                });
            }
            return(PartialView(model));
        }
        public async Task <ActionResult <OrderModel> > AddItemToOrder(int orderId, AddItemModel addItemModel)
        {
            try
            {
                _logger.LogInformation("{Username} has started adding {Amount} items with id {ItemId} to order with id {OrderId}",
                                       addItemModel.Username, addItemModel.Amount, addItemModel.ItemId, orderId);

                var order = await _orderRepository.AddItemToOrderAsync(
                    orderId,
                    addItemModel.ItemId,
                    addItemModel.Amount,
                    addItemModel.Username);

                var location = _linkGenerator.GetPathByAction(
                    "GetOrderById",
                    "Orders",
                    new { orderId = order.OrderId });

                var reserveItemsDto = new ReserveItemsDto(order, addItemModel);
                _rabbitManager.Publish(reserveItemsDto, "OrderService_ReserveItemsExchange", ExchangeType.Direct, "ReserveItems");

                if (orderId == 0)
                {
                    _logger.LogInformation("{Username} has successfuly added {Amount} items with id {ItemId} to a newly created order with id {OrderId}",
                                           addItemModel.Username, addItemModel.Amount, addItemModel.ItemId, order.OrderId);

                    return(Created(location, _mapper.Map <OrderModel>(order)));
                }
                else
                {
                    _logger.LogInformation("{Username} has successfuly added {Amount} items with id {ItemId} to an existing order with id {OrderId}",
                                           addItemModel.Username, addItemModel.Amount, addItemModel.ItemId, order.OrderId);

                    return(_mapper.Map <OrderModel>(order));
                }
            }
            catch (Exception e)
            {
                _logger.LogInformation("{Username} has failed to add {Amount} items with id {ItemId} to an order with id {OrderId}",
                                       addItemModel.Username, addItemModel.Amount, addItemModel.ItemId, orderId);

                return(BadRequest(e.Message));
            }
        }
Beispiel #30
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = Services.ProductService.GetByKey(model.ProductKey);

            // check if content has sample shipper property - isOverWeight
            // if yes, set basket item extended property
            var content = Umbraco.Content(model.ContentId.ToString(CultureInfo.InvariantCulture));

            if (content.HasProperty("IsOverweight") && content.HasValue("IsOverweight"))
            {
                extendedData.SetValue("IsOverweight", "true");
            }
            else
            {
                extendedData.SetValue("IsOverweight", "false");
            }

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = Services.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);
                Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                Basket.AddItem(product, product.Name, 1, extendedData);
            }

            Basket.Save();

            return(RedirectToUmbracoPage(GetContentIdByContentName(BasketPage)));
        }