/// <summary>
        /// Found maximum discount for iteration
        /// </summary>
        /// <param name="campaigns">Applied Campaigns </param>
        /// <param name="cart"></param>
        /// <returns>Best discounted campaign returns</returns>
        public Campaign Iterate(IEnumerable <Campaign> campaigns, Models.ShoppingCart cart)
        {
            var minimumTotalPrice = double.MaxValue;
            // Campaign ordered by discount type. If the amounts of the campaigns in Amount Discount type are the same as Rate Discount, the rate discount must be done first
            var orderedCampaigns = campaigns.OrderByDescending(en => en.DiscountType).ToList();
            // Best Discounted Campaign  initialized with first campaign
            Campaign bestDiscountedCampaign = orderedCampaigns.First();

            // Cart Products
            foreach (var campaign in orderedCampaigns)
            {
                CalculateCampaignExpectedDiscountValues(cart, campaign);
                // Expected Total price checked for best discount
                if (!(minimumTotalPrice > cart.ProductsExpectedDiscountedTotalPrice))
                {
                    continue;
                }

                minimumTotalPrice      = cart.ProductsExpectedDiscountedTotalPrice;
                bestDiscountedCampaign = campaign;
            }

            // Best discounted campaign expected values calculating
            CalculateCampaignExpectedDiscountValues(cart, bestDiscountedCampaign);
            // Expected Discount Applied for products
            cart.ApplyExpectedDiscounts();
            return(bestDiscountedCampaign);
        }
        public async Task <IActionResult> Create([Bind("FirstName,LastName,City,PostalCode,Country,Phone")]
                                                 Order order)
        {
            ApplicationUser user = await _userManager.GetUserAsync(User);

            if (ModelState.IsValid)
            {
                Models.ShoppingCart cart    = Models.ShoppingCart.GetCart(this.HttpContext);
                List <CartItem>     items   = cart.GetCartItems(_context);
                List <OrderDetail>  details = new List <OrderDetail>();
                foreach (CartItem item in items)
                {
                    OrderDetail detail = CreateOrderDetailForThisItem(item);
                    detail.Order = order;
                    details.Add(detail);
                    _context.Add(detail);
                }

                order.User         = user;
                order.OrderDate    = DateTime.Today;
                order.Total        = Models.ShoppingCart.GetCart(this.HttpContext).GetTotal(_context);
                order.GST          = order.Total * (decimal)0.15;
                order.GrandTotal   = order.Total + order.GST;
                order.OrderDetails = details;

                _context.SaveChanges();

                return(RedirectToAction("Purchased",
                                        new RouteValueDictionary(new { action = "Purchased", id = order.OrderID })));
            }

            return(View(order));
        }
        private void Button_Clicked(object sender, EventArgs e)
        {
            using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
            {
                conn.CreateTable <ShoppingCart>();



                var cart =
                    conn.Table <ShoppingCart>().Where(i => i.UserId == App.user.Id).ToList();



                var productInCart =
                    conn.Table <ShoppingCart>().Where(p => p.ProductId == Product.Id).Where(i => i.UserId == App.user.Id).ToList();


                try
                {
                    if (productInCart.Count == 0)
                    {
                        Models.ShoppingCart carts = new Models.ShoppingCart()
                        {
                            ProductId = Product.Id,
                            Name      = Product.Name,
                            Price     = Product.Price,
                            UserId    = App.user.Id,
                            ImageUrl  = Product.ImageUrl,
                            Quantity  = int.Parse(productQty.Value.ToString())
                        };
                        conn.Insert(carts);
                    }
                    else
                    {
                        var cartTable = conn.Table <ShoppingCart>().ToList();

                        var shoppingCartId = (from p in cartTable where p.UserId == App.user.Id where p.ProductId == Product.Id select p.Id).Distinct().ToList();


                        Models.ShoppingCart carts = new Models.ShoppingCart()
                        {
                            Id        = shoppingCartId[0],
                            ProductId = Product.Id,
                            Name      = Product.Name,
                            Price     = Product.Price,
                            UserId    = App.user.Id,
                            ImageUrl  = Product.ImageUrl,
                            Quantity  = int.Parse(productQty.Value.ToString())
                        };

                        conn.Update(carts);
                    }
                }
                catch
                {
                }
            }

            Navigation.PushAsync(new Cart.CartPage());
        }
        /// <summary>
        /// finding campaign products in cart and Campaign expected discount calculation for this products
        /// </summary>
        /// <param name="cart"></param>
        /// <param name="campaign"></param>
        private void CalculateCampaignExpectedDiscountValues(Models.ShoppingCart cart, Campaign campaign)
        {
            //Clear Expected values for clean calculation
            cart.ClearExpectedValues();
            var appliedCampaignProducts =
                cart.GetItems().Where(en => en.Product.Category.Title == campaign.Category.Title).ToList();

            CalculateCampaignExpectedDiscountValues(appliedCampaignProducts, campaign);
        }
        public async Task <IActionResult> AddItemsToCart(int userId, [FromBody] int[] productIds)
        {
            if (userId <= 0)
            {
                return(BadRequest());
            }

            var shoppingCart = await _cartContext.ShoppingCarts
                               .Include(b => b.Items)
                               .SingleOrDefaultAsync(ci => ci.UserId == userId);

            if (shoppingCart == null)
            {
                shoppingCart = new Models.ShoppingCart()
                {
                    UserId = userId
                };

                _cartContext.ShoppingCarts.Add(shoppingCart);

                var createCartResult = await _cartContext.SaveChangesAsync();

                if (createCartResult > 0)
                {
                    _eventStore.Raise("Создана корзина", shoppingCart);
                }
            }

            var shoppingCartItems = await _productCatalogueClient.GetShoppingCartItems(productIds).ConfigureAwait(false);


            if (shoppingCartItems.Count() > 0)
            {
                foreach (var item in shoppingCartItems)
                {
                    var cartItem = _cartContext.ShoppingCartItems.FirstOrDefault(i => i.Id == item.Id);

                    if (cartItem == null)
                    {
                        item.ShoppingCartId = shoppingCart.Id;
                        _cartContext.ShoppingCartItems.Add(item);
                    }
                }
            }

            var addItemResult = await _cartContext.SaveChangesAsync();

            if (addItemResult > 0)
            {
                _eventStore.Raise("Добавлен товар", shoppingCart);
            }

            return(Ok(shoppingCart));
        }
Exemple #6
0
        public string AddShoppingCart([FromBody] Models.ShoppingCart value)
        {
            if (value == null)
            {
                return("Objeto invalido");
            }

            db.ShoppingCarts.Add(value);
            db.SaveChanges();
            return("OK");
        }
        public ActionResult AddToCart(string TicketId, string Quantity, string Price)
        {
            int TickId = Convert.ToInt32(TicketId);

            int    qty   = Convert.ToInt32(Quantity);
            double price = Convert.ToDouble(Price);

            using (TicketDomContext context = new TicketDomContext())
            {
                Tickets ticket = context.Tickets.FirstOrDefault(x => x.Id == TickId);
                if (System.Web.HttpContext.Current.Session["cartId"] == null)
                {
                    ShoppingCart newCart = new Models.ShoppingCart();
                    context.ShoppingCart.Add(newCart);
                    context.SaveChanges();
                    System.Web.HttpContext.Current.Session["cartId"] = newCart.Id;
                }


                int          cartId    = Convert.ToInt32(System.Web.HttpContext.Current.Session["cartId"]);
                ShoppingCart cart      = context.ShoppingCart.FirstOrDefault(x => x.Id == cartId);
                bool         newTicket = true;

                if (cart.Items.Count() > 0)
                {
                    foreach (CartItem item in cart.Items)
                    {
                        if (item.TicketId == TickId)
                        {
                            newTicket = false;
                            int qt = item.Quantity + qty;
                            item.Quantity = qt;
                            context.SaveChanges();
                        }
                    }
                }
                if (newTicket == true)
                {
                    CartItem newItem = new CartItem();
                    newItem.TicketId    = TickId;
                    newItem.Quantity    = qty;
                    newItem.TicketPrice = price;
                    newItem.CartId      = cart.Id;
                    newItem.Ticket      = ticket;
                    newItem.Description = ticket.Title + " at " + ticket.Venue + " located in " + ticket.City + ", " + ticket.State + " on " + ticket.Date.ToString("M/d/yyyy hh:mm tt");
                    cart.Items.Add(newItem);
                    context.CartItem.Add(newItem);
                    context.SaveChanges();
                }
            }
            return(RedirectToAction("Shop"));
        }
        public IActionResult CheckOut()
        {
            Models.ShoppingCart cart = new Models.ShoppingCart();
            string json        = HttpContext.Session.GetString("shoppingCart");
            var    productList = JsonConvert.DeserializeObject <Models.ShoppingCart>(json);

            Dictionary <string, int> newDictionary = new Dictionary <string, int>();
            var productCount = 0;
            Dictionary <int, int> dictionaryCounts = new Dictionary <int, int>();
            Sepet sepet = new Sepet();

            foreach (int i in productList.ProductsIdList)
            {
                int count;
                if (dictionaryCounts.TryGetValue(i, out count))
                {
                    dictionaryCounts[i] = count + 1;
                    productCount++;
                    newDictionary[_products.GetTitle(i)] = count + 1;
                }
                else
                {
                    dictionaryCounts.Add(i, 1);
                    var productId = productList.ProductsIdList[0];
                    newDictionary.Add(_products.GetTitle(i), 1);
                }
            }

            foreach (var i in dictionaryCounts)
            {
                Product product = new Product();
                product = _products.GetProduct(i.Key);
                SepetDetay sptDetay = new SepetDetay();
                sptDetay.product           = new ProductDetailModel();
                sptDetay.product.ProductId = product.Id;
                sptDetay.product.Title     = product.Title;
                sptDetay.product.Price     = product.Price;
                sptDetay.Quantity          = i.Value;
                sepet.sepetDetayList.Add(sptDetay);
            }
            return(View(sepet));
        }
        public IActionResult AddToCart(AddToCartBindingModel model)
        {
            Models.ShoppingCart cart;
            if (HttpContext.Session.Keys.Contains("shoppingCart"))
            {
                string json = HttpContext.Session.GetString("shoppingCart");
                cart = JsonConvert.DeserializeObject <Models.ShoppingCart>(json);
            }
            else
            {
                cart = new Models.ShoppingCart();
            }

            for (int i = 0; i < model.Quantity; i++)
            {
                cart.ProductsIdList.Add(model.ProductId);
            }
            HttpContext.Session.SetString("shoppingCart", JsonConvert.SerializeObject(cart));

            return(RedirectToAction("Index"));
        }
        public async Task <bool> AddToCart(string productId, string deviceId, string userId)
        {
            var cart = await GetCurrentCartForUser(deviceId, userId);

            if (cart == null)
            {
                cart            = new Models.ShoppingCart();
                cart.ClientGuid = deviceId;

                if (userId != null)
                {
                    try
                    {
                        cart.User = _context.Users.SingleOrDefault(u => u.Id == Int32.Parse(userId));
                    }
                    catch (Exception e)
                    {
                        return(false);
                    }
                }

                _context.ShoppingCarts.Add(cart);
            }

            var item = _context.ProductShoppingCarts.SingleOrDefault(
                pc => pc.ShoppingCartId == cart.ShoppingCartId && pc.ProductId == Int32.Parse(productId)
                );

            if (item == null)
            {
                item                = new ProductShoppingCart();
                item.ProductId      = Int32.Parse(productId);
                item.ShoppingCartId = cart.ShoppingCartId;
                cart.ProductShoppingCarts.Add(item);

                await _context.SaveChangesAsync();
            }

            return(true);
        }
Exemple #11
0
            public async Task <Unit> Handle(Execute request, CancellationToken cancellationToken)
            {
                var shoppingCart = new Models.ShoppingCart
                {
                    CreationDate = request.CreationDate
                };

                _context.ShoppingCart.Add(shoppingCart);
                var rows = await _context.SaveChangesAsync();

                if (rows == 0)
                {
                    throw new Exception("There was an error creating Shopping Cart");
                }

                int id = shoppingCart.ShoppingCartId;

                foreach (var item in request.ProductsList)
                {
                    var shoopingCartDetail = new ShoppingCartDetail
                    {
                        CreationDate    = DateTime.Now,
                        ShoppingCartId  = id,
                        SelectedProduct = item
                    };
                    _context.ShoppingCartDetail.Add(shoopingCartDetail);
                }

                id = await _context.SaveChangesAsync();

                if (id > 0)
                {
                    return(Unit.Value);
                }
                throw new Exception("There was an error inserting Shopping Cart details");
            }
Exemple #12
0
 public ShoppingCartSummary(Models.ShoppingCart shoppingCart)
 {
     _shoppingCart = shoppingCart;
 }
 public OrderController(IOrderRepository orderRepository, Models.ShoppingCart shoppingCart)
 {
     _orderRepository = orderRepository;
     _shoppingCart    = shoppingCart;
 }
Exemple #14
0
 public ShoppingCartController(IDrinkRepository drinkRepository, Models.ShoppingCart shoppingCart)
 {
     _drinkRepository = drinkRepository;
     _shoppingCart    = shoppingCart;
 }
Exemple #15
0
 public OrderRepository(SqlDbContext sqlDbContext, Models.ShoppingCart shoppingCart)
 {
     _sqlDbContext = sqlDbContext;
     _shoppingCart = shoppingCart;
 }
 public ShoppingCartController(ICandyRepository candyRepository, Models.ShoppingCart shoppingCart)
 {
     _candyRepository = candyRepository;
     _shoppingCart    = shoppingCart;
 }
Exemple #17
0
        public void Post(Models.ShoppingCart cart)
        {
            IDatabase db = _redis.GetDatabase();

            db.StringSetAsync(cart.Id, JsonConvert.SerializeObject(cart));
        }
Exemple #18
0
 /// <summary>
 /// Calculating Delivery Cost for cart
 /// </summary>
 /// <param name="cart"></param>
 /// <returns></returns>
 public double CalculateFor(Models.ShoppingCart cart)
 {
     return(Math.Round((CostPerDelivery * cart.NumberOfDeliveries) + (CostPerProduct * cart.NumberOfProducts) + FixedCost, 2));
 }