예제 #1
0
        public async Task EstabSearch_Index_WithValidURN_RedirectsToEstabDetail()
        {
            var ers     = new Mock <IEstablishmentReadService>(MockBehavior.Strict);
            var eds     = new Mock <IEstablishmentDownloadService>(MockBehavior.Strict);
            var cls     = new Mock <ICachedLookupService>(MockBehavior.Strict);
            var request = new Mock <HttpRequestBase>(MockBehavior.Strict);
            var context = new Mock <HttpContextBase>(MockBehavior.Strict);

            request.SetupGet(x => x.QueryString).Returns(HttpUtility.ParseQueryString(string.Empty));
            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.User).Returns(null as IPrincipal);
            ers.Setup(x => x.CanAccess(It.IsAny <int>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ServiceResultDto <bool>(true));

            var subject = new EstablishmentsSearchController(ers.Object, eds.Object, cls.Object);

            subject.ControllerContext = new ControllerContext(context.Object, new RouteData(), subject);

            var vm = new EstablishmentSearchViewModel();

            vm.TextSearchModel.AutoSuggestValue = "123456";

            var result = (RedirectToRouteResult)await subject.Index(vm);

            Assert.That(result.RouteValues["action"], Is.EqualTo("Details"));
            Assert.That(result.RouteValues["controller"], Is.EqualTo("Establishment"));
            Assert.That(result.RouteValues["id"], Is.EqualTo(123456));
            Assert.That(result.RouteValues["area"], Is.EqualTo("Establishments"));
        }
예제 #2
0
        public async Task EstabSearch_Index_GoToDetailPageOnOneResult_OneResult()
        {
            var ers           = new Mock <IEstablishmentReadService>(MockBehavior.Strict);
            var eds           = new Mock <IEstablishmentDownloadService>(MockBehavior.Strict);
            var cls           = new Mock <ICachedLookupService>(MockBehavior.Loose);
            var request       = new Mock <HttpRequestBase>(MockBehavior.Strict);
            var context       = new Mock <HttpContextBase>(MockBehavior.Strict);
            var mockUrlHelper = new Mock <UrlHelper>();

            mockUrlHelper.Setup(x => x.RouteUrl(It.IsAny <RouteValueDictionary>())).Returns <RouteValueDictionary>(n => n.Select(s => string.Format("{0}={1}", s.Key, s.Value)).Aggregate((c, nx) => string.Format("{0}|{1}", c, nx)));
            request.SetupGet(x => x.QueryString).Returns(HttpUtility.ParseQueryString(string.Empty));
            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.User).Returns(null as IPrincipal);
            cls.Setup(x => x.LocalAuthorityGetAllAsync()).ReturnsAsync(new[] { new LookupDto {
                                                                                   Id = 2, Name = "TESTLA"
                                                                               }, new LookupDto {
                                                                                   Id = 3, Name = "BOB"
                                                                               } });
            cls.Setup(x => x.EstablishmentStatusesGetAllAsync()).ReturnsAsync(new[] { new LookupDto {
                                                                                          Id = 1, Name = "status1"
                                                                                      }, new LookupDto {
                                                                                          Id = 2, Name = "status2"
                                                                                      } });
            cls.Setup(x => x.GetNameAsync(It.IsAny <string>(), It.IsAny <int?>(), It.IsAny <string>())).ReturnsAsync("bob");
            ers.Setup(x => x.CanAccess(It.IsAny <int>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ServiceResultDto <bool>(false));
            ers.Setup(x => x.GetPermittedStatusIdsAsync(It.IsAny <IPrincipal>())).ReturnsAsync(new[] { 1 });
            ers.Setup(x => x.SearchAsync(It.IsAny <EstablishmentSearchPayload>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ApiPagedResult <EstablishmentSearchResultModel>(1, new List <EstablishmentSearchResultModel>
            {
                new EstablishmentSearchResultModel
                {
                    Name = "School 1",
                    Urn  = 672393
                }
            }));

            var subject = new EstablishmentsSearchController(ers.Object, eds.Object, cls.Object);

            subject.ControllerContext = new ControllerContext(context.Object, new RouteData(), subject);
            subject.Url = mockUrlHelper.Object;

            var vm = new EstablishmentSearchViewModel();

            vm.TextSearchModel.Text      = "school";
            vm.GoToDetailPageOnOneResult = true;
            var result = (RedirectToRouteResult)await subject.Index(vm);

            Assert.That(result.RouteValues["action"], Is.EqualTo("Details"));
            Assert.That(result.RouteValues["controller"], Is.EqualTo("Establishment"));
            Assert.That(result.RouteValues["id"], Is.EqualTo(672393));
            Assert.That(result.RouteValues["area"], Is.EqualTo("Establishments"));

            vm = new EstablishmentSearchViewModel();
            vm.TextSearchModel.Text      = "school";
            vm.GoToDetailPageOnOneResult = false;
            var result2 = (ViewResult)await subject.Index(vm);

            Assert.That(vm.Count, Is.EqualTo(1));
            Assert.That(vm.Results.Count, Is.EqualTo(1));
            Assert.That(vm.Results[0].Name, Is.EqualTo("School 1"));
        }
예제 #3
0
        public async Task EstabSearch_Index_WithInvalidURN_RedirectsBackOnSelf()
        {
            var ers           = new Mock <IEstablishmentReadService>(MockBehavior.Strict);
            var eds           = new Mock <IEstablishmentDownloadService>(MockBehavior.Strict);
            var cls           = new Mock <ICachedLookupService>(MockBehavior.Strict);
            var request       = new Mock <HttpRequestBase>(MockBehavior.Strict);
            var context       = new Mock <HttpContextBase>(MockBehavior.Strict);
            var mockUrlHelper = new Mock <UrlHelper>();

            mockUrlHelper.Setup(x => x.Action(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())).Returns("/Establishments/Search");
            mockUrlHelper.Setup(x => x.RouteUrl(It.IsAny <RouteValueDictionary>())).Returns <RouteValueDictionary>(n => n.Select(s => string.Format("{0}={1}", s.Key, s.Value)).Aggregate((c, nx) => string.Format("{0}|{1}", c, nx)));
            request.SetupGet(x => x.QueryString).Returns(HttpUtility.ParseQueryString(string.Empty));
            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.User).Returns(null as IPrincipal);
            ers.Setup(x => x.CanAccess(It.IsAny <int>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ServiceResultDto <bool>(false));
            ers.Setup(x => x.SearchAsync(It.IsAny <EstablishmentSearchPayload>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ApiPagedResult <EstablishmentSearchResultModel>(0, new List <EstablishmentSearchResultModel>()));

            var subject = new EstablishmentsSearchController(ers.Object, eds.Object, cls.Object);

            subject.ControllerContext = new ControllerContext(context.Object, new RouteData(), subject);
            subject.Url = mockUrlHelper.Object;

            var vm = new EstablishmentSearchViewModel();

            vm.TextSearchModel.AutoSuggestValue = "1256";

            var result = (RedirectResult)await subject.Index(vm);

            Assert.That(result.Url, Is.EqualTo("action=Index|controller=Search|area=|SearchType=Text|TextSearchModel.Text=|NoResults=True"));
        }
예제 #4
0
        private ActionResult NoResults(EstablishmentSearchViewModel model)
        {
            var routeDictionary = new RouteValueDictionary
            {
                { "action", "Index" },
                { "controller", "Search" },
                { "area", string.Empty },
                { "SearchType", model.SearchType }
            };

            string queryStringToAppend = string.Empty;

            switch (model.SearchType)
            {
            case eSearchType.Text:
                routeDictionary.Add("TextSearchModel.Text", model.TextSearchModel.Text);
                routeDictionary.Add("NoResults", true);
                break;

            case eSearchType.Location:
                routeDictionary.Add("LocationSearchModel.Text", model.LocationSearchModel.Text);
                routeDictionary.Add("NoResults", true);
                break;

            case eSearchType.ByLocalAuthority:
                queryStringToAppend = string.Concat("&",
                                                    QueryStringHelper.ToQueryString(EstablishmentSearchViewModel.BIND_ALIAS_LAIDS,
                                                                                    model.SelectedLocalAuthorityIds.ToArray()));
                routeDictionary.Add("NoResults", true);
                break;
            }

            return(new RedirectResult(string.Concat(Url.RouteUrl(routeDictionary), queryStringToAppend)));
        }
        public async Task <ActionResult> Index(EstablishmentSearchViewModel model)
        {
            model.SearchQueryString = Request.QueryString.ToString();

            var retVal = await SearchByUrnAsync(model);

            if (retVal != null)
            {
                return(retVal);
            }

            model.SavedFilterToken = TempData["SavedToken"]?.ToString();

            // if the user navigates back to or reloads the search results => look up saved results token
            if (Request.IsAuthenticated && string.IsNullOrEmpty(model.SavedFilterToken))
            {
                var userId = User.Identity.GetUserId();
                model.SavedFilterToken = (await _userPreferenceRepository.GetAsync(userId))?.SavedSearchToken;
            }

            var payload = await GetEstablishmentSearchPayload(model);

            if (!payload.Success)
            {
                model.Error = payload.ErrorMessage;
            }
            return(await ProcessEstablishmentsSearch(model, payload.Object));
        }
        public async Task EstabSearch_Index_SearchWithLAESTAB(string laestab)
        {
            var ers           = new Mock <IEstablishmentReadService>(MockBehavior.Strict);
            var eds           = new Mock <IEstablishmentDownloadService>(MockBehavior.Strict);
            var cls           = new Mock <ICachedLookupService>(MockBehavior.Loose);
            var upr           = new Mock <IUserPreferenceRepository>(MockBehavior.Loose);
            var request       = new Mock <HttpRequestBase>(MockBehavior.Strict);
            var context       = new Mock <HttpContextBase>(MockBehavior.Strict);
            var mockUrlHelper = new Mock <UrlHelper>();

            mockUrlHelper.Setup(x => x.RouteUrl(It.IsAny <RouteValueDictionary>())).Returns <RouteValueDictionary>(n => n.Select(s => string.Format("{0}={1}", s.Key, s.Value)).Aggregate((c, nx) => string.Format("{0}|{1}", c, nx)));
            request.SetupGet(x => x.QueryString).Returns(HttpUtility.ParseQueryString(string.Empty));
            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.User).Returns(null as IPrincipal);
            context.SetupGet(x => x.Request.IsAuthenticated).Returns(false);
            cls.Setup(x => x.LocalAuthorityGetAllAsync()).ReturnsAsync(new[] { new LookupDto {
                                                                                   Id = 2, Name = "TESTLA"
                                                                               }, new LookupDto {
                                                                                   Id = 3, Name = "BOB"
                                                                               } });
            cls.Setup(x => x.EstablishmentStatusesGetAllAsync()).ReturnsAsync(new[] { new LookupDto {
                                                                                          Id = 1, Name = "status1"
                                                                                      }, new LookupDto {
                                                                                          Id = 2, Name = "status2"
                                                                                      } });
            cls.Setup(x => x.GetNameAsync(It.IsAny <string>(), It.IsAny <int?>(), It.IsAny <string>())).ReturnsAsync("bob");
            ers.Setup(x => x.CanAccess(It.IsAny <int>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ServiceResultDto <bool>(false));
            ers.Setup(x => x.GetPermittedStatusIdsAsync(It.IsAny <IPrincipal>())).ReturnsAsync(new[] { 1 });
            ers.Setup(x => x.SearchAsync(It.IsAny <EstablishmentSearchPayload>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ApiPagedResult <EstablishmentSearchResultModel>(1, new List <EstablishmentSearchResultModel>
            {
                new EstablishmentSearchResultModel
                {
                    Name = "School 1",
                    Urn  = 672393,
                    EstablishmentNumber = 5437,
                    LocalAuthorityId    = 432
                }
            }));

            upr.Setup(x => x.Get(It.IsAny <string>())).Returns(new UserPreference());
            var subject = new EstablishmentsSearchController(ers.Object, eds.Object, cls.Object, upr.Object);

            subject.ControllerContext = new ControllerContext(context.Object, new RouteData(), subject);
            subject.Url = mockUrlHelper.Object;

            var vm = new EstablishmentSearchViewModel();

            vm.TextSearchModel.Text = laestab;
            var result = (ViewResult)await subject.Index(vm);

            Assert.That(vm.TextSearchType, Is.EqualTo(eTextSearchType.LAESTAB));
            Assert.That(vm.Count, Is.EqualTo(1));
            Assert.That(vm.Results.Count, Is.EqualTo(1));
            Assert.That(vm.Results[0].Name, Is.EqualTo("School 1"));
            Assert.That(vm.Results[0].LocalAuthorityId, Is.EqualTo(432));
            Assert.That(vm.Results[0].EstablishmentNumber, Is.EqualTo(5437));
        }
        public async Task EstabSearch_Index_DisplaysResults()
        {
            var ers           = new Mock <IEstablishmentReadService>(MockBehavior.Strict);
            var eds           = new Mock <IEstablishmentDownloadService>(MockBehavior.Strict);
            var cls           = new Mock <ICachedLookupService>(MockBehavior.Loose);
            var upr           = new Mock <IUserPreferenceRepository>(MockBehavior.Loose);
            var request       = new Mock <HttpRequestBase>(MockBehavior.Strict);
            var context       = new Mock <HttpContextBase>(MockBehavior.Strict);
            var mockUrlHelper = new Mock <UrlHelper>();

            request.SetupGet(x => x.QueryString).Returns(HttpUtility.ParseQueryString(string.Empty));
            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.User).Returns(null as IPrincipal);
            context.SetupGet(x => x.Request.IsAuthenticated).Returns(false);
            cls.Setup(x => x.LocalAuthorityGetAllAsync()).ReturnsAsync(new[] { new LookupDto {
                                                                                   Id = 2, Name = "TESTLA"
                                                                               }, new LookupDto {
                                                                                   Id = 3, Name = "BOB"
                                                                               } });
            cls.Setup(x => x.EstablishmentStatusesGetAllAsync()).ReturnsAsync(new[] { new LookupDto {
                                                                                          Id = 1, Name = "status1"
                                                                                      }, new LookupDto {
                                                                                          Id = 2, Name = "status2"
                                                                                      } });
            cls.Setup(x => x.GetNameAsync(It.IsAny <string>(), It.IsAny <int?>(), It.IsAny <string>())).ReturnsAsync("bob");
            ers.Setup(x => x.CanAccess(It.IsAny <int>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ServiceResultDto <bool>(false));
            ers.Setup(x => x.GetPermittedStatusIdsAsync(It.IsAny <IPrincipal>())).ReturnsAsync(new[] { 1 });
            ers.Setup(x => x.SearchAsync(It.IsAny <EstablishmentSearchPayload>(), It.IsAny <IPrincipal>())).ReturnsAsync(() => new ApiPagedResult <EstablishmentSearchResultModel>(2, new List <EstablishmentSearchResultModel>
            {
                new EstablishmentSearchResultModel
                {
                    Name = "School 1"
                },
                new EstablishmentSearchResultModel
                {
                    Name = "School 2"
                }
            }));

            var subject = new EstablishmentsSearchController(ers.Object, eds.Object, cls.Object, upr.Object);

            subject.ControllerContext = new ControllerContext(context.Object, new RouteData(), subject);
            subject.Url = mockUrlHelper.Object;

            var vm = new EstablishmentSearchViewModel();

            vm.TextSearchModel.Text = "school";

            var result = (ViewResult)await subject.Index(vm);

            Assert.That(vm.Count, Is.EqualTo(2));
            Assert.That(vm.Results.Count, Is.EqualTo(2));
            Assert.That(vm.Results[0].Name, Is.EqualTo("School 1"));
            Assert.That(vm.Results[1].Name, Is.EqualTo("School 2"));
        }
예제 #8
0
        public async Task <ActionResult> JsonResults(EstablishmentSearchViewModel model)
        {
            var payload = await GetEstablishmentSearchPayload(model);

            payload.Object.Take = 100;

            if (!payload.Success)
            {
                model.Error = payload.ErrorMessage;
            }
            await ProcessEstablishmentsSearch(model, payload.Object);

            var localAuthorities   = (await _lookupService.LocalAuthorityGetAllAsync());
            var establishmentTypes = await _lookupService.EstablishmentTypesGetAllAsync();

            var educationPhases = await _lookupService.EducationPhasesGetAllAsync();

            var counties = (await _lookupService.CountiesGetAllAsync()).Where(c => c.Id != 63); //remove "not recorded"

            HttpContext.Response.Headers.Add("x-count", model.Count.ToString());

            var filtered = model.Results
                           .Select(result => new
            {
                Result = result, LA = localAuthorities.SingleOrDefault(la => la.Id == result.LocalAuthorityId)
            })
                           .Select(a => new
            {
                Name     = a.Result.Name,
                Location = a.Result.Location,
                Address  = StringUtil.ConcatNonEmpties(", ", a.Result.Address_Line1,
                                                       a.Result.Address_Locality,
                                                       a.Result.Address_Line3,
                                                       a.Result.Address_CityOrTown,
                                                       counties.FirstOrDefault(c => c.Id == a.Result.Address_CountyId)?.Name,
                                                       a.Result.Address_PostCode),
                Urn     = a.Result.Urn,
                LAESTAB =
                    a.LA?.Code != null && a.Result.EstablishmentNumber.HasValue
                            ? $"{a.LA.Code}/{a.Result.EstablishmentNumber.Value:D4}"
                            : string.Empty,
                Status =
                    model.EstablishmentStatuses.FirstOrDefault(x => x.Id == a.Result.StatusId)?.Name ??
                    "Not recorded",
                LocalAuthority = a.LA?.Name ?? "Not recorded",
                PhaseType      = string.Concat(
                    educationPhases.FirstOrDefault(x => x.Id == a.Result.EducationPhaseId)?.Name ?? "Not recorded",
                    ", ", establishmentTypes.FirstOrDefault(x => x.Id == a.Result.TypeId)?.Name ?? "Not recorded"),
            });

            return(Json(filtered));
        }
예제 #9
0
        public async Task <PartialViewResult> ResultsPartial(EstablishmentSearchViewModel model)
        {
            var payload = await GetEstablishmentSearchPayload(model);

            if (!payload.Success)
            {
                model.Error = payload.ErrorMessage;
            }
            await ProcessEstablishmentsSearch(model, payload.Object);

            HttpContext.Response.Headers.Add("x-count", model.Count.ToString());
            HttpContext.Response.Headers.Add("x-show-date-filter-warning", model.ShowDateFilterWarning.ToString().ToLower());
            return(PartialView("Partials/_EstablishmentSearchResults", model));
        }
예제 #10
0
        private async Task <EstablishmentSearchViewModel> PopulateLookups(EstablishmentSearchViewModel vm)
        {
            vm.LocalAuthorities = (await _lookupService.LocalAuthorityGetAllAsync()).OrderBy(x => x.Name)
                                  .Select(x => new LookupItemViewModel(x));
            vm.GovernorRoles = (await _lookupService.GovernorRolesGetAllAsync()).OrderBy(x => x.Name)
                               .Select(x => new LookupItemViewModel(x));
            vm.AdmissionsPolicies = (await _lookupService.AdmissionsPoliciesGetAllAsync()).OrderBy(x => x.Name)
                                    .Select(x => new LookupItemViewModel(x));
            vm.BoardingProvisions = (await _lookupService.ProvisionBoardingGetAllAsync()).OrderBy(x => x.Name)
                                    .Select(x => new LookupItemViewModel(x));
            vm.Dioceses = (await _lookupService.DiocesesGetAllAsync()).OrderBy(x => x.Name)
                          .Select(x => new LookupItemViewModel(x));
            vm.Districts = (await _lookupService.AdministrativeDistrictsGetAllAsync()).OrderBy(x => x.Name)
                           .Select(x => new LookupItemViewModel(x));
            vm.FurtherEducationTypes = (await _lookupService.FurtherEducationTypesGetAllAsync())
                                       .OrderBy(x => x.Name)
                                       .Select(x => new LookupItemViewModel(x));
            vm.Genders = (await _lookupService.GendersGetAllAsync()).OrderBy(x => x.Name)
                         .Select(x => new LookupItemViewModel(x));
            vm.GORs = (await _lookupService.GovernmentOfficeRegionsGetAllAsync()).OrderBy(x => x.Name)
                      .Select(x => new LookupItemViewModel(x));
            vm.NurseryProvisions = (await _lookupService.ProvisionNurseriesGetAllAsync()).OrderBy(x => x.Name)
                                   .Select(x => new LookupItemViewModel(x));
            vm.ParliamentaryConstituencies = (await _lookupService.ParliamentaryConstituenciesGetAllAsync())
                                             .OrderBy(x => x.Name)
                                             .Select(x => new LookupItemViewModel(x));
            vm.ReligiousEthoses = (await _lookupService.ReligiousEthosGetAllAsync()).OrderBy(x => x.Name)
                                  .Select(x => new LookupItemViewModel(x));
            vm.RSCRegions = (await _lookupService.RscRegionsGetAllAsync()).OrderBy(x => x.Name)
                            .Select(x => new LookupItemViewModel(x));
            vm.Section41Designations = (await _lookupService.Section41ApprovedGetAllAsync()).OrderBy(x => x.Name)
                                       .Select(x => new LookupItemViewModel(x));
            vm.SixthFormProvisions = (await _lookupService.ProvisionOfficialSixthFormsGetAllAsync())
                                     .OrderBy(x => x.Name)
                                     .Select(x => new LookupItemViewModel(x));
            vm.SpecialClassesProvisions = (await _lookupService.ProvisionSpecialClassesGetAllAsync())
                                          .OrderBy(x => x.Name)
                                          .Select(x => new LookupItemViewModel(x));
            vm.TypeOfSENProvisions = (await _lookupService.SpecialEducationNeedsGetAllAsync()).OrderBy(x => x.Name)
                                     .Select(x => new LookupItemViewModel(x));
            vm.UrbanRuralDesignations = (await _lookupService.UrbanRuralGetAllAsync()).OrderBy(x => x.Name)
                                        .Select(x => new LookupItemViewModel(x));
            vm.OfstedRatings = (await _lookupService.OfstedRatingsGetAllAsync()).OrderBy(x => x.Name)
                               .Select(x => new LookupItemViewModel(x));

            return(vm);
        }
예제 #11
0
        private async Task <ActionResult> SearchByUrnAsync(EstablishmentSearchViewModel model)
        {
            var urn = model.TextSearchModel.AutoSuggestValueAsInt
                      ?? (model.TextSearchType == EstablishmentSearchViewModel.eTextSearchType.URN
                          ? model.TextSearchModel.Text.ToInteger()
                          : null);

            if (urn.HasValue)
            {
                if ((await _establishmentReadService.CanAccess(urn.Value, User)).ReturnValue)
                {
                    return(RedirectToEstabDetail(urn.Value));
                }
            }

            return(null);
        }
예제 #12
0
        public async Task <ActionResult> Index(EstablishmentSearchViewModel model)
        {
            model.SearchQueryString = Request.QueryString.ToString();

            var retVal = await SearchByUrnAsync(model);

            if (retVal != null)
            {
                return(retVal);
            }

            var payload = await GetEstablishmentSearchPayload(model);

            if (!payload.Success)
            {
                model.Error = payload.ErrorMessage;
            }
            return(await ProcessEstablishmentsSearch(model, payload.Object));
        }
예제 #13
0
        private async Task <ActionResult> ProcessEstablishmentsSearch(EstablishmentSearchViewModel model,
                                                                      EstablishmentSearchPayload payload)
        {
            if (model.HasError)
            {
                return(NoResults(model));
            }
            else
            {
                PopulateSelectList(payload); // select only fields we use in this context

                var results = await _establishmentReadService.SearchAsync(payload, User);

                if (payload.Skip == 0)
                {
                    model.Count = results.Count;
                }
                model.Results = results.Items;

                if (results.Count == 0)
                {
                    return(NoResults(model));
                }

                var localAuthorities = await _lookupService.LocalAuthorityGetAllAsync();

                foreach (var item in model.Results)
                {
                    model.Addresses.Add(item, await item.GetAddressAsync(_lookupService));
                    var laEstab = string.Empty;
                    if (item.LocalAuthorityId.HasValue && item.EstablishmentNumber.HasValue)
                    {
                        var code = localAuthorities.FirstOrDefault(x => x.Id == item.LocalAuthorityId)?.Code;
                        if (code != null)
                        {
                            laEstab = string.Concat(code, "/", item.EstablishmentNumber?.ToString("D4"));
                        }
                    }

                    model.LAESTABs.Add(item, laEstab);
                }
            }

            if (model.Count == 1 && model.GoToDetailPageOnOneResult)
            {
                return(RedirectToEstabDetail(model.Results.First().Urn.GetValueOrDefault()));
            }
            else
            {
                var permittedStatusIds = await _establishmentReadService.GetPermittedStatusIdsAsync(User);

                var establishmentTypes = await _lookupService.EstablishmentTypesGetAllAsync();

                var establishmentGroupTypes = await _lookupService.EstablishmentTypeGroupsGetAllAsync();


                model.EstablishmentTypes = establishmentGroupTypes.Select(groupType =>
                                                                          new HeirarchicalLookupItemViewModel
                {
                    Id         = groupType.Id,
                    Name       = groupType.Name,
                    ChildItems = establishmentTypes.Where(c => c.GroupIds.Contains(groupType.Id))
                                 .Select(e => new HeirarchicalLookupItemViewModel {
                        Id = e.Id, Name = e.Name
                    })
                                 .ToList()
                })
                                           .ToList();

                model.EstablishmentTypeLookup = establishmentTypes.ToDictionary(e => e.Id, e => e.Name);

                model.EstablishmentStatuses = (await _lookupService.EstablishmentStatusesGetAllAsync())
                                              .Where(x => permittedStatusIds == null || permittedStatusIds.Contains(x.Id))
                                              .Select(x => new LookupItemViewModel(x));

                model.EducationPhases =
                    (await _lookupService.EducationPhasesGetAllAsync()).Select(x => new LookupItemViewModel(x));

                model.ReligiousCharacters =
                    (await _lookupService.ReligiousCharactersGetAllAsync()).Select(x => new LookupItemViewModel(x));

                await PopulateLookups(model);


                return(View("Index", model));
            }
        }
예제 #14
0
        private async Task <Returns <EstablishmentSearchPayload> > GetEstablishmentSearchPayload(
            EstablishmentSearchViewModel model)
        {
            var retVal  = new Returns <EstablishmentSearchPayload>();
            var payload = new EstablishmentSearchPayload(model.StartIndex, model.PageSize);
            var filters = payload.Filters;

            if (model.SearchType == eSearchType.Text || model.SearchType == eSearchType.EstablishmentAll)
            {
                if (model.TextSearchType == EstablishmentSearchViewModel.eTextSearchType.UKPRN)
                {
                    filters.UKPRN = model.TextSearchModel.Text;
                }
                else if (model.TextSearchType == EstablishmentSearchViewModel.eTextSearchType.LAESTAB)
                {
                    var laestab          = LAESTAB.TryParse(model.TextSearchModel.Text).Value;
                    var localAuthorityId = (await _lookupService.LocalAuthorityGetAllAsync())
                                           .FirstOrDefault(x => x.Code == laestab.LocalAuthorityCode)?.Id;
                    if (localAuthorityId.HasValue)
                    {
                        filters.LocalAuthorityIds = new int[] { localAuthorityId.Value }
                    }
                    ;
                    filters.EstablishmentNumber = laestab.EstablishmentNumber;
                }
                else if ((model.TextSearchType == EstablishmentSearchViewModel.eTextSearchType.EstablishmentName &&
                          model.TextSearchModel.Text != null) || model.SearchType == eSearchType.EstablishmentAll)
                {
                    payload.Text = model.TextSearchModel.Text;
                }
                else
                {
                    retVal.ErrorMessage = "The LAESTAB, UKPRN or URN was invalid.";
                }
            }
            else if (model.SearchType == eSearchType.Location)
            {
                var coord = model.LocationSearchCoordinate;
                if (coord != null)
                {
                    payload.GeoSearchLocation = coord;
                    payload.RadiusInMiles     = model.GetRadiusOption();
                }
                else
                {
                    retVal.ErrorMessage = "The co-ordinate could not be parsed.";
                }
            }
            else if (model.SearchType == eSearchType.ByLocalAuthority)
            {
                if (!model.SelectedLocalAuthorityIds.Any())
                {
                    retVal.ErrorMessage = "No local authority was selected";
                }
            }

            filters.EducationPhaseIds = model.SelectedEducationPhaseIds.ToArray();
            filters.StatusIds         = model.SelectedEstablishmentStatusIds.ToArray();
            filters.TypeIds           = model.SelectedEstablishmentTypeIds.ToArray();
            if (!filters.LocalAuthorityIds.Any())
            {
                filters.LocalAuthorityIds = model.SelectedLocalAuthorityIds.ToArray();
            }
            filters.ReligiousCharacterIds = model.SelectedReligiousCharacterIds.ToArray();

            filters.AdmissionsPolicyIds       = model.SelectedAdmissionsPolicyIds.ToArray();
            filters.ProvisionBoardingIds      = model.SelectedBoardingProvisionIds.ToArray();
            filters.DioceseIds                = model.SelectedDioceseIds.ToArray();
            filters.AdministrativeDistrictIds = model.SelectedDistrictIds.ToArray();
            filters.FurtherEducationTypeIds   = model.SelectedFETypeIds.ToArray();
            filters.GenderIds = model.SelectedGenderIds.ToArray();
            filters.GovernmentOfficeRegionIds    = model.SelectedGORIds.ToArray();
            filters.ProvisionNurseryIds          = model.SelectedNurseryProvisionIds.ToArray();
            filters.ParliamentaryConstituencyIds = model.SelectedParliamentaryConstituencyIds.ToArray();
            filters.ReligiousEthosIds            = model.SelectedReligiousEthosIds.ToArray();
            filters.RSCRegionIds                  = model.SelectedRSCRegionIds.ToArray();
            filters.Section41ApprovedIds          = model.SelectedSection41Ids.ToArray();
            filters.ProvisionOfficialSixthFormIds = model.SelectedSixthFormProvisionIds.ToArray();
            filters.ProvisionSpecialClassesIds    = model.SelectedSpecialClassesProvisionIds.ToArray();
            filters.SENIds        = model.SelectedTypeOfSENProvisionIds.ToArray();
            filters.UrbanRuralIds = model.SelectedUrbanRuralIds.ToArray();

            filters.CloseDateMin        = model.CloseDateFrom?.ToDateTime();
            filters.CloseDateMax        = model.CloseDateTo?.ToDateTime();
            filters.OpenDateMin         = model.OpenDateFrom?.ToDateTime();
            filters.OpenDateMax         = model.OpenDateTo?.ToDateTime();
            filters.StatutoryLowAgeMin  = model.AgeRangeLow?.From;
            filters.StatutoryLowAgeMax  = model.AgeRangeLow?.To;
            filters.StatutoryHighAgeMin = model.AgeRangeHigh?.From;
            filters.StatutoryHighAgeMax = model.AgeRangeHigh?.To;
            filters.OfstedRatingIds     = model.SelectedOfstedRatingIds.ToArray();


            payload.SortBy = model.GetSortOption();

            return(retVal.Set(payload));
        }