Example #1
0
        public async Task <IActionResult> Create([FromBody] ReservationViewModel model)
        {
            if (model == null)
            {
                return(StatusCode(400, "Invalid parameter(s)."));
            }

            Reservation reservation = new Reservation
            {
                RoomCode    = model.RoomCode,
                UserId      = model.UserId,
                StartTime   = model.StartTime,
                EndTime     = model.EndTime,
                Description = model.Description
            };

            // Return error message when date is not valid
            if (!IsDateValid(reservation.StartTime, false) || !IsDateValid(reservation.EndTime, false))
            {
                return(StatusCode(400, "The date or time is not valid."));
            }
            if (reservation.StartTime > reservation.EndTime)
            {
                return(StatusCode(400, "Start time cannot be later than end time."));
            }

            // Check if reservation timeslot isn't already taken
            var exists = await _reservationRepository.CheckIfReservationExists(reservation);

            if (exists)
            {
                return(StatusCode(500, "The reservation on '" + reservation.StartTime.ToString("MMMM dd") + " at " + reservation.StartTime.ToString("HH:mm") + "' is already taken. Please choose a differenct time or room!"));
            }

            // Insert reservation
            var result = await _reservationRepository.Add(reservation);

            if (result == null)
            {
                return(StatusCode(500, "A problem occured while saving the reservation. Please try again!"));
            }

            // Send email for confirmation
            var user = await _userRepository.Get(reservation.UserId);

            await _email.ReservationConfirmationEmail(user.Email, reservation.RoomCode, reservation.StartTime, reservation.EndTime);

            return(Ok(new ReservationViewModel
            {
                ReservationId = result.ReservationId,
                UserId = result.UserId,
                StartTime = result.StartTime,
                EndTime = result.EndTime,
                RoomCode = result.RoomCode,
                Description = result.Description
            }));
        }