Beispiel #1
0
        public async Task LeaseBookAsync(BookLeaseViewModel bookLeaseViewModel)
        {
            var storableBook = await _bookStorage.GetAll().FirstOrDefaultAsync(x => x.BookId == bookLeaseViewModel.BookId);

            _bookRentValidator.AfterLeaseValidate(storableBook, bookLeaseViewModel);

            using var transaction = new CommittableTransaction(new TransactionOptions
                                                               { IsolationLevel = IsolationLevel.ReadCommitted });
            try
            {
                storableBook.Free--;
                await _bookStorage.SaveAsync(storableBook);

                await _bookRent.SaveAsync(new BookRent
                {
                    BookId      = bookLeaseViewModel.BookId,
                    CustomerId  = bookLeaseViewModel.CustomerId,
                    StartRent   = DateTime.Now,
                    PlanEndRent = bookLeaseViewModel.PlanEndDate,
                });

                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                // log error
                throw e;
            }
        }
        public void AfterLeaseValidate(BookStorage storableBook, BookLeaseViewModel bookLeaseViewModel)
        {
            if (storableBook == null)
            {
                throw new ValidationException("Данной книги нет в хранилище.");
            }

            if (_bookRent.GetAll().Any(x =>
                                       x.CustomerId == bookLeaseViewModel.CustomerId &&
                                       x.BookId == bookLeaseViewModel.BookId &&
                                       !x.FactEndRent.HasValue))
            {
                throw new ValidationException("У клиента уже есть данная книга в аренде.");
            }

            if (storableBook.Free == 0)
            {
                throw new ValidationException("Экземпляров книги больше нет в наличии.");
            }
        }
        public async Task <IActionResult> LeaseOne([FromBody] BookLeaseViewModel bookLeaseViewModel)
        {
            await _bookRentService.LeaseBookAsync(bookLeaseViewModel);

            return(Ok());
        }