Esempio n. 1
0
        public async Task <IActionResult> CreateBooking([FromBody] SaveBookingResource bookingResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var booking = mapper.Map <SaveBookingResource, Booking>(bookingResource);

            var roomExist     = repository.BookingRoomExist(booking);
            var offeringExist = repository.BookingOfferingExist(booking);

            if (roomExist && offeringExist)
            {
                return(Conflict("The room and module is already taken"));
            }
            else if (roomExist)
            {
                return(Conflict("The room is already taken"));
            }
            else if (offeringExist)
            {
                return(Conflict("The module is already booked in the same time slot"));
            }

            repository.Add(booking);
            await unitOfWork.CompleteAsync();

            booking = await repository.GetBooking(booking.Id);

            var result = mapper.Map <Booking, BookingResource>(booking);

            return(Ok(result));
        }
Esempio n. 2
0
        public Task <IResult <Booking> > AddAsync(Booking booking)
        {
            var bookValidationResult = new AddNewBookingValidation().Validate(booking);

            if (!bookValidationResult.IsValid)
            {
                return(new ErrorResult <Booking>(bookValidationResult.Errors.FirstOrDefault()?.ErrorMessage ?? string.Empty).ToTask());
            }

            if (_customerRepository.GetById(booking.Customer.Id) == null)
            {
                throw new ExceptionHandler(HttpStatusCode.NotFound, $"Customer id {booking.Customer.Id} not found.");
            }

            if (_bookRepository.GetById(booking.Book.Id) == null)
            {
                throw new ExceptionHandler(HttpStatusCode.NotFound, $"Book id {booking.Book.Id} not found.");
            }

            var bookingEntity = _bookingRepository.Add(booking);

            if (!_unitOfWork.Commit())
            {
                throw new ExceptionHandler(HttpStatusCode.BadRequest, "A problem occurred during saving the data.");
            }

            return(new SuccessResult <Booking>(bookingEntity).ToTask());
        }
        public async Task <int> HandleAsync(CreateBookingCommand message, CancellationToken cancellationToken)
        {
            var court = await bookingRepository.GetCourtAsync(message.CourtId);

            var booking = new Domain.Model.Booking(message.PhoneNo, court, message.BookedFrom);

            bookingRepository.Add(booking);

            return(await bookingRepository.UnitOfWork.SaveChangesAsync(cancellationToken));
        }
Esempio n. 4
0
        public IActionResult Index(Booking model, LU_Treatment models)
        {
            var obj = new Booking();

            obj.Name       = model.Name;
            obj.Mobile     = model.Mobile;
            obj.Email      = model.Email;
            obj.Note       = model.Note;
            obj.BookedDate = model.BookedDate;
            _bookingRepository.Add(obj);
            return(View());
        }
Esempio n. 5
0
        public async Task <IActionResult> CreateReview(int userId, ReviewForCreationDto ReviewForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            ReviewForCreationDto.SenderId = userId;

            var hotelRecipient = await _repo.GetHotel(ReviewForCreationDto.RecipientId);

            if (hotelRecipient == null)
            {
                return(BadRequest("Could not find this hotel"));
            }

            var review = _mapper.Map <Review>(ReviewForCreationDto);

            _repo.Add(review);

            var reviewToReturn = _mapper.Map <ReviewForCreationDto>(review);

            if (await _repo.SaveAll())
            {
                return(CreatedAtRoute("GetReview", new { id = review.Id }, reviewToReturn));
            }

            throw new Exception("Creating the review failed on save");
        }
        public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto)
        {
            var user = await _repo.GetUser(userId);

            if (user.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            messageForCreationDto.SenderId = userId;

            // Gets another user, recipient to the this single Post call. Might be the fix your looking for?
            var recipient = await _repo.GetUser(messageForCreationDto.RecipientId);

            if (recipient == null)
            {
                return(BadRequest("Could not find user"));
            }

            var message = _mapper.Map <Message>(messageForCreationDto);

            _repo.Add(message); // Dont need to make await

            var messageToReturn = _mapper.Map <MessageForCreationDto>(message);

            if (await _repo.SaveAll())
            {
                return(CreatedAtRoute("GetMessage", new { userId, id = message.Id }, messageToReturn));
            }

            throw new Exception("Creating the message failed on save");
        }
Esempio n. 7
0
        /// <summary>
        /// Executes the interactor
        /// </summary>
        public void Execute()
        {
            try
            {
                if (Booking == null)
                {
                    throw new ArgumentException("Booking cannot be null");
                }

                var results = validator.Validate(Booking);

                if (results.IsValid == false)
                {
                    throw new InvalidBookingException(results.Flatten());
                }

                if (bookingRepository.HasOverlapping(Booking))
                {
                    responseHandler.Fail("Another booking overlaps with this one.");
                }
                else
                {
                    bookingRepository.Add(Booking);
                    responseHandler.Success();
                }
            }
            catch (Exception e)
            {
                responseHandler.Error(e);
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> CreateNote([FromBody] NoteforListDto noteForUpdateDto)
        {
            if (noteForUpdateDto == null)
            {
                return(BadRequest());
            }
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var userFromRepo = await _hotelrepo.GetUser(currentUserId);

            noteForUpdateDto.CreatedOn = DateTime.Now;
            noteForUpdateDto.CreatedBy = userFromRepo.UserName;

            var noteEntity = _mapper.Map <Note>(noteForUpdateDto);

            _repo.Add(noteEntity);

            if (await _unitOfWork.CompleteAsync())
            {
                var noteToReturn = _mapper.Map <NoteforListDto>(noteEntity);
                return(CreatedAtRoute("GetNote", new { id = noteEntity.Id }, noteToReturn));
            }

            throw new Exception("Creating the note failed on save");
        }
        public async Task <ActionResult> Handle(CreateBookingCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            // gets the available car
            var availableCar = availableCarRepository.Get(request.AvailableCarId);

            if (availableCar == null)
            {
                var result = new ActionResult
                {
                    Status  = ActionResultCode.Failed,
                    Message = $"Cannot find an available car with the {request.AvailableCarId} id",
                    Errors  = new List <string> {
                        $"Cannot find an available car with the {request.AvailableCarId} id"
                    }
                };
                return(await Task.FromResult(result));
            }

            // gets the user
            var user = userRepository.GetUser(request.UserId);

            if (user == null)
            {
                var result = new ActionResult
                {
                    Status  = ActionResultCode.Failed,
                    Message = $"Cannot find an user with the {request.UserId} id",
                    Errors  = new List <string> {
                        $"Cannot find an user with the {request.UserId} id"
                    }
                };
                return(await Task.FromResult(result));
            }

            // creates the booking
            var booking = BookingFactory.CreateBooking(availableCar, user, request.From, request.To);

            // validates the booking
            var validationContext = new ValidationContext(booking);

            Validator.ValidateObject(booking, validationContext, validateAllProperties: true);

            bookingRepository.Add(booking);

            // saves changes
            await bookingRepository.UnitOfWork.SaveChangesAsync();

            var res = new ActionResult
            {
                Status = ActionResultCode.Success
            };

            return(await Task.FromResult(res));
        }
Esempio n. 10
0
 public IActionResult Create(Booking booking)
 {
     booking.CustomerId = userManager.GetUserId(HttpContext.User);
     booking.Hotel      = hotelRepository.Get(booking.Id);
     booking.Price      = booking.NumberOfDays * booking.NumberOfRooms * booking.Hotel.Price;
     bookingRepository.Add(booking);
     return(RedirectToAction("Index", "Hotel"));
 }
Esempio n. 11
0
        public Booking AddNewBooking(Booking booking)
        {
            if (!booking.IsValid())
            {
                return(booking);
            }

            return(_bookingRepository.Add(booking));
        }
Esempio n. 12
0
 public IActionResult Create([Bind("Id,OtelId,OtelAd,Fiyat,Description,ImageUrl")] Room room)
 {
     if (ModelState.IsValid)
     {
         repository.Add(room);
         return(RedirectToAction(nameof(Index)));
     }
     return(View(room));
 }
Esempio n. 13
0
 public IActionResult SaveBooking(IndexViewModel model)
 {
     if (ModelState.IsValid)
     {
         _bookingRepository.Add(model.Bookings.First());
         return(RedirectToAction("Index"));
     }
     return(View("Index"));
 }
        public async Task <IActionResult> CreateReservation(ReservationForCreateDto reservationForCreateDto)
        {
            if (reservationForCreateDto == null)
            {
                return(BadRequest());
            }

            // retrieve current user's detail
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
//            var userFromRepo = await _hotelrepo.GetUser(currentUserId);

            // booking details
            var bookingFromRepo = await _repo.GuestCurrentBooking(currentUserId);

            if (bookingFromRepo == null)
            {
                return(NotFound($"Could not find guest booking"));
            }

            var reservationEntity = _mapper.Map <Reservation>(reservationForCreateDto);

            reservationEntity.GuestName   = bookingFromRepo.GuestName;
            reservationEntity.Email       = bookingFromRepo.Email;
            reservationEntity.Phone       = bookingFromRepo.Phone;
            reservationEntity.RoomNumber  = bookingFromRepo.RoomNumber;
            reservationEntity.IsNew       = true;
            reservationEntity.IsDeleted   = false;
            reservationEntity.IsCompleted = false;
            reservationEntity.BookingId   = bookingFromRepo.Id;
            reservationEntity.HotelId     = bookingFromRepo.HotelId;
            _repo.Add(reservationEntity);

            /// signalR section to copy out
            var notificationFromRepo = await _hotelrepo.GetNotificationCounters(bookingFromRepo.HotelId);

            if (notificationFromRepo != null)
            {
                notificationFromRepo.ReservationCount += 1;

                var notificationToReturn = _mapper.Map <NotificationDto>(notificationFromRepo);

                var notificationMessage = NotificationMessage.CreateNotification(bookingFromRepo.HotelId, "Reservation",
                                                                                 reservationEntity.RoomNumber, notificationToReturn);

                await _notifyHub.Clients.All.SendAsync("NewRequest", notificationMessage);
            }

            if (await _unitOfWork.CompleteAsync())
            {
                var reservationToReturn = _mapper.Map <ReservationForDetailDto>(reservationEntity);

                return(CreatedAtRoute("GetReservation", new { id = reservationEntity.Id }, reservationToReturn));
            }

            throw new Exception("Creating the reservation failed on save");
        }
Esempio n. 15
0
        public long AddBooking(Booking booking)
        {
            if (booking == null)
            {
                return(0);
            }
            var idBooking = _bookingRepository.Add(booking);

            return(idBooking);
        }
 public ActionResult SaveBooking([Bind(Include = "Id,Date,Payment,Customer_Id")] Booking booking)
 {
     if (CheckDate(booking) == true)
     {
         db.Add(booking);
         return(RedirectToAction("AnimalsBooking", "Bookings", booking));
     }
     ViewBag.ErrorMessage = "Datum moet in de toekomst liggen.";
     return(View("Index"));
 }
        public ServiceCallResult CreateBooking(Booking booking)
        {
            //int roomId = FindAvailableRoom(booking.StartDate, booking.EndDate);

            //if (roomId >= 0)
            //{
            //    booking.RoomId = roomId;
            //    booking.IsActive = true;
            //    bookingRepository.Add(booking);
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}

            var callResult = new ServiceCallResult()
            {
                Success = false
            };

            if (booking.StartDate < DateTime.Today)
            {
                callResult.ErrorMessages.Add("Geçmiş tarihli rezervasyon yapılamaz!");
                return(callResult);
            }

            if (booking.StartDate > booking.EndDate)
            {
                callResult.ErrorMessages.Add("Hatalı Tarih Seçimi");
                return(callResult);
            }

            var activeBooking = bookingRepository.GetAll().Where(x => x.RoomId == booking.RoomId && (x.EndDate > booking.StartDate && x.StartDate < booking.EndDate));

            if (activeBooking.Count() > 0)
            {
                callResult.ErrorMessages.Add("Bu tarih aralığında odamız doludur!");
                return(callResult);
            }

            var fark      = booking.EndDate - booking.StartDate;
            var totalDays = fark.TotalDays;
            var room      = roomRepository.Get(booking.RoomId);

            booking.Fiyat = room.Fiyat * totalDays;

            callResult.Success = true;
            callResult.SuccessMessages.Add("Rezervasyonunuz oluşturuldu. 'Sepete Ekle' butonuna tıklayınız.");
            booking.IsActive = true;
            bookingRepository.Add(booking);
            return(callResult);
        }
Esempio n. 18
0
        public void BookingDelete()
        {
            Booking booking = new Booking();

            booking.Date = new DateTime(2020, 1, 31);
            BookingRepo.Add(booking);

            var result = bookingManageController.DeleteConfirmed(booking.Id) as RedirectToRouteResult;

            Assert.AreEqual("Index", result.RouteValues["Action"]);
            Assert.IsNotNull(result.ToString());
        }
Esempio n. 19
0
        public void InsertBooking(BookingDto b)
        {
            try
            {
                //check date
                if ((b.BookedFrom == b.BookedTo) || (b.BookedTo < b.BookedFrom))
                {
                    throw new Exception($"Impossibile inserire la prenotazione. Periodo di prenotazione non valido");
                }

                //check if the reservation already exists for the room
                var exist = _bookingRepository.GetAll()
                            .Any(
                    x =>
                    x.RoomId == b.RoomId &&
                    (
                        (x.BookedFrom >= b.BookedFrom && x.BookedFrom < b.BookedTo) ||
                        (x.BookedTo > b.BookedFrom && x.BookedTo <= b.BookedTo) ||
                        (x.BookedFrom <b.BookedFrom && x.BookedTo> b.BookedTo) ||
                        (x.BookedFrom == b.BookedFrom && x.BookedTo == b.BookedTo)
                    )
                    );

                //insert the reservation
                if (!exist)
                {
                    Booking newB = new Booking()
                    {
                        EmployeeId  = b.EmployeeId,
                        RoomId      = b.RoomId,
                        Description = b.Description,
                        BookedFrom  = b.BookedFrom,
                        BookedTo    = b.BookedTo,
                        CreatedOn   = DateTime.Now,
                        UpdatedOn   = DateTime.Now
                    };

                    _bookingRepository.Add(newB);

                    LogManager.Debug($"Inserita nuova prenotazione: (RoomId:{newB.RoomId}, Da:{newB.BookedFrom}, A:{newB.BookedTo})");
                }
                else
                {
                    throw new Exception($"Impossibile inserire la prenotazione. La sala '{b.RoomName}' è già prenotata nel periodo selezionato");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
                throw ex;
            }
        }
        public IActionResult Post([FromBody] Booking booking)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            _bookingRepo.Add(booking);
            if (_bookingRepo.SaveAll())
            {
                return(Created("", booking));
            }
            return(BadRequest($"failed to add new booking"));
        }
Esempio n. 21
0
        public async Task <Booking> BookCar(Guid carId, Guid userId, DateTime startDate, DateTime endDate, string bearer)
        {
            var car = await carRepository.GetAsync(carId);

            User user = await userOperationHandler.GetUser(userId);

            var claim = JWTTokenGenerator.GetClaim(bearer, emailClaim);

            var booking = Booking.Create(car, user, startDate, endDate);

            bookingRepository.Add(booking);
            await bookingRepository.SaveAsync();

            return(booking);
        }
        public void IsRepositoryAddsBooking()
        {
            var     count   = BookingRepo.GetBookings().Count() + 1;
            Booking booking = new Booking();

            {
                booking.Date = new DateTime(2020, 1, 31);
            }
            BookingRepo.Add(booking);

            var result          = BookingRepo.GetBookings();
            var numberOfRecords = result.ToList().Count;

            Assert.AreEqual(count, numberOfRecords);

            BookingRepo.Remove(booking.Id);
        }
Esempio n. 23
0
        public long AddBooking(Booking booking)
        {
            var booklingList = _bookingRepository.ListBookingByDate(booking.ArrivalTime);

            if (booklingList.Where(x => x.ArrivalTime == booking.ArrivalTime).Count() > 0)
            {
                var bookingInTime = booklingList.Where(x => x.ArrivalTime == booking.ArrivalTime).ToList();
                foreach (var book in bookingInTime)
                {
                    if (booking.IdBed == book.IdBed)
                    {
                        return(0);
                    }
                }
            }
            return(_bookingRepository.Add(booking));
        }
        public async Task <IActionResult> Checkout([FromBody] BookingCheckout bookingCheckout)
        {
            var userId = _identityService.GetUserIdentity();

            //to do: check unique request id

            var booking = new Booking(bookingCheckout.ProductId, bookingCheckout.ProductName, bookingCheckout.UnitPrice, bookingCheckout.Quantity, userId);

            _bookingRepository.Add(booking);

            await _bookingRepository.SaveChangesAsync();

            var eventMessage = new BookingStartedIntegrationEvent(userId, booking.Id, bookingCheckout.ProductId, bookingCheckout.Quantity);
            await _endpoint.Publish(eventMessage);

            return(Accepted());
        }
        public ClientMessage <BookingModel> SaveBookingDetails(BookingModel model)
        {
            model.BookingNumber = base.GenerateTicketNumber();
            Console.WriteLine(model.BookingNumber);
            model.CreatedDate = DateTime.Now;
            model.ID          = Guid.NewGuid();
            //model.BusID=Guid.NewGuid();
            var data           = _bookingRepo.Add(model);
            var _clientMessage = new ClientMessage <BookingModel>();

            _clientMessage.ClientData = model;
            if (data.IsCompletedSuccessfully)
            {
                _clientMessage.HasError = true;
            }

            return(_clientMessage);
        }
Esempio n. 26
0
        public async Task <Booking> BookCar(Guid carId, Guid userId, DateTime startDate, DateTime endDate, string bearer)
        {
            var car = await carRepository.GetAsync(carId);

            var user = await userRepository.GetAsync(userId);

            var claim = JWTTokenGenerator.GetClaim(bearer, emailClaim);

            if (user.Email != claim)
            {
                throw new InvalidCredentialException("Not authorized!");
            }

            var booking = Booking.Create(car, user, startDate, endDate);

            bookingRepository.Add(booking);
            await bookingRepository.SaveAsync();

            return(booking);
        }
Esempio n. 27
0
        public async Task<IActionResult> CreateOrder(OrderForCreationDto orderForCreationDto)
        {
            var order = _mapper.Map<Order>(orderForCreationDto);
            var createdOrder = await _repo.CreateOrder(order);

            var cartItems = orderForCreationDto.CartItems;
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetails();
                orderDetail.BookId = item.Id;
                orderDetail.OrderId = createdOrder.Id;
                orderDetail.TotalPrice = item.TotalPrice;
                orderDetail.TotalQuantity = item.TotalQuantity;
                _repo.Add(orderDetail);
                
            }
            await _repo.SaveAll();
            return Ok(createdOrder);

        }
        public async Task <IActionResult> CreateBooking(BookingForCreationDto bookingForCreationDto)
        {
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var bookingToCreate = _mapper.Map <Booking>(bookingForCreationDto);

            _repo.Add(bookingToCreate);

            if (await _repo.SaveAll())
            {
                var bookingToReturn = _mapper.Map <BookingToReturnDto>(bookingToCreate);
                return(CreatedAtRoute("GetBooking", new { id = bookingToCreate.Id }, bookingToReturn));
            }
            throw new Exception("Creating the booking failed on save");
        }
Esempio n. 29
0
        public Task <int> Handle(RequestBooking request, CancellationToken cancellationToken)
        {
            var booking = new Booking(
                request.PatientRequest.DateFrom,
                request.PatientRequest.DateTo);

            booking.AssignPatient(request.PatientRequest.PatientId);

            request.SurgeonRequests.ForEach(sr =>
            {
                var surgeon = booking.AssignSurgeon(sr.SurgeonId);
                sr.AssistantIds?.ForEach(a => booking.AssignSurgeonAssistant(surgeon, a));
                sr.ProcedureIds.ForEach(p => booking.AssignSurgeonProcedure(surgeon, p));
            });

            booking.Request();

            _bookingRepository.Add(booking);

            _bookingRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return(Task.FromResult(0));
        }
Esempio n. 30
0
        public HttpResponseMessage Post(List <BookingDetails> bookings)
        {
            int bookingId = db.BookingDetails.Count() + 1;

            foreach (var book in bookings)
            {
                BookingDetails bookingDetails = new BookingDetails
                {
                    FlightId     = book.FlightId,
                    FlightName   = book.FlightName,
                    BookingRefNo = "AC0" + bookingId,
                    BookingDate  = Convert.ToDateTime(book.BookingDate),
                    FirstName    = book.FirstName,
                    LastName     = book.LastName,
                    Email        = book.Email
                };
                _repository.Add(bookingDetails);
            }

            HttpResponseMessage response = Request.CreateResponse <List <BookingDetails> >(HttpStatusCode.Created, bookings, this.Configuration);

            return(response);
        }