public async Task TryLoanBook_BookNotInStock_BookLoaned()
        {
            // Arrange
            var context = _inMemoryLibraryContextFactory.Create();
            var user    = new User("FirstName", "LastName", new Email("*****@*****.**"), UserRolesConsts.Reader);

            context.Users.Add(user);
            context.SaveChanges();

            var book = new Book("Title", new Author("FirstName", "LastName"), 2020, "Description");

            book.Borrow();
            context.Books.Add(book);
            context.SaveChanges();

            var bookLoan = new BookLoan(book.Id, user.Id);

            context.BookLoans.Add(bookLoan);

            _userRepositoryMock.Setup(x => x.GetAsync(user.Id)).ReturnsAsync(user);
            _bookRepositoryMock.Setup(x => x.GetAsync(book.Id)).ReturnsAsync(book);

            // Act
            var result = await _sut.TryLoanBook(bookLoan);

            // Assert
            result.Should().BeFalse();
            bookLoan.IsPending.Should().BeTrue();
        }
Example #2
0
        public async Task <BookLoanInfoDTO> Handle(BookLoanCommand command, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetAsync(command.UserId);

            if (user == null)
            {
                throw new UserNotFoundException(command.UserId);
            }
            var book = await _bookRepository.GetAsync(command.BookId);

            if (book == null)
            {
                throw new BookNotFoundException(command.BookId);
            }
            if (user.BookLoans.Any(x => x.BookId == command.BookId && (x.IsBorrowed || x.IsPending)))
            {
                throw new LibraryDomainException(
                          $"User with id: {command.UserId} has already unfinished order for book with id: {command.BookId}");
            }

            var bookLoan = new BookLoan(command.BookId, command.UserId);
            await _bookLoanService.TryLoanBook(bookLoan);

            _bookLoanRepository.Create(bookLoan);
            await _bookLoanRepository.UnitOfWork.SaveChangesAsync();

            return(_bookLoanMapper.Map(bookLoan));
        }
Example #3
0
        public static async Task ReturnBook(BookLoan bookrent)
        {
            var bc = bookrent.BookCopy;

            if (bc == null)
            {
                bc = await GetBookCopy(new BookCopy()
                {
                    ID = bookrent.BookCopyID
                });
            }

            bc.State = (int)BookCopyState.Available;

            var r = new BookRentRecord()
            {
                BookCopyID = bookrent.BookCopyID,
                RentDate   = bookrent.RentDate,
                DeadLine   = bookrent.DeadLine,
                RetrunDate = DateTime.Now,
                UserID     = bookrent.UserID,
            };

            await conn.DeleteAsync(bookrent);

            await conn.InsertAsync(r);

            await conn.UpdateAsync(bc);
        }
Example #4
0
        public async Task <IActionResult> PutBookLoan(int id, BookLoan bookLoan)
        {
            if (id != bookLoan.Id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
Example #5
0
        //Permitir Reserva de Livros se:
        //Se Estoque de livro for > 0
        //Se livro não estiver descontinuado (inativo)
        //Se usuario nao estiver bloqueado
        //Se usuário não estiver dois empréstimos em progresso
        //Se data informada for menor que 30 dias
        //Se instituição nao estiver inativa
        public async Task <ReturnModel> BookReservation(BookLoanRequest request)
        {
            var(condition, errorMsg) = await CanUserLoanBook(request.UserId, request.BookId, request.LoanUntil);

            if (!condition)
            {
                return new ReturnModel {
                           Errors = errorMsg
                }
            }
            ;

            var bookInventory = await _bookInventoryRepository.GetByBookId(request.BookId);

            bookInventory.Quantity -= 1;
            await _bookInventoryRepository.Update(bookInventory);

            var bookLoan = new BookLoan
            {
                BeginDate    = DateTime.Now,
                EndDate      = request.LoanUntil,
                BookId       = request.BookId,
                UserId       = request.UserId,
                LoanStatusId = (int)BookLoanStatus.BookReserved
            };
            var result = await _bookLoanRepository.Insert(bookLoan);

            return(new ReturnModel {
                Data = _mapper.Map <BookLoanModel>(result)
            });
        }
Example #6
0
        private static BookLoan ReadingBookData(long bookTumbleNumber, long idCustomer)
        {
            DateTime dod;
            bool     dodIsPast;

            do
            {
                Console.Write("Data da devolução: ");
                string devolutionDate = Console.ReadLine();
                DateTime.TryParse(devolutionDate, out dod);
                if (DateTime.Compare(dod, DateTime.Now.Date) < 0)
                {
                    dodIsPast = true;
                    Console.WriteLine("A data tem que ser igual ou posterior a data de hoje!!");
                }
                else
                {
                    dodIsPast = false;
                }
            } while (dod.ToString("dd/MM/yyyy") == "01/01/0001" || dodIsPast);

            BookLoan bookLoan = new BookLoan
            {
                IdCustomer     = idCustomer,
                TumbleNumber   = bookTumbleNumber,
                LoanDate       = DateTime.Now,
                DevolutionDate = dod,
                LoanStatus     = 1
            };

            return(bookLoan);
        }
Example #7
0
        public async Task <ReturnBookCommandResponseViewModel> Handle(ReturnBookCommand request, CancellationToken cancellationToken)
        {
            ReturnBookCommandResponseViewModel response = new ReturnBookCommandResponseViewModel();

            if (!request.ValidateBookLoanGuid())
            {
                return(response);
            }

            BookLoan bookLoan = await _bookLoanRepository.GetByLoanId(Guid.Parse(request.LoanId), true);

            if (!request.ValidateBookLoanExists(bookLoan))
            {
                return(response);
            }

            if (!bookLoan.ReturnBook())
            {
                return(response);
            }

            _bookLoanRepository.Update(bookLoan);

            return(response);
        }
Example #8
0
        public async Task <IActionResult> Create([Bind("BookId,LoanId,DeleteFlag,LoanDate,LoanReturnDate")] BookLoan bookLoan)
        {
            int CountOfBooks = context.GetBookById(bookLoan.BookId).BookAmount;

            if (CountOfBooks > 0)
            {
                bookLoan.LoanDate = DateTime.Now;
                if (ModelState.IsValid)
                {
                    context.Create(bookLoan);
                    return(RedirectToAction(nameof(Index)));
                }
                var books = context.GetAllBooks();
                var loans = context.GetAllLoans();
                ViewData["BookId"] = new SelectList(books, "BookId", "BookName", bookLoan.BookId);
                ViewData["LoanId"] = new SelectList(loans, "LoanId", "LoanPFname", bookLoan.LoanId);
                return(View(bookLoan));
            }
            else
            {
                TempData["AmountError"] = "The Amount of this book doesn't allow this operation";
                var books = context.GetAllBooks();
                var loans = context.GetAllLoans();
                ViewData["BookId"] = new SelectList(books, "BookId", "BookName", bookLoan.BookId);
                ViewData["LoanId"] = new SelectList(loans, "LoanId", "LoanPFname", bookLoan.LoanId);
                return(View(bookLoan));
            }
        }
Example #9
0
        public async Task <IActionResult> Edit(int id, [Bind("BookLoanID,LoanDate,DevolutionDate,DevolutionDateMade,UserID,BookID")] BookLoan bookLoan)
        {
            if (id != bookLoan.BookLoanID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(bookLoan);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BookLoanExists(bookLoan.BookLoanID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["BookID"] = new SelectList(_context.Book, "BookID", "Edition", bookLoan.BookID);
            return(View(bookLoan));
        }
Example #10
0
        public UserBookLoanDTO AddUserBookLoanByBookId(int userId, int bookId)
        {
            if (_repo.getUserById(userId) == null)
            {
                throw new UserNotFoundException();
            }
            if (_bookRepo.getBookById(bookId) == null)
            {
                throw new BookNotFoundException();
            }
            try
            {
                if (_repo.GetBookLoan(userId, bookId) != null)
                {
                    throw new AlreadyBorrowedByUserException();
                }
            }
            catch (BookLoanNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
            var newLoan = new BookLoan
            {
                DateOfLoan = DateTime.Now,
                BookId     = bookId,
                UserId     = userId
            };

            _repo.AddBookLoan(newLoan);
            return(GetUserBookLoanByBookId(userId, bookId));
        }
        public async Task <IActionResult> Checkout(int BookID, int StudentID)
        {
            if (ModelState.IsValid && isBookCheckedOut(BookID) == false)
            {
                int CheckoutDuration =
                    _context.Settings
                    .Select(s => s.CheckoutDurationInDays)
                    .FirstOrDefault();


                var bookloan = new BookLoan()
                {
                    BookID       = BookID,
                    StudentID    = StudentID,
                    CheckedOutOn = DateTime.Now,
                    DueOn        = DateTime.Now.AddDays(CheckoutDuration)
                };

                _context.Add(bookloan);
                await _context.SaveChangesAsync();

                ViewBag.SuccessfullyCheckedOut = "Successfully checked out!";
                return(RedirectToAction("Index"));
            }
            else
            {
                return(RedirectToAction("CheckedOut"));
            }
        }
Example #12
0
        public async Task <IActionResult> Edit(int BlId, [Bind("BlId,BookId,LoanId,DeleteFlag,LoanDate,LoanReturnDate")] BookLoan bookLoan)
        {
            if (BlId != bookLoan.BlId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    bookLoan.LoanDate = DateTime.Now;
                    context.Edit(bookLoan);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BookLoanExists(BlId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            var books = context.GetAllBooks();
            var loans = context.GetAllLoans();

            ViewData["BookId"] = new SelectList(books, "BookId", "BookName", bookLoan.BookId);
            ViewData["LoanId"] = new SelectList(loans, "LoanId", "LoanPFname", bookLoan.LoanId);
            return(View(bookLoan));
        }
Example #13
0
        public async Task <ActionResult <BookLoan> > PostBookLoan(BookLoan bookLoan)
        {
            _context.BookLoan.Add(bookLoan);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBookLoan", new { id = bookLoan.Id }, bookLoan));
        }
Example #14
0
        private static List <BookLoan> ConvertFileToList()
        {
            List <BookLoan> loanedsBooks = new List <BookLoan>();
            FileHandler     file         = new FileHandler();

            string[] fileContent;

            file.FileName = "EMPRESTIMO.csv";

            fileContent = FileHandlerController.ReadFile(file);

            if (fileContent != null)
            {
                foreach (var lineContent in fileContent)
                {
                    string[] lineLoan = lineContent.Split(';');

                    BookLoan bookLoan = new BookLoan
                    {
                        IdCustomer     = long.Parse(lineLoan[0]),
                        TumbleNumber   = long.Parse(lineLoan[1]),
                        LoanDate       = Convert.ToDateTime(lineLoan[2]),
                        DevolutionDate = Convert.ToDateTime(lineLoan[3]),
                        LoanStatus     = int.Parse(lineLoan[4])
                    };

                    loanedsBooks.Add(bookLoan);
                }
            }

            return(loanedsBooks);
        }
        public void When_the_loan_is_indefinite()
        {
            var loan = new BookLoan();
            loan.MemberName = "Jill";

            Assert.IsFalse(loan.IsDue());
        }
Example #16
0
        public async Task <IActionResult> CreateBookLoan(Guid?id)
        {
            if (id != null)
            {
                var libAccounts = await _context.LibAccounts.Include(l => l.Owner).ToListAsync();

                var newBookItem = await _context.BookItems.SingleOrDefaultAsync(b => b.ID == id);

                var newLoan = new BookLoan
                {
                    BookItemID = newBookItem.ID,
                };

                var bookLoanData = new BookLoanData
                {
                    loan        = newLoan,
                    libAccounts = libAccounts,
                    bookItem    = newBookItem
                };

                return(View(bookLoanData));
            }

            return(RedirectToAction(nameof(Index)));
        }
        public async Task ReturnBook_BorrowedBook_BookReturned()
        {
            // Arrange
            var context = _inMemoryLibraryContextFactory.Create();
            var user    = new User("FirstName", "LastName", new Email("*****@*****.**"), UserRolesConsts.Reader);

            context.Users.Add(user);
            context.SaveChanges();

            var book = new Book("Title", new Author("FirstName", "LastName"), 2020, "Description");

            book.Borrow();
            context.Books.Add(book);
            context.SaveChanges();

            var bookLoan = new BookLoan(book.Id, user.Id);

            context.BookLoans.Add(bookLoan);
            bookLoan.SetBookBorrowed();

            _userRepositoryMock.Setup(x => x.GetAsync(user.Id)).ReturnsAsync(user);
            _bookRepositoryMock.Setup(x => x.GetAsync(book.Id)).ReturnsAsync(book);
            _bookRepositoryMock.SetupGet(x => x.UnitOfWork).Returns(_unitOfWorkMock.Object);

            // Act
            await _sut.ReturnBook(user.Id, book.Id);

            // Assert
            bookLoan.IsReturned.Should().BeTrue();
            book.InStock.Should().BeTrue();
        }
Example #18
0
        public void When_the_loan_is_due()
        {
            var loan = new BookLoan {
                MemberName = "Jill", DueDate = new DateTime(2000, 12, 31)
            };

            Assert.IsTrue(loan.IsDue());
        }
Example #19
0
        public void When_the_loan_is_indefinite()
        {
            var loan = new BookLoan {
                MemberName = "Jill"
            };

            Assert.IsFalse(loan.IsDue());
        }
        public void ReturnDueDate_BorrowedBookLoan_CorrectReturnDueDate()
        {
            var bookLoan = new BookLoan(1, 1);

            bookLoan.SetBookBorrowed();

            bookLoan.ReturnDueDate.Should().Be(bookLoan.BorrowedDate.Value.AddDays(BookLoan.LoanDaysLimit));
        }
        public void When_the_loan_is_not_yet_due()
        {
            var loan = new BookLoan();
            loan.MemberName = "Jill";
            loan.DueDate = new DateTime(2100, 12, 31);

            Assert.IsFalse(loan.IsDue());
        }
        public void Create(BookLoan bookloan)
        {
            BookLoan.Add(bookloan);
            var book = GetBookById(bookloan.BookId);

            book.BookAmount = book.BookAmount - 1;
            Book.Update(book);
        }
Example #23
0
 public static async Task <bool> AddBookRent(BookLoan bookrent)
 {
     if (bookrent.BookCopy == null || bookrent.User == null)
     {
         return(false);
     }
     return(await conn.InsertAsync(bookrent) == 1);
 }
        public void Create_BookLoan_CreatedPendingBookLoan()
        {
            var bookLoan = new BookLoan(1, 1);

            bookLoan.Should().NotBeNull();
            bookLoan.IsPending.Should().BeTrue();
            bookLoan.IsBorrowed.Should().BeFalse();
            bookLoan.IsReturned.Should().BeFalse();
        }
        public void When_the_loan_is_not_yet_due()
        {
            var loan = new BookLoan();

            loan.MemberName = "Jill";
            loan.DueDate    = new DateTime(2100, 12, 31);

            Assert.IsFalse(loan.IsDue());
        }
        public void Delete(BookLoan bookloan)
        {
            bookloan.DeleteFlag = 1;
            BookLoan.Update(bookloan);
            var book = GetBookById(bookloan.BookId);

            book.BookAmount = book.BookAmount + 1;
            Book.Update(book);
        }
        public void FinishLoan_BookLoan_BookLoanInReturnedState()
        {
            var bookLoan = new BookLoan(1, 1);

            bookLoan.FinishLoan();

            bookLoan.IsPending.Should().BeFalse();
            bookLoan.IsBorrowed.Should().BeFalse();
            bookLoan.IsReturned.Should().BeTrue();
        }
        public void SetBookBorrowed_BookLoan_BookLoanInBorrowedState()
        {
            var bookLoan = new BookLoan(1, 1);

            bookLoan.SetBookBorrowed();

            bookLoan.IsPending.Should().BeFalse();
            bookLoan.IsBorrowed.Should().BeTrue();
            bookLoan.IsReturned.Should().BeFalse();
        }
Example #29
0
        public void ValidateBookLoan_Lend_ShouldReturnNoErrors()
        {
            //arrage
            Book     book     = BookFactory.ReturnBook().WithBookSituation(BookSituationEnum.Awaiting);
            BookLoan bookLoan = new BookLoan(Guid.NewGuid(), book, PersonFactory.ReturnPerson());

            //act
            bookLoan.LendBook();
            //assert
            DomainNotifications.GetAll().Should().BeEmpty();
        }
Example #30
0
        public void ValidateBookLoan_Return_ShouldReturnNoErrors()
        {
            //arrage
            BookLoan bookLoan = new BookLoan(Guid.NewGuid(), BookFactory.ReturnBook().WithBookSituation(BookSituationEnum.Lent), PersonFactory.ReturnPerson());

            //act
            bookLoan.ReturnBook();
            //assert
            DomainNotifications.GetAll().Should().BeEmpty();
            bookLoan.Book.BookSituation.Value.Should().Be(BookSituationEnum.Awaiting.Value);
        }
        public void FinishLoan_BookLoan_AddBookLoanFinishedEvent()
        {
            var bookLoan = new BookLoan(1, 1);

            bookLoan.FinishLoan();

            bookLoan.DomainEvents.Count.Should().Be(1);
            var bookReturnedEvent = bookLoan.DomainEvents.First();

            (bookReturnedEvent is BookLoanFinishedEvent).Should().BeTrue();
        }
        public void AddLoan(int customerID, int bookID)
        {
            using var context = new LibraryContext();
            var bookLoan = new BookLoan();

            bookLoan.BookID     = bookID;
            bookLoan.CustomerID = customerID;
            bookLoan.IsActive   = true;

            context.BookLoans.Add(bookLoan);
            context.SaveChanges();
        }
        public void When_the_loan_is_due()
        {
            var loan = new BookLoan("Jill", new DateTime(2000, 12, 31));

            Assert.IsTrue(loan.IsDue());
        }
        public void When_the_loan_is_indefinite()
        {
            var loan = new BookLoan("Jill");

            Assert.IsFalse(loan.IsDue());
        }
        public void When_the_loan_is_not_yet_due()
        {
            var loan = new BookLoan("Jill", new DateTime(2100, 12, 31));

            Assert.IsFalse(loan.IsDue());
        }
        public void When_the_loan_is_due()
        {
            var loan = new BookLoan {MemberName = "Jill", DueDate = new DateTime(2000, 12, 31)};

            Assert.IsTrue(loan.IsDue());
        }