public async Task Check_PaginationDetails_Default_Value()
        {
            // arrange
            var list = new List <string> {
                "a", "b", "c", "d",
            };

            var pagingDetails = new PaginationDetails();

            var connectionFactory = new QueryableConnectionResolver <string>(list.AsQueryable(), pagingDetails);

            // act
            Connection <string> connection = await connectionFactory.ResolveAsync(CancellationToken.None);

            // assert
            Assert.AreEqual(connection.PageInfo.Limit, 10);

            Assert.AreEqual(connection.PageInfo.PageNumber, 1);

            Assert.False(connection.PageInfo.HasNextPage);

            Assert.False(connection.PageInfo.HasPreviousPage);

            Assert.AreEqual(connection.PageInfo.TotalCount, list.Count);
        }
        public async Task Check_Items()
        {
            // arrange
            var list = new List <string> {
                "a", "b", "c", "d",
            };

            var pagingDetails = new PaginationDetails
            {
                Limit = 10
            };

            var connectionFactory = new QueryableConnectionResolver <string>(
                list.AsQueryable(), pagingDetails);

            // act
            Connection <string> connection = await connectionFactory.ResolveAsync(CancellationToken.None);

            // assert
            Assert.AreEqual(connection.Edges[0].Node,
                            list[0],
                            "Check_Items[0]");

            Assert.AreEqual(connection.Edges[1].Node,
                            list[1],
                            "Check_Items[1]");

            Assert.AreEqual(connection.Edges[2].Node,
                            list[2],
                            "Check_Items[2]");

            Assert.AreEqual(connection.Edges[3].Node,
                            list[3],
                            "Check_Items[3]");
        }
        public void CustomConstructorTestEmptyToken(string token)
        {
            var sut = new PaginationDetails(token);

            sut.NextToken.Should().BeNull();
            sut.HasNext.Should().BeFalse();
        }
        public void DefaultConstructorTest()
        {
            var sut = new PaginationDetails();

            sut.NextToken.Should().BeNull();
            sut.HasNext.Should().BeFalse();
        }
        public void CustomConstructorTestWithTokenValue(string token)
        {
            var sut = new PaginationDetails(token);

            sut.NextToken.Should().Be(Base64UrlEncoder.Encode(token));
            sut.HasNext.Should().BeTrue();
        }
        public PagedMediaRecords GetPagedMediaRecords(ApiResponse <List <MediaRecord> > mediaRecords)
        {
            foreach (var mr in mediaRecords.ResponseData)
            {
                mr.ImageLink = mr.Links.FirstOrDefault(l => l.Rel == "Thumbnail").Href;
            }
            ;

            PaginationDetails paginationDetails = new PaginationDetails();

            var paginationHeader = mediaRecords.ResponseHeaders.Where(a => a.Key == "X-Pagination")
                                   .FirstOrDefault().Value;

            if (paginationHeader != null)
            {
                paginationDetails = JsonConvert.DeserializeObject <PaginationDetails>(paginationHeader.FirstOrDefault());
            }
            PagedMediaRecords pagedMediaRecords = new PagedMediaRecords()
            {
                PaginationDetails = paginationDetails,
                MediaRecords      = mediaRecords.ResponseData
            };

            return(pagedMediaRecords);
        }
예제 #7
0
        /// <summary>
        /// PaginationDetails to QueryablePagingDetails object
        /// </summary>
        /// <param name="pagination">Pagination</param>
        /// <returns>QueryablePagingDetails</returns>
        private QueryablePagingDetails DeserializePagingDetails(PaginationDetails pagination)
        {
            long?totalCount = GetTotalCountFromCursor(_properties);

            return(new QueryablePagingDetails(totalCount,
                                              pagination.PageNumber,
                                              pagination.Limit));
        }
        public void EncodeNextTokenTestEmptyToken(string token)
        {
            var sut = new PaginationDetails();

            sut.EncodeNextToken(token);
            sut.NextToken.Should().BeNull();
            sut.HasNext.Should().BeFalse();
        }
예제 #9
0
        public void PagedResultConstructorSetPaginationToken()
        {
            var list = _fixture.CreateMany <string>(10);
            var paginationDetails = new PaginationDetails();
            var sut = new PagedResult <string>(list, paginationDetails);

            sut.Results.Should().BeEquivalentTo(list);
            sut.PaginationDetails.Should().Be(paginationDetails);
        }
예제 #10
0
 public ApiResponse(int statusCode, string message = "", object result = null, ApiError apiError = null, string apiVersion = "", PaginationDetails paginationDetails = null)
 {
     StatusCode        = statusCode;
     Message           = message;
     Result            = result;
     ResponseException = apiError;
     Version           = string.IsNullOrWhiteSpace(apiVersion) ? Assembly.GetEntryAssembly().GetName().Version.ToString() : apiVersion;
     IsError           = false;
     PaginationDetails = paginationDetails;
 }
예제 #11
0
        public QueryableConnectionResolver(IQueryable <T> source,
                                           PaginationDetails paginationDetails)
        {
            if (paginationDetails == null)
            {
                throw new ArgumentNullException(nameof(paginationDetails));
            }

            _source      = source ?? throw new ArgumentNullException(nameof(source));
            _pageDetails = DeserializePagingDetails(paginationDetails);

            _properties = paginationDetails.Properties
                          ?? new Dictionary <string, object>();
        }
예제 #12
0
        public void ShouldCheckPaginationProcessesAreCorrect(int page, int pageSize, int totalCount, int expectedPage, int lastPage, int noOfRecordsToSkip)
        {
            var result         = new PaginationHelper().GeneratePaginationDetails(page, pageSize, totalCount);
            var expectedResult = new PaginationDetails
            {
                Page                  = expectedPage,
                TotalCount            = totalCount,
                LastPage              = lastPage,
                NumberOfRecordsToSkip = noOfRecordsToSkip,
                NumberPerPage         = pageSize
            };

            result.Should().BeEquivalentTo(expectedResult);
        }
        public void ShouldReturnActiveListOfProviderApprenticeshipsForUkprn()
        {
            const long ukprn = 10005214L;

            const int totalCount             = 400;
            var       apprenticeshipTraining = new ApprenticeshipTraining
            {
                Identifier   = "321-1-1",
                Name         = "Archeologist",
                TrainingType = ApprenticeshipTrainingType.Framework,
                Level        = 3,
                Type         = "Framework"
            };

            var apprenticeshipTrainingList = new List <ApprenticeshipTraining>
            {
                apprenticeshipTraining
            };

            const int numberPerPage     = 20;
            const int numberReturned    = 1;
            const int page              = 2;
            const int lastPage          = 37;
            var       paginationDetails = new PaginationDetails {
                NumberPerPage = 20, Page = page, TotalCount = totalCount, LastPage = lastPage
            };

            var expected = new ApprenticeshipTrainingSummary
            {
                ApprenticeshipTrainingItems = apprenticeshipTrainingList,
                PaginationDetails           = paginationDetails,
                Ukprn = ukprn
            };

            _mockGetProviders.Setup(
                x =>
                x.GetActiveApprenticeshipTrainingByProvider(ukprn, 1)).Returns(expected);

            var result = _sut.GetActiveApprenticeshipTrainingByProvider(ukprn);
            var providerApprenticeships = result.Value.ApprenticeshipTrainingItems.ToArray();

            Assert.AreEqual(apprenticeshipTrainingList.Count, providerApprenticeships.Length);
            Assert.AreEqual(totalCount, result.Value.PaginationDetails.TotalCount);
            Assert.AreEqual(numberPerPage, result.Value.PaginationDetails.NumberPerPage);
            Assert.AreEqual(numberReturned, result.Value.ApprenticeshipTrainingItems.Count());
            Assert.AreEqual(page, result.Value.PaginationDetails.Page);
            Assert.AreEqual(lastPage, result.Value.PaginationDetails.LastPage);
            Assert.AreEqual(providerApprenticeships[0].Identifier, apprenticeshipTraining.Identifier);
        }
예제 #14
0
        public async Task <PagedResult <Note> > GetByTargetIdAsync(GetNotesByTargetIdQuery query)
        {
            int pageSize = query.PageSize.HasValue ? query.PageSize.Value : MAX_RESULTS;
            var dbNotes  = new List <NoteDb>();
            var table    = _dynamoDbContext.GetTargetTable <NoteDb>();

            var queryConfig = new QueryOperationConfig
            {
                IndexName       = GETNOTESBYTARGETIDINDEX,
                BackwardSearch  = true,
                ConsistentRead  = true,
                Limit           = pageSize,
                PaginationToken = PaginationDetails.DecodeToken(query.PaginationToken),
                Filter          = new QueryFilter(TARGETID, QueryOperator.Equal, query.TargetId)
            };
            var search = table.Query(queryConfig);

            _logger.LogDebug($"Querying {queryConfig.IndexName} index for targetId {query.TargetId}");
            var resultsSet = await search.GetNextSetAsync().ConfigureAwait(false);

            var paginationToken = search.PaginationToken;

            if (resultsSet.Any())
            {
                dbNotes.AddRange(_dynamoDbContext.FromDocuments <NoteDb>(resultsSet));

                // Look ahead for any more, but only if we have a token
                if (!string.IsNullOrEmpty(PaginationDetails.EncodeToken(paginationToken)))
                {
                    queryConfig.PaginationToken = paginationToken;
                    queryConfig.Limit           = 1;
                    search     = table.Query(queryConfig);
                    resultsSet = await search.GetNextSetAsync().ConfigureAwait(false);

                    if (!resultsSet.Any())
                    {
                        paginationToken = null;
                    }
                }
            }

            return(new PagedResult <Note>(dbNotes.Select(x => x.ToDomain()), new PaginationDetails(paginationToken)));
        }
        public async Task TotalCount()
        {
            // arrange
            var list = new List <string> {
                "a", "b", "c", "d",
            };

            var pagingDetails = new PaginationDetails();

            var connectionFactory = new QueryableConnectionResolver <string>(list.AsQueryable(), pagingDetails);

            // act
            Connection <string> connection = await connectionFactory.ResolveAsync(CancellationToken.None);

            // assert
            Assert.True(
                connection.PageInfo.TotalCount == 4,
                "TotalCount");
        }
예제 #16
0
        public IActionResult Index(int pageNumber = 1)
        {
            var authors    = _iUnitOfWork.AuthorRepository.GetAuthorWithBooks().ToList();
            var pagingInfo = new PaginationDetails()
            {
                TotalItems   = authors.Count(),
                CurrentPage  = pageNumber,
                ItemsPerPage = AppConstants.ItemsPerPage,
                Url          = "/Authors/Index"
            };

            var itemsToSkip   = (pageNumber * AppConstants.ItemsPerPage) - AppConstants.ItemsPerPage;
            var dataToDisplay = authors.Skip(itemsToSkip).Take(AppConstants.ItemsPerPage);

            var viewModel = new AuthorViewModel()
            {
                Authors = dataToDisplay, PageModel = pagingInfo
            };

            return(View(viewModel));
        }
예제 #17
0
        public async Task <IActionResult> UsersWithRoles(int pageNumber = 1)
        {
            var users = _unitOfWork.UserRepository
                        .GetAll()
                        .ToList();

            var itemsToSkip   = (pageNumber * AppConstants.ItemsPerPage) - AppConstants.ItemsPerPage;
            var dataToDisplay = users.Skip(itemsToSkip).Take(AppConstants.ItemsPerPage);

            var model = new List <UserWithRolesModel>();

            foreach (var user in dataToDisplay)
            {
                var roles = await _userManager.GetRolesAsync(user);

                if (roles.Contains(AppConstants.AdminUser))
                {
                    user.IsAdmin = true;
                }

                model.Add(new UserWithRolesModel()
                {
                    Roles = string.Join(", ", roles), ApplicationUser = user
                });
            }
            var pagingInfo = new PaginationDetails()
            {
                TotalItems   = users.Count(),
                CurrentPage  = pageNumber,
                ItemsPerPage = AppConstants.ItemsPerPage,
                Url          = "/Users/UsersWithRoles"
            };

            var viewModel = new UserWithRolesViewModel()
            {
                PageModel = pagingInfo, Users = model
            };

            return(View(viewModel));
        }
        public async Task PageNumber()
        {
            // arrange
            var list = new List <string> {
                "a", "b", "c", "d",
            };

            var pagingDetails = new PaginationDetails
            {
                PageNumber = 123
            };

            var connectionFactory = new QueryableConnectionResolver <string>(list.AsQueryable(), pagingDetails);

            // act
            Connection <string> connection = await connectionFactory.ResolveAsync(CancellationToken.None);

            // assert
            Assert.True(
                connection.PageInfo.PageNumber == 123,
                "PageNumber");
        }
        public async Task <IActionResult> SearchResults(string apiUrl, int pageNumber = 1, int pageSize = 5)
        {
            //TODO Use common methods
            if (apiUrl == null)
            {
                apiUrl = $"https://localhost:44300/api/v1/archives/9/mediarecords?pagesize={pageSize}&pagenumber={pageNumber}";
            }
            var responseObject = await HttpClientHelper.GetFromLMARApi <List <MediaRecord> >(apiUrl);

            List <MediaRecord> mediaRecords = responseObject.ResponseData;

            if (mediaRecords == null)
            {
                return(NotFound());
            }

            foreach (var mr in mediaRecords)
            {
                mr.ImageLink = mr.Links.FirstOrDefault(l => l.Rel == "Thumbnail").Href;
            }
            ;

            PaginationDetails paginationDetails = new PaginationDetails();

            var paginationHeader = responseObject.ResponseHeaders.Where(a => a.Key == "X-Pagination")
                                   .FirstOrDefault().Value;

            if (paginationHeader != null)
            {
                paginationDetails = JsonConvert.DeserializeObject <PaginationDetails>(paginationHeader.FirstOrDefault());
            }
            PagedMediaRecords pagedMediaRecords = new PagedMediaRecords()
            {
                PaginationDetails = paginationDetails,
                MediaRecords      = mediaRecords
            };

            return(View(pagedMediaRecords));
        }
        public async Task HasNextPage_False()
        {
            // arrange
            var list = new List <string> {
                "a", "b", "c", "d",
            };

            var pagingDetails = new PaginationDetails
            {
                PageNumber = 2,
                Limit      = 10
            };

            var connectionFactory = new QueryableConnectionResolver <string>(list.AsQueryable(), pagingDetails);

            // act
            Connection <string> connection = await connectionFactory.ResolveAsync(CancellationToken.None);

            // assert
            Assert.False(
                connection.PageInfo.HasNextPage,
                "HasNextPage_False");
        }
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            await _next(context).ConfigureAwait(false);

            var pagingDetails = new PaginationDetails
            {
                Limit      = context.Argument <int?>("limit"),
                PageNumber = context.Argument <int?>("pageNumber"),
            };

            IQueryable <T> source = null;

            if (context.Result is PageableData <T> p)
            {
                source = p.Source;
                pagingDetails.Properties = p.Properties;
            }

            if (context.Result is IQueryable <T> q)
            {
                source = q;
            }
            else if (context.Result is IEnumerable <T> e)
            {
                source = e.AsQueryable();
            }

            if (source != null)
            {
                IConnectionResolver connectionResolver = _createConnectionResolver(
                    source, pagingDetails);

                context.Result = await connectionResolver
                                 .ResolveAsync(context, source)
                                 .ConfigureAwait(false);
            }
        }
예제 #22
0
        public PaginationDetails GeneratePaginationDetails(int page, int pageSize, int totalCount)
        {
            var paginationDetails = new PaginationDetails {
                NumberOfRecordsToSkip = 0, Page = 1, TotalCount = totalCount, NumberPerPage = pageSize
            };

            if (totalCount <= 0)
            {
                return(paginationDetails);
            }

            var pageUsed = page <= 0 ? 1 : page;
            var skip     = (pageUsed - 1) * pageSize;

            while (skip >= totalCount)
            {
                skip = skip - pageSize;
            }

            paginationDetails.LastPage = (totalCount + pageSize - 1) / pageSize;
            paginationDetails.NumberOfRecordsToSkip = skip;
            paginationDetails.Page = (skip / pageSize) + 1;
            return(paginationDetails);
        }
        public void DecodeTokensTestWithTokenValue(string token)
        {
            var sut = new PaginationDetails(token);

            sut.DecodeNextToken().Should().Be(token);
        }
        public void DecodeTokensTestEmptyToken()
        {
            var sut = new PaginationDetails();

            sut.DecodeNextToken().Should().BeNull();
        }
        public void ShouldReturnActiveListOfProviderApprenticeshipsForUkprnInExpectedOrder()
        {
            const long ukprn = 10005214L;
            var        searchResponseForDtos          = new Mock <ISearchResponse <ProviderStandardDto> >();
            var        apiCallForStandards            = new Mock <IApiCallDetails>();
            var        apiCallForDtos                 = new Mock <IApiCallDetails>();
            var        searchResponse                 = new Mock <ISearchResponse <ProviderStandard> >();
            var        apiCallForFrameworks           = new Mock <IApiCallDetails>();
            var        searchResponseForFrameworkDtos = new Mock <ISearchResponse <ProviderFrameworkDto> >();
            var        apiCallForFrameworkDtos        = new Mock <IApiCallDetails>();
            var        searchResponseForFrameworks    = new Mock <ISearchResponse <ProviderFramework> >();

            searchResponseForDtos.Setup(x => x.Documents).Returns(new List <ProviderStandardDto> {
                new ProviderStandardDto()
            });
            searchResponseForFrameworkDtos.Setup(x => x.Documents).Returns(new List <ProviderFrameworkDto>());

            apiCallForDtos.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            searchResponseForDtos.SetupGet(x => x.ApiCall).Returns(apiCallForDtos.Object);
            apiCallForStandards.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            apiCallForFrameworks.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            apiCallForFrameworkDtos.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            searchResponse.SetupGet(x => x.ApiCall).Returns(apiCallForStandards.Object);
            searchResponseForFrameworks.SetupGet(x => x.ApiCall).Returns(apiCallForFrameworks.Object);
            searchResponseForFrameworkDtos.SetupGet(x => x.ApiCall).Returns(apiCallForFrameworkDtos.Object);

            var providerStandardArcheologistLev1 = new ProviderStandard {
                StandardId = 20, Title = "Archeologist", Level = 1, EffectiveFrom = DateTime.Today.AddDays(-3), Published = true
            };
            var providerStandardZebraWranglerShouldBeCutOffByProviderApprenticeshipTrainingMaximum
                = new ProviderStandard()
                {
                StandardId = 10, Title = "Zebra Wrangler", Level = 1, EffectiveFrom = DateTime.Today.AddDays(-3), Published = true
                };

            var providerStandardWithNoEffectiveFrom = new ProviderStandard {
                StandardId = 30, Title = "Absent because no effective from date", Level = 4, EffectiveFrom = null, Published = true
            };

            var providerStandardNotPublished = new ProviderStandard {
                StandardId = 31, Title = "Absent because not published", Level = 4, EffectiveFrom = DateTime.Today.AddDays(-3), Published = false
            };

            var standards = new List <ProviderStandard>
            {
                providerStandardZebraWranglerShouldBeCutOffByProviderApprenticeshipTrainingMaximum,
                providerStandardArcheologistLev1,
                providerStandardWithNoEffectiveFrom,
                providerStandardNotPublished
            };

            searchResponse.Setup(x => x.Documents).Returns(standards);

            var providerFrameworkAccountingLev3 = new ProviderFramework {
                FrameworkId = "321-1-1", PathwayName = "Accounting", Level = 3, EffectiveFrom = DateTime.Today.AddDays(-3)
            };
            var providerFrameworkAccountingLev2 = new ProviderFramework {
                FrameworkId = "321-2-1", PathwayName = "Accounting", Level = 2, EffectiveFrom = DateTime.Today.AddDays(-3), EffectiveTo = DateTime.Today.AddDays(2)
            };
            var providerFrameworkNoLongerActive = new ProviderFramework {
                FrameworkId = "234-3-2", PathwayName = "Active in the past", Level = 4, EffectiveFrom = DateTime.MinValue, EffectiveTo = DateTime.Today.AddDays(-2)
            };

            var frameworks = new List <ProviderFramework>
            {
                providerFrameworkAccountingLev3,
                providerFrameworkAccountingLev2,
                providerFrameworkNoLongerActive
            };

            searchResponseForFrameworks.Setup(x => x.Documents).Returns(frameworks);

            _mockActiveFrameworkChecker
            .Setup(x => x.CheckActiveFramework(It.IsAny <string>(), It.IsAny <DateTime?>(), It.IsAny <DateTime?>()))
            .Returns(true);
            _mockActiveFrameworkChecker
            .Setup(x => x.CheckActiveFramework("234-3-2", It.IsAny <DateTime?>(), It.IsAny <DateTime?>()))
            .Returns(false);
            _mockActiveFrameworkChecker
            .Setup(x => x.CheckActiveStandard(It.IsAny <string>(), It.IsAny <DateTime?>(), It.IsAny <DateTime?>()))
            .Returns(true);
            _mockActiveFrameworkChecker
            .Setup(x => x.CheckActiveStandard(It.IsAny <string>(), null, It.IsAny <DateTime?>()))
            .Returns(false);

            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderStandardDto>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponseForDtos.Object);
            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderStandard>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponse.Object);
            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderFrameworkDto>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponseForFrameworkDtos.Object);
            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderFramework>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponseForFrameworks.Object);

            var paginationDetails = new PaginationDetails
            {
                LastPage = 1,
                NumberOfRecordsToSkip = 0,
                NumberPerPage         = 20,
                Page       = 0,
                TotalCount = 3
            };

            _mockPaginationHelper
            .Setup(x => x.GeneratePaginationDetails(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>())).Returns(paginationDetails);

            var repo = new ProviderRepository(
                _elasticClient.Object,
                _log.Object,
                _mockConfigurationSettings.Object,
                Mock.Of <IProviderLocationSearchProvider>(),
                Mock.Of <IProviderMapping>(),
                _queryHelper.Object,
                _mockActiveFrameworkChecker.Object,
                new PaginationHelper());

            var result = repo.GetActiveApprenticeshipTrainingByProvider(ukprn, 1);

            var providerApprenticeships = result.ApprenticeshipTrainingItems.ToArray();

            Assert.AreEqual(PageSizeApprenticeshipSummary, providerApprenticeships.Length);
            Assert.AreEqual(4, result.PaginationDetails.TotalCount);
            Assert.AreEqual(providerApprenticeships[0].Identifier, providerFrameworkAccountingLev2.FrameworkId,
                            $"Expect first item to be Framework Id [{providerFrameworkAccountingLev2.FrameworkId}], but was [{providerApprenticeships[0].Identifier} ]");
            Assert.AreEqual(providerApprenticeships[1].Identifier, providerFrameworkAccountingLev3.FrameworkId);
            Assert.AreEqual(providerApprenticeships[1].TrainingType, ApprenticeshipTrainingType.Framework);
            Assert.AreEqual(providerApprenticeships[1].Type, "Framework");
            Assert.AreEqual(providerApprenticeships[1].Level, 3);
            Assert.AreEqual(providerApprenticeships[1].Name, "Accounting");
            Assert.AreEqual(providerApprenticeships[2].Identifier, providerStandardArcheologistLev1.StandardId.ToString());
            Assert.AreEqual(providerApprenticeships[2].TrainingType, ApprenticeshipTrainingType.Standard);
            Assert.AreEqual(providerApprenticeships[2].Type, "Standard");
            Assert.AreEqual(providerApprenticeships[2].Level, 1);
            Assert.AreEqual(providerApprenticeships[2].Name, "Archeologist");
        }
        public void ShouldReturnActiveListOfProviderApprenticeshipsForUkprnInExpectedOrderSecondPage()
        {
            const long ukprn = 10005214L;
            var        searchResponseForDtos          = new Mock <ISearchResponse <ProviderStandardDto> >();
            var        apiCallForStandards            = new Mock <IApiCallDetails>();
            var        apiCallForDtos                 = new Mock <IApiCallDetails>();
            var        searchResponse                 = new Mock <ISearchResponse <ProviderStandard> >();
            var        apiCallForFrameworks           = new Mock <IApiCallDetails>();
            var        searchResponseForFrameworkDtos = new Mock <ISearchResponse <ProviderFrameworkDto> >();
            var        apiCallForFrameworkDtos        = new Mock <IApiCallDetails>();
            var        searchResponseForFrameworks    = new Mock <ISearchResponse <ProviderFramework> >();

            searchResponseForDtos.Setup(x => x.Documents).Returns(new List <ProviderStandardDto> {
                new ProviderStandardDto()
            });
            searchResponseForFrameworkDtos.Setup(x => x.Documents).Returns(new List <ProviderFrameworkDto>());

            apiCallForDtos.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            searchResponseForDtos.SetupGet(x => x.ApiCall).Returns(apiCallForDtos.Object);
            apiCallForStandards.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            apiCallForFrameworks.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            apiCallForFrameworkDtos.SetupGet(x => x.HttpStatusCode).Returns((int)HttpStatusCode.OK);
            searchResponse.SetupGet(x => x.ApiCall).Returns(apiCallForStandards.Object);
            searchResponseForFrameworks.SetupGet(x => x.ApiCall).Returns(apiCallForFrameworks.Object);
            searchResponseForFrameworkDtos.SetupGet(x => x.ApiCall).Returns(apiCallForFrameworkDtos.Object);

            var providerStandardArcheologistEntry4 = new ProviderStandard {
                StandardId = 20, Title = "Archeologist", Level = 1, EffectiveFrom = DateTime.Today.AddDays(-3), Published = true
            };
            var providerStandardArcheologistEntry5 = new ProviderStandard {
                StandardId = 21, Title = "Archeologist", Level = 2, EffectiveFrom = DateTime.Today.AddDays(-3), Published = true
            };
            var providerStandardArcheologistEntry6 = new ProviderStandard {
                StandardId = 22, Title = "Archeologist", Level = 3, EffectiveFrom = DateTime.Today.AddDays(-3), Published = true
            };

            var standards = new List <ProviderStandard>
            {
                providerStandardArcheologistEntry4,
                providerStandardArcheologistEntry5,
                providerStandardArcheologistEntry6
            };

            searchResponse.Setup(x => x.Documents).Returns(standards);

            var frameworkAccountingEntry2 = new ProviderFramework {
                FrameworkId = "321-1-1", PathwayName = "Accounting", Level = 3, EffectiveFrom = DateTime.Today.AddDays(-3)
            };
            var frameworkAccountingEntry1 = new ProviderFramework {
                FrameworkId = "321-2-1", PathwayName = "Accounting", Level = 2, EffectiveFrom = DateTime.Today.AddDays(-3), EffectiveTo = DateTime.Today.AddDays(2)
            };
            var frameworkAccountingEntry3 = new ProviderFramework {
                FrameworkId = "234-3-2", PathwayName = "Accounting", Level = 4, EffectiveFrom = DateTime.Today.AddDays(-3), EffectiveTo = DateTime.Today.AddDays(3)
            };
            var standardZebraWranglerEntry7 = new ProviderFramework()
            {
                FrameworkId = "235-4-1", PathwayName = "Zebra Wrangler", Level = 1, EffectiveFrom = DateTime.Today.AddDays(-3)
            };

            var frameworks = new List <ProviderFramework>
            {
                frameworkAccountingEntry2,
                frameworkAccountingEntry3,
                frameworkAccountingEntry1,
                standardZebraWranglerEntry7
            };

            searchResponseForFrameworks.Setup(x => x.Documents).Returns(frameworks);

            _mockActiveFrameworkChecker
            .Setup(x => x.CheckActiveFramework(It.IsAny <string>(), It.IsAny <DateTime?>(), It.IsAny <DateTime?>()))
            .Returns(true);
            _mockActiveFrameworkChecker
            .Setup(x => x.CheckActiveStandard(It.IsAny <string>(), It.IsAny <DateTime?>(), It.IsAny <DateTime?>()))
            .Returns(true);
            _mockActiveFrameworkChecker
            .Setup(x => x.CheckActiveStandard(It.IsAny <string>(), null, It.IsAny <DateTime?>()))
            .Returns(false);

            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderStandardDto>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponseForDtos.Object);
            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderStandard>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponse.Object);
            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderFrameworkDto>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponseForFrameworkDtos.Object);
            _elasticClient.Setup(x => x.Search(It.IsAny <Func <SearchDescriptor <ProviderFramework>, ISearchRequest> >(), It.IsAny <string>())).Returns(searchResponseForFrameworks.Object);

            var paginationDetails = new PaginationDetails
            {
                LastPage = 1,
                NumberOfRecordsToSkip = 0,
                NumberPerPage         = 20,
                Page       = 0,
                TotalCount = 3
            };

            _mockPaginationHelper
            .Setup(x => x.GeneratePaginationDetails(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>())).Returns(paginationDetails);

            var repo = new ProviderRepository(
                _elasticClient.Object,
                _log.Object,
                _mockConfigurationSettings.Object,
                Mock.Of <IProviderLocationSearchProvider>(),
                Mock.Of <IProviderMapping>(),
                _queryHelper.Object,
                _mockActiveFrameworkChecker.Object,
                new PaginationHelper());

            var result = repo.GetActiveApprenticeshipTrainingByProvider(ukprn, 2);

            var providerApprenticeships = result.ApprenticeshipTrainingItems.ToArray();

            Assert.AreEqual(3, providerApprenticeships.Length);

            Assert.AreEqual(providerApprenticeships[0].Identifier, providerStandardArcheologistEntry5.StandardId.ToString(),
                            $"Expect first item to be Standard Id [{providerStandardArcheologistEntry5.StandardId}], but was [{providerApprenticeships[0].Identifier}]");
            Assert.AreEqual(providerApprenticeships[0].TrainingType, ApprenticeshipTrainingType.Standard);
            Assert.AreEqual(providerApprenticeships[0].Type, "Standard");
            Assert.AreEqual(providerApprenticeships[0].Level, 2);
            Assert.AreEqual(providerApprenticeships[0].Name, "Archeologist");
            Assert.AreEqual(providerApprenticeships[1].Identifier, providerStandardArcheologistEntry6.StandardId.ToString(),
                            $"Expect first item to be Standard Id [{providerStandardArcheologistEntry6.StandardId}], but was [{providerApprenticeships[1].Identifier}]");
            Assert.AreEqual(providerApprenticeships[2].Identifier, standardZebraWranglerEntry7.FrameworkId,
                            $"Expect first item to be Framework Id [{standardZebraWranglerEntry7.FrameworkId}], but was [{providerApprenticeships[2].Identifier}]");
        }
예제 #27
0
 public Uri CreatePreviousPageUri(PaginationDetails paginationDetails) =>
 CreateUriFor(paginationDetails.ApiRoute, paginationDetails.PreviousPageNumber,
              paginationDetails.PageSize);
예제 #28
0
        public IEnumerable <AssociateSummaryModel> GetPaginatedAssociates(AssociateSearchModel search, PaginationDetails paginationDetails)
        {
            bool company = false;
            IQueryable <Associate> associates = this.associateRepo.GetAssociates();

            if (search.SelectedStatuses != null)
            {
                if (search.SelectedStatuses.SelectedItems.Count > 0)
                {
                    // Add status filters to query
                    List <int> statusAsInts = search.SelectedStatuses.SelectedItems.Select(s => s.Id).ToList();
                    associates = associates.Where(a => statusAsInts.Contains(a.AssociateApprovalStatusId));
                }
            }

            if (!string.IsNullOrEmpty(search.FirstName))
            {
                associates = associates.Where(a => a.FirstName.ToLower().Contains(search.FirstName.Trim().ToLower()));
            }

            if (!string.IsNullOrEmpty(search.LastName))
            {
                associates = associates.Where(a => a.LastName.ToLower().Contains(search.LastName.Trim().ToLower()));
            }

            if (!string.IsNullOrEmpty(search.Email))
            {
                associates = associates.Where(a => a.Email.ToLower().Contains(search.Email.Trim().ToLower()));
            }

            paginationDetails.ItemsCount = associates.Count();

            if (paginationDetails.SortColumn == "Status")
            {
                associates = paginationDetails.AscendingSort
                                 ? associates.OrderBy(a => a.AssociateApprovalStatus.Description)
                                 : associates.OrderByDescending(a => a.AssociateApprovalStatus.Description);
            }
            else
            {
                if (paginationDetails.SortColumn != "Company")
                {
                    associates = paginationDetails.AscendingSort
                                     ? associates.OrderBy(paginationDetails.SortColumn)
                                     : associates.OrderByDescending(paginationDetails.SortColumn);
                }
                else
                {
                    company = true;
                }
            }

            if (company)
            {
                var result = this.dataMapper.MapAssociateSummaryListE2M(associates);

                result = paginationDetails.AscendingSort
                     ? result.OrderBy(a => a.Company)
                     : result.OrderByDescending(a => a.Company);

                result =
                    result.Skip((paginationDetails.PageNumber - 1) * paginationDetails.PageSize).Take(
                        paginationDetails.PageSize);

                return(result);
            }
            else
            {
                associates =
                    associates.Skip((paginationDetails.PageNumber - 1) * paginationDetails.PageSize).Take(
                        paginationDetails.PageSize);

                return(this.dataMapper.MapAssociateSummaryListE2M(associates));
            }
        }
예제 #29
0
        public IEnumerable<AssociateSummaryModel> GetPaginatedAssociates(AssociateSearchModel search, PaginationDetails paginationDetails)
        {
            bool company = false;
            IQueryable<Associate> associates = this.associateRepo.GetAssociates();

            if (search.SelectedStatuses != null)
            {
                if (search.SelectedStatuses.SelectedItems.Count > 0)
                {
                    // Add status filters to query
                    List<int> statusAsInts = search.SelectedStatuses.SelectedItems.Select(s => s.Id).ToList();
                    associates = associates.Where(a => statusAsInts.Contains(a.AssociateApprovalStatusId));
                }
            }

            if (!string.IsNullOrEmpty(search.FirstName))
            {
                associates = associates.Where(a => a.FirstName.ToLower().Contains(search.FirstName.Trim().ToLower()));
            }

            if (!string.IsNullOrEmpty(search.LastName))
            {
                associates = associates.Where(a => a.LastName.ToLower().Contains(search.LastName.Trim().ToLower()));
            }

            if (!string.IsNullOrEmpty(search.Email))
            {
                associates = associates.Where(a => a.Email.ToLower().Contains(search.Email.Trim().ToLower()));
            }

            paginationDetails.ItemsCount = associates.Count();

            if (paginationDetails.SortColumn == "Status")
            {
                associates = paginationDetails.AscendingSort
                                 ? associates.OrderBy(a => a.AssociateApprovalStatus.Description)
                                 : associates.OrderByDescending(a => a.AssociateApprovalStatus.Description);
            }
            else
            {
                if (paginationDetails.SortColumn != "Company")
                {
                    associates = paginationDetails.AscendingSort
                                     ? associates.OrderBy(paginationDetails.SortColumn)
                                     : associates.OrderByDescending(paginationDetails.SortColumn);
                }
                else { company = true; }
            }

            if (company)
            {
                var result = this.dataMapper.MapAssociateSummaryListE2M(associates);

                result = paginationDetails.AscendingSort
                     ? result.OrderBy(a => a.Company)
                     : result.OrderByDescending(a => a.Company);

                result =
                    result.Skip((paginationDetails.PageNumber - 1) * paginationDetails.PageSize).Take(
                        paginationDetails.PageSize);

                return result;
            }
            else
            {
                associates =
                    associates.Skip((paginationDetails.PageNumber - 1) * paginationDetails.PageSize).Take(
                        paginationDetails.PageSize);

                return this.dataMapper.MapAssociateSummaryListE2M(associates);
            }
        }
 private static IConnectionResolver CreateConnectionResolver(IQueryable <T> source,
                                                             PaginationDetails pagingDetails)
 {
     return(new QueryableConnectionResolver <T>(source, pagingDetails));
 }
예제 #31
0
        public ActionResult Index(AssociateSearchModel search, GridSortOptions sort, string btnSearch, int page = 1,
            int pageSize = 10)
        {
            if (sort.Column == null)
            {
                if (string.IsNullOrEmpty(btnSearch))
                {
                    sort.Column = "CreatedDate";
                }
                else
                {
                    sort.Column = "LastName";
                }
            }

            this.ViewBag.CurrentUserId = this.MembershipService.GetCurrentUserId();

            var paginationDetails = new PaginationDetails
            {
                SortColumn = sort.Column,
                AscendingSort = sort.Direction == SortDirection.Ascending,
                PageNumber = page,
                PageSize = pageSize
            };

            var vm = new AssociateIndexModel {Search = search};

            var all = AssociateStatuses.GetAllAssociateApprovalStatuses(this.associateService);

            var statuses = AssociateStatuses.GetMainAssociateApprovalStatuses(all);

            var archive = AssociateStatuses.GetArchiveAssociateApprovalStatuses(all);

            var doNotUse = AssociateStatuses.GetDoNotUseAssociateApprovalStatuses(archive);

            var archiveActive = AssociateStatuses.GetArchiveActiveAssociateApprovalStatuses(archive);

            vm.Search.Statuses = statuses.ToList();

            // order the statuses by the Order property then the name
            vm.Search.ArchiveDoNotUseStatuses = doNotUse.ToList();
            vm.Search.ArchiveActiveStatuses = archiveActive.ToList();

            if (btnSearch == "Search")
            {
                GetStatuses(search, vm.Search.Statuses, "AssociateStatuses");
                GetStatuses(search, vm.Search.ArchiveDoNotUseStatuses, "ArchiveDoNotUse");
                GetStatuses(search, vm.Search.ArchiveActiveStatuses, "ArchiveActive");
            }
            else
            {
                foreach (var checkBoxItem in vm.Search.Statuses)
                {
                    search.SelectedStatuses.SelectedItems.Add(checkBoxItem);
                }
                foreach (var checkBoxItem in vm.Search.ArchiveDoNotUseStatuses)
                {
                    search.SelectedStatuses.SelectedItems.Add(checkBoxItem);
                }
            }

            var associates = this.associateService.GetPaginatedAssociates(search, paginationDetails);

            vm.PageSize = pageSize;

            vm.Associates = new CustomPagination<AssociateSummaryModel>(
                associates, page, pageSize, paginationDetails.ItemsCount);

            var statusCount = search.Statuses.Count;
            statusCount += search.ArchiveActiveStatuses.Count;
            statusCount += search.ArchiveDoNotUseStatuses.Count;

            this.ViewBag.FilterApplied = !(string.IsNullOrEmpty(search.FirstName) &&
                                           string.IsNullOrEmpty(search.LastName) &&
                                           string.IsNullOrEmpty(search.Email) &&
                                           search.SelectedStatuses.SelectedItems.Count() == statusCount);

            this.ViewData["sort"] = sort;
            this.ViewBag.FilterURL = this.Request.QueryString.ToString();

            return View(vm);
        }