public CartItemModel(CartItemEntity entity) { Count = entity.Count; Product = new ProductModel(entity.Product); Price = entity.Price; CartItemId = entity.CartItemId.ToString(); }
public CartItemViewModel(CartItemEntity cartItem) { ProductId = cartItem.ProductId; Quantity = cartItem.Quantity; AddedAt = cartItem.AddedAt; Product = cartItem.Product != null ? new ProductViewModel(cartItem.Product) : null; }
public int AddItem(CartItemEntity entity) { var connectionString = ConfigurationManager.ConnectionStrings["dbComercial"].ConnectionString; using (var session = SessionManager.OpenSession(connectionString)) { if (entity.Id == 0) { if (entity.Cantidad > 0) { session.Save(entity); } } else { if (entity.Cantidad > 0) { session.Update(entity); session.Flush(); } else { session.Delete(entity); session.Flush(); } } } return(1); }
public bool SaveChanges(CartItemEntity cart) { bool result = false; try { using (var db = DatabaseManager.GetOpenConnection()) { var sql = ""; if (cart.ItemId == 0) { sql = "INSERT INTO CartItems (CartId, ProductId , Quantity, DateCreated) VALUES ('{0}', {1}, {2}, '{3}');"; sql = string.Format(sql, cart.CartId, cart.ProductId, cart.Quantity, cart.DateCreated.ToString("yyyy-MM-dd HH:mm:ss")); } else { sql = "UPDATE CartItems SET CartId='{0}', ProductId={1}, Quantity={2} WHERE ItemId={3};"; sql = string.Format(sql, cart.CartId, cart.ProductId, cart.Quantity, cart.ItemId); } result = db.Execute(sql) > 0; } } catch (Exception e) { Console.WriteLine(e); } return(result); }
public static ShoppingCart Map(CartItemEntity cartItem) { return(new ShoppingCart { UserId = cartItem.UserId }); }
public CartItem2DTO(CartItemEntity cartItemEntity) { Id = cartItemEntity.Id; Quantity = cartItemEntity.Quantity; Actived = cartItemEntity.Actived; Deleted = cartItemEntity.Deleted; Product = cartItemEntity.Product; }
public ShoppingCartResponse AddItemToCart(long productId, int quantity, long userId) { var cartItem = new CartItemEntity { ProductId = productId, Quantity = quantity, UserId = userId }; return(_client.Post <ShoppingCartResponse>(EndpointsResources.AddNewItem, cartItem)); }
public static CartItem CartItemEntityToCartItem(this CartItemEntity item) { return(new CartItem { Id = item.Id, Quantity = item.Count }); }
public HttpResponseMessage Post([FromBody] List <ItemPedido> items) { var Session = HttpContext.Current.Session; HttpResponseMessage msg = new HttpResponseMessage(); try { if (Session["UserNit"] != null) { PedidoService ps = new PedidoService(); foreach (ItemPedido item in items) { if (item.Cantidad >= 0) { CartItemEntity cie = new CartItemEntity(); cie.Id = item.Id; cie.Nit = Session["UserNit"].ToString(); cie.Referencia = item.Referencia; cie.Oferta = item.Oferta; cie.Plu = item.Plu; cie.Talla = item.Talla; cie.Color = item.Color; cie.Cantidad = item.Cantidad; ps.AddItem(cie); } } Mensaje mensaje = new Mensaje() { Type = "success", Descripcion = "El carro de compras ha sido actualizado" }; msg.Content = new ObjectContent <object>(mensaje, new System.Net.Http.Formatting.JsonMediaTypeFormatter()); msg.StatusCode = HttpStatusCode.OK; return(msg); } else { Mensaje mensaje = new Mensaje() { Type = "danger", Descripcion = "La sesión ha sido finalizada por inactividad" }; msg.Content = new ObjectContent <object>(mensaje, new System.Net.Http.Formatting.JsonMediaTypeFormatter()); msg.StatusCode = HttpStatusCode.Gone; return(msg); } } catch { Mensaje mensaje = new Mensaje() { Type = "danger", Descripcion = "Ha ocurrido un error agregando el producto" }; msg.Content = new ObjectContent <object>(mensaje, new System.Net.Http.Formatting.JsonMediaTypeFormatter()); msg.StatusCode = HttpStatusCode.BadRequest; return(msg); } }
private string DisplayedQuantity(CartItemEntity ci) { if (!ci.IsWeighable) { return(ci.Quantity.ToString()); } var quantityDisplayed = ci.Quantity < 1000 ? ci.Quantity : Math.Round((decimal)ci.Quantity / 1000, 1); return(ShortUom(quantityDisplayed, ci.Quantity, ci.IsInGrams)); }
private void ApplayPromotion(CartItemEntity cartItemAdded, PromotionEntity promotionRelated, int promotionApplies) { if (cartItemAdded.Promotion == null) { cartItemAdded.Promotion = Mapper.Map <CartItemPromotion>(promotionRelated); } var discountPerApply = GetDiscountPerApply(promotionRelated, cartItemAdded); cartItemAdded.Promotion.Discount = Math.Round(promotionApplies * discountPerApply, 2); }
private int PromotionApplies(CartItemEntity cartItem, PromotionEntity promotionRelated) { var quantity = cartItem.Quantity / (cartItem.IsWeighable ? cartItem.Size : 1); var applies = quantity / promotionRelated.TriggeringQuantity; if (applies > 1 && !promotionRelated.IsReApply) { return(1); } return(applies); }
public CartModel AddToCart(AddToCartRequest request) { var productEntity = _context.Products .SingleOrDefault(x => x.ProductId == new Guid(request.ProductId)); var userEntity = _context.Users .Include(x => x.Cart) .SingleOrDefault(x => x.UserId == new Guid(request.UserId)); var cartEntity = _context.Carts .Include(x => x.CartItems) .Include(x => x.CartItems.Select(y => y.Product)) .SingleOrDefault(x => x.User.UserId == userEntity.UserId); var cartItemEntity = cartEntity.CartItems .SingleOrDefault(x => x.Product.ProductId == productEntity.ProductId); var model = new CartModel(); if (cartItemEntity != null) { cartItemEntity.Count += request.Count; cartItemEntity.Price += productEntity.Price * request.Count; cartEntity.TotalPrice += productEntity.Price * request.Count; _context.CartItems.AddOrUpdate(cartItemEntity); _context.SaveChanges(); model = new CartModel(cartEntity); return(model); } var cartItem = new CartItemEntity() { CartItemId = Guid.NewGuid(), Product = productEntity, Cart = userEntity.Cart, Count = request.Count, Price = request.Count * productEntity.Price }; cartEntity.TotalPrice += cartItem.Price; _context.CartItems.Add(cartItem); _context.Carts.AddOrUpdate(cartEntity); _context.SaveChanges(); model = new CartModel(cartEntity); return(model); }
public CartItemEntity SaveCart(CartItemEntity cartItemEntity) { dbContext.Entry(cartItemEntity).Reference(x => x.Product).IsModified = false; dbContext.Entry(cartItemEntity).Reference(x => x.Cart).IsModified = false; // dbContext.CartItems.Add(cartItemEntity); dbContext.SaveChanges(); if (cartItemEntity.Deleted == true) { dbContext.Remove(cartItemEntity); } return(cartItemEntity); }
/// <summary> /// Process updating product availability /// </summary> /// <param name="cartItem"></param> /// <exception cref="ProductNotAvailableException"></exception> /// <returns></returns> public override ShoppingCartResponse Process(CartItemEntity cartItem) { var product = GetProduct(cartItem.ProductId); if (!IsProductAvailable(product, cartItem.Quantity)) { throw new ProductNotAvailableException(string.Format(ErrorMessages.ProductNotAvailable, cartItem.Quantity, cartItem.ProductId)); } UpdateProductAvailability(product, cartItem.Quantity); return(base.Process(cartItem)); }
// Adds an entity public void Save(CartItemEntity itemValidate, bool addOne) { using (CartContext ctx = new CartContext()) { var cartItem = ctx.CartItems.SingleOrDefault(x => x.ProductId == itemValidate.ProductId && x.UserId == itemValidate.UserId); if (cartItem == null) { ctx.CartItems.Add(itemValidate); } else { cartItem.Quantity = addOne ? cartItem.Quantity + 1: itemValidate.Quantity; } ctx.SaveChanges(); } }
protected void Page_Load(object sender, EventArgs e) { if (Session["modal"] == null || Session["modal"].ToString().Equals("hide")) { CartItem cart = new CartItem(); List <CartItemEntity> list; if (ProductID > 0) { list = cart.Select(ProductID); } else { list = cart.Select(2); } modalContent.DataSource = list; modalContent.DataBind(); // Set the info for popup cart LblSubQuantity.Text = "0"; LblSubAmount.Text = "0"; } else { CartItem cart = new CartItem(); CartItemEntity cartItem = cart.AddToCart(ProductID, Quantity); modalContent.DataSource = new List <CartItemEntity>() { cartItem }; modalContent.DataBind(); // Set the info for popup cart LblSubQuantity.Text = cartItem.Quantity.ToString(); LblSubAmount.Text = cartItem.Total.ToString(); } Control control = (Control)sender; mainPage = control.Page.ToString(); mainPage = mainPage.Substring(4); mainPage = mainPage.Substring(0, mainPage.Length - 5); }
//[Dependency] //public ILogger<PromotionsApplayer> logger { get; set; } public async Task ApplayOnItem(CartEntity cartEntity, CartItemEntity cartItem) { cartItem.Promotion = null; var promotionRelated = await GetPromotionRelated(cartItem); if (promotionRelated == null) { return; } var promotionApplies = PromotionApplies(cartItem, promotionRelated); if (promotionApplies == 0) { return; } ApplayPromotion(cartItem, promotionRelated, promotionApplies); }
/// <summary> /// Add products to Cart /// </summary> /// <param name="productId"></param> /// <param name="quantity"></param> /// <returns></returns> public CartItemEntity AddToCart(int productId, int quantity) { // Retrieve shopping cart id ShoppingCartId = CartCookieKey; CartItemEntity cartItem = null; using (var db = DatabaseManager.GetOpenConnection()) { var sql = "select * from cartitems where CartId='{0}' AND ProductId={1};"; sql = string.Format(sql, ShoppingCartId, productId); cartItem = db.QuerySingleOrDefault <CartItemEntity>(sql); } // The product does not exist in the cart if (cartItem == null) { // Create a new cart item when the product does not exist in the db cartItem = new CartItemEntity { CartId = ShoppingCartId, ProductId = productId, Quantity = quantity, DateCreated = DateTime.Now }; } else { // If the item does exist in the cart, add quantity. cartItem.Quantity += quantity; } if (cartItem != null) { cartItem.Product = Product.Get(productId); } // Update Cart item to DB SaveChanges(cartItem); return(cartItem); }
public ActionResult Index(string productId) { var cartCookie = this.Request.Cookies.Get("cart"); if (cartCookie == null || string.IsNullOrWhiteSpace(cartCookie.Value)) { var guid = Guid.NewGuid(); cartCookie = new HttpCookie("cart", guid.ToString()); Response.Cookies.Add(cartCookie); } var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>(); var productPage = contentRepository.Get <ProductPage>(new ContentReference(int.Parse(productId))); // Creates a new Entity for the cart var cartItem = new CartItemEntity(); cartItem.ProductId = int.Parse(productId); cartItem.ProductName = productPage.Name; cartItem.ProductPrice = int.Parse(productPage.ProductPrice); cartItem.UserId = cartCookie.Value; cartItem.Quantity = 1; // Gets the converted price and adds it to the cart Entity var currencyClient = new CurrencyClient(); var convertedPrice = currencyClient.GetConvertedFromUsd(productPage.ProductPrice); cartItem.ConvertedPrice = convertedPrice; var cartRepository = new CartRepository(); cartRepository.Save(cartItem, true); // Adds the converted price to the viewmodel var viewModel = new ProductPageViewModel(); viewModel.CurrentPage = productPage; viewModel.ConvertedPrice = convertedPrice.ToString("C3"); return(View("~/Views/ProductPage/Index.cshtml", viewModel)); }
/// <summary> /// Process adding new Item to cart /// </summary> /// <remarks> /// There is two scenarios for this: /// 1. Either there is no active shopping cart, then a new cart will be created with the new item. /// 2. or there is an active shopping cart, then the new item will be added to the same cart. /// </remarks> /// <param name="cartItem"></param> /// <returns></returns> public override ShoppingCartResponse Process(CartItemEntity cartItem) { var cart = CheckExistingCart(cartItem.UserId); if (cart == null) { cart = MapperHelper.Map(cartItem); cart.CartItems.Add(new CartItem { ProductId = cartItem.ProductId, Quantity = cartItem.Quantity }); _unitOfWork.RepositoryFactory <ShoppingCart>().Insert(cart); } else { cart.CartItems.Add(new CartItem { ProductId = cartItem.ProductId, Quantity = cartItem.Quantity }); _unitOfWork.RepositoryFactory <ShoppingCart>().Update(cart); } _unitOfWork.Save(); return(MapperHelper.Map(cart)); }
private async Task <PromotionEntity> GetPromotionRelated(CartItemEntity cartItem) { return(await promotionsRepository.GetByProductId(cartItem.Id)); }
public ShoppingCartResponse AddToCart(CartItemEntity cartItem) { return(_newItemProcessor.Process(cartItem)); }
public bool AddOrUpdateCartItem(CartItemEntity cartItem) { return((_connection.Table <CartItemEntity>().FirstOrDefault(x => x.Id == cartItem.Id) == null ? _connection.Insert(cartItem) : _connection.Update(cartItem)) != -1); }
public ActionResult postCart([FromBody] FormAddCart formAddCart) { // Lấy UserEntity đang đăng nhập từ jwt UserEntity user = (UserEntity)HttpContext.Items["User"]; Console.WriteLine("User: "******"User"] = null; //Xóa hết tất cả sản phẩm trong giỏ hàng cartDAO.deleteAllItemCart(user.Id); CartEntity c = cartDAO.getCart(user.Id); foreach (CartItem ci in formAddCart.CartItems) { Console.WriteLine("productId: {0}, amount: {1}", ci.Idp, ci.Quantity); if (ci.Idp == 0) { return(BadRequest("Thiếu tham số idp.")); } Console.WriteLine("productSpecificId {0}", ci.Idp); Product2 p = product2DAO.getProduct(ci.Idp); if (p == null) { return(BadRequest()); } try { CartItemEntity cartItemEntity = null; if (c.Items != null) { cartItemEntity = c.Items.Find(X => { int tmp = X.Product.Id; Console.WriteLine("ProductId : {0}", tmp); return (tmp.CompareTo(ci.Idp) == 0); }); } else { c.Items = new List <CartItemEntity>(); } Console.WriteLine("cartItemEntity" + cartItemEntity); if (cartItemEntity == null) { cartItemEntity = new CartItemEntity(); cartItemEntity.Quantity = ci.Quantity; cartItemEntity.ProductId = ci.Idp; cartItemEntity.Product = p; cartItemEntity.CartId = c.Id; // if (cartItemEntity.Deleted == false) { c.Items.Add(cartItemEntity); } } else { Console.WriteLine("Increase amount"); cartItemEntity.Quantity += ci.Quantity; //cartItemEntity.Quantity = ci.Quantity; if (cartItemEntity.Quantity < 0) { return(BadRequest("Số lượng item trong giỏ hàng nhỏ hơn 0, hãy xóa item này khỏi giỏ hàng")); } } cartItemEntity.Actived = ci.Actived; cartItemEntity.Deleted = ci.Deleted; cartItemEntity = cartDAO.SaveCart(cartItemEntity); } catch (Exception e) { if (e.InnerException != null) { Console.WriteLine(e.InnerException.Message); } return(BadRequest(e.Message)); } } c = cartDAO.getCart(c); //return Ok(c); return(Ok(new CartDTO(c))); }
private int Quantity(CartItemEntity ci) { return(ci.IsWeighable ? (ci.Quantity > 0 ? 1 : 0) : ci.Quantity); }
private static async Task AddCartItem(CartEntity cart, IPromotionsApplayer promotionsApplayer, CartItemEntity cartItem) { var existingCartItem = cart.Items.FirstOrDefault(ci => ci.Id == cartItem.Id); if (cartItem.IsWeighable) { cartItem.Quantity = (cartItem.Quantity / cartItem.QuantityInterval) * cartItem.QuantityInterval; } if (existingCartItem == null) { cart.Items.Add(cartItem); } else { existingCartItem.Quantity = Math.Max(existingCartItem.Quantity, cartItem.Quantity); } await promotionsApplayer.ApplayOnItem(cart, cartItem); }
/// <summary> /// Process the next step of the current step if any /// </summary> /// <param name="cartItem"></param> /// <returns></returns> public virtual ShoppingCartResponse Process(CartItemEntity cartItem) { return(_nextStep?.Process(cartItem)); }
private static decimal GetDiscountPerApply(PromotionEntity promotionRelated, CartItemEntity cartItem) { return(((decimal)promotionRelated.DiscountPercentage / 100) * cartItem.Price); }