public async Task Then_Total_Apprentices_Available_Will_Be_Return_For_Employer_When_Getting_All_Results(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext)
        {
            //Arrange
            searchParameters.PageNumber    = 0;
            searchParameters.PageItemCount = 2;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();

            var apprenticeships = GetTestApprenticeshipsWithAlerts(searchParameters);

            apprenticeships[0].Cohort.EmployerAccountId = 0;
            apprenticeships[0].EmployerRef = null;
            searchParameters.ProviderId    = null;

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var service = new ApprenticeshipSearchService(mockContext.Object);

            //Act
            var actual = await service.Find(searchParameters);

            //Assert
            Assert.AreEqual(5, actual.TotalAvailableApprenticeships);
        }
        public async Task Then_Apprentices_Are_Return_Per_Page(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext)
        {
            //Arrange
            searchParameters.PageNumber    = 2;
            searchParameters.PageItemCount = 2;
            searchParameters.ReverseSort   = false;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();

            var apprenticeships = GetTestApprenticeshipsWithAlerts(searchParameters);

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var service = new ApprenticeshipSearchService(mockContext.Object);

            //Act
            var actual = await service.Find(searchParameters);

            //Assert
            Assert.AreEqual(2, actual.Apprenticeships.Count());
            Assert.AreEqual("C", actual.Apprenticeships.ElementAt(0).FirstName);
            Assert.AreEqual("D", actual.Apprenticeships.ElementAt(1).FirstName);
        }
        public async Task Then_Downloads_Are_Restricted_To_Twelve_Months_for_Default_Search(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext)
        {
            //Arrange
            searchParameters.PageNumber        = 0;
            searchParameters.ReverseSort       = false;
            searchParameters.Filters           = new ApprenticeshipSearchFilters();
            searchParameters.CancellationToken = CancellationToken.None;
            searchParameters.EmployerAccountId = null;


            var apprenticeships = GetTestApprenticeshipsWithAlerts(searchParameters);

            apprenticeships[1].ProviderRef = null;
            apprenticeships[1].EndDate     = DateTime.UtcNow.AddMonths(-13);;

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var service = new ApprenticeshipSearchService(mockContext.Object);

            //Act
            var actual = await service.Find(searchParameters);

            //Assert
            Assert.AreEqual(apprenticeships.Count - 1, actual.Apprenticeships.Count());
            Assert.IsFalse(actual.Apprenticeships.Contains(apprenticeships[1]));
        }
        public async Task Then_Returns_Employer_Apprenticeships(
            ApprenticeshipSearchParameters searchParameters,
            List <Apprenticeship> apprenticeships,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext,
            ApprenticeshipSearchService service)
        {
            searchParameters.PageNumber    = 1;
            searchParameters.PageItemCount = 10;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();
            searchParameters.ProviderId    = null;

            apprenticeships[0].Cohort.EmployerAccountId = searchParameters.EmployerAccountId.Value;
            apprenticeships[1].Cohort.EmployerAccountId = searchParameters.EmployerAccountId.Value;

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var expectedApprenticeships =
                apprenticeships.Where(app => app.Cohort.EmployerAccountId == searchParameters.EmployerAccountId);

            var result = await service.Find(searchParameters);

            result.Apprenticeships.Count()
            .Should().Be(apprenticeships
                         .Count(apprenticeship => apprenticeship.Cohort.EmployerAccountId == searchParameters.EmployerAccountId));

            result.Apprenticeships.Should().BeEquivalentTo(expectedApprenticeships);
        }
        public async Task Then_Will_Return_Page_Number_If_All_Apprenticeships_Are_With_Alerts(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext)
        {
            //Arrange
            searchParameters.ReverseSort   = false;
            searchParameters.PageNumber    = 2;
            searchParameters.PageItemCount = 2;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();

            var apprenticeships = GetTestApprenticeshipsWithAlerts(searchParameters);

            searchParameters.ProviderId = null;

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var service = new ApprenticeshipSearchService(mockContext.Object);

            //Act
            var actual = await service.Find(searchParameters);

            //Assert
            Assert.AreEqual(searchParameters.PageNumber, actual.PageNumber);
            Assert.IsNotEmpty(actual.Apprenticeships);
        }
Beispiel #6
0
        public async Task Then_Will_Not_Search_For_Apprenticeships_That_Will_Be_Skipped(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext,
            [Frozen] Mock <IMapper <Apprenticeship, GetApprenticeshipsQueryResult.ApprenticeshipDetails> > mockMapper,
            ApprenticeshipSearchService service)
        {
            searchParameters.PageNumber    = 2;
            searchParameters.PageItemCount = 3;
            searchParameters.ReverseSort   = false;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();

            var apprenticeships = GetTestApprenticeshipsWithAlerts(searchParameters);

            AssignProviderToApprenticeships(searchParameters.ProviderId ?? 0, apprenticeships);

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            await service.Find(searchParameters);

            mockContext.Verify(context => context.Apprenticeships, Times.Exactly(4));

            mockMapper.Verify(x => x.Map(It.Is <Apprenticeship>(app => app.DataLockStatus.Any())), Times.Never);
        }
Beispiel #7
0
 public ApprenticeshipSearchViewModel(ApprenticeshipSearchParameters searchParameters) : base(searchParameters)
 {
     Keywords            = searchParameters.Keywords;
     LocationType        = searchParameters.VacancyLocationType;
     ApprenticeshipLevel = searchParameters.ApprenticeshipLevel;
     Category            = searchParameters.CategoryCode;
     SubCategories       = searchParameters.SubCategoryCodes;
     SearchMode          = string.IsNullOrWhiteSpace(searchParameters.CategoryCode) ? ApprenticeshipSearchMode.Keyword : ApprenticeshipSearchMode.Category;
     SearchField         = searchParameters.SearchField.ToString();
     LocationSearches    = Enumerable.Empty <ApprenticeshipSearchViewModel>();
 }
        public SearchResults <ApprenticeshipSearchResponse, ApprenticeshipSearchParameters> GetSuggestedApprenticeshipVacancies(
            ApprenticeshipSearchParameters searchParameters,
            IList <ApprenticeshipApplicationSummary> candidateApplications,
            int vacancyId)
        {
            var vacancy            = _vacancyDataProvider.GetVacancyDetails(vacancyId);
            var vacancySubCategory = _referenceDataService.GetSubCategoryByName(vacancy.SubCategory);

            if (vacancySubCategory == null)
            {
                return(null);
            }

            searchParameters.CategoryCode     = vacancySubCategory.ParentCategoryCodeName;
            searchParameters.SubCategoryCodes = new[] { vacancySubCategory.CodeName };

            var excludeVacancyIds = candidateApplications.Select(x => x.LegacyVacancyId).ToList();

            excludeVacancyIds.Add(vacancyId);
            searchParameters.ExcludeVacancyIds = excludeVacancyIds;

            if (searchParameters.Location != null)
            {
                if (searchParameters.Location.GeoPoint == null || (searchParameters.Location.GeoPoint.Latitude == 0 && searchParameters.Location.GeoPoint.Longitude == 0))
                {
                    var locations = _locationSearchService.FindLocation(searchParameters.Location.Name);
                    searchParameters.Location = locations != null?locations.FirstOrDefault() : null;
                }
            }

            if (searchParameters.Location == null)
            {
                searchParameters.Location = new Location
                {
                    Name     = vacancy.VacancyAddress.Postcode,
                    GeoPoint = new GeoPoint
                    {
                        Latitude  = vacancy.VacancyAddress.GeoPoint.Latitude,
                        Longitude = vacancy.VacancyAddress.GeoPoint.Longitude,
                    }
                };
            }

            var searchResults = _searchService.Search(searchParameters);

            if (searchResults.Total == 0)
            {
                //Widen search to category alone
                searchParameters.SubCategoryCodes = null;
                searchResults = _searchService.Search(searchParameters);
            }

            return(searchResults);
        }
 protected VacancySearchViewModel(ApprenticeshipSearchParameters searchParameters)
 {
     Location       = searchParameters.Location != null ? searchParameters.Location.Name : string.Empty;
     Longitude      = searchParameters.Location != null && searchParameters.Location.GeoPoint != null ? searchParameters.Location.GeoPoint.Longitude : 0;
     Latitude       = searchParameters.Location != null && searchParameters.Location.GeoPoint != null ? searchParameters.Location.GeoPoint.Latitude : 0;
     WithinDistance = searchParameters.SearchRadius;
     PageNumber     = searchParameters.PageNumber;
     SortType       = searchParameters.SortType;
     ResultsPerPage = searchParameters.PageSize;
     SearchAction   = SearchAction.Search;
 }
        public static ApprenticeshipSearchParameters Create(SavedSearch savedSearch)
        {
            ApprenticeshipSearchField searchField;

            if (!Enum.TryParse(savedSearch.SearchField, out searchField))
            {
                searchField = ApprenticeshipSearchField.All;
            }

            var location = new Location {
                Name = savedSearch.Location
            };

            if (savedSearch.HasGeoPoint())
            {
                location.GeoPoint = new GeoPoint
                {
                    // ReSharper disable PossibleInvalidOperationException HasGeoPoint() checks for this
                    Latitude  = savedSearch.Latitude.Value,
                    Longitude = savedSearch.Longitude.Value
                                // ReSharper restore PossibleInvalidOperationException
                };
            }

            var parameters = new ApprenticeshipSearchParameters
            {
                PageNumber = 1,
                PageSize   = 5,

                Location            = location,
                SearchRadius        = savedSearch.WithinDistance,
                SortType            = VacancySearchSortType.RecentlyAdded,
                ApprenticeshipLevel = savedSearch.ApprenticeshipLevel,

                VacancyLocationType = ApprenticeshipLocationType.NonNational,
                SearchField         = searchField
            };

            switch (savedSearch.SearchMode)
            {
            case ApprenticeshipSearchMode.Keyword:
                parameters.Keywords = savedSearch.Keywords;
                break;

            case ApprenticeshipSearchMode.Category:
                parameters.CategoryCode     = savedSearch.Category;
                parameters.SubCategoryCodes = savedSearch.SubCategories;
                parameters.SearchField      = ApprenticeshipSearchField.All;
                break;
            }

            return(parameters);
        }
Beispiel #11
0
        public void Then_Returns_All_Apprenticeships_If_No_Provider_Or_Employer_Id_Found(
            ApprenticeshipSearchParameters searchParameters,
            List <Apprenticeship> apprenticeships)
        {
            searchParameters.PageNumber        = 0;
            searchParameters.PageItemCount     = 0;
            searchParameters.Filters           = new ApprenticeshipSearchFilters();
            searchParameters.ProviderId        = null;
            searchParameters.EmployerAccountId = null;

            var result = apprenticeships.AsQueryable().WithProviderOrEmployerId(searchParameters);

            result.Should().BeEquivalentTo(apprenticeships);
        }
        public void Run()
        {
            var parameters = new ApprenticeshipSearchParameters
            {
                Keywords = string.Empty,
                Location = new Location {
                    GeoPoint = new GeoPoint()
                },
                PageNumber          = 1,
                PageSize            = 10,
                SearchRadius        = 10,
                SortType            = VacancySearchSortType.Distance,
                VacancyLocationType = ApprenticeshipLocationType.National
            };

            _vacancySearchProvider.FindVacancies(parameters);
        }
Beispiel #13
0
        private WhatHappensNextApprenticeshipViewModel WhatHappensNextSuggestions(WhatHappensNextApprenticeshipViewModel whatHappensNextViewModel, Guid candidateId, int vacancyId, string searchReturnUrl)
        {
            var searchReturnViewModel = ApprenticeshipSearchViewModel.FromSearchUrl(searchReturnUrl) ?? new ApprenticeshipSearchViewModel {
                WithinDistance = 40, ResultsPerPage = 5, PageNumber = 1
            };
            var searchLocation = _apprenticeshipCandidateWebMappers.Map <ApprenticeshipSearchViewModel, Location>(searchReturnViewModel);

            var searchParameters = new ApprenticeshipSearchParameters
            {
                VacancyLocationType = ApprenticeshipLocationType.NonNational,
                ApprenticeshipLevel = searchReturnViewModel.ApprenticeshipLevel,
                SortType            = VacancySearchSortType.Distance,
                Location            = searchLocation,
                PageNumber          = 1,
                PageSize            = searchReturnViewModel.ResultsPerPage,
                SearchRadius        = searchReturnViewModel.WithinDistance
            };

            var suggestedVacancies = _candidateService.GetSuggestedApprenticeshipVacancies(searchParameters, candidateId, vacancyId);

            if (suggestedVacancies == null)
            {
                return(whatHappensNextViewModel);
            }

            var searchedCategory = (suggestedVacancies.SearchParameters.SubCategoryCodes != null && suggestedVacancies.SearchParameters.SubCategoryCodes.Length == 1
                ? _referenceDataService.GetSubCategoryByCode(suggestedVacancies.SearchParameters.SubCategoryCodes[0])
                : _referenceDataService.GetCategoryByCode(suggestedVacancies.SearchParameters.CategoryCode)) ?? Category.InvalidSectorSubjectAreaTier1;

            whatHappensNextViewModel.SuggestedVacanciesSearchViewModel = new ApprenticeshipSearchViewModel(suggestedVacancies.SearchParameters);
            whatHappensNextViewModel.SuggestedVacanciesCategory        = searchedCategory.FullName;
            whatHappensNextViewModel.SuggestedVacanciesSearchDistance  = suggestedVacancies.SearchParameters.SearchRadius;
            whatHappensNextViewModel.SuggestedVacanciesSearchLocation  = suggestedVacancies.SearchParameters.Location.Name;
            whatHappensNextViewModel.SuggestedVacancies =
                suggestedVacancies.Results.Select(x => new SuggestedVacancyViewModel
            {
                VacancyId    = x.Id,
                VacancyTitle = x.Title,
                IsPositiveAboutDisability = x.IsPositiveAboutDisability,
                Distance = Math.Round(x.Distance, 1, MidpointRounding.AwayFromZero).ToString(CultureInfo.InvariantCulture)
            }).ToList();

            return(whatHappensNextViewModel);
        }
Beispiel #14
0
        public SearchResponse Search(SearchRequest request)
        {
            var searchFactorConfiguration = new SearchFactorConfiguration
            {
                DescriptionFactors = GetFactorsFromRequest(SearchFactorKeys.Description, request),
                EmployerFactors    = GetFactorsFromRequest(SearchFactorKeys.Employer, request),
                JobTitleFactors    = GetFactorsFromRequest(SearchFactorKeys.JobTitle, request),
                ProviderFactors    = GetFactorsFromRequest(SearchFactorKeys.Provider, request)
            };

            var configurationService = new VacancySearchConfigurationService(
                _configurationService, searchFactorConfiguration);

            var elasticsearchClientFactory = new ElasticsearchClientFactory(
                configurationService, _logService);

            var searchProvider = new ApprenticeshipsSearchProvider(
                elasticsearchClientFactory, _mapper, configurationService, _logService);

            var parameters = new ApprenticeshipSearchParameters
            {
                PageNumber  = 1,
                PageSize    = 50,
                SearchField = GetSearchFieldFromRequest(request),
                Keywords    = request.SearchTerms,
                SortType    = VacancySearchSortType.Relevancy
            };

            var indexDate  = new DateTime(2020, 01, 01, 12, 00, 00);
            var indexAlias = elasticsearchClientFactory.GetIndexNameForType(typeof(ApprenticeshipSummary));
            var indexName  = string.Format("{0}.{1}", indexAlias, indexDate.ToUniversalTime().ToString("yyyy-MM-dd-HH"));

            var vacancies = searchProvider.FindVacancies(parameters, indexName);

            return(new SearchResponse
            {
                Request = request,
                SearchResults = vacancies.Results.ToArray(),
                Total = vacancies.Total,
                SearchFactorConfiguration = configurationService.Get <SearchFactorConfiguration>(),
                Parameters = parameters
            });
        }
        public async Task Then_Returns_Apprenticeships_Total_Found(
            ApprenticeshipSearchParameters searchParameters,
            List <Apprenticeship> apprenticeships,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext,
            ApprenticeshipSearchService service)
        {
            searchParameters.PageNumber    = 1;
            searchParameters.PageItemCount = 10;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();

            apprenticeships[0].Cohort.ProviderId = searchParameters.ProviderId ?? 0;
            apprenticeships[1].Cohort.ProviderId = searchParameters.ProviderId ?? 0;
            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var result = await service.Find(searchParameters);

            result.TotalApprenticeshipsFound
            .Should().Be(apprenticeships
                         .Count(apprenticeship => apprenticeship.Cohort.ProviderId == searchParameters.ProviderId));
        }
        public async Task ThenWillGetSearchHandler(
            [Frozen] Mock <IApprenticeshipSearchService <ApprenticeshipSearchParameters> > service,
            [Frozen] Mock <IServiceProvider> serviceProvider,
            ApprenticeshipSearchParameters searchParameters,
            ApprenticeshipSearch search)
        {
            //Arrange
            var expectedResult = new ApprenticeshipSearchResult();

            serviceProvider.Setup(x =>
                                  x.GetService(It.IsAny <Type>()))
            .Returns(service.Object);

            service.Setup(x => x.Find(searchParameters))
            .ReturnsAsync(expectedResult);

            //Act
            var result = await search.Find(searchParameters);

            //Assert
            Assert.AreEqual(expectedResult, result);
        }
        public async Task Then_Apprentices_With_Alerts_Total_Found_Are_Return_With_Page_Data(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext)
        {
            //Arrange
            searchParameters.PageNumber    = 2;
            searchParameters.PageItemCount = 2;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();

            var apprenticeships = GetTestApprenticeshipsWithAlerts(searchParameters);

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var service = new ApprenticeshipSearchService(mockContext.Object);

            //Act
            var actual = await service.Find(searchParameters);

            //Assert
            Assert.AreEqual(3, actual.TotalApprenticeshipsWithAlertsFound);
        }
Beispiel #18
0
        public void Then_Returns_Employer_Apprenticeships(
            ApprenticeshipSearchParameters searchParameters,
            List <Apprenticeship> apprenticeships)
        {
            searchParameters.PageNumber    = 0;
            searchParameters.PageItemCount = 0;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();
            searchParameters.ProviderId    = null;

            apprenticeships[0].Cohort.EmployerAccountId = searchParameters.EmployerAccountId.Value;
            apprenticeships[1].Cohort.EmployerAccountId = searchParameters.EmployerAccountId.Value;

            var expectedApprenticeships =
                apprenticeships.Where(app => app.Cohort.EmployerAccountId == searchParameters.EmployerAccountId);

            var result = apprenticeships.AsQueryable().WithProviderOrEmployerId(searchParameters);

            result.Count()
            .Should().Be(apprenticeships
                         .Count(apprenticeship => apprenticeship.Cohort.EmployerAccountId == searchParameters.EmployerAccountId));

            result.Should().BeEquivalentTo(expectedApprenticeships);
        }
        public void ExecuteSearch(bool alertsEnabled)
        {
            var candidateId          = Guid.NewGuid();
            var candidateSavedSearch = new CandidateSavedSearches {
                CandidateId = candidateId
            };

            var savedSearchReadRepository = new Mock <ISavedSearchReadRepository>();

            savedSearchReadRepository.Setup(r => r.GetForCandidate(candidateId)).Returns(new Fixture().Build <SavedSearch>().With(s => s.AlertsEnabled, alertsEnabled).CreateMany(3).ToList());
            var userReadRepository = new Mock <IUserReadRepository>();

            userReadRepository.Setup(r => r.Get(candidateId)).Returns(new UserBuilder(candidateId).Activated(true).Build);
            var candidateReadRepository = new Mock <ICandidateReadRepository>();

            candidateReadRepository.Setup(r => r.Get(candidateId)).Returns(new CandidateBuilder(candidateId).EnableSavedSearchAlertsViaEmailAndText(true).Build);
            var vacancySearchProvider = new Mock <IVacancySearchProvider <ApprenticeshipSearchResponse, ApprenticeshipSearchParameters> >();
            ApprenticeshipSearchParameters searchParameters = null;

            vacancySearchProvider.Setup(p => p.FindVacancies(It.IsAny <ApprenticeshipSearchParameters>()))
            .Returns(new ApprenticeshipSearchResultsBuilder().WithResultCount(3).Build)
            .Callback <ApprenticeshipSearchParameters>(p => { searchParameters = p; });
            var processor = new SavedSearchProcessorBuilder().With(savedSearchReadRepository).With(userReadRepository).With(candidateReadRepository).With(vacancySearchProvider).Build();

            processor.ProcessCandidateSavedSearches(candidateSavedSearch);

            if (alertsEnabled)
            {
                vacancySearchProvider.Verify(sp => sp.FindVacancies(It.IsAny <ApprenticeshipSearchParameters>()), Times.Exactly(3));
                searchParameters.Should().NotBeNull();
            }
            else
            {
                vacancySearchProvider.Verify(sp => sp.FindVacancies(It.IsAny <ApprenticeshipSearchParameters>()), Times.Never);
                searchParameters.Should().BeNull();
            }
        }
Beispiel #20
0
        public async Task <GetApprenticeshipsQueryResult> Handle(GetApprenticeshipsQuery query, CancellationToken cancellationToken)
        {
            var matchedApprenticeshipDetails = new List <GetApprenticeshipsQueryResult.ApprenticeshipDetails>();

            ApprenticeshipSearchResult searchResult;

            if (string.IsNullOrEmpty(query.SortField) || query.SortField == "DataLockStatus")
            {
                var searchParameters = new ApprenticeshipSearchParameters
                {
                    EmployerAccountId = query.EmployerAccountId,
                    ProviderId        = query.ProviderId,
                    PageNumber        = query.PageNumber,
                    PageItemCount     = query.PageItemCount,
                    ReverseSort       = query.ReverseSort,
                    Filters           = query.SearchFilters,
                    CancellationToken = cancellationToken
                };

                searchResult = await _apprenticeshipSearch.Find(searchParameters);
            }
            else
            {
                if (query.ReverseSort)
                {
                    var searchParameters = new ReverseOrderedApprenticeshipSearchParameters
                    {
                        EmployerAccountId = query.EmployerAccountId,
                        ProviderId        = query.ProviderId,
                        PageNumber        = query.PageNumber,
                        PageItemCount     = query.PageItemCount,
                        ReverseSort       = query.ReverseSort,
                        Filters           = query.SearchFilters,
                        FieldName         = query.SortField,
                        CancellationToken = cancellationToken
                    };

                    searchResult = await _apprenticeshipSearch.Find(searchParameters);
                }
                else
                {
                    var searchParameters = new OrderedApprenticeshipSearchParameters
                    {
                        EmployerAccountId = query.EmployerAccountId,
                        ProviderId        = query.ProviderId,
                        PageNumber        = query.PageNumber,
                        PageItemCount     = query.PageItemCount,
                        ReverseSort       = query.ReverseSort,
                        Filters           = query.SearchFilters,
                        FieldName         = query.SortField,
                        CancellationToken = cancellationToken
                    };

                    searchResult = await _apprenticeshipSearch.Find(searchParameters);
                }
            }
            searchResult.Apprenticeships = searchResult.Apprenticeships
                                           .Select(c => { c.IsProviderSearch = query.ProviderId.HasValue; return(c); })
                                           .ToList();

            foreach (var apprenticeship in searchResult.Apprenticeships)
            {
                var details = await _mapper.Map(apprenticeship);

                matchedApprenticeshipDetails.Add(details);
            }

            return(new GetApprenticeshipsQueryResult
            {
                Apprenticeships = matchedApprenticeshipDetails,
                TotalApprenticeshipsFound = searchResult.TotalApprenticeshipsFound,
                TotalApprenticeshipsWithAlertsFound = searchResult.TotalApprenticeshipsWithAlertsFound,
                TotalApprenticeships = searchResult.TotalAvailableApprenticeships,
                PageNumber = searchResult.PageNumber
            });
        }
        protected static List <Apprenticeship> GetTestApprenticeshipsWithAlerts(ApprenticeshipSearchParameters searchParameters)
        {
            var apprenticeships = new List <Apprenticeship>
            {
                new Apprenticeship
                {
                    FirstName   = "A",
                    LastName    = "Zog",
                    Uln         = "Uln",
                    CourseName  = "Course",
                    StartDate   = DateTime.UtcNow,
                    EndDate     = DateTime.UtcNow.AddMonths(12),
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    EmployerRef = searchParameters.EmployerAccountId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("Employer")
                    },
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>(),
                    DataLockStatus       = new List <DataLockStatus> {
                        new DataLockStatus {
                            IsResolved = false, Status = Status.Fail, EventStatus = EventStatus.New
                        }
                    }
                },
                new Apprenticeship
                {
                    FirstName   = "B",
                    LastName    = "Zog",
                    Uln         = "Uln",
                    CourseName  = "Course",
                    StartDate   = DateTime.UtcNow,
                    EndDate     = DateTime.UtcNow.AddMonths(12),
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    EmployerRef = searchParameters.EmployerAccountId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("Employer")
                    },
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>(),
                    DataLockStatus       = new List <DataLockStatus> {
                        new DataLockStatus {
                            IsResolved = false, Status = Status.Fail, EventStatus = EventStatus.New
                        }
                    }
                },
                new Apprenticeship
                {
                    FirstName   = "C",
                    LastName    = "Zog",
                    Uln         = "Uln",
                    CourseName  = "Course",
                    StartDate   = DateTime.UtcNow,
                    EndDate     = DateTime.UtcNow.AddMonths(12),
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    EmployerRef = searchParameters.EmployerAccountId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("Employer")
                    },
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>(),
                    DataLockStatus       = new List <DataLockStatus> {
                        new DataLockStatus {
                            IsResolved = false, Status = Status.Fail, EventStatus = EventStatus.New
                        }
                    }
                },
                new Apprenticeship
                {
                    FirstName  = "D",
                    LastName   = "Zog",
                    Uln        = "Uln",
                    CourseName = "Course",
                    StartDate  = DateTime.UtcNow,
                    EndDate    = DateTime.UtcNow.AddMonths(12),
                    Cohort     = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("Employer")
                    },
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>(),
                    DataLockStatus       = new List <DataLockStatus>()
                },
                new Apprenticeship
                {
                    FirstName  = "E",
                    LastName   = "Fog",
                    Uln        = "Uln",
                    CourseName = "Course",
                    StartDate  = DateTime.UtcNow,
                    EndDate    = DateTime.UtcNow.AddMonths(12),
                    Cohort     = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("Employer")
                    },
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>(),
                    DataLockStatus       = new List <DataLockStatus>()
                },
                new Apprenticeship
                {
                    FirstName  = "F",
                    LastName   = "Fog",
                    Uln        = "Uln",
                    CourseName = "Course",
                    StartDate  = DateTime.UtcNow,
                    Cohort     = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("Employer")
                    },
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>(),
                    DataLockStatus       = new List <DataLockStatus>()
                }
            };

            if (searchParameters.ProviderId.HasValue)
            {
                AssignProviderToApprenticeships(searchParameters.ProviderId.Value, apprenticeships);
            }

            if (searchParameters.EmployerAccountId.HasValue)
            {
                AssignEmployerToApprenticeships(searchParameters.EmployerAccountId.Value, apprenticeships);
            }


            return(apprenticeships);
        }
        public void FindLocation(bool latLongSpecified, bool locationFound)
        {
            var candidateId          = Guid.NewGuid();
            var candidateSavedSearch = new CandidateSavedSearches {
                CandidateId = candidateId
            };

            var savedSearchReadRepository = new Mock <ISavedSearchReadRepository>();
            List <SavedSearch> savedSearches;

            if (latLongSpecified)
            {
                savedSearches = new Fixture().Build <SavedSearch>().With(s => s.AlertsEnabled, true).CreateMany(3).ToList();
            }
            else
            {
                savedSearches = new Fixture().Build <SavedSearch>()
                                .With(s => s.Latitude, null)
                                .With(s => s.Longitude, null)
                                .With(s => s.AlertsEnabled, true)
                                .CreateMany(3).ToList();
            }
            savedSearchReadRepository.Setup(r => r.GetForCandidate(candidateId)).Returns(savedSearches);
            var userReadRepository = new Mock <IUserReadRepository>();

            userReadRepository.Setup(r => r.Get(candidateId)).Returns(new UserBuilder(candidateId).Activated(true).Build);
            var candidateReadRepository = new Mock <ICandidateReadRepository>();

            candidateReadRepository.Setup(r => r.Get(candidateId)).Returns(new CandidateBuilder(candidateId).EnableSavedSearchAlertsViaEmailAndText(true).Build);
            var locationSearchService = new Mock <ILocationSearchService>();

            if (locationFound)
            {
                locationSearchService.Setup(s => s.FindLocation(It.IsAny <string>())).Returns(new Fixture().Build <Location>().CreateMany(3));
            }
            var vacancySearchProvider = new Mock <IVacancySearchProvider <ApprenticeshipSearchResponse, ApprenticeshipSearchParameters> >();
            ApprenticeshipSearchParameters searchParameters = null;

            vacancySearchProvider.Setup(p => p.FindVacancies(It.IsAny <ApprenticeshipSearchParameters>()))
            .Returns(new ApprenticeshipSearchResultsBuilder().WithResultCount(3).Build)
            .Callback <ApprenticeshipSearchParameters>(p => { searchParameters = p; });
            var savedSearchWriteRepository = new Mock <ISavedSearchWriteRepository>();
            var processor = new SavedSearchProcessorBuilder().With(savedSearchReadRepository).With(userReadRepository).With(candidateReadRepository).With(locationSearchService).With(vacancySearchProvider).With(savedSearchWriteRepository).Build();

            processor.ProcessCandidateSavedSearches(candidateSavedSearch);

            if (latLongSpecified)
            {
                locationSearchService.Verify(l => l.FindLocation(It.IsAny <string>()), Times.Never);
                savedSearchWriteRepository.Verify(p => p.Save(It.IsAny <SavedSearch>()), Times.Exactly(3));
                searchParameters.Should().NotBeNull();
                vacancySearchProvider.Verify(sp => sp.FindVacancies(It.IsAny <ApprenticeshipSearchParameters>()), Times.Exactly(3));
            }
            else
            {
                locationSearchService.Verify(l => l.FindLocation(It.IsAny <string>()), Times.Exactly(3));
                if (locationFound)
                {
                    //One save to update lat/long and one for the new results. 3 searches x 2 = 6
                    savedSearchWriteRepository.Verify(p => p.Save(It.IsAny <SavedSearch>()), Times.Exactly(6));
                    searchParameters.Should().NotBeNull();
                    vacancySearchProvider.Verify(sp => sp.FindVacancies(It.IsAny <ApprenticeshipSearchParameters>()), Times.Exactly(3));
                }
                else
                {
                    savedSearchWriteRepository.Verify(p => p.Save(It.IsAny <SavedSearch>()), Times.Never);
                    searchParameters.Should().BeNull();
                    vacancySearchProvider.Verify(sp => sp.FindVacancies(It.IsAny <ApprenticeshipSearchParameters>()), Times.Never);
                }
            }
        }
        public async Task And_No_Sort_Term_Then_Apprentices_Are_Default_Sorted(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext)
        {
            //Arrange

            searchParameters.ReverseSort       = false;
            searchParameters.PageNumber        = 1;
            searchParameters.PageItemCount     = 10;
            searchParameters.EmployerAccountId = null;

            searchParameters.Filters = new ApprenticeshipSearchFilters();

            var apprenticeships = new List <Apprenticeship>
            {
                new Apprenticeship
                {
                    FirstName   = "XX",
                    LastName    = "XX",
                    Uln         = "Should_Be_Third",
                    CourseName  = "XX",
                    StartDate   = DateTime.UtcNow,
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("XX")
                    },
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>()
                },
                new Apprenticeship
                {
                    FirstName   = "XX",
                    LastName    = "XX",
                    Uln         = "XX",
                    CourseName  = "XX",
                    StartDate   = DateTime.UtcNow.AddMonths(2),
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("XX")
                    },
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>()
                },
                new Apprenticeship
                {
                    FirstName   = "XX",
                    LastName    = "XX",
                    Uln         = "XX",
                    CourseName  = "XX",
                    StartDate   = DateTime.UtcNow,
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("Should_Be_Fourth")
                    },
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>()
                },
                new Apprenticeship
                {
                    FirstName   = "XX",
                    LastName    = "XX",
                    Uln         = "XX",
                    CourseName  = "Should_Be_Fifth",
                    StartDate   = DateTime.UtcNow,
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("XX")
                    },
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>()
                },
                new Apprenticeship
                {
                    FirstName   = "Should_Be_First",
                    LastName    = "XX",
                    Uln         = "XX",
                    CourseName  = "XX",
                    StartDate   = DateTime.UtcNow,
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("XX")
                    },
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>()
                },
                new Apprenticeship
                {
                    FirstName   = "XX",
                    LastName    = "Should_Be_Second",
                    Uln         = "XX",
                    CourseName  = "XX",
                    StartDate   = DateTime.UtcNow,
                    ProviderRef = searchParameters.ProviderId.ToString(),
                    Cohort      = new Cohort {
                        AccountLegalEntity = CreateAccountLegalEntity("XX")
                    },
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>()
                }
            };

            AssignProviderToApprenticeships(searchParameters.ProviderId ?? 0, apprenticeships);

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var service = new ApprenticeshipSearchService(mockContext.Object);

            //Act
            var actual = await service.Find(searchParameters);

            //Assert
            Assert.AreEqual("Should_Be_First", actual.Apprenticeships.ElementAt(0).FirstName);
            Assert.AreEqual("Should_Be_Second", actual.Apprenticeships.ElementAt(1).LastName);
            Assert.AreEqual("Should_Be_Third", actual.Apprenticeships.ElementAt(2).Uln);
            Assert.AreEqual("Should_Be_Fourth", actual.Apprenticeships.ElementAt(3).Cohort.AccountLegalEntity.Name);
            Assert.AreEqual("Should_Be_Fifth", actual.Apprenticeships.ElementAt(4).CourseName);
            Assert.AreEqual(DateTime.UtcNow.AddMonths(2).ToString("d"), actual.Apprenticeships.ElementAt(5).StartDate.Value.ToString("d"));
        }
 public ApprenticeshipSearchResultsBuilder WithSearchParameters(ApprenticeshipSearchParameters searchParameters)
 {
     _searchParameters = searchParameters;
     return(this);
 }
        public async Task And_No_Sort_Term_And_Is_And_There_Are_ApprenticeshipUpdates_These_Appear_First(
            ApprenticeshipSearchParameters searchParameters,
            [Frozen] Mock <IProviderCommitmentsDbContext> mockContext)
        {
            //Arrange
            searchParameters.PageNumber    = 0;
            searchParameters.PageItemCount = 0;
            searchParameters.ReverseSort   = false;
            searchParameters.Filters       = new ApprenticeshipSearchFilters();


            var apprenticeships = new List <Apprenticeship>
            {
                new Apprenticeship
                {
                    FirstName            = "XX",
                    LastName             = "Should_Be_Second",
                    Uln                  = "XX",
                    CourseName           = "XX",
                    StartDate            = DateTime.UtcNow,
                    ProviderRef          = "ABC",
                    Cohort               = new Cohort(),
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>
                    {
                        new ApprenticeshipUpdate
                        {
                            Status     = (byte)ApprenticeshipUpdateStatus.Pending,
                            Originator = (byte)Originator.Employer
                        }
                    }
                },
                new Apprenticeship
                {
                    FirstName            = "XX",
                    LastName             = "Should_Be_First",
                    Uln                  = "XX",
                    CourseName           = "XX",
                    StartDate            = DateTime.UtcNow,
                    ProviderRef          = "ABC",
                    Cohort               = new Cohort(),
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>()
                },
                new Apprenticeship
                {
                    FirstName            = "XX",
                    LastName             = "Should_Be_Third",
                    Uln                  = "XX",
                    CourseName           = "XX",
                    StartDate            = DateTime.UtcNow,
                    ProviderRef          = "ABC",
                    Cohort               = new Cohort(),
                    DataLockStatus       = new List <DataLockStatus>(),
                    ApprenticeshipUpdate = new List <ApprenticeshipUpdate>
                    {
                        new ApprenticeshipUpdate
                        {
                            Status     = (byte)ApprenticeshipUpdateStatus.Pending,
                            Originator = Originator.Provider
                        }
                    }
                },
            };

            AssignProviderToApprenticeships(searchParameters.ProviderId ?? 0, apprenticeships);

            mockContext
            .Setup(context => context.Apprenticeships)
            .ReturnsDbSet(apprenticeships);

            var service = new ApprenticeshipSearchService(mockContext.Object);

            //Act
            var actual = await service.Find(searchParameters);

            //Assert
            Assert.AreEqual("Should_Be_Second", actual.Apprenticeships.ElementAt(0).LastName);
            Assert.AreEqual("Should_Be_Third", actual.Apprenticeships.ElementAt(1).LastName);
            Assert.AreEqual("Should_Be_First", actual.Apprenticeships.ElementAt(2).LastName);
        }
        public SearchResults <ApprenticeshipSearchResponse, ApprenticeshipSearchParameters> GetSuggestedApprenticeshipVacancies(ApprenticeshipSearchParameters searchParameters, Guid candidateId, int vacancyId)
        {
            Condition.Requires(searchParameters).IsNotNull();
            Condition.Requires(vacancyId);

            var candidateApplications = GetApprenticeshipApplications(candidateId);

            return(_apprenticeshipVacancySuggestionsStrategy.GetSuggestedApprenticeshipVacancies(searchParameters, candidateApplications, vacancyId));
        }
Beispiel #27
0
        public ApprenticeshipSearchResponseViewModel FindVacancies(ApprenticeshipSearchViewModel search)
        {
            _logger.Debug("Calling SearchProvider to find apprenticeship vacancies.");

            var searchLocation = _apprenticeshipSearchMapper.Map <ApprenticeshipSearchViewModel, Location>(search);

            try
            {
                string vacancyReference;
                var    isVacancyReference = VacancyHelper.TryGetVacancyReference(search.Keywords, out vacancyReference);

                if ((search.SearchField == ApprenticeshipSearchField.All.ToString() && isVacancyReference) || search.SearchField == ApprenticeshipSearchField.ReferenceNumber.ToString())
                {
                    if (isVacancyReference)
                    {
                        var searchParameters = new ApprenticeshipSearchParameters
                        {
                            VacancyReference = vacancyReference,
                            PageNumber       = 1,
                            PageSize         = 1
                        };

                        var searchResults = _apprenticeshipSearchService.Search(searchParameters);

                        //Expect only a single result. Any other number should be interpreted as no results
                        if (searchResults.Total == 1)
                        {
                            var exactMatchResponse = _apprenticeshipSearchMapper.Map <SearchResults <ApprenticeshipSearchResponse, ApprenticeshipSearchParameters>, ApprenticeshipSearchResponseViewModel>(searchResults);
                            exactMatchResponse.ExactMatchFound = true;
                            return(exactMatchResponse);
                        }

                        if (searchResults.Total > 1)
                        {
                            _logger.Info("{0} results found for Vacancy Reference Number {1} parsed from {2}. Expected 0 or 1", searchResults.Total, vacancyReference, search.Keywords);
                        }
                    }

                    var response = new ApprenticeshipSearchResponseViewModel
                    {
                        Vacancies     = new List <ApprenticeshipVacancySummaryViewModel>(),
                        VacancySearch = search
                    };

                    return(response);
                }

                var results = ProcessNationalAndNonNationalSearches(search, searchLocation);

                var nationalResults    = results[ResultsKeys.National];
                var nonNationalResults = results[ResultsKeys.NonNational];
                var unfilteredResults  = results[ResultsKeys.Unfiltered];

                var nationalResponse = _apprenticeshipSearchMapper.Map <SearchResults <ApprenticeshipSearchResponse, ApprenticeshipSearchParameters>, ApprenticeshipSearchResponseViewModel>(nationalResults);

                nationalResponse.VacancySearch = search;

                var nonNationalResponse = _apprenticeshipSearchMapper.Map <SearchResults <ApprenticeshipSearchResponse, ApprenticeshipSearchParameters>, ApprenticeshipSearchResponseViewModel>(nonNationalResults);

                nonNationalResponse.VacancySearch = search;

                if (search.LocationType == ApprenticeshipLocationType.NonNational)
                {
                    nonNationalResponse.TotalLocalHits    = nonNationalResults.Total;
                    nonNationalResponse.TotalNationalHits = nationalResults.Total;
                    nonNationalResponse.PageSize          = search.ResultsPerPage;

                    if (nonNationalResults.Total == 0 && nationalResults.Total > 0)
                    {
                        nonNationalResponse.Vacancies = nationalResponse.Vacancies;

                        var vacancySearch = nonNationalResponse.VacancySearch;

                        if (vacancySearch.SearchAction == SearchAction.Search || vacancySearch.SortType == VacancySearchSortType.Distance)
                        {
                            vacancySearch.SortType = string.IsNullOrWhiteSpace(vacancySearch.Keywords) ? VacancySearchSortType.ClosingDate : VacancySearchSortType.Relevancy;
                        }

                        vacancySearch.LocationType = ApprenticeshipLocationType.National;
                        SetAggregationResults(nonNationalResponse, nationalResults.AggregationResults, unfilteredResults.AggregationResults);
                    }
                    else
                    {
                        SetAggregationResults(nonNationalResponse, nonNationalResults.AggregationResults, unfilteredResults.AggregationResults);
                    }

                    return(nonNationalResponse);
                }

                nationalResponse.TotalLocalHits    = nonNationalResults.Total;
                nationalResponse.TotalNationalHits = nationalResults.Total;
                nationalResponse.PageSize          = search.ResultsPerPage;

                if (nationalResults.Total == 0 && nonNationalResults.Total > 0)
                {
                    nationalResponse.Vacancies = nonNationalResponse.Vacancies;
                    SetAggregationResults(nonNationalResponse, nonNationalResults.AggregationResults, unfilteredResults.AggregationResults);
                }
                else
                {
                    SetAggregationResults(nonNationalResponse, nationalResults.AggregationResults, unfilteredResults.AggregationResults);
                }

                return(nationalResponse);
            }
            catch (CustomException ex)
            {
                _logger.Error("Find apprenticeship vacancies failed. Check inner details for more info", ex);
                return(new ApprenticeshipSearchResponseViewModel(VacancySearchResultsPageMessages.VacancySearchFailed));
            }
            catch (Exception e)
            {
                _logger.Error("Find apprenticeship vacancies failed. Check inner details for more info", e);
                throw;
            }
        }