private static List <LinkedParticipantDto> MapLinkedParticipants(BookNewHearingRequest request)
        {
            var dto = LinkedParticipantRequestToLinkedParticipantDtoMapper.MapToDto(request.LinkedParticipants)
                      .ToList();

            return(dto);
        }
        private static List <NewParticipant> MapParticipants(BookNewHearingRequest request, CaseType caseType)
        {
            var newParticipants = request.Participants.Select(
                x => ParticipantRequestToNewParticipantMapper.Map(x, caseType)).ToList();

            return(newParticipants);
        }
        public async Task Should_create_a_hearing_with_endpoints()
        {
            var newHearingRequest = new BookNewHearingRequest
            {
                Participants = new List <BookingsApi.Contract.Requests.ParticipantRequest>
                {
                    new BookingsApi.Contract.Requests.ParticipantRequest
                    {
                        CaseRoleName     = "CaseRole", ContactEmail = "*****@*****.**",
                        HearingRoleName  = "HearingRole", DisplayName = "display name1",
                        FirstName        = "fname", MiddleNames = "", LastName = "lname1", Username = "******",
                        OrganisationName = "", Representee = "", TelephoneNumber = ""
                    },
                    new BookingsApi.Contract.Requests.ParticipantRequest
                    {
                        CaseRoleName    = "CaseRole", ContactEmail = "*****@*****.**",
                        HearingRoleName = "HearingRole", DisplayName = "display name2",
                        FirstName       = "fname2", MiddleNames = "", LastName = "lname2",
                        Username        = "******", OrganisationName = "", Representee = "",
                        TelephoneNumber = ""
                    },
                },
                Endpoints = new List <EndpointRequest>
                {
                    new EndpointRequest
                    {
                        DisplayName = "displayname1", DefenceAdvocateUsername = "******"
                    },
                    new EndpointRequest
                    {
                        DisplayName = "displayname2", DefenceAdvocateUsername = "******"
                    },
                }
            };

            var bookingRequest = new BookHearingRequest
            {
                BookingDetails = newHearingRequest
            };

            // setup response
            var hearingDetailsResponse = HearingResponseBuilder.Build()
                                         .WithEndPoints(2)
                                         .WithParticipant("Representative", "*****@*****.**")
                                         .WithParticipant("Individual", "*****@*****.**");

            _bookingsApiClient.Setup(x => x.BookNewHearingAsync(newHearingRequest))
            .ReturnsAsync(hearingDetailsResponse);

            var result = await _controller.Post(bookingRequest);

            result.Result.Should().BeOfType <CreatedResult>();
            var createdObjectResult = (CreatedResult)result.Result;

            createdObjectResult.StatusCode.Should().Be(201);
        }
 public static Dictionary <string, string> ErrorMessages(BookNewHearingRequest request)
 {
     return(new Dictionary <string, string>
     {
         { "payload", JsonConvert.SerializeObject(request) },
         { "ScheduledDateTime", request.ScheduledDateTime.ToString("s") },
         { "ScheduledDuration", request.ScheduledDuration.ToString() },
         { "CaseTypeName", request.CaseTypeName },
         { "HearingTypeName", request.HearingTypeName }
     });
 }
Exemple #5
0
        public void Should_return_error_messages_with_empty_validation_result_and_booking_request()
        {
            var validationResult = new ValidationResult();

            var request = new BookNewHearingRequest();
            var result  = HearingControlLogHelper.ErrorMessages(validationResult, request);

            result.Should().NotBeNull();
            result.Count.Should().Be(1);
            result["payload"].Should().NotBe("Empty Payload");
        }
Exemple #6
0
 public BookHearingRequestBuilder(CreateHearingRequest createHearingRequest)
 {
     _request = new BookNewHearingRequest
     {
         CaseTypeName = createHearingRequest.CaseType,
         Cases        = new List <CaseRequest>(),
         Participants = new List <ParticipantRequest>()
     };
     _createHearingRequest = createHearingRequest;
     _randomNumber         = new Random();
 }
        private static List <NewEndpoint> MapEndpoints(BookNewHearingRequest request, IRandomGenerator randomGenerator,
                                                       string sipAddressStem)
        {
            var endpoints = new List <NewEndpoint>();

            if (request.Endpoints != null)
            {
                endpoints = request.Endpoints.Select(x =>
                                                     EndpointToResponseMapper.MapRequestToNewEndpointDto(x, randomGenerator, sipAddressStem)).ToList();
            }

            return(endpoints);
        }
        private async Task <ActionResult <HearingDetailsResponse> > PostWithParticipants(
            params BookingsApi.Contract.Requests.ParticipantRequest[] participants)
        {
            var hearing = new BookNewHearingRequest
            {
                Participants = new List <BookingsApi.Contract.Requests.ParticipantRequest>(participants)
            };

            var bookingRequest = new BookHearingRequest
            {
                BookingDetails = hearing
            };

            return(await _controller.Post(bookingRequest));
        }
Exemple #9
0
        public void Should_return_error_messages_with_validation_result_and_booking_request()
        {
            var validationResult = new ValidationResult();

            validationResult.Errors.Add(new ValidationFailure("TestProp", "Test Error Message"));

            var request = new BookNewHearingRequest();
            var result  = HearingControlLogHelper.ErrorMessages(validationResult, request);

            result.Should().NotBeNull();
            result.Count.Should().Be(2);
            result["payload"].Should().Be(JsonConvert.SerializeObject(request));
            result.Keys.First().Should().StartWith("TestProp-");
            result.Keys.First().Length.Should().Be(45);
            result.ContainsValue("Test Error Message").Should().BeTrue();
        }
        public void Should_throw_Exception()
        {
            var hearing = new BookNewHearingRequest
            {
                Participants = new List <BookingsApi.Contract.Requests.ParticipantRequest>()
            };

            var bookingRequest = new BookHearingRequest
            {
                BookingDetails = hearing
            };

            _bookingsApiClient.Setup(x => x.BookNewHearingAsync(It.IsAny <BookNewHearingRequest>()))
            .Throws(new Exception("Some internal error"));

            Assert.ThrowsAsync <Exception>(() => _controller.Post(bookingRequest));
        }
        public void Should_throw_BookingsApiException()
        {
            var hearing = new BookNewHearingRequest
            {
                Participants = new List <BookingsApi.Contract.Requests.ParticipantRequest>()
            };

            var bookingRequest = new BookHearingRequest
            {
                BookingDetails = hearing
            };

            _bookingsApiClient.Setup(x => x.BookNewHearingAsync(It.IsAny <BookNewHearingRequest>()))
            .Throws(ClientException.ForBookingsAPI(HttpStatusCode.InternalServerError));

            Assert.ThrowsAsync <BookingsApiException>(() => _controller.Post(bookingRequest));
        }
        public async Task Should_pass_bad_request_from_bookings_api()
        {
            var hearing = new BookNewHearingRequest
            {
                Participants = new List <BookingsApi.Contract.Requests.ParticipantRequest>()
            };

            var bookingRequest = new BookHearingRequest
            {
                BookingDetails = hearing
            };

            _bookingsApiClient.Setup(x => x.BookNewHearingAsync(It.IsAny <BookNewHearingRequest>()))
            .Throws(ClientException.ForBookingsAPI(HttpStatusCode.BadRequest));

            var result = await _controller.Post(bookingRequest);

            result.Result.Should().BeOfType <BadRequestObjectResult>();
        }
        public async Task Should_update_participant_username_to_aad_email_id()
        {
            var participant = new BookingsApi.Contract.Requests.ParticipantRequest
            {
                Username        = "******",
                CaseRoleName    = "Applicant",
                HearingRoleName = "Representative",
                ContactEmail    = "*****@*****.**"
            };
            var participantList = new List <BookingsApi.Contract.Requests.ParticipantRequest> {
                participant
            };

            const string da        = "*****@*****.**";
            var          endpoints = new EndpointRequest {
                DisplayName = "displayname", DefenceAdvocateUsername = da
            };
            var endpointList = new List <EndpointRequest> {
                endpoints
            };

            var hearing = new BookNewHearingRequest
            {
                Participants = participantList,
                Endpoints    = endpointList
            };

            var bookingRequest = new BookHearingRequest
            {
                BookingDetails = hearing
            };

            // setup response
            var hearingDetailsResponse = HearingResponseBuilder.Build()
                                         .WithParticipant("Representative", participant.Username);

            _bookingsApiClient.Setup(x => x.BookNewHearingAsync(It.IsAny <BookNewHearingRequest>()))
            .ReturnsAsync(hearingDetailsResponse);

            await _controller.Post(bookingRequest);

            _userAccountService.Verify(x => x.GetAdUserIdForUsername(participant.Username), Times.Once);
        }
Exemple #14
0
        public void Should_return_error_messages_with_booking_request()
        {
            var request = new BookNewHearingRequest
            {
                ScheduledDateTime = DateTime.Now,
                ScheduledDuration = 30,
                CaseTypeName      = "TestCaseTypeName",
                HearingTypeName   = "TestHearingTypeName"
            };
            var result = HearingControlLogHelper.ErrorMessages(request);

            result.Should().NotBeNull();
            result.Count.Should().Be(5);
            result["payload"].Should().Be(JsonConvert.SerializeObject(request));
            result["ScheduledDateTime"].Should().Be(request.ScheduledDateTime.ToString("s"));
            result["ScheduledDuration"].Should().Be(request.ScheduledDuration.ToString());
            result["CaseTypeName"].Should().Be(request.CaseTypeName);
            result["HearingTypeName"].Should().Be(request.HearingTypeName);
        }
Exemple #15
0
 public BookHearingRequestBuilder(string usernameStem)
 {
     _randomNumber = new Random();
     _usernameStem = usernameStem;
     _request      = new BookNewHearingRequest
     {
         AudioRecordingRequired = HearingData.AUDIO_RECORDING_REQUIRED,
         CaseTypeName           = HearingData.CASE_TYPE_NAME,
         CreatedBy                = EmailData.NON_EXISTENT_USERNAME,
         Endpoints                = new List <EndpointRequest>(),
         HearingRoomName          = HearingData.HEARING_ROOM_NAME,
         HearingTypeName          = HearingData.HEARING_TYPE_NAME,
         HearingVenueName         = HearingData.VENUE_NAME,
         OtherInformation         = HearingData.OTHER_INFORMATION,
         QuestionnaireNotRequired = HearingData.QUESTIONNAIRE_NOT_REQUIRED,
         ScheduledDateTime        = DateTime.UtcNow.AddMinutes(5),
         ScheduledDuration        = HearingData.SCHEDULED_DURATION
     };
 }
        public static CreateVideoHearingCommand Map(
            BookNewHearingRequest request,
            CaseType caseType,
            HearingType hearingType,
            HearingVenue venue,
            List <Case> cases,
            IRandomGenerator randomGenerator,
            string sipAddressStem)
        {
            var newParticipants    = MapParticipants(request, caseType);
            var newEndpoints       = MapEndpoints(request, randomGenerator, sipAddressStem);
            var linkedParticipants = MapLinkedParticipants(request);

            return(new CreateVideoHearingCommand(caseType, hearingType,
                                                 request.ScheduledDateTime, request.ScheduledDuration, venue, newParticipants, cases,
                                                 request.QuestionnaireNotRequired, request.AudioRecordingRequired, newEndpoints, linkedParticipants)
            {
                HearingRoomName = request.HearingRoomName,
                OtherInformation = request.OtherInformation,
                CreatedBy = request.CreatedBy
            });
        }
 public HearingDetailsResponseBuilder(BookNewHearingRequest request)
 {
     _request = request;
 }
Exemple #18
0
        public CreateHearingRequestBuilder(string caseName)
        {
            var participants = Builder <ParticipantRequest> .CreateListOfSize(5).All()
                               .With(x => x.Title            = "Mrs")
                               .With(x => x.FirstName        = $"Automation_{Faker.Name.First()}")
                               .With(x => x.LastName         = $"Automation_{Faker.Name.Last()}")
                               .With(x => x.ContactEmail     = $"Automation_{Faker.Internet.Email()}")
                               .With(x => x.TelephoneNumber  = Faker.Phone.Number())
                               .With(x => x.Username         = $"Automation_{Faker.Internet.Email()}")
                               .With(x => x.DisplayName      = $"Automation_{Faker.Name.FullName()}")
                               .With(x => x.OrganisationName = $"{Faker.Company.Name()}")
                               .With(x => x.HouseNumber      = $"{Faker.RandomNumber.Next(0, 999)}")
                               .With(x => x.Street           = $"{Faker.Address.StreetName()}")
                               .With(x => x.Postcode         = $"{Faker.Address.UkPostCode()}")
                               .With(x => x.City             = $"{Faker.Address.City()}")
                               .With(x => x.County           = $"{Faker.Address.UkCounty()}")
                               .Build().ToList();

            participants[0].CaseRoleName    = "Claimant";
            participants[0].HearingRoleName = "Claimant LIP";
            participants[0].Reference       = participants[1].DisplayName;
            participants[0].Representee     = null;

            participants[1].CaseRoleName    = "Claimant";
            participants[1].HearingRoleName = "Representative";
            participants[1].Reference       = null;
            participants[1].Representee     = participants[0].DisplayName;

            participants[2].CaseRoleName    = "Defendant";
            participants[2].HearingRoleName = "Defendant LIP";
            participants[2].Reference       = participants[3].DisplayName;
            participants[2].Representee     = null;

            participants[3].CaseRoleName    = "Defendant";
            participants[3].HearingRoleName = "Representative";
            participants[2].Reference       = null;
            participants[3].Representee     = participants[2].DisplayName;

            participants[4].CaseRoleName    = "Judge";
            participants[4].HearingRoleName = "Judge";
            participants[4].Reference       = null;
            participants[4].Representee     = null;

            var cases = Builder <CaseRequest> .CreateListOfSize(1).Build().ToList();

            cases[0].IsLeadCase = false;
            cases[0].Name       = $"{caseName} {Faker.RandomNumber.Next(0, 9999999)}";
            cases[0].Number     = $"{Faker.RandomNumber.Next(0, 9999)}/{Faker.RandomNumber.Next(0, 9999)}";

            const string createdBy = "*****@*****.**";

            _request = Builder <BookNewHearingRequest> .CreateNew()
                       .With(x => x.CaseTypeName             = "Civil Money Claims")
                       .With(x => x.HearingTypeName          = "Application to Set Judgment Aside")
                       .With(x => x.HearingVenueName         = "Birmingham Civil and Family Justice Centre")
                       .With(x => x.ScheduledDateTime        = DateTime.Today.ToUniversalTime().AddDays(1).AddMinutes(-1))
                       .With(x => x.ScheduledDuration        = 5)
                       .With(x => x.Participants             = participants)
                       .With(x => x.Cases                    = cases)
                       .With(x => x.CreatedBy                = createdBy)
                       .With(x => x.QuestionnaireNotRequired = false)
                       .With(x => x.AudioRecordingRequired   = true)
                       .Build();
        }
Exemple #19
0
        private void InitHearingForTest()
        {
            // request with existing person, new user, existing user in AD but not in persons table
            _bookNewHearingRequest = new BookNewHearingRequest
            {
                Participants = new List <BookingsApi.Contract.Requests.ParticipantRequest>
                {
                    new BookingsApi.Contract.Requests.ParticipantRequest
                    {
                        CaseRoleName     = "CaseRole", ContactEmail = "*****@*****.**",
                        HearingRoleName  = "HearingRole", DisplayName = "display name1",
                        FirstName        = "fname", MiddleNames = "", LastName = "lname1", Username = "******",
                        OrganisationName = "", Representee = "", TelephoneNumber = ""
                    },
                    new BookingsApi.Contract.Requests.ParticipantRequest
                    {
                        CaseRoleName    = "CaseRole", ContactEmail = "*****@*****.**",
                        HearingRoleName = "HearingRole", DisplayName = "display name2",
                        FirstName       = "fname2", MiddleNames = "", LastName = "lname2", OrganisationName = "",
                        Representee     = "", TelephoneNumber = ""
                    },
                    new BookingsApi.Contract.Requests.ParticipantRequest
                    {
                        CaseRoleName    = "CaseRole", ContactEmail = "*****@*****.**",
                        HearingRoleName = "HearingRole", DisplayName = "display name3",
                        FirstName       = "fname3", MiddleNames = "", LastName = "lname3", OrganisationName = "",
                        Representee     = "", TelephoneNumber = ""
                    },
                    new BookingsApi.Contract.Requests.ParticipantRequest
                    {
                        CaseRoleName    = "Panel Member", ContactEmail = "*****@*****.**",
                        HearingRoleName = "HearingRole", DisplayName = "display name4",
                        FirstName       = "fname4", MiddleNames = "", LastName = "lname4", OrganisationName = "",
                        Representee     = "", TelephoneNumber = ""
                    },
                    new BookingsApi.Contract.Requests.ParticipantRequest
                    {
                        CaseRoleName    = "Judge", ContactEmail = "*****@*****.**",
                        HearingRoleName = "Judge", DisplayName = "Judge Fudge",
                        FirstName       = "Jack", MiddleNames = "", LastName = "Fudge",
                        Username        = "******", OrganisationName = "", Representee = "",
                        TelephoneNumber = ""
                    }
                },
                Endpoints = new List <EndpointRequest>
                {
                    new EndpointRequest
                    {
                        DisplayName = "displayname1", DefenceAdvocateUsername = "******"
                    },
                    new EndpointRequest
                    {
                        DisplayName = "displayname2", DefenceAdvocateUsername = "******"
                    },
                }
            };

            foreach (var participant in _bookNewHearingRequest.Participants.Where(x =>
                                                                                  !string.IsNullOrWhiteSpace(x.Username)))
            {
                var profile = new UserProfile
                {
                    UserId    = Guid.NewGuid().ToString(),
                    UserName  = participant.Username,
                    FirstName = participant.FirstName,
                    LastName  = participant.LastName
                };
                _userApiClient.Setup(x => x.GetUserByAdUserIdAsync(It.Is <string>(e => e == participant.Username)))
                .ReturnsAsync(profile);
            }

            foreach (var participant in _bookNewHearingRequest.Participants.Where(x =>
                                                                                  string.IsNullOrWhiteSpace(x.Username)))
            {
                var newUser = new NewUserResponse()
                {
                    UserId          = Guid.NewGuid().ToString(),
                    Username        = $"{participant.FirstName}.{participant.LastName}@hmcts.net",
                    OneTimePassword = "******"
                };
                _userApiClient
                .Setup(x => x.CreateUserAsync(It.Is <CreateUserRequest>(userRequest =>
                                                                        userRequest.RecoveryEmail == participant.ContactEmail))).ReturnsAsync(newUser);
            }

            var existingPat3 = _bookNewHearingRequest.Participants.Single(x => x.ContactEmail == "*****@*****.**");

            var existingUser3 = new UserProfile()
            {
                UserId      = Guid.NewGuid().ToString(),
                UserName    = $"{existingPat3.FirstName}.{existingPat3.LastName}@hmcts.net",
                Email       = existingPat3.ContactEmail,
                FirstName   = existingPat3.FirstName,
                LastName    = existingPat3.LastName,
                DisplayName = existingPat3.DisplayName,
            };

            _userApiClient
            .Setup(x => x.GetUserByEmailAsync(existingPat3.ContactEmail)).ReturnsAsync(existingUser3);

            _pollyRetryServiceMock.Setup(x => x.WaitAndRetryAsync <Exception, Task>
                                         (
                                             It.IsAny <int>(), It.IsAny <Func <int, TimeSpan> >(), It.IsAny <Action <int> >(),
                                             It.IsAny <Func <Task, bool> >(), It.IsAny <Func <Task <Task> > >()
                                         ))
            .Callback(async(int retries, Func <int, TimeSpan> sleepDuration, Action <int> retryAction,
                            Func <Task, bool> handleResultCondition, Func <Task> executeFunction) =>
            {
                sleepDuration(1);
                retryAction(1);
                handleResultCondition(Task.CompletedTask);
                await executeFunction();
            })
            .ReturnsAsync(Task.CompletedTask);
        }
Exemple #20
0
        public CreateHearingRequestBuilder(string caseName)
        {
            var participants = Builder <ParticipantRequest> .CreateListOfSize(5).All()
                               .With(x => x.Title            = "Mrs")
                               .With(x => x.FirstName        = $"Automation_{Faker.Name.First()}")
                               .With(x => x.LastName         = $"Automation_{Faker.Name.Last()}")
                               .With(x => x.ContactEmail     = $"Automation_{Faker.RandomNumber.Next()}@hmcts.net")
                               .With(x => x.TelephoneNumber  = Faker.Phone.Number())
                               .With(x => x.Username         = $"Automation_{Faker.RandomNumber.Next()}@hmcts.net")
                               .With(x => x.DisplayName      = $"Automation_{Faker.Name.FullName()}")
                               .With(x => x.OrganisationName = $"{Faker.Company.Name()}")
                               .Build().ToList();

            participants[0].CaseRoleName    = "Applicant";
            participants[0].HearingRoleName = "Litigant in person";
            participants[0].Representee     = null;

            participants[1].CaseRoleName    = "Applicant";
            participants[1].HearingRoleName = "Representative";
            participants[1].Representee     = participants[0].DisplayName;

            participants[2].CaseRoleName    = "Respondent";
            participants[2].HearingRoleName = "Litigant in person";
            participants[2].Representee     = null;

            participants[3].CaseRoleName    = "Respondent";
            participants[3].HearingRoleName = "Representative";
            participants[3].Representee     = participants[2].DisplayName;

            participants[4].CaseRoleName    = "Judge";
            participants[4].HearingRoleName = "Judge";
            participants[4].Representee     = null;

            var cases = Builder <CaseRequest> .CreateListOfSize(1).Build().ToList();

            cases[0].IsLeadCase = false;
            cases[0].Name       = $"{caseName} {Faker.RandomNumber.Next(0, 9999999)}";
            cases[0].Number     = $"{Faker.RandomNumber.Next(0, 9999)}/{Faker.RandomNumber.Next(0, 9999)}";

            var endpoints = Builder <EndpointRequest> .CreateListOfSize(3)
                            .All()
                            .Build().ToList();

            const string createdBy = "*****@*****.**";

            _request = Builder <BookNewHearingRequest> .CreateNew()
                       .With(x => x.CaseTypeName             = "Generic")
                       .With(x => x.HearingTypeName          = "Automated Test")
                       .With(x => x.HearingVenueName         = "Birmingham Civil and Family Justice Centre")
                       .With(x => x.ScheduledDateTime        = DateTime.Today.ToUniversalTime().AddDays(1).AddMinutes(-1))
                       .With(x => x.ScheduledDuration        = 5)
                       .With(x => x.Participants             = participants)
                       .With(x => x.Endpoints                = endpoints)
                       .With(x => x.Cases                    = cases)
                       .With(x => x.CreatedBy                = createdBy)
                       .With(x => x.QuestionnaireNotRequired = false)
                       .With(x => x.AudioRecordingRequired   = true)
                       .With(x => x.Endpoints                = new List <EndpointRequest> {
                new EndpointRequest {
                    DisplayName = "New Endpoint"
                }
            })
                       .Build();
        }
        public static Dictionary <string, string> ErrorMessages(ValidationResult result, BookNewHearingRequest request)
        {
            var dictionary = result.Errors.ToDictionary(x => $"{x.PropertyName}-{Guid.NewGuid()}", x => x.ErrorMessage);

            dictionary.Add("payload", JsonConvert.SerializeObject(request));
            return(dictionary);
        }
Exemple #22
0
        public async Task <IActionResult> BookNewHearing(BookNewHearingRequest request)
        {
            var result = new BookNewHearingRequestValidation().Validate(request);

            if (!result.IsValid)
            {
                ModelState.AddFluentValidationErrors(result.Errors);
                return(BadRequest(ModelState));
            }

            var query    = new GetCaseTypeQuery(request.CaseTypeName);
            var caseType = await _queryHandler.Handle <GetCaseTypeQuery, CaseType>(query);


            if (caseType == null)
            {
                ModelState.AddModelError(nameof(request.CaseTypeName), "Case type does not exist");
                return(BadRequest(ModelState));
            }

            var individualRoles = caseType.CaseRoles.SelectMany(x => x.HearingRoles).Where(x => x.UserRole.IsIndividual).Select(x => x.Name).ToList();

            var addressValidationResult = AddressValidationHelper.ValidateAddress(individualRoles, request.Participants);

            if (!addressValidationResult.IsValid)
            {
                ModelState.AddFluentValidationErrors(addressValidationResult.Errors);
                return(BadRequest(ModelState));
            }

            var hearingType = caseType.HearingTypes.SingleOrDefault(x => x.Name == request.HearingTypeName);

            if (hearingType == null)
            {
                ModelState.AddModelError(nameof(request.HearingTypeName), "Hearing type does not exist");
                return(BadRequest(ModelState));
            }

            var venue = await GetVenue(request.HearingVenueName);

            if (venue == null)
            {
                ModelState.AddModelError(nameof(request.HearingVenueName), "Hearing venue does not exist");
                return(BadRequest(ModelState));
            }

            var mapper          = new ParticipantRequestToNewParticipantMapper();
            var newParticipants = request.Participants.Select(x => mapper.MapRequestToNewParticipant(x, caseType))
                                  .ToList();

            var cases = request.Cases.Select(x => new Case(x.Number, x.Name)).ToList();

            var createVideoHearingCommand = new CreateVideoHearingCommand(caseType, hearingType,
                                                                          request.ScheduledDateTime, request.ScheduledDuration, venue, newParticipants, cases,
                                                                          request.QuestionnaireNotRequired, request.AudioRecordingRequired)
            {
                HearingRoomName  = request.HearingRoomName,
                OtherInformation = request.OtherInformation,
                CreatedBy        = request.CreatedBy
            };

            await _commandHandler.Handle(createVideoHearingCommand);

            var videoHearingId = createVideoHearingCommand.NewHearingId;

            var getHearingByIdQuery = new GetHearingByIdQuery(videoHearingId);

            var queriedVideoHearing = await _queryHandler.Handle <GetHearingByIdQuery, VideoHearing>(getHearingByIdQuery);

            var hearingMapper = new HearingToDetailResponseMapper();
            var response      = hearingMapper.MapHearingToDetailedResponse(queriedVideoHearing);

            return(CreatedAtAction(nameof(GetHearingDetailsById), new { hearingId = response.Id }, response));
        }
        public async Task Should_create_a_hearing_with_LinkedParticipants()
        {
            // request.
            var newHearingRequest = new BookNewHearingRequest()
            {
                Participants = new List <BookingsApi.Contract.Requests.ParticipantRequest>
                {
                    new BookingsApi.Contract.Requests.ParticipantRequest {
                        CaseRoleName     = "CaseRole", ContactEmail = "*****@*****.**",
                        DisplayName      = "firstName1 lastName1", FirstName = "firstName1", HearingRoleName = "Litigant in person", LastName = "lastName1", MiddleNames = "",
                        OrganisationName = "", Representee = "", TelephoneNumber = "1234567890", Title = "Mr.", Username = "******"
                    },
                    new BookingsApi.Contract.Requests.ParticipantRequest {
                        CaseRoleName     = "CaseRole", ContactEmail = "*****@*****.**",
                        DisplayName      = "firstName2 lastName2", FirstName = "firstName2", HearingRoleName = "Interpreter", LastName = "lastName2", MiddleNames = "",
                        OrganisationName = "", Representee = "", TelephoneNumber = "1234567890", Title = "Mr.", Username = "******"
                    },
                },
                LinkedParticipants = new List <LinkedParticipantRequest>
                {
                    new LinkedParticipantRequest {
                        ParticipantContactEmail       = "*****@*****.**",
                        LinkedParticipantContactEmail = "*****@*****.**", Type = LinkedParticipantType.Interpreter
                    },
                    new LinkedParticipantRequest {
                        ParticipantContactEmail       = "*****@*****.**",
                        LinkedParticipantContactEmail = "*****@*****.**", Type = LinkedParticipantType.Interpreter
                    }
                }
            };
            var bookingRequest = new BookHearingRequest
            {
                BookingDetails = newHearingRequest
            };
            // set response.
            var linkedParticipant1 = new List <LinkedParticipantResponse>()
            {
                new LinkedParticipantResponse()
                {
                    LinkedId = Guid.NewGuid(), Type = LinkedParticipantType.Interpreter
                }
            };
            var participant1 = Builder <ParticipantResponse> .CreateNew().With(x => x.Id = Guid.NewGuid())
                               .With(x => x.UserRoleName       = "Individual").With(x => x.Username = "******")
                               .With(x => x.LinkedParticipants = linkedParticipant1)
                               .Build();

            var linkedParticipant2 = new List <LinkedParticipantResponse>()
            {
                new LinkedParticipantResponse()
                {
                    LinkedId = Guid.NewGuid(), Type = LinkedParticipantType.Interpreter
                }
            };
            var participant2 = Builder <ParticipantResponse> .CreateNew().With(x => x.Id = Guid.NewGuid())
                               .With(x => x.UserRoleName       = "Individual").With(x => x.Username = "******")
                               .With(x => x.LinkedParticipants = linkedParticipant2)
                               .Build();

            var hearingDetailsResponse = Builder <HearingDetailsResponse> .CreateNew()
                                         .With(x => x.Cases        = Builder <CaseResponse> .CreateListOfSize(2).Build().ToList())
                                         .With(x => x.Endpoints    = Builder <EndpointResponse> .CreateListOfSize(2).Build().ToList())
                                         .With(x => x.Participants = new List <ParticipantResponse> {
                participant1, participant2
            }).Build();

            _bookingsApiClient.Setup(x => x.BookNewHearingAsync(newHearingRequest))
            .ReturnsAsync(hearingDetailsResponse);
            var result = await _controller.Post(bookingRequest);

            result.Result.Should().BeOfType <CreatedResult>();
            var createdObjectResult = (CreatedResult)result.Result;

            createdObjectResult.StatusCode.Should().Be(201);
        }
        public async Task <IActionResult> BookNewHearing(BookNewHearingRequest request)
        {
            try
            {
                if (request == null)
                {
                    const string modelErrorMessage    = "BookNewHearingRequest is null";
                    const string logModelErrorMessage = "BookNewHearing Error: BookNewHearingRequest is null";

                    return(ModelStateErrorLogger(nameof(BookNewHearingRequest), modelErrorMessage, logModelErrorMessage,
                                                 null, SeverityLevel.Information));
                }

                var result = await new BookNewHearingRequestValidation().ValidateAsync(request);
                if (!result.IsValid)
                {
                    const string logBookNewHearingValidationError = "BookNewHearing Validation Errors";
                    const string emptyPayLoadErrorMessage         = "Empty Payload";
                    const string keyPayload = "payload";

                    ModelState.AddFluentValidationErrors(result.Errors);
                    var dictionary = result.Errors.ToDictionary(x => x.PropertyName + "-" + Guid.NewGuid(), x => x.ErrorMessage);
                    var payload    = JsonConvert.SerializeObject(request);
                    dictionary.Add(keyPayload, !string.IsNullOrWhiteSpace(payload) ? payload : emptyPayLoadErrorMessage);
                    _logger.TrackTrace(logBookNewHearingValidationError, SeverityLevel.Error, dictionary);
                    return(BadRequest(ModelState));
                }

                var query    = new GetCaseTypeQuery(request.CaseTypeName);
                var caseType = await _queryHandler.Handle <GetCaseTypeQuery, CaseType>(query);

                if (caseType == null)
                {
                    const string logCaseDoesNotExist = "BookNewHearing Error: Case type does not exist";
                    return(ModelStateErrorLogger(nameof(request.CaseTypeName),
                                                 "Case type does not exist", logCaseDoesNotExist, request.CaseTypeName, SeverityLevel.Error));
                }

                var hearingType = caseType.HearingTypes.SingleOrDefault(x => x.Name == request.HearingTypeName);
                if (hearingType == null)
                {
                    const string logHearingTypeDoesNotExist = "BookNewHearing Error: Hearing type does not exist";
                    return(ModelStateErrorLogger(nameof(request.HearingTypeName),
                                                 "Hearing type does not exist", logHearingTypeDoesNotExist, request.HearingTypeName, SeverityLevel.Error));
                }

                var venue = await GetVenue(request.HearingVenueName);

                if (venue == null)
                {
                    const string logHearingVenueDoesNotExist = "BookNewHearing Error: Hearing venue does not exist";

                    return(ModelStateErrorLogger(nameof(request.HearingVenueName),
                                                 "Hearing venue does not exist", logHearingVenueDoesNotExist, request.HearingVenueName, SeverityLevel.Error));
                }

                var          cases       = request.Cases.Select(x => new Case(x.Number, x.Name)).ToList();
                const string logHasCases = "BookNewHearing got cases";
                const string keyCases    = "Cases";
                _logger.TrackTrace(logHasCases, SeverityLevel.Information, new Dictionary <string, string>
                {
                    { keyCases, string.Join(", ", cases.Select(x => new { x.Name, x.Number })) }
                });

                var createVideoHearingCommand = BookNewHearingRequestToCreateVideoHearingCommandMapper.Map(
                    request, caseType, hearingType, venue, cases, _randomGenerator, _kinlyConfiguration.SipAddressStem);

                const string logCallingDb    = "BookNewHearing Calling DB...";
                const string dbCommand       = "createVideoHearingCommand";
                const string logSaveSuccess  = "BookNewHearing DB Save Success";
                const string logNewHearingId = "NewHearingId";

                _logger.TrackTrace(logCallingDb, SeverityLevel.Information, new Dictionary <string, string> {
                    { dbCommand, JsonConvert.SerializeObject(createVideoHearingCommand) }
                });
                await _commandHandler.Handle(createVideoHearingCommand);

                _logger.TrackTrace(logSaveSuccess, SeverityLevel.Information, new Dictionary <string, string> {
                    { logNewHearingId, createVideoHearingCommand.NewHearingId.ToString() }
                });

                var videoHearingId = createVideoHearingCommand.NewHearingId;

                var getHearingByIdQuery = new GetHearingByIdQuery(videoHearingId);
                var queriedVideoHearing = await _queryHandler.Handle <GetHearingByIdQuery, VideoHearing>(getHearingByIdQuery);

                const string logRetrieveNewHearing = "BookNewHearing Retrieved new hearing from DB";
                const string keyHearingId          = "HearingId";
                const string keyCaseType           = "CaseType";
                const string keyParticipantCount   = "Participants.Count";
                _logger.TrackTrace(logRetrieveNewHearing, SeverityLevel.Information, new Dictionary <string, string>
                {
                    { keyHearingId, queriedVideoHearing.Id.ToString() },
                    { keyCaseType, queriedVideoHearing.CaseType?.Name },
                    { keyParticipantCount, queriedVideoHearing.Participants.Count.ToString() },
                });

                var          hearingMapper      = new HearingToDetailsResponseMapper();
                var          response           = hearingMapper.MapHearingToDetailedResponse(queriedVideoHearing);
                const string logProcessFinished = "BookNewHearing Finished, returning response";
                _logger.TrackTrace(logProcessFinished, SeverityLevel.Information, new Dictionary <string, string> {
                    { "response", JsonConvert.SerializeObject(response) }
                });
                return(CreatedAtAction(nameof(GetHearingDetailsById), new { hearingId = response.Id }, response));
            }
            catch (Exception ex)
            {
                const string keyPayload           = "payload";
                const string keyScheduledDateTime = "ScheduledDateTime";
                const string keyScheduledDuration = "ScheduledDuration";
                const string keyCaseTypeName      = "CaseTypeName";
                const string keyHearingTypeName   = "HearingTypeName";

                if (request != null)
                {
                    var payload = JsonConvert.SerializeObject(request);
                    _logger.TrackError(ex, new Dictionary <string, string>
                    {
                        { keyPayload, !string.IsNullOrWhiteSpace(payload) ? payload : "Empty Payload" },
                        { keyScheduledDateTime, request.ScheduledDateTime.ToString("s") },
                        { keyScheduledDuration, request.ScheduledDuration.ToString() },
                        { keyCaseTypeName, request.CaseTypeName },
                        { keyHearingTypeName, request.HearingTypeName }
                    });
                }

                throw;
            }
        }