public async Task UpdateWithNullTagReturnsFailure()
        {
            // Arrange
            SimpleCriteria <Tag> criteria = new SimpleCriteria <Tag>(TestUtility.DefaultAccountId)
            {
                Value = null
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.UpdateAsync(criteria);

            // Assert
            if (result.Success)
            {
                Assert.Fail("Expected update to fail.");
            }
            else
            {
                Assert.IsTrue(
                    String.Compare("Unable to find or access the specified Tag.", result.ErrorMessage) == 0,
                    "Expected error message was not returned.");
            }
        }
        public async Task UpdateWithFailedSaveReturnsFailure()
        {
            // Arrange
            var tag = TestUtility.GetDefaultTag();

            tag.Description = "new description";
            SimpleCriteria <Tag> criteria = new SimpleCriteria <Tag>(TestUtility.DefaultAccountId)
            {
                Value = tag
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            mockContext.Setup(c => c.SaveChangesAsync()).Returns(Task.FromResult(0));
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.UpdateAsync(criteria);

            // Assert
            if (result.Success)
            {
                Assert.Fail("Expected update to fail.");
            }
            else
            {
                Assert.IsTrue(
                    String.Compare("The Tag failed to save.", result.ErrorMessage) == 0,
                    "Expected error message was not returned.");
            }
        }
        public async Task UpdateWithNullCriteriaReturnsFailure()
        {
            // Arrange
            SimpleCriteria <Tag> criteria = null;
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.UpdateAsync(criteria);

            // Assert
            if (result.Success)
            {
                Assert.Fail("Expected update to fail.");
            }
            else
            {
                Assert.IsTrue(
                    String.Compare("Cannot update a tag using a null criteria.", result.ErrorMessage) == 0,
                    "Expected error message was not returned.");
            }
        }
        public async Task <IHttpActionResult> DeleteRecipe(int id)
        {
            // Get the user's account Id.
            var accountIdClaim = this.ClaimsProvider.GetClaim(Utility.AccountIdClaimName);

            if (accountIdClaim == null || String.IsNullOrWhiteSpace(accountIdClaim.Value))
            {
                return(Unauthorized());
            }

            // Create the criteria object and delete.
            var criteria = new SimpleCriteria <int>(accountIdClaim.Value)
            {
                Value = id
            };
            var result = await this.DataManager.DeleteAsync(criteria);

            if (result.Success)
            {
                return(NoContent());
            }
            else
            {
                return(NotFound());
            }
        }
        public async Task ReadManyWithNoResultQueryReturnsSuccessWithEmptyList()
        {
            // Arrange
            var criteria = new SimpleCriteria <EmptyClass>()
            {
                AccountId = String.Concat(TestUtility.DefaultAccountId, "X")
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.ReadManyAsync(criteria);

            // Assert
            if (!result.Success)
            {
                Assert.Fail("Expected read to succeed.");
            }
            else
            {
                Assert.IsTrue(
                    result.Model != null && result.Model.Count == 0,
                    "Expected an empty list.");
            }
        }
        public async Task ReadWithSuccessfulFindReturnsSuccess()
        {
            // Arrange
            var tag      = TestUtility.GetDefaultTag();
            var criteria = new SimpleCriteria <int>(tag.AccountId)
            {
                Value = tag.Id
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.ReadAsync(criteria);

            // Assert
            if (result.Success)
            {
                Assert.IsTrue(TagsMatch(result.Model, tag), "Tag returned was not correct.");
            }
            else
            {
                Assert.Fail("Expected read to succeed.");
            }
        }
        public async Task ReadManyReturnsAllAccountTags()
        {
            // Arrange
            var criteria = new SimpleCriteria <EmptyClass>()
            {
                AccountId = TestUtility.DefaultAccountId
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.ReadManyAsync(criteria);

            // Assert
            if (!result.Success)
            {
                Assert.Fail("Expected read to succeed.");
            }
            else
            {
                Assert.IsTrue(
                    result.Model != null && result.Model.Count == mockTags.Object.Count(t => t.AccountId == TestUtility.DefaultAccountId),
                    "Expected all tags the default account only.");
            }
        }
Example #8
0
        public async Task <IHttpActionResult> GetTag(int id)
        {
            // Get the user's account Id.
            string accountId = GetAccountId();

            if (accountId == null)
            {
                return(Unauthorized());
            }

            // Fetch the Tag.
            var criteria = new SimpleCriteria <int>(accountId)
            {
                Value = id
            };
            var result = await this.DataManager.ReadAsync(criteria);

            if (result.Success)
            {
                return(Ok(result.Model));
            }
            else
            {
                return(NotFound());
            }
        }
        public async Task ReadWithInvalidIdReturnsFailure()
        {
            // Arrange
            var tag      = TestUtility.GetDefaultTag();
            var criteria = new SimpleCriteria <int>(tag.AccountId)
            {
                Value = -1
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.ReadAsync(criteria);

            // Assert
            if (result.Success)
            {
                Assert.Fail("Expected read to fail.");
            }
            else
            {
                Assert.IsTrue(
                    String.Compare("Unable to find or access the specified Tag.", result.ErrorMessage) == 0,
                    "Expected error message was not returned.");
            }
        }
Example #10
0
        public async Task <IHttpActionResult> PutTag(Tag tag)
        {
            // Get the user's account Id.
            string accountId = GetAccountId();

            if (accountId == null)
            {
                return(Unauthorized());
            }

            // Update the Tag.
            var criteria = new SimpleCriteria <Tag>(accountId)
            {
                Value = tag
            };
            var result = await this.DataManager.UpdateAsync(criteria);

            if (result.Success)
            {
                return(Ok(result.Model));
            }
            else
            {
                return(BadRequest(result.ErrorMessage));
            }
        }
Example #11
0
        public async Task <IHttpActionResult> GetAccount(string userName)
        {
            // Get the user's account Id.
            var accountIdClaim = this.ClaimsProvider.GetClaim(Utility.AccountIdClaimName);

            if (accountIdClaim == null || String.IsNullOrWhiteSpace(accountIdClaim.Value))
            {
                return(Unauthorized());
            }

            // Fetch the Account.
            var criteria = new SimpleCriteria <int>(accountIdClaim.Value);
            var result   = await this.DataManager.ReadAsync(criteria);

            if (result == null ||
                !result.Success ||
                result.Model == null ||
                !result.Model.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase))
            {
                return(NotFound());
            }
            else
            {
                return(Ok(result.Model));
            }
        }
Example #12
0
        public async Task <IHttpActionResult> PutAccount(Account account)
        {
            // Get the user's account Id.
            var accountIdClaim = this.ClaimsProvider.GetClaim(Utility.AccountIdClaimName);

            if (accountIdClaim == null || String.IsNullOrWhiteSpace(accountIdClaim.Value))
            {
                return(Unauthorized());
            }

            // Update the account.
            var criteria = new SimpleCriteria <Account>(accountIdClaim.Value)
            {
                Value = account
            };
            var result = await this.DataManager.UpdateAsync(criteria);

            if (result.Success)
            {
                return(Ok(account));
            }
            else
            {
                return(BadRequest("Account was not updated."));
            }
        }
Example #13
0
        public async Task <IHttpActionResult> PutRecipe(Recipe recipe)
        {
            // Get the user's account Id.
            var accountIdClaim = this.ClaimsProvider.GetClaim(Utility.AccountIdClaimName);

            if (accountIdClaim == null || String.IsNullOrWhiteSpace(accountIdClaim.Value))
            {
                return(Unauthorized());
            }

            // Update the Recipe.
            var criteria = new SimpleCriteria <Recipe>(accountIdClaim.Value)
            {
                Value = recipe
            };
            var result = await this.DataManager.UpdateAsync(criteria);

            if (result.Success)
            {
                return(Ok(result.Model));
            }
            else
            {
                return(BadRequest(result.ErrorMessage));
            }
        }
Example #14
0
        public async Task <IHttpActionResult> DeleteTag(int id)
        {
            // Get the user's account Id.
            string accountId = GetAccountId();

            if (accountId == null)
            {
                return(Unauthorized());
            }

            // Create the criteria object and delete.
            var criteria = new SimpleCriteria <int>()
            {
                AccountId = accountId, Value = id
            };
            var result = await this.DataManager.DeleteAsync(criteria);

            if (result.Success)
            {
                return(NoContent());
            }
            else
            {
                return(NotFound());
            }
        }
        public async Task UpdateWithSuccessSavesCorrectData()
        {
            // Arrange
            var tag = TestUtility.GetDefaultTag();

            tag.AccountId   = String.Concat(TestUtility.DefaultAccountId, "XYZ");
            tag.Description = "new description";
            tag.Recipes     = new List <Recipe>()
            {
                new Recipe()
                {
                    Name = "test"
                }
            };
            tag.RowVersion = new byte[5];

            SimpleCriteria <Tag> criteria = new SimpleCriteria <Tag>(TestUtility.DefaultAccountId)
            {
                Value = tag
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            mockContext.Setup(c => c.SaveChangesAsync()).Returns(Task.FromResult(1));
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.UpdateAsync(criteria);

            // Assert
            if (!result.Success)
            {
                Assert.Fail("Expected update to succeed.");
            }
            else if (result.Model == null)
            {
                Assert.Fail("Expected non-null return model.");
            }
            else
            {
                bool correctDataSaved = String.Compare(result.Model.Description, tag.Description) == 0 &&
                                        String.Compare(result.Model.AccountId, tag.AccountId) != 0 &&
                                        (result.Model.Recipes == null || result.Model.Recipes.Count == 0) &&
                                        result.Model.RowVersion == null;
                Assert.IsTrue(correctDataSaved, "Save did not update data correctly.");
            }
        }
        public async Task ReadManyReturnsTagsOrderdByDescription()
        {
            // Arrange
            var criteria = new SimpleCriteria <EmptyClass>()
            {
                AccountId = TestUtility.DefaultAccountId
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.ReadManyAsync(criteria);

            // Assert
            if (!result.Success)
            {
                Assert.Fail("Expected read to succeed.");
            }
            if (result.Model == null || result.Model.Count < 2)
            {
                Assert.Fail("Expected a valid return list.");
            }
            else
            {
                var descriptions = result.Model
                                   .Select(t => t.Description)
                                   .ToArray();
                bool isOrdered = true;
                for (int i = 0; i < descriptions.Length - 1; i++)
                {
                    if (String.Compare(descriptions[i], descriptions[i + 1]) > 0)
                    {
                        isOrdered = false;
                        break;
                    }
                }
                Assert.IsTrue(isOrdered, "Expected retuned list to be ordered by Description.");
            }
        }
        public async Task DeleteWithSuccessfulSaveReturnsSuccess()
        {
            // Arrange
            var tag      = TestUtility.GetDefaultTag();
            var criteria = new SimpleCriteria <int>(tag.AccountId)
            {
                Value = tag.Id
            };
            var mockContext = new Mock <IRecipeBoxContext>();
            var mockTags    = TestUtility.GetTagsDbSet();

            mockContext.Setup(c => c.Tags).Returns(mockTags.Object);
            mockContext.Setup(c => c.SaveChangesAsync()).Returns(Task.FromResult(1));
            var dataManager = new TagDataManager(mockContext.Object);

            // Act
            var result = await dataManager.DeleteAsync(criteria);

            // Assert
            Assert.IsTrue(result.Success, "Expected delete to succeed.");
        }
Example #18
0
        public async Task <IHttpActionResult> GetRecipe(int id)
        {
            // Get the user's account Id.
            var accountIdClaim = this.ClaimsProvider.GetClaim(Utility.AccountIdClaimName);

            if (accountIdClaim == null || String.IsNullOrWhiteSpace(accountIdClaim.Value))
            {
                return(Unauthorized());
            }

            // Fetch the Recipe.
            var criteria = new SimpleCriteria <int>(accountIdClaim.Value)
            {
                Value = id
            };
            var result = await this.DataManager.ReadAsync(criteria);

            if (result == null || !result.Success || result.Model == null)
            {
                return(NotFound());
            }
            return(Ok(result.Model));
        }
Example #19
0
        public async Task <IEnumerable <Tag> > GetTags()
        {
            // Get the user's account Id.
            string accountId = GetAccountId();

            if (accountId == null)
            {
                return(new Tag[0]);
            }

            // Get the data.
            var criteria = new SimpleCriteria <EmptyClass>(accountId);
            var result   = await this.DataManager.ReadManyAsync(criteria);

            // Results
            if (result.Success)
            {
                return(result.Model);
            }
            else
            {
                return(new Tag[0]);
            }
        }
 public SimpleCharacteristicsViewModel(SchoolViewModel school, SimpleCriteria simpleCriteria)
 {
     this.BenchmarkSchool = school;
     this.SimpleCriteria  = simpleCriteria;
 }
        /// <summary>
        /// Step 3 - Simple
        /// </summary>
        /// <param name="urn"></param>
        /// <param name="comparisonType"></param>
        /// <param name="basketSize"></param>
        /// <param name="estType"></param>
        /// <param name="simpleCriteria"></param>
        /// <returns></returns>
        public ActionResult SimpleCharacteristics(int urn, ComparisonType comparisonType, int basketSize, EstablishmentType estType, SimpleCriteria SimpleCriteria)
        {
            ViewBag.URN            = urn;
            ViewBag.ComparisonType = comparisonType;
            ViewBag.BasketSize     = basketSize;
            ViewBag.EstType        = estType;

            var benchmarkSchool = new SchoolViewModel(_contextDataService.GetSchoolByUrn(urn.ToString()), base.ExtractSchoolComparisonListFromCookie());

            var schoolCharsVM = new SimpleCharacteristicsViewModel(benchmarkSchool, SimpleCriteria);

            return(View(schoolCharsVM));
        }
Example #22
0
        /// <summary>
        /// Step 3 - Simple
        /// </summary>
        /// <param name="urn"></param>
        /// <param name="fuid"></param>
        /// <param name="comparisonType"></param>
        /// <param name="estType"></param>
        /// <param name="simpleCriteria"></param>
        /// <returns></returns>
        public async Task <ActionResult> SimpleCharacteristics(long?urn, long?fuid, ComparisonType comparisonType, EstablishmentType?estType, SimpleCriteria SimpleCriteria)
        {
            if (estType.HasValue)
            {
                ViewBag.URN            = urn;
                ViewBag.Fuid           = fuid;
                ViewBag.ComparisonType = comparisonType;
                ViewBag.EstType        = estType;

                EstablishmentViewModelBase benchmarkSchool;

                if (fuid.HasValue)
                {
                    benchmarkSchool = new FederationViewModel(await _contextDataService.GetSchoolDataObjectByUrnAsync(fuid.Value), _benchmarkBasketService.GetSchoolBenchmarkList());
                }
                else
                {
                    benchmarkSchool = new SchoolViewModel(await _contextDataService.GetSchoolDataObjectByUrnAsync(urn.GetValueOrDefault()), _benchmarkBasketService.GetSchoolBenchmarkList());
                }

                var schoolCharsVM = new SimpleCharacteristicsViewModel(benchmarkSchool, SimpleCriteria);
                return(View(schoolCharsVM));
            }
            else
            {
                ViewBag.URN            = urn;
                ViewBag.Fuid           = fuid;
                ViewBag.ComparisonType = comparisonType;

                EstablishmentViewModelBase benchmarkSchool;
                if (fuid.HasValue)
                {
                    benchmarkSchool = new FederationViewModel(await _contextDataService.GetSchoolDataObjectByUrnAsync(fuid.Value), _benchmarkBasketService.GetSchoolBenchmarkList());
                }
                else
                {
                    benchmarkSchool = new SchoolViewModel(await _contextDataService.GetSchoolDataObjectByUrnAsync(urn.GetValueOrDefault()), _benchmarkBasketService.GetSchoolBenchmarkList());
                }

                benchmarkSchool.ErrorMessage = ErrorMessages.SelectSchoolType;

                return(View("SelectSchoolType", benchmarkSchool));
            }
        }
 public BenchmarkCriteria BuildFromSimpleComparisonCriteria(FinancialDataModel benchmarkSchoolData, SimpleCriteria simpleCriteria, int percentageMargin = 0)
 {
     return(BuildFromSimpleComparisonCriteria(benchmarkSchoolData, simpleCriteria.IncludeFsm.GetValueOrDefault(),
                                              simpleCriteria.IncludeSen.GetValueOrDefault(), simpleCriteria.IncludeEal.GetValueOrDefault(),
                                              simpleCriteria.IncludeLa.GetValueOrDefault(), percentageMargin));
 }
Example #24
0
        public async Task <ActionResult> GenerateFromSimpleCriteria(string urn, int basketSize, EstablishmentType estType, SimpleCriteria simpleCriteria)
        {
            var benchmarkSchool = InstantiateBenchmarkSchool(urn);

            var benchmarkCriteria = _benchmarkCriteriaBuilderService.BuildFromSimpleComparisonCriteria(benchmarkSchool.LatestYearFinancialData, simpleCriteria);

            var comparisonResult = await _comparisonService.GenerateBenchmarkListWithSimpleComparisonAsync(benchmarkCriteria, estType, basketSize, simpleCriteria, benchmarkSchool.LatestYearFinancialData);

            var benchmarkSchools = comparisonResult.BenchmarkSchools;

            benchmarkCriteria = comparisonResult.BenchmarkCriteria;

            var cookie = base.UpdateSchoolComparisonListCookie(CompareActions.CLEAR_BENCHMARK_LIST, null);

            Response.Cookies.Add(cookie);

            foreach (var schoolDoc in benchmarkSchools)
            {
                var benchmarkSchoolToAdd = new BenchmarkSchoolViewModel()
                {
                    Name          = schoolDoc.GetPropertyValue <string>("School Name"),
                    Type          = schoolDoc.GetPropertyValue <string>("Type"),
                    FinancialType = schoolDoc.GetPropertyValue <string>("FinanceType") == "A" ? SchoolFinancialType.Academies.ToString() : SchoolFinancialType.Maintained.ToString(),
                    Urn           = schoolDoc.GetPropertyValue <string>("URN")
                };
                cookie = base.UpdateSchoolComparisonListCookie(CompareActions.ADD_TO_COMPARISON_LIST, benchmarkSchoolToAdd);
                Response.Cookies.Add(cookie);
            }

            AddDefaultBenchmarkSchoolToList();

            return(await Index(urn, simpleCriteria, benchmarkCriteria, basketSize, benchmarkSchool.LatestYearFinancialData, estType, ComparisonType.Basic));
        }
Example #25
0
        public async Task <ActionResult> Index(
            string urn,
            SimpleCriteria simpleCriteria,
            BenchmarkCriteria benchmarkCriteria,
            int basketSize = ComparisonListLimit.DEFAULT,
            SchoolFinancialDataModel benchmarkSchoolData = null,
            EstablishmentType searchedEstabType          = EstablishmentType.All,
            ComparisonType comparisonType = ComparisonType.Manual,
            ComparisonArea areaType       = ComparisonArea.All,
            string laCode                  = null,
            RevenueGroupType tab           = RevenueGroupType.Expenditure,
            CentralFinancingType financing = CentralFinancingType.Include)
        {
            ChartGroupType chartGroup;

            switch (tab)
            {
            case RevenueGroupType.Expenditure:
                chartGroup = ChartGroupType.TotalExpenditure;
                break;

            case RevenueGroupType.Income:
                chartGroup = ChartGroupType.TotalIncome;
                break;

            case RevenueGroupType.Balance:
                chartGroup = ChartGroupType.InYearBalance;
                break;

            case RevenueGroupType.Workforce:
                chartGroup = ChartGroupType.Workforce;
                break;

            default:
                chartGroup = ChartGroupType.All;
                break;
            }

            var defaultUnitType = tab == RevenueGroupType.Workforce ? UnitType.AbsoluteCount : UnitType.AbsoluteMoney;
            var benchmarkCharts = await BuildSchoolBenchmarkChartsAsync(tab, chartGroup, defaultUnitType, financing);

            var establishmentType = DetectEstablishmentType(base.ExtractSchoolComparisonListFromCookie());

            var chartGroups = _benchmarkChartBuilder.Build(tab, establishmentType).DistinctBy(c => c.ChartGroup).ToList();

            string selectedArea = "";

            switch (areaType)
            {
            case ComparisonArea.All:
                selectedArea = "All England";
                break;

            case ComparisonArea.LaCode:
            case ComparisonArea.LaName:
                selectedArea = _laService.GetLaName(laCode);
                break;
            }

            string schoolArea = "";

            if (benchmarkSchoolData != null)
            {
                schoolArea = _laService.GetLaName(benchmarkSchoolData.LaNumber.ToString());
            }

            var academiesTerm  = FormatHelpers.FinancialTermFormatAcademies(_financialDataService.GetLatestDataYearPerSchoolType(SchoolFinancialType.Academies));
            var maintainedTerm = FormatHelpers.FinancialTermFormatMaintained(_financialDataService.GetLatestDataYearPerSchoolType(SchoolFinancialType.Maintained));

            var vm = new BenchmarkChartListViewModel(benchmarkCharts, base.ExtractSchoolComparisonListFromCookie(), chartGroups, comparisonType, benchmarkCriteria, simpleCriteria, benchmarkSchoolData, establishmentType, searchedEstabType, schoolArea, selectedArea, academiesTerm, maintainedTerm, areaType, laCode, urn, basketSize);

            ViewBag.Tab               = tab;
            ViewBag.ChartGroup        = chartGroup;
            ViewBag.UnitType          = defaultUnitType;
            ViewBag.HomeSchoolId      = vm.SchoolComparisonList.HomeSchoolUrn;
            ViewBag.EstablishmentType = vm.EstablishmentType;
            ViewBag.Financing         = financing;
            ViewBag.ChartFormat       = ChartFormat.Charts;

            return(View("Index", vm));
        }
 public BenchmarkChartListViewModel(List <ChartViewModel> modelList, ComparisonListModel comparisonList, List <ChartViewModel> chartGroups, ComparisonType comparisonType, BenchmarkCriteria advancedCriteria, SimpleCriteria simpleCriteria, SchoolFinancialDataModel benchmarkSchoolData, EstablishmentType estabType, EstablishmentType searchedEstabType, string schoolArea, string selectedArea, string latestTermAcademies, string latestTermMaintained, ComparisonArea areaType, string laCode, string urn, int basketSize, TrustComparisonViewModel trustComparisonList = null)
 {
     base.SchoolComparisonList      = comparisonList;
     base.ModelList                 = modelList;
     this.ChartGroups               = chartGroups;
     this.AdvancedCriteria          = advancedCriteria;
     this.SimpleCriteria            = simpleCriteria;
     this.ComparisonType            = comparisonType;
     this.BenchmarkSchoolData       = benchmarkSchoolData;
     this.EstablishmentType         = estabType;
     this.SearchedEstablishmentType = searchedEstabType;
     this.SchoolArea                = schoolArea;
     this.SelectedArea              = selectedArea;
     this.TrustComparisonList       = trustComparisonList;
     this.LatestTermAcademies       = latestTermAcademies;
     this.LatestTermMaintained      = latestTermMaintained;
     this.AreaType   = areaType;
     this.LaCode     = laCode;
     this.URN        = urn;
     this.BasketSize = basketSize;
 }
Example #27
0
        public async Task <ComparisonResult> GenerateBenchmarkListWithSimpleComparisonAsync(
            BenchmarkCriteria benchmarkCriteria,
            EstablishmentType estType,
            int basketSize,
            SimpleCriteria simpleCriteria,
            FinancialDataModel defaultSchoolFinancialDataModel,
            bool excludeFeds = true)
        {
            //STEP 1: Straight search with predefined criteria
            var benchmarkSchools = await _financialDataService.SearchSchoolsByCriteriaAsync(benchmarkCriteria, estType, false, excludeFeds);

            if (benchmarkSchools.Count > basketSize) //Original query returns more than required. Clip from top by people count proximity.
            {
                benchmarkSchools             = benchmarkSchools.OrderBy(b => Math.Abs(b.NoPupils.GetValueOrDefault() - defaultSchoolFinancialDataModel.PupilCount.GetValueOrDefault())).Take(basketSize).ToList();
                benchmarkCriteria.MinNoPupil = benchmarkSchools.Min(s => s.NoPupils);
                benchmarkCriteria.MaxNoPupil = benchmarkSchools.Max(s => s.NoPupils); //Update the used criteria to reflect the max and min pupil count of the found schools
            }

            //STEP 2: Original query returns less than required. Expand criteria values gradually and try this max 10 times
            var tryCount = 0;

            while (benchmarkSchools.Count < basketSize)
            {
                if (++tryCount > CriteriaSearchConfig.MAX_TRY_LIMIT) //Max query try reached. Return whatever is found.
                {
                    break;
                }

                benchmarkCriteria = _benchmarkCriteriaBuilderService.BuildFromSimpleComparisonCriteria(defaultSchoolFinancialDataModel, simpleCriteria, tryCount);

                benchmarkSchools = await _financialDataService.SearchSchoolsByCriteriaAsync(benchmarkCriteria, estType, false, excludeFeds);

                if (benchmarkSchools.Count > basketSize) //Number jumping to more than ideal. Cut from top by proximity.
                {
                    benchmarkSchools             = benchmarkSchools.OrderBy(b => Math.Abs(b.NoPupils.GetValueOrDefault() - defaultSchoolFinancialDataModel.PupilCount.GetValueOrDefault())).Take(basketSize).ToList();
                    benchmarkCriteria.MinNoPupil = benchmarkSchools.Min(s => s.NoPupils);
                    benchmarkCriteria.MaxNoPupil = benchmarkSchools.Max(s => s.NoPupils); //Update the criteria to reflect the max and min pupil count of the found schools
                    break;
                }
            }

            //STEP 3: Query return is still less than required. Flex the Urban/Rural criteria gradually. Not applied to federations.
            if (defaultSchoolFinancialDataModel.EstabType != EstablishmentType.Federation)
            {
                tryCount = 1;
                while (benchmarkSchools.Count < basketSize)
                {
                    var urbanRuralDefault = defaultSchoolFinancialDataModel.UrbanRural;
                    var urbanRuralKey     = Dictionaries.UrbanRuralDictionary.First(d => d.Value == urbanRuralDefault).Key;

                    var urbanRuralQuery = Dictionaries.UrbanRuralDictionary.Where(d =>
                                                                                  d.Key >= urbanRuralKey - tryCount && d.Key <= urbanRuralKey + tryCount).Select(d => d.Value).ToArray();

                    benchmarkCriteria.UrbanRural = urbanRuralQuery;

                    benchmarkSchools = await _financialDataService.SearchSchoolsByCriteriaAsync(benchmarkCriteria, estType, false, excludeFeds);

                    if (benchmarkSchools.Count > basketSize) //Number jumping to more than ideal. Cut from top by pupil count proximity.
                    {
                        benchmarkSchools             = benchmarkSchools.OrderBy(b => Math.Abs(b.NoPupils.GetValueOrDefault() - defaultSchoolFinancialDataModel.PupilCount.GetValueOrDefault())).Take(basketSize).ToList();
                        benchmarkCriteria.MinNoPupil = benchmarkSchools.Min(s => s.NoPupils);
                        benchmarkCriteria.MaxNoPupil = benchmarkSchools.Max(s => s.NoPupils); //Update the criteria to reflect the max and min pupil count of the found schools
                        break;
                    }

                    if (urbanRuralQuery.Length == Dictionaries.UrbanRuralDictionary.Count)
                    {
                        break;
                    }

                    tryCount++;
                }
            }

            //STEP 4: For federations, eliminate the schools if both federation and its schools are found
            if (defaultSchoolFinancialDataModel.EstabType == EstablishmentType.Federation)
            {
                var fedSchools = benchmarkSchools.Where(school => !school.IsFederation && school.IsPartOfFederation && benchmarkSchools.Exists(fed => fed.IsFederation && fed.FederationUid == school.FederationUid));
                benchmarkSchools = benchmarkSchools.Except(fedSchools).ToList();
            }

            return(new ComparisonResult()
            {
                BenchmarkSchools = benchmarkSchools,
                BenchmarkCriteria = benchmarkCriteria
            });
        }
Example #28
0
 public SimpleCharacteristicsViewModel(EstablishmentViewModelBase school, SimpleCriteria simpleCriteria)
 {
     this.BenchmarkSchool = school;
     this.SimpleCriteria  = simpleCriteria;
 }
Example #29
0
 public BenchmarkChartListViewModel(List <ChartViewModel> modelList, SchoolComparisonListModel comparisonList, List <ChartViewModel> chartGroups,
                                    ComparisonType comparisonType, BenchmarkCriteria advancedCriteria, SimpleCriteria simpleCriteria, BestInClassCriteria bicCriteria,
                                    FinancialDataModel benchmarkSchoolData, EstablishmentType estabType, EstablishmentType searchedEstabType, string schoolArea, string selectedArea,
                                    string latestTermAcademies, string latestTermMaintained, ComparisonArea areaType, string laCode, long?urn, int basketSize,
                                    TrustComparisonListModel trustComparisonList = null, List <EstablishmentViewModelBase> comparisonSchools = null, bool excludePartial = false)
     : base(modelList, comparisonList)
 {
     this.ChartGroups               = chartGroups;
     this.AdvancedCriteria          = advancedCriteria;
     this.SimpleCriteria            = simpleCriteria;
     this.BicCriteria               = bicCriteria;
     this.ComparisonType            = comparisonType;
     this.BenchmarkSchoolData       = benchmarkSchoolData;
     this.EstablishmentType         = estabType;
     this.SearchedEstablishmentType = searchedEstabType;
     this.SchoolArea           = schoolArea;
     this.SelectedArea         = selectedArea;
     this.TrustComparisonList  = trustComparisonList;
     this.LatestTermAcademies  = latestTermAcademies;
     this.LatestTermMaintained = latestTermMaintained;
     this.AreaType             = areaType;
     this.LaCode            = laCode;
     this.URN               = urn;
     this.BasketSize        = basketSize;
     this.ComparisonSchools = comparisonSchools;
     this.ExcludePartial    = excludePartial;
 }
Example #30
0
        public async Task <ComparisonResult> GenerateBenchmarkListWithSimpleComparisonAsync(
            BenchmarkCriteria benchmarkCriteria, EstablishmentType estType,
            int basketSize,
            SimpleCriteria simpleCriteria, SchoolFinancialDataModel defaultSchoolFinancialDataModel)
        {
            var benchmarkSchools = await _financialDataService.SearchSchoolsByCriteriaAsync(benchmarkCriteria, estType);

            if (benchmarkSchools.Count > basketSize) //Original query returns more than required. Cut from top by proximity.
            {
                benchmarkSchools             = benchmarkSchools.OrderBy(b => Math.Abs(b.GetPropertyValue <int>("No Pupils") - defaultSchoolFinancialDataModel.PupilCount)).Take(basketSize).ToList();
                benchmarkCriteria.MinNoPupil = benchmarkSchools.Min(s => s.GetPropertyValue <int>("No Pupils"));
                benchmarkCriteria.MaxNoPupil = benchmarkSchools.Max(s => s.GetPropertyValue <int>("No Pupils")); //Update the criteria to reflect the max and min pupil count of the found schools
            }

            var tryCount = 0;

            while (benchmarkSchools.Count < basketSize)              //Original query returns less than required
            {
                if (++tryCount > CriteriaSearchConfig.MAX_TRY_LIMIT) //Max query try reached. Return whatever is found.
                {
                    break;
                }

                benchmarkCriteria = _benchmarkCriteriaBuilderService.BuildFromSimpleComparisonCriteria(defaultSchoolFinancialDataModel, simpleCriteria, tryCount);

                benchmarkSchools = await _financialDataService.SearchSchoolsByCriteriaAsync(benchmarkCriteria, estType);

                if (benchmarkSchools.Count > basketSize) //Number jumping to more than ideal. Cut from top by proximity.
                {
                    benchmarkSchools             = benchmarkSchools.OrderBy(b => Math.Abs(b.GetPropertyValue <int>("No Pupils") - defaultSchoolFinancialDataModel.PupilCount)).Take(basketSize).ToList();
                    benchmarkCriteria.MinNoPupil = benchmarkSchools.Min(s => s.GetPropertyValue <int>("No Pupils"));
                    benchmarkCriteria.MaxNoPupil = benchmarkSchools.Max(s => s.GetPropertyValue <int>("No Pupils")); //Update the criteria to reflect the max and min pupil count of the found schools
                    break;
                }
            }

            tryCount = 1;
            while (benchmarkSchools.Count < basketSize) //Query return is still less than required
            {
                var urbanRuralDefault = defaultSchoolFinancialDataModel.UrbanRural;
                var urbanRuralKey     = Dictionaries.UrbanRuralDictionary.First(d => d.Value == urbanRuralDefault).Key;

                var urbanRuralQuery = Dictionaries.UrbanRuralDictionary.Where(d =>
                                                                              d.Key >= urbanRuralKey - tryCount && d.Key <= urbanRuralKey + tryCount).Select(d => d.Value).ToArray();

                benchmarkCriteria.UrbanRural = urbanRuralQuery;

                benchmarkSchools = await _financialDataService.SearchSchoolsByCriteriaAsync(benchmarkCriteria, estType);

                if (benchmarkSchools.Count > basketSize) //Number jumping to more than ideal. Cut from top by proximity.
                {
                    benchmarkSchools             = benchmarkSchools.OrderBy(b => Math.Abs(b.GetPropertyValue <int>("No Pupils") - defaultSchoolFinancialDataModel.PupilCount)).Take(basketSize).ToList();
                    benchmarkCriteria.MinNoPupil = benchmarkSchools.Min(s => s.GetPropertyValue <int>("No Pupils"));
                    benchmarkCriteria.MaxNoPupil = benchmarkSchools.Max(s => s.GetPropertyValue <int>("No Pupils")); //Update the criteria to reflect the max and min pupil count of the found schools
                    break;
                }

                if (urbanRuralQuery.Length == Dictionaries.UrbanRuralDictionary.Count)
                {
                    break;
                }

                tryCount++;
            }

            return(new ComparisonResult()
            {
                BenchmarkSchools = benchmarkSchools,
                BenchmarkCriteria = benchmarkCriteria
            });
        }