Exemplo n.º 1
0
        public ActionResult <CartProduct> AddToCart([FromBody] ProductForCart productForCart)
        {
            if (productForCart == null)
            {
                return(BadRequest());
            }

            Product product = productService.GetProductById(productForCart.ProductId);

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

            Client client = clientService.GetClientById(productForCart.ClientId);

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

            var cartProduct = cartProductService.GetProduct(productForCart.ClientId, productForCart.ProductId);

            /*
             * If cartProduct is null this means that the cart doesn't have the selected product
             * then we will add it to the DB
             */
            if (cartProduct == null)
            {
                cartProduct = cartProductService.AddProduct(new CartProduct
                {
                    ProductId = product.Id,
                    Amount    = productForCart.Amount,
                    ClientId  = client.Id
                });
            }
            else
            {
                /*
                 * If cartProduct is not null, it means that the user has already this product in his cart
                 * then we will increment the amount of the desired product and update the entity
                 */

                if (Int32.TryParse(cartProduct.Amount, out int productAmount))
                {
                    productAmount     += Convert.ToInt32(productForCart.Amount);
                    cartProduct.Amount = productAmount.ToString();
                }
                cartProductService.EditProduct(cartProduct);
            }
            return(Ok(cartProduct));
        }