public MenuViewModel(Menu menu, Cart cart) { List<CartLine> tempLines = new List<CartLine>(); foreach (var dish in menu.Dishes) { CartLine line = new CartLine() {Dish = dish}; if (cart.Contains(dish)) { line.Quantity = cart.Get(dish).Quantity; } tempLines.Add(line); } Starters = tempLines .Where(x => x.Dish.DishType == DishType.Starter) .ToList(); MainDishes = tempLines .Where(x => x.Dish.DishType == DishType.MainDish) .ToList(); Deserts = tempLines .Where(x => x.Dish.DishType == DishType.Desert) .ToList(); }
public void AddToCart(Product p) { if (lineItems.Find(li=>li.product.ProductID==p.ProductID)!=null) { CartLine cartLine = lineItems.Find(li => li.product.ProductID == p.ProductID); cartLine.quantity += 1; } else { CartLine cartLine = new CartLine(); cartLine.product = p; cartLine.quantity = 1; lineItems.Add(cartLine); } }
[HttpPost] // it is critical that the parameter has the same name as the <select> tag. public IActionResult CartLineForm(string itmSelect) // ---------------------------------------- { // action method to display info from CiFilteredList.itmSelect <select>tag return // from CartForm if (itmSelect != null) { CartLine cl; CatalogItem c = repository.CatalogItems.FirstOrDefault(ci => ci.ItemId == itmSelect); // cast CatalogItem object to CartLine type cl = new CartLine(c); // call CartForm view to enable input additional information as CartLine return View(cl); } else { return RedirectToAction("/Home/Index"); } } //eo CartLineForm -----------------------------------------------------------------------------
/// <summary> /// Creates the cart. /// </summary> /// <returns>Cart with one line item.</returns> public Cart CreateCart() { var shoppingCartId = GenerateTransactionId(); var cart = new Cart { Id = shoppingCartId, CustomerId = this.Customer.AccountNumber, CartType = CartType.Checkout }; OrderManager.CreateOrUpdateCart(cart, 0); //// get cart line from the product var variants = this.Product.CompositionInformation.VariantInformation.IndexedVariants; var variantId = variants.Keys.FirstOrDefault(); var productVariant = variants[variantId]; var cartLines = new Collection <CartLine>(); var cartLine = new CartLine(); var cartLineData = new CartLineData { ItemId = productVariant.ItemId, InventoryDimensionId = productVariant.InventoryDimensionId, ProductId = productVariant.DistinctProductVariantId, Quantity = 1, Comment = string.Empty, ["ProductDetails"] = string.Empty }; cartLine.LineData = cartLineData; cartLines.Add(cartLine); var modes = CalculationModes.Totals | CalculationModes.Discounts | CalculationModes.Prices; return(OrderManager.AddCartLines(shoppingCartId, this.Customer.AccountNumber, cartLines, new CalculationModes?(modes))); }
/// <summary> /// Initializes a new instance of the <see cref="UpdateLinesOnCartTest"/> class. /// </summary> public UpdateLinesOnCartTest() { this.visitorId = Guid.NewGuid(); this.lineToUpdate = new CartLine { ExternalCartLineId = "LineId2", Product = new CartProduct { ProductId = "100500", Price = new Price { Amount = 100 } }, Quantity = 12 }; this.cart = new Cart { ExternalId = this.visitorId.ToString(), Lines = new ReadOnlyCollection <CartLine>(new List <CartLine> { new CartLine(), this.lineToUpdate }) }; this.request = new UpdateCartLinesRequest(this.cart, new[] { this.lineToUpdate }); this.result = new CartResult(); this.args = new ServicePipelineArgs(this.request, this.result); this.client = Substitute.For <ICartsServiceChannel>(); var clientFactory = Substitute.For <ServiceClientFactory>(); clientFactory.CreateClient <ICartsServiceChannel>(Arg.Any <string>(), Arg.Any <string>()).Returns(this.client); this.processor = new UpdateLinesOnCart { ClientFactory = clientFactory }; }
public ActionResult OrderList(int page = 1, int category = 0) { List <OrderDetailItem> orderDetailItemList = _orderDetailService.GetAllItems(); string actionName = CookieHelper.GetPropertyNameFromCookies("action"); string controllerName = CookieHelper.GetPropertyNameFromCookies("controller"); CartLine cartList = new CartLine(); string userName = ""; bool isCompleted = false; int orderNumber = 0; foreach (var item in orderDetailItemList) { cartList = JsonConvert.DeserializeObject <CartLine>(item.List); userName = item.UserName; isCompleted = item.IsCompleted; orderNumber = item.OrderDetailId; } OrderDetailViewModel orderDetailViewModel = new OrderDetailViewModel { OrderDetailItemList = orderDetailItemList.Skip((page - 1) * PageSize).Take(5).ToList(), CartList = cartList, UserName = userName, IsCompleted = isCompleted, OrderNumber = orderNumber, Route = String.Format("/{0}/{1}", controllerName, actionName), PagingInfo = new PagingInfo { ItemsPerPage = PageSize, TotalItems = orderDetailItemList.Count(), CurrentPage = page, CurrentCategory = category } }; return(View(orderDetailViewModel)); }
public void ShouldLeaveThePriceIntactIfFailedToRetrievePrices() { // arrange var cartLine = new CartLine { Product = new CartProduct { ProductId = "TestProductId" } }; this.cart.Lines = new ReadOnlyCollectionAdapter <CartLine> { cartLine }; var result = new GetProductPricesResult(); this.pricingService.GetProductPrices(Arg.Is <GetProductPricesRequest>(r => r.ProductId == "TestProductId")).Returns(result); // act var cartModel = this.service.GetCart(); // assert cartModel.Lines.Single().Product.Price.Should().BeNull(); }
public void Can_Mark_Shipped() { // Arrange var mock = new Mock <IOrderRepository>(); var cartLine = new CartLine { Product = new Product(), Quantity = 1 }; var order = new Order { OrderId = 1, Shipped = false, Lines = new[] { cartLine } }; mock.Setup(m => m.Orders).Returns(new[] { order }.AsQueryable()); var controller = new OrderController(mock.Object, new Cart()); // Act var result = controller.MarkShipped(1) as RedirectToActionResult; // Assert mock.Verify(m => m.SaveOrder(order), Times.Once); Assert.True(order.Shipped); Assert.Equal("List", result.ActionName); }
public virtual void Initialize(Order order) { this.OrderId = order.OrderID; foreach (CartLine line in order.Lines) { CartLine orderLine = line; OrderLineVariantRenderingModel model = this.ModelProvider.GetModel <OrderLineVariantRenderingModel>(); Party party = null; ShippingInfo shipping = order.Shipping.FirstOrDefault(s => s.LineIDs.ToList().Contains(orderLine.ExternalCartLineId)); if (shipping != null) { party = order.Parties.FirstOrDefault(p => p.ExternalId.Equals(shipping.PartyID, StringComparison.OrdinalIgnoreCase)); } model.Initialize(orderLine, shipping, party); this.Lines.Add(model); } this.StoreOrder = order.Status.ToLower() == "storeorder" ? true : false; this.StoreName = !String.IsNullOrEmpty(order.ShopName) ? GetDisplayName(order.ShopName) : ""; this.TrackingNumber = order.TrackingNumber; this.InitializeDataSourceValues(); }
//This is the base method that enables an item to be added to a cart public virtual void AddItem(Book book, int qty) { //grab the line that stores the book that is being added CartLine line = Lines .Where(p => p.Book.BookID == book.BookID) .FirstOrDefault(); //If nothing is returned, the book is not currently in the Lines list //If that is the case, add the book to the list and set the qty of for that book if (line == null) { Lines.Add(new CartLine { Book = book, Quantity = qty }); } //If the book is already in the list, increase the quantity else { line.Quantity += qty; } }
/// <summary> /// Adds specified quantity of product to cart. /// </summary> /// <param name="cart">Cart</param> /// <param name="product">Add this product to cart.</param> /// <param name="quantity">Add specified quantity.</param> public void AddItem(Cart cart, Product product, int quantity = 1) { CartLine line = cart.CartLines ?.Where(p => p.Product.ID == product.ID) .DefaultIfEmpty() .FirstOrDefault(); if (line == null) { line = new CartLine { Product = product, Quantity = quantity, Cart_Id = cart.ID }; cart.CartLines.Add(line); } else { line.Quantity += quantity; } Update(cart); }
public void When_Map_CartLine_To_ViewModel_Expect_Valid_Properties() { //Arrange var cartLine = new CartLine() { Amount = 5, Id = 1, Product = new Product() { Description = "description", Id = 15, Name = "name", Price = 19.95 } }; //Act var viewModel = _mapper.Map <CartLineViewModel>(cartLine); //Assert Assert.Equal(cartLine.Id, viewModel.Id); Assert.Equal(cartLine.Amount, viewModel.Amount); Assert.Equal(cartLine.Product.Id, viewModel.Product.Id); Assert.Equal(cartLine.Product.Description, viewModel.Product.Description); Assert.Equal(cartLine.Product.Name, viewModel.Product.Name); Assert.Equal(cartLine.Product.Price, viewModel.Product.Price); Assert.Equal(cartLine.Product.Price * cartLine.Amount, viewModel.TotalPrice); }
//Pass in the project object and the quantity public void AddItem(Project proj, int quant) { //New instance of a cart line, created here //Go out to lines and look first in the list for the BookId and the one that's been added CartLine line = Lines .Where(p => p.Project.BookId == proj.BookId) .FirstOrDefault(); //Check if they match, and if not add a new CartLine if (line == null) { Lines.Add(new CartLine { Project = proj, Quantity = quant }); } //Otherwise, update quantity else { line.Quantity += quant; } }
public void CalcualteTotal(List <CartLine> cartLines) { decimal total; // seperate out each kind of prodcut from the orderlist and // apply the promotional discount accordingly. CartLine productA = new CartLine(); CartLine productB = new CartLine(); CartLine productC = new CartLine(); foreach (CartLine cartline in cartLines) { if (cartline.Product.Name == ProductType.A) { productA = cartline; } if (cartline.Product.Name == ProductType.B) { productB = cartline; } if (cartline.Product.Name == ProductType.c) { productC = cartline; } } ComputeTotalValueBase computeTotalA = CartLineComputeTotalService.GetComputedPaymentFor(ProductType.A); Buy1Get1Total = computeTotalA.ComputeTotalValue(productA); ComputeTotalValueBase computeTotalB = CartLineComputeTotalService.GetComputedPaymentFor(ProductType.B); ThreeFor10Total = computeTotalB.ComputeTotalValue(productB); ComputeTotalValueBase computeTotalC = CartLineComputeTotalService.GetComputedPaymentFor(ProductType.c); NoOfferTotal = computeTotalC.ComputeTotalValue(productC); Total = Buy1Get1Total + ThreeFor10Total + NoOfferTotal; }
public ManagerResponse <CartResult, Cart> UpdateLineItemsInCart(Cart cart, IEnumerable <CartLineArgument> cartLines, string giftCardProductId, string giftCardPageLink) { Assert.ArgumentNotNull(cart, nameof(cart)); Assert.ArgumentNotNull(cartLines, nameof(cartLines)); var cartLineList = new List <CartLine>(); foreach (CartLineArgument cartLine in cartLines) { Assert.ArgumentNotNullOrEmpty(cartLine.ProductId, "inputModel.ProductId"); Assert.ArgumentNotNullOrEmpty(cartLine.CatalogName, "inputModel.CatalogName"); Assert.ArgumentNotNull(cartLine.Quantity, "inputModel.Quantity"); decimal quantity = cartLine.Quantity; bool Selector(CartLine x) { var product = (CommerceCartProduct)x.Product; return(x.Product.ProductId == cartLine.ProductId && product.ProductVariantId == cartLine.VariantId && product.ProductCatalog == cartLine.CatalogName); } CartLine commerceCartLine = cart.Lines.FirstOrDefault(Selector) ?? new CommerceCartLine(cartLine.CatalogName, cartLine.ProductId, cartLine.VariantId == "-1" ? null : cartLine.VariantId, quantity); commerceCartLine.Quantity = quantity; cartLineList.Add(commerceCartLine); } var request = new UpdateCartLinesRequest(cart, cartLineList); var updateCartResult = this.cartServiceProvider.UpdateCartLines(request); if (!updateCartResult.Success) { updateCartResult.SystemMessages.LogSystemMessages(this); } return(new ManagerResponse <CartResult, Cart>(updateCartResult, updateCartResult.Cart)); }
private void SetQteOrItem(decimal qte, CartLine cart) { try { var exited = CurrentTicket?.CarteLines?.Where(a => a == cart).FirstOrDefault(); if (exited != null) {// Just add qts exited.Qts = qte; } else { //AllCartLines?.Add(cart); } if (CurrentTicket != null) { CurrentTicket.EstEnvoyerCuisine = false; } CreateCartLines(); } catch (Exception s) { MessageQueue.Enqueue(s.Message); } }
public async void When_CartLine_Is_Updated_Expect_Ok_StatusCode_And_Updated_Amount() { //Arrange var newAmount = 10; var product = _fixture.GenerateProduct(); var newCartLine = new CartLine() { ProductId = product.Id, Amount = 5 }; await _fixture.Context.CartLines.AddAsync(newCartLine); await _fixture.Context.SaveChangesAsync(); var content = new StringContent(JsonConvert.SerializeObject(new UpdateCartLineDTO() { LineId = newCartLine.Id, Amount = newAmount }), Encoding.UTF8, "application/json"); //Act var response = await _fixture.Client.PutAsync("api/cart/" + newCartLine.Id, content); //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); var viewModel = JsonConvert.DeserializeObject <CartLineViewModel>(result); Assert.Equal(newCartLine.Id, viewModel.Id); Assert.Equal(newAmount, viewModel.Amount); await _fixture.Context.Entry(newCartLine).ReloadAsync(); //reload entity to refresh data ; Assert.Equal(newAmount, newCartLine.Amount); }
public Result <CartModel> UpdateProductVariantQuantity(string productId, string variantId, decimal quantity) { ManagerResponse <CartResult, Cart> model = this.CartManager.GetCurrentCart(this.StorefrontContext.ShopName, this.VisitorContext.ContactId); CartLine cartLine = model.Result.Lines.FirstOrDefault(x => { var current = x.Product as CommerceCartProduct; return(current?.ProductId == productId && current?.ProductVariantId == variantId); }); if (cartLine != null) { if (quantity <= 0) { return(this.RemoveProductVariantFromCart(cartLine.ExternalCartLineId)); } var cartLineArgument = new CartLineArgument { CatalogName = this.StorefrontContext.CatalogName, ProductId = productId, Quantity = quantity, VariantId = variantId }; ManagerResponse <CartResult, Cart> cart = this.CartManager.UpdateLineItemsInCart(model.Result, new[] { cartLineArgument }, null, null); Result <CartModel> result = this.GetCart(cart.ServiceProviderResult, cart.Result); return(result); } else if (quantity > 0) { return(this.AddProductVariantToCart(productId, variantId, quantity)); } return(null); }
//the Virtual keyword will allow you to override members of a class public virtual void AddItem(Book book, int qty) //public void AddItem(Book book, int qty, double price) { //the next block will check to see if you have the selected item in your cart CartLine line = Lines .Where(b => b.Book.BookId == book.BookId) .FirstOrDefault(); //if you don't, it'll add it to the cart if (line == null) { Lines.Add(new CartLine { Book = book, Quantity = qty //Price = (decimal)price }); } //if you do, it'll update the quantity rather than adding the item twice else { line.Quantity += qty; } }
/// <summary> /// Initializes a new instance of the <see cref="CartLineModel" /> class. /// </summary> /// <param name="line">The line.</param> /// <param name="productName">Name of the product.</param> public CartLineModel([NotNull] CartLine line, string productName = null) { Assert.ArgumentNotNull(line, "line"); this.Id = line.ExternalCartLineId; this.Quantity = line.Quantity; if (line.Product != null) { this.ProductId = line.Product.ProductId; if (line.Product.Price != null) { this.UnitPrice = line.Product.Price.Amount; } this.ProductName = productName ?? line.Product.ProductId; } if (line.Total != null) { this.TotalPrice = line.Total.Amount.ToString("C", Context.Language.CultureInfo); } }
public void ShouldGetPriceForProduct() { // arrange var cartLine = new CartLine { Product = new CartProduct { ProductId = "TestProductId" } }; this.cart.Lines = new ReadOnlyCollectionAdapter <CartLine> { cartLine }; var result = new GetProductPricesResult(); result.Prices.Add("List", new Price(10.50m, "USD")); this.pricingService.GetProductPrices(Arg.Is <GetProductPricesRequest>(r => r.ProductId == "TestProductId")).Returns(result); // act var cartModel = this.service.GetCart(); // assert cartModel.Lines.Single().Product.Price.Amount.Should().Be(10.50m); }
/// <summary> /// Changes the lines. /// </summary> /// <param name="cartModel">The cart model.</param> /// <param name="client">The client.</param> /// <param name="cartLine">The cart line.</param> /// <returns>The changed cart model.</returns> protected override ShoppingCartModel ChangeLines(ShoppingCartModel cartModel, ICartsServiceChannel client, CartLine cartLine) { if (cartLine.Product != null) { cartModel = client.UpdateQuantity(cartModel.CustomerGuid, cartLine.Product.ProductId, (int)cartLine.Quantity); } return cartModel; }
public JsonResult AddToCart(Cart cart, string productId, int quantity = 1) { bool addNew = false; var warningMessage = ""; if (quantity < 0) { quantity = 1; } var product = _productRepo.FindById(productId); if (product != null) { CartLine line = cart.LineCollection.Where(p => p.Product.Id == product.Id).FirstOrDefault(); if (product.Quantity != 0) { if (quantity != 0) { if (line == null) { line = new CartLine { Product = product, Quantity = quantity }; product.Images = _productRepo.GetImages(product.Id).ToList(); if (product.Images.Count == 0) { product.Images.Add(ImageLinks.BrokenProductImage); } cart.LineCollection.Add(line); addNew = true; } else { line.Quantity += quantity; } } if (line.Quantity > product.Quantity) { line.Quantity = product.Quantity; warningMessage = "Some product is out of stock, so you can only set max quantity we have in stock!"; } } else { warningMessage = "Some product is out of stock, so you can only set max quantity we have in stock!"; } } return(Json(new { success = true, addNew = addNew, warningMessage = warningMessage, cart = cart, summary = cart.Summary, summaryQuantity = cart.SummaryQuantity })); }
public ActionResult UpdateQuantity(Cart cart, CartLine line) { CartLine lineItem = cart.Lines.First(p => p.Product.ProductID == line.Product.ProductID); lineItem.Quantity = line.Quantity; CartIndexViewModel model = new CartIndexViewModel { Cart = cart, ReturnUrl = "", Total = cart.ComputeTotalValue() }; //return Json(new { success = true, lineTotal = lineItem.LineTotal, total = cart.ComputeTotalValue() }); return Json(new {success = true, model}); }
private static CommerceShippingInfo GetOrderLineShippingInfo(CommerceOrder commerceOrder, CartLine orderLine) { var uniqueShippingInfo = commerceOrder.Shipping.FirstOrDefault(shipping => shipping.LineIDs.ToList().Contains(orderLine.ExternalCartLineId) && shipping.LineIDs.Count == 1) as CommerceShippingInfo; if (uniqueShippingInfo != null) { return(uniqueShippingInfo); } return(commerceOrder.Shipping.FirstOrDefault(s => s.LineIDs.Contains(orderLine.ExternalCartLineId)) as CommerceShippingInfo); }
public void ChangeQuantity(Product prod, int quantity) { CartLine cline = line.Find(x => x.Product.ID == prod.ID); cline.Quantity = quantity; }
[ProducesResponseType(500)] //Returned when there was an error in the repo public ActionResult <CartLine> GetCartLine(long id) { CartLine cartLine = _repo.Find(id); return(cartLine ?? (ActionResult <CartLine>)NotFound()); }
private static bool DoesProductIdMatch(string productId, CartLine cartLine) { return((cartLine.Product.ProductId.Contains("|") ? cartLine.Product.ProductId.Split('|')[1] : cartLine.Product.ProductId) == productId); }
private AddToBasketPipelineArgs GetAddToBasketPipelineArgs(ICatalogContext catalogContext, PurchaseOrder purchaseOrder, CartLine cartLine) { var addToBasketPipelineArgs = new AddToBasketPipelineArgs( new AddToBasketRequest { AddToExistingOrderLine = true, ExecuteBasketPipeline = false, PriceGroup = catalogContext.CurrentPriceGroup, Product = GetProduct(cartLine.Product), PurchaseOrder = purchaseOrder, Quantity = (int)cartLine.Quantity }, new AddToBasketResponse()); addToBasketPipelineArgs.Request.Properties["FromUCommerce"] = false; return(addToBasketPipelineArgs); }
public IActionResult RemoveFromCart([DataSourceRequest] DataSourceRequest request, CartLine cartLine) { var cart = GetCart(); cart.RemoveLine(cartLine.Id); HttpContext.Session.SetObjectAsJson(sessionKey, cart); return(Json(ModelState.ToDataSourceResult())); }
public IViewComponentResult Invoke(CartLine line) { return(View(line)); }
public virtual OrderLine MapCartLineToOrderLine(CartLine cartLine) { return(_mapCartLineToOrderLine.Map(cartLine)); }
public override void Initialize(CartLine cartLine, ShippingInfo shippingInfo, Sitecore.Commerce.Entities.Party party) { base.Initialize(cartLine, shippingInfo, party); }