示例#1
0
        public async Task <CartDTO> AddAsync(ProductCartPostRequest model, ApiDbContext apiDbContext)
        {
            try
            {
                Product product = await apiDbContext.Products.FindAsync(model.ProductId);

                if (product == null)
                {
                    throw new Exception($"Error cargadndo el producto con id {model.ProductId}");
                }

                if (product.Stock.Avaliable < model.Quantity)
                {
                    throw new Exception($"Stock insuficiente. Unidades restantes: {product.Stock.Avaliable}");
                }

                apiDbContext.Users_Products_Cart.Add(new User_Product_Cart
                {
                    IsCompleted = false,
                    ProductId   = model.ProductId,
                    UserId      = model.UserId,
                    Quantity    = model.Quantity
                });

                product.Stock.Avaliable -= model.Quantity;

                await apiDbContext.SaveChangesAsync();

                return(ModelToDTO(apiDbContext.Users_Products_Cart.Where(pc => !pc.IsCompleted && pc.UserId == model.UserId).ToList()));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
示例#2
0
        public async Task <IActionResult> Add(ProductCartPostRequest model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("Petición de alta inválida");
                }

                return(Ok(await _cartService.AddAsync(model, _apiDbContext)));
            }
            catch (Exception e)
            {
                return(StatusCode(500, e.Message));
            }
        }