public async Task <IActionResult> AddToShoppingCart(Guid catalogItemId) { var user = await _userManager.GetUserAsync(User); // Create a new shoppingcart item dto var item = new ShoppingCartItemDto { CatalogItemId = catalogItemId, UserId = user.Id }; var client = _clientFactory.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Post, $"{_shoppingCartServiceRoot}AddItemToShoppingCart"); var itemJson = JsonSerializer.Serialize(item); request.Content = new StringContent(itemJson, Encoding.UTF8, "application/json"); request.Headers.Add("User-Agent", "AvcPgm.UI"); var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { TempData["PostError"] = "Something went wrong when adding to shoppingcart, try again or contact support!"; } return(RedirectToAction("DisplayShoppingCart")); }
/// <summary> /// Adds product to cart and saves them in DB /// </summary> /// <param name="dto">product DTO</param> /// <param name="amount">quantity amount</param> /// <param name="ShoppingCartId">shopping cart ID</param> public void AddtoCart(ProductDto dto, int amount, string ShoppingCartId) { try { var dbEntries = DbContext.ShoppingCartItems.SingleOrDefault(s => s.ProductID == dto.Id && s.ShoppingCartId == ShoppingCartId); var shoppingCartItemDto = _mapper.Map <ShoppingCartItemDto>(dbEntries); if (shoppingCartItemDto == null) { shoppingCartItemDto = new ShoppingCartItemDto { ShoppingCartId = ShoppingCartId, Amount = amount, ProductID = dto.Id }; var shoppingCartItem = _mapper.Map <ShoppingCartItem>(shoppingCartItemDto); DbContext.ShoppingCartItems.Add(shoppingCartItem); } else { dbEntries.Amount += amount; } DbContext.SaveChanges(); } catch (Exception ex) { throw ex; } }
public async Task DeleteShoppingCart_ReturnsOK() { using (var client = new TestClientProvider().Client) { // Add a test item to the shoppingcart database var item = new ShoppingCartItemDto { UserId = "d28888e9-2ba9-473a-a40f-e38cb54f9b99", CatalogItemId = Guid.Parse("90d6da79-e0e2-4ba8-bf61-2d94d90df899"), Amount = 1 }; var request = new HttpRequestMessage(HttpMethod.Post, $"ShoppingCartService/ShoppingCart/AddItemToShoppingCart"); var orderJson = JsonSerializer.Serialize(item); request.Content = new StringContent(orderJson, Encoding.UTF8, "application/json"); request.Headers.Add("User-Agent", "AvcPgm.ShoppingCartService.Test"); var responseAdd = await client.SendAsync(request); responseAdd.EnsureSuccessStatusCode(); // Delete item from database var responseDel = await client.DeleteAsync("ShoppingCartService/ShoppingCart/DeleteShoppingCart/d28888e9-2ba9-473a-a40f-e38cb54f9b99"); responseDel.EnsureSuccessStatusCode(); // Assert result of delete Assert.Equal(HttpStatusCode.OK, responseDel.StatusCode); } }
public ShoppingCartItem SaveCartItem([FromBody] ShoppingCartItemDto sCartItemDto) { ShoppingCartItem shoppingCartItem = null; if (shoppingCartItem.Id > 0) { shoppingCartItem = _shoppingCartRepo.GetById(sCartItemDto.Id); if (shoppingCartItem != null) { shoppingCartItem.Quantity = sCartItemDto.Quantity; shoppingCartItem.UnitPrice = sCartItemDto.UnitPrice; // return(shoppingCartItem); } } // shoppingCartItem = new ShoppingCartItem(); shoppingCartItem.ProductId = sCartItemDto.ProductId; shoppingCartItem.Quantity = sCartItemDto.Quantity; shoppingCartItem.UnitPrice = sCartItemDto.UnitPrice; // _shoppingCartRepo.Insert(shoppingCartItem); // return(shoppingCartItem); }
public async Task <ShoppingCartItemDto> ChangeQuantity(ShoppingCartItemDto dto) { try { var cartItem = await _shoppingCartItemService.Get(x => x.Product_Id == dto.productId && x.ShoppingCart_Id == dto.cartId); if (cartItem == null) { throw new Exception("can not find"); } var product = await _productService.Get(x => x.Id == dto.productId); if (product.InStock < dto.quantity) { cartItem.Quantity = (short)product.InStock; await _shoppingCartItemService.Update(cartItem); throw new Exception("no stock"); } cartItem.Quantity = dto.quantity; await _shoppingCartItemService.Update(cartItem); return(dto); } catch (Exception) { throw; } }
public IHttpActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder <ShoppingCartItemDto>))] Delta <ShoppingCartItemDto> shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // We kno that the id will be valid integer because the validation for this happens in the validator which is executed by the model binder. ShoppingCartItem shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(int.Parse(shoppingCartItemDelta.Dto.Id)); if (shoppingCartItemForUpdate == null) { return(Error(HttpStatusCode.NotFound, "shopping_cart_item", "not found")); } // Here we make sure that the product id and the customer id won't be modified. int productId = shoppingCartItemForUpdate.ProductId; int customerId = shoppingCartItemForUpdate.CustomerId; shoppingCartItemDelta.Merge(shoppingCartItemForUpdate); shoppingCartItemForUpdate.ProductId = productId; shoppingCartItemForUpdate.CustomerId = customerId; if (!shoppingCartItemForUpdate.Product.IsRental) { shoppingCartItemForUpdate.RentalStartDateUtc = null; shoppingCartItemForUpdate.RentalEndDateUtc = null; } if (!string.IsNullOrEmpty(shoppingCartItemDelta.Dto.ShoppingCartType)) { ShoppingCartType shoppingCartType = (ShoppingCartType)Enum.Parse(typeof(ShoppingCartType), shoppingCartItemDelta.Dto.ShoppingCartType); shoppingCartItemForUpdate.ShoppingCartType = shoppingCartType; } // The update time is set in the service. _shoppingCartService.UpdateShoppingCartItem(shoppingCartItemForUpdate.Customer, shoppingCartItemForUpdate.Id, shoppingCartItemForUpdate.AttributesXml, shoppingCartItemForUpdate.CustomerEnteredPrice, shoppingCartItemForUpdate.RentalStartDateUtc, shoppingCartItemForUpdate.RentalEndDateUtc, shoppingCartItemForUpdate.Quantity); // Preparing the result dto of the new product category mapping ShoppingCartItemDto newShoppingCartItemDto = shoppingCartItemForUpdate.ToDto(); newShoppingCartItemDto.ProductDto = shoppingCartItemForUpdate.Product.ToDto(); newShoppingCartItemDto.CustomerDto = shoppingCartItemForUpdate.Customer.ToCustomerForShoppingCartItemDto(); newShoppingCartItemDto.ShoppingCartType = shoppingCartItemForUpdate.ShoppingCartType.ToString(); var shoppingCartsRootObject = new ShoppingCartItemsRootObject(); shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto); var json = _jsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public static ShoppingCartItem Map(ShoppingCartItemDto itemDto) { return(new ShoppingCartItem { Id = itemDto.Id, BookId = itemDto.BookId, BookTitle = itemDto.Title, BookPrice = itemDto.Price }); }
/// <summary> /// Transfers Shopping Cart Item DTO to Shopping Cart Item BO. /// </summary> /// <param name="item">Shopping Cart Item DTO.</param> /// <returns>Shopping Cart Item BO.</returns> public static ShoppingCartItem FromDataTransferObject(ShoppingCartItemDto item) { return(new ShoppingCartItem { Id = item.Id, Name = item.Name, Quantity = item.Quantity, UnitPrice = item.UnitPrice }); }
public async Task AddItemToShoppingCart_ReturnsBadRequest() { var item = new ShoppingCartItemDto { }; using (var client = new TestClientProvider().Client) { var request = new HttpRequestMessage(HttpMethod.Post, $"ShoppingCartService/ShoppingCart/AddItemToShoppingCart"); var orderJson = JsonSerializer.Serialize(item); request.Content = new StringContent(orderJson, Encoding.UTF8, "application/json"); request.Headers.Add("User-Agent", "AvcPgm.ShoppingCartService.Test"); var response = await client.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } }
public async Task <ActionResult> UpdateItemQuantityAsync(ShoppingCartItemDto cartDto) { if (cartDto is null) { return(NotFound()); } bool success = await _cartService.UpdateItemQuantityAsync(cartDto.ShoppingCartId, cartDto.ProductId, cartDto.Quantity); if (!success) { return(BadRequest()); } return(Ok()); }
public async Task Delete(ShoppingCartItemDto dto) { try { var cartItem = await _shoppingCartItemService.Get(x => x.Product_Id == dto.productId && x.ShoppingCart_Id == dto.cartId); if (cartItem == null) { throw new Exception("can not find"); } _shoppingCartItemService.Delete(cartItem); } catch (Exception) { throw; } }
public void Add(int productId, int quantity, double price) { ShoppingCartItemDto product = Items.Where(p => p.ProductId == productId).FirstOrDefault(); if (product == null) { Items.Add(new ShoppingCartItemDto() { ProductId = productId, Quantity = quantity, Price = price }); } else { product.Quantity += quantity; } }
public async Task AddItemToShoppingCart_ReturnsOK() { var item = new ShoppingCartItemDto { UserId = "d28888e9-2ba9-473a-a40f-e38cb54f9b35", CatalogItemId = Guid.Parse("90d6da79-e0e2-4ba8-bf61-2d94d90df801"), Amount = 1 }; using (var client = new TestClientProvider().Client) { var request = new HttpRequestMessage(HttpMethod.Post, $"ShoppingCartService/ShoppingCart/AddItemToShoppingCart"); var orderJson = JsonSerializer.Serialize(item); request.Content = new StringContent(orderJson, Encoding.UTF8, "application/json"); request.Headers.Add("User-Agent", "AvcPgm.ShoppingCartService.Test"); var response = await client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } }
public async Task <ActionResult <ProductDto> > GetItemFromCartAsync(int cartId, int productId) { var dto = new ShoppingCartItemDto(); try { var item = await _cartService.GetItemFromCartAsync(cartId, productId); if (item == null) { return(Ok(null)); } dto = _mapper.Map <ShoppingCartItemDto>(item); } catch (Exception e) { } return(Ok(dto)); }
public async Task <ActionResult> AddItemToCartAsync(int cartId, ShoppingCartItemDto cartItemDto) { if (cartItemDto is null) { return(NotFound()); } //var prod = await _productService.GetProductByIdAsync(cartItemDto.ProductId); var item = new ShoppingCartItem { ProductId = cartItemDto.ProductId, ProductName = cartItemDto.ProductName, Price = cartItemDto.Price, Quantity = cartItemDto.Quantity, ImageUrl = cartItemDto.ImageUrl, CategoryId = cartItemDto.CategoryId, ShoppingCart = await _cartService.GetCartByIdAsync(cartId) }; await _cartService.AddItemToCartAsync(item); return(Ok()); }
public IHttpActionResult CreateShoppingCartItem([ModelBinder(typeof (JsonModelBinder<ShoppingCartItemDto>))] Delta<ShoppingCartItemDto> shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return Error(); } ShoppingCartItem newShoppingCartItem = _factory.Initialize(); shoppingCartItemDelta.Merge(newShoppingCartItem); // We know that the product id and customer id will be provided because they are required by the validator. // TODO: validate Product product = _productService.GetProductById(shoppingCartItemDelta.Dto.ProductId.Value); if (product == null) { return Error(HttpStatusCode.NotFound, "product", "not found"); } Customer customer = _customerService.GetCustomerById(shoppingCartItemDelta.Dto.CustomerId.Value); if (customer == null) { return Error(HttpStatusCode.NotFound, "customer", "not found"); } ShoppingCartType shoppingCartType = (ShoppingCartType)Enum.Parse(typeof(ShoppingCartType), shoppingCartItemDelta.Dto.ShoppingCartType); if (!product.IsRental) { newShoppingCartItem.RentalStartDateUtc = null; newShoppingCartItem.RentalEndDateUtc = null; } IList<string> warnings = _shoppingCartService.AddToCart(customer, product, shoppingCartType, 0, null, 0M, shoppingCartItemDelta.Dto.RentalStartDateUtc, shoppingCartItemDelta.Dto.RentalEndDateUtc, shoppingCartItemDelta.Dto.Quantity ?? 1); if (warnings.Count > 0) { foreach (var warning in warnings) { ModelState.AddModelError("shopping cart item", warning); } return Error(HttpStatusCode.BadRequest); } // Preparing the result dto of the new product category mapping ShoppingCartItemDto newShoppingCartItemDto = newShoppingCartItem.ToDto(); newShoppingCartItemDto.ProductDto = product.ToDto(); newShoppingCartItemDto.CustomerDto = customer.ToCustomerForShoppingCartItemDto(); newShoppingCartItemDto.ShoppingCartType = shoppingCartType.ToString(); var shoppingCartsRootObject = new ShoppingCartItemsRootObject(); shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto); var json = _jsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty); return new RawJsonActionResult(json); }
public IActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder <ShoppingCartItemDto>))] Delta <ShoppingCartItemDto> shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // We kno that the id will be valid integer because the validation for this happens in the validator which is executed by the model binder. ShoppingCartItem shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(int.Parse(shoppingCartItemDelta.Dto.Id)); if (shoppingCartItemForUpdate == null) { return(Error(HttpStatusCode.NotFound, "shopping_cart_item", "not found")); } shoppingCartItemDelta.Merge(shoppingCartItemForUpdate); if (!shoppingCartItemForUpdate.Product.IsRental) { shoppingCartItemForUpdate.RentalStartDateUtc = null; shoppingCartItemForUpdate.RentalEndDateUtc = null; } if (shoppingCartItemDelta.Dto.Attributes != null) { shoppingCartItemForUpdate.AttributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, shoppingCartItemForUpdate.Product.Id); } // The update time is set in the service. var warnings = _shoppingCartService.UpdateShoppingCartItem(shoppingCartItemForUpdate.Customer, shoppingCartItemForUpdate.Id, shoppingCartItemForUpdate.AttributesXml, shoppingCartItemForUpdate.CustomerEnteredPrice, shoppingCartItemForUpdate.RentalStartDateUtc, shoppingCartItemForUpdate.RentalEndDateUtc, shoppingCartItemForUpdate.Quantity); if (warnings.Count > 0) { foreach (var warning in warnings) { ModelState.AddModelError("shopping cart item", warning); } return(Error(HttpStatusCode.BadRequest)); } else { shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(shoppingCartItemForUpdate.Id); } // Preparing the result dto of the new product category mapping ShoppingCartItemDto newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItemForUpdate); var shoppingCartsRootObject = new ShoppingCartItemsRootObject(); shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto); var json = _jsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder <ShoppingCartItemDto>))] Delta <ShoppingCartItemDto> shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } ShoppingCartItem newShoppingCartItem = _factory.Initialize(); shoppingCartItemDelta.Merge(newShoppingCartItem); // We know that the product id and customer id will be provided because they are required by the validator. // TODO: validate Product product = _productService.GetProductById(newShoppingCartItem.ProductId); if (product == null) { return(Error(HttpStatusCode.NotFound, "product", "not found")); } Customer customer = _customerService.GetCustomerById(newShoppingCartItem.CustomerId); if (customer == null) { return(Error(HttpStatusCode.NotFound, "customer", "not found")); } ShoppingCartType shoppingCartType = (ShoppingCartType)Enum.Parse(typeof(ShoppingCartType), shoppingCartItemDelta.Dto.ShoppingCartType); if (!product.IsRental) { newShoppingCartItem.RentalStartDateUtc = null; newShoppingCartItem.RentalEndDateUtc = null; } string attributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, product.Id); int currentStoreId = _storeContext.CurrentStore.Id; IList <string> warnings = _shoppingCartService.AddToCart(customer, product, shoppingCartType, currentStoreId, attributesXml, 0M, newShoppingCartItem.RentalStartDateUtc, newShoppingCartItem.RentalEndDateUtc, shoppingCartItemDelta.Dto.Quantity ?? 1); if (warnings.Count > 0) { foreach (var warning in warnings) { ModelState.AddModelError("shopping cart item", warning); } return(Error(HttpStatusCode.BadRequest)); } else { // the newly added shopping cart item should be the last one newShoppingCartItem = customer.ShoppingCartItems.LastOrDefault(); } // Preparing the result dto of the new product category mapping ShoppingCartItemDto newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(newShoppingCartItem); var shoppingCartsRootObject = new ShoppingCartItemsRootObject(); shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto); var json = _jsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public void Add(ShoppingCartItemDto item) { Items.Add(item); }
public async Task <ActionResult <ShoppingCartItemDto> > AddItemToShoppingCart(ShoppingCartItemDto shoppingCartItemDto) { if (shoppingCartItemDto.CatalogItemId == null || shoppingCartItemDto.UserId == null) { return(BadRequest("Provided object does not contain necessary information.")); } var shoppingCartItemEntity = new ShoppingCartItem(shoppingCartItemDto); // If item already exists in users shoppingcart increase amount with one, else add one new item. var itemInDb = _shoppingCartRepository.GetItemFromShoppingCart(shoppingCartItemEntity); if (itemInDb == null) { shoppingCartItemEntity.Amount = 1; _shoppingCartRepository.AddItemToShoppingCart(shoppingCartItemEntity); } else { itemInDb.Amount++; } if (!await _shoppingCartRepository.Save()) { return(BadRequest("Save item to shoppingcart failed.")); } return(Ok()); }