public async Task PerformSearch_StartAndEndItemsNumbersDisplayedCorrectlyOnSecondPageOfItemsWithMorePagesAvailable()
        {
            // Arrange
            ISpecificationsApiClient specsClient = Substitute.For <ISpecificationsApiClient>();
            ILogger logger = Substitute.For <ILogger>();
            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger);

            int numberOfItems = 50;

            PagedResult <SpecificationSearchResultItem> itemResult = GeneratePagedResult(numberOfItems);

            itemResult.PageNumber = 2;
            itemResult.PageSize   = 50;
            itemResult.TotalItems = 175;

            specsClient
            .FindSpecifications(Arg.Any <SearchFilterRequest>())
            .Returns(itemResult);

            SearchRequestViewModel request = new SearchRequestViewModel()
            {
                PageNumber = 2,
            };

            // Act
            SpecificationSearchResultViewModel results = await SpecificationSearchService.PerformSearch(request);

            // Assert
            results.StartItemNumber.Should().Be(51);
            results.EndItemNumber.Should().Be(100);
        }
        public async Task PerformSearch_FirstSearchResultReturnedCorrectly()
        {
            // Arrange
            ISpecificationsApiClient specsClient = Substitute.For <ISpecificationsApiClient>();
            ILogger logger = Substitute.For <ILogger>();
            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger);

            int numberOfItems = 25;

            PagedResult <SpecificationSearchResultItem> itemResult = GeneratePagedResult(numberOfItems);

            specsClient
            .FindSpecifications(Arg.Any <SearchFilterRequest>())
            .Returns(itemResult);

            SearchRequestViewModel request = new SearchRequestViewModel();

            // Act
            SpecificationSearchResultViewModel results = await SpecificationSearchService.PerformSearch(request);

            // Assert
            SpecificationSearchResultItemViewModel first = results.Specifications.First();

            first.Should().NotBeNull();
            first.Id.Should().Be("10");
            first.Name.Should().Be("Specification 1");
            first.Status.Should().Be("Draft");
            first.FundingPeriodName.Should().Be("Test Period");
            first.IsSelectedForFunding.Should().BeTrue();
        }
        public async Task PerformSearch_FirstSearchResultWithFacets_ReturnedCorrectly()
        {
            // Arrange
            ISpecificationsApiClient specsClient = Substitute.For <ISpecificationsApiClient>();
            ILogger logger = Substitute.For <ILogger>();
            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger);

            int numberOfItems = 25;

            IEnumerable <SearchFacet> facets = new[]
            {
                new SearchFacet(), new SearchFacet()
            };

            PagedResult <SpecificationSearchResultItem> itemResult = GeneratePagedResult(numberOfItems, facets);

            specsClient
            .FindSpecifications(Arg.Any <SearchFilterRequest>())
            .Returns(itemResult);

            SearchRequestViewModel request = new SearchRequestViewModel();

            // Act
            SpecificationSearchResultViewModel results = await SpecificationSearchService.PerformSearch(request);

            // Assert
            SpecificationSearchResultItemViewModel first = results.Specifications.First();

            first
            .Should()
            .NotBeNull();

            first
            .Should()
            .BeEquivalentTo(new SpecificationSearchResultItemViewModel()
            {
                Id   = "10",
                Name = "Specification 1",
                FundingPeriodName    = "Test Period",
                FundingPeriodId      = "FundingPeriodID",
                Status               = "Draft",
                Description          = "Description",
                FundingStreamIds     = new[] { "fs1", "fs2" },
                FundingStreamNames   = new[] { "Funding Stream 1", "Funding Stream 2" },
                LastUpdatedDate      = new DateTime(2018, 12, 5, 12, 5, 6),
                IsSelectedForFunding = true
            });

            results
            .Facets
            .Count()
            .Should()
            .Be(2);
        }
        public async Task PerformSearch_WhenFindSpecificationsServiceReturnsNotFound_ThenNullReturned()
        {
            // Arrange
            ISpecificationsApiClient specsClient = Substitute.For <ISpecificationsApiClient>();
            ILogger logger = Substitute.For <ILogger>();
            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger);

            PagedResult <SpecificationSearchResultItem> expectedServiceResult = null;

            specsClient
            .FindSpecifications(Arg.Any <SearchFilterRequest>())
            .Returns(expectedServiceResult);

            SearchRequestViewModel request = new SearchRequestViewModel();

            // Act
            SpecificationSearchResultViewModel result = await SpecificationSearchService.PerformSearch(request);

            // Assert
            result.Should().BeNull();
        }
        public async Task PerformSearch_FirstSearchResultWithFacets_EnsuresFacetsLoadedCorrectly()
        {
            // Arrange
            ISpecificationsApiClient specsClient = Substitute.For <ISpecificationsApiClient>();
            ILogger logger = Substitute.For <ILogger>();
            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger);

            int numberOfItems = 25;

            IEnumerable <SearchFacet> facets = new[]
            {
                new SearchFacet
                {
                    Name        = "facet 1",
                    FacetValues = new[]
                    {
                        new SearchFacetValue {
                            Name = "f1", Count = 5
                        }
                    }
                },
                new SearchFacet
                {
                    Name        = "facet 2",
                    FacetValues = new[]
                    {
                        new SearchFacetValue {
                            Name = "f2", Count = 11
                        },
                        new SearchFacetValue {
                            Name = "f3", Count = 1
                        }
                    }
                }
            };

            PagedResult <SpecificationSearchResultItem> itemResult = GeneratePagedResult(numberOfItems, facets);

            specsClient
            .FindSpecifications(Arg.Any <SearchFilterRequest>())
            .Returns(itemResult);

            SearchRequestViewModel request = new SearchRequestViewModel();

            // Act
            SpecificationSearchResultViewModel results = await SpecificationSearchService.PerformSearch(request);

            // Assert
            SpecificationSearchResultItemViewModel first = results.Specifications.First();

            first.Should().NotBeNull();
            first.Id.Should().Be("10");
            first.Name.Should().Be("Specification 1");
            first.Status.Should().Be("Draft");
            first.FundingPeriodName.Should().Be("Test Period");

            results.Facets.Count().Should().Be(2);
            results.Facets.First().Name.Should().Be("facet 1");
            results.Facets.First().FacetValues.Count().Should().Be(1);
            results.Facets.First().FacetValues.First().Name.Should().Be("f1");
            results.Facets.First().FacetValues.First().Count.Should().Be(5);
            results.Facets.Last().Name.Should().Be("facet 2");
            results.Facets.Last().FacetValues.Count().Should().Be(2);
            results.Facets.Last().FacetValues.First().Name.Should().Be("f2");
            results.Facets.Last().FacetValues.First().Count.Should().Be(11);
            results.Facets.Last().FacetValues.Last().Name.Should().Be("f3");
            results.Facets.Last().FacetValues.Last().Count.Should().Be(1);
        }
        public async Task <IActionResult> GetAllSpecifications([FromQuery] SpecificationSearchRequestViewModel viewModel)
        {
            var searchFilterRequest = new SearchFilterRequest
            {
                Filters       = new Dictionary <string, string[]>(),
                ErrorToggle   = false,
                SearchMode    = SearchMode.All,
                FacetCount    = 0,
                PageSize      = viewModel.PageSize,
                Page          = viewModel.Page,
                IncludeFacets = true,
                SearchFields  = new List <string>(),
                SearchTerm    = ""
            };

            if (viewModel.Status?.Length > 0)
            {
                searchFilterRequest.Filters.Add("status", viewModel.Status.ToArray());
            }

            if (viewModel.FundingPeriods?.Length > 0)
            {
                searchFilterRequest.Filters.Add("fundingPeriodName", viewModel.FundingPeriods.ToArray());
            }

            if (viewModel.FundingStreams?.Length > 0)
            {
                searchFilterRequest.Filters.Add("fundingStreamNames", viewModel.FundingStreams.ToArray());
            }

            if (!string.IsNullOrEmpty(viewModel.SearchText))
            {
                searchFilterRequest.SearchTerm = viewModel.SearchText;
            }

            PagedResult <SpecificationSearchResultItem> result = await _specificationsApiClient.FindSpecifications(searchFilterRequest);

            if (result != null)
            {
                int totalPages = result.Items.Count() / viewModel.PageSize;
                if (result.Items.Count() % viewModel.PageSize > 0)
                {
                    totalPages++;
                }

                int startNumber = ((viewModel.PageSize * viewModel.Page) - viewModel.PageSize) + 1;
                int endNumber   = (viewModel.PageSize * viewModel.Page);
                if (endNumber > result.TotalItems)
                {
                    endNumber = result.TotalItems;
                }

                PagedSpecficationSearchResults searchPagedResult = new PagedSpecficationSearchResults
                {
                    Items           = result.Items,
                    TotalCount      = result.TotalItems,
                    PagerState      = new PagerState(viewModel.Page, result.TotalPages),
                    StartItemNumber = startNumber,
                    EndItemNumber   = endNumber,
                    Facets          = result.Facets
                };

                return(Ok(searchPagedResult));
            }

            return(new BadRequestResult());
        }
        public async Task <SpecificationSearchResultViewModel> PerformSearch(SearchRequestViewModel request)
        {
            SearchFilterRequest requestOptions = new SearchFilterRequest()
            {
                Page          = request.PageNumber.HasValue ? request.PageNumber.Value : 1,
                PageSize      = request.PageSize.HasValue ? request.PageSize.Value : 50,
                SearchTerm    = request.SearchTerm,
                IncludeFacets = request.IncludeFacets,
                Filters       = request.Filters,
                SearchMode    = SearchMode.All
            };

            if (request.PageNumber.HasValue && request.PageNumber.Value > 0)
            {
                requestOptions.Page = request.PageNumber.Value;
            }

            PagedResult <SpecificationSearchResultItem> calculationsResult = await _specsApiClient.FindSpecifications(requestOptions);

            if (calculationsResult == null)
            {
                _logger.Error("Find calculations HTTP request failed");
                return(null);
            }

            SpecificationSearchResultViewModel result = new SpecificationSearchResultViewModel
            {
                TotalResults = calculationsResult.TotalItems,
                CurrentPage  = calculationsResult.PageNumber
            };

            List <SearchFacetViewModel> searchFacets = new List <SearchFacetViewModel>();

            if (calculationsResult.Facets != null)
            {
                foreach (SearchFacet facet in calculationsResult.Facets)
                {
                    searchFacets.Add(_mapper.Map <SearchFacetViewModel>(facet));
                }
            }

            result.Facets = searchFacets.AsEnumerable();

            List <SpecificationSearchResultItemViewModel> itemResults = new List <SpecificationSearchResultItemViewModel>();

            foreach (SpecificationSearchResultItem searchResult in calculationsResult.Items)
            {
                itemResults.Add(_mapper.Map <SpecificationSearchResultItemViewModel>(searchResult));
            }

            result.Specifications = itemResults.AsEnumerable();
            if (result.TotalResults == 0)
            {
                result.StartItemNumber = 0;
                result.EndItemNumber   = 0;
            }
            else
            {
                result.StartItemNumber = ((requestOptions.Page - 1) * requestOptions.PageSize) + 1;
                result.EndItemNumber   = result.StartItemNumber + requestOptions.PageSize - 1;
            }

            if (result.EndItemNumber > calculationsResult.TotalItems)
            {
                result.EndItemNumber = calculationsResult.TotalItems;
            }

            result.PagerState = new PagerState(requestOptions.Page, calculationsResult.TotalPages, 4);

            return(result);
        }