public bool SaveBookings(BookingDto booking) { using (SqlConnection conn = new SqlConnection(connString)) { booking.Date = DateTime.Now; conn.Open(); var query = "insert into pc_bookings(driverid,customerid,date,fromd,tod,distance,totalfare,vehicletype) values(@driverid,@customerid,@date,@fromd,@tod,@distance,@totalfare,@vehicletype)"; //var query = "insert into pc_bookings(driverid,customerid,date,fromd,tod,distance,totalfare,vehicletype) values(@driverid,@customerid,@date,@from,@to,@distance,@totalfare,@vehicletype)"; //SqlCommand comm = new SqlCommand(query, conn); //comm.Parameters.AddWithValue("@driverid", booking.Driverid); //comm.Parameters.AddWithValue("@customerid", booking.CustomerId); //comm.Parameters.AddWithValue("@date", booking.Date); //comm.Parameters.AddWithValue("@from", booking.FromD); //comm.Parameters.AddWithValue("@to", booking.ToD); //comm.Parameters.AddWithValue("@distance", booking.Distance); //comm.Parameters.AddWithValue("@totalfare", booking.Totalfare); //comm.Parameters.AddWithValue("@vehicletype", booking.Vehicletype); var result = conn.Query<BookingDto>(query,booking); if (result != null) { return true; } else { return false; } } }
/// <summary> /// From Contract to model /// </summary> /// <param name="contract"></param> /// <param name="slotId"></param> /// <param name="clientId"></param> /// <param name="price"></param> /// <returns></returns> public static Booking BookingMapFromContractToModel(BookingDto contract, int slotId, int clientId, decimal price) { return(new Booking() { ServiceId = contract.ServiceId, SlotId = slotId, ClientId = clientId, ResultPrice = price }); }
public void BookingValidator_ShouldFailIfEndDateTimeIsGreaterThenStartDateTime() { var bookingVal = new BookingValidator(); var booking = new BookingDto { StartDateTime = new DateTime(2018, 08, 22, 12, 00, 00), EndDateTime = new DateTime(2018, 08, 22, 11, 00, 00) }; bookingVal.ShouldHaveValidationErrorFor(e => e.EndDateTime, booking); }
public async Task Book(int meetupId, BookingDto booking) { await _unitOfWork.BookingRepository.CreateAsync(new Booking { MeetupId = meetupId, RoomId = booking.RoomId, DateFrom = booking.DateFrom, DateTo = booking.DateTo }); await _unitOfWork.SaveAsync(); }
public async Task <ActionResult> BookTennisCourt(int tennisClubId, BookingDto booking) { Booking newBooking; /* if (await _bookingService.CheckAvailability(booking, tennisClubId)) * { */ var user = await _userRepository.GetUserByUsernameAsync(booking.UserName); if (user != null) { newBooking = new Booking { UserId = user.Id, DateStart = booking.DateStart, DateEnd = booking.DateEnd, TennisCourtId = booking.TennisCourtId, FirstName = booking.FirstName, LastName = booking.LastName, Email = booking.Email, PhoneNumber = booking.PhoneNumber }; } else { newBooking = new Booking { DateStart = booking.DateStart, DateEnd = booking.DateEnd, TennisCourtId = booking.TennisCourtId, FirstName = booking.FirstName, LastName = booking.LastName, Email = booking.Email, PhoneNumber = booking.PhoneNumber }; } _bookingService.Book(newBooking); if (await _bookingService.SaveAllAsync()) { var lastBooking = await _bookingService.GetLastBooking(); return(CreatedAtRoute("GetBooking", new { tennisClubId = tennisClubId, bookingId = newBooking.Id }, lastBooking)); } /* } * * * return BadRequest("Unavailable on that time");*/ return(BadRequest("Unavailable on that time")); }
public void EditBooking(int id, BookingDto bookingDto) { var updatedBooking = _context.Bookings.FirstOrDefault(s => s.Id == id); updatedBooking = Mapper.Map(bookingDto, updatedBooking); var spot = _context.Spots.FirstOrDefault(s => s.Id == updatedBooking.SpotId); var previousBooking = spot.SpotBookings.FirstOrDefault(b => b.SpotId == bookingDto.SpotId); spot.SpotBookings.Remove(previousBooking); spot.SpotBookings.Add(updatedBooking); _context.Bookings.Update(updatedBooking); }
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; } }
private bool CheckEligibility(BookingDto dto) { TimeSpan interval = dto.To - dto.From; if (interval.TotalMinutes > 120 || interval.TotalMinutes < 30 || interval.TotalMinutes % 30 != 0) { return(false); } var eligiblity = db.Bookings.Where(b => b.TableId == dto.TableId).All(b => b.From >= dto.To.AddMinutes(30) || b.To.AddMinutes(30) <= dto.From); return(eligiblity); }
public BookingDto GetBooking(int id) { VehicleBooking vehicle = _repositoryFactory.VehicleBookingRepository.GetVehicleBooking(id); vehicle.account.DecryptModel(); BookingDto dto = new BookingDto() { vehicleBooking = _mapper.Map <VehicleBookingDto>(vehicle), equipmentBookings = _mapper.Map <List <EquipmentBookingDto> >(_repositoryFactory.EquipmentBookingRepository.GetEquipmentBookingsFromBooking(id)) }; return(dto); }
public async Task <IActionResult> CreateBookings([FromBody] BookingDto booking) { _logger.LogInformation("Call CreateBookings method with params - " + JsonConvert.SerializeObject(booking)); if (!ModelState.IsValid || booking == null || booking.From > booking.To) { _logger.LogError("return Bad request"); return(BadRequest("Please, specify a valid fields")); } var message = await _service.CreateBookings(booking); _logger.LogInformation("return OK"); return(Ok(message)); }
public async Task <IActionResult> GetBookingById(int id) { try { BookingDto booking = await Task.FromResult(_bookingService.GetBooking(id)); return(Ok(booking)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public bool AddBooking(BookingDto dataDto) { if (dataDto != null) { using (EcommerceDB context = new EcommerceDB()) { if (dataDto.Id <= 0) { Booking AddData = new Booking(); AddData.Date = dataDto.Date; AddData.Name = dataDto.Name; AddData.MobileNo = dataDto.MobileNo; AddData.EmailId = dataDto.EmailId; AddData.Address = dataDto.Address; AddData.Remarks = dataDto.Remarks; AddData.ItemId = dataDto.ItemId; AddData.IsActive = true; context.Bookings.Add(AddData); context.SaveChanges(); return(true); } else { var olddata = context.Bookings.FirstOrDefault(x => x.Id == dataDto.Id); if (olddata != null) { olddata.Date = dataDto.Date; olddata.Name = dataDto.Name; olddata.MobileNo = dataDto.MobileNo; olddata.EmailId = dataDto.EmailId; olddata.Address = dataDto.Address; olddata.Remarks = dataDto.Remarks; olddata.ItemId = dataDto.ItemId; olddata.IsActive = true; context.Entry(olddata).Property(x => x.Date).IsModified = true; context.Entry(olddata).Property(x => x.Name).IsModified = true; context.Entry(olddata).Property(x => x.MobileNo).IsModified = true; context.Entry(olddata).Property(x => x.EmailId).IsModified = true; context.Entry(olddata).Property(x => x.Address).IsModified = true; context.Entry(olddata).Property(x => x.Remarks).IsModified = true; context.Entry(olddata).Property(x => x.ItemId).IsModified = true; context.Entry(olddata).Property(x => x.IsActive).IsModified = true; olddata.IsActive = true; context.SaveChanges(); return(true); } } } } return(false); }
public void RegisterBooking(BookingDto NewBookingDto) { //Console.ForegroundColor = ConsoleColor.DarkYellow; //Console.WriteLine("LibraryService - Reservando libro para su préstamo \n"); //Console.ForegroundColor = ConsoleColor.White; BookingEntity bookingEntity = new BookingEntity(); bookingEntity.BookId = NewBookingDto.BookId; bookingEntity.EndBookingDate = NewBookingDto.EndBookingDate; bookingEntity.LibraryAppUsername = NewBookingDto.LibraryAppUsername; bookingEntity.StartBookingDate = NewBookingDto.StartBookingDate; _dblibrary.RegisterBooking(bookingEntity); }
private Booking MapFrom(BookingDto b) { return(new Booking() { Id = b.Id, EmployeeId = b.EmployeeId, RoomId = b.RoomId, Description = b.Description, BookedFrom = b.BookedFrom, BookedTo = b.BookedTo, CreatedOn = b.CreatedOn, UpdatedOn = b.UpdatedOn }); }
public async Task <BaseResponse> Create(BookingDto booking) { var response = new BaseResponse(); User currentUser = await _requestDataService.GetCurrentUser(); var dbCategory = await _categoryRepository.GetById(booking.BookingCategoryId); if (dbCategory is null) { response.Infos.Errors.Add($"No category found with id {booking.BookingCategoryId}"); response.StatusCode = HttpStatusCode.NotFound; return(response); } if (dbCategory.CategoryOwner.UserId != currentUser.UserId) { response.Infos.Errors.Add($"You can only create bookings for categories that belong to you"); response.StatusCode = HttpStatusCode.UnprocessableEntity; return(response); } BookingDtoValidator validator = new BookingDtoValidator(); var result = await validator.ValidateAsync(booking); if (!result.IsValid) { response.Infos.Errors.AddRange(result.Errors.ToList().Select(error => error.ErrorMessage)); response.StatusCode = HttpStatusCode.UnprocessableEntity; return(response); } Booking newBooking = new Booking { BookingAmount = booking.BookingAmount, BookingCategory = dbCategory, BookingDate = DateTime.Now, BookingUser = currentUser, BookingDescription = booking.BookingDescription, BookingType = booking.BookingType }; var responseBooking = await _bookingRepository.Insert(newBooking); responseBooking.BookingUser.Password = null; response.Data.Add("booking", responseBooking); return(response); }
public async Task AddBooking_UnsuitableTime() { Setup(); var services = new List <Service>() { new(){ Id = 1, Name = "FirstService", Description = "Description", Price = 5555 }, new(){ Id = 2, Name = "SecondService", Description = "Description ", Price = 6666 }, new(){ Id = 3, Name = "ThirdService", Description = "Description", Price = 7777 } }; var slots = new List <Slot>() { new() { Id = 1, CoachId = 3, Date = new DateTime(2021, 6, 16), StartTime = new TimeSpan(23, 0, 0) }, new() { Id = 2, CoachId = 2, Date = new DateTime(2021, 4, 20), StartTime = new TimeSpan(18, 0, 0) } }; var bookings = new List <Booking>() { new() { Id = 1, SlotId = 2, ServiceId = 3 }, new() { Id = 2, SlotId = 5, ServiceId = 2 } }; _applicationContextMock.Setup(x => x.Services).ReturnsDbSet(services); _applicationContextMock.Setup(x => x.Slots).ReturnsDbSet(slots); _applicationContextMock.Setup(x => x.Bookings).ReturnsDbSet(bookings); _testedService = new BookingService(Logger, _applicationContextMock.Object); var dto = new BookingDto() { Date = "06.16.2021", Time = "23:59", CoachId = 3, ServiceId = 3 }; var result = await _testedService.AddBooking(dto, 1, CancellationToken.None); Assert.False(result); }
public ActionResult Book(FormCollection frm) { BookingDto booking = new BookingDto(); booking.ToD = frm["to"]; booking.FromD = frm["from"]; booking.Distance = 553; booking.Totalfare = booking.Distance * 5; booking.Driverid = Convert.ToInt16(frm["driverId"]); booking.CustomerId = Convert.ToInt16(frm["customerId"]); booking.Vehicletype = frm["vehicleType"]; booking.Date = DateTime.Now; var result = new BookingServices().SaveBookings(booking); ViewBag.Message = "booking successful"; return View("Index"); }
public ActionResult <BookingDto> BookApartment([FromBody] BookingDto booking) { if (!ModelState.IsValid) { return(BadRequest("Invalid booking information")); } var reservation = _repository.NuomosLaikotarpis.CreateReservation(booking); if (reservation == null) { return(Conflict("Those days are already rented")); } return(Ok(reservation)); }
public IHttpActionResult CreateBooking(BookingDto bookingDto) { if (!ModelState.IsValid) { return(BadRequest()); } var booking = Mapper.Map <BookingDto, Booking>(bookingDto); _db.Bookings.Add(booking); _db.SaveChanges(); bookingDto.Id = booking.Id; return(Created(new Uri(Request.RequestUri + "/" + booking.Id), bookingDto)); }
public ActionResult <BookingReplyDto> Post([FromBody] BookingDto bookingDto) { var booking = new Booking().CopyPropertiesFrom(bookingDto); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var bookingReply = bookingService.PostBooking(booking); if (!bookingReply.Success) { return(BadRequest(bookingReply.Error)); } return(Ok(new BookingReplyDto().CopyPropertiesFrom(bookingReply.Booking))); }
public void CreateBookings_BookingIsValid_ExpectedResult_WithoutCallSaveToDb_NullResult() { BookingDto bookingDto = new BookingDto { From = DateTime.Today, To = DateTime.Today.AddDays(1), HotelId = 1 }; Hotel hotel = new Hotel(); RepoMock.Setup(m => m.GetHotelById(It.IsAny <int>())).Returns(Task.FromResult(hotel)) .Verifiable(); var response = sut.CreateBookings(bookingDto).GetAwaiter().GetResult(); RepoMock.Verify(x => x.GetHotelById(It.IsAny <int>()), Times.Once); Assert.IsNotNull(response); Assert.IsInstanceOfType(response, typeof(string)); }
public decimal GetBookingTotalAmount(BookingDto booking) { var bookingTotalAmount = 0.00M; try { //ToDo } catch (Exception ex) { var errorMessage = $"Error in: {GetType().FullName}, method: GetBookingTotalAmount, exception: BookingCalculatorException, message: {ex.Message}."; Trace.TraceError(errorMessage, ex); } return(bookingTotalAmount); }
public void UpdateCustomer(int id, BookingDto bookingDto) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var bookingInDb = _db.Bookings.SingleOrDefault(b => b.Id == id); if (bookingInDb == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } Mapper.Map <BookingDto, Booking>(bookingDto, bookingInDb); _db.SaveChanges(); }
public BookingDto GetBooking(string Username, string bookTitle) { //Console.ForegroundColor = ConsoleColor.DarkYellow; //Console.WriteLine("LibraryService - Obteniendo reserva del usuario {0} del libro {1}... \n", Username, bookTitle); //Console.ForegroundColor = ConsoleColor.White; BookingEntity bookingEntity = _dblibrary.GetBooking(Username, bookTitle); BookingDto bookingDto = new BookingDto(); bookingDto.Id = bookingEntity.Id; bookingDto.BookId = bookingEntity.BookId; bookingDto.EndBookingDate = bookingEntity.EndBookingDate; bookingDto.StartBookingDate = bookingEntity.StartBookingDate; bookingDto.LibraryAppUsername = bookingEntity.LibraryAppUsername; bookingDto.UserReturnDate = bookingEntity.UserReturnDate; return(bookingDto); }
public OkObjectResult RequestBooking([FromBody] BookingDto dto) { var userId = GetUserId(); var validMod = _context.EventModerators .Any(em => em.EventId == dto.EventId && em.UserIdRecipient == userId && em.Status == RequestStatus.Accepted); if (!validMod) { return(new OkObjectResult(new { success = false, error = "Not a valid event mod" })); } var ensembleMod = _context.EnsembleModerators .FirstOrDefault(em => em.EnsembleId == dto.EnsembleId && em.Status == RequestStatus.Accepted); if (ensembleMod == null) { return(new OkObjectResult(new { success = false, error = "No group mod" })); } // if user is default ensemble mod, immediate accept var userIsEnsMod = ensembleMod.UserIdRecipient == userId; var status = userIsEnsMod ? RequestStatus.Accepted : RequestStatus.Pending; var user = _context.Users.Find(userId); var ensemble = _context.Ensembles.Find(dto.EnsembleId); var ev = _context.Events.Find(dto.EventId); _context.Bookings.Add(new Booking { EnsembleId = dto.EnsembleId, EventId = dto.EventId, UserIdRecipient = ensembleMod.UserIdRecipient, UserIdRequester = userId, Status = status, ConfirmedAt = userIsEnsMod ? DateTime.Now : (DateTime?)null, Text = $"{user.FullName} would like your ensemble {ensemble.Name} to perform at the event {ev.Name}" }); _context.SaveChanges(); return(new OkObjectResult(new { success = true })); }
public IActionResult BookingDetails(int id) { if (id <= 0) { return(BadRequest()); } var booking = _bookingRepository.GetBooking(id); if (booking == null) { return(NotFound()); } BookingDto results = new BookingDto { Amount = booking.Amount, DateToPresent = Convert.ToString(booking.DateToPresent), MovieId = booking.MovieId, SeatNo = booking.SeatNo, UserId = booking.SeatNo }; return(Ok(results)); }
public bool CreateBooking(BookingDto dto) { if (CheckEligibility(dto)) { Booking booking = new Booking { TableId = dto.TableId, From = dto.From, To = dto.To, ContactPhone = dto.ContactPhone }; db.Bookings.Add(booking); db.SaveChanges(); return(true); } return(false); }
private IEnumerable <PaymentDto> UpdateValidPaymentCollectedAmount(IEnumerable <PaymentDto> validPaymentsWithOriginalCollectedAmount, BookingDto booking) { var result = new List <PaymentDto>(); foreach (var validPayment in validPaymentsWithOriginalCollectedAmount) { validPayment.CollectedAmount = validPayment.CollectedAmount + booking.Payments .Where(p => p.ParentPaymentId.Equals(validPayment.PaymentId)) .Sum(p => p.CollectedAmount); if (validPayment.CollectedAmount > 0) { result.Add(validPayment); } } return(result); }
public void Mapping_Should_Return_Proper_Booking() { var seanceId = Guid.NewGuid(); var bookingDto = new BookingDto() { Id = Guid.NewGuid(), Bought = true, BookedPlaces = new List <int> { 1, 2, 3 }, SeanceId = seanceId }; var booking = this.mapper.Map <Booking>(bookingDto); Assert.Equal(booking.Id, bookingDto.Id); Assert.Equal(booking.Seance.Id, bookingDto.SeanceId); Assert.Equal(booking.Places, ConversionHelper.ParseIntsToDelimitedString(':', bookingDto.BookedPlaces)); Assert.Equal(booking.Bought, bookingDto.Bought); }
public IHttpActionResult InsertNewBooking(BookingDto booking) { try { if (booking != null && ModelState.IsValid) { _bookingManager.InsertBooking(booking); return(Ok()); } else { return(BadRequest("I valori indicati per la nuova prenotazione non sono validi")); } } catch (Exception ex) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message))); } }
public IActionResult Post([FromBody] BookingDto dto) { if (ModelState.IsValid) { try { if (bookingRepository.CreateBooking(dto)) { return(Ok(dto)); } ; return(BadRequest("The table that you selected is not available anymore. Please try another one.")); } catch (Exception) { return(StatusCode(503)); } } return(BadRequest("Your selection is invalid.")); #region MyRegion //if (ModelState.IsValid) //{ // if (CheckEligibility(dto)) // { // Booking booking = new Booking // { // TableId = dto.TableId, // From = dto.From, // To = dto.To, // ContactPhone = dto.ContactPhone // }; // db.Bookings.Add(booking); // db.SaveChanges(); // return Ok(dto); // } // return BadRequest("Table is already booked by someone else."); //} //return BadRequest("Your selection is invalid."); #endregion }
public async Task <string> CreateBookings(BookingDto booking) { if (booking == null) { _logger.LogError("Booking model are null"); throw new ArgumentNullException("Booking model are null"); } var bookingDbo = _mapper.Map <Booking>(booking); var hotel = await _repository.GetHotelById(booking.HotelId); if (hotel != null) { bookingDbo.Hotel = hotel; await _repository.AddBooking(bookingDbo); return("Booking successfully added"); } return("There is no such hotel"); }
/// <summary> /// Converts Booking object to Booking DTO /// </summary> /// <param name="booking">Booking to convert</param> /// <returns>Converted Booking DTO</returns> public static Booking ConvertBookingDtoToBooking(BookingDto booking) { return new Booking { Id = booking.Id, BusinessId = booking.BusinessId, BookingReferenceNumber = booking.BookingReferenceNumber, StartDateUTC = booking.StartDateUTC, EndDateUTC = booking.EndDateUTC, NumberOfAdults = booking.NumberOfAdults, NumberOfChildren = booking.NumberOfChildren, Cost = booking.Cost, IsBookingConfirmed = booking.IsBookingConfirmed, IsOffline = booking.IsOffline, RoomTypeId = booking.RoomTypeId, RoomId = booking.RoomId, RatePlanId = booking.RatePlanId, IsCheckedIn = booking.IsCheckedIn, IsCheckedOut = booking.IsCheckedOut, CheckInDateLT = booking.CheckInDateLT, CheckOutDateLT = booking.CheckOutDateLT, EstimatedTimeOfArrivalLT = booking.EstimatedTimeOfArrivalLT, IsProvisional = booking.IsProvisional, BookingScenario = (BookingScenarioType)booking.BookingScenarioType, Notes = booking.Notes, Customer = ConvertCustomerDtoToCustomer(booking.Customer), BookingStatus = GetBookingStatusFromBookingDto(booking), CreatedByUserId = booking.CreatedByUserId, CreatedDateTimeUTC = booking.CreatedDateTimeUTC }; }
public void CreateProvisionalBookingInvalidBusinessThrowsValidationException() { // Arrange // businessId we know will never exist in the cache const long BUSINESS_ID = -100; var bookingDto = new BookingDto { BusinessId = 1, Customer = new CustomerDto { Id = 1, BusinessId = BUSINESS_ID, Surname = "Test Customer", Email = "*****@*****.**" }, StartDateUTC = new DateTime(2012, 2, 1, 0, 0, 0, DateTimeKind.Utc), EndDateUTC = new DateTime(2012, 2, 2, 0, 0, 0, DateTimeKind.Utc), NumberOfAdults = 2, NumberOfChildren = 1, Cost = new decimal(120.5), IsBookingConfirmed = true, IsOffline = true, RoomTypeId = 1, RoomId = 1, RatePlanId = 1, IsCheckedIn = false, IsProvisional = false, Notes = "Testing note", BookingScenarioType = BookingScenarioTypeDto.OnAccountBooking }; try { // Act limitedMobileService.CreateProvisionalBooking(BUSINESS_ID, bookingDto); // Assert Assert.Fail("An exception SRVEX30001 of type ValidationException should have been thrown"); } catch (ValidationException ex) { // Assert Assert.AreEqual("SRVEX30001", ex.Code, "The Validation exception is not returning the right error code"); } }
public void CreateBookingInvalidBusinessIdThrowsValidationException() { // Arrange // businessId that we know will never exist const long BUSINESS_ID = -100011110010000; var bookingDto = new BookingDto { BusinessId = BUSINESS_ID, Customer = new CustomerDto { Id = 1, BusinessId = BUSINESS_ID, Surname = "Test Customer", Email = "*****@*****.**" }, StartDateUTC = DateTime.Now, EndDateUTC = DateTime.Now.AddDays(1), NumberOfAdults = 2, IsBookingConfirmed = false, IsOffline = true, RoomTypeId = 1, RoomId = 1, RatePlanId = 1, IsProvisional = true, BookingScenarioType = BookingScenarioTypeDto.OnAccountBooking }; try { // Act limitedMobileService.CreateBooking(BUSINESS_ID, bookingDto); // Assert Assert.Fail("An exception SRVEX30001 of type ValidationException should have been thrown"); } catch (ValidationException ex) { // Assert Assert.AreEqual("SRVEX30001", ex.Code, "The Validation exception is not returning the right error code"); } }
/// <summary> /// To do non-mocking tests of check availability in a bit more easily done manner /// </summary> /// <param name="includeRoomType">If room type should be in search criteria</param> /// <param name="expectedRoomTypeIds">A list of the expected room type ids</param> /// <param name="includeRatePlan">If rate plan should be in search criteria</param> /// <param name="expectedRatePlanIdsForRoomType">A list of the expected rate plan ids for each room type</param> /// <param name="includeRoomId">If Room Id should be in search criteria</param> /// <param name="expectedRoomIdsForRoomType">A list of the expected room ids for each room type</param> /// <param name="numberOfAdults">Set a number of adults in the search criteria</param> /// <param name="numberOfChildren">Set a number of children in the search criteria</param> /// <remarks>Room type is only one verified to work correctly. Check asserts if using the rate plan or room id flags</remarks> private void CheckAvailabilityWithoutMockingForBookingModifyTests(bool includeRoomType = false, List<int> expectedRoomTypeIds = null, bool includeRatePlan = false, Dictionary<int, List<int>> expectedRatePlanIdsForRoomType = null, bool includeRoomId = false, Dictionary<int, List<int>> expectedRoomIdsForRoomType = null, int? numberOfAdults = null, int? numberOfChildren = null) { using (new TestDataHelper(TestDataQueriesLimited.PopulateCheckRatePlanAvailabilityTestData, TestDataQueriesLimited.CleanupTestData)) { // Arrange var serviceWithoutMock = new LimitedMobileService { DisableAccessRightsCheck = true, FakeAuthenticationForDebugging = true, AvailabilityManager = new AvailabilityManager { RoomAvailabilityDao = new RoomsAvailabilityDao() }, BookingManager = new BookingManager { BookingDao = new BookingDao() }, BusinessManager = new BusinessManager { BusinessDao = new BusinessDao() } }; const long BUSINESS_ID = 1; // Create booking var booking = new BookingDto { BusinessId = BUSINESS_ID, Customer = new CustomerDto { BusinessId = BUSINESS_ID, Surname = "Test Customer", Email = "*****@*****.**" }, StartDateUTC = DateTime.Now, EndDateUTC = DateTime.Now.AddDays(1), NumberOfAdults = 2, IsBookingConfirmed = true, IsOffline = true, RoomTypeId = 1, RoomId = 1, RatePlanId = 1, IsProvisional = false, Cost = new decimal(50), BookingScenarioType = BookingScenarioTypeDto.OnAccountBooking }; booking = serviceWithoutMock.CreateBooking(BUSINESS_ID, booking); Assert.IsNotNull(booking.Id, "Booking Id is not attributed upon creation."); // Build availability Search criteria var searchCriteria = new AvailabilitySearchCriteriaDto { BusinessId = booking.BusinessId, StartDate = new CalendarDateDto { Day = booking.StartDateUTC.Day, Month = booking.StartDateUTC.Month, Year = booking.StartDateUTC.Year }, EndDate = new CalendarDateDto { Day = booking.EndDateUTC.Day, Month = booking.EndDateUTC.Month, Year = booking.EndDateUTC.Year }, NumberOfAdults = numberOfAdults ?? booking.NumberOfAdults, NumberOfChildren = numberOfChildren ?? booking.NumberOfChildren, RoomTypeId = includeRoomType ? (int?)booking.RoomTypeId : null, RatePlanId = includeRatePlan ? booking.RatePlanId : null, RoomId = includeRoomId ? (int?)booking.RoomId : null, ModifyBookingId = booking.Id }; // Act AvailabilitySearchResultDto searchResult = serviceWithoutMock.CheckAvailability(booking.BusinessId, searchCriteria); // Assert Assert.IsNotNull(searchResult, "AvailabilitySearchResult is null"); Assert.AreEqual(1, searchResult.BusinessCandidates.Count, "Total number of business candidates returned is incorrect."); Assert.IsTrue(searchResult.BusinessCandidates[0].BusinessId == booking.BusinessId, "BusinessId returned on search results is incorrect."); AvailabilityResultBusinessDto businessCandidate = searchResult.BusinessCandidates[0]; if (expectedRoomTypeIds == null && includeRoomType) { // Default to booking room type id if it is to be included expectedRoomTypeIds = new List<int> { booking.RoomTypeId }; } if (expectedRoomTypeIds != null) { // Validate room types Assert.AreEqual(expectedRoomTypeIds.Count, businessCandidate.RoomTypes.Count, "Number of roomTypes returned is incorrect."); foreach (var expectedRoomTypeId in expectedRoomTypeIds) { var roomType = businessCandidate.RoomTypes.Find(x => x.RoomTypeId == expectedRoomTypeId); Assert.IsNotNull(roomType, "An expected room type was not returned"); // Validate rooms if (expectedRoomIdsForRoomType == null && includeRoomId) { // Default to booking room id if it is to be included expectedRoomIdsForRoomType = new Dictionary<int, List<int>> { { booking.RoomTypeId, new List<int> { booking.RoomId } } }; } if (expectedRoomIdsForRoomType != null) { List<int> roomIds; expectedRoomIdsForRoomType.TryGetValue(expectedRoomTypeId, out roomIds); if (roomIds != null) { Assert.IsNotNull(roomType.RoomIds, "Room ids are not retrieved for roomType."); Assert.AreEqual(roomIds.Count, roomType.RoomIds.Count, "Number of rooms returned is incorrect."); } } // Validate rate plans if (expectedRatePlanIdsForRoomType == null && includeRatePlan) { // Default to booking room id if it is to be included expectedRatePlanIdsForRoomType = new Dictionary<int, List<int>> { { booking.RoomTypeId, new List<int> { booking.RatePlanId.Value } } }; } if (expectedRatePlanIdsForRoomType != null) { List<int> ratePlanIds; expectedRatePlanIdsForRoomType.TryGetValue(expectedRoomTypeId, out ratePlanIds); if (ratePlanIds != null && ratePlanIds.Count > 0) { Assert.IsNotNull(roomType.RatePlans, "RatePlans are not retrieved for roomType."); Assert.AreEqual(ratePlanIds.Count, roomType.RatePlans.Count, "Number of rate plans returned is incorrect."); foreach (var ratePlanId in ratePlanIds) { Assert.IsTrue(roomType.RatePlans.Any(x => x.RatePlanId == ratePlanId), "The rate plan returned is incorrect."); } } else { Assert.IsNull(roomType.RatePlans, "RatePlan should not exist for room type."); } } } } // NoRateDefined or NoAvailability reason code should be returned at RoomType level if there is no priced defined or weekly availability criteria is not met Assert.IsTrue(businessCandidate.RoomTypes[0].UnAvailabilityReasonCode == UnavailabilityReasonCodeDto.NoRateDefined || businessCandidate.RoomTypes[0].UnAvailabilityReasonCode == UnavailabilityReasonCodeDto.NoAvailability, "UnAvailabilityReasonCode at RoomType level is incorrect."); } }
public void CreateProvisionalBookingCreatesBookingAndModifiesCustomer() { // Arrange const long BUSINESS_ID = 1; // Stub the BusinessCache to be used by our service method CacheHelper.StubBusinessCacheSingleBusiness(BUSINESS_ID); // invalidate the cache so we make sure our business is loaded into the cache Cache.Business.Invalidate(); var bookingDto = new BookingDto { BusinessId = BUSINESS_ID, Customer = new CustomerDto { Id = 1, BusinessId = BUSINESS_ID, Surname = "Test Customer", Email = "*****@*****.**" }, StartDateUTC = DateTime.Now, EndDateUTC = DateTime.Now.AddDays(1), NumberOfAdults = 2, IsBookingConfirmed = false, IsOffline = true, RoomTypeId = 1, RoomId = 1, RatePlanId = 1, IsProvisional = true, BookingScenarioType = BookingScenarioTypeDto.OnAccountBooking }; var bookingManager = MockRepository.GenerateMock<IBookingManager>(); var customerManager = MockRepository.GenerateMock<ICustomerManager>(); customerManager.Expect(cm => cm.ModifyLimited(Arg<Customer>.Is.Anything)); bookingManager.Expect(x => x.CreateProvisionalBooking(Arg<Booking>.Is.Anything)); limitedMobileService.BookingManager = bookingManager; limitedMobileService.CustomerManager = customerManager; limitedMobileService.FakeAuthenticationForDebugging = true; // Act limitedMobileService.CreateProvisionalBooking(BUSINESS_ID, bookingDto); // Assert customerManager.VerifyAllExpectations(); bookingManager.VerifyAllExpectations(); // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method CacheHelper.ReAssignBusinessDaoToBusinessCache(); }
public void CheckAvailabilityWithoutMockingToChangeRatePlanOfBookingReturnsAllRatePlansApplicable() { using (new TestDataHelper(TestDataQueriesLimited.PopulateCheckRatePlanAvailabilityTestData, TestDataQueriesLimited.CleanupTestData)) { // Arrange var serviceWithoutMock = new LimitedMobileService { DisableAccessRightsCheck = true, FakeAuthenticationForDebugging = true, AvailabilityManager = new AvailabilityManager {RoomAvailabilityDao = new RoomsAvailabilityDao()}, BookingManager = new BookingManager {BookingDao = new BookingDao()}, BusinessManager = new BusinessManager {BusinessDao = new BusinessDao()} }; const long BUSINESS_ID = 1; // Create booking var booking = new BookingDto { BusinessId = BUSINESS_ID, Customer = new CustomerDto { BusinessId = BUSINESS_ID, Surname = "Test Customer", Email = "*****@*****.**" }, StartDateUTC = DateTime.Now, EndDateUTC = DateTime.Now.AddDays(1), NumberOfAdults = 2, IsBookingConfirmed = true, IsOffline = true, RoomTypeId = 1, RoomId = 1, RatePlanId = 1, IsProvisional = false, Cost = new decimal(50), BookingScenarioType = BookingScenarioTypeDto.OnAccountBooking }; booking = serviceWithoutMock.CreateBooking(BUSINESS_ID, booking); Assert.IsNotNull(booking.Id, "Booking Id is not attributed upon creation."); // Build availability Search criteria var searchCriteria = new AvailabilitySearchCriteriaDto { BusinessId = booking.BusinessId, StartDate = new CalendarDateDto { Day = booking.StartDateUTC.Day, Month = booking.StartDateUTC.Month, Year = booking.StartDateUTC.Year }, EndDate = new CalendarDateDto { Day = booking.EndDateUTC.Day, Month = booking.EndDateUTC.Month, Year = booking.EndDateUTC.Year }, NumberOfAdults = booking.NumberOfAdults, NumberOfChildren = booking.NumberOfChildren, RoomTypeId = booking.RoomTypeId, RoomId = booking.RoomId, ModifyBookingId = booking.Id }; // Act AvailabilitySearchResultDto searchResult = serviceWithoutMock.CheckAvailability(booking.BusinessId, searchCriteria); // Assert Assert.IsNotNull(searchResult, "AvailabilitySearchResult is null"); Assert.AreEqual(1, searchResult.BusinessCandidates.Count, "Total number of business candidates returned is incorrect."); Assert.IsTrue(searchResult.BusinessCandidates[0].BusinessId == booking.BusinessId, "BusinessId returned on search results is incorrect."); AvailabilityResultBusinessDto businessCandidate = searchResult.BusinessCandidates[0]; Assert.AreEqual(1, businessCandidate.RoomTypes.Count, "Number of roomTypes returned is incorrect."); Assert.AreEqual(booking.RoomTypeId, businessCandidate.RoomTypes[0].RoomTypeId, "RoomTypeId returned is incorrect."); Assert.AreEqual(1, businessCandidate.RoomTypes[0].RoomIds.Count, "Number of rooms returned is incorrect."); Assert.AreEqual(booking.RoomId, businessCandidate.RoomTypes[0].RoomIds[0], "RoomId returned is incorrect."); // Check Rateplans // There should be additional rateplans returned as available. Assert.AreEqual(2, businessCandidate.RoomTypes[0].RatePlans.Count, "Total number of rateplans returned is incorrect."); Assert.IsNotNull(businessCandidate.RoomTypes[0].RatePlans.Find(r => r.RatePlanId == booking.RatePlanId), "The rateplan for which the booking is made is not returned as available."); Assert.IsNotNull(businessCandidate.RoomTypes[0].RatePlans.Find(r => r.RatePlanId != booking.RatePlanId), "Additional rateplan is not returned as available."); // Since we have not setup price as part of test data, NoRateDefined reason code should be returned at RoomType level. Assert.AreEqual(UnavailabilityReasonCodeDto.NoRateDefined, businessCandidate.RoomTypes[0].UnAvailabilityReasonCode, "UnAvailabilityReasonCode at RoomType level is incorrect."); } }
public void ModifyBookingWithMisMatchBusinessThrowsException() { // Arrange const long BUSINESS_ID = 2; const long MISMATCHED_BUSINESS_ID = 5; // Stub the BusinessCache to have the businesses to be used by our service method CacheHelper.StubBusinessCacheMultipleBusiness(new List<long> { MISMATCHED_BUSINESS_ID, BUSINESS_ID }); // invalidate the cache so we make sure both our businesses are loaded into the cache Cache.Business.Invalidate(); //Set up a customer for the booking var customer = new CustomerDto { Id = 23, BusinessId = BUSINESS_ID, Surname = "Doe" }; var bookingDto = new BookingDto { BusinessId = BUSINESS_ID, StartDateUTC = DateTime.Now, EndDateUTC = DateTime.Now.AddDays(1), Customer = customer, RoomId = 1 }; try { // Act limitedMobileService.ModifyBooking(MISMATCHED_BUSINESS_ID, false, bookingDto); // Assert Assert.Fail("An exception SRVEX30000 of type ValidationException should have been thrown"); } catch (ValidationException ex) { // Assert Assert.AreEqual("SRVEX30000", ex.Code, "The Validation exception is not returning the right error code"); } finally { // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method CacheHelper.ReAssignBusinessDaoToBusinessCache(); } }
public void ModifyBookingWithInvalidBusinessThrowsException() { // Arrange const long BUSINESS_ID = 123456; //Set up a customer for the booking var customer = new CustomerDto { Id = 23, BusinessId = BUSINESS_ID, Surname = "Doe" }; var bookingDto = new BookingDto { BusinessId = BUSINESS_ID, StartDateUTC = DateTime.Now, EndDateUTC = DateTime.Now.AddDays(1), Customer = customer, RoomId = 1 }; try { // Act limitedMobileService.ModifyBooking(BUSINESS_ID, false, bookingDto); // Assert Assert.Fail("An exception SRVEX30001 of type ValidationException should have been thrown"); } catch (ValidationException ex) { // Assert Assert.AreEqual("SRVEX30001", ex.Code, "The Validation exception is not returning the right error code"); } }
public void ModifyBookingWithExpectedResult() { // Arrange const long BUSINESS_ID = 1; //Set up a customer for the booking var customer = new CustomerDto { Id = 23, BusinessId = BUSINESS_ID, Surname = "Doe" }; var bookingDto = new BookingDto { BusinessId = BUSINESS_ID, StartDateUTC = DateTime.Now, EndDateUTC = DateTime.Now.AddDays(1), Customer = customer, RoomId = 1 }; var stubBookingManager = MockRepository.GenerateMock<IBookingManager>(); limitedMobileService.BookingManager = stubBookingManager; stubBookingManager.Expect(c => c.ModifyBooking(Arg<bool>.Is.Equal(false), Arg<Booking>.Is.Anything)).Return(true); // Stub the BusinessCache to be used by our service method CacheHelper.StubBusinessCacheSingleBusiness(BUSINESS_ID); // invalidate the cache so we make sure our business is loaded into the cache Cache.Business.Invalidate(); // Act bool modifyBookingResult = limitedMobileService.ModifyBooking(BUSINESS_ID, false, bookingDto); // Assert Assert.IsTrue(modifyBookingResult, "booking was not modified successfully"); stubBookingManager.VerifyAllExpectations(); // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method CacheHelper.ReAssignBusinessDaoToBusinessCache(); }
public void CreateBookingMismatchedBusinessIdThrowsValidationException() { // Arrange // Parameters for the invoke const long BUSINESS_ID = 2; const long MISMATCHED_BUSINESS_ID = 5; var bookingDto = new BookingDto { BusinessId = BUSINESS_ID, Customer = new CustomerDto { Id = 1, BusinessId = BUSINESS_ID, Surname = "Test Customer", Email = "*****@*****.**" }, StartDateUTC = new DateTime(2012, 2, 1, 0, 0, 0, DateTimeKind.Utc), EndDateUTC = new DateTime(2012, 2, 2, 0, 0, 0, DateTimeKind.Utc), NumberOfAdults = 2, NumberOfChildren = 1, Cost = new decimal(120.5), IsBookingConfirmed = true, IsOffline = true, RoomTypeId = 1, RoomId = 1, RatePlanId = 1, IsCheckedIn = false, IsProvisional = false, Notes = "Testing note", BookingScenarioType = BookingScenarioTypeDto.OnAccountBooking }; // Stub the BusinessCache to be used by our service method CacheHelper.StubBusinessCacheSingleBusiness(MISMATCHED_BUSINESS_ID); // invalidate the cache so we make sure our business is loaded into the cache Cache.Business.Invalidate(); try { // Act limitedMobileService.CreateBooking(MISMATCHED_BUSINESS_ID, bookingDto); // Assert Assert.Fail("An exception SRVEX30000 of type ValidationException should have been thrown"); } catch (ValidationException ex) { // Assert Assert.AreEqual("SRVEX30000", ex.Code, "The Validation exception is not returning the right error code"); } finally { // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method CacheHelper.ReAssignBusinessDaoToBusinessCache(); } }
public bool SaveBooking(BookingDto booking) { var response = _bookingServices.SaveBookings(booking); return response; }
/// <summary> /// Infers the booking status by the boolean variables on the bookingDto /// </summary> /// <param name="booking">Booking object to use to infer the booking status</param> /// <returns>A booking status based upon the dto object state</returns> private static BookingStatusType GetBookingStatusFromBookingDto(BookingDto booking) { if (booking.IsProvisional) { return BookingStatusType.Provisional; } return BookingStatusType.Confirmed; }