public void TestTransformAffiliationsFirstProviderTypeFacility()
        {
            VitalsProviderSearch sourceData =
                new VitalsProviderSearch {
                providers = new List <Provider> {
                    new Provider()
                }
            };

            sourceData.providers[0].type      = "F";
            sourceData.providers[0].locations = new List <Location> {
                new Location()
            };
            sourceData.providers[0].locations[0].contracts = new List <Contract> {
                new Contract()
            };
            sourceData.providers[0].locations[0].contracts[0].hospital_affiliations =
                new List <HospitalAffiliation> {
                new HospitalAffiliation()
                {
                    name = "foo"
                }
            };

            ProviderSearchResults result = Mapper.Transform(sourceData);

            result.providers[0].affiliations[0].Should().Be("foo");
        }
Exemple #2
0
        private async Task <int> DetermineTotalCountFromSearch()
        {
            ProviderSearchResults providers = await SearchProviders(new SearchModel
            {
                PageNumber    = 1,
                Top           = 1,
                IncludeFacets = false
            });

            return(providers.TotalCount);
        }
        public void ShouldMapVitalsToProviderResultsForPages()
        {
            //arrange

            //act
            ProviderSearchResults result = Mapper.Transform(_sourceData);

            //assert
            _sourceData._meta.pages.total.Should().Be(result.pages.total);
            _sourceData._meta.pages.current.Should().Be(result.pages.current);
        }
        async Task <int> GetTotalCount()
        {
            ProviderSearchResults providers = await SearchProviders(new SearchModel
            {
                PageNumber    = 1,
                Top           = 1,
                IncludeFacets = false
            });

            return(providers.TotalCount);
        }
Exemple #5
0
        private async Task <IEnumerable <ProviderSummary> > FetchProviderSummariesFromSearch(int pageNumber, int top = 50)
        {
            ProviderSearchResults providers = await SearchProviders(new SearchModel
            {
                PageNumber    = pageNumber,
                Top           = top,
                IncludeFacets = false,
                OrderBy       = new string[] { "name", "authority" },
            });

            return(_mapper.Map <IEnumerable <ProviderSummary> >(providers.Results));
        }
        public void TestTransformEmptyAddressForFirstProviderTypeP()
        {
            VitalsProviderSearch sourceData = new VitalsProviderSearch();

            sourceData.providers = new List <Provider> {
                new Provider()
            };
            sourceData.providers[0].type = "P";

            ProviderSearchResults result = Mapper.Transform(sourceData);

            result.providers[0].address.Should().BeNull();
        }
        public async Task ShouldReturnResultOfSearch()
        {
            var providerStandardSearchResults = new ProviderSearchResults();

            _mockSearchService.Setup(x => x.SearchProviders(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Pagination>(), It.IsAny <IEnumerable <string> >(), It.IsAny <bool>(), It.IsAny <bool>(), 0)).Returns(Task.FromResult(providerStandardSearchResults));
            var message = new ProviderSearchQuery {
                ApprenticeshipId = "1", PostCode = "GU21 6DB", Page = 0
            };

            var response = await _handler.Handle(message, default(CancellationToken));

            response.Results.Should().BeSameAs(providerStandardSearchResults);
        }
        private static ProviderSearchResults GetProviderSearchResultErrorResponse(string apprenticeshipId, string Title, string postCode, string responseCode)
        {
            var errorResponse = new ProviderSearchResults
            {
                TotalResults     = 0,
                ApprenticeshipId = apprenticeshipId,
                Title            = Title,
                PostCode         = postCode,
                Hits             = new ProviderSearchResultItem[0],
                ResponseCode     = responseCode
            };

            return(errorResponse);
        }
        public async Task ShouldSignalFailureWhenApprenticeshipIsNotFound()
        {
            var providerStandardSearchResults = new ProviderSearchResults {
                ResponseCode = ProviderSearchResponseCodes.ApprenticeshipNotFound.ToString()
            };

            _mockSearchService.Setup(x => x.SearchProviders(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Pagination>(), It.IsAny <IEnumerable <string> >(), It.IsAny <bool>(), It.IsAny <bool>(), 0)).Returns(Task.FromResult(providerStandardSearchResults));
            var message = new ProviderSearchQuery {
                ApprenticeshipId = "1", PostCode = "GU21 6DB", Page = 0
            };

            var response = await _handler.Handle(message, default(CancellationToken));

            response.Success.Should().BeFalse();
            response.StatusCode.ShouldBeEquivalentTo(ProviderSearchResponseCodes.ApprenticeshipNotFound);
        }
        /// <summary>
        /// Creates the ui friendly class from the results.
        /// </summary>
        /// <param name="output">The results of the search.</param>
        /// <returns>A class containing the results</returns>
        private ProviderSearchResults CreateProviderSearchResults(ProviderSearchOutput output)
        {
            ProviderSearchResults results = new ProviderSearchResults();

            if (output != null &&
                output.ProviderSearchResponse != null &&
                output.ProviderSearchResponse.ProviderDetails != null)
            {
                foreach (ProviderStructure course in output.ProviderSearchResponse.ProviderDetails)
                {
                    results.Add(CreateResult(course));
                }
            }

            return(results);
        }
        public async Task ShouldReturnLastPageIfCurrentPageExtendsUpperBound()
        {
            _mockPaginationSettings.Setup(x => x.DefaultResultsAmount).Returns(10);
            var providerStandardSearchResults = new ProviderSearchResults()
            {
                TotalResults = 42, Hits = new List <ProviderSearchResultItem>()
            };

            _mockSearchService.Setup(x => x.SearchProviders(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Pagination>(), It.IsAny <IEnumerable <string> >(), It.IsAny <bool>(), It.IsAny <bool>(), 0)).Returns(Task.FromResult(providerStandardSearchResults));

            var message = new ProviderSearchQuery {
                ApprenticeshipId = "1", PostCode = "GU21 6DB", Page = 8
            };

            var response = await _handler.Handle(message, default(CancellationToken));

            response.CurrentPage.Should().Be(5);
            response.StatusCode.ShouldBeEquivalentTo(ProviderSearchResponseCodes.PageNumberOutOfUpperBound);
        }
Exemple #12
0
        public void TestTransformAddressForFirstProviderTypeP()
        {
            VitalsProviderSearch sourceData = new VitalsProviderSearch();

            sourceData.providers = new List <Provider> {
                new Provider()
            };
            sourceData.providers[0].type      = "P";
            sourceData.providers[0].locations = new List <Location> {
                new Location(), new Location(), new Location()
            };
            sourceData.providers[0].locations[0].address = new Address()
            {
                addr_line1 = "123 main st"
            };
            ProviderSearchResults result = Mapper.Transform(sourceData);

            result.providers[0].address.addr_line1.Should().Be("123 main st");
        }
Exemple #13
0
        public void ShouldMapVitalsToProviderResultsForSecondProvider()
        {
            //arrange

            //act
            ProviderSearchResults result = Mapper.Transform(_sourceData);

            //assert
            result.providers.Should().NotBeNull();
            result.providers.Count.Should().Be(2);

            MapperRefactor.DataBags.Results.Provider provider = result.providers[1];
            provider.id.Should().Be(1007346793);
            provider.name.Should().Be("Erica K Kass");
            provider.gender.Should().Be("F");
            provider.degrees.Count.Should().Be(1);
            provider.degrees[0].Should().Be("MD");
            provider.languages.Count.Should().Be(0);
            Address addr =
                new Address
            {
                addr_line1   = "3959 Broadway",
                addr_line2   = null,
                city         = "New York",
                state_code   = "NY",
                sub_national = null,
                county       = "New York",
                country_code = null,
                postal_code  = "10032",
                latitude     = 40.839768,
                longitude    = -73.941483
            };

            provider.address.ShouldBeEquivalentTo(addr);
            provider.phone_number.Should().Be("2123055437");
            provider.affiliations.Count.Should().Be(0);
            provider.specialties.Count.Should().Be(2);
            provider.specialties.Count.Should().Be(2);
            provider.specialties[0].Should().Be("Neurologist");
            provider.specialties[1].Should().Be("Psychiatrist");
            provider.awards.Count.Should().Be(0);
        }
Exemple #14
0
        public void ShouldMapVitalsToProviderResultsForFirstProvider()
        {
            //arrange

            //act
            ProviderSearchResults result = Mapper.Transform(_sourceData);

            //assert
            result.providers.Should().NotBeNull();
            result.providers.Count.Should().Be(2);
            MapperRefactor.DataBags.Results.Provider provider = result.providers[0];
            provider.id.Should().Be(1007346649);
            provider.name.Should().Be("Deana Marie Gazzola");
            provider.gender.Should().Be("F");
            provider.degrees.Count.Should().Be(1);
            provider.degrees[0].Should().Be("MD");
            provider.languages.Count.Should().Be(0);
            Address addr =
                new Address
            {
                addr_line1   = "223 E 34th St",
                addr_line2   = null,
                city         = "New York",
                state_code   = "NY",
                sub_national = null,
                county       = "New York",
                country_code = null,
                postal_code  = "10016",
                latitude     = 40.745324,
                longitude    = -73.976885
            };

            provider.address.ShouldBeEquivalentTo(addr);
            provider.phone_number.Should().Be("2122638710");
            provider.affiliations.Count.Should().Be(2);
            provider.affiliations[0].Should().Be("NYU Langone Medical Center");
            provider.affiliations[1].Should().Be("Hospital for Joint Diseases Orthopedic Institute");
            provider.specialties.Count.Should().Be(2);
            provider.specialties[0].Should().Be("Psychiatrist Pro");
            provider.specialties[1].Should().Be("Neurologist Pro");
            provider.awards.Count.Should().Be(0);
        }
        public void Setup()
        {
            _mockSearchService      = new Mock <IProviderSearchService>();
            _mockPostcodeIoService  = new Mock <IPostcodeService>();
            _mockLogger             = new Mock <ILog>();
            _mockPaginationSettings = new Mock <IPaginationSettings>();

            var providerSearchResults = new ProviderSearchResults
            {
                ResponseCode = LocationLookupResponse.Ok
            };

            _mockSearchService.Setup(x => x.SearchProviders(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Pagination>(), It.IsAny <IEnumerable <string> >(), It.IsAny <bool>(), It.IsAny <bool>(), 0)).Returns(Task.FromResult(providerSearchResults));

            _handler = new ProviderSearchHandler(
                new ProviderSearchQueryValidator(new Validation()),
                _mockSearchService.Object,
                _mockPaginationSettings.Object,
                _mockPostcodeIoService.Object,
                _mockLogger.Object);
        }
        async Task <IEnumerable <ProviderSummary> > GetProviderSummaries(int pageNumber, int top = 50)
        {
            ProviderSearchResults providers = await SearchProviders(new SearchModel
            {
                PageNumber    = pageNumber,
                Top           = top,
                IncludeFacets = false
            });

            IEnumerable <ProviderSearchResult> searchResults = providers.Results;

            return(searchResults.Select(x => new ProviderSummary
            {
                Name = x.Name,
                Id = x.ProviderProfileId,
                ProviderProfileIdType = x.ProviderProfileIdType,
                UKPRN = x.UKPRN,
                URN = x.URN,
                Authority = x.Authority,
                UPIN = x.UPIN,
                ProviderSubType = x.ProviderSubType,
                EstablishmentNumber = x.EstablishmentNumber,
                ProviderType = x.ProviderType,
                DateOpened = x.OpenDate,
                DateClosed = x.CloseDate,
                LACode = x.LACode,
                CrmAccountId = x.CrmAccountId,
                LegalName = x.LegalName,
                NavVendorNo = x.NavVendorNo,
                DfeEstablishmentNumber = x.DfeEstablishmentNumber,
                Status = x.Status,
                PhaseOfEducation = x.PhaseOfEducation,
                ReasonEstablishmentClosed = x.ReasonEstablishmentClosed,
                ReasonEstablishmentOpened = x.ReasonEstablishmentOpened,
                Successor = x.Successor,
                TrustStatus = x.TrustStatus,
                TrustName = x.TrustName,
                TrustCode = x.TrustCode
            }));
        }
Exemple #17
0
        public void TestTransformLanguagesForFirstProvider()
        {
            VitalsProviderSearch sourceData =
                new VitalsProviderSearch {
                providers = new List <Provider> {
                    new Provider()
                }
            };

            sourceData.providers[0].languages = new List <Language> {
                new Language {
                    name = "Esperanto"
                }, new Language {
                    name = "Catalan"
                }
            };

            ProviderSearchResults result = Mapper.Transform(sourceData);

            result.providers[0].languages[0].Should().Be("Esperanto");
            result.providers[0].languages[1].Should().Be("Catalan");
        }
        /// <summary>
        /// Gets the data and displays on screen if we have any.
        /// </summary>
        /// <param name="criteria"></param>
        private void PopulateData(SearchCriteriaStructure criteria)
        {
            try
            {
                // fire the web service to get some results
                ProviderSearchOutput  output  = GetResults(criteria);
                ProviderSearchResults results = CreateProviderSearchResults(output);

                if (results.Count() > 0)
                {
                    ResultsOverviewLabel.Text    = "No of records: " + results.Count;
                    RepeaterContainer.DataSource = results; // pagedDS;
                    RepeaterContainer.DataBind();
                }
                else
                {
                    ResultsOverviewLabel.Text = "There are no results to display.";
                }
            }
            catch (Exception ex)
            {
                ResultsOverviewLabel.Text = ex.Message + "/n/n" + ex.StackTrace;
            }
        }
        async public Task <IActionResult> SearchProviders(HttpRequest request)
        {
            string json = await request.GetRawBodyStringAsync();

            SearchModel searchModel = JsonConvert.DeserializeObject <SearchModel>(json);

            if (searchModel == null || searchModel.PageNumber < 1 || searchModel.Top < 1)
            {
                _logger.Error("A null or invalid search model was provided for searching providers");

                return(new BadRequestObjectResult("An invalid search model was provided"));
            }

            IEnumerable <Task <SearchResults <ProviderIndex> > > searchTasks = BuildSearchTasks(searchModel);

            try
            {
                await TaskHelper.WhenAllAndThrow(searchTasks.ToArraySafe());

                ProviderSearchResults providerSearchResults = new ProviderSearchResults();


                foreach (Task <SearchResults <ProviderIndex> > searchTask in searchTasks)
                {
                    ProcessSearchResults(searchTask.Result, searchModel, providerSearchResults);
                }

                return(new OkObjectResult(providerSearchResults));
            }
            catch (FailedToQuerySearchException exception)
            {
                _logger.Error(exception, $"Failed to query search with term: {searchModel.SearchTerm}");

                return(new StatusCodeResult(500));
            }
        }
        void ProcessSearchResults(SearchResults <ProviderIndex> searchResult, SearchModel searchModel, ProviderSearchResults results)
        {
            if (!searchResult.Facets.IsNullOrEmpty())
            {
                results.Facets = results.Facets.Concat(searchResult.Facets);
            }
            else
            {
                results.TotalCount = (int)(searchResult?.TotalCount ?? 0);

                if (!searchModel.CountOnly)
                {
                    results.Results = searchResult?.Results?.Select(m => new ProviderSearchResult
                    {
                        UKPRN                     = m.Result.UKPRN,
                        URN                       = m.Result.URN,
                        UPIN                      = m.Result.UPIN,
                        Rid                       = m.Result.Rid,
                        ProviderId                = m.Result.ProviderId,
                        EstablishmentNumber       = m.Result.EstablishmentNumber,
                        Name                      = m.Result.Name,
                        Authority                 = m.Result.Authority,
                        ProviderType              = m.Result.ProviderType,
                        ProviderSubType           = m.Result.ProviderSubType,
                        OpenDate                  = m.Result.OpenDate,
                        CloseDate                 = m.Result.CloseDate,
                        ProviderProfileId         = m.Result.ProviderId,
                        NavVendorNo               = m.Result.NavVendorNo,
                        CrmAccountId              = m.Result.CrmAccountId,
                        LegalName                 = m.Result.LegalName,
                        LACode                    = m.Result.LACode,
                        ProviderProfileIdType     = m.Result.ProviderIdType,
                        Status                    = m.Result.Status,
                        DfeEstablishmentNumber    = m.Result.DfeEstablishmentNumber,
                        PhaseOfEducation          = m.Result.PhaseOfEducation,
                        ReasonEstablishmentClosed = m.Result.ReasonEstablishmentClosed,
                        ReasonEstablishmentOpened = m.Result.ReasonEstablishmentOpened,
                        Successor                 = m.Result.Successor
                    });
                }
            }
        }
Exemple #21
0
 public void TestTransformEmptyVitalsSearch()
 {
     VitalsProviderSearch  sourceData = new VitalsProviderSearch();
     ProviderSearchResults result     = Mapper.Transform(sourceData);
 }
Exemple #22
0
 public void ShouldDeserializeProviderResultsFromVitals()
 {
     string jsonRaw = File.ReadAllText(@"..\..\Refactor - Mapper\testData.json");
     VitalsProviderSearch  vitalsProviderSearch = JsonConvert.DeserializeObject <VitalsProviderSearch>(jsonRaw);
     ProviderSearchResults result = Mapper.Transform(vitalsProviderSearch);
 }
Exemple #23
0
 public void ShouldNotThrowGivenEmptyJsonString()
 {
     VitalsProviderSearch  vitalsProviderSearch = JsonConvert.DeserializeObject <VitalsProviderSearch>("");
     ProviderSearchResults result = Mapper.Transform(vitalsProviderSearch);
 }
        public void ShouldFullyPopulateTheMappedViewModel()
        {
            var mapper = new MappingService(null);

            var trainingLocations = new List <TrainingLocation> {
                new TrainingLocation {
                    LocationId = 1, LocationName = "Location1", Address = new Address {
                        Postcode = "N17"
                    }
                }
            };

            var results = new ProviderSearchResults
            {
                TrainingOptionsAggregation = new Dictionary <string, long?>
                {
                    ["dayrelease"]   = 10,
                    ["blockrelease"] = 2
                },
                SelectedTrainingOptions = new List <string> {
                    "dayrelease"
                },
                Hits = new List <ProviderSearchResultItem>
                {
                    new ProviderSearchResultItem {
                        LocationId = 1, LocationName = "Location1", Address = new Address {
                            Postcode = "N17"
                        }, OverallAchievementRate = 42.5
                    },
                    new ProviderSearchResultItem {
                        LocationId = 1, LocationName = "Location1", Address = new Address {
                            Postcode = "N17"
                        }
                    },
                    new ProviderSearchResultItem {
                        LocationId = 1, LocationName = "Location1", Address = new Address {
                            Postcode = "N17"
                        }
                    }
                },
                TotalResults     = 105,
                ResultsToTake    = 10,
                PostCode         = "GU21 6DB",
                PostCodeMissing  = true,
                ApprenticeshipId = "1234",
                Title            = "Test Name"
            };

            var source = new ProviderSearchResponse
            {
                Success                = false,
                CurrentPage            = 2,
                Results                = results,
                SearchTerms            = "a b c",
                ShowAllProviders       = true,
                TotalResultsForCountry = 1000,
                StatusCode             = ProviderSearchResponseCodes.ApprenticeshipNotFound
            };

            var viewModel = mapper.Map <ProviderSearchResponse, ProviderStandardSearchResultViewModel>(source);

            viewModel.ActualPage.Should().Be(2);
            viewModel.DeliveryModes.Count().Should().Be(2);
            viewModel.DeliveryModes.Count(x => x.Checked).Should().Be(1);
            viewModel.Hits.Count().Should().Be(3);
            viewModel.LastPage.Should().Be(11);
            viewModel.SearchTerms.Should().Be("a b c");
            viewModel.PostCode.Should().Be("GU21 6DB");
            viewModel.PostCodeMissing.Should().BeTrue();
            viewModel.ResultsToTake.Should().Be(10);
            viewModel.ShowAll.Should().BeTrue();
            viewModel.StandardId.Should().Be("1234");
            viewModel.StandardName.Should().Be("Test Name");
            viewModel.TotalResultsForCountry.Should().Be(1000);
            viewModel.TotalResults.Should().Be(105);
            viewModel.HasError.Should().BeTrue();
            viewModel.Hits.First().LocationId.Should().Be(1);
            viewModel.Hits.First().LocationName.Should().Be("Location1");
            viewModel.Hits.First().Address.Postcode.Should().Be("N17");
            viewModel.Hits.First().AchievementRateMessage.Should().Be("42.5%");
            viewModel.Hits.ElementAt(2).AchievementRateMessage.Should().Be("no data available");
        }
        public async Task <ProviderSearchResults> SearchProviders(string apprenticeshipId, string postCode, Pagination pagination, IEnumerable <string> deliveryModes, bool hasNonLevyContract, bool showNationalOnly, int orderBy = 0)
        {
            if (string.IsNullOrEmpty(postCode))
            {
                return(new ProviderSearchResults {
                    ApprenticeshipId = apprenticeshipId, PostCodeMissing = true
                });
            }

            int apprenticeshipIdInt;

            IApprenticeshipProduct apprenticeship;

            if (int.TryParse(apprenticeshipId, out apprenticeshipIdInt))
            {
                apprenticeship = _getStandards.GetStandardById(apprenticeshipId);
            }
            else
            {
                apprenticeship = _getFrameworks.GetFrameworkById(apprenticeshipId);
            }

            if (apprenticeship == null)
            {
                return(GetProviderSearchResultErrorResponse(apprenticeshipId, null, postCode, LocationLookupResponse.ApprenticeshipNotFound));
            }

            try
            {
                var coordinateResponse = await _postCodeLookup.GetLatLongFromPostCode(postCode);

                var coordinates = coordinateResponse.Coordinate;


                if (coordinateResponse.ResponseCode != LocationLookupResponse.Ok)
                {
                    return(GetProviderSearchResultErrorResponse(apprenticeshipId, apprenticeship?.Title, postCode, coordinateResponse.ResponseCode));
                }

                var takeElements = pagination.Take == 0 ? _paginationSettings.DefaultResultsAmount : pagination.Take;

                LogSearchRequest(postCode, coordinates);

                var filter = new ProviderSearchFilter
                {
                    DeliveryModes      = deliveryModes,
                    HasNonLevyContract = hasNonLevyContract,
                    ShowNationalOnly   = showNationalOnly
                };

                var searchResults = await _providerSearchProvider.SearchProvidersByLocation(apprenticeshipId, coordinates, pagination.Page, takeElements, filter, orderBy);

                var result = new ProviderSearchResults
                {
                    TotalResults               = searchResults.Total,
                    ResultsToTake              = takeElements,
                    ApprenticeshipId           = apprenticeshipId,
                    Title                      = apprenticeship?.Title,
                    Level                      = apprenticeship.Level,
                    PostCode                   = postCode,
                    TrainingOptionsAggregation = searchResults.TrainingOptionsAggregation,
                    NationalProviders          = searchResults.NationalProvidersAggregation,
                    SelectedTrainingOptions    = deliveryModes,
                    ResponseCode               = LocationLookupResponse.Ok,
                    ShowNationalProvidersOnly  = false,
                    Hits     = searchResults.Hits,
                    LastPage = takeElements > 0 ? (int)System.Math.Ceiling((double)searchResults.Total / takeElements) : 1
                };

                return(result);
            }
            catch (SearchException ex)
            {
                _logger.Error(ex, "Search for provider failed.");

                return(GetProviderSearchResultErrorResponse(apprenticeshipId, apprenticeship?.Title, postCode, ServerLookupResponse.InternalServerError));
            }
        }
Exemple #26
0
        public static ProviderSearchResults Transform(VitalsProviderSearch sourceData)
        {
            ProviderSearchResults newResult = new ProviderSearchResults();

            if (sourceData?._meta?.pages != null)
            {
                newResult.pages.total   = sourceData._meta.pages.total;
                newResult.pages.current = sourceData._meta.pages.current;
            }

            if (sourceData?.providers == null)
            {
                return(newResult);
            }
            foreach (var sourceProvider in sourceData.providers)
            {
                MapperRefactor.DataBags.Results.Address sourceProviderFirstLocationAddress = null;
                string phoneNumber = null;

                if (sourceProvider.locations != null && sourceProvider.locations.Count > 0)
                {
                    sourceProviderFirstLocationAddress              = new MapperRefactor.DataBags.Results.Address();
                    sourceProviderFirstLocationAddress.addr_line1   = sourceProvider.locations[0].address?.addr_line1;
                    sourceProviderFirstLocationAddress.addr_line2   = sourceProvider.locations[0].address?.addr_line2;
                    sourceProviderFirstLocationAddress.city         = sourceProvider.locations[0].address?.city;
                    sourceProviderFirstLocationAddress.state_code   = sourceProvider.locations[0].address?.state_code;
                    sourceProviderFirstLocationAddress.sub_national = sourceProvider.locations[0].address?.sub_national;
                    sourceProviderFirstLocationAddress.county       = sourceProvider.locations[0].address?.county;
                    sourceProviderFirstLocationAddress.country_code = sourceProvider.locations[0].address?.country_code;
                    sourceProviderFirstLocationAddress.postal_code  = sourceProvider.locations[0].address?.postal_code;
                    sourceProviderFirstLocationAddress.latitude     = sourceProvider.locations[0].address?.latitude;
                    sourceProviderFirstLocationAddress.longitude    = sourceProvider.locations[0].address?.longitude;

                    phoneNumber = sourceProvider.locations?[0]?.phones?.voice?[0]?.number;
                }

                var provider = new MapperRefactor.DataBags.Results.Provider();
                provider.id           = sourceProvider.id;
                provider.name         = sourceProvider.name;
                provider.gender       = sourceProvider.gender;
                provider.degrees      = new List <string>();
                provider.languages    = new List <string>();
                provider.address      = sourceProviderFirstLocationAddress;
                provider.phone_number = phoneNumber;
                provider.affiliations = new List <string>();
                provider.specialties  = new List <string>();
                provider.awards       = new List <string>();

                if (sourceProvider.degrees != null)
                {
                    foreach (var degree in sourceProvider.degrees)
                    {
                        provider.degrees.Add(degree);
                    }
                }

                if (sourceProvider.languages != null)
                {
                    foreach (var lang in sourceProvider.languages)
                    {
                        provider.languages.Add(lang.name);
                    }
                }

                if (sourceProvider.locations != null)
                {
                    Location location = sourceProvider.locations.FirstOrDefault();

                    if (location?.contracts != null && location.contracts.Count > 0 && location.contracts[0].hospital_affiliations != null)
                    {
                        foreach (var affiliation in location.contracts[0].hospital_affiliations)
                        {
                            provider.affiliations.Add(affiliation.name);
                        }
                    }

                    if (sourceProvider.type == "F")
                    {
                        if (location != null)
                        {
                            if (location.contracts?[0].specializations != null)
                            {
                                foreach (var specialization in location.contracts[0].specializations)
                                {
                                    if (specialization.field_specialty != null)
                                    {
                                        provider.specialties.Add(specialization.field_specialty.name);
                                    }
                                }
                            }

                            if (sourceProvider.bdc?.bdtc != null)
                            {
                                foreach (var award in location.bdc.bdtc)
                                {
                                    if (award != null)
                                    {
                                        provider.awards.Add(award.name);
                                    }
                                }
                            }
                        }
                    }
                }

                if (sourceProvider.type == "P")
                {
                    if (sourceProvider.specializations != null)
                    {
                        foreach (var specialization in sourceProvider.specializations)
                        {
                            if (specialization.field_specialty != null)
                            {
                                provider.specialties.Add(specialization.field_specialty.name);
                            }
                        }
                    }

                    if (sourceProvider.bdc?.bdtc != null)
                    {
                        foreach (var award in sourceProvider.bdc.bdtc)
                        {
                            if (award != null)
                            {
                                provider.awards.Add(award.name);
                            }
                        }
                    }
                }

                newResult.providers.Add(provider);
            }

            return(newResult);
        }