public async Task BookProduct(BookProductDto bookProduct)
        {
            Product     product;
            User        user;
            BookProduct book;

            product = await Repository.GetByIdAsync(bookProduct.ProductId);

            user = await UserRepository.GetByEmail(bookProduct.Email);

            if (product == null || user == null)
            {
                throw new KeyNotFoundException();
            }

            book = ProductRepository.GetBookByPersonAndProduct(user.Id, product.Id);

            if (book == null)
            {
                book = new BookProduct
                {
                    ProductId = product.Id,
                    UserID    = user.Id,
                    Quantity  = 1
                };
                await ProductRepository.CreateAsync(book);
            }

            if (bookProduct.Value < 0)
            {
                book.Quantity             -= 1;
                product.AvailableQuantity += 1;
            }
            else
            {
                book.Quantity             += 1;
                product.AvailableQuantity -= 1;
            }

            if (product.AvailableQuantity == 0)
            {
                throw new InvalidOperationException("There is no more quantity available");
            }

            if (product.AvailableQuantity > product.Quantity)
            {
                throw new InvalidOperationException("There is no more quantity available");
            }

            await ProductRepository.UpdateAsync(book);

            await Repository.UpdateAsync(product);
        }
Exemple #2
0
        public async Task <IActionResult> BookProduct([FromBody] BookProductDto bookProduct)
        {
            try
            {
                await ProductsBusiness.BookProduct(bookProduct);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }