public async Task <IActionResult> AddSearchResultsToCompare([FromQuery] SearchResultsQuery searchQuery, string orderBy = "relevance")
        {
            if (!searchQuery.TryValidateSearchParams(out HttpStatusViewResult result))
            {
                return(result);
            }

            // generate compare list
            var searchParams = SearchResultsQueryToEmployerSearchParameters(searchQuery);

            // set maximum search size
            searchParams.Page     = 1;
            searchParams.PageSize = CompareViewService.MaxCompareBasketCount;
            SearchViewModel searchResultsModel = await ViewingService.SearchAsync(searchParams, orderBy);

            // add any new items to the compare list
            string[] resultIds = searchResultsModel.Employers.Results
                                 .Where(employer => CompareViewService.BasketContains(employer.OrganisationIdEncrypted) == false)
                                 .Take(CompareViewService.MaxCompareBasketCount - CompareViewService.BasketItemCount)
                                 .Select(employer => employer.OrganisationIdEncrypted)
                                 .ToArray();

            CompareViewService.AddRangeToBasket(resultIds);

            // save the results to the cookie
            CompareViewService.SaveComparedEmployersToCookie(Request);

            return(RedirectToAction(nameof(SearchResults), "Viewing", searchQuery));
        }
        public async Task <IActionResult> SearchResults([FromQuery] SearchResultsQuery searchQuery, string orderBy = "relevance")
        {
            //When never searched in this session
            if (string.IsNullOrWhiteSpace(SearchViewService.LastSearchParameters))
            {
                //If no compare employers in session then load employers from the cookie
                if (CompareViewService.BasketItemCount == 0)
                {
                    CompareViewService.LoadComparedEmployersFromCookie();
                }
            }

            //Clear the default back url of the employer hub pages
            EmployerBackUrl = null;
            ReportBackUrl   = null;

            // ensure parameters are valid
            if (!searchQuery.TryValidateSearchParams(out HttpStatusViewResult result))
            {
                return(result);
            }

            // generate result view model
            var             searchParams = SearchResultsQueryToEmployerSearchParameters(searchQuery);
            SearchViewModel model        = await ViewingService.SearchAsync(searchParams, orderBy);

            ViewBag.ReturnUrl = SearchViewService.GetLastSearchUrl();

            ViewBag.BasketViewModel = new CompareBasketViewModel {
                CanAddEmployers = false, CanViewCompare = CompareViewService.BasketItemCount > 1, CanClearCompare = true
            };

            return(View("Finder/SearchResults", model));
        }
        public IActionResult AddEmployer(string employerIdentifier, string returnUrl)
        {
            //Check the parameters are populated
            if (string.IsNullOrWhiteSpace(employerIdentifier))
            {
                return(new HttpBadRequestResult($"Missing {nameof(employerIdentifier)}"));
            }

            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return(new HttpBadRequestResult($"Missing {nameof(returnUrl)}"));
            }

            //Get the employer from the encrypted identifier
            EmployerSearchModel employer = GetEmployer(employerIdentifier);

            //Add the employer to the compare list
            CompareViewService.AddToBasket(employer.OrganisationIdEncrypted);

            //Save the compared employers to the cookie
            CompareViewService.SaveComparedEmployersToCookie(Request);

            //Redirect the user to the original page
            return(LocalRedirect(returnUrl));
        }
        public IActionResult ClearEmployers(string returnUrl)
        {
            //Check the parameters are populated
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return(new HttpBadRequestResult($"Missing {nameof(returnUrl)}"));
            }

            CompareViewService.ClearBasket();

            //Save the compared employers to the cookie
            CompareViewService.SaveComparedEmployersToCookie(Request);

            return(LocalRedirect(returnUrl));
        }
        public IActionResult AddEmployerJs(string employerIdentifier, string returnUrl)
        {
            //Check the parameters are populated
            if (string.IsNullOrWhiteSpace(employerIdentifier))
            {
                return(new HttpBadRequestResult($"Missing {nameof(employerIdentifier)}"));
            }

            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return(new HttpBadRequestResult($"Missing {nameof(returnUrl)}"));
            }

            //Get the employer from the encrypted identifier
            EmployerSearchModel employer = GetEmployer(employerIdentifier);

            //Add the employer to the compare list
            CompareViewService.AddToBasket(employer.OrganisationIdEncrypted);

            //Save the compared employers to the cookie
            CompareViewService.SaveComparedEmployersToCookie(Request);

            //Setup compare basket
            bool fromSearchResults = returnUrl.Contains("/search-results");
            bool fromEmployer      = returnUrl.StartsWithI("/employer");

            ViewBag.BasketViewModel = new CompareBasketViewModel {
                CanAddEmployers = false,
                CanClearCompare = true,
                CanViewCompare  = fromSearchResults && CompareViewService.BasketItemCount > 1 ||
                                  fromEmployer && CompareViewService.BasketItemCount > 0,
                IsSearchPage   = fromSearchResults,
                IsEmployerPage = fromEmployer
            };

            ViewBag.ReturnUrl = returnUrl;

            var model = new AddRemoveButtonViewModel {
                OrganisationIdEncrypted = employer.OrganisationIdEncrypted, OrganisationName = employer.Name
            };

            return(PartialView("Basket_Button", model));
        }
        public void LoadsEmployersFromCookie(params string[] expectedEmployerIds)
        {
            // Arrange
            mockHttpContext.Setup(x => x.Request.Cookies[It.Is <string>(arg => arg == CookieNames.LastCompareQuery)])
            .Returns(string.Join(",", expectedEmployerIds));

            var testService = new CompareViewService(
                mockHttpContextAccessor.Object,
                Mock.Of <IHttpSession>());

            // Act
            testService.LoadComparedEmployersFromCookie();

            // Assert
            Assert.AreEqual(
                expectedEmployerIds.Length,
                testService.BasketItemCount,
                $"Expected basket to contain {expectedEmployerIds.Length} employers");
            Assert.IsTrue(testService.ComparedEmployers.Value.Contains(expectedEmployerIds), "Expected employer ids to match basket items");
        }
        public void ClearsBasketBeforeLoadingFromCookie()
        {
            // Arrange
            mockHttpContext.Setup(x => x.Request.Cookies[It.Is <string>(arg => arg == CookieNames.LastCompareQuery)])
            .Returns("12345678");

            var testService = new CompareViewService(
                mockHttpContextAccessor.Object,
                Mock.Of <IHttpSession>());

            var testPreviousIds = new[] { "AAA", "BBB", "CCC" };

            testService.AddRangeToBasket(testPreviousIds);

            // Act
            testService.LoadComparedEmployersFromCookie();

            // Assert
            Assert.AreEqual(1, testService.BasketItemCount, "Expected basket to contain 1 employer");
            Assert.IsFalse(
                testService.ComparedEmployers.Value.Contains(testPreviousIds),
                "Expected previous employer ids to be cleared from basket");
        }
        public IActionResult CompareEmployers(int year, string employers = null)
        {
            if (year == 0)
            {
                CompareViewService.SortColumn    = null;
                CompareViewService.SortAscending = true;
                year = ReportingYearsHelper.GetTheMostRecentCompletedReportingYear();
            }

            //Load employers from querystring (via shared email)
            if (!string.IsNullOrWhiteSpace(employers))
            {
                string[] comparedEmployers = employers.SplitI("-");
                if (comparedEmployers.Any())
                {
                    CompareViewService.ClearBasket();
                    CompareViewService.AddRangeToBasket(comparedEmployers);
                    CompareViewService.SortAscending = true;
                    CompareViewService.SortColumn    = null;
                    return(RedirectToAction("CompareEmployers", new { year }));
                }
            }

            //If the session is lost then load employers from the cookie
            else if (CompareViewService.BasketItemCount == 0)
            {
                CompareViewService.LoadComparedEmployersFromCookie();
            }

            ViewBag.ReturnUrl = Url.Action("CompareEmployers", new { year });

            //Clear the default back url of the employer hub pages
            EmployerBackUrl = null;
            ReportBackUrl   = null;

            //Get the compare basket organisations
            IEnumerable <CompareReportModel> compareReports = OrganisationBusinessLogic.GetCompareData(
                CompareViewService.ComparedEmployers.Value.AsEnumerable(),
                year,
                CompareViewService.SortColumn,
                CompareViewService.SortAscending);

            //Track the compared employers
            string lastComparedEmployerList = CompareViewService.ComparedEmployers.Value.ToList().ToSortedSet().ToDelimitedString();

            if (CompareViewService.LastComparedEmployerList != lastComparedEmployerList && IsAction("CompareEmployers"))
            {
                SortedSet <string> employerIds = compareReports.Select(r => r.EncOrganisationId).ToSortedSet();
                WebTracker.TrackPageView(
                    this,
                    $"compare-employers: {employerIds.ToDelimitedString()}",
                    $"{ViewBag.ReturnUrl}?{employerIds.ToEncapsulatedString("e=", null, "&", "&", false)}");
                foreach (CompareReportModel employer in compareReports)
                {
                    WebTracker.TrackPageView(
                        this,
                        $"{employer.EncOrganisationId}: {employer.OrganisationName}",
                        $"{ViewBag.ReturnUrl}?{employer.EncOrganisationId}={employer.OrganisationName}");
                }

                CompareViewService.LastComparedEmployerList = lastComparedEmployerList;
            }

            //Generate the shared links
            string shareEmailUrl = Url.Action(
                nameof(CompareEmployers),
                "Compare",
                new { year, employers = CompareViewService.ComparedEmployers.Value.ToList().ToDelimitedString("-") },
                Request.Scheme);

            ViewBag.BasketViewModel = new CompareBasketViewModel {
                CanAddEmployers = true, CanViewCompare = false, CanClearCompare = true
            };

            return(View(
                       "CompareEmployers",
                       new CompareViewModel {
                LastSearchUrl = SearchViewService.GetLastSearchUrl(),
                CompareReports = compareReports,
                CompareBasketCount = CompareViewService.BasketItemCount,
                ShareEmailUrl =
                    CompareViewService.BasketItemCount <= CompareViewService.MaxCompareBasketShareCount ? shareEmailUrl : null,
                Year = year,
                SortAscending = CompareViewService.SortAscending,
                SortColumn = CompareViewService.SortColumn
            }));
        }