private EmployerSearchModel GetEmployer(string employerIdentifier, bool activeOnly = true)
        {
            EmployerSearchModel employer = SearchViewService.LastSearchResults?.GetEmployer(employerIdentifier);

            if (employer == null)
            {
                //Get the employer from the database
                CustomResult <Organisation> organisationResult = activeOnly
                    ? OrganisationBusinessLogic.LoadInfoFromActiveEmployerIdentifier(employerIdentifier)
                    : OrganisationBusinessLogic.LoadInfoFromEmployerIdentifier(employerIdentifier);
                if (organisationResult.Failed)
                {
                    throw organisationResult.ErrorMessage.ToHttpException();
                }

                if (organisationResult.Result.OrganisationId == 0)
                {
                    throw new HttpException(HttpStatusCode.NotFound, "Employer not found");
                }

                employer = organisationResult.Result.ToEmployerSearchResult();
            }

            return(employer);
        }
        [Obsolete("Please use method 'Employer' instead.")] //, true)]
        public IActionResult EmployerDetails(string e = null, int y = 0, string id = null)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                Organisation organisation;

                try
                {
                    CustomResult <Organisation> organisationLoadingOutcome =
                        OrganisationBusinessLogic.GetOrganisationByEncryptedReturnId(id);

                    if (organisationLoadingOutcome.Failed)
                    {
                        return(organisationLoadingOutcome.ErrorMessage.ToHttpStatusViewResult());
                    }

                    organisation = organisationLoadingOutcome.Result;
                }
                catch (Exception ex)
                {
                    CustomLogger.Error("Cannot decrypt return id from query string", ex);
                    return(View("CustomError", new ErrorViewModel(400)));
                }

                string organisationIdEncrypted = organisation.GetEncryptedId();
                return(RedirectToActionPermanent(nameof(Employer), new { employerIdentifier = organisationIdEncrypted }));
            }

            if (string.IsNullOrWhiteSpace(e))
            {
                return(new HttpBadRequestResult("EmployerDetails: \'e\' query parameter was null or white space"));
            }

            return(RedirectToActionPermanent(nameof(Employer), new { employerIdentifier = e }));
        }
        public IActionResult DownloadCompareData(int year = 0)
        {
            if (year == 0)
            {
                year = ReportingYearsHelper.GetTheMostRecentCompletedReportingYear();
            }

            var result    = CompareEmployers(year) as ViewResult;
            var viewModel = result.Model as CompareViewModel;
            IEnumerable <CompareReportModel> data = viewModel?.CompareReports;

            //Ensure we some data
            if (data == null || !data.Any())
            {
                return(new HttpNotFoundResult($"There is no employer data for year {year}"));
            }

            DataTable model = OrganisationBusinessLogic.GetCompareDatatable(data);

            //Setup the HTTP response
            var contentDisposition = new ContentDisposition {
                FileName = $"Compared GPG Data {ReportingYearsHelper.FormatYearAsReportingPeriod(year)}.csv", Inline = false
            };

            HttpContext.SetResponseHeader("Content-Disposition", contentDisposition.ToString());

            /* No Longer required as AspNetCore has response buffering on by default
             * Response.BufferOutput = true;
             */
            //Track the download
            WebTracker.TrackPageView(this, contentDisposition.FileName);

            //Return the data
            return(Content(model.ToCSV(), "text/csv"));
        }
        public async Task OrganisationBusinessLogic_GetCompareData_Leaves_Null_Values_At_The_Bottom_Of_The_ListAsync()
        {
            // Arrange
            var listOfReturns = GetFourOrgsWithVariousReturns();

            var listOfOrgs = listOfReturns.Select(ret => ret.Organisation);

            var mockedDataRepository = MoqHelpers.CreateMockDataRepository();

            mockedDataRepository.SetupGetAll(listOfOrgs, listOfReturns);

            var dataRepository = mockedDataRepository.Object;


            var mockedSharedBusinessLogic = Get <ISharedBusinessLogic>();

            var submissionBusinessLogic =
                new SubmissionBusinessLogic(mockedSharedBusinessLogic, dataRepository, Mock.Of <IRecordLogger>());

            var mockedScopeBusinessLogic        = Get <IScopeBusinessLogic>();
            var mockedSecurityCodeBusinessLogic = Get <ISecurityCodeBusinessLogic>();
            var mockedEncryptionHandler         = Get <IEncryptionHandler>();
            var mockedObfuscator = Get <IObfuscator>();

            var mockedDnBRepo = Get <IDnBOrgsRepository>();

            var organisationBusinessLogic = new OrganisationBusinessLogic(
                mockedSharedBusinessLogic,
                dataRepository,
                submissionBusinessLogic,
                mockedScopeBusinessLogic,
                mockedEncryptionHandler,
                mockedSecurityCodeBusinessLogic,
                mockedDnBRepo,
                mockedObfuscator);

            var listEncOrgIds = listOfReturns.Select(x => mockedObfuscator.Obfuscate(x.OrganisationId.ToString()));
            var year          = 2017;
            var sortColumn    = "DiffMedianBonusPercent";
            var sortAscending = true;

            // Act
            var data = await organisationBusinessLogic.GetCompareDataAsync(
                listEncOrgIds,
                year,
                sortColumn,
                sortAscending);

            // Assert
        }
        public async Task ScopePresentation_CreateOrganisationViewModel_When_Data_Is_Valid_It_SucceedsAsync()
        {
            // Arrange
            var          employerRef = "6MQP1ETH";
            User         mockUser    = UserHelper.GetNotAdminUserWithVerifiedEmailAddress();
            Organisation mockOrg     = OrganisationHelper.GetPrivateOrganisation(employerRef);

            mockOrg.SetSecurityCode(VirtualDateTime.Now.AddDays(1));
            UserOrganisation mockUserOrg = UserOrganisationHelper.LinkUserWithOrganisation(mockUser, mockOrg);

            var dataRepo = new Mock <IDataRepository>();

            dataRepo.SetupGetAll(mockOrg);

            var organisationBusinessLogic = new OrganisationBusinessLogic(
                testCommonBL,
                dataRepo.Object,
                new Mock <ISubmissionBusinessLogic>().Object,
                new Mock <IScopeBusinessLogic>().Object,
                new Mock <IEncryptionHandler>().Object,
                new Mock <ISecurityCodeBusinessLogic>().Object,
                new Mock <IDnBOrgsRepository>().Object,
                new Mock <IObfuscator>().Object);

            var scopePresenter = new ScopePresenter(
                mockScopeBL.Object,
                dataRepo.Object,
                organisationBusinessLogic,
                testCommonBL);

            var testModel = new EnterCodesViewModel {
                EmployerReference = mockOrg.EmployerReference, SecurityToken = mockOrg.SecurityCode
            };

            // Act
            OrganisationViewModel actual = await scopePresenter.CreateOrganisationViewModelAsync(testModel, mockUser);

            // Assert
            Assert.NotNull(actual, "Expected an organisation view model");
            Assert.AreEqual(employerRef, actual.Employers.Results[0].EmployerReference);
            Assert.False(actual.IsSecurityCodeExpired, "the security code was set to expire tomorrow");
        }
        public IActionResult Employer(string employerIdentifier)
        {
            if (string.IsNullOrWhiteSpace(employerIdentifier))
            {
                return(new HttpBadRequestResult("Missing employer identifier"));
            }

            CustomResult <Organisation> organisationLoadingOutcome;

            try
            {
                organisationLoadingOutcome = OrganisationBusinessLogic.LoadInfoFromActiveEmployerIdentifier(employerIdentifier);

                if (organisationLoadingOutcome.Failed)
                {
                    return(organisationLoadingOutcome.ErrorMessage.ToHttpStatusViewResult());
                }
            }
            catch (Exception ex)
            {
                CustomLogger.Error($"Cannot decrypt return employerIdentifier from '{employerIdentifier}'", ex);
                return(View("CustomError", new ErrorViewModel(400)));
            }

            //Clear the default back url of the report page
            ReportBackUrl = null;

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

            return(View(
                       "EmployerDetails/Employer",
                       new EmployerDetailsViewModel {
                Organisation = organisationLoadingOutcome.Result,
                LastSearchUrl = SearchViewService.GetLastSearchUrl(),
                EmployerBackUrl = EmployerBackUrl,
                ComparedEmployers = CompareViewService.ComparedEmployers.Value
            }));
        }
        public async Task ScopePresentation_CreateOrganisationViewModel_When_Record_Not_Found_Returns_NullAsync()
        {
            // Arrange
            var          employerRef = "SomeThatWillBeInDatabase";
            User         mockUser    = UserHelper.GetNotAdminUserWithVerifiedEmailAddress();
            Organisation mockOrg     = OrganisationHelper.GetPrivateOrganisation(employerRef);

            mockOrg.SetSecurityCode(VirtualDateTime.Now.AddDays(1));
            UserOrganisation mockUserOrg = UserOrganisationHelper.LinkUserWithOrganisation(mockUser, mockOrg);

            var dataRepo = new Mock <IDataRepository>();

            dataRepo.SetupGetAll(mockOrg);

            var organisationBusinessLogic = new OrganisationBusinessLogic(
                testCommonBL,
                dataRepo.Object,
                new Mock <ISubmissionBusinessLogic>().Object,
                new Mock <IScopeBusinessLogic>().Object,
                new Mock <IEncryptionHandler>().Object,
                new Mock <ISecurityCodeBusinessLogic>().Object,
                new Mock <IDnBOrgsRepository>().Object,
                new Mock <IObfuscator>().Object);

            var scopePresenter = new ScopePresenter(
                mockScopeBL.Object,
                dataRepo.Object,
                organisationBusinessLogic,
                testCommonBL);

            var testModel = new EnterCodesViewModel {
                EmployerReference = "NotFoundInDB", SecurityToken = mockOrg.SecurityCode
            };

            // Act
            OrganisationViewModel actual = await scopePresenter.CreateOrganisationViewModelAsync(testModel, mockUser);

            // Assert
            Assert.Null(actual, "When the combination EmployerReference/SecurityCode is not found in DB, this method must return null");
        }
        public void OrganisationBusinessLogic_GetCompareData_Leaves_Null_Values_At_The_Bottom_Of_The_List()
        {
            // Arrange
            List <Return> listOfReturns = GetFourOrgsWithVariousReturns();

            IEnumerable <Organisation> listOfOrgs = listOfReturns.Select(ret => ret.Organisation);

            Mock <IDataRepository> mockedDataRepository = MoqHelpers.CreateMockDataRepository();

            mockedDataRepository.SetupGetAll(listOfOrgs, listOfReturns);

            IDataRepository dataRepository = mockedDataRepository.Object;


            var submissionBusinessLogic = new SubmissionBusinessLogic(dataRepository);

            var mockedEncryptionHandler = Get <IEncryptionHandler>();
            var mockedObfuscator        = Get <IObfuscator>();

            var organisationBusinessLogic = new OrganisationBusinessLogic(
                dataRepository,
                submissionBusinessLogic,
                mockedEncryptionHandler,
                mockedObfuscator);

            IEnumerable <string> listEncOrgIds = listOfReturns.Select(x => mockedObfuscator.Obfuscate(x.OrganisationId.ToString()));
            var year          = 2017;
            var sortColumn    = "DiffMedianBonusPercent";
            var sortAscending = true;

            // Act
            IEnumerable <CompareReportModel> data = organisationBusinessLogic.GetCompareData(
                listEncOrgIds,
                year,
                sortColumn,
                sortAscending);

            // Assert
        }
        public IActionResult Report(string employerIdentifier, int year)
        {
            if (string.IsNullOrWhiteSpace(employerIdentifier))
            {
                return(new HttpBadRequestResult("Missing employer identifier"));
            }

            if (year < Global.FirstReportingYear || year > VirtualDateTime.Now.Year)
            {
                return(new HttpBadRequestResult($"Invalid snapshot year {year}"));
            }

            #region Load organisation

            CustomResult <Organisation> organisationLoadingOutcome;

            try
            {
                organisationLoadingOutcome = OrganisationBusinessLogic.LoadInfoFromActiveEmployerIdentifier(employerIdentifier);

                if (organisationLoadingOutcome.Failed)
                {
                    return(organisationLoadingOutcome.ErrorMessage.ToHttpStatusViewResult());
                }
            }
            catch (Exception ex)
            {
                CustomLogger.Error($"Cannot decrypt return employerIdentifier from '{employerIdentifier}'", ex);
                return(View("CustomError", new ErrorViewModel(400)));
            }

            Organisation foundOrganisation = organisationLoadingOutcome.Result;

            #endregion

            #region Load latest submission

            ReturnViewModel model;

            try
            {
                CustomResult <Return> getLatestSubmissionLoadingOutcome =
                    SubmissionBusinessLogic.GetSubmissionByOrganisationAndYear(foundOrganisation, year);

                if (getLatestSubmissionLoadingOutcome.Failed)
                {
                    return(getLatestSubmissionLoadingOutcome.ErrorMessage.ToHttpStatusViewResult());
                }

                model = SubmissionBusinessLogic.ConvertSubmissionReportToReturnViewModel(getLatestSubmissionLoadingOutcome.Result);
            }
            catch (Exception ex)
            {
                CustomLogger.Error($"Exception processing the return information for Organisation '{foundOrganisation.OrganisationId}:{foundOrganisation.OrganisationName}'", ex);
                return(View("CustomError", new ErrorViewModel(400)));
            }

            #endregion

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

            return(View("EmployerDetails/Report", model));
        }
        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
            }));
        }