public void AddCourse(int quantity, Course course, ApplicationUser user) { // 1. Avoid duplicate order var isOrderDuplicate = ShoppingCartItems.Select(i => i.CourseId).Contains(course.Id); if (isOrderDuplicate) { throw new ShoppingCartValidationException("Course \"" + course.Title + "\" already in your ShoppingCart."); } // 2. check course state if (!course.IsActivate) { throw new ShoppingCartValidationException("Course \"" + course.Title + "\" is not activate, please remove it from your selection."); } // 3. check user purchase history, avoid duplicate purchase if (user.PurchasedCourses.Any(uc => uc.CourseId == course.Id)) { throw new ShoppingCartValidationException("Course \"" + course.Title + "\" has already purchased, please check your course list."); } // 4. create line item (shoppingCartItem) var shoppingCartItem = LineItem.Create(quantity, this, course); // 4. add shoppingCartItem into shoppingCart ShoppingCartItems.Add(shoppingCartItem); }
public void Clear() { DiscountPercent = 0; DiscountAmount = 0; ShoppingCartItems.Clear(); ShoppingCartCoupons.Clear(); }
public IHttpActionResult PutShoppingCartItems(string id, ShoppingCartItems shoppingCartItems) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != shoppingCartItems.UserID) { return(BadRequest()); } db.Entry(shoppingCartItems).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ShoppingCartItemsExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <IActionResult> PutShoppingCartItems(int id, ShoppingCartItems shoppingCartItems) { if (id != shoppingCartItems.Id) { return(BadRequest()); } _context.Entry(shoppingCartItems).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ShoppingCartItemsExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <ShoppingCartItems> > PostShoppingCartItems(ShoppingCartItems shoppingCartItems) { _context.ShoppingCartItems.Add(shoppingCartItems); await _context.SaveChangesAsync(); return(CreatedAtAction("GetShoppingCartItems", new { id = shoppingCartItems.Id }, shoppingCartItems)); }
public string print() { StringBuilder stringBuilder = new StringBuilder(); var campaignDiscount = getAvailableCampaign(); double couponDiscountPerProduct = getCouponDiscount(); if (couponDiscountPerProduct.CompareTo(0.0) != 0) { couponDiscountPerProduct = getCouponDiscount() / getNumberOfProducts(); } var calculatedDiscounts = new Dictionary <string, double>(); var products = ShoppingCartItems.GroupBy(p => p.Key.Category.Title).ToDictionary(it => it.Key, it => it.ToList()); stringBuilder.AppendLine($"{"Category ",15} {"Product ",15} {"Quantity",15} {"Unit Price",15} {"Total Price",15} {"Total Discount For Campaign", 15} {"Total Discount For Coupon", 15}"); foreach (var item in products) { foreach (var p in item.Value) { stringBuilder.AppendLine($"{item.Key,15} {p.Key.Title,15} {p.Value,15} {p.Key.Price,15} {p.Value * p.Key.Price,15} {getAvailableCampaignDiscountByProduct(calculatedDiscounts,campaignDiscount,p.Key),15} {couponDiscountPerProduct, 15}\t"); } } stringBuilder.AppendLine($"Total Amount: {getTotalAmount()}"); stringBuilder.AppendLine($"Total Amount After Discounts: {getTotalAmountAfterDiscounts()}"); stringBuilder.AppendLine($"Delivery Cost: {getDeliveryCost()}"); return(stringBuilder.ToString()); }
public IHttpActionResult PostShoppingCartItems(ShoppingCartItems shoppingCartItems) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.ShoppingCartItems.Add(shoppingCartItems); try { db.SaveChanges(); } catch (DbUpdateException) { if (ShoppingCartItemsExists(shoppingCartItems.UserID)) { return(Conflict()); } else { throw; } } return(CreatedAtRoute("DefaultApi", new { id = shoppingCartItems.UserID }, shoppingCartItems)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); IdentityRole role = _context.Roles.Find("2"); await UserManager.AddToRoleAsync(user.Id, role.Name); ShoppingCartItems submitedList = new ShoppingCartItems(user.Id); _context.ShoppingCartItems.Add(submitedList); _context.Entry(submitedList).State = System.Data.Entity.EntityState.Added; _context.SaveChanges(); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
private double getAvailableCampaignDiscountByProduct(Dictionary <string, double> calculatedDiscounts, Tuple <Campaign, double> campaignWithDiscount, Product product) { double productDiscount = 0.0; if (campaignWithDiscount.Item1 == null) { return(productDiscount); } if (campaignWithDiscount.Item1.Category != product.Category) { return(productDiscount); } if (calculatedDiscounts != null) { if (calculatedDiscounts.TryGetValue(product.Category.Title, out double discount)) { return(discount); } } var selectedShoppingCartItemsByCategory = ShoppingCartItems.Where(it => it.Key.Category == campaignWithDiscount.Item1.Category).ToDictionary(it => it.Key, it => it.Value); if (selectedShoppingCartItemsByCategory.Count > 0) { productDiscount = campaignWithDiscount.Item2 / selectedShoppingCartItemsByCategory.Count; calculatedDiscounts.Add(product.Category.Title, productDiscount); } return(productDiscount); }
private double calculateCampaignDiscount(Campaign campaign) { if (campaign == null) { throw new ArgumentNullException("campaign is Null"); } double totalAmount = 0; int totalNumberOfProduct = 0; double campaignDiscount = 0; var selectedShoppingCartItemsByCategory = ShoppingCartItems.Where(it => it.Key.Category == campaign.Category).ToDictionary(it => it.Key, it => it.Value); foreach (var item in selectedShoppingCartItemsByCategory) { totalNumberOfProduct += item.Value; totalAmount += (item.Value * item.Key.Price); } if (totalNumberOfProduct <= campaign.MinimumAmount) { return(campaignDiscount); } if (campaign.DiscountType == DiscountType.Rate) { campaignDiscount = totalAmount * (campaign.DiscountAmount / 100); } else { campaignDiscount = campaign.DiscountAmount; } return(campaignDiscount); }
public decimal GetTotalDiscount(ShoppingCartItems ShoppingCartItems) { try { decimal TotalPriceAfterDiscount = 0; // decimal TotalPrice = 0; ShoppingCartItems.Items.ForEach(s => { if (s.Product is BuyMoreGetMoreProduct) { var item = s.Product as BuyMoreGetMoreProduct; var eligibleFreeItems = Math.Floor(Convert.ToDecimal(s.Count / (item.NoOfFreeItems + item.NoOfItemsToBuy))); //Get the number of items which are free var actualFreeItems = eligibleFreeItems * item.NoOfFreeItems; //minus these free items from total var itemsPriceAfterDiscount = CalculateDiscountPrice(s.Product.Discount, s.Product.Price, (s.Count - actualFreeItems)); TotalPriceAfterDiscount += GetBestCategoryDiscount(s, s.Product.Price * s.Count - itemsPriceAfterDiscount); } else { TotalPriceAfterDiscount += GetBestCategoryDiscount(s, CalculateDiscountPrice(s.Product.Discount, s.Product.Price, s.Count)); } //TotalPrice += s.Product.Price * s.Count; }); return(TotalPriceAfterDiscount); } catch (Exception ex) { _logger.LogError("Caught some error: " + ex.Message); return(0); } }
public decimal GetTotal(ShoppingCartItems ShoppingCartItems) { decimal ItemsTotal = 0; ShoppingCartItems.Items.ForEach(s => { ItemsTotal += s.Product.Price * s.Count; }); return(ItemsTotal); }
public ShoppingCartService(ICalculationService CalculationService) { ShoppingCart = new ShoppingCartItems(); ShoppingCart.Id = Guid.NewGuid(); ShoppingCart.Items = new List <CartItem>(); _calculationService = CalculationService; }
public ActionResult DeleteConfirmed(string id) { ShoppingCartItems shoppingCartItems = db.ShoppingCartItems.Find(id); db.ShoppingCartItems.Remove(shoppingCartItems); db.SaveChanges(); return(RedirectToAction("Index")); }
public int getNumberOfDeliveries() { if (ShoppingCartItems == null) { throw new NullReferenceException("ShoppingCartItems is Null"); } return(ShoppingCartItems.GroupBy(it => it.Key.Category.Title).Count());; }
public void RemoveFromCart(Product product) { var productInItem = ShoppingCartItems.Where(x => x.Product.Equals(product)).FirstOrDefault(); if (productInItem != null) { ShoppingCartItems.Remove(productInItem); } }
public void InsertIntoCart(Product product, int quantity) { RemoveFromCart(product); ShoppingCartItems.Add(new ShoppingCartItemDTO() { Product = product, Quantity = quantity }); }
public IHttpActionResult GetShoppingCartItems(string id) { ShoppingCartItems shoppingCartItems = db.ShoppingCartItems.Find(id); if (shoppingCartItems == null) { return(NotFound()); } return(Ok(shoppingCartItems)); }
// GET: Cart public int Add(ShoppingCartItems items) { ShoppingCart cart = (ShoppingCart)Session[WebUtil.CART]; if (cart == null) { cart = new ShoppingCart(); } cart.Add(items); Session.Add(WebUtil.CART, cart); return(cart.NumberOfItems); }
// GET: ShoppingCartItems/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ShoppingCartItems shoppingCartItems = db.ShoppingCartItems.Find(id); if (shoppingCartItems == null) { return(HttpNotFound()); } return(View(shoppingCartItems)); }
static ShoppingCartItems() { if(HttpContext.Current.Session["CSharpShoppingCart"] == null) { Instance = new ShoppingCartItems(); Instance.Items = new List<ShoppingItems>(); HttpContext.Current.Session["CSHarpShoppingCart"] = Instance; } else { Instance = (ShoppingCartItems)HttpContext.Current.Session["CSharpSHoppingCart"]; } }
public IHttpActionResult DeleteShoppingCartItems(int id) { ShoppingCartItems shoppingCartItems = db.ShoppingCartItems.Find(User.Identity.GetUserId()); if (shoppingCartItems == null) { return(NotFound()); } shoppingCartItems.items.Remove(db.ShoppingItems.Find(id)); db.Entry(shoppingCartItems).State = EntityState.Modified; db.SaveChanges(); return(Ok(shoppingCartItems)); }
public ActionResult Order() { ApplicationUser user = db.Users.Find(User.Identity.GetUserId()); ShoppingCartItems items = db.ShoppingCartItems.Find(User.Identity.GetUserId()); for (int i = 0; i < items.items.Count; i++) { items.items.Remove(items.items[i]); i--; } db.Entry(items).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Details")); }
// GET: ShoppingCart/Create public ActionResult AddItemToCart(int id, int quantity = 1) { string Userid = User.Identity.GetUserId(); ShoppingCartItems shoppingCartItems = db.ShoppingCartItems.Find(Userid);//.Where(i => i.UserID.Equals(Userid)).First(); if (shoppingCartItems != null) { ShoppingItem item = db.ShoppingItems.Find(id); shoppingCartItems.Quantity.Add(item.Quantity >= quantity ? quantity : item.Quantity); shoppingCartItems.items.Add(item); db.Entry(shoppingCartItems).State = EntityState.Modified; db.SaveChanges(); } return(Redirect(Request.UrlReferrer.ToString())); }
public void PopulateShoppingCartItemsByLineItems(List <AddItemViewModel> lineItems) { foreach (var lineItem in lineItems) { var item = _context.Items.Find(lineItem.ItemId); var lineItemTotal = item.Price * lineItem.Quantity; ShoppingCartItems.Add(new ShoppingCartLineItemViewModel { ItemId = lineItem.ItemId, Item = item, Quantity = lineItem.Quantity, Total = lineItemTotal }); Total += lineItemTotal; } }
public void PopulateShoppingCartItemsByCustomerId(string customerId) { var lineItems = _context.ShoppingCartLineItems.Include(li => li.Item).Where(li => li.CustomerId == customerId).ToList(); foreach (var lineItem in lineItems) { var lineItemTotal = lineItem.Item.Price * lineItem.Quantity; ShoppingCartItems.Add(new ShoppingCartLineItemViewModel { ItemId = lineItem.ItemId, Item = lineItem.Item, Quantity = lineItem.Quantity, Total = lineItemTotal }); Total += lineItemTotal; } }
// GET: ShoppingCart/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ShoppingCartItems shoppingCartItems = db.ShoppingCartItems.Find(User.Identity.GetUserId()); if (shoppingCartItems == null) { return(HttpNotFound()); } shoppingCartItems.items.Remove(db.ShoppingItems.Find(id)); db.Entry(shoppingCartItems).State = EntityState.Modified; db.SaveChanges(); return(Redirect(Request.UrlReferrer.ToString())); }
public void addItem(Product product, int quantity) { if (product == null) { throw new ArgumentNullException("Product is Null"); } if (quantity > 0) { if (ShoppingCartItems.ContainsKey(product)) { ShoppingCartItems[product] += quantity; } else { ShoppingCartItems.Add(product, quantity); } } }
public void RemoveShoppingCartItem(LineItem item) { // remove item var itemList = ShoppingCartItems.ToList(); itemList.Remove(item); ShoppingCartItems = itemList; // check coupons if not valid then remvove the coupon var lineCoupons = ShoppingCartCoupons.ToList(); var coupons = ShoppingCartCoupons.Select(sc => sc.Coupon); foreach (var c in coupons) { if (!c.IsCouponRulesApplicable(itemList)) { c.Remove(this); lineCoupons.Remove(ShoppingCartCoupons.SingleOrDefault(sc => sc.CouponId == c.Id)); } } ShoppingCartCoupons = lineCoupons; }
public void AddToShoppingCart(int id) { var shoppingCart = GetShoppingCart(); var product = shoppingCart.Find(i => i.Product.ProductsId == id); if (product != null) { product.Pieces++; } else { var toAdd = db.Product.Where(i => i.ProductsId == id).SingleOrDefault(); var NewItem = new ShoppingCartItems { Product = toAdd, Pieces = 1, OrderValue = toAdd.Price }; shoppingCart.Add(NewItem); } session.Set <List <ShoppingCartItems> >(Consts.KoszykSessionKey, shoppingCart); }
public async Task <ShoppingCartItems> AddItemToCart(ShoppingCartAddItemDto dto, int userId) { try { var cartList = await _shoppingCartService.GetListWithShoppingCartItems_ShoppingCarts(x => x.User_Id == userId && x.Status && !x.Is_Deleted); var cart = cartList.FirstOrDefault(); var product = await _productService.Get(x => x.Id == dto.productId); if (product.InStock < dto.quantity) { throw new Exception("no stock"); } else { if (cart != null) { var cartItems = cart.ShoppingCartItems; if (cartItems != null && cartItems.Any(x => x.Product_Id == dto.productId)) { var cartProduct = await _shoppingCartItemService.Get(x => x.Product_Id == dto.productId && x.ShoppingCart_Id == cart.Id); cartProduct.Quantity += dto.quantity; if (product.InStock < cartProduct.Quantity) { throw new Exception("no stock"); } return(await _shoppingCartItemService.Update(cartProduct)); } else { var itemCartItem = new ShoppingCartItems() { Product_Id = dto.productId, Quantity = dto.quantity, ShoppingCart_Id = cart.Id, }; return(await _shoppingCartItemService.Add(itemCartItem)); } } else { var itemCart = new ShoppingCarts() { User_Id = userId, Status = true, Is_Deleted = false, }; var newCart = await _shoppingCartService.Add(itemCart); var itemCartItem = new ShoppingCartItems() { Product_Id = dto.productId, Quantity = dto.quantity, ShoppingCart_Id = newCart.Id, }; return(await _shoppingCartItemService.Add(itemCartItem)); } } } catch (Exception) { throw; } }