public async Task Then_It_Validates_The_Id( CreateReservationCommand command) { await _commandHandler.Handle(command, CancellationToken.None); _mockCreateCommandValidator.Verify(validator => validator.ValidateAsync(command), Times.Once); }
public async Task <IActionResult> Create(CreateReservationCommand command) { if (!ModelState.IsValid) { ViewData["Room"] = await Mediator.Send(new GetHotelRoomQuery { Id = command.RoomId }); return(View()); } try { var id = await Mediator.Send(command); return(Redirect("/Reservation/" + nameof(Checkout) + '/' + id)); } catch (ModelStateException ex) { if (ex.ModelStates.Count > 0) { foreach (var key in ex.ModelStates) { ModelState.AddModelError(key, ex.Message); } } else { ModelState.AddModelError(string.Empty, ex.Message); } ViewData["Room"] = await Mediator.Send(new GetHotelRoomQuery { Id = command.RoomId }); return(View()); } }
public async Task <IActionResult> Create([FromBody] CreateReservationCommand command) { if (!ModelState.IsValid) { return(BadRequest( ModelState.Keys.SelectMany(x => this.ModelState[x].Errors) )); } bool response = false; var scheduleResponse = await mediator.Send( new CreateScheduleCommand() { Date = command.Date } ); if (scheduleResponse != Guid.Empty) { command.ScheduleId = scheduleResponse; response = await mediator.Send(command); } if (response) { return(Ok()); } else { return(BadRequest()); } }
public async Task Then_Cache_Service_Removes_From_Cache( CreateReservationCommand command) { await _commandHandler.Handle(command, CancellationToken.None); _mockCacheService.Verify(service => service.DeleteFromCache(command.Id.ToString()), Times.Once); }
// Commands private void LoadCommands() { CreateReservationCommand = new CreateReservationCommand(CreateReservation, CanCreateReservation); SelectAreaCommand = new SelectAreaUpdateFreeTablesCommand(UpdateCurrentFreeTables); AddTableToReservationCommand = new AddTableToReservationCommand(AddTableToCurrentReservation); RemoveTableFromReservationCommand = new RemoveTableFromReservationCommand(RemoveTableFromCurrentReservation); }
public async Task <FlightReservationCreateModel> Create([FromBody] FlightReservationCreateModel reservation) { Result result = Result.Success(); if (ModelState.IsValid) { //reservation.CombineTime(); try { CreateReservationCommand createReservationCommand = new CreateReservationCommand(reservation); result = await _mediator.Send(createReservationCommand); System.Diagnostics.Debug.WriteLine(reservation?.ToString()); } catch (MyValidationException ve) { System.Diagnostics.Debug.WriteLine(ve.Failures); reservation.ReturnResult = ve.FailuresMessage.ToString(); return(reservation); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } reservation.ReturnResult = String.Join("/n", result.Errors); return(reservation); } reservation.ReturnResult = "InValid Model"; return(reservation); }
public async Task Then_Gets_Provider_Reservation_From_The_Cache(CreateReservationCommand command) { await _commandHandler.Handle(command, CancellationToken.None); _mockCacheRepository.Verify(service => service.GetProviderReservation(command.Id, command.UkPrn.Value), Times.Once); _mockCacheRepository.Verify(service => service.GetEmployerReservation(It.IsAny <Guid>()), Times.Never); }
public async void CreateReservation_ContactInvalid_False() { //arrange var contact = ContactFaker.GetContactContactNameGreater(); var contactType = ContactTypeFaker.GetContactTypeOk(); var faker = new Faker(); var message = faker.Lorem.Paragraph(); var createReservationCommand = new CreateReservationCommand( contactId: contact.Id, contactName: contact.Name, contactPhone: contact.Name, contactBirthdate: contact.BirthDate, contactTypeId: contactType.Id, message: message ); _dependencyResolverMock .Setup(x => x.Resolve <IReservationRepository>()) .Returns(_reservationRepositoryMock.Object); _dependencyResolverMock .Setup(x => x.Resolve <IContactRepository>()) .Returns(_contactRepositoryMock.Object); _dependencyResolverMock .Setup(x => x.Resolve <IContactTypeRepository>()) .Returns(_contactTypeRepositoryMock.Object); _contactRepositoryMock.Setup(x => x.GetByIdAsync(createReservationCommand.ContactId.Value)) .Returns(Task.FromResult((Contact)null)); _contactTypeRepositoryMock.Setup(x => x.GetByIdAsync(createReservationCommand.ContactTypeId)) .Returns(Task.FromResult(contactType)); var handler = new ReservationCommandHandler(_dependencyResolverMock.Object); //Act var result = await handler.Handle(createReservationCommand, new CancellationToken()); //Assert Assert.False(result.Success); _contactRepositoryMock.Verify(x => x.GetByIdAsync(createReservationCommand.ContactId.Value), Times.Once); _reservationRepositoryMock.Verify(x => x.AddAsync(It.IsAny <Reservation>()), Times.Never); _reservationRepositoryMock.Verify(x => x.CommitAsync(), Times.Never); }
public async Task <IActionResult> PostReview(ReservationsRouteModel routeModel, PostReviewViewModel viewModel) { var isProvider = routeModel.UkPrn.HasValue; var reviewViewName = isProvider ? ViewNames.ProviderReview : ViewNames.EmployerReview; try { if (!isProvider) { if (!ModelState.IsValid) { var reviewViewModel = new ReviewViewModel(routeModel, viewModel); return(View(reviewViewName, reviewViewModel)); } if (!viewModel.Reserve.Value) { var homeUrl = _urlHelper.GenerateDashboardUrl(routeModel.EmployerAccountId); return(Redirect(homeUrl)); } } Guid?userId = null; if (!isProvider) { var userAccountIdClaim = HttpContext.User.Claims.First(c => c.Type.Equals(EmployerClaims.IdamsUserIdClaimTypeIdentifier)); userId = Guid.Parse(userAccountIdClaim.Value); } var command = new CreateReservationCommand { Id = routeModel.Id.GetValueOrDefault(), UkPrn = routeModel.UkPrn, UserId = userId }; var result = await _mediator.Send(command); routeModel.AccountLegalEntityPublicHashedId = result.AccountLegalEntityPublicHashedId; routeModel.CohortReference = result.CohortRef; if (result.IsEmptyCohortFromSelect) { routeModel.ProviderId = result.ProviderId; } } catch (ValidationException ex) { _logger.LogWarning(ex, "Validation error when trying to create reservation from cached reservation."); return(RedirectToRoute(routeModel.UkPrn.HasValue ? RouteNames.ProviderIndex : RouteNames.EmployerIndex, routeModel)); } catch (CachedReservationNotFoundException ex) { _logger.LogWarning(ex, "Expected a cached reservation but did not find one."); return(RedirectToRoute(routeModel.UkPrn.HasValue ? RouteNames.ProviderIndex : RouteNames.EmployerIndex, routeModel)); } return(RedirectToRoute(routeModel.UkPrn.HasValue ? RouteNames.ProviderCompleted : RouteNames.EmployerCompleted, routeModel)); }
public async Task <IActionResult> Post([FromBody] CreateReservationCommand command) { if (await authService.CheckIfBanned(this.User).ConfigureAwait(false)) { return(this.Forbid()); } return(this.Ok(await this.mediator.Send(command).ConfigureAwait(false))); }
public async Task Then_Returns_Response_From_Reservation_Api( CreateReservationCommand command) { var result = await _commandHandler.Handle(command, CancellationToken.None); result.Id.Should().Be(_apiResponse.Id); result.AccountLegalEntityPublicHashedId.Should() .Be(_cachedReservation.AccountLegalEntityPublicHashedId); result.CohortRef.Should().Be(_cachedReservation.CohortRef); }
public async Task Then_Gets_Employer_Reservation_From_The_Cache(CreateReservationCommand command) { command.UkPrn = null; _mockCacheRepository.Setup(r => r.GetEmployerReservation(It.IsAny <Guid>())) .ReturnsAsync(_cachedReservation); await _commandHandler.Handle(command, CancellationToken.None); _mockCacheRepository.Verify(service => service.GetEmployerReservation(command.Id), Times.Once); _mockCacheRepository.Verify(service => service.GetProviderReservation(It.IsAny <Guid>(), It.IsAny <uint>()), Times.Never); }
public async Task Then_If_Has_Id_Is_Valid( CreateReservationCommandValidator validator) { var command = new CreateReservationCommand { Id = Guid.NewGuid() }; var result = await validator.ValidateAsync(command); result.IsValid().Should().BeTrue(); }
public async Task Then_If_Has_No_Id_Is_Invalid( CreateReservationCommandValidator validator) { var command = new CreateReservationCommand(); var result = await validator.ValidateAsync(command); result.IsValid().Should().BeFalse(); result.ValidationDictionary.Count.Should().Be(1); result.ValidationDictionary .Should().ContainKey(nameof(CreateReservationCommand.Id)) .WhichValue.Should().Be($"{nameof(CreateReservationCommand.Id)} has not been supplied"); }
public int CreateReservation(RequestBase request) { CreateReservationCommand command = new CreateReservationCommand(new Reservation() { Channel = request.Document.Header.Channel, Date = DateTime.Now, PrinterName = request.Document.Header.PrinterName, Register = request.Document.Header.Register }); _commandProcessor.Handler(command); return(command.Reservation.Id); }
public void And_No_Reservation_Found_In_Cache_Then_Throws_Exception( CreateReservationCommand command) { _mockCacheRepository .Setup(service => service.GetProviderReservation(It.IsAny <Guid>(), It.IsAny <uint>())) .ReturnsAsync((CachedReservation)null); _mockCacheRepository .Setup(service => service.GetEmployerReservation(It.IsAny <Guid>())) .ReturnsAsync((CachedReservation)null); Func <Task> act = async() => { await _commandHandler.Handle(command, CancellationToken.None); }; act.Should().ThrowExactly <CachedReservationNotFoundException>() .WithMessage($"No reservation was found with id [{command.Id}]."); }
public async Task Then_Calls_Reservation_Api_To_Create_Reservation_With_Course_And_UserId( CreateReservationCommand command) { _cachedReservation.CourseId = "123-1"; command.UserId = _expectedUserId; await _commandHandler.Handle(command, CancellationToken.None); _mockApiClient.Verify(client => client.Create <CreateReservationResponse>(It.Is <ReservationApiRequest>(apiRequest => apiRequest.AccountId == _expectedAccountId && apiRequest.StartDate == $"{_expectedStartDate:yyyy-MMM}-01" && apiRequest.AccountLegalEntityName == _expectedLegalEntityName && apiRequest.UserId == _expectedUserId && apiRequest.CourseId.Equals("123-1"))), Times.Once); }
public void And_The_Command_Is_Not_Valid_Then_Throws_ValidationException( CreateReservationCommand command, ValidationResult validationResult, string propertyName) { validationResult.AddError(propertyName); _mockCachedReservationValidator .Setup(validator => validator.ValidateAsync(_cachedReservation)) .ReturnsAsync(validationResult); Func <Task> act = async() => { await _commandHandler.Handle(command, CancellationToken.None); }; act.Should().ThrowExactly <ValidationException>() .Which.ValidationResult.MemberNames.First(c => c.StartsWith(propertyName)).Should().NotBeNullOrEmpty(); }
public async Task <IActionResult> Post([FromBody] CreateReservationCommand command) { try { var response = await _mediator.Send(command); // if (!response.IsValid) // return BadRequest(response.Errors); // return Ok(response.Result); return(Ok(response)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task WhenApartmantIsUnavailable_ThrowApartmentUnavailableException() { this.mediatorMock.Setup(m => m.Send(It.IsAny <GetAvailableDatesQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(this.forRentalDates.Select(frd => frd.Date).Skip(2)); var request = new CreateReservationCommand() { ApartmentId = this.apartment.Id, GuestId = this.guest.UserId, StartDate = minDate, NumberOfNights = DaysToAdd }; await Assert .ThrowsAsync <ApartmentUnavailableException>(async() => await this.sut.Handle(request, CancellationToken.None).ConfigureAwait(false)) .ConfigureAwait(false); }
private async Task CheckAvailabilityAsync(CreateReservationCommand command) { var roomAvailablityTask = _bus.Request <CheckRoomCapacity, RoomCapacityRespond>(new { command.RoomId, command.PersonCount }); var officeAvailabilityTask = _bus.Request <CheckOfficeHoursAvailable, OfficeHoursAvailabilityRespond>(new { command.OfficeId, StartTime = command.StartDate.TimeOfDay, EndTime = command.EndDate.TimeOfDay }); var reservationAvailabilityTask = CheckReservationAvailable(new CheckReservationAvailableCommand { RoomId = command.RoomId, StartDate = command.StartDate, EndDate = command.EndDate }); await Task.WhenAll(officeAvailabilityTask, roomAvailablityTask, reservationAvailabilityTask); var roomAvailabilityResponse = await roomAvailablityTask; var officeAvailabilityResponse = await officeAvailabilityTask; var reservationAvailabilityResponse = await reservationAvailabilityTask; if (roomAvailabilityResponse.Message.Available == false) { throw new ServiceException("Please make a selection according to the number of office capacity."); } if (officeAvailabilityResponse.Message.Available == false) { throw new ServiceException("Please make an appropriate choice for office hours."); } if (reservationAvailabilityResponse == false) { throw new ServiceException("Please choose available range of date to make an reservation"); } }
public async Task <IActionResult> CreateReservation([FromBody] CreateReservationCommand command) { try { var result = await _mediator.Send(command); return(NoContent()); // TEMPORARY } catch (ClassRoomAlreadyReservedAtThatTimePeriodException e) { logger.LogError(e.Message); return(BadRequest(e.Message)); } catch (InstructorAlreadyAssignedAtThatTimePeriodException e) { logger.LogError(e.Message); return(BadRequest(e.Message)); } }
public Task <HttpResponseMessage> Post(CreateReservationCommand reserve) { HttpResponseMessage response = new HttpResponseMessage(); try { _service.Create(reserve); response = Request.CreateResponse(HttpStatusCode.OK, new { message = "Pacote cadastrado com sucesso" }); } catch (Exception ex) { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); } var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); }
public async Task WhenApartmantIsAvailable_CreateReservationWithCreatedState() { this.mediatorMock.Setup(m => m.Send(It.IsAny <GetAvailableDatesQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(this.forRentalDates.Select(frd => frd.Date)); var request = new CreateReservationCommand() { ApartmentId = this.apartment.Id, GuestId = this.guest.UserId, StartDate = minDate, NumberOfNights = DaysToAdd }; var response = await this.sut.Handle(request, CancellationToken.None).ConfigureAwait(false); var reservation = this.Context.Reservations.SingleOrDefault(r => r.Id == response.Id && !r.IsDeleted); Assert.NotNull(reservation); Assert.Equal(ReservationStates.Created, reservation.ReservationState); }
public async Task CreateReservationAsync(CreateReservationCommand command) { Check.NotNull(command, nameof(command)); await CheckAvailabilityAsync(command); Reservation reservation = _mapper.Map <Reservation>(command); reservation.CreatedBy = UserId; reservation.Resources.AddRange(command.Resources.Select(x => new Resource { Id = Guid.NewGuid(), ResourceId = x })); await _applicationContext.Reservations.AddAsync(reservation); await _applicationContext.SaveChangesAsync(); }
public async Task <ActionResult <ReservationResponseDto> > Post(CreateReservationCommand command) { return(await Mediator.Send(command)); }
public async Task CreateReservation([FromServices] CreateReservationCommand command, [FromBody] ReservationInput input) { await command.ExecuteAsync(input); }
public async Task <IActionResult> Create([FromBody] CreateReservationCommand command) { var result = await _mediator.Send(command); return(new JsonResult(result)); }
public async Task AddAsync(Domain.Models.Reservation reservation) { var command = new CreateReservationCommand(reservation.Id, reservation.UserId, reservation.ResourceId, reservation.Timeslot); await _eventBus.SendCommand(command); }
public async Task<IActionResult> Post(CreateReservationCommand command) { return Ok(await Mediator.Send(command)); }