public FinancialDataModel(string id, string term, SchoolTrustFinancialDataObject financialDataObject, EstablishmentType estabType)
 {
     Id   = id;
     Term = term;
     FinancialDataObjectModel = financialDataObject;
     EstabType = estabType;
 }
Exemple #2
0
 public BenchmarkSchoolModel(SchoolTrustFinancialDataObject schoolFinanceData)
 {
     Name      = schoolFinanceData.SchoolName ?? schoolFinanceData.FederationName;
     Type      = schoolFinanceData.Type;
     EstabType = schoolFinanceData.FinanceType;
     Urn       = schoolFinanceData.URN.ToString();
 }
        private async Task <List <FinancialDataModel> > GetFinancialDataHistoricallyAsync(int companyNo, MatFinancingType matFinancing)
        {
            var models     = new List <FinancialDataModel>();
            var latestYear = await _financialDataService.GetLatestDataYearPerEstabTypeAsync(EstablishmentType.MAT);

            var taskList = new List <Task <SchoolTrustFinancialDataObject> >();

            for (int i = ChartHistory.YEARS_OF_HISTORY - 1; i >= 0; i--)
            {
                var term = SchoolFormatHelpers.FinancialTermFormatAcademies(latestYear - i);
                var task = _financialDataService.GetTrustFinancialDataObjectByCompanyNoAsync(companyNo, term, matFinancing);
                taskList.Add(task);
            }

            for (int i = ChartHistory.YEARS_OF_HISTORY - 1; i >= 0; i--)
            {
                var term         = SchoolFormatHelpers.FinancialTermFormatAcademies(latestYear - i);
                var taskResult   = await taskList[ChartHistory.YEARS_OF_HISTORY - 1 - i];
                var resultObject = taskResult;

                if (resultObject != null && resultObject.DidNotSubmit)
                {
                    var emptyObj = new SchoolTrustFinancialDataObject();
                    emptyObj.DidNotSubmit = true;
                    resultObject          = emptyObj;
                }

                models.Add(new FinancialDataModel(companyNo.ToString(), term, resultObject, EstablishmentType.MAT));
            }

            return(models);
        }
        private async Task AddAssessmentAreasToModel(string termYears, SchoolTrustFinancialDataObject schoolFinancialData, EdubaseDataObject schoolContextData, SelfAssesmentModel model)
        {
            model.SadAssesmentAreas = new(); //C#9

            await AddAssessmentArea("Spending", "Teaching staff", schoolFinancialData?.TeachingStaff.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Spending", "Supply staff", schoolFinancialData?.SupplyStaff.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Spending", "Education support staff", schoolFinancialData?.EducationSupportStaff.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Spending", "Administrative and clerical staff", schoolFinancialData?.AdministrativeClericalStaff.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Spending", "Other staff costs", schoolFinancialData?.OtherStaffCosts.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Spending", "Premises costs", schoolFinancialData?.Premises.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Spending", "Educational supplies", schoolFinancialData?.EducationalSupplies.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Spending", "Energy", schoolFinancialData?.Energy.GetValueOrDefault(), schoolFinancialData?.TotalExpenditure.GetValueOrDefault(), schoolFinancialData, model, termYears);

            await AddAssessmentArea("Reserve and balance", "In-year balance", schoolFinancialData?.InYearBalance.GetValueOrDefault(), schoolFinancialData?.TotalIncome.GetValueOrDefault(), schoolFinancialData, model, termYears);
            await AddAssessmentArea("Reserve and balance", "Revenue reserve", schoolFinancialData?.RevenueReserve.GetValueOrDefault(), schoolFinancialData?.TotalIncome.GetValueOrDefault(), schoolFinancialData, model, termYears);

            await AddAssessmentArea("School characteristics", "Average teacher cost", null, null, schoolFinancialData, model, termYears);
            await AddAssessmentArea("School characteristics", "Senior leaders as a percentage of workforce", null, null, schoolFinancialData, model, termYears);;;
            await AddAssessmentArea("School characteristics", "Pupil to teacher ratio", null, null, schoolFinancialData, model, termYears);
            await AddAssessmentArea("School characteristics", "Pupil to adult ratio", null, null, schoolFinancialData, model, termYears);

            if (!_exclusionPhaseList.Contains(schoolFinancialData?.OverallPhase ?? schoolContextData.OverallPhase))
            {
                await AddAssessmentArea("School characteristics", "Teacher contact ratio (less than 1)", null, null, schoolFinancialData, model, termYears);
            }

            await AddAssessmentArea("School characteristics", "Predicted percentage pupil number change in 3-5 years", null, null, schoolFinancialData, model, termYears);

            if (!_exclusionPhaseList.Contains(schoolFinancialData?.OverallPhase ?? schoolContextData.OverallPhase))
            {
                await AddAssessmentArea("School characteristics", "Average Class size", null, null, schoolFinancialData, model, termYears);
            }
        }
        private string GetProgressScoreType(SchoolTrustFinancialDataObject schoolFinancialData)
        {
            if (schoolFinancialData.Phase is "Nursery" or "Infant and junior") //C#9
            {
                if (schoolFinancialData.Ks2Progress is not null)               //C#9
                {
                    return("KS2 score");
                }

                return(null);
            }

            if (schoolFinancialData.Phase is "Special" or "Pupil referral unit")
            {
                if (schoolFinancialData.Progress8Measure is not null)
                {
                    return("Progress 8 score");
                }

                if (schoolFinancialData.Ks2Progress is not null)
                {
                    return("KS2 score");
                }

                return(null);
            }

            if (schoolFinancialData.OverallPhase is "All-through")
            {
                return("All-through");
            }

            return(schoolFinancialData.OverallPhase == "Secondary" ? "Progress 8 score" : "KS2 score");
        }
        public void BuildShouldApplyPercentageMarginForNumberOfPupils()
        {
            dynamic model = new EdubaseDataObject();

            model.NumberOfPupils = 100;

            var financeObj = new SchoolTrustFinancialDataObject();

            financeObj.NoPupils             = 100;
            financeObj.OverallPhase         = "Secondary";
            financeObj.UrbanRural           = "Urban and city";
            financeObj.PercentageFSM        = 100;
            financeObj.PercentagePupilsWSEN = 100;
            financeObj.PercentagePupilsWEAL = 100;
            financeObj.LA = 831;

            var benchmarkSchool = new SchoolViewModel(model);

            benchmarkSchool.HistoricalFinancialDataModels = new List <FinancialDataModel>();
            benchmarkSchool.HistoricalFinancialDataModels.Add(new FinancialDataModel("123", "2014-2015", financeObj, EstablishmentType.Maintained));

            var builder = new BenchmarkCriteriaBuilderService();

            var criteria = builder.BuildFromSimpleComparisonCriteria(benchmarkSchool.HistoricalFinancialDataModels.Last(), true, true, true, true, 5);

            Assert.AreEqual((financeObj.NoPupils - CriteriaSearchConfig.QC_DEFAULT_CONSTANT_PUPIL_COUNT_TOPUP) * 0.85m, criteria.MinNoPupil);
            Assert.AreEqual((financeObj.NoPupils + CriteriaSearchConfig.QC_DEFAULT_CONSTANT_PUPIL_COUNT_TOPUP) * 1.15m, criteria.MaxNoPupil);
        }
        public void BuildShouldApplyUrbanRuralToCriteria()
        {
            dynamic model = new EdubaseDataObject();

            model.NumberOfPupils = 100;

            var financeObj = new SchoolTrustFinancialDataObject();

            financeObj.NoPupils             = 100;
            financeObj.OverallPhase         = "Secondary";
            financeObj.UrbanRural           = "Urban and city";
            financeObj.PercentageFSM        = 100;
            financeObj.PercentagePupilsWSEN = 100;
            financeObj.PercentagePupilsWEAL = 100;
            financeObj.LA = 831;

            var benchmarkSchool = new SchoolViewModel(model);

            benchmarkSchool.HistoricalFinancialDataModels = new List <FinancialDataModel>();
            benchmarkSchool.HistoricalFinancialDataModels.Add(new FinancialDataModel("123", "2014-2015", financeObj, EstablishmentType.Maintained));

            var builder = new BenchmarkCriteriaBuilderService();

            var criteria = builder.BuildFromSimpleComparisonCriteria(benchmarkSchool.HistoricalFinancialDataModels.Last(), true, true, true, true, 0);

            Assert.AreEqual(financeObj.UrbanRural, criteria.UrbanRural[0]);
        }
        public void BuildShouldNotApplyOptionalCriteriaIfNotIncluded()
        {
            dynamic model = new EdubaseDataObject();

            model.NumberOfPupils = 100;

            var financeObj = new SchoolTrustFinancialDataObject();

            financeObj.NoPupils             = 100;
            financeObj.OverallPhase         = "Secondary";
            financeObj.UrbanRural           = "Urban and city";
            financeObj.PercentageFSM        = 2;
            financeObj.PercentagePupilsWSEN = 2;
            financeObj.PercentagePupilsWEAL = 2;
            financeObj.LA = 831;

            var benchmarkSchool = new SchoolViewModel(model);

            benchmarkSchool.HistoricalFinancialDataModels = new List <FinancialDataModel>();
            benchmarkSchool.HistoricalFinancialDataModels.Add(new FinancialDataModel("123", "2014-2015", financeObj, EstablishmentType.Maintained));

            var builder = new BenchmarkCriteriaBuilderService();

            var criteria = builder.BuildFromSimpleComparisonCriteria(benchmarkSchool.HistoricalFinancialDataModels.Last(), false, false, false, false, 10);

            Assert.AreEqual(null, criteria.MinPerFSM);
            Assert.AreEqual(null, criteria.MaxPerFSM);
            Assert.AreEqual(null, criteria.MinPerSEN);
            Assert.AreEqual(null, criteria.MaxPerSEN);
            Assert.AreEqual(null, criteria.MinPerEAL);
            Assert.AreEqual(null, criteria.MaxPerEAL);
            Assert.AreEqual(null, criteria.LocalAuthorityCode);
        }
        private Decimal?GetFinancialDataValueForChartField(string chartFieldName, SchoolTrustFinancialDataObject dataObject)
        {
            if (dataObject == null)
            {
                return(null);
            }

            return((Decimal?)typeof(SchoolTrustFinancialDataObject).GetProperties()
                   .First(p => (p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).First() as JsonPropertyAttribute).PropertyName == chartFieldName)
                   .GetValue(dataObject));
        }
        public async Task GenerateBenchmarkListWithSimpleComparisonAsyncShouldExpandTheUrbanRuralIfNotEnoughSchoolsFound()
        {
            var mockFinancialDataService = new Mock <IFinancialDataService>();
            var testResult = new SchoolTrustFinancialDataObject();

            testResult.URN         = 321;
            testResult.SchoolName  = "test";
            testResult.FinanceType = "Academies";
            testResult.UrbanRural  = "Town and fringe";
            Task <List <SchoolTrustFinancialDataObject> > task = Task.Run(() =>
            {
                return(new List <SchoolTrustFinancialDataObject> {
                    testResult
                });
            });

            mockFinancialDataService.Setup(m => m.SearchSchoolsByCriteriaAsync(It.IsAny <BenchmarkCriteria>(), It.IsAny <EstablishmentType>(), false, true))
            .Returns((BenchmarkCriteria criteria, EstablishmentType estType, bool excludePartial, bool excludeFeds) => task);

            var mockContextDataService = new Mock <IContextDataService>();

            var mockBenchmarkCriteriaBuilderService = new Mock <IBenchmarkCriteriaBuilderService>();

            mockBenchmarkCriteriaBuilderService.Setup(s => s.BuildFromSimpleComparisonCriteria(It.IsAny <FinancialDataModel>(), It.IsAny <SimpleCriteria>(), It.IsAny <int>()))
            .Returns((FinancialDataModel dm, SimpleCriteria sc, int percentage) => new BenchmarkCriteria()
            {
                Gender = new[] { "Male" }
            });
            mockBenchmarkCriteriaBuilderService.Setup(s => s.BuildFromSimpleComparisonCriteriaExtended(It.IsAny <FinancialDataModel>(), It.IsAny <SimpleCriteria>(), It.IsAny <int>()))
            .Returns((FinancialDataModel dm, SimpleCriteria sc, int percentage) => new BenchmarkCriteria()
            {
                Gender = new[] { "Male" }
            });

            var service = new ComparisonService(mockFinancialDataService.Object, mockBenchmarkCriteriaBuilderService.Object);

            var comparisonResult = await service.GenerateBenchmarkListWithSimpleComparisonAsync(new BenchmarkCriteria()
            {
                Gender = new [] { "Male" }
            },
                                                                                                EstablishmentType.Maintained, 15, new SimpleCriteria(), new FinancialDataModel("123", "14-15", testResult, EstablishmentType.Maintained));

            mockFinancialDataService.Verify(s => s.SearchSchoolsByCriteriaAsync(It.IsAny <BenchmarkCriteria>(), EstablishmentType.Maintained, false, true), Times.AtLeast(11));
            Assert.AreEqual(5, comparisonResult.BenchmarkCriteria.UrbanRural.Length);
            Assert.IsTrue(comparisonResult.BenchmarkCriteria.UrbanRural.Contains("Rural and village"));
            Assert.IsTrue(comparisonResult.BenchmarkCriteria.UrbanRural.Contains("Town and fringe"));
            Assert.IsTrue(comparisonResult.BenchmarkCriteria.UrbanRural.Contains("Urban and city"));
            Assert.IsTrue(comparisonResult.BenchmarkCriteria.UrbanRural.Contains("Hamlet and isolated dwelling"));
            Assert.IsTrue(comparisonResult.BenchmarkCriteria.UrbanRural.Contains("Conurbation"));
        }
        public async Task <List <SchoolTrustFinancialDataObject> > GetMultipleTrustFinancialDataObjectsAsync(List <int> companyNoList, string term, MatFinancingType matFinance)
        {
            var dataGroup = EstablishmentType.MAT.ToDataGroup(matFinance);

            var collectionName = await _dataCollectionManager.GetCollectionIdByTermByDataGroupAsync(term, dataGroup);

            if (collectionName == null)
            {
                return(null);
            }

            var container = _client.GetContainer(_databaseId, collectionName);

            var queryString = $"SELECT * FROM c WHERE c['{SchoolTrustFinanceDataFieldNames.COMPANY_NUMBER}'] in ({string.Join(",", companyNoList)})";

            var queryDefinition = new QueryDefinition(queryString);

            var feedIterator = container.GetItemQueryIterator <SchoolTrustFinancialDataObject>(queryDefinition, null);

            var resultsList = new List <SchoolTrustFinancialDataObject>();

            while (feedIterator.HasMoreResults)
            {
                foreach (var item in await feedIterator.ReadNextAsync())
                {
                    resultsList.Add(item);
                }
            }

            try
            {
                resultsList.ForEach(result => {
                    if (result.DidNotSubmit)
                    {
                        var emptyObj          = new SchoolTrustFinancialDataObject();
                        emptyObj.DidNotSubmit = true;
                        result = emptyObj;
                    }
                });
            }
            catch (Exception ex)
            {
                var errorMessage = $"{collectionName} could not be loaded! : {ex.Message} : URNs = {string.Join(",", companyNoList)}";
                base.LogException(ex, errorMessage);
                throw new ApplicationException($"One or more documents could not be loaded from {collectionName} : URNs = {string.Join(",", companyNoList)}");
            }

            return(resultsList);
        }
        public async Task GenerateBenchmarkListWithBestInClassComparisonAsyncShouldNotExpandWhenNotEnoughSchoolsFound()
        {
            var testResult = new SchoolTrustFinancialDataObject();

            testResult.URN            = 321;
            testResult.SchoolName     = "test";
            testResult.FinanceType    = "Maintained";
            testResult.UrbanRural     = "Town and fringe";
            testResult.RevenueReserve = 10;
            testResult.TotalIncome    = 100;
            Task <List <SchoolTrustFinancialDataObject> > task = Task.Run(() =>
            {
                var results = new List <SchoolTrustFinancialDataObject>();
                for (var i = 0; i < 51; i++)
                {
                    results.Add(testResult);
                }

                return(results);
            });

            var mockFinancialDataService = new Mock <IFinancialDataService>();

            mockFinancialDataService.Setup(m => m.SearchSchoolsByCriteriaAsync(It.IsAny <BenchmarkCriteria>(), It.IsAny <EstablishmentType>(), true, true))
            .Returns((BenchmarkCriteria criteria, EstablishmentType estType, bool excludePartial, bool excludeFeds) => task);

            var mockBenchmarkCriteriaBuilderService = new Mock <IBenchmarkCriteriaBuilderService>();

            mockBenchmarkCriteriaBuilderService.Setup(s => s.BuildFromBicComparisonCriteria(It.IsAny <FinancialDataModel>(), It.IsAny <BestInClassCriteria>(), It.IsAny <int>()))
            .Returns((FinancialDataModel dm, BestInClassCriteria bic, int percentage) => new BenchmarkCriteria()
            {
                Gender = new[] { "Male" }
            });

            var service = new ComparisonService(mockFinancialDataService.Object, mockBenchmarkCriteriaBuilderService.Object);

            var comparisonResult = await service.GenerateBenchmarkListWithBestInClassComparisonAsync(EstablishmentType.Maintained, new BenchmarkCriteria()
            {
                Gender = new[] { "Male" }
            },
                                                                                                     new BestInClassCriteria(), new FinancialDataModel("123", "14-15", testResult, EstablishmentType.Maintained));

            mockFinancialDataService.Verify(s => s.SearchSchoolsByCriteriaAsync(It.IsAny <BenchmarkCriteria>(), EstablishmentType.Maintained, true, true), Times.Exactly(1));
            Assert.AreEqual(15, comparisonResult.BenchmarkSchools.Count);
        }
        public void PopulateHistoricalChartsWithFinancialDataGeneratesJSONWithCorrectYearLabels()
        {
            List <ChartViewModel> historicalCharts = new List <ChartViewModel>()
            {
                new ChartViewModel()
                {
                    Name       = "Special Facilities",
                    FieldName  = "Special facilities",
                    TabType    = Helpers.Enums.TabType.Expenditure,
                    ChartGroup = Helpers.Enums.ChartGroupType.SpecialFacilities,
                },
                new ChartViewModel()
                {
                    Name       = "Education Support Staff",
                    FieldName  = "Education support staff",
                    TabType    = Helpers.Enums.TabType.Expenditure,
                    ChartGroup = Helpers.Enums.ChartGroupType.Staff,
                }
            };

            var financialObj = new SchoolTrustFinancialDataObject();

            financialObj.Specialfacilities     = 1000;
            financialObj.EducationSupportStaff = 2000;
            financialObj.NoPupils   = 100;
            financialObj.NoTeachers = 10;

            var dataModels = new List <FinancialDataModel>()
            {
                new FinancialDataModel("123", "2014 / 2015", financialObj, EstablishmentType.Maintained)
            };

            var mockLaService = new Mock <ILocalAuthoritiesService>();

            mockLaService.Setup(m => m.GetLocalAuthorities()).Returns(() => "[{\"id\": \"0\",\"LANAME\": \"Hartlepool\",\"REGION\": \"1\",\"REGIONNAME\": \"North East A\"}]");

            var service = new FinancialCalculationsService(mockLaService.Object);

            service.PopulateHistoricalChartsWithFinancialData(historicalCharts, dataModels, "2014 / 2015", Helpers.Enums.TabType.Expenditure, Helpers.Enums.UnitType.AbsoluteMoney, EstablishmentType.Maintained);

            var historicalChartData = JsonConvert.DeserializeObject <List <HistoricalChartData> >(historicalCharts[0].DataJson);

            Assert.AreEqual("2014-15", historicalChartData[0].Year);
        }
        public void PopulateHistoricalChartsWithFinancialDataCalculatesAmountsByPercentage()
        {
            List <ChartViewModel> historicalCharts = new List <ChartViewModel>()
            {
                new ChartViewModel()
                {
                    Name       = "Special Facilities",
                    FieldName  = "Special facilities",
                    TabType    = Helpers.Enums.TabType.Expenditure,
                    ChartGroup = Helpers.Enums.ChartGroupType.SpecialFacilities,
                },
                new ChartViewModel()
                {
                    Name       = "Education Support Staff",
                    FieldName  = "Education support staff",
                    TabType    = Helpers.Enums.TabType.Expenditure,
                    ChartGroup = Helpers.Enums.ChartGroupType.Staff,
                }
            };

            var financialObj = new SchoolTrustFinancialDataObject();

            financialObj.Specialfacilities     = 1000;
            financialObj.EducationSupportStaff = 2000;
            financialObj.NoPupils         = 100;
            financialObj.NoTeachers       = 10;
            financialObj.TotalExpenditure = 5000;

            var dataModels = new List <FinancialDataModel>()
            {
                new FinancialDataModel("123", "2014 / 2015", financialObj, EstablishmentType.Maintained)
            };

            var mockLaService = new Mock <ILocalAuthoritiesService>();

            mockLaService.Setup(m => m.GetLocalAuthorities()).Returns(() => "[{\"id\": \"0\",\"LANAME\": \"Hartlepool\",\"REGION\": \"1\",\"REGIONNAME\": \"North East A\"}]");

            var service = new FinancialCalculationsService(mockLaService.Object);

            service.PopulateHistoricalChartsWithFinancialData(historicalCharts, dataModels, "2014 / 2015", Helpers.Enums.TabType.Expenditure, Helpers.Enums.UnitType.PercentageOfTotalExpenditure, EstablishmentType.Academies);

            Assert.AreEqual(20, historicalCharts[0].LastYearBalance);
            Assert.AreEqual(40, historicalCharts[1].LastYearBalance);
        }
        public async Task <SchoolTrustFinancialDataObject> GetTrustFinancialDataObjectByMatNameAsync(string matName, string term, MatFinancingType matFinance)
        {
            var dataGroup = EstablishmentType.MAT.ToDataGroup(matFinance);

            var collectionName = await _dataCollectionManager.GetCollectionIdByTermByDataGroupAsync(term, dataGroup);

            if (collectionName == null)
            {
                return(null);
            }

            var container = _client.GetContainer(_databaseId, collectionName);

            var queryString = $"SELECT * FROM c WHERE c['{SchoolTrustFinanceDataFieldNames.TRUST_COMPANY_NAME}']=@matName";

            var queryDefinition = new QueryDefinition(queryString)
                                  .WithParameter($"@matName", matName);

            var feedIterator = container.GetItemQueryIterator <SchoolTrustFinancialDataObject>(queryDefinition, null);

            try
            {
                var result = (await feedIterator.ReadNextAsync()).FirstOrDefault();

                if (result != null && result.DidNotSubmit)
                {
                    var emptyObj = new SchoolTrustFinancialDataObject();
                    emptyObj.DidNotSubmit = true;
                    return(emptyObj);
                }
                return(result);
            }
            catch (Exception ex)
            {
                if (term.Contains(_dataCollectionManager.GetLatestFinancialDataYearPerEstabTypeAsync(EstablishmentType.MAT).ToString()))
                {
                    var errorMessage = $"{collectionName} could not be loaded! : {ex.Message} : {queryDefinition.QueryText}";
                    base.LogException(ex, errorMessage);
                }
                return(null);
            }
        }
        private async Task AddAssessmentArea(string areaType, string areaName, decimal?schoolData, decimal?totalForAreaType, SchoolTrustFinancialDataObject schoolFinancialData, SelfAssesmentModel model, string termYears)
        {
            List <SADSchoolRatingsDataObject> ratings = await _selfAssesmentDashboardDataService.GetSADSchoolRatingsDataObjectAsync(areaName, schoolFinancialData?.OverallPhase, bool.Parse(schoolFinancialData?.Has6Form ?? "false"), schoolFinancialData?.LondonWeight, model.SadSizeLookup?.SizeType, model.SadFSMLookup?.FSMScale, termYears);

            ratings = ratings.OrderBy(t => t.ScoreLow).ToList();
            model.SadAssesmentAreas.Add(new SadAssesmentAreaModel(areaType, areaName, schoolData, totalForAreaType, ratings));
        }
        private async Task <SelfAssesmentModel> BuildSelfAssesmentModel(long id, string name, EstablishmentType financeType, EdubaseDataObject schoolContextData, SchoolTrustFinancialDataObject schoolFinancialData)
        {
            string termYears = await GetLatestTermYears(financeType);

            SelfAssesmentModel model;

            if (schoolFinancialData is not null)
            {
                model = new SelfAssesmentModel(
                    id,
                    name,
                    schoolFinancialData.OverallPhase,
                    financeType.ToString(),
                    schoolFinancialData.LondonWeight,
                    schoolFinancialData.NoPupils.GetValueOrDefault(),
                    schoolFinancialData.PercentageFSM.GetValueOrDefault(),
                    schoolContextData.OfstedRating,
                    FormatOfstedDate(schoolContextData.OfstedLastInsp),
                    schoolFinancialData.Progress8Measure,
                    schoolFinancialData.Ks2Progress,
                    GetProgressScoreType(schoolFinancialData),
                    schoolFinancialData.Progress8Banding.GetValueOrDefault(),
                    bool.Parse(schoolFinancialData.Has6Form),
                    schoolFinancialData.TotalExpenditure.GetValueOrDefault(),
                    schoolFinancialData.TotalIncome.GetValueOrDefault(),
                    termYears,
                    schoolFinancialData.TeachersTotal.GetValueOrDefault(),
                    schoolFinancialData.TeachersLeader.GetValueOrDefault(),
                    schoolFinancialData.WorkforceTotal.GetValueOrDefault(),
                    schoolFinancialData.PeriodCoveredByReturn >= 12,
                    true
                    );

                model.SadSizeLookup = await _selfAssesmentDashboardDataService.GetSADSizeLookupDataObject(schoolFinancialData.OverallPhase, bool.Parse(schoolFinancialData.Has6Form), schoolFinancialData.NoPupils.GetValueOrDefault(), termYears);

                model.SadFSMLookup = await _selfAssesmentDashboardDataService.GetSADFSMLookupDataObject(schoolFinancialData.OverallPhase, bool.Parse(schoolFinancialData.Has6Form), schoolFinancialData.PercentageFSM.GetValueOrDefault(), termYears);

                model.AvailableScenarioTerms = await GetAllAvailableTermYears();
            }
            else
            {
                model = new SelfAssesmentModel(id, name, schoolContextData.OverallPhase, financeType.ToString(), schoolContextData.OfstedRating,
                                               FormatOfstedDate(schoolContextData.OfstedLastInsp),
                                               schoolContextData.GovernmentOfficeRegion,
                                               schoolContextData.OfficialSixthForm);

                model.AvailableScenarioTerms = await GetAllAvailableTermYears();
            }

            await AddAssessmentAreasToModel(termYears, schoolFinancialData, schoolContextData, model);

            return(model);
        }
        public async Task DoNotAskForOverwriteStrategyIfOnlyBenchmarkSchoolInListAsync()
        {
            var mockCookieManager        = new Mock <ISchoolBenchmarkListService>();
            var fakeSchoolComparisonList = new SchoolComparisonListModel();

            fakeSchoolComparisonList.HomeSchoolUrn  = "100";
            fakeSchoolComparisonList.HomeSchoolName = "home school";
            fakeSchoolComparisonList.BenchmarkSchools.Add(new BenchmarkSchoolModel()
            {
                Name = "test", Urn = "100"
            });

            mockCookieManager.Setup(m => m.GetSchoolBenchmarkList()).Returns(fakeSchoolComparisonList);

            var _mockDocumentDbService = new Mock <IFinancialDataService>();
            var testResult             = new SchoolTrustFinancialDataObject();

            testResult.URN        = 321;
            testResult.SchoolName = "test";
            Task <List <SchoolTrustFinancialDataObject> > task = Task.Run(() =>
            {
                return(new List <SchoolTrustFinancialDataObject> {
                    testResult
                });
            });

            _mockDocumentDbService.Setup(m => m.SearchSchoolsByCriteriaAsync(It.IsAny <BenchmarkCriteria>(), It.IsAny <EstablishmentType>(), false, true))
            .Returns((BenchmarkCriteria criteria, EstablishmentType estType, bool excludePartial, bool excludeFeds) => task);

            Task <int> GetLatestFinancialDataYearPerEstabTypeAsyncTask = Task.Run(() => {
                return(2015);
            });

            var _mockDataCollectionManager = new Mock <IDataCollectionManager>();

            _mockDataCollectionManager.Setup(m => m.GetLatestFinancialDataYearPerEstabTypeAsync(It.IsAny <EstablishmentType>()))
            .Returns(GetLatestFinancialDataYearPerEstabTypeAsyncTask);

            var _mockEdubaseDataService = new Mock <IContextDataService>();
            Task <EdubaseDataObject> GetSchoolDataObjectByUrnAsyncTask = Task.Run(() => {
                return(new EdubaseDataObject
                {
                    URN = 100,
                    EstablishmentName = "test"
                });
            });

            _mockEdubaseDataService.Setup(m => m.GetSchoolDataObjectByUrnAsync(100)).Returns((string urn) => GetSchoolDataObjectByUrnAsyncTask);

            var mockComparisonService = new Mock <IComparisonService>();

            var controller = new BenchmarkCriteriaController(null, _mockDocumentDbService.Object, _mockEdubaseDataService.Object, null, mockCookieManager.Object, mockComparisonService.Object, new ValidationService());

            var result = await controller.OverwriteStrategy(10000, ComparisonType.Advanced, EstablishmentType.Maintained, new BenchmarkCriteriaVM(new BenchmarkCriteria()
            {
                Gender = new[] { "Boys" }
            }), ComparisonArea.All, 306, "test", 10);

            Assert.AreEqual("BenchmarkCharts", (result as RedirectToRouteResult).RouteValues["Controller"]);
            Assert.AreEqual("GenerateNewFromAdvancedCriteria", (result as RedirectToRouteResult).RouteValues["Action"]);
        }