/// <summary>
        /// Creates a new reservation and saves it to the database
        /// </summary>
        /// <param name="request">Create reservation DTO</param>
        /// <returns>The newly created reserrvation DTO</returns>
        public Dto.ReservationResult AddNewReservation(Dto.ReservationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            return(Call(() =>
            {
                //creates a new reservation entity
                var reservation = ReservationFactory.CreateReservation(request.Name, request.ReservationDateTime, request.GuestsCount, request.UserId);

                var entityValidator = EntityValidatorLocator.CreateValidator();
                if (entityValidator.IsValid(reservation))
                {
                    using (var transaction = _reservationRepository.BeginTransaction())
                    {
                        _reservationRepository.Add(reservation);
                        transaction.Commit();
                    }
                }
                else
                {
                    return new Dto.ReservationResult
                    {
                        Status = ActionResultCode.Errored,
                        Message = Messages.validation_errors,
                        Errors = entityValidator.GetInvalidMessages(reservation)
                    };
                }

                //returns success
                return reservation.ProjectedAs <Dto.ReservationResult>();
            }));
        }
示例#2
0
        public Reservation MakeReservation(string loginEmail, int carId, DateTime rentalDate, DateTime returnDate)
        {
            return(ExecuteFaultHandledOperation(() =>
            {
                IAccountRepository accountRepository = _DataRepositoryFactory.GetDataRepository <IAccountRepository>();
                IReservationRepository reservationRepository = _DataRepositoryFactory.GetDataRepository <IReservationRepository>();

                Account account = accountRepository.GetByLogin(loginEmail);

                if (account == null)
                {
                    NotFoundException ex = new NotFoundException(string.Format("No account found for login '{0}'", loginEmail));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                ValidateAuthorization(account);

                Reservation reservation = new Reservation()
                {
                    AccountId = account.AccountId,
                    CarId = carId,
                    RentalDate = rentalDate,
                    ReturnDate = returnDate
                };

                Reservation savedEntity = reservationRepository.Add(reservation);

                return savedEntity;
            }));
        }
        public ReservationDTO Add(ReservationDTO res)
        {
            RESERVATION    resToAdd, addedRes;
            ReservationDTO retVal;

            retVal = null;

            if (CheckHelper.IsFilled(res))
            {
                try
                {
                    resToAdd = transformer.TransformFromDTO(-1, res);
                    AddARandomSeat(resToAdd, res);
                    addedRes = reservationRepository.Add(resToAdd);

                    if (CheckHelper.IsFilled(addedRes))
                    {
                        retVal = transformer.TransformToDTO(addedRes);
                    }
                }
                catch (Exception) { }
            }

            return(retVal);
        }
        public async Task <Reservation> Handle(MakeReservationCommand request, CancellationToken cancellationToken)
        {
            List <MovableResource> movableResources = new List <MovableResource>();

            foreach (var resource in request.MovableResources)
            {
                ResourceType resourceType = (ResourceType)Enum.Parse(typeof(ResourceType), resource);
                movableResources.Add(new MovableResource(resourceType));
            }

            var reservation = await Reservation.CreateReservation(
                request.MeetingRoomId,
                request.EmployeeId,
                request.ReservationDate,
                request.StartTime,
                request.EndTime,
                movableResources,
                _reservationService);


            _logger.LogInformation("----- Making Reservation - Reservation: {@Reservation}", reservation);

            _reservationRepository.Add(reservation);

            await _reservationRepository.UnitOfWork
            .SaveEntitiesAsync(cancellationToken);

            return(reservation);
        }
示例#5
0
        public Reservation UpdateReservation(Reservation reservation)
        {
            return(ExecuteFaultHandledOperation(() =>
            {
                IAccountRepository accountRepository = _DataRepositoryFactory.GetDataRepository <IAccountRepository>();
                IReservationRepository reservationRepository = _DataRepositoryFactory.GetDataRepository <IReservationRepository>();

                Account account = accountRepository.GetByLogin(reservation.Account.LoginEmail);
                if (account == null)
                {
                    NotFoundFault fault = new NotFoundFault(string.Format("No account found for login '{0}'.", reservation.Account.LoginEmail));
                    throw new FaultException <NotFoundFault>(fault, fault.Message);
                }

                ValidateAuthorization(account);

                Reservation updatedEntity = null;

                if (reservation.ReservationID == 0)
                {
                    updatedEntity = reservationRepository.Add(reservation);
                }
                else
                {
                    updatedEntity = reservationRepository.Update(reservation);
                }

                return updatedEntity;
            }));
        }
        public IActionResult Reservation(IFormCollection frm)
        {
            var startDate      = frm["txtStartDate"];
            var endDate        = frm["txtEndDate"];
            var numberOfPerson = frm["txtNoPerson"];
            var roomCount      = frm["txtRoom"];
            var room           = frm["txtRoomType"];

            var SdateConverted = DateTime.Parse(startDate);
            var EdateConverted = DateTime.Parse(endDate);
            var today          = DateTime.Today;
            int resultSE       = DateTime.Compare(SdateConverted, EdateConverted);
            int resultST       = DateTime.Compare(SdateConverted, today);

            if (
                string.IsNullOrWhiteSpace(startDate) ||
                string.IsNullOrWhiteSpace(endDate) ||
                string.IsNullOrWhiteSpace(numberOfPerson) ||
                string.IsNullOrWhiteSpace(roomCount) ||
                string.IsNullOrWhiteSpace(room)
                )
            {
                TempData["Info"] = "Lütfen bütün alanları doldurun.";
                return(RedirectToAction("Index", "Reservation"));
            }

            else if (resultSE < 0)
            {
                TempData["Info"] = "Çıkış tarihiniz giriş tarihinizden önce olamaz.";
                return(RedirectToAction("Index", "Reservation"));
            }
            else if (resultSE == 0)
            {
                TempData["Info"] = "Giriş tarihinizle çıkış tarihiniz aynı olamaz.";
                return(RedirectToAction("Index", "Reservation"));
            }
            else if (resultST < 0)
            {
                TempData["Info"] = "Giriş tarihiniz bugünden önce olamaz.";
                return(RedirectToAction("Index", "Reservation"));
            }
            else
            {
                var PNRCode = new Cryptography().GenerateKey(6, true);

                reservationRepo.Add(new Reservation
                {
                    StartDate      = DateTime.Parse(startDate),
                    EndDate        = DateTime.Parse(endDate),
                    NumberOfPerson = Int32.Parse(numberOfPerson),
                    RoomCount      = Int32.Parse(roomCount),
                    //Room = ,
                    UserID    = CurrentUserID,
                    PNRNumber = PNRCode
                });
            }
            TempData["Info"] = "Ödeme sayfasına yönlendiriliyorsunuz";
            return(RedirectToAction("Index", "Payment"));
        }
示例#7
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
            }));
        }
        public async Task <ReservationDto> Create(ReservationForCreationDto input)
        {
            var reservation = _mapper.Map <Reservation>(input);
            await _repository.Add(reservation);

            var output = _mapper.Map <ReservationDto>(reservation);

            return(output);
        }
示例#9
0
 public int CreateReservation(Reservation reservation)
 {
     try
     {
         _reservationRepository.Add(reservation);
         SaveReservation();
         return(reservation.Id);
     }
     catch { throw; }
 }
示例#10
0
        public void MakeReservation(int carId, DateTime startTime, DateTime endTime)
        {
            var reservation = new Reservation
            {
                CarId     = carId,
                StartDate = startTime,
                EndTime   = endTime,
            };

            _reservationRepository.Add(reservation);
        }
示例#11
0
        public async Task AddReservation(ReservationDto reservationDto)
        {
            var reservation = _mapper.Map <Reservation>(reservationDto);

            reservation.Guid         = Guid.NewGuid();
            reservation.CreationDate = DateTime.Now;
            reservation.IsAccepted   = false;

            _reservationRepository.Add(reservation);
            await _reservationRepository.SaveChangesAsync();
        }
示例#12
0
        public async Task ReserveBook(Guid bookId, string userName)
        {
            var reservation = new ReservationEntity
            {
                ReservationDate = DateTime.Now,
                BookId          = bookId,
                User            = await _userRepository.GetUserEntity(userName)
            };

            await _reservationRepository.Add(reservation);
        }
示例#13
0
        private string AddResveration(Airplane airplane)
        {
            var reservation = new Reservation
            {
                PlaneId   = airplane.Id,
                PlaneType = airplane.Type,
                Slots     = airplane.Size
            };

            _reservationRepository.Add(reservation);
            return("Plane can park.");
        }
示例#14
0
        public async Task <Reservation> Add(Reservation reservationIn)
        {
            var validDuration = await ValidateReservationDuration(reservationIn);

            if (!validDuration)
            {
                throw new ReservationServiceException(_errorHandler.GetMessage(ErrorMessagesEnum.MaximumDurationExceeded)
                                                      , new string[] { nameof(Reservation.End) });
            }

            var availability = await _reservationRepository.CheckResourceAvailability(reservationIn.Start, reservationIn.End, reservationIn.ResourceId);

            if (!availability)
            {
                throw new ReservationServiceException(_errorHandler.GetMessage(ErrorMessagesEnum.NotAvailable)
                                                      , new string[] { nameof(Reservation.Start), nameof(Reservation.End) });
            }
            await _reservationRepository.Add(reservationIn);

            return(reservationIn);
        }
        public IReservation CreateReservation(int roomNumber, string startDate, string endDate, string firstName, string lastName, string email)
        {
            var room = _roomRepo.Find(roomNumber);

            if (IsRoomAvailable(roomNumber, startDate, endDate))
            {
                var reservation = _factory.Create(roomNumber, room.Price, startDate, endDate, firstName, lastName, email);
                _reservationRepo.Add(reservation);
                return(reservation);
            }
            throw new ArgumentException("Room occupied at selected date interval");
        }
示例#16
0
        public int AddReservation(Reservation reservation)
        {
            var roomId = TryGetFreeRoomId(reservation);

            if (!roomId.HasValue)
            {
                throw new Exception("Not Available rooms");
            }

            reservation.RoomId = roomId.Value;
            _reservationRepository.Add(reservation);
            return(roomId.Value);
        }
示例#17
0
        public async Task <IActionResult> Post(List <Reservation> tickets)
        {
            try
            {
                await _dataRepository.Add(tickets);
            }
            catch (DbUpdateException)
            {
                return(BadRequest("Seats are already reserved, please refresh page and select available."));
            }

            return(Ok());
        }
示例#18
0
        public async Task <SimpleResponse> Handle(CreateReservationCommand request,
                                                  CancellationToken cancellationToken)
        {
            var user = await _dbContext.User?.FirstOrDefaultAsync(s => s.Id == request.UserId);

            var untilWhen     = user.IsVip ? DateTime.Now.AddMinutes(Invariants.ReservationLengthForVIPUser) : DateTime.Now.AddMinutes(Invariants.ReservationLengthForRegularUser);
            var reservationId = Guid.NewGuid();
            await _reservationRepository.Add(new Reservation()
            {
                Id        = reservationId,
                UserId    = request.UserId,
                UntilWhen = untilWhen
            });

            return(new SimpleResponse(reservationId));
        }
示例#19
0
        public void Create(ReservationCreateRequestModel reservationCreateRequestModel, User owner)
        {
            if (owner == null)
            {
                throw new ArgumentNullException(nameof(owner));
            }

            if (reservationCreateRequestModel == null)
            {
                throw new ArgumentNullException(nameof(reservationCreateRequestModel));
            }

            var reservation = new Reservation(reservationCreateRequestModel.Date, owner, reservationCreateRequestModel.Difficulty);

            _reservationRepository.Add(reservation);
        }
示例#20
0
        public Reservation Create(EventsUser user, Ticket ticket, int ticketsQuantity)
        {
            var iEvent = eventRepository.GetById(ticket.EventId);

            if (iEvent == null)
            {
                throw new Exception("Event not found!");
            }
            ticket.TicketEvent = iEvent;
            Reservation reservation = new Reservation {
                ReservationId = Guid.NewGuid(), TicketReserved = ticket, TicketsQuantity = ticketsQuantity, User = user
            };

            reservation.TicketReserved.TicketEvent.AvailableTickets -= ticketsQuantity;
            reservationRepository.Add(reservation);
            return(reservation);
        }
示例#21
0
        public async Task <IActionResult> Add(ReservationsViewModel model)
        {
            if (ModelState.IsValid)
            {
                Flight flight = _flightRepository.Items.SingleOrDefault(item => item.Id == model.Id);
                model.FlightId = flight.Id;
                model.Flight   = flight;
                if (model.Flight.CapacityEconomyPassengers >= model.PassengersEconomyCount && model.Flight.CapacityBusinessPassengers >= model.PassengersBusinessCount)
                {
                    Reservation reservation = new Reservation()
                    {
                        FlightId = model.FlightId,
                        Flight   = flight,
                        Email    = model.Email,
                        PassengersEconomyCount  = model.PassengersEconomyCount,
                        PassengersBusinessCount = model.PassengersBusinessCount,
                        Passengers = null
                    };

                    await _reservationRepository.Add(reservation);

                    await _flightRepository.Update(flight);

                    return(RedirectToAction("AddPassengers", reservation));
                }
                else
                {
                    if (model.Flight.CapacityEconomyPassengers < model.PassengersEconomyCount &&
                        model.Flight.CapacityBusinessPassengers < model.PassengersBusinessCount)
                    {
                        ViewData["Message"] = "This flight does not have this much free economy and business seats";
                    }
                    else if (model.Flight.CapacityBusinessPassengers < model.PassengersBusinessCount)
                    {
                        ViewData["Message"] = "This flight does not have this much free business seats";
                    }
                    else if (model.Flight.CapacityEconomyPassengers < model.PassengersEconomyCount)
                    {
                        ViewData["Message"] = "This flight does not have this much free economy seats";
                    }
                    return(View(model));
                }
            }
            return(View(model));
        }
        public async Task <ViewResult> ReservationAsync(ReservationViewModel reservationViewModel, int id)
        {
            // check if we have valid data in the form
            if (ModelState.IsValid)
            {
                var user = await GetCurrentUserAsync();

                Reservation newReservation = new Reservation
                {
                    UserId    = user.Id,
                    CarId     = id,
                    StartDate = reservationViewModel.StartDate,
                    EndDate   = reservationViewModel.EndDate
                };

                _reservationRepository.Add(newReservation);
                return(View("ReservationComplete"));
            }
            return(View());
        }
 public CreateResponse Create(ReservationRequest request)
 {
     try
     {
         var reservation = TypeAdapter.Adapt <Reservation>(request);
         _reservationValidator.ValidateAndThrowException(reservation, "Base,Create");
         _reservationRepository.Add(reservation);
         var reservationDetails = _reservationDetailFactory.BySaucer(reservation.SaucerId);
         reservationDetails.ForEach(reservationDetail =>
         {
             reservationDetail.ReservationId = reservation.Id;
             _reservationDetailRepository.Add(reservationDetail);
         });
         return(new CreateResponse(reservation.Id));
     }
     catch (DataAccessException)
     {
         throw new ApplicationException();
     }
 }
示例#24
0
        public ActionResult Create(ReservationViewModels reservationViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "The Information is Not Vaild"));
            }
            if (!CheckRoom(reservationViewModel, User.Identity.GetUserId()))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "The Room is Already Reserved please see Reservations"));
            }


            Reservation reservation = new Reservation()
            {
                UserID          = User.Identity.GetUserId(),
                ReservationDate = reservationViewModel.CheckIn,
                DepatureDate    = reservationViewModel.CheckOut,
                Checkout        = false,
                IsApproved      = false,
                IsDeleted       = false,
                LeavingDate     = null,
                ComingDate      = null,
                RoomID          = reservationViewModel.RoomID,
            };

            _reservation.Add(reservation);
            _reservation.CloseTheRoomForReservation(reservationViewModel.RoomID);
            if (_reservation.SaveChanges() > 0)
            {
                //send Data to Desktop Application // if we using signalR
                //var Ihub = GlobalHost.ConnectionManager.GetHubContext<ReservationHub>();
                //Ihub.Clients.All.SendMessage(reservation.RoomID, reservation.UserID,reservation.ReservationDate,reservation.DepatureDate);

                this.roomReposity.SaveChanges();
                return(Json(new { result = true }));
            }
            else
            {
                return(Json(new { result = false }));
            }
        }
示例#25
0
        public async Task <Reservation> CreateClientReservation(CreateReservationModel newReservation)
        {
            var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

            var reservation = new Reservation()
            {
                UserId    = int.Parse(userId),
                CarId     = newReservation.CarId,
                StartDate = newReservation.StartDate,
                EndDate   = newReservation.EndDate
            };

            if (!await IsReservationIntervalValid(reservation))
            {
                throw new InvalidInputException("Date interval is not valid!");
            }

            _reservationRepository.Add(reservation);
            await _reservationRepository.SaveAll();

            return(reservation);
        }
示例#26
0
        public IActionResult Post(Reservation reservation)
        {
            // Validations
            if (reservation.StartDate > reservation.EndDate)
            {
                return(BadRequest());
            }

            var currentUser = GetCurrentUserProfile();

            reservation.CustomerId = currentUser.Id;

            try
            {
                _reservationRepository.Add(reservation);
                return(CreatedAtAction("Get", new { id = reservation.Id }, reservation));
            }
            catch
            {
                return(StatusCode(500));
            }
        }
示例#27
0
 public Reservation Add(Reservation reservation, string accommodationName)
 {
     try
     {
         if (!ValidAmountOfGuests(reservation))
         {
             throw new ArgumentOutOfRangeException();
         }
         Accommodation accommodationForReservation = accommodationLogic.GetByName(accommodationName);
         if (accommodationForReservation is null)
         {
             throw new ObjectNotFoundInDatabaseException();
         }
         if (!accommodationForReservation.FullCapacity)
         {
             reservation.AccommodationForReservation = accommodationForReservation;
             reservation.SetInfoText();
             reservation.SetPhoneNumber();
             return(reservationRepository.Add(reservation));
         }
         else
         {
             throw new Exception();
         }
     }
     catch (ObjectNotFoundInDatabaseException e)
     {
         throw new ObjectNotFoundInDatabaseException();
     }
     catch (ArgumentOutOfRangeException a)
     {
         throw new ArgumentOutOfRangeException();
     }
     catch (Exception ex)
     {
         throw new Exception();
     }
 }
示例#28
0
        public void AddReservation(ReservationDto reservationDto, int userId)
        {
            Reservation reservation = _mapper.Map <Reservation>(reservationDto);

            if (reservation.Date < DateTime.Now)
            {
                throw new ValidationException("Reservation date cannot be before current");
            }

            if (!_reservationRepository.CheckIfAvalible(reservation))
            {
                throw new ValidationException("Given date is not avalible");
            }

            if (!ValidateReservation(reservation))
            {
                throw new ValidationException("Unavalible at given day");
            }

            reservation.UserId    = userId;
            reservation.Confirmed = false;
            _reservationRepository.Add(reservation);
        }
示例#29
0
        //public ReservationService() { }

        public bool ReserveBook(int bookID, string username)
        {
            if (isBookUnavaliable(bookID))
            {
                return(false);
            }
            var book = _bookRepository.GetByID(bookID);
            var user = _userRepository.GetByUsername(username);

            UpdateBookStatus(bookID, "Reserved");
            var date        = DateTime.Now;
            var reservation = new Reservation
            {
                Id              = RandomNumber(10000, 100000),
                BookId          = bookID,
                Book            = book,
                CustomerId      = user.Id,
                User            = user,
                ReservationDate = date
            };

            _reservationRepository.Add(reservation);
            return(true);
        }
示例#30
0
 public Reservation CreateReservation(Reservation item)
 {
     return(repo.Add(item));
 }