async void addToCart_Clicked(System.Object sender, System.EventArgs e) { Button button = (Button)sender; string CurrentProductId = button.CommandParameter.ToString(); Console.Write(CurrentProductId); //bool currentUserEmpty = string.IsNullOrEmpty(App.currentUser.Email); //bool currentCartEmpty = string.IsNullOrEmpty(""+App.currentCart.Id); //App.currentProduct = (Product)productList.curr; if (App.currentCart.Id == null || App.currentCart.Id == string.Empty) { Cart cart = new Cart() { Id = Guid.NewGuid().ToString() }; await App.DatabaseServiceClient.GetTable <Cart>().InsertAsync(cart); App.currentCart = cart; CartProducts cart_products = new CartProducts() { //Id = Guid.NewGuid().ToString(), Cart_id = App.currentCart.Id, Product_id = CurrentProductId }; await App.DatabaseServiceClient.GetTable <CartProducts>().InsertAsync(cart_products); await DisplayAlert("Done", " Product Added", "Ok"); } else { CartProducts cart_products = new CartProducts() { //Id = Guid.NewGuid().ToString(), Cart_id = App.currentCart.Id, Product_id = CurrentProductId }; await App.DatabaseServiceClient.GetTable <CartProducts>().InsertAsync(cart_products); await DisplayAlert("Done", " Product Added ", "Ok"); } }
public void AddItemsToCart(List <char> productIds) { foreach (char item in productIds) { var existingItem = CartProducts.SingleOrDefault(x => x.ProductId == item); if (existingItem != null) { existingItem.Quantity++; } else { CartProducts.Add(new CartProduct() { ProductId = item, Quantity = 1 }); } } }
public async Task AddToCartAsync(string productId, string userId, int quantity = 1) { if (this.IsProductAlreadyInCart(productId, userId)) { var productCart = this.GetProductFromCart(productId, userId); productCart.Quantity += quantity; } else { var cartProduct = new CartProducts { UserId = userId, ProductId = productId, Quantity = quantity }; await this.cartsRepository.AddAsync(cartProduct); } await this.cartsRepository.SaveChangesAsync(); }
public List <CartProducts> FindCartProducts(int cartID) { List <Entity.Cartproduct> entityCart = _context.Cartproducts.Where(x => x.CartId.Equals(cartID)).AsNoTracking().ToList(); List <Model.CartProducts> modelCartProducts = new List <CartProducts>(); if (entityCart.Count == 0) { CartProducts cartProducts = new CartProducts(); cartProducts.CartID = cartID; AddCartProduct(cartProducts); } foreach (Entity.Cartproduct cartProduct in entityCart) { Model.CartProducts modelCartProduct = _mapper.ParseCartProduct(cartProduct); modelCartProducts.Add(modelCartProduct); } _context.SaveChanges(); return(modelCartProducts); }
private bool CheckAddProduct() { if (QuantityOfProduct > 0) { if (!CartProducts.Contains(SelctedProduct)) { return(true); } else { MessageBox.Show("Item already in the cart"); return(false); } } else { MessageBox.Show("You must enter quantity and positive number"); } return(true); }
/// <summary> /// /// </summary> /// <param name="id">ProductId</param> /// <param name="quantity">Quantity</param> /// /// <param name="flag">Flag helps to check product already available in cart and update quantity of selected product on cart</param> /// <returns></returns> public JsonResult Buy(int id, int quantity, bool flag = false) { var user = User.Identity.Name; string Userid = _user.FindById(user).Id; Cart objCart = new Cart(); CartProducts objCartProducts = new CartProducts(); objCart.UserId = Userid; var cartdetails = _cart.FindById(Userid); if (cartdetails == null) { _cart.Create(objCart); cartdetails = _cart.FindById(Userid); } var cartProductDetails = _cartProdrepo.FindById(cartdetails.Id, id); if (cartProductDetails == null) { objCartProducts.CartId = cartdetails.Id; objCartProducts.productId = id; objCartProducts.quantity = quantity; _cartProdrepo.Create(objCartProducts); cartProductDetails = _cartProdrepo.FindById(cartdetails.Id, id); } else { // update quantity if already available if (flag) { cartProductDetails.quantity = quantity; } else { cartProductDetails.quantity = cartProductDetails.quantity + quantity; } _cartProdrepo.Update(cartProductDetails); } return(Json(quantity)); //return RedirectToAction("Index"); }
public string Print() { StringBuilder sb = new StringBuilder(); sb.Append("Category").Append("\t").Append("Product").Append("\t").Append("\t").Append("Quantity").Append("\t").Append("Unit Price").Append("\t").Append("Total Price").Append("\t").Append("Total Dicount").Append("\t"); sb.AppendLine(); var groupedProducts = CartProducts.GroupBy(x => x.Product.Category).Select(group => new { Category = group.Key, CartProduct = group.ToList() }); foreach (var groupedProduct in groupedProducts) { foreach (var cartProduct in groupedProduct.CartProduct) { var campaignDiscountPerItem = 0m; var couponDiscountPerItem = CouponDiscountTotal / CartProducts.Sum(x => x.Quantity) * cartProduct.Quantity; if (CampaignDiscount != null && groupedProduct.Category.Guid == CampaignDiscount.Category.Guid) { campaignDiscountPerItem = CampaignDiscountTotal / groupedProduct.CartProduct.Sum(x => x.Quantity) * cartProduct.Quantity; } var totalDiscount = campaignDiscountPerItem + couponDiscountPerItem; sb.Append(groupedProduct.Category.Title); sb.Append("\t"); sb.Append(cartProduct.Product.Title); sb.Append("\t"); sb.Append(cartProduct.Quantity); sb.Append("\t"); sb.Append(cartProduct.Product.Price); sb.Append("\t"); sb.Append(cartProduct.Product.Price * cartProduct.Quantity); sb.Append("\t"); sb.Append(totalDiscount); sb.AppendLine(); //sb.AppendLine($"{groupedProduct.Category.Title} || {cartProduct.Product.Title} || {cartProduct.Quantity} || {cartProduct.Product.Price} || {cartProduct.Product.Price * cartProduct.Quantity} || {totalDiscount}"); } } sb.AppendLine($"Total Amount : {NetTotalPrice}"); sb.AppendLine($"Total Delivery Cost : {DeliveryCost}"); return(sb.ToString()); }
public void LoadCartFromFile() { OpenFileDialog openFileDialog1 = new OpenFileDialog { Filter = "Date File|*.dat", Title = "Open file Shopping Cart" }; openFileDialog1.ShowDialog(); var fileName = openFileDialog1.FileName; if (fileName.Any()) { CartProducts.Clear(); } _appManager.LoadShoppingCart(fileName); CalculateCartPrice(); }
/// <summary> /// Method used to store user selected items in session /// </summary> /// <param name="selectedItem"></param> /// <returns></returns> public JsonResult ToggleCartSelection(ProductAddedToCart selectedItem) { var itemsInCart = _session.Get <CartProducts>(SessionKey.CART_ITEMS); if (itemsInCart == null) { itemsInCart = new CartProducts() { CartItems = new List <ProductAddedToCart>() }; } if (itemsInCart.CartItems.Any(x => x.ProductId == selectedItem.ProductId)) { itemsInCart.CartItems.RemoveAll(x => x.ProductId == selectedItem.ProductId); } else { itemsInCart.CartItems.Add(selectedItem); } _session.Set <CartProducts>(SessionKey.CART_ITEMS, itemsInCart); return(Json(itemsInCart)); }
public void ExportExcelFile() { if (!CartProducts.Any()) { MessageBox.Show("Empty Cart"); return; } SaveFileDialog saveFileDialog1 = new SaveFileDialog { Filter = "Date Data|*.xls", Title = "Save Shopping Cart" }; saveFileDialog1.ShowDialog(); var fileName = saveFileDialog1.FileName; if (fileName.Any()) { _appManager.CreatExcelFileShoppingCart(fileName); } }
public void AddItem(Product product, decimal Quantity) { CartProducts.Add(new CartProduct { Product = product, Quantity = Quantity }); }
public void Start() { //Select customer Console.WriteLine("Enter customer ID: "); Customer buyer = _biz.SearchCustomerByID(Int32.Parse(Console.ReadLine())); if (buyer == null) { Console.WriteLine("No customers found."); return; } else { Console.WriteLine("Customer Found!"); Console.WriteLine(MainMenu.linebreak); Console.WriteLine(buyer.ToString()); Console.WriteLine(MainMenu.linebreak); Console.WriteLine(MainMenu.presskey); Console.ReadLine(); } //Select location Console.WriteLine("Choose location:"); Console.WriteLine("[100] Philadelphia, PA"); Console.WriteLine("[200] New York City, NY"); int localWeWant = Int32.Parse(Console.ReadLine()); if (localWeWant != 100 && localWeWant != 200) { Console.WriteLine("Not a valid location."); Console.WriteLine(MainMenu.presskey); Console.ReadLine(); return; } Cart cart = _biz.newCart(buyer.CustomerID); //Cart Creation List <Inventory> localinventory = _biz.GetInventory(localWeWant); //Sets inventory to only have location inventory foreach (Inventory i in localinventory) { Record iR = _biz.SearchRecordByID(i.RecID); Console.WriteLine(iR.ToString()); Console.WriteLine(MainMenu.linebreak); } Console.WriteLine("Which record would you like to buy?"); Console.WriteLine("Enter record ID: "); int RecIDWeWant = Int32.Parse(Console.ReadLine()); Record foundRecord = _biz.SearchRecordByID(RecIDWeWant); if (foundRecord == null) { Console.WriteLine("No record found."); return; } int recInInv = localinventory.FindIndex(x => x.RecID == RecIDWeWant); if (recInInv < 0) { Console.WriteLine("Record not in local inventory!"); Console.WriteLine(MainMenu.presskey); Console.ReadLine(); return; } Console.WriteLine(foundRecord.ToString()); Console.WriteLine(MainMenu.linebreak); //Quantity select Console.WriteLine("How many would you like to buy?"); int BuyerQuan = Int32.Parse(Console.ReadLine()); //New cartProducts CartProducts cartProducts = new CartProducts(); cartProducts.RecID = foundRecord.RecID; cartProducts.RecQuan = BuyerQuan; cartProducts.CartID = cart.CartID; //Add cartProducts to database _biz.AddToCartProducts(cartProducts); Console.WriteLine(MainMenu.linebreak); //Order confirmation and total float total = 0; //TODO: Convert prices from floats to decimal Console.WriteLine("Confirm order: "); Console.WriteLine(MainMenu.linebreak); List <CartProducts> cartProdList = _biz.GetCartProducts(); foreach (CartProducts c in cartProdList) { Record boughtRecord = _biz.SearchRecordByID(c.RecID); float subtotal = c.RecQuan * boughtRecord.Price; Console.WriteLine(boughtRecord.ToString()); Console.WriteLine("Quantity: " + c.RecQuan); Console.WriteLine(MainMenu.linebreak); total = total + subtotal; } Console.WriteLine("Total: " + total); //Reset Total total = 0; Order finalOrder = new Order(); finalOrder.CartID = cart.CartID; finalOrder.Customer = buyer; finalOrder.CusID = buyer.CustomerID; finalOrder.localID = localWeWant; finalOrder.OrDate = DateTime.Now; _biz.AddOrder(finalOrder); //adding orderProducts to database OrderProducts orderProcessed = new OrderProducts(); //orderProcessed.RecQuan = 0; orderProcessed.OrdID = finalOrder.OrdID; orderProcessed.RecID = cartProducts.RecID; orderProcessed.RecQuan = cartProducts.RecQuan; _biz.addOrderProducts(orderProcessed); foreach (CartProducts c in cartProdList) { _biz.PurgeCartProducts(cartProducts); } /*TODO: Implement purgecart maybe?? I have a feeling if I do this * it's gonna break some more code, and I don't wanna do that rn. */ //_cartBL.PurgeCart(cart) Console.WriteLine("Order bought."); Console.WriteLine(MainMenu.presskey); Console.ReadLine(); }
public CartProducts AddCartProduct(CartProducts newCartProduct) { _context.Cartproducts.Add(_mapper.ParseCartProduct(newCartProduct)); _context.SaveChanges(); return(newCartProduct); }
public bool Delete(CartProducts entity) { _dbContext.Remove(entity); return(Save()); }
public void AddToCartProducts(CartProducts cartProducts) { _repo.AddToCartProducts(cartProducts); }
public bool Create(CartProducts entity) { _dbContext.Add(entity); return(Save()); }
public DeliveryInfo calculateDelivery([FromBody] CartProducts cartProducts) { return(_deliveryService.calculateFor(cartProducts)); }
public void RemoveCartProducts(CartProducts cartProducts) { _repo.RemoveCartProducts(cartProducts); }
public void AddCartProduct(CartProducts newCartProduct) { _repo.AddCartProduct(newCartProduct); }
//public async Task<OperationResponse<List<OrderReponseModel>>> GetHistoryOrders(decimal delivertClientID) //{ // OperationResponse<List<OrderReponseModel>> or = new OperationResponse<List<OrderReponseModel>>(); // try // { // //get headers with client id and details with headerID // // get customer headers of orders // var headers = await context.PoscurrentDailyTransHeader.Where(h => h.ClientId == delivertClientID && h.FkInvoiceStatusId == 4 /*Paid*/).ToListAsync(); // List<OrderReponseModel> result = new List<OrderReponseModel>(); // foreach (var item in headers) // { // var detailsData = await context.PoscurrentDailyTransDetails.Where(d => d.HeaderId == item.HeaderId).ToListAsync(); // result.Add(new OrderReponseModel() // { // header = item, // details = detailsData // }); // } // or.Data = result; // } // catch (Exception ex) // { // or.HasErrors = true; // or.Message = ex.Message; // } // return or; //} public async Task <OperationResponse <object> > reorder(decimal deliveryClientID, decimal HeaderID, int clearCart) { OperationResponse <object> or = new OperationResponse <object>(); try { // get headers with client id and details with headerID // get customer headers of orders var headerID = getNextHeaderID(); if (clearCart == 1) { var res = context.CartProducts.Where(a => a.FkDeliveryClientId == deliveryClientID).ToList(); context.CartProducts.RemoveRange(res); context.SaveChanges(); } var header = await context.PoscurrentDailyTransHeader.Where(h => h.HeaderId == HeaderID).Include(d => d.PoscurrentDailyTransDetails).FirstOrDefaultAsync(); foreach (var item in header.PoscurrentDailyTransDetails) { //abdelrhman mohamed start 15-1-2021 bool isItemExist = await context.CartProducts.Where(i => i.FkDeliveryClientId == deliveryClientID && i.FkItemId == item.ItemId).AnyAsync(); //abdelrhman mohamed end 15-1-2021 if (isItemExist) { var cartProItem = await context.CartProducts.Where(i => i.FkDeliveryClientId == deliveryClientID && i.FkItemId == item.ItemId).FirstAsync(); var returnItem = await context.OrderProducts.FromSql("getCartItemsByItemIDAndUserID @p0,@p1", cartProItem.FkDeliveryClientId, cartProItem.FkItemId).FirstAsync(); if ((cartProItem.quantity + item.Qty) >= returnItem.MaxOrderQuantity) { return(returnStatus(((decimal)returnItem.MaxOrderQuantity - cartProItem.quantity) + 1)); } else { cartProItem.quantity = cartProItem.quantity + item.Qty; var addedItem = context.CartProducts.Update(cartProItem); var rowsEffected = context.SaveChanges(); if (rowsEffected > 0) { // returnItem.quantity = cartProItem.quantity; //abdelrhman mohamed start 15-1-2021 or.Data = true; or.StatusCode = "200"; or.Message = "Success"; //abdelrhman mohamed end 15-1-2021 } } } else { CartProducts cartObj = new CartProducts(); cartObj.FkDeliveryClientId = deliveryClientID; cartObj.quantity = item.Qty; cartObj.FkItemId = item.ItemId; cartObj.fkPackageID = item.PackageId; cartObj.fk_itemBarCodeID = item.FkItemBarcodeId; cartObj.InsertDateTime = DateTime.Now; var addedItem = context.CartProducts.Add(cartObj); var rowsEffected = context.SaveChanges(); if (rowsEffected > 0) { //abdelrhman mohamed start 15-1-2021 or.Data = true; or.StatusCode = "200"; or.Message = "Success"; //abdelrhman mohamed end 15-1-2021 } } } //await CartService.AddItemToUserCart() header.FkInvoiceStatusId = 4;//old; context.SaveChanges(); or.Data = true; } catch (Exception ex) { or.Data = false; or.HasErrors = true; or.Message = ex.Message; } return(or); }
public bool Update(CartProducts entity) { _dbContext.Update(entity); return(Save()); }
public void createCartProducts(CartProducts cartProducts) { _cartProductDAL.Add(cartProducts); }
public void PurgeCartProducts(CartProducts cartProductsforDeletion) { _repo.PurgeCartProducts(cartProductsforDeletion); }
public void GetFilteredProductsForProcessing(string searchTerm, int cartID, List <Inventory> inventories, Location location) { //keeps track of the product if only 1 product is found Product foundProduct = new Product(); //tracks how many products have been found given the search int tracker = 0; LineSeparator line = new LineSeparator(); //retrieves a list of all products List <Product> productList = _productBL.GetProduct(); //new list intended to filter products down to only those that exist in inventories for our location List <Product> filteredByInventoryProducts = new List <Product>(); //our list of filtered inventories List <Inventory> filteredByLocationInventories = new List <Inventory>(); //filter inventories to only those at our location //if the location ID of this inventory matches our stored location ID, then add it to the list of filtered locations foreach (Inventory i in inventories) { if (i.Location.LocationID == location.LocationID) { filteredByLocationInventories.Add(i); } } //filter products to display only those that exist in one of the found inventories //for each product that we've retrieved, make sure that the product ID matches a product ID stored in an inventory foreach (Product p in productList) { foreach (Inventory i in filteredByLocationInventories) { if (i.ProductID == p.ProductID) { filteredByInventoryProducts.Add(p); } } } foreach (Product product in filteredByInventoryProducts) { if (product.ProductName.Contains(searchTerm) || product.Manufacturer.Contains(searchTerm) || product.ProductID.ToString().Contains(searchTerm)) { line.LineSeparate(); Console.WriteLine(product); tracker++; //for the first found customer, store in our foundcustomer object, but don't do it again if (tracker == 1) { foundProduct.ProductID = product.ProductID; foundProduct.ProductName = product.ProductName; foundProduct.ProductDescription = product.ProductDescription; foundProduct.Manufacturer = product.Manufacturer; foundProduct.ProductPrice = product.ProductPrice; } } } if (tracker == 0) { line.LineSeparate(); Console.WriteLine("No results found! Please double-check customer name spelling. \nReminder: This search system is Case Sensitive :)"); } //if the tracker only happened once, that means one customer with the matching value was found, so we pass that customer reference //back out to our manager system :) if (tracker == 1) { line.LineSeparate(); Console.WriteLine("We have found one product from your search. Please see the details displayed above."); Console.WriteLine("Would you like to add this product to your cart?"); Console.WriteLine("[0] Yes"); Console.WriteLine("[1] No"); switch (Console.ReadLine()) { case "0": CartProducts cartProduct = new CartProducts(); List <Inventory> inventoriesFiltered = new List <Inventory>(); //we need to check if the specified inventory has said product in stock for the amount desired foreach (Inventory i in inventories) { if (i.ProductID == foundProduct.ProductID && i.InventoryLocation == location.LocationID) { inventoriesFiltered.Add(i); } } Inventory realInventory = inventoriesFiltered[0]; Console.WriteLine($"We currently have {realInventory.ProductQuantity} of these in stock at the {location.LocationName} location!"); Console.WriteLine("Please enter how many you would like to order: "); cartProduct.ProductCount = Int32.Parse(Console.ReadLine()); if (realInventory.ProductQuantity < cartProduct.ProductCount) { Console.WriteLine($"Sorry, we only have {realInventory.ProductQuantity} left in stock at {location.LocationName}.\nPlease enter a lower quantity"); Console.WriteLine("Press enter to continue."); break; } if (cartProduct.ProductCount <= 0) { Console.WriteLine("Sorry, you've entered an invalid value. Please try again"); Console.WriteLine("Press enter to continue."); Console.ReadLine(); break; } cartProduct.CartID = cartID; cartProduct.ProductID = foundProduct.ProductID; realInventory.ProductQuantity = realInventory.ProductQuantity - cartProduct.ProductCount.Value; Console.WriteLine($"current inventory value: {realInventory.ProductQuantity}"); _cartProductsBL.AddCartProduct(cartProduct); _inventoryBL.UpdateInventory(realInventory); Log.Information($"product added to cart {cartProduct.ProductID}"); Console.WriteLine("Product added to cart successfully!"); Console.WriteLine("Press enter to continue."); Console.ReadLine(); break; case "1": Console.WriteLine("Okay, please search again to find a different product. \nPress enter to continue."); Console.ReadLine(); break; default: Console.WriteLine("This is not a valid menu option!"); break; } } line.LineSeparate(); }
public double CalculateCost() { return(CartProducts.Select(p => Cart[p.Sku].Quantity * p.Price).Sum()); }