Пример #1
0
        public async Task <int> UpdateShoppingCart(ShoppingCartDto model)
        {
            var shopCart = await _service.QueryAsync(model.Id);

            shopCart.Number += 1;
            return(await _service.EditAsync(shopCart));
        }
Пример #2
0
        public async Task <IActionResult> PutShoppingCart(int id, ShoppingCartDto shoppingCartDto)
        {
            if (id != shoppingCartDto.Id)
            {
                return(BadRequest());
            }

            var shoppingCart = _mapper.Map <ShoppingCart>(shoppingCartDto);

            _context.Entry(shoppingCart).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ShoppingCartExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #3
0
        public IActionResult AddItem([FromBody] ShoppingCartDto item)
        {
            _logger.LogInformation("Hello from dummy controller!");
            //_logger.LogInformation("User name: " + User.Identity.Name + "User role: " + User.Identity.ToString() + "Time: " + DateTime.Now.ToString("h:mm:ss tt") + "ShoppingCartController:CheckIfUserHasShoppingCart()");
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (item.itemQuantity == 0)
            {
                return(NoContent());
            }

            var userName = JWTtoken.GetTokenInfo(Request, "sub");

            if (userName == null)
            {
                return(NotFound("Could not get token"));
            }

            var itemFromDb = _itemsRepository.GetItem(item.itemId);

            if (itemFromDb == null)
            {
                return(NotFound("Item with given id not found"));
            }

            var shoppingCart = _shoppingCartRepository.Get(userName);

            _shoppingCartRepository.Add(shoppingCart, itemFromDb.Id, item.itemQuantity);

            return(Ok("Item(s) added successfully"));
        }
Пример #4
0
        public async Task <ActionResult> CreateCartAsync(ShoppingCartDto cartDto)
        {
            if (cartDto is null)
            {
                return(NotFound());
            }

            int cartId = 0;

            try
            {
                var cart = new ShoppingCart
                {
                    DateCreatedUtc = DateTime.Parse(cartDto.DateCreatedUtc).ToUniversalTime()
                };

                cartId = await _cartService.CreateCartAsync(cart);
            }
            catch (Exception e)
            {
                return(BadRequest());
            }

            return(Ok(new { cartId }));
        }
Пример #5
0
        public ShoppingCartDto getShoppingCartInfo(string userId)
        {
            var loggedInUser = this._userRepository.Get(userId);

            var userShoppingCart = loggedInUser.UserCart;

            var AllProducts = userShoppingCart.products.ToList();

            var allProductPrice = AllProducts.Select(z => new
            {
                ProductPrice = z.product.ProductPrice,
                Quanitity    = z.Qantity
            }).ToList();

            var totalPrice = 0;


            foreach (var item in allProductPrice)
            {
                totalPrice += item.Quanitity * item.ProductPrice;
            }


            ShoppingCartDto scDto = new ShoppingCartDto
            {
                productInShoppingCart = AllProducts,
                TotalPrice            = totalPrice
            };


            return(scDto);
        }
Пример #6
0
        public IShoppingCartDto GetShoppingCartById(int id)
        {
            SqlConnection conn = webShopContext.GetConnection();

            IShoppingCartDto shoppingCart = null;

            try
            {
                conn.Open();

                string     sql = "SELECT profile_id, product_id, amount FROM shoppingcart WHERE profile_id = @id;";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@id", id);
                SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    shoppingCart = new ShoppingCartDto()
                    {
                        ProfileID = rdr.GetInt32(0),
                        ProductID = rdr.GetInt32(1),
                        Amount    = rdr.GetInt32(2),
                    };
                }
                rdr.Close();
            }
            catch (Exception e)
            {
                throw e;
            }

            conn.Close();

            return(shoppingCart);
        }
Пример #7
0
        public List <ShoppingCartDto> AddToCart(long id, int quantity, User user, object session)
        {
            List <ShoppingCartDto> listItem = new List <ShoppingCartDto>();
            var product = new ShoppingDao().GetDetailProduct(id);

            if (session != null)
            {
                listItem = (List <ShoppingCartDto>)session;
                if (listItem.Exists(x => x.ProductId == id))
                {
                    foreach (var item in listItem)
                    {
                        if (item.ProductId == id)
                        {
                            item.Quantity  += quantity;
                            item.TotalPrice = item.Quantity * item.Price;
                        }
                    }
                }
                else
                {
                    var  newCart = new ShoppingCartDto();
                    long orderId = new OrderDao().GetOrderId() + 1;
                    newCart.OrderId      = orderId;
                    newCart.CustomerId   = user.UserID;
                    newCart.ProductId    = product.ProductID;
                    newCart.ProductName  = product.ProductName;
                    newCart.Image        = product.Image;
                    newCart.Price        = product.Price;
                    newCart.Quantity     = quantity;
                    newCart.TotalPrice   = product.Price * newCart.Quantity;
                    newCart.CustomerName = user.Name;
                    newCart.Address      = user.Address;
                    newCart.Phone        = user.Phone;
                    newCart.Email        = user.Email;
                    listItem.Add(newCart);
                }
            }
            else
            {
                var  newCart = new ShoppingCartDto();
                long orderId = new OrderDao().GetOrderId() + 1;
                newCart.OrderId      = orderId;
                newCart.CustomerId   = user.UserID;
                newCart.ProductId    = product.ProductID;
                newCart.ProductName  = product.ProductName;
                newCart.Image        = product.Image;
                newCart.Price        = product.Price;
                newCart.Quantity     = quantity;
                newCart.TotalPrice   = product.Price * newCart.Quantity;
                newCart.CustomerName = user.Name;
                newCart.Address      = user.Address;
                newCart.Phone        = user.Phone;
                newCart.Email        = user.Email;
                listItem.Add(newCart);
            }

            return(listItem);
        }
 public static CheckoutDto CreateCheckOutDto(
     ShoppingCartDto shoppingCart = null,
     double shippingCost          = 0,
     double customerDiscount      = 0,
     double total = 0
     )
 {
     return(new(shoppingCart, shippingCost, customerDiscount, total));
 }
Пример #9
0
        public async Task <ActionResult <ShoppingCart> > PostShoppingCart(ShoppingCartDto shoppingCartDto)
        {
            var shoppingCart = _mapper.Map <ShoppingCart>(shoppingCartDto);
            await _context.ShoppingCart.AddAsync(shoppingCart);

            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetShoppingCart", new { id = shoppingCart.Id }, shoppingCart));
        }
        public void When_Coupon_Is_Null_Return_Zero()
        {
            var sut             = new CouponEngine();
            var shoppingCartDto = new ShoppingCartDto()
            {
                Id = "1", Items = Utility.GenerateListOfDtoItems()
            };
            var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 100);

            var result = sut.CalculateDiscount(checkout, null);

            result.Should().Be(0);
        }
        public ShoppingCartDto CreateShoppingCart(int clientId)
        {
            var client = _clientRepo.SingleOrDefault(x => x.Id == clientId);

            var shoppingCart = _cartRepo.Create(
                new ShoppingCart
            {
                Client   = client,
                Products = new List <Product>()
            });

            return(ShoppingCartDto.ToDto(shoppingCart));
        }
Пример #12
0
        public async Task <int> AddShoppingCart(ShoppingCartDto model)
        {
            IProductService service2 = new  ProductService();
            var             product  = await service2.QueryAsync(model.ProductId);

            return(await _service.AddAsync(new ShoppingCart()
            {
                ProductId = model.ProductId,
                ColorId = product.ColorId,
                SizeId = product.SizeId,
                Number = 1,
                UserId = model.UserId
            }));
        }
Пример #13
0
        public async Task <IActionResult> Addtocart(ShoppingCartDto shoppingCartDto)
        {
            ErrorDto errorDto     = new ErrorDto();
            var      usercontrole = await _shoppingCartService.AppuserControl(shoppingCartDto.AppuserId);

            if (!usercontrole.IsOk)
            {
                errorDto.Errors = usercontrole.Errors;
                errorDto.Status = usercontrole.Status;
                return(NotFound(errorDto));
            }

            var userproductstokcontrol = await _shoppingCartService.ProductStockControl(shoppingCartDto.ProductId, shoppingCartDto.Count);

            if (!userproductstokcontrol.IsOk)
            {
                errorDto.Errors = usercontrole.Errors;
                errorDto.Status = usercontrole.Status;
                return(NotFound(errorDto));
            }

            var shoppingCartControl = await _shoppingCartService.ShoppingCartControl(shoppingCartDto.ProductId, shoppingCartDto.AppuserId);


            if (!shoppingCartControl.IsOk)
            {
                var newshoppingCartDto = await _shoppingCartService.AddAsync(_mapper.Map <ShoppingCart>(shoppingCartDto));

                return(Created(string.Empty, _mapper.Map <ShoppingCartDto>(newshoppingCartDto)));
            }


            var shoppingCart = shoppingCartControl.Model;

            shoppingCart.Count = shoppingCart.Count + shoppingCartDto.Count;

            if (userproductstokcontrol.Model.Stock < shoppingCart.Count)
            {
                errorDto.Status = 400;
                errorDto.Errors.Add("Product is out of stock");
                return(NotFound(errorDto));
            }


            var cart = _shoppingCartService.Update(shoppingCart);


            return(Ok(cart));
        }
Пример #14
0
        private ShoppingCartDto MapOrderToShoppingCartDto(Order order)
        {
            var shoppingCart = new ShoppingCartDto
            {
                CustomerId  = order.CustomerId,
                OrderId     = order.Id,
                TotalPrice  = order.TotalPrice,
                Discount    = order.Discount,
                Subtotal    = order.TotalPrice + order.Discount,
                VoucherCode = order?.Voucher?.Code,
                Items       = MapOrderItemsToShoppingCartItemDtos(order.OrderItems).ToList()
            };

            return(shoppingCart);
        }
Пример #15
0
        public async Task <IActionResult> StartOrder(ShoppingCartDto shoppingCartDto)
        {
            var command = new StartOrderCommand(CustomerId, shoppingCartDto.OrderId, shoppingCartDto.TotalPrice, shoppingCartDto.Payment.CardName, shoppingCartDto.Payment.CardNumber,
                                                shoppingCartDto.Payment.CardExpirationDate, shoppingCartDto.Payment.CardCvv);

            await _mediatrHandler.SendCommand(command);

            if (IsOperationValid())
            {
                return(RedirectToAction("Index", "Order"));
            }

            shoppingCartDto = await _orderQueries.GetCustomerShoppingCart(CustomerId);

            return(View("PurchaseSummary", shoppingCartDto));
        }
        public void Coupon_Cannot_Be_Greater_Than_Cart_Total()
        {
            var sut             = new CouponEngine();
            var shoppingCartDto = new ShoppingCartDto()
            {
                Id = "1", Items = Utility.GenerateListOfDtoItems()
            };
            var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 10);

            Action result = () => sut.CalculateDiscount(checkout, new Coupon()
            {
                Amount = 100, ExpiryDate = DateTime.Now.AddDays(-60)
            });

            result.Should().Throw <CouponExpiredException>()
            .WithMessage("Coupon past 30 days and has expired.");
        }
        public void Coupon_Calculated_As_A_Percentage()
        {
            var sut             = new CouponEngine();
            var shoppingCartDto = new ShoppingCartDto()
            {
                Id = "1", Items = Utility.GenerateListOfDtoItems()
            };
            var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 10);

            var result = sut.CalculateDiscount(checkout,
                                               new Coupon()
            {
                Amount = 2, Type = CouponType.Percentage, ExpiryDate = DateTime.Now.AddDays(10)
            });

            result.Should().Be(20);
        }
Пример #18
0
        public async Task <ActionResult <ProductDto> > GetCartAsync(int cartId)
        {
            var cart = await _cartService.GetCartByIdAsync(cartId);

            if (cart == null)
            {
                return(NotFound());
            }

            var dto = new ShoppingCartDto
            {
                ShoppingCartId    = cart.ShoppingCartId,
                DateCreatedUtc    = cart.DateCreatedUtc.ToString("MM/dd/yyyy HH:mm:ss"),
                ShoppingCartItems = _mapper.Map <IEnumerable <ShoppingCartItemDto> >(cart.ShoppingCartItems)
            };

            return(Ok(dto));
        }
        public void Coupon_Cannot_Be_A_Negative_Number()
        {
            var sut             = new CouponEngine();
            var shoppingCartDto = new ShoppingCartDto()
            {
                Id = "1", Items = Utility.GenerateListOfDtoItems()
            };
            var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 10);

            Action result = () => sut.CalculateDiscount(checkout,
                                                        new Coupon()
            {
                Amount = -2, ExpiryDate = DateTime.Now.AddDays(10)
            });

            result.Should().Throw <InvalidCouponException>()
            .WithMessage("Coupon amount cannot be negative.");
        }
        public void Coupon_No_More_Than_OneHundred()
        {
            var sut             = new CouponEngine();
            var shoppingCartDto = new ShoppingCartDto()
            {
                Id = "1", Items = Utility.GenerateListOfDtoItems()
            };
            var checkout = new CheckoutDto(shoppingCartDto, 20, 10, 200);

            Action result = () => sut.CalculateDiscount(checkout,
                                                        new Coupon()
            {
                Amount = 100, Type = CouponType.Percentage, ExpiryDate = DateTime.Now.AddDays(10)
            });

            result.Should().Throw <InvalidCouponException>()
            .WithMessage("Coupon amount cannot be equal to 100.");
        }
Пример #21
0
        public void Complex_Class_Auto_Mapping_Test()
        {
            //the mappings are declared in reverse order to test that the order does not influence the mappings
            //as long as the <ShoppingCartDto, ShoppingCart> compilation batch is not done at a later time
            Mapper.CreateMap <ShoppingCart, ShoppingCartDto>();
            Mapper.CreateMap <Product, ProductDto>();

            ShoppingCart shoppingCart = GenerateShoppingCart();

            ShoppingCartDto shoppingCartDto = Mapper.Map <ShoppingCart, ShoppingCartDto>(shoppingCart);

            Assert.IsNotNull(shoppingCartDto);
            Assert.IsNotNull(shoppingCartDto.Products);
            Assert.AreEqual(2, shoppingCartDto.Products.Count);
            Assert.AreEqual("First Product", shoppingCartDto.Products[0].Name);
            Assert.AreEqual(13m, shoppingCartDto.Products[0].Price);
            Assert.AreEqual("Second Product", shoppingCartDto.Products[1].Name);
            Assert.AreEqual(12.5m, shoppingCartDto.Products[1].Price);
            Assert.AreEqual(2, shoppingCart.Products[0].Feedback.Count);
        }
        public async Task <IActionResult> Create(ShoppingCartDto shoppingcartRequest)
        {
            if (shoppingcartRequest == null)
            {
                throw new ArgumentNullException("Invalid supermarket");
            }

            if (shoppingcartRequest.Name == null)
            {
                throw new ArgumentNullException("Supermarket's name is required");
            }

            var newShoppingCart = _mapper.Map <ShoppingCart>(shoppingcartRequest);

            newShoppingCart.CreatedAt = DateTime.Now;
            newShoppingCart.CreatedBy = CurrentUserId;

            var shoppingcart = await _shoppingcartRepository.Add(newShoppingCart);

            return(Ok(shoppingcart));
        }
Пример #23
0
        /// <summary>
        /// Gets the shopping cart products.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>Shopping Cart Dto.</returns>
        public async Task <ShoppingCartDto> GetShoppingCartProducts(string id)
        {
            if (!await this.unitOfWork.Set <ShoppingCart>().AnyAsync(sc => sc.ShoppingCartID == id))
            {
                return(null);
            }

            ShoppingCartDto shoppingCart = await this.unitOfWork.Set <ShoppingCart>()
                                           .Where(sc => sc.ShoppingCartID == id)
                                           .Select(sc => new ShoppingCartDto
            {
                ShoppingCartID = sc.ShoppingCartID,
                Products       = sc.CartContents.Select(p => new ProductDto
                {
                    ProductID      = p.ProductID,
                    CartContentID  = p.CartContentID,
                    Type           = p.Product.ProductType.Value,
                    Characteristic = p.Product.ProductCharacteristics
                                     .Select(pc => new
                    {
                        Key   = pc.Characteristic.Name,
                        Value = pc.Value
                    }).ToDictionary(d => d.Key, d => d.Value)
                }).ToArray()
            }).SingleOrDefaultAsync();

            double totalPrice = 0.0;

            foreach (ProductDto product in shoppingCart.Products)
            {
                totalPrice += Convert.ToDouble(product.Characteristic["Price"], CultureInfo.InvariantCulture);
            }
            shoppingCart.TotalPrice = totalPrice;

            return(shoppingCart);
        }
Пример #24
0
        public virtual async Task <List <ShoppingCartDto> > GetShoppingCartItem(int id)
        {
            _logger.LogInformation($"Getting shopping cart items");
            List <ShoppingCartDto> listOfShoppingCart = new List <ShoppingCartDto>();
            Product product = await GetProductById(id);

            if (accessor.HttpContext.Session.GetInt32("counter") != null)
            {
                listOfShoppingCart = JsonConvert.DeserializeObject <List <ShoppingCartDto> >(accessor.HttpContext.Session.GetString("data"));
            }

            if (listOfShoppingCart.Any(x => x.ProductID == id))
            {
                listOfShoppingCart.Where(x => x.ProductID == id).Select(x => { x.Quantity = x.Quantity + 1; x.Total = x.Quantity * x.Price; return(x); }).ToList();
            }
            else
            {
                ShoppingCartDto dto = new ShoppingCartDto
                {
                    ProductID   = product.ProductID,
                    ProductName = product.ProductName,
                    Description = product.Description,
                    Price       = product.Price,
                    Image       = product.Image,
                    Quantity    = 1,
                    Total       = product.Price
                };

                listOfShoppingCart.Add(dto);
            }

            accessor.HttpContext.Session.SetInt32("counter", listOfShoppingCart.Count);
            accessor.HttpContext.Session.SetString("data", JsonConvert.SerializeObject(listOfShoppingCart));

            return(listOfShoppingCart);
        }
Пример #25
0
        public async Task <ActionResult <ProductDto> > CreateCartAsync()
        {
            try
            {
                var cart = new ShoppingCart
                {
                    DateCreatedUtc = DateTime.UtcNow
                };

                int cartId = await _cartService.CreateCartAsync(cart);

                var dto = new ShoppingCartDto
                {
                    ShoppingCartId = cartId,
                    DateCreatedUtc = cart.DateCreatedUtc.ToString("MM/dd/yyyy HH:mm:ss"),
                };

                return(Ok(dto));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Пример #26
0
        public void GetShoppingCartById_ShoppingCartExists_ReturnShoppingCart()
        {
            //Arrange
            var shoppingCartProductId = 34;
            var shoppingCartProfileId = 21;
            var shoppingCartAmount    = 2;

            var shoppingCartDto = new ShoppingCartDto
            {
                ProductID = shoppingCartProductId,
                ProfileID = shoppingCartProfileId,
                Amount    = shoppingCartAmount,
            };

            _shoppingCartRepoMock.Setup(x => x.GetShoppingCartById(shoppingCartProductId)).Returns(shoppingCartDto);

            //Act
            var shoppingCart = _sut.GetShoppingCartById(shoppingCartProductId);

            //Assert
            Assert.AreEqual(shoppingCartProductId, shoppingCart.ProductID);
            Assert.AreEqual(shoppingCartProfileId, shoppingCart.ProfileID);
            Assert.AreEqual(shoppingCartAmount, shoppingCart.Amount);
        }
Пример #27
0
        public IActionResult Delete(int id)
        {
            cartItems = JsonConvert.DeserializeObject <List <ShoppingCartDto> >(HttpContext.Session.GetString("data"));
            int productQuantity = cartItems.Where(x => x.ProductID == id).Select(x => x.Quantity).FirstOrDefault();

            if (productQuantity == 1)
            {
                ShoppingCartDto removeItem = cartItems.Where(x => x.ProductID == id).FirstOrDefault();
                if (removeItem != null)
                {
                    cartItems.Remove(removeItem);
                    HttpContext.Session.SetString("data", JsonConvert.SerializeObject(cartItems));
                    HttpContext.Session.SetInt32("counter", cartItems.Count);
                }
            }
            else
            {
                cartItems.Where(x => x.ProductID == id).Select(x => { x.Quantity = x.Quantity - 1; x.Total = x.Price * x.Quantity; return(x); }).ToList();
                HttpContext.Session.SetString("data", JsonConvert.SerializeObject(cartItems));
                HttpContext.Session.SetInt32("counter", cartItems.Count);
            }

            return(RedirectToAction("ShoppingCart"));
        }
        public IEnumerable <IShoppingCart> GetAll()
        {
            _connection.SqlConnection.Open();

            var cmd    = new MySqlCommand("SELECT * FROM shoppingcart", _connection.SqlConnection);
            var reader = cmd.ExecuteReader();

            var shoppingCartRecords = new List <IShoppingCart>();

            while (reader.Read())
            {
                var shoppingCart = new ShoppingCartDto
                {
                    ShoppingCartId = (int)reader["ShoppingCartId"],
                    UserId         = (int)reader["UserId"],
                    OrderId        = (int)reader["OrderId"],
                    Date           = DateTime.Parse(reader["Date"]?.ToString() ?? ""),
                    Quantity       = (int)reader["Quantity"]
                };

                shoppingCartRecords.Add(shoppingCart);
            }
            return(shoppingCartRecords);
        }
        public ShoppingCartDto GetShoppingCart(int shoppingCartId)
        {
            var cart = _cartRepo.SingleOrDefault(x => x.Id == shoppingCartId);

            return(ShoppingCartDto.ToDto(cart));
        }
 public GetUserShoppingCartResponse()
 {
     ShoppingCartDto = new ShoppingCartDto();
 }
Пример #31
0
 public async Task CheckoutAsync(ShoppingCartDto shoppingCartDto)
 => await _client.PostAsJsonAsync("o/api/v1/orders", shoppingCartDto);