public void TestBookingFormSuccessfulPost() { BookingController controller = GetController(true); var formModel = new BookingFormViewModel() { AccommodationId = 1, AccommodationName = "Test Accommodation", Persons = new List <BookingPerson>() { new BookingPerson() { Country = new Country() { Id = 1 }, Nationality = new Country() { Id = 2 } } } }; RedirectToActionResult result = controller.BookingForm(formModel) as RedirectToActionResult; Assert.Equal("InsuranceForm", result.ActionName); }
public ActionResult BookingConfirm(BookingFormViewModel model) { if (!ModelState.IsValid) { //var errors = ModelState.Select(x => x.Value.Errors).Where(y => y.Count > 0).Select(r => r[0].ErrorMessage).ToList(); //model.Errors = String.Join("\n", errors); return(View("BookingForm", model)); } var booking = new BookingDto { ClientEmail = model.ClientEmail, ClientName = model.ClientName, DateCreated = DateTime.Now, SeatId = model.SeatId, PlayBillId = model.Poster.Id, Id = 0 }; bool isTicketBusy = _bookingService.IsBookingBusy(booking); if (isTicketBusy) { return(View("_Result", new ResultViewModel("Sorry. Ticket was already booked."))); } bool success = _bookingService.AddBooking(booking); string message = success ? "You successfully boocked a ticket" : "Server error occured :("; return(View("_Result", new ResultViewModel(message))); }
public void TestBookingFormBadPost() { BookingController controller = GetController(true); //Fake post data with missing attributes var formModel = new BookingFormViewModel() { AccommodationId = 1, AccommodationName = "Test Accommodation", Persons = new List <BookingPerson>() { new BookingPerson() { Country = new Country() { Id = 1 }, Nationality = new Country() { Id = 2 } } } }; //Manually add error to model state controller.ModelState.AddModelError("test", "Test Error"); ViewResult result = controller.BookingForm(formModel) as ViewResult; Assert.Equal("BookingForm", result.ViewName); Assert.False(controller.ModelState.IsValid); }
public void TestBookingFormPostNonExistentAccommodation() { BookingController controller = GetController(false); //Fake post data with a non-existent accommodation var formModel = new BookingFormViewModel() { AccommodationId = 333, AccommodationName = "Test Accommodation", Persons = new List <BookingPerson>() { new BookingPerson() { Country = new Country() { Id = 1 }, Nationality = new Country() { Id = 2 } } } }; IActionResult result = controller.BookingForm(formModel); Assert.IsType <BadRequestResult>(result); }
public ActionResult BookTables(BookingFormViewModel model) { if (!ModelState.IsValid) { return(PartialView("_AvailableTables", model)); } var currentUserId = this.authProvider.CurrentUserId; var peopleCount = 2 * model.TwoPeopleInput + 4 * model.FourPeopleInput + 6 * model.SixPeopleInput; var booking = this.bookingService.CreateBooking(model.PlaceId, currentUserId, model.DateTime, peopleCount); model.BookingId = booking.Id; if (model.TwoPeopleInput > 0) { var table = this.tablesService.GetByPlaceAndNumberOfPeople(model.PlaceId, 2); this.bookedTablesService.AddBookedTables(booking.Id, table.Id, model.TwoPeopleInput); } if (model.FourPeopleInput > 0) { var bookedTable = this.tablesService.GetByPlaceAndNumberOfPeople(model.PlaceId, 4); this.bookedTablesService.AddBookedTables(booking.Id, bookedTable.Id, model.FourPeopleInput); } if (model.SixPeopleInput > 0) { var bookedTable = this.tablesService.GetByPlaceAndNumberOfPeople(model.PlaceId, 6); this.bookedTablesService.AddBookedTables(booking.Id, bookedTable.Id, model.SixPeopleInput); } return(PartialView("_SuccessfullBooking", model)); }
public async Task <IActionResult> Create(ListingDetailsViewModel model) { if (!ModelState.IsValid) { return(RedirectToAction("Details", "Listing", new { id = model.Id })); } var listing = await _unitOfWork.Listings.GetByIdWithAccessories(model.Id); var available = await _unitOfWork.Bookings.IsAvailable(listing.Id, model.From.Value, model.To.Value); if (!available) { return(RedirectToAction("Details", "Listing", new { id = model.Id })); } var user = await _userManager.GetUserAsync(User); BookingFormViewModel viewModel = new BookingFormViewModel { Listing = _mapper.Map <ListingDetailsViewModel>(listing) }; viewModel.PricePerDay = viewModel.Listing.Price; viewModel.Listing.From = model.From.Value; viewModel.Listing.To = model.To.Value; viewModel.UserEmailAddress = user.Email; viewModel.CalculateTotalPrice(); return(View(viewModel)); }
public void BookTablesShould_ReturnSameView_WhenModelIsNotValid() { var bookingsServiceMock = new Mock <IBookingService>(); var placeServiceMock = new Mock <IPlaceService>(); var consumableServiceMock = new Mock <IConsumableService>(); var tableServiceMock = new Mock <ITablesService>(); var bookedTableServiceMock = new Mock <IBookedTablesService>(); var authProviderMock = new Mock <IAuthenticationProvider>(); var factoryMock = new Mock <IViewModelFactory>(); var controller = new Web.Controllers.BookingsController(authProviderMock.Object, placeServiceMock.Object, bookingsServiceMock.Object, factoryMock.Object, consumableServiceMock.Object, bookedTableServiceMock.Object, tableServiceMock.Object); controller.ModelState.AddModelError("key", "message"); var model = new BookingFormViewModel() { DateTime = DateTime.Now, PlaceId = Guid.NewGuid() }; controller .WithCallTo(c => c.BookTables(model)) .ShouldRenderPartialView("_AvailableTables") .WithModel(model); }
public ActionResult New() { var viewModel = new BookingFormViewModel { Booking = new Booking() }; return(View("AccommodationForm", viewModel)); }
public ActionResult BookingForm(int playBillId) { var poster = _bookingService.GetBookingDtoForm(playBillId); var model = new BookingFormViewModel { Poster = poster, FreeSeats = _bookingService.GetFreeSeatsForPlayBill(playBillId).ToList() }; return(View("BookingForm", model)); }
public void GetAvailableTablesShould_ReturnViewWithCorrectModel_WhenModelIsValid(int peoplePerTable) { var bookingsServiceMock = new Mock <IBookingService>(); var placeServiceMock = new Mock <IPlaceService>(); var consumableServiceMock = new Mock <IConsumableService>(); var tableServiceMock = new Mock <ITablesService>(); var bookedTableServiceMock = new Mock <IBookedTablesService>(); var authProviderMock = new Mock <IAuthenticationProvider>(); var factoryMock = new Mock <IViewModelFactory>(); var controller = new Web.Controllers.BookingsController(authProviderMock.Object, placeServiceMock.Object, bookingsServiceMock.Object, factoryMock.Object, consumableServiceMock.Object, bookedTableServiceMock.Object, tableServiceMock.Object); var model = new BookingViewModel() { DateTime = DateTime.Now, PlaceId = Guid.NewGuid() }; var booking = new Booking() { Id = Guid.NewGuid() }; var list = new List <Booking>() { booking }; var table = new Table() { Id = Guid.NewGuid(), NumberOfPeople = peoplePerTable }; var bookedTable = new BookedTables() { BookingId = booking.Id, TableId = table.Id, Table = table, TablesCount = 3 }; bookingsServiceMock.Setup(s => s.FindAllOn(model.DateTime, model.PlaceId)).Returns(list.AsQueryable()); bookedTableServiceMock.Setup(s => s.GetBookedTable(booking.Id)).Returns(bookedTable); tableServiceMock.Setup(s => s.GetTablesCount(model.PlaceId, peoplePerTable)).Returns(10); var returnModel = new BookingFormViewModel() { TwoPeopleTablesCount = 7, FourPeopleTablesCount = 0, SixPeopleTablesCount = 0, DateTime = model.DateTime, PlaceId = model.PlaceId }; factoryMock.Setup(f => f.CreateBookingFormViewModel(7, 0, 0, model.PlaceId, model.DateTime)).Returns(returnModel); controller .WithCallTo(c => c.GetAvailableTables(model)) .ShouldRenderPartialView("_AvailableTables") .WithModel(returnModel); }
public void TestBookingFormSuccessfulGet() { //Initialize controller and execute action //There are accommodations in the repository. BookingController controller = GetController(true); ViewResult result = controller.BookingForm(1, null) as ViewResult; BookingFormViewModel model = result.Model as BookingFormViewModel; Assert.Equal("BookingForm", result.ViewName); Assert.Equal(4, model.Persons.Count); }
public IActionResult BookingForm(int id, int?persons) { var formModel = new BookingFormViewModel(); Accommodation accommodation; try { accommodation = _accommodationManager.GetAccommodation(id); formModel.AccommodationId = accommodation.Id; formModel.AccommodationName = accommodation.Name; } catch (KeyNotFoundException) { return(NotFound()); } formModel.Persons = new List <BookingPerson>(); //If an amount of persons was given, use it. //Otherwise, get the maximum persons from the Accommodation. int maxPersons; if (persons.HasValue && persons.Value <= accommodation.MaxPersons) { maxPersons = persons.Value; } else { maxPersons = accommodation.MaxPersons; } ViewBag.MaxPersons = maxPersons; //Initialize BookingPersons for the form for (int i = 0; i < accommodation.MaxPersons; i++) { formModel.Persons.Add(new BookingPerson()); } //Get countries from db var countries = _countryManager.GetCountries(); ViewBag.Countries = countries; //Get client API key ViewBag.MapApiKey = _mapService.GetApiKey(); return(View("BookingForm", formModel)); }
public ActionResult Create(BookingFormViewModel viewModel) { var containers = new List <Container>(); var shipInDb = _context.Ships.Single(s => s.Id == viewModel.ShipId); var totalNumberOfContainer = 0; foreach (var containerId in viewModel.ContainerIds) { containers.Add(_context.Containers.Find(containerId)); } foreach (var container in containers) { totalNumberOfContainer += container.Amount; } try { shipInDb.Containers = containers; shipInDb.NumberOfAvailableContainerBay -= totalNumberOfContainer; _context.SaveChanges(); } catch (Exception ex) { return(Json(new { success = false, responseText = "Fail to update ship containers.<br/><strong>Error:</strong> " + ex.Message }, JsonRequestBehavior.AllowGet)); } var booking = new Booking { BookedBy = _context.Users.Find(User.Identity.GetUserId()), Customer = _context.Customers.Find(viewModel.CustomerId), Containers = containers, Schedule = _context.Schedules.Find(viewModel.ScheduleId), Ship = shipInDb, BookedAt = DateTime.Now }; try { _context.Bookings.Add(booking); _context.SaveChanges(); return(Json(new { success = true, responseText = "Booking has been created successfully." }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, responseText = "Booking Failed.<br/><strong>Error:</strong> " + ex.Message }, JsonRequestBehavior.AllowGet)); } }
public ActionResult New(int?id) { if (id == null) { TempData["Message"] = "Please select an existing customer or create a new one before proceeding to create booking."; return(RedirectToAction("Index", "Customers")); } var viewModel = new BookingFormViewModel { Customer = _context.Customers.Single(c => c.Id == id) }; return(View(viewModel)); }
public ActionResult Save(Booking booking) { if (!ModelState.IsValid) { var viewModel = new BookingFormViewModel { Booking = booking }; return(View("AccommodationForm", viewModel)); } _db.Bookings.Add(booking); _db.SaveChanges(); return(RedirectToAction("Index", "Bookings")); }
public void BookTablesShould_ReturnViewWithCorrectModel_WhenModelIsValid() { var bookingsServiceMock = new Mock <IBookingService>(); var placeServiceMock = new Mock <IPlaceService>(); var consumableServiceMock = new Mock <IConsumableService>(); var tableServiceMock = new Mock <ITablesService>(); var bookedTableServiceMock = new Mock <IBookedTablesService>(); var authProviderMock = new Mock <IAuthenticationProvider>(); var factoryMock = new Mock <IViewModelFactory>(); var controller = new Web.Controllers.BookingsController(authProviderMock.Object, placeServiceMock.Object, bookingsServiceMock.Object, factoryMock.Object, consumableServiceMock.Object, bookedTableServiceMock.Object, tableServiceMock.Object); var model = new BookingFormViewModel() { DateTime = DateTime.Now, PlaceId = Guid.NewGuid(), TwoPeopleInput = 1, FourPeopleInput = 0, SixPeopleInput = 0 }; var userId = Guid.NewGuid().ToString(); authProviderMock.Setup(ap => ap.CurrentUserId).Returns(userId); var booking = new Booking() { Id = Guid.NewGuid() }; bookingsServiceMock.Setup(s => s.CreateBooking(model.PlaceId, userId, model.DateTime, 2)).Returns(booking); var table = new Table() { Id = Guid.NewGuid() }; tableServiceMock.Setup(s => s.GetByPlaceAndNumberOfPeople(model.PlaceId, 2)).Returns(table); controller .WithCallTo(c => c.BookTables(model)) .ShouldRenderPartialView("_SuccessfullBooking") .WithModel(model); }
public void BookTablesShould_CallBookedTableServiceMethodAddBookedTables_WhenModelIsValid() { var bookingsServiceMock = new Mock <IBookingService>(); var placeServiceMock = new Mock <IPlaceService>(); var consumableServiceMock = new Mock <IConsumableService>(); var tableServiceMock = new Mock <ITablesService>(); var bookedTableServiceMock = new Mock <IBookedTablesService>(); var authProviderMock = new Mock <IAuthenticationProvider>(); var factoryMock = new Mock <IViewModelFactory>(); var controller = new Web.Controllers.BookingsController(authProviderMock.Object, placeServiceMock.Object, bookingsServiceMock.Object, factoryMock.Object, consumableServiceMock.Object, bookedTableServiceMock.Object, tableServiceMock.Object); var model = new BookingFormViewModel() { DateTime = DateTime.Now, PlaceId = Guid.NewGuid(), TwoPeopleInput = 1, FourPeopleInput = 0, SixPeopleInput = 0 }; var userId = Guid.NewGuid().ToString(); authProviderMock.Setup(ap => ap.CurrentUserId).Returns(userId); var booking = new Booking() { Id = Guid.NewGuid() }; bookingsServiceMock.Setup(s => s.CreateBooking(model.PlaceId, userId, model.DateTime, 2)).Returns(booking); var table = new Table() { Id = Guid.NewGuid() }; tableServiceMock.Setup(s => s.GetByPlaceAndNumberOfPeople(model.PlaceId, 2)).Returns(table); controller.BookTables(model); bookedTableServiceMock.Verify(s => s.AddBookedTables(booking.Id, table.Id, model.TwoPeopleInput), Times.Once); }
public async Task <IActionResult> Create(BookingFormViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.GetUserAsync(HttpContext.User); var listing = await _unitOfWork.Listings.GetByIdWithImagesAndAccessories(model.Listing.Id); var available = await _unitOfWork.Bookings.IsAvailable(listing.Id, model.Listing.From.Value, model.Listing.To.Value); if (!available) { return(NotFound()); } var stripeCustomerId = await _stripe.AddCustomerToStripeAsync(model.StripeToken, user.Email); var booking = _mapper.Map <Booking>(model); _mapper.Map(listing, booking); booking.User = user; booking.StripeCustomerIdToken = stripeCustomerId; booking.CalculateTotalPrice(); booking.NewlyCreated(); await _unitOfWork.Bookings.AddAsync(booking); _unitOfWork.Complete(); var bookingUrl = Url.NewBookingCallbackLink(listing.Id, Request.Scheme); var imageUrl = _imageUploader.GetBikeImageById(listing.Images.FirstOrDefault()?.ImagePublicId, 690, 690); await _emailSender.SendNewBookingEmailAsync(listing.User.Email, bookingUrl, imageUrl, booking); return(RedirectToAction("Details", new { id = booking.Id })); }
/// <summary> /// Component initialization logic. /// </summary> /// <returns></returns> protected override async Task OnInitializedAsync() { Status = APIOperationStatus.GET_Pending; _hubConnection = new HubConnectionBuilder() .WithUrl(NavigationManager.ToAbsoluteUri("/appointment")) .Build(); _hubConnection.On <AppointmentMessage>("Appointment", msg => { ToastService.ShowInfo("Received"); var consultant = ViewModel.ConsultantList .FirstOrDefault(c => c.Id == msg.ConsultantId); var appointment = new AppointmentViewModel { Id = msg.AppointmentId, ConsultantId = msg.ConsultantId, Date = msg.Date, TimeSlotId = msg.TimeSlotId }; consultant?.Appointment.Add(appointment); EvaluateTimeSlots(); StateHasChanged(); }); await _hubConnection.StartAsync(); ViewModel = new BookingViewModel(); FormModel = new BookingFormViewModel(); ConsultantIsValid = false; PatientIsValid = false; PatientEditContext = new EditContext(FormModel.Patient); PatientEditContext.OnFieldChanged += HandlePatientEditContextFieldChanged; ScheduleEditContext = new EditContext(FormModel.Schedule); ScheduleEditContext.OnFieldChanged += HandleConsultantFieldChanged; try { ViewModel = await FetchBookingInfo(); Status = APIOperationStatus.GET_Success; } catch (Exception e) { Console.WriteLine(e); Status = APIOperationStatus.GET_Error; } StateHasChanged(); await base.OnInitializedAsync(); }
public IActionResult BookingForm(BookingFormViewModel formData) { if (!ModelState.IsValid) { //Restore accommodation object from ID Accommodation accommodation; try { accommodation = _accommodationManager.GetAccommodation(formData.AccommodationId); formData.AccommodationName = accommodation.Name; } catch (KeyNotFoundException) { return(NotFound()); } ViewBag.Countries = _countryManager.GetCountries(); ViewBag.MaxPersons = formData.Persons.Count(); //Initialize BookingPersons up to the maximum that the accommodation will support. //Old values entered by the user should be kept. for (int i = 0; i < accommodation.MaxPersons; i++) { if (formData.Persons.ElementAtOrDefault(i) == null) { formData.Persons.Add(new BookingPerson()); } } return(View("BookingForm", formData)); } else { //Get accommodation from posted ID Accommodation accommodation; try { accommodation = _accommodationManager.GetAccommodation(formData.AccommodationId); } catch (KeyNotFoundException) { return(BadRequest()); } //Get country and nationality objects from ID foreach (BookingPerson person in formData.Persons) { person.Country = _countryManager.GetCountry(person.Country.Id); person.Nationality = _countryManager.GetCountry(person.Nationality.Id); } //Store model in Session HttpContext.Session.Set(BOOKINGSESSIONKEY, new Booking() { Accommodation = accommodation, Persons = formData.Persons, }); return(RedirectToAction("InsuranceForm")); } }