public void AddToCart(int id)
        {
            // Retrieve the product from the database.           
            ShoppingCartId = GetCartId();

            var cartItem = _db.ShoppingCartItems.SingleOrDefault(
                c => c.CartId == ShoppingCartId
                && c.ProductId == id);
            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists.                 
                cartItem = new CartItem
                {
                    ItemId = Guid.NewGuid().ToString(),
                    ProductId = id,
                    CartId = ShoppingCartId,
                    Product = _db.Products.SingleOrDefault(
                   p => p.ProductID == id),
                    Quantity = 1,
                    DateCreated = DateTime.Now
                };

                _db.ShoppingCartItems.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,                  
                // then add one to the quantity.                 
                cartItem.Quantity++;
            }
            _db.SaveChanges();
        }
Exemple #2
0
 public bool AddToCartAsync(int cartId, int ProductID)
 {
     myHandler = new BusinessLogicHandler();
     item = new CartItem();
     item = myHandler.CheckIfExist(cartId, ProductID);
     if(item == null)
     {
         item = new CartItem();
         item.CartID = cartId;
         item.ProductID = ProductID;
         item.DateAdded = DateTime.Now;
         item.Quantity = 1;
         if (myHandler.AddCartItem(item))
         { return true; }
         else
             return false;
     }
     else
     {
         item.Quantity += 1;
         if (myHandler.UpdateCartItem(item))
         { return true; }
         else
             return false;
     }
 }
Exemple #3
0
    /**
     * AddItem() - Adds an item to the shopping
     */
    public void AddItem(int productId, int kolicina)
    {
        if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
        {
            ShoppingCart Instance;
            Instance = new ShoppingCart();
            Instance.Items = new List<CartItem>();
            HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
        }

        // Create a new item to add to the cart
        CartItem newItem = new CartItem(productId);

        // If this item already exists in our list of items, increase the quantity
        // Otherwise, add the new item to the list
        if (Items.Contains(newItem))
        {
            foreach (CartItem item in Items)
            {
                if (item.Equals(newItem))
                {
                    item.Quantity = item.Quantity + kolicina;
                    return;
                }
            }
        }
        else
        {
            newItem.Quantity = kolicina;
            Items.Add(newItem);
        }
    }
Exemple #4
0
        public void AddToCart(Product product, decimal price)
        {
            // Get the matching cart and product instances
            var cartItem = db.CartItems.SingleOrDefault(
                c => c.CartID == ShoppingCartId
                && c.ProductID == product.ProductID);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new CartItem
                {
                    ProductID = product.ProductID,
                    CartID = ShoppingCartId,
                    Amount = 1,
                    Price = price,
                    Creation = DateTime.Now
                };

                db.CartItems.AddObject(cartItem);
            }
            else
            {
                // If the item does exist in the cart, then add one to the quantity
                cartItem.Amount++;
            }

            // Save changes
            db.SaveChanges();
        }
        /**
     * AddItem() - Adds an item to the shopping 
     */
        public void AddItem(int productId, string productName, int productQuantity, decimal productPrice)
        {
            // Create a new item to add to the cart
            CartItem newItem = new CartItem(productId, productName, productQuantity, productPrice);

            // If this item already exists in our list of items, increase the quantity
            // Otherwise, add the new item to the list
            if (Items.Contains(newItem))
            {
                foreach (CartItem item in Items)
                {
                    if (item.Equals(newItem))
                    {
                        //item.ProductQuantity++;
                        item.ProductQuantity += productQuantity;
                        return;
                    }
                }
            }
            else
            {
                //newItem.ProductQuantity = 1;
                Items.Add(newItem);
            }
        }
Exemple #6
0
		/// <summary>
		/// Add an item to the cart.
		/// When ItemId to be added has already existed, this method will update the quantity instead.
		/// </summary>
		/// <param name="itemId">Item Id of item to add</param>
		public void Add(string itemId)
		{
			CartItem cartItem;

			if (!_items.TryGetValue(itemId, out cartItem))
			{
				Item item = new ProductManager().GetItem(itemId);

				if (item != null)
				{
					cartItem = new CartItem();

					cartItem.ItemID     = itemId;
					cartItem.Name       = item.ProductName;
					cartItem.Price      = (decimal)item.Price;
					cartItem.Type       = item.Name;
					cartItem.CategoryID = item.CategoryID;
					cartItem.ProductID  = item.ProductID;

					_items.Add(itemId, cartItem);
				}
			}

			cartItem.Quantity++;
		}
Exemple #7
0
        public void AddItem(CartItem item)
        {
            if (Items.Contains(item))
                return;

            Items.Add(item);
        }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        selectedProduct = new Product();
        this.selectedProduct.Course_id = course_id.ToString();

        if (Page.IsValid)
        {
            CartItemList cart = CartItemList.GetCart();
            int locCount = cart.Count;
            locCount = locCount + 1;
            this.selectedProduct.assignmentNumber = locCount.ToString();
            this.selectedProduct.aGUID = Guid.NewGuid().ToString();
            this.selectedProduct.Num_Assignment = locCount;
            CartItem cartItem = new CartItem();

            int Num_Assignments=0;
            int assignment = 1; //will be produced from loop according to Num_Assignments
            cart = CartItemList.GetCart();
            cartItem = cart[selectedProduct.Course_id];

            if (cartItem == null)
            {
                cart.AddItem(selectedProduct, Num_Assignments,assignment);
            }
            else
            {
                cart.AddItem(selectedProduct, Num_Assignments, assignment);
                cartItem.AddQuantity(1);
            }
            this.DisplayCart();

        }
    }
Exemple #9
0
        public CartItem AddToCart(long userId, long productId, string variationName, int quantity)
        {
            var cartItemQuery = cartItemRepository
                .Query()
                .Include(x => x.Product)
                .Where(x => x.ProductId == productId && x.UserId == userId);

            var cartItem = cartItemQuery.FirstOrDefault();

            if (cartItem == null)
            {
                cartItem = new CartItem
                {
                    UserId = userId,
                    ProductId = productId,
                    Quantity = quantity,
                    CreatedOn = DateTime.Now
                };

                cartItemRepository.Add(cartItem);
            }
            else
            {
                cartItem.Quantity = quantity;
            }

            cartItemRepository.SaveChange();

            return cartItem;
        }
        public void AddToCart(int Id)
        {
            ShoppingCartId = GetCartid();

            var cartitem = db.CartItems.SingleOrDefault(p => p.CartId == ShoppingCartId && p.ProductId == Id);

            if (cartitem == null)
            {
                cartitem = new CartItem
                {
                    ItemId = Guid.NewGuid().ToString(),
                    CartId = GetCartid(),
                    Quantity = 1,
                    CreateDate = DateTime.Now,
                    Product = db.Products.SingleOrDefault(p => p.Id == Id),
                    ProductId = Id
                };
                db.CartItems.Add(cartitem);
            }
            else
            {
                cartitem.Quantity++;
            }
            db.SaveChanges();
        }
        public void Comparer_DifferentInstancesWithSameValues_ReturnsTrue()
        {
            Guid memberId = new Guid("3E522B6E-9F75-4E9A-BB11-52CE00827977");
            Guid productId = new Guid("6C7133F7-143A-4CF1-90C5-8661A4AC6B87");
            int quantity = 4;
            bool isNew = true;

            CartItem item1 = new CartItem
            {
                IsNew = isNew,
                MemberId = memberId,
                ProductId = productId,
                Quantity = quantity
            };
            CartItem item2 = new CartItem
            {
                IsNew = isNew,
                MemberId = memberId,
                ProductId = productId,
                Quantity = quantity
            };

            bool result = CartItem.CartItemComparer.Equals(item1, item2);

            Assert.That(result, Is.True);
        }
 public CartItemViewModel(CartItem cartItem)
 {
     ItemID = cartItem.ItemID;
     //SeasonNo = "NA";
     Category = cartItem.ItemCategory;
     QuantityRequired = cartItem.NoOfCopies;
     AmountPerItem = cartItem.Cost;
 }
Exemple #13
0
        public void RemoveItem_should_remove_item_from_shopping_cart()
        {
            var cartItem = new CartItem();
            _shoppingCart.AddItem(cartItem);
            _shoppingCart.RemoveItem(cartItem);

            Assert.IsEmpty(_shoppingCart.CartItems);
        }
        public void Comparer_SameInstance_ReturnsTrue()
        {
            CartItem item = new CartItem();

            bool result = CartItem.CartItemComparer.Equals(item, item);

            Assert.That(result, Is.True);
        }
    protected void addToCart1_Click(object sender, EventArgs e)
    {
        //
        CartItem newItem = new CartItem(name, price, itemPic, type,
                            quantity, total, mPrice, dayDelivered, discount, prod_id);

        // Add Current product to Shopping cart when button clicked
        Profile.ShoppingCart.Items.Add(newItem);
    }
    protected void btnAccept_Click(object sender, EventArgs e)
    {
        CCEncrypt cce = new CCEncrypt();
        string ccencrypted = cce.EncryptTripleDES(txtCardNumber.Text, "aptech");
        ccservice.Service ccser = new ccservice.Service();
        bool valid = ccser.CheckCC(ccencrypted).CardValid;
        string ct = ccser.CheckCC(ccencrypted).CardType;
        if (valid == true)
        {
            Label9.Visible = false;
            int id = 1;
            DateTime datetime = DateTime.Now;
            SqlConnection con = DBConnection.getConnection();
            SqlCommand cmd = new SqlCommand("INSERT INTO Orders VALUES ((SELECT Customer.CustomerID FROM Customer WHERE Customer.UserName = @UserName), @PaymentMethodID, @OrderTime, @ShippingAddress, @PaymentDetail, @TotalPrice, @OrderStatus)", con);
            cmd.Parameters.Add(new SqlParameter("@UserName", Request.Cookies["UserName"].Value));
            cmd.Parameters.Add(new SqlParameter("@PaymentMethodID", id));
            cmd.Parameters.Add(new SqlParameter("@OrderTime", datetime));
            cmd.Parameters.Add(new SqlParameter("@ShippingAddress", txtAddress3.Text));
            cmd.Parameters.Add(new SqlParameter("@PaymentDetail", ct));
            cmd.Parameters.Add(new SqlParameter("@TotalPrice", Int32.Parse(Cart.Instance.GetSubTotal().ToString())));
            cmd.Parameters.Add(new SqlParameter("@OrderStatus", "Pending"));
            cmd.ExecuteNonQuery();
            con.Close();

            IEnumerator enm = Cart.Instance.Items.GetEnumerator();
            while (enm.MoveNext())
            {
                Object obj = enm.Current;
                CartItem item = new CartItem();
                item = (CartItem)obj;

                SqlDataReader dr;
                SqlConnection con1 = DBConnection.getConnection();
                SqlCommand cmd1 = new SqlCommand("INSERT INTO OrderDetails VALUES (@OrderID, @ImageUrl, @RES, @Quantity, @TPrice)", con1);
                SqlCommand cmd2 = new SqlCommand("SELECT TOP 1 * FROM Orders Order BY OrderID DESC", con1);
                dr = cmd2.ExecuteReader();
                while (dr.Read())
                {
                    cmd1.Parameters.Add(new SqlParameter("@OrderID", dr["OrderID"]));
                }
                dr.Close();
                cmd1.Parameters.Add(new SqlParameter("@ImageUrl", item.ImageUrl));
                cmd1.Parameters.Add(new SqlParameter("@RES", item.Res));
                cmd1.Parameters.Add(new SqlParameter("@Quantity", item.Quantity));
                cmd1.Parameters.Add(new SqlParameter("@TPrice", item.TotalPrice));
                cmd1.ExecuteNonQuery();
                con1.Close();

            }
            Cart.Instance.RemoveCart();
            MultiView1.ActiveViewIndex = 0;
        }
        else
        {
            Label9.Visible = true;
        }
    }
    public CartItem[] GetItems()
    {
        CartItem[] items = new CartItem[cart.Count];

        for (int i = 0; i < cart.Count; i++)
            items[i] = (CartItem) cart.GetByIndex(i);

        return items;
    }
Exemple #18
0
		/// <summary>
		/// Add an item to the cart.
		/// When ItemId to be added has already existed, this method will update the quantity instead.
		/// </summary>
		/// <param name="item">Item to add</param>
		public void Add(CartItem item)
		{
			CartItem cartItem;

			if (!_items.TryGetValue(item.ItemID, out cartItem))
				_items.Add(item.ItemID, item);
			else
				cartItem.Quantity += item.Quantity;
		}
        public ActionResult Add(string productId)
        {
            var product = this.catalogService.GetProduct(productId);
            var cart = this.GetCurrentCart();
            var item = new CartItem { Id = product.Id, Name = product.Name, Price = product.Price };
            cart.Add(item);

            return this.Index();
        }
 // Set item quantity
 public void SetItemQuantity(int id, int quantity)
 {
     CartItem updateItem = new CartItem(id);
     foreach (var item in Items)
         if (updateItem.Equals(item))
         {
             item.Quantity = quantity;
             return;
         }
 }
Exemple #21
0
        public void ChangeQuantityNegativeFailsTest()
        {
            var cartItem = new CartItem
            {
                ArticleNumber = "ART1",
                Quantity = 1
            };

            cart.AddItem(cartItem);
            cart.ChangeQuantity(cartItem.Id, -2m);
        }
Exemple #22
0
 public void AddItemToCart(Product item, int Quantity)
 {
     CartItem cartItem = CartItems.FirstOrDefault(p => p.ProductId == item.Id);
     if (cartItem == null)
     {
         cartItem = new CartItem { Price = (Quantity * item.Price), ProductId = item.Id, ProductName = item.Name, Quantity = Quantity, CartId = Id, Isnew = true };
         CartItems.Add(cartItem);
     }
     else
         cartItem.Price = Quantity * item.Price;
     Price = CartItems.Select(p => p.Price).Sum();
 }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            CartItem item = new CartItem();

            item.Product = selectedProduct;
            item.Quantity = Convert.ToInt32(txtQuantity.Text);
            Profile.Cart.AddItem(item);
            Response.Redirect("Cart.aspx");
        }
    }
Exemple #24
0
    /*
     * AddItem() adds an item to the shopping cart.
     */
    public void AddItem(string upc, string name, decimal discountPrice, int _quantity, bool reserved)
    {
        // Create a new item to add to the cart.
        CartItem newItem = new CartItem(upc);
        // If this item already exists in the list of items, increase the quantity.
        // Otherwise, add the new item to the list of items with quantity 1;
        if (Items.Contains(newItem))
        {
            foreach (CartItem item in Items)
            {
                if (item.Equals(newItem))
                {
                    if (GenericQuery.CheckItemStock(connectionString, newItem, _quantity - 1))
                    {
                        if (!reserved)
                            item.Quantity++;
                        GenericQuery.UpdateDBItem(connectionString, upc, -_quantity);
                        return;
                    }
                }
            }
        }

        else if (reserved )
        {
            newItem.UPC = upc;
            newItem.ItemName = name;
            newItem.DiscountPrice = discountPrice;
            newItem.Quantity = _quantity;
            Items.Add(newItem);
        }

        else if (GenericQuery.CheckItemStock(connectionString, newItem, _quantity - 1))
        {
            newItem.UPC = upc;
            newItem.ItemName = name;
            newItem.DiscountPrice = discountPrice;
            newItem.Quantity = _quantity;
            Items.Add(newItem);
            GenericQuery.UpdateDBItem(connectionString, upc, -_quantity);
            return;
        }

        else
        {
            // Inform the user the quantity is alreadt exceed the stock
            //msg += "The item " + name + " is deleted from your shopping cart.";
            //UserNotify test = new UserNotify(msg);
            UserNotify.outstock(name.Trim());
            GenericQuery.RemoveFromDBOrderItem(connectionString, upc, GenericQuery.GetOrderNumber(connectionString, userName));
            return;
        }
    }
        public void Comparer_OneNullOneNot_ReturnsFalse()
        {
            CartItem item = new CartItem();

            bool result = CartItem.CartItemComparer.Equals(item, null);

            Assert.That(result, Is.False);

            result = CartItem.CartItemComparer.Equals(null, item);

            Assert.That(result, Is.False);
        }
 public ActionResult addToCart(int? item_id, int quantity)
 {
     Product prod = db.Products.Where(p => p.p_id == item_id).FirstOrDefault();
     CartItem newItem = new CartItem(prod, quantity);
     if (prod.avail_inventory >= quantity)
     {
         ShoppingCartModel cart = Siebu.Models.ShoppingCartModel.GetInstance(int.Parse(Session["UserId"].ToString()));
         cart.AddToCart(newItem);
         return this.Json(cart.totalItems, JsonRequestBehavior.AllowGet);
     }
     else
         return this.Json(-1, JsonRequestBehavior.AllowGet); // Return -1 if item was not added
 }
    public void AddItem(CartItem item)
    {
        string productID = item.Product.ProductID;

        if (cart.ContainsKey(productID))
        {
            CartItem existingItem = (CartItem) cart[productID];

            existingItem.Quantity += item.Quantity;
        }
        else
            cart.Add(productID, item);
    }
		public ScannerPageViewModel (IMyNavigationService navigationService)
		{
			this.navigationService = navigationService;

			ScanItemToCart = new Command (() => {
				var database = new ECOdatabase();

				CartItem item1 = new CartItem ("Apple", 4.00);
				database.InsertItemToCart(item1);

			});
				
		}
Exemple #29
0
        protected void btnAddToCart_Click(object sender, EventArgs e)
        {
            LaSuBuContainer db = new LaSuBuContainer();
            //1) the product to be added
            StoreItem theproduct = (from p in db.StoreItems
                                     where p.Id == (int)lvShop.SelectedValue
                                     select p).Single();

            //2) the qty

            //get the tbbox
            //textbox tbqty = (textbox)dvselectedproduct.findcontrol("tbqty");
            //int qty = int.parse(tbqty.text);

               // TextBox ddlQty = (TextBox).FindControl("ddlQty");
            DropDownList ddlQty = (DropDownList)lvSelectedItem.Items[0].FindControl("ddlQty");
            DropDownList ddlSize = (DropDownList)lvSelectedItem.Items[0].FindControl("ddlSize");
            DropDownList ddlColor = (DropDownList)lvSelectedItem.Items[0].FindControl("ddlColor");
            //Label lblTest = new Label();
            // lblTest.Text = ddlQty.Text;
            //or
            int qty = int.Parse(ddlQty.SelectedValue.ToString());
            string size = ddlSize.SelectedValue.ToString();
            string color = ddlColor.SelectedValue;
            //cart item
            CartItem item = new CartItem(theproduct, qty, size, color);

            //cart logic
            List<CartItem> cart = null;

            //is the cart already in the session
            if (Session["cart"] != null)
            {
                //cart is already in the session
                cart = (List<CartItem>)Session["cart"];
            }
            else
            {
                //no cart in the session create a new one
                cart = new List<CartItem>();
            }

            //add the item to the cart
            cart.Add(item);

            //put the cart back in the session
            Session["cart"] = cart;
            //mvShop.SetActiveView(vwConfirm);
            mvShop.SetActiveView(vwConfirm);
            lblConfirm.Text = "Item has been added to your cart";
        }
 public void AddItem(CartItem newItem)
 {
     foreach (CartItem item in cartItems)
     {
         if (item.name == newItem.name && item.size == newItem.size)
         {
             item.quantity += 1;
             totalPrice += newItem.price;
             return;
         }
     }
     cartItems.Add(newItem);
     totalPrice += newItem.price;
 }
 public void deleteCartItem(CartItem obj)
 {
     this.cartData.GetCartData().Remove(obj);
 }
Exemple #32
0
        public ActionResult add_to_cart(FormCollection collection)
        {
            // Get form data
            Int32 productId = Convert.ToInt32(collection["pid"]);
            decimal quantity = 0;
            decimal.TryParse(collection["qty"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out quantity);
            string[] productOptionTypeIds = collection["optionTypes"].Split('|');
            string[] selectedOptionIds = collection["optionIds"].Split('|');

            // Get the current domain
            Domain domain = Tools.GetCurrentDomain();

            // Get the currency
            Currency currency = Currency.GetOneById(domain.currency);

            // Get the product by id
            Product product = Product.GetOneById(productId, domain.front_end_language);

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC");

            // Make sure that the product not is null
            if (product == null)
            {
                return new EmptyResult();
            }

            // Get product values
            string productName = product.title;
            string productCode = product.product_code;
            string manufacturerCode = product.manufacturer_code;
            decimal unitPrice = product.unit_price;
            decimal unitFreight = product.unit_freight + product.toll_freight_addition;
            string variantImageUrl = product.variant_image_filename;

            // Update the added to cart statistic
            if (product.added_in_basket <= Int32.MaxValue - 1)
            {
                Product.UpdateAddedInBasket(product.id, product.added_in_basket + 1);
            }

            // The count of option ids
            Int32 optionIdCount = selectedOptionIds != null && selectedOptionIds[0] != "" ? selectedOptionIds.Length : 0;

            // Loop option identities and add to the price, freight and product code
            for (int i = 0; i < optionIdCount; i++)
            {
                // Convert the ids
                Int32 optionTypeId = Convert.ToInt32(productOptionTypeIds[i]);
                Int32 optionId = Convert.ToInt32(selectedOptionIds[i]);

                // Get the product option type and the product option
                ProductOptionType productOptionType = ProductOptionType.GetOneById(optionTypeId, domain.front_end_language);
                ProductOption productOption = ProductOption.GetOneById(optionTypeId, optionId, domain.front_end_language);

                // Add to values
                productName += "," + productOptionType.title + ": " + productOption.title;
                productCode += productOption.product_code_suffix;
                manufacturerCode += productOption.mpn_suffix;
                unitPrice += productOption.price_addition;
                unitFreight += productOption.freight_addition;
                variantImageUrl = variantImageUrl.Replace("[" + i + "]", productOption.product_code_suffix);
            }

            // Add delivery time to the product name
            productName += "," + tt.Get("delivery_time") + ": " + product.delivery_time;

            // Adjust the price and the freight with the conversion rate
            unitPrice *= (currency.currency_base / currency.conversion_rate);
            unitFreight *= (currency.currency_base / currency.conversion_rate);

            // Round the price to the minor unit for the currency
            Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals);
            unitPrice = Math.Round(unitPrice * (1 - product.discount) * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;
            unitFreight = Math.Round(unitFreight * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;

            // Get the value added tax
            ValueAddedTax vat = ValueAddedTax.GetOneById(product.value_added_tax_id);

            // Create a cart item
            CartItem cartItem = new CartItem();
            cartItem.product_code = productCode;
            cartItem.product_id = product.id;
            cartItem.manufacturer_code = manufacturerCode;
            cartItem.product_name = productName;
            cartItem.quantity = quantity;
            cartItem.unit_price = unitPrice;
            cartItem.unit_freight = unitFreight;
            cartItem.vat_percent = vat.value;
            cartItem.variant_image_url = variantImageUrl;
            cartItem.use_local_images = product.use_local_images;

            // Add the cart item to the shopping cart
            CartItem.AddToShoppingCart(cartItem);

            // Check if prices should include VAT or not
            bool pricesIncludesVat = Session["PricesIncludesVat"] != null ? Convert.ToBoolean(Session["PricesIncludesVat"]) : domain.prices_includes_vat;

            // Get the current culture info
            CultureInfo cultureInfo = Tools.GetCultureInfo(Language.GetOneById(domain.front_end_language));

            // Get cart statistics
            Dictionary<string, decimal> cartStatistics = CartItem.GetCartStatistics(domain, pricesIncludesVat);

            // Create the dictionary to return
            Dictionary<string, string> cartData = new Dictionary<string, string>(3);
            cartData.Add("cart_quantity", cartStatistics["total_quantity"].ToString("##,0.##", cultureInfo));
            cartData.Add("cart_amount", cartStatistics["total_amount"].ToString("##,0.##", cultureInfo) + " " + domain.currency + (pricesIncludesVat == true ? " (" + tt.Get("including_vat").ToLower() + ")" : " (" + tt.Get("excluding_vat").ToLower() + ")"));
            cartData.Add("units_in_cart", tt.Get("units_in_cart").ToLower());

            // Return a dictionary with cart data
            return Json(cartData);

        } // End of the add_to_cart method
Exemple #33
0
 public void UpdateCart(CartItem cartItem)
 {
     Cart = _cartService.UpdateCartItem(cartItem);
 }
Exemple #34
0
        public async Task <IActionResult> Order()
        {
            if (User.Identity.Name != null && User.Identity.IsAuthenticated)
            {
                if (_context.CartItems.Any())
                {
                    List <CartItem> cartItems   = new List <CartItem>();
                    List <CartItem> cartItemsDb = await _context.CartItems.ToListAsync();

                    //ziskanie z kosika
                    foreach (var item in cartItemsDb)
                    {
                        var cartItem = new CartItem
                        {
                            CartProduct = _context.Products.Where(p => p.ID == item.ProductID).FirstOrDefault(),
                            ProductID   = _context.Products.Where(p => p.ID == item.ProductID).FirstOrDefault().ID,
                        };

                        cartItems.Add(cartItem);
                        _context.CartItems.Remove(item);
                    }
                    await _context.SaveChangesAsync();

                    // pridanie do comon items
                    //pre kazdy produkt v kosiku
                    foreach (var cartItm in cartItems)
                    {
                        //pripiseme kazdu polozku z kosiku ako common
                        foreach (var item in cartItems)
                        {
                            //ochrana pred pridanim sameho seba ako common
                            if (cartItm != item)
                            {
                                CommonProduct commonProduct = new CommonProduct {
                                    ProductID = cartItm.ProductID, CommonProductID = item.CartProduct.ID
                                };
                                if (!_context.CommonProductsDbSet.Any(cp => cp.ProductID == cartItm.ProductID && cp.CommonProductID == item.CartProduct.ID))
                                {
                                    _context.CommonProductsDbSet.Add(commonProduct);
                                }

                                await _context.SaveChangesAsync();
                            }
                        }
                    }
                    await _context.SaveChangesAsync();

                    //var pp = _context;

                    //vytvorenie objednavky
                    Order order;
                    if (!_context.Order.Any())
                    {
                        order = new Order
                        {
                            OrderNumber = "0",
                            UserName    = User.Identity.Name,
                            OrderItems  = new List <OrderItem>()
                        };
                    }
                    else
                    {
                        order = new Order
                        {
                            OrderNumber = (UInt32.Parse(_context.Order.Last().OrderNumber) + 1).ToString(),
                            UserName    = User.Identity.Name,
                            OrderItems  = new List <OrderItem>()
                        };
                    }

                    _context.Order.Add(order);
                    await _context.SaveChangesAsync();

                    //vytvorenie orderItems
                    IList <OrderItem> orderItemsList = new List <OrderItem>();

                    foreach (var item in cartItems)
                    {
                        OrderItem orderItem = new OrderItem
                        {
                            Order     = _context.Order.Where(o => o.ID == order.ID).FirstOrDefault(),
                            Amount    = 1,
                            Price     = item.CartProduct.Price,
                            ProductID = item.CartProduct.ID,
                            OrderID   = _context.Order.Where(o => o.ID == order.ID).FirstOrDefault().ID,
                            Product   = item.CartProduct,
                        };

                        orderItemsList.Add(orderItem);
                    }

                    //pridanie orderItems do objednavky
                    Order editingOrder = _context.Order.Where(o => o.ID == order.ID).FirstOrDefault();
                    editingOrder.OrderItems = orderItemsList;
                    await _context.SaveChangesAsync();
                }
            }


            return(View(nameof(Index)));
        }
Exemple #35
0
        public ActionResult AddItem(Guid id, int quantity)
        {
            if (User.Identity.IsAuthenticated == false)
            {
                var product = _productService.GetById(id);
                int k       = -1;
                var list3   = new List <CartItem>();
                while (1 != 2)
                {
                    k++;
                    HttpCookie cooki = HttpContext.Request.Cookies[k.ToString()];// lấy cookie// convert json to  list object
                    if (cooki != null)
                    {
                        string ValueCookie = Server.UrlDecode(cooki.Value);//Decode dịch ngược mã  các ký tự đặc biệt
                        var    cart        = JsonConvert.DeserializeObject <List <CartItem> >(ValueCookie);
                        var    list        = (List <CartItem>)cart.ToList();

                        if (list.Exists(x => x.Product.Id == id))
                        {
                            foreach (var item in list)
                            {
                                if (item.Product.Id == product.Id)
                                {
                                    item.Quatity += quantity;
                                }
                                list3.Add(item);
                            }
                            string jsonitem = JsonConvert.SerializeObject(list3, Formatting.Indented);
                            //HttpCookie cookie = new HttpCookie(ListCart.CartCookie);// create
                            cooki.Value = Server.UrlEncode(jsonitem);
                            string b = cooki.Value;
                            HttpContext.Response.Cookies[k.ToString()].Value   = b;
                            HttpContext.Response.Cookies[k.ToString()].Expires = DateTime.Now.AddHours(15);
                            return(RedirectToAction("Index"));

                            //int f = 0;
                            //while (1 != 2)
                            //{
                            //    f++;
                            //    HttpCookie cookie = HttpContext.Request.Cookies[f.ToString()];
                            //    if (cookie == null)
                            //    {
                            //        HttpCookie Cooki2 = new HttpCookie(f.ToString());// create
                            //        Cooki2.Expires = DateTime.Now.AddHours(15);

                            //        Cooki2.Value = Server.UrlEncode(jsonitem);//Encode dịch  mã  các ký tự đặc biệt, từ string
                            //        HttpContext.Response.Cookies.Add(Cooki2);// cookie mới đè lên cookie cũ
                            //        break;
                            //    }


                            //}
                            //return RedirectToAction("Index");
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                HttpCookie Cookie = HttpContext.Request.Cookies[ListCart.CartCookie];// lấy cookie



                if (Cookie != null)
                {
                    string ValueCookie = Server.UrlDecode(Cookie.Value);                                //Decode dịch ngược mã  các ký tự đặc biệt
                    var    cart        = JsonConvert.DeserializeObject <List <CartItem> >(ValueCookie); // convert json to  list object
                    if (cart != null)
                    {
                        var list  = (List <CartItem>)cart;
                        var list2 = new List <CartItem>();
                        if (list.Exists(x => x.Product == product))
                        {
                            foreach (var item in list)
                            {
                                if (item.Product == product)
                                {
                                    item.Quatity += quantity;
                                }
                            }
                        }
                        else
                        {
                            var item = new CartItem();
                            item.Product = product;
                            item.Quatity = quantity;

                            list2.Add(item);
                        }

                        string jsonItem = JsonConvert.SerializeObject(list2, Formatting.Indented);
                        //HttpCookie cookie = new HttpCookie(ListCart.CartCookie);// create

                        int i = 0;
                        while (1 != 2)
                        {
                            i++;
                            HttpCookie cooki = HttpContext.Request.Cookies[i.ToString()];
                            if (cooki == null)
                            {
                                HttpCookie Cooki2 = new HttpCookie(i.ToString());// create
                                Cooki2.Expires = DateTime.Now.AddHours(15);

                                Cooki2.Value = Server.UrlEncode(jsonItem); //Encode dịch  mã  các ký tự đặc biệt, từ string
                                HttpContext.Response.Cookies.Add(Cooki2);  // cookie mới đè lên cookie cũ
                                break;
                            }
                        }


                        //cookie.Expires.AddDays(1);
                        //cookie.Value = Server.UrlEncode(jsonItem);//Encode dịch  mã  các ký tự đặc biệt, từ string
                        //HttpContext.Response.Cookies.Add(cookie);// cookie mới đè lên cookie cũ
                    }
                }
                else
                {
                    //Tạo mới CartItem
                    var item = new CartItem();
                    item.Product = product;
                    item.Quatity = quantity;
                    var list = new List <CartItem>();
                    list.Add(item);

                    string     jsonItem = JsonConvert.SerializeObject(list, Formatting.Indented);
                    HttpCookie cookie   = new HttpCookie(ListCart.CartCookie);// create
                    cookie.Expires = DateTime.Now.AddHours(15);

                    cookie.Value = Server.UrlEncode(jsonItem); //Encode dịch  mã  các ký tự đặc biệt, từ string
                    HttpContext.Response.Cookies.Add(cookie);  // cookie mới đè lên cookie cũ
                }
            }
            else
            {
                var orderDetailTemp = _orderDetailTempService.ListAllByUserID(User.Identity.GetUserId());
                var product         = _productService.GetById(id);
                if (orderDetailTemp == null)
                {
                    OrderDetailTemp temp = new OrderDetailTemp();
                    temp.Id     = Guid.NewGuid();
                    temp.UserID = User.Identity.GetUserId();
                    _orderDetailTempService.Create(temp);
                    orderDetailTemp = _orderDetailTempService.ListAllByUserID(User.Identity.GetUserId());
                }
                if (orderDetailTemp.CartContent == null)
                {
                    var item = new CartItem();
                    item.Product = product;
                    item.Quatity = quantity;
                    var list = new List <CartItem>();
                    list.Add(item);

                    string jsonItem = JsonConvert.SerializeObject(list, Formatting.Indented);

                    var value = Server.UrlEncode(jsonItem); //Encode dịch  mã  các ký tự đặc biệt, từ string
                    orderDetailTemp.CartContent = value;    // cookie mới đè lên cookie cũ
                }
                else
                {
                    string value = Server.UrlDecode(orderDetailTemp.CartContent);           //Decode dịch ngược mã  các ký tự đặc biệt tham khảo
                    var    cart  = JsonConvert.DeserializeObject <List <CartItem> >(value); // convert json to  list object
                    var    list  = (List <CartItem>)cart;
                    if (list.Exists(x => x.Product.Id == product.Id))
                    {
                        foreach (var item in list)
                        {
                            if (item.Product.Id == product.Id)
                            {
                                item.Quatity += quantity;
                            }
                        }
                    }
                    else
                    {
                        var item = new CartItem();
                        item.Product = product;
                        item.Quatity = quantity;

                        list.Add(item);
                    }

                    string          jsonItem = JsonConvert.SerializeObject(list, Formatting.Indented);
                    OrderDetailTemp temp     = new OrderDetailTemp();
                    temp.Id          = _orderDetailTempService.ListAllByUserID(User.Identity.GetUserId()).Id;
                    temp.UserID      = User.Identity.GetUserId();
                    temp.CartContent = jsonItem;
                    _orderDetailTempService.Update(temp);
                }

                //string Value = Server.UrlDecode(orderDetailTemp.CartContent);//Decode dịch ngược mã  các ký tự đặc biệt tham khảo
                //var cart = JsonConvert.DeserializeObject<List<CartItem>>(Value);// convert json to  list object
                //list = (List<CartItem>)cart;
            }


            return(RedirectToAction("Index"));
        }
Exemple #36
0
 public void AddItem(CartItem item)
 {
     db.CartItems.Add(item);
     db.SaveChanges();
 }
Exemple #37
0
 public void DeleteCartItem(CartItem item)
 {
     db.CartItems.Remove(item);
     db.SaveChanges();
 }
Exemple #38
0
 /// <summary>
 /// Update a given user's cart item quantity
 /// </summary>
 /// <param name="cartItem">CartItem information for update</param>
 /// <returns>Successful result of specified updated cartItem</returns>
 public async Task Update(CartItem cartItem)
 {
     _context.Entry(cartItem).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
Exemple #39
0
        public ActionResult add_product(FormCollection collection)
        {
            // Get the product id
            Int32 productId = Convert.ToInt32(collection["hiddenProductId"]);

            // Get the current domain
            Domain domain = Tools.GetCurrentDomain();

            // Get the currency
            Currency currency = Currency.GetOneById(domain.currency);

            // Get the product by id
            Product product = Product.GetOneById(productId, domain.front_end_language);

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC");

            // Make sure that the product not is null
            if (product == null)
            {
                Response.StatusCode = 404;
                Response.Status = "404 Not Found";
                Response.Write(Tools.GetHttpNotFoundPage());
                return new EmptyResult();
            }

            // Get form data
            decimal quantity = 0;
            decimal.TryParse(collection["txtQuantity"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out quantity);
            string[] productOptionTypeIds = collection.GetValues("productOptionTypeId");
            string[] selectedOptionIds = collection.GetValues("selectProductOption");

            // Get other values
            string productName = product.title;
            string productCode = product.product_code;
            string manufacturerCode = product.manufacturer_code;
            decimal unitPrice = product.unit_price;
            decimal unitFreight = product.unit_freight + product.toll_freight_addition;
            string variantImageUrl = product.variant_image_filename;

            // Update the added to cart statistic
            if(product.added_in_basket <= Int32.MaxValue - 1)
            {
                Product.UpdateAddedInBasket(product.id, product.added_in_basket + 1);
            }

            // Check if the product has a affiliate link
            if (product.affiliate_link != "")
            {
                // Redirect the user to the affiliate site
                return Redirect(product.affiliate_link);
            }

            // The count of option ids
            Int32 optionIdCount = selectedOptionIds != null ? selectedOptionIds.Length : 0;

            // Loop option identities and add to the price, freight and product code
            for (int i = 0; i < optionIdCount; i++)
            {
                // Convert the ids
                Int32 optionTypeId = Convert.ToInt32(productOptionTypeIds[i]);
                Int32 optionId = Convert.ToInt32(selectedOptionIds[i]);

                // Get the product option type and the product option
                ProductOptionType productOptionType = ProductOptionType.GetOneById(optionTypeId, domain.front_end_language);
                ProductOption productOption = ProductOption.GetOneById(optionTypeId, optionId, domain.front_end_language);

                // Add to values
                productName += "," + productOptionType.title + ": " + productOption.title;
                productCode += productOption.product_code_suffix;
                manufacturerCode += productOption.mpn_suffix;
                unitPrice += productOption.price_addition;
                unitFreight += productOption.freight_addition;
                variantImageUrl = variantImageUrl.Replace("[" + i + "]", productOption.product_code_suffix);
            }

            // Add delivery time to the product name
            productName += "," + tt.Get("delivery_time") + ": " + product.delivery_time;

            // Adjust the price and the freight with the conversion rate
            unitPrice *= (currency.currency_base / currency.conversion_rate);
            unitFreight *= (currency.currency_base / currency.conversion_rate);

            // Round the price to the minor unit for the currency
            Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals);
            unitPrice = Math.Round(unitPrice * (1 - product.discount) * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;
            unitFreight = Math.Round(unitFreight * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;

            // Get the value added tax
            ValueAddedTax vat = ValueAddedTax.GetOneById(product.value_added_tax_id);

            // Create a cart item
            CartItem cartItem = new CartItem();
            cartItem.product_code = productCode;
            cartItem.product_id = product.id;
            cartItem.manufacturer_code = manufacturerCode;
            cartItem.product_name = productName;
            cartItem.quantity = quantity;
            cartItem.unit_price = unitPrice;
            cartItem.unit_freight = unitFreight;
            cartItem.vat_percent = vat.value;
            cartItem.variant_image_url = variantImageUrl;
            cartItem.use_local_images = product.use_local_images;

            // Add the cart item to the shopping cart
            CartItem.AddToShoppingCart(cartItem);

            // Redirect the user to the same product page
            return RedirectToAction("product", "home", new { id = product.page_name, cu = "true" });

        } // End of the add_product method
Exemple #40
0
 public OrderRow(CartItem cartItem)
 {
     Amount  = cartItem.Amount;
     Product = cartItem.Product;
 }
Exemple #41
0
 /// <summary>
 /// Creates a new cart items in the database
 /// </summary>
 /// <param name="cartItem">CartItem information for creation</param>
 /// <returns>Successful result of cartItem creation</returns>
 public async Task Create(CartItem cartItem)
 {
     _context.Entry(cartItem).State = EntityState.Added;
     await _context.SaveChangesAsync();
 }
Exemple #42
0
        public AddToCartViewModel BuildAddToCartViewModel(
            UrlHelper urlHelper,
            ProductVariant variant,
            Product product,
            CartItem cartItem,
            Customer customer,
            bool showWishlistButton,
            bool colorSelectorChangesImage,
            int defaultQuantity  = 1,
            string selectedSize  = "",
            string selectedColor = "")
        {
            // Build our options and prompts
            var customerEntersPricePrompt = XmlCommon.GetLocaleEntry(variant.CustomerEntersPricePrompt, customer.LocaleSetting, true);

            customerEntersPricePrompt = !string.IsNullOrEmpty(customerEntersPricePrompt)
                                        ? customerEntersPricePrompt
                                        : "Price";

            var textOptionPrompt = XmlCommon.GetLocaleEntry(product.TextOptionPrompt, customer.LocaleSetting, true);

            textOptionPrompt = !string.IsNullOrEmpty(textOptionPrompt)
                                        ? textOptionPrompt
                                        : "Customization Text";

            var sizes            = XmlCommon.GetLocaleEntry(variant.Sizes, Localization.GetDefaultLocale(), true);
            var displaySizes     = XmlCommon.GetLocaleEntry(variant.Sizes, customer.LocaleSetting, true);
            var sizeOptionPrompt = XmlCommon.GetLocaleEntry(product.SizeOptionPrompt, customer.LocaleSetting, true);

            sizeOptionPrompt = !string.IsNullOrEmpty(sizeOptionPrompt)
                                ? sizeOptionPrompt
                                : "Size";

            var colors            = XmlCommon.GetLocaleEntry(variant.Colors, Localization.GetDefaultLocale(), true);
            var displayColors     = XmlCommon.GetLocaleEntry(variant.Colors, customer.LocaleSetting, true);
            var colorOptionPrompt = XmlCommon.GetLocaleEntry(product.ColorOptionPrompt, customer.LocaleSetting, true);

            colorOptionPrompt = !string.IsNullOrEmpty(colorOptionPrompt)
                                ? colorOptionPrompt
                                : "Color";

            var quantity = defaultQuantity;

            if (cartItem != null && cartItem.Quantity > 0)
            {
                quantity = cartItem.Quantity;
            }
            else if (variant.MinimumQuantity > 0)
            {
                quantity = variant.MinimumQuantity;
            }
            else if (!string.IsNullOrEmpty(AppLogic.AppConfig("DefaultAddToCartQuantity")))
            {
                quantity = AppLogic.AppConfigUSInt("DefaultAddToCartQuantity");
            }

            selectedSize = cartItem != null
                                        ? AppLogic.CleanSizeColorOption(cartItem.ChosenSize)
                                        : AppLogic.CleanSizeColorOption(selectedSize);;

            selectedColor = cartItem != null
                                        ? AppLogic.CleanSizeColorOption(cartItem.ChosenColor)
                                        : AppLogic.CleanSizeColorOption(selectedColor);

            // If this is a single variant product, setup the PayPal ad.
            PayPalAd payPalAd = null;

            if (AppLogic.GetNextVariant(product.ProductID, variant.VariantID) == variant.VariantID)
            {
                payPalAd = new PayPalAd(PayPalAd.TargetPage.Product);
            }

            var variantCount = DB.GetSqlN(
                sql: "SELECT COUNT(*) AS N FROM ProductVariant WHERE Deleted = 0 and published = 1 and ProductID = @productId",
                parameters: new SqlParameter("productId", product.ProductID));

            // Now build the model
            var model = new AddToCartViewModel(
                showQuantity: (!variant.CustomerEntersPrice
                               // nal
                               //&& AppLogic.AppConfigBool("ShowQuantityOnProductPage")
                               && !product.IsAKit)
                // nal
                //|| !AppLogic.AppConfigBool("HideKitQuantity")
                && product.IsAKit,
                restrictedQuantities: RestrictedQuantityProvider.BuildRestrictedQuantityList(variant.RestrictedQuantities),
                customerEntersPrice: variant.CustomerEntersPrice,
                customerEntersPricePrompt: customerEntersPricePrompt,
                colorOptions: BuildOptionList(colors, displayColors, customer, product.TaxClassID, colorOptionPrompt),
                colorOptionPrompt: colorOptionPrompt,
                sizeOptions: BuildOptionList(sizes, displaySizes, customer, product.TaxClassID, sizeOptionPrompt),
                sizeOptionPrompt: sizeOptionPrompt,
                requiresTextOption: product.RequiresTextOption,
                showTextOption: product.RequiresTextOption ||
                !string.IsNullOrEmpty(XmlCommon.GetLocaleEntry(product.TextOptionPrompt, customer.LocaleSetting, true)),
                textOptionPrompt: textOptionPrompt,
                textOptionMaxLength: product.TextOptionMaxLength == 0
                                        ? 50
                                        : product.TextOptionMaxLength,
                isCallToOrder: product.IsCalltoOrder,
                // nal
                //showBuyButton: AppLogic.AppConfigBool("ShowBuyButtons")
                showBuyButton: product.ShowBuyButton &&
                !AppLogic.HideForWholesaleSite(customer.CustomerLevelID),
                // nal
                //showWishlistButton: showWishlistButton && AppLogic.AppConfigBool("ShowWishButtons"),
                showWishlistButton: showWishlistButton,
                payPalAd: payPalAd,
                showBuySafeKicker: (!AppLogic.AppConfigBool("BuySafe.DisableAddToCartKicker") &&
                                    AppLogic.GlobalConfigBool("BuySafe.Enabled") &&
                                    AppLogic.GlobalConfig("BuySafe.Hash").Length != 0),
                buySafeKickerType: AppLogic.AppConfig("BuySafe.KickerType"),
                colorSelectorChangesImage: colorSelectorChangesImage,
                isSimpleProduct: !product.IsAKit &&
                variantCount == 1 &&
                string.IsNullOrEmpty(displaySizes) &&
                string.IsNullOrEmpty(displayColors) &&
                !product.RequiresTextOption &&
                !variant.CustomerEntersPrice,
                cartType: cartItem != null
                                        ? cartItem.CartType
                                        : CartTypeEnum.ShoppingCart) // if no current cart item, this won't be used, so it doesn't matter what it's set to
            {
                ProductId    = variant.ProductID,
                VariantId    = variant.VariantID,
                CartRecordId = cartItem != null
                                        ? cartItem.ShoppingCartRecordID
                                        : 0,
                Quantity             = quantity,
                CustomerEnteredPrice = (cartItem != null && variant.CustomerEntersPrice)
                                        ? cartItem.Price
                                        : 0.00M,
                TextOption = cartItem != null
                                        ? cartItem.TextOption
                                        : String.Empty,
                Color          = selectedColor,
                Size           = selectedSize,
                UpsellProducts = null,
                IsWishlist     = false,
                ReturnUrl      = urlHelper.MakeSafeReturnUrl(HttpContext.Current.Request.RawUrl)
            };

            return(model);
        }
        public static TableLayoutPanel CreateHorizontalBookItem(CartItem drawingItem, Panel container, string listType, EventHandler selectorEvent)
        {
            int tblLayoutHeight = 50;
            int tblLayoutWidth  = container.Width;
            int tblLayoutX      = 0;
            int tblLayoutY      = (container.Controls.Count * tblLayoutHeight) + (int)(container.Controls.Count * tblLayoutHeight * 0.1);

            //Setting culture info
            Culture.SetCultureInfo();

            //Create title label
            Label titleLabel = new Label();

            titleLabel.Padding   = new Padding(5, 5, 5, 5);
            titleLabel.AutoSize  = true;
            titleLabel.BackColor = Color.Transparent;
            titleLabel.Font      = new Font("Tahoma", 12F, FontStyle.Regular, GraphicsUnit.Point, 0);
            titleLabel.Text      = drawingItem.Book.Title + " - " + drawingItem.Book.Author;
            if (!drawingItem.IsAvailable)
            {
                if (listType == "CHECKOUT")
                {
                    titleLabel.ForeColor = Color.Red;
                    titleLabel.Text     += " (Not Available)";
                }
                else if (listType == "ORDER")
                {
                    titleLabel.ForeColor = Color.Gray;
                    titleLabel.Text     += " (Not Ordered)";
                }
            }

            //Create quantity selector
            NumericUpDown quantitySelector = new NumericUpDown();

            quantitySelector.AutoSize  = true;
            quantitySelector.BackColor = Color.White;
            quantitySelector.Font      = new Font("Tahoma", 8F, FontStyle.Regular, GraphicsUnit.Point, 0);
            quantitySelector.Padding   = new Padding(5, 5, 5, 5);
            quantitySelector.Value     = drawingItem.Quantity;
            quantitySelector.Anchor    = AnchorStyles.Top;
            quantitySelector.Tag       = drawingItem;
            if (listType == "CHECKOUT")
            {
                quantitySelector.ValueChanged += new EventHandler(selectorEvent);
            }
            else if (listType == "ORDER")
            {
                quantitySelector.Enabled = false;
            }

            //Create price label
            Label priceLabel = new Label();

            priceLabel.AutoSize  = true;
            priceLabel.BackColor = Color.Transparent;
            priceLabel.Dock      = DockStyle.Fill;
            priceLabel.Font      = new Font("Tahoma", 8F, FontStyle.Regular, GraphicsUnit.Point, 0);
            priceLabel.Margin    = new Padding(0);
            priceLabel.Padding   = new Padding(5, 5, 5, 5);
            priceLabel.Anchor    = AnchorStyles.Top | AnchorStyles.Right;
            if (drawingItem.IsAvailable)
            {
                priceLabel.Text = drawingItem.Book.Price.ToString("C");
            }
            else
            {
                if (listType == "CHECKOUT")
                {
                    priceLabel.Text = drawingItem.Book.Price.ToString("C");
                }
                else if (listType == "ORDER")
                {
                    priceLabel.Text = "-";
                }
            }

            //Create TableLayout
            TableLayoutPanel tblLayoutHandler = new TableLayoutPanel();

            tblLayoutHandler.BackColor = Color.White;
            //tblLayoutHandler.Dock = DockStyle.Fill;
            tblLayoutHandler.Anchor   = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            tblLayoutHandler.Location = new Point(tblLayoutX, tblLayoutY);
            tblLayoutHandler.Size     = new Size(tblLayoutWidth, tblLayoutHeight);
            tblLayoutHandler.Margin   = new Padding(10);
            tblLayoutHandler.RowCount = 1;
            tblLayoutHandler.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
            tblLayoutHandler.ColumnCount = 3;
            tblLayoutHandler.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 65F));
            tblLayoutHandler.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 15F));
            tblLayoutHandler.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20F));
            //add the control to the table layout panel
            tblLayoutHandler.Controls.Add(titleLabel, 0, 0);
            tblLayoutHandler.Controls.Add(quantitySelector, 1, 0);
            tblLayoutHandler.Controls.Add(priceLabel, 2, 0);

            return(tblLayoutHandler);
        }
Exemple #44
0
 public void DeleteCartItem(CartItem cartItem)
 {
     _orderDAO.DeleteCartItem(cartItem);
 }
Exemple #45
0
        public int getCartItemTotalPris(CartItem item)
        {
            var pris = item.Count * item.Produkt.Pris;

            return(pris);
        }
Exemple #46
0
        public ActionResult AddOrRemove(int garantiaId, int cod_cliente, string cod_foxlux, int cod_item, bool isDelete, decimal qtde, int num_nota, decimal vlr_unitario
                                        , decimal vlr_ipi, decimal vlr_icms_subs, decimal vlr_icms, decimal vlr_base_subs, string obsitem, decimal fator,
                                        decimal picms, decimal pipi, decimal pcimsst, decimal mvast, int cod_unidade

                                        )
        {
            //int sessao = db.Database.SqlQuery<int>(" SELECT USERENV('SESSIONID') FROM DUAL ").FirstOrDefault();
            int    NextRecordId = db.Database.SqlQuery <int>(" SELECT CartItemSeq.NextVal FROM DUAL ").FirstOrDefault();
            string Msg          = "";


            if (!isDelete)
            {
                CartItem NewItem = new CartItem()
                {
                    garantiaId    = garantiaId,
                    cod_Foxlux    = cod_foxlux.TrimStart().TrimEnd(),
                    cod_item      = cod_item,
                    num_nota      = num_nota,
                    qtde_Garantia = qtde,
                    recordId      = NextRecordId,
                    vlr_Unitario  = vlr_unitario / fator,
                    vlr_icms      = (vlr_icms / fator) * qtde,
                    vlr_icms_subs = (vlr_icms_subs / fator) * qtde,
                    vlr_ipi       = (vlr_ipi / fator) * qtde,
                    vlr_base_subs = (vlr_base_subs / fator) * qtde,
                    ObsItem       = obsitem,
                    picms         = picms,
                    pipi          = pipi,
                    picmsst       = pcimsst,
                    mvast         = mvast,
                    cod_unidade   = cod_unidade
                };
                db.CartItem.Add(NewItem);
            }
            else
            {
                int      RecordId   = db.CartItem.Where(a => a.cod_Foxlux == cod_foxlux && a.garantiaId == garantiaId && a.num_nota == num_nota).Select(a => a.recordId).FirstOrDefault();
                CartItem DeleteItem = db.CartItem.Find(garantiaId, RecordId, cod_foxlux, cod_item, num_nota);

                if (DeleteItem != null)
                {
                    db.CartItem.Remove(DeleteItem);
                }
                else
                {
                    Msg = " Não existem Item para deletar";
                }
            }

            try
            {
                db.SaveChanges();
                Msg = " Item atualizado com êxito ";
            }
            catch (Exception e)
            {
                Msg = e.Message;
            }


            var _itens  = db.CartItem.Where(a => a.garantiaId == garantiaId).ToList();
            var results = new
            {
                Msg       = Msg,
                CartTotal = _itens.Select(a => a.qtde_Garantia * a.vlr_Unitario).Sum(),
                CartCount = _itens.Count()
            };

            return(Json(results));
        }
        public AddItemToCartResponse AddItemToCart(AddItemToCartRequest addItemToCartRequest)
        {
            AddItemToCartResponse response = new AddItemToCartResponse();

            var cart = GetCart();

            if (cart != null)
            {
                var existingCartItem = _cartItemRepository.FindCartItemsByCartId(cart.Id)
                                       .FirstOrDefault(c => c.ProductId == addItemToCartRequest.ProductId);
                if (existingCartItem != null)
                {
                    existingCartItem.Quantity++;
                    _cartItemRepository.UpdateCartItem(existingCartItem);

                    response.CartItem = _messageMapper.MapToCartItemDto(existingCartItem);
                }
                else
                {
                    var product = _productRepository.FindProductById(addItemToCartRequest.ProductId);

                    if (product != null)
                    {
                        var cartItem = new CartItem
                        {
                            CartId    = cart.Id,
                            Cart      = cart,
                            ProductId = addItemToCartRequest.ProductId,
                            Product   = product,
                            Quantity  = 1
                        };
                        _cartItemRepository.SaveCartItem(cartItem);
                        response.CartItem = _messageMapper.MapToCartItemDto(cartItem);
                    }
                }
            }
            else
            {
                var product = _productRepository.FindProductById(addItemToCartRequest.ProductId);
                if (product != null)
                {
                    var newCart = new Cart
                    {
                        UniqueCartId = UniqueCartId(),
                        CartStatus   = cartStatus.Open
                    };

                    _cartRepository.SaveCart(newCart);

                    var cartItem = new CartItem
                    {
                        CartId    = newCart.Id,
                        Cart      = newCart,
                        ProductId = addItemToCartRequest.ProductId,
                        Product   = product,
                        Quantity  = 1
                    };

                    _cartItemRepository.SaveCartItem(cartItem);

                    response.CartItem = _messageMapper.MapToCartItemDto(cartItem);
                }
            }
            return(response);
        }
Exemple #48
0
 private void FindSameItemAlreadyInCart()
 {
     _itemFound = _cart.Items
                  .FirstOrDefault(item => item.ProductId == _itemToAdd.ProductId);
 }
 public void addCartItem(CartItem obj)
 {
     this.cartData.GetCartData().Add(obj);
     MessageBox.Show("Succeful");
 }
Exemple #50
0
        public IActionResult Index(int id, int quantity)
        {
            // I have a few cases to work through here :
            //Does this user have an old cart?
            //Are they logged in or anonymous?
            Cart cart = null;

            if (User.Identity.IsAuthenticated)
            {
                var currentStoreUser = _context.Users
                                       .Include(x => x.Cart)
                                       .ThenInclude(x => x.CartItems)
                                       .ThenInclude(x => x.Product)
                                       .First(x => x.UserName == User.Identity.Name);
                if (currentStoreUser.Cart != null)
                {
                    cart = currentStoreUser.Cart;
                }
                else
                {
                    cart = new Cart
                    {
                        CookieID = Guid.NewGuid(),
                        Created  = DateTime.UtcNow
                    };
                    currentStoreUser.Cart = cart;
                    _context.SaveChanges();
                }
            }

            if ((cart == null) && (Request.Cookies.ContainsKey("CartID")))
            {
                if (Guid.TryParse(Request.Cookies["CartID"], out Guid cookieId))
                {
                    cart = _context.Carts.Include(x => x.CartItems)
                           .ThenInclude(x => x.Product)
                           .FirstOrDefault(x => x.CookieID == cookieId);
                }
            }

            if (cart == null)   //I either couldn't find the cart from the cookie, or the user had no cookie.
            {
                cart = new Cart
                {
                    CookieID = Guid.NewGuid(),
                    Created  = DateTime.UtcNow
                };
                _context.Carts.Add(cart);
            }
            cart.LastModified = DateTime.UtcNow;

            CartItem cartItem = null;   //I also need to check if this item is already in the cart!

            cartItem = cart.CartItems.FirstOrDefault(x => x.Product.ID == id);

            if (cartItem == null) //If still null, this is the first time this item has been added to the cart
            {
                cartItem = new CartItem
                {
                    Quantity = 0,
                    Product  = _context.Products.Find(id),
                    Created  = DateTime.UtcNow,
                };
                cart.CartItems.Add(cartItem);
            }
            cartItem.Quantity    += quantity;
            cartItem.LastModified = DateTime.UtcNow;
            _context.SaveChanges();
            if (!User.Identity.IsAuthenticated)
            {
                Response.Cookies.Append("CartID", cart.CookieID.Value.ToString());
            }
            return(RedirectToAction("Index", "Cart"));
        }
        public ActionResult Confirm()
        {
            bool       errorQuantity = false;
            ProductDAO dao           = new ProductDAO();
            CartItem   c             = (CartItem)Session["CART"];

            string[,] listErrorQuantity = new string[c.Cart.Count, 1];
            for (int i = 0; i < c.Cart.Count; i++)
            {
                int quantityAtCart     = c.Cart[i].Quantity;
                int quantityInDatabase = dao.GetProductQuantity(c.Cart[i].Product.ID);
                if (quantityAtCart > quantityInDatabase)
                {
                    listErrorQuantity.SetValue("Max : " + quantityInDatabase, i, 0);
                    errorQuantity = true;
                }
            }
            if (errorQuantity == false)
            {
                for (int i = 0; i < c.Cart.Count; i++)
                {
                    dao.UpdateQuantitty(c.Cart[i].Product.ID, c.Cart[i].Quantity);
                }


                float       totalPrice = float.Parse(Request["TotalPrice"]);
                CustomerDAO daoCus     = new CustomerDAO();
                CustomerDTO cus        = (CustomerDTO)Session["CUSTOMER"];
                bool        result     = daoCus.CheckOut(totalPrice, cus.Username);

                //check point and maybe update rank

                string newRank = "";

                float  point       = daoCus.GetPointOfCus(cus.Username);
                string currentRank = cus.Rank;
                if (currentRank == null)
                {
                    currentRank = "";
                }

                if (point >= 500 && point < 2000 && currentRank.Equals("bronze") == false)
                {
                    newRank = "bronze";
                    daoCus.UpdateRank(cus.Username, newRank);
                    ViewBag.Congrats = "Congratulations!!! Your rank is Bronze now. Thank you for choosing our service.";
                }
                if (point >= 2000 && point < 5000 && currentRank.Equals("silver") == false)
                {
                    newRank = "silver";
                    daoCus.UpdateRank(cus.Username, newRank);
                    ViewBag.Congrats = "Congratulations!!! Your rank is Silver now. Thank you for choosing our service.";
                }
                if (point >= 5000 && point < 15000 && currentRank.Equals("gold") == false)
                {
                    newRank = "gold";
                    daoCus.UpdateRank(cus.Username, newRank);
                    ViewBag.Congrats = "Congratulations!!! Your rank is Gold now. Thank you for choosing our service.";
                }
                if (point >= 15000 && currentRank.Equals("platinum") == false)
                {
                    newRank = "platinum";
                    daoCus.UpdateRank(cus.Username, newRank);
                    ViewBag.Congrats = "Congratulations!!! Your rank is Platinum now. Thank you for choosing our service.";
                }

                //when checkout done
                if (result)
                {
                    // create order
                    DateTime createDate = DateTime.Now;
                    string   cusID      = cus.Username;
                    int      state      = 0;// start order

                    float discount = 0;
                    if (Session["Discount"] != null) // neu moi mua lan dau thi ko co discount
                    {
                        discount = (float)Session["Discount"];
                    }

                    BillDTO order       = new BillDTO(createDate, cusID, state, totalPrice, discount);
                    BillDAO daoOrder    = new BillDAO();
                    bool    resultOrder = daoOrder.CreateOrder(order);// create order
                    if (resultOrder)
                    {
                        OrderDetailDAO daoOrderDetail = new OrderDetailDAO();
                        int            orderID        = daoOrder.GetOrderID(); // get orderID has created
                        for (int i = 0; i < c.Cart.Count; i++)
                        {
                            OrderDetailDTO orderDetail = new OrderDetailDTO(orderID, c.Cart[i].Product.ID,
                                                                            c.Cart[i].Quantity, c.Cart[i].Product.Price, c.Cart[i].Product.NameProduct);
                            daoOrderDetail.CreateOrderDetail(orderDetail);
                        }

                        Session.Remove("CART");

                        Session.Remove("txtSearchValue");
                    }
                }
            }
            else
            {
                ViewBag.ErrorQuantity = listErrorQuantity;
                return(View("ViewCart"));
            }



            return(View("ViewOrdercomplete"));
        }
Exemple #52
0
    //add, remove and clear from the list
    public void AddItem(Note note)
    {
        CartItem item = new CartItem(note);

        cartItems.Add(item);
    }
 public static IO <IChangeQuantityResult> ChangeQuantity(ClientAgg clientAgg, CartItem cartItem, uint quantity) =>
 NewIO <ChangeQuantityOp.ChangeQuantityCmd, IChangeQuantityResult>(new ChangeQuantityOp.ChangeQuantityCmd(clientAgg, cartItem, quantity));
Exemple #54
0
        public async Task <ActionResult <CartItem> > Create(CartItem cart)
        {
            await _cartRepository.Create(cart);

            return(CreatedAtAction("GetById", new { id = cart.Id }, cart));
        }
 public void Add(CartItem newItem)
 {
     newItem.Id = 1;
     _shoppingCart.Add(newItem);
 }
    public void AddItem(Product product, int quantity)
    {
        CartItem c = new CartItem(product, quantity);

        cartItems.Add(c);
    }
Exemple #57
0
        public Object Get(string artid, string type)
        {
            try
            {
                int artidInt = Int32.Parse(artid);
                if (HttpContext.Current.Session["username"] != null)
                {
                    if (HttpContext.Current.Session["cart"] == null)
                    {
                        HttpContext.Current.Session["cart"] = new Cart()
                        {
                            CartItems = new List <CartItem>()
                        };
                    }

                    Cart     cart            = (Cart)HttpContext.Current.Session["cart"];
                    CartItem currentCartItem =
                        cart.CartItems.Find(cartItem => cartItem.ArticleId == artidInt);
                    if (currentCartItem == null)
                    {
                        cart.CartItems.Add(new CartItem()
                        {
                            ArticleId = artidInt, Count = 0
                        });
                        currentCartItem =
                            cart.CartItems.Find(cartItem => cartItem.ArticleId == artidInt);
                    }
                    if (type == "neg")
                    {
                        currentCartItem.Count--;
                        if (currentCartItem.Count <= 0)
                        {
                            cart.CartItems.Remove(currentCartItem);
                        }
                    }
                    else if (type == "rem")
                    {
                        cart.CartItems.Remove(currentCartItem);
                    }
                    else if (type == "add")
                    {
                        currentCartItem.Count++;
                    }


                    HttpContext.Current.Session["cart"] = cart;

                    return(new ApiResponse()
                    {
                        data = new List <Cart>()
                        {
                            HttpContext.Current.Session["cart"] as Cart
                        }
                        ,
                        error = ""
                    });
                }
                else
                {
                    var response = Request.CreateResponse(HttpStatusCode.Moved);
                    response.Headers.Location =
                        new Uri(Url.Content("~/wwwroot/pages/home.htm"));
                    return(response);
                }
            }
            catch (DbEntityValidationException e)
            {
                string errorString = "";
                foreach (var eve in e.EntityValidationErrors)
                {
                    errorString += String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                                 eve.Entry.Entity.GetType().Name, eve.Entry.State);

                    /*Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                     *  eve.Entry.Entity.GetType().Name, eve.Entry.State);*/
                    foreach (var ve in eve.ValidationErrors)
                    {
                        errorString += String.Format("- Property: \"{0}\", Error: \"{1}\"",
                                                     ve.PropertyName, ve.ErrorMessage);

                        /*Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                         *  ve.PropertyName, ve.ErrorMessage);*/
                    }
                }
                throw;
            }
            catch (Exception ex)
            {
                return(new ApiResponse()
                {
                    data = null, error = ex.Message + " : " + ex.StackTrace
                });
            }
        }
 public void AddItemToCart(CartItem cartItem)
 {
     productList.Add(cartItem);
 }
        public async Task <bool> AddToCart(CartItem ci)
        {
            var cartItem = _mapper.Map <DataModel.CartItem>(ci);

            return(await _cartItemRepository.AddToCart(cartItem));
        }
Exemple #60
0
 public void AddCartItem(CartItem cartItem)
 {
     _orderDAO.AddCartItem(cartItem);
 }