Example #1
0
        /// <inheritdoc />
        public async Task <RequestDto> MakeAsync(int userId, int bookId)
        {
            var book = await _bookRepository.GetAll().Include(x => x.User).FirstOrDefaultAsync(x => x.Id == bookId);

            var isNotAvailableForRequest = book == null || book.State != BookState.Available;

            if (isNotAvailableForRequest)
            {
                return(null);
            }

            if (userId == book.UserId)
            {
                throw new InvalidOperationException("You cannot request your book");
            }

            var user = await _userRepository.FindByIdAsync(userId);

            if (user.IsDeleted)
            {
                throw new InvalidOperationException("As deleted user you cannot request books");
            }

            var request = new Request()
            {
                BookId      = book.Id,
                OwnerId     = book.UserId,
                UserId      = userId,
                RequestDate = DateTime.UtcNow
            };

            _requestRepository.Add(request);
            await _requestRepository.SaveChangesAsync();

            book.State = BookState.Requested;
            await _bookRepository.SaveChangesAsync();

            if (book.User.IsEmailAllowed)
            {
                var emailMessageForRequest = new RequestMessage()
                {
                    OwnerName    = book.User.FirstName + " " + book.User.LastName,
                    BookName     = book.Name,
                    RequestDate  = request.RequestDate,
                    RequestId    = request.Id,
                    OwnerAddress = new MailboxAddress($"{book.User.Email}"),
                    UserName     = user.FirstName + " " + user.LastName
                };
                await _emailSenderService.SendForRequestAsync(emailMessageForRequest);
            }

            await _notificationsService.NotifyAsync(
                book.User.Id,
                $"Your book '{book.Name}' was requested by {user.FirstName} {user.LastName}",
                book.Id,
                NotificationAction.Open);

            await _notificationsService.NotifyAsync(
                user.Id,
                $"The book '{book.Name}' successfully requested.",
                book.Id,
                NotificationAction.Open);

            var emailMessageForReceiveConfirmation = new RequestMessage()
            {
                UserName    = user.FirstName + " " + user.LastName,
                BookName    = book.Name,
                BookId      = book.Id,
                RequestId   = request.Id,
                UserAddress = new MailboxAddress($"{user.Email}"),
                User        = user
            };
            await _hangfireJobScheduleService.ScheduleRequestJob(emailMessageForReceiveConfirmation);

            return(_mapper.Map <RequestDto>(request));
        }