public async Task <IActionResult> OnGetAsync(string specificationId)
        {
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));

            SpecificationId = specificationId;

            Specification specification = await GetSpecification(specificationId);

            IsAuthorizedToEdit =
                await _authorizationHelper.DoesUserHavePermission(User, specification,
                                                                  SpecificationActionTypes.CanEditSpecification);

            if (specification != null)
            {
                FundingPeriodName = specification.FundingPeriod.Name;

                FundingPeriodId = specification.FundingPeriod.Id;

                SpecificationName = specification.Name;

                PopulatePolicies(specification);
            }

            return(Page());
        }
示例#2
0
        public async Task <IActionResult> OnGetAsync(string specificationId)
        {
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));

            SpecificationId = specificationId;

            SpecificationSummary specification = await GetSpecification(specificationId);

            IsAuthorizedToEdit =
                await _authorizationHelper.DoesUserHavePermission(User, specification,
                                                                  SpecificationActionTypes.CanEditSpecification);

            if (specification != null)
            {
                SpecificationName = specification.Name;

                FundingPeriodName = specification.FundingPeriod.Name;

                FundingPeriodId = specification.FundingPeriod.Id;

                return(Page());
            }
            else
            {
                throw new InvalidOperationException($"Unable to retreive specification");
            }
        }
        public async Task <IActionResult> SaveTimetable([FromBody] ReleaseTimetableViewModel viewModel)
        {
            if (!await _authorizationHelper.DoesUserHavePermission(
                    User,
                    viewModel.SpecificationId,
                    SpecificationActionTypes.CanEditSpecification))
            {
                return(new ForbidResult());
            }

            SpecificationPublishDateModel publishData = new SpecificationPublishDateModel
            {
                EarliestPaymentAvailableDate = viewModel.FundingDate,
                ExternalPublicationDate      = viewModel.StatementDate
            };

            HttpStatusCode publish =
                await _specificationsApiClient.SetPublishDates(viewModel.SpecificationId, publishData);

            if (publish == HttpStatusCode.OK)
            {
                return(new OkObjectResult(publishData));
            }

            if (publish == HttpStatusCode.BadRequest)
            {
                return(new BadRequestObjectResult(
                           Content("There was a problem with the data submitted. Please check and try again.")));
            }

            return(new NotFoundObjectResult(Content("Error. Not Found.")));
        }
示例#4
0
        public async Task <IActionResult> OnGetAsync(string specificationId)
        {
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));

            ApiResponse <Specification> specificationResponse = await _specsClient.GetSpecification(specificationId);

            if (specificationResponse.StatusCode == HttpStatusCode.OK && specificationResponse.Content != null)
            {
                EditSpecificationViewModel = _mapper.Map <EditSpecificationViewModel>(specificationResponse.Content);
                IsAuthorizedToEdit         = await _authorizationHelper.DoesUserHavePermission(User,
                                                                                               specificationResponse.Content, SpecificationActionTypes.CanEditSpecification);

                EditSpecificationViewModel.OriginalSpecificationName = specificationResponse.Content.Name;
                EditSpecificationViewModel.OriginalFundingStreams    = string.Join(",", EditSpecificationViewModel.FundingStreamIds);
                EditSpecificationViewModel.OriginalFundingPeriodId   = EditSpecificationViewModel.FundingPeriodId;

                await TaskHelper.WhenAllAndThrow(PopulateFundingPeriods(EditSpecificationViewModel.FundingPeriodId), PopulateFundingStreams(EditSpecificationViewModel.FundingStreamIds));

                return(Page());
            }
            else
            {
                throw new InvalidOperationException($"Unable to retreive specification. Status Code = {specificationResponse.StatusCode}");
            }
        }
示例#5
0
        public async Task <IActionResult> SaveCalculation(string specificationId, string calculationId, [FromBody] CalculationUpdateViewModel vm)
        {
            Guard.ArgumentNotNull(specificationId, nameof(specificationId));
            Guard.ArgumentNotNull(calculationId, nameof(calculationId));
            Guard.ArgumentNotNull(vm, nameof(vm));

            if (!await _authorizationHelper.DoesUserHavePermission(User, specificationId, SpecificationActionTypes.CanEditCalculations))
            {
                return(new ForbidResult());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CalculationUpdateModel    update   = _mapper.Map <CalculationUpdateModel>(vm);
            ApiResponse <Calculation> response = await _calcClient.UpdateCalculation(calculationId, update);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(Ok(response.Content));
            }
            else
            {
                throw new InvalidOperationException($"An error occurred while saving calculation. Status code={response.StatusCode}");
            }
        }
示例#6
0
        public async Task <IActionResult> OnGetAsync(string relationshipId)
        {
            Guard.IsNullOrWhiteSpace(relationshipId, nameof(relationshipId));

            ApiResponse <SelectDataSourceModel> sourcesResponse = await _datasetClient.GetDatasourcesByRelationshipId(relationshipId);

            if (sourcesResponse.StatusCode != HttpStatusCode.OK || sourcesResponse.Content == null)
            {
                _logger.Error($"Failed to fetch data sources with status code {sourcesResponse.StatusCode.ToString()}");
                return(NotFound());
            }

            IsAuthorizedToMap = await _authorizationHelper.DoesUserHavePermission(User, sourcesResponse.Content, SpecificationActionTypes.CanMapDatasets);

            SelectDataSourceViewModel viewModel = PopulateViewModel(sourcesResponse.Content);

            if (viewModel == null)
            {
                return(new StatusCodeResult(500));
            }

            ViewModel = viewModel;

            return(Page());
        }
        public async Task <IActionResult> CreateTestScenario(string specificationId, [FromBody] ScenarioCreateViewModel vm)
        {
            Guard.ArgumentNotNull(specificationId, nameof(specificationId));
            Guard.ArgumentNotNull(vm, nameof(vm));

            if (!await _authorizationHelper.DoesUserHavePermission(User, specificationId, SpecificationActionTypes.CanCreateQaTests))
            {
                return(new ForbidResult());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CreateScenarioModel createScenario = _mapper.Map <CreateScenarioModel>(vm);

            createScenario.SpecificationId = specificationId;

            ApiResponse <TestScenario> result = await _scenariosClient.CreateTestScenario(createScenario);

            if (result.StatusCode == HttpStatusCode.OK)
            {
                return(Ok(result.Content));
            }
            else
            {
                HttpStatusCode statusCode = result.StatusCode;

                _logger.Error("An error occurred while saving scenario. Status code from backend={statusCode} for specification {specificationId}", statusCode, specificationId);

                throw new InvalidOperationException($"An error occurred while saving scenario. Status code={result.StatusCode}");
            }
        }
示例#8
0
        public async Task <IActionResult> UpdateApprovalStatusForAllocationLine([FromRoute] string specificationId, [FromBody] PublishedAllocationLineResultStatusUpdateViewModel allocationLines)
        {
            Guard.ArgumentNotNull(allocationLines, nameof(allocationLines));

            if (allocationLines.Status != AllocationLineStatusViewModel.Approved && allocationLines.Status != AllocationLineStatusViewModel.Published)
            {
                ModelState.AddModelError(nameof(allocationLines.Status), "The status provided is not a valid destination status");
            }

            SpecificationActionTypes permissionRequired = allocationLines.Status == AllocationLineStatusViewModel.Approved ? SpecificationActionTypes.CanApproveFunding : SpecificationActionTypes.CanPublishFunding;

            if (!await _authorizationHelper.DoesUserHavePermission(User, specificationId, permissionRequired))
            {
                return(new ForbidResult());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            PublishedAllocationLineResultStatusUpdateModel updateModel = new PublishedAllocationLineResultStatusUpdateModel()
            {
                Status = _mapper.Map <AllocationLineStatus>(allocationLines.Status),
            };

            Dictionary <string, PublishedAllocationLineResultStatusUpdateProviderModel> updateProviders = new Dictionary <string, PublishedAllocationLineResultStatusUpdateProviderModel>();

            foreach (PublishedAllocationLineResultStatusUpdateProviderViewModel updateItem in allocationLines.Providers)
            {
                PublishedAllocationLineResultStatusUpdateProviderModel providerUpdateModel = null;
                if (!updateProviders.ContainsKey(updateItem.ProviderId))
                {
                    providerUpdateModel = new PublishedAllocationLineResultStatusUpdateProviderModel()
                    {
                        ProviderId = updateItem.ProviderId,
                    };

                    updateProviders.Add(updateItem.ProviderId, providerUpdateModel);
                    updateModel.AddProvider(providerUpdateModel);
                }
                else
                {
                    providerUpdateModel = updateProviders[updateItem.ProviderId];
                }

                providerUpdateModel.AddAllocationLine(updateItem.AllocationLineId);
            }

            await _resultsClient.UpdatePublishedAllocationLineStatus(specificationId, updateModel);

            return(Ok());
        }
        public async Task <IActionResult> OnGetAsync(string specificationId, string subPolicyId, string parentPolicyId)
        {
            Guard.IsNullOrWhiteSpace(subPolicyId, nameof(subPolicyId));
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));
            Guard.IsNullOrWhiteSpace(parentPolicyId, nameof(parentPolicyId));

            SpecificationId = specificationId;
            ParentPolicyId  = parentPolicyId;

            (Specification specification, IActionResult error)specificationQuery = await GetSpecification(specificationId);

            if (specificationQuery.error != null)
            {
                return(specificationQuery.error);
            }

            Specification specification = specificationQuery.specification;

            IsAuthorizedToEdit =
                await _authorizationHelper.DoesUserHavePermission(User, specification,
                                                                  SpecificationActionTypes.CanEditSpecification);

            PopulateSpecificationProperites(specification);

            foreach (Policy policy in specification.Policies)
            {
                if (!policy.SubPolicies.IsNullOrEmpty())
                {
                    if (policy.Id == parentPolicyId)
                    {
                        Policy subPolicy = policy.SubPolicies.FirstOrDefault(m => m.Id == subPolicyId);

                        if (subPolicy != null)
                        {
                            if (subPolicy.Id == subPolicyId)
                            {
                                this.EditSubPolicyViewModel = _mapper.Map <EditSubPolicyViewModel>(subPolicy);
                            }
                        }
                    }
                }
            }

            if (EditSubPolicyViewModel == null)
            {
                return(NotFound("Sub Policy not found"));
            }

            return(Page());
        }
示例#10
0
        public async Task <IActionResult> OnGetAsync(string specificationId, bool wasSuccess = false)
        {
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));

            ShowSuccessMessage = wasSuccess;

            ApiResponse <SpecificationSummary> specificationResponse = await _specsApiClient.GetSpecificationSummary(specificationId);

            if (specificationResponse.StatusCode != HttpStatusCode.OK)
            {
                _logger.Error($"Failed to fetch specification with status code {specificationResponse.StatusCode.ToString()}");
                return(new StatusCodeResult((int)specificationResponse.StatusCode));
            }

            IsAuthorizedToMap = await _authorizationHelper.DoesUserHavePermission(User, specificationResponse.Content,
                                                                                  SpecificationActionTypes.CanMapDatasets);

            SpecificationDatasetRelationshipsViewModel viewModel = await PopulateViewModel(specificationResponse.Content);

            if (viewModel == null)
            {
                _logger.Error($"A null view model was returned");
                return(new StatusCodeResult(500));
            }

            ViewModel = viewModel;

            return(Page());
        }
        public async Task OnGet_WhenUserDoesHaveEditCalculationsPermission_ThenDoesUserHavePermissionToApproveOrEditIsTrue()
        {
            // Arrange
            string      calculationId    = "5";
            Calculation calcsCalculation = new Calculation()
            {
                SpecificationId          = "abc123",
                CalculationSpecification = new Reference {
                    Id = "cs345", Name = "calc name"
                }
            };

            ICalculationsApiClient calcsClient = Substitute.For <ICalculationsApiClient>();

            calcsClient
            .GetCalculationById(calculationId)
            .Returns(new ApiResponse <Calculation>(System.Net.HttpStatusCode.OK, calcsCalculation));

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <ISpecificationAuthorizationEntity>(), Arg.Is(SpecificationActionTypes.CanEditCalculations))
            .Returns(true);

            EditCalculationPageModel pageModel = CreatePageModel(calcsClient: calcsClient, authorizationHelper: authorizationHelper);

            // Act
            IActionResult result = await pageModel.OnGet("5");

            // Assert
            pageModel.DoesUserHavePermissionToApproveOrEdit.Should().Be("true");
        }
示例#12
0
        public async Task EditSpecificationStatus_WhenUserDoesNotHaveApproveSpecificationPermission_ThenReturn403()
        {
            //Arrange
            string specificationId = "5";

            PublishStatusEditModel model = new PublishStatusEditModel();

            PublishStatusResult publishStatusResult = new PublishStatusResult();

            ValidatedApiResponse <PublishStatusResult> response = new ValidatedApiResponse <PublishStatusResult>(HttpStatusCode.OK, publishStatusResult);

            ISpecsApiClient specsClient = Substitute.For <ISpecsApiClient>();

            specsClient
            .UpdatePublishStatus(Arg.Is(specificationId), Arg.Is(model))
            .Returns(response);

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper.DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanApproveSpecification))
            .Returns(false);
            SpecificationController controller = CreateSpecificationController(specsClient, authorizationHelper);

            // Act
            IActionResult result = await controller.EditSpecificationStatus(specificationId, model);

            // Assert
            result.Should().BeOfType <ForbidResult>();
        }
示例#13
0
        public async Task EditCalculationStatus_GivenUserDoesNotHaveEditCalculationPermission_Returns403()
        {
            //Arrange
            string specificationId = "abc123";
            string calculationId   = "5";

            PublishStatusEditModel model = new PublishStatusEditModel();

            PublishStatusResult publishStatusResult = new PublishStatusResult();

            ValidatedApiResponse <PublishStatusResult> response = new ValidatedApiResponse <PublishStatusResult>(HttpStatusCode.OK, publishStatusResult);

            ICalculationsApiClient calcsClient = Substitute.For <ICalculationsApiClient>();

            calcsClient
            .UpdatePublishStatus(Arg.Is(calculationId), Arg.Is(model))
            .Returns(response);

            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper.DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanEditCalculations))
            .Returns(false);

            CalculationController controller = CreateCalculationController(calcsClient, mapper, authorizationHelper);

            // Act
            IActionResult result = await controller.EditCalculationStatus(specificationId, calculationId, model);

            // Assert
            result.Should().BeOfType <ForbidResult>();
        }
示例#14
0
        internal static IAuthorizationHelper CreateAuthorizationHelperSubstitute(string specificationId, SpecificationActionTypes permissionRequired)
        {
            IAuthorizationHelper authHelper = Substitute.For <IAuthorizationHelper>();

            authHelper.DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(permissionRequired)).Returns(true);
            return(authHelper);
        }
        public async Task UpdateApprovalStatusForAllocationLine_ThenCallEndpointToScheduleJob()
        {
            // Arrange
            string specificationId = "abc123";

            PublishedAllocationLineResultStatusUpdateViewModel model = new PublishedAllocationLineResultStatusUpdateViewModel
            {
                Status    = AllocationLineStatusViewModel.Approved,
                Providers = new List <PublishedAllocationLineResultStatusUpdateProviderViewModel>()
            };

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanApproveFunding))
            .Returns(true);

            IResultsApiClient resultsClient = CreateResultsClient();

            ApprovalController controller = CreateApprovalController(resultsClient: resultsClient, authorizationHelper: authorizationHelper);

            // Act
            IActionResult result = await controller.UpdateApprovalStatusForAllocationLine(specificationId, model);

            // Assert
            result.Should().BeOfType <OkResult>();

            await resultsClient
            .Received(1)
            .UpdatePublishedAllocationLineStatus(Arg.Is(specificationId), Arg.Any <PublishedAllocationLineResultStatusUpdateModel>());
        }
        public async Task UpdateApprovalStatusForAllocationLine_WhenUserDoesHavePublishFundingPermission_ThenActionAllowed()
        {
            // Arrange
            string specificationId = "abc123";

            PublishedAllocationLineResultStatusUpdateViewModel model = new PublishedAllocationLineResultStatusUpdateViewModel
            {
                Status    = AllocationLineStatusViewModel.Published,
                Providers = new List <PublishedAllocationLineResultStatusUpdateProviderViewModel>()
            };

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanPublishFunding))
            .Returns(true);

            IResultsApiClient resultsClient = CreateResultsClient();

            resultsClient
            .UpdatePublishedAllocationLineStatusByBatch(Arg.Is(specificationId), Arg.Any <PublishedAllocationLineResultStatusUpdateModel>())
            .Returns(new ValidatedApiResponse <PublishedAllocationLineResultStatusUpdateResponseModel>(HttpStatusCode.OK, new PublishedAllocationLineResultStatusUpdateResponseModel()));

            ApprovalController controller = CreateApprovalController(resultsClient: resultsClient, authorizationHelper: authorizationHelper);

            // Act
            IActionResult result = await controller.UpdateApprovalStatusForAllocationLine(specificationId, model);

            // Assert
            result.Should().BeOfType <OkResult>();
        }
示例#17
0
        public async Task OnPostAsync_GivenUserDoesNotHaveEditSpecificationPermission_ThenForbidResultReturned()
        {
            // Arrange
            ISpecsApiClient specsClient = Substitute.For <ISpecsApiClient>();

            specsClient
            .GetSpecification(Arg.Is(specificationId))
            .Returns(new ApiResponse <Specification>(HttpStatusCode.OK, new Specification {
                Id = specificationId
            }));

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <ISpecificationAuthorizationEntity>(), Arg.Is(SpecificationActionTypes.CanEditSpecification))
            .Returns(false);

            EditSpecificationPageModel pageModel = CreatePageModel(specsClient: specsClient, authorizationHelper: authorizationHelper);

            // Act
            IActionResult result = await pageModel.OnPostAsync(specificationId);

            // Assert
            pageModel
            .IsAuthorizedToEdit
            .Should().BeFalse();

            result.Should().BeOfType <ForbidResult>();
        }
        public async Task OnPostAsync_GivenUserDoesNotHaveMapDatasetsPermission_Returns403()
        {
            // Arrange
            SelectDataSourceModel sourceModel = new SelectDataSourceModel();

            ApiResponse <SelectDataSourceModel> sourcesResponse = new ApiResponse <SelectDataSourceModel>(HttpStatusCode.OK, sourceModel);

            IDatasetsApiClient datasetsApiClient = CreateDatasetsApiClient();

            datasetsApiClient
            .GetDatasourcesByRelationshipId(Arg.Is(relationshipId))
            .Returns(sourcesResponse);

            ILogger logger = CreateLogger();

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <ISpecificationAuthorizationEntity>(), Arg.Is(SpecificationActionTypes.CanMapDatasets))
            .Returns(false);

            SelectSourceDatasetPageModel pageModel = CreatePageModel(datasetsApiClient, logger, authorizationHelper);

            // Act
            IActionResult result = await pageModel.OnPostAsync(relationshipId, specificationId);

            //Assert
            result
            .Should()
            .BeOfType <ForbidResult>();

            pageModel
            .IsAuthorizedToMap
            .Should().BeFalse();
        }
        internal static IAuthorizationHelper CreateAuthorizationHelperSubstitute(SpecificationActionTypes permissionRequired, bool returns = true)
        {
            IAuthorizationHelper authHelper = Substitute.For <IAuthorizationHelper>();

            authHelper.DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <ISpecificationAuthorizationEntity>(), Arg.Is(permissionRequired)).Returns(returns);
            return(authHelper);
        }
示例#20
0
        public async Task ApproveAllCalculations_GivenApproveAllCalculationsReturnsBadRequest_ThrowsInvalidOperationException()
        {
            //Arrange

            string specificationId             = "abc123";
            ICalculationsApiClient calcsClient = Substitute.For <ICalculationsApiClient>();

            calcsClient
            .QueueApproveAllSpecificationCalculations(Arg.Is(specificationId))
            .Returns(new ApiResponse <Job>(HttpStatusCode.BadRequest));

            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper.DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanApproveAllCalculations))
            .Returns(true);

            CalculationController controller = CreateCalculationController(calcsClient, mapper, authorizationHelper, resultsApiClient);

            // Act
            Action a = new Action(() =>
            {
                IActionResult result = controller.ApproveAllCalculations(specificationId).Result;
            });

            // Assert
            a.Should().Throw <InvalidOperationException>();
        }
        public async Task CreateTestScenario_WhenUserDoesHaveCreateQaTestPermission_ThenActionAllowed()
        {
            // Arrange
            string specificationId = "abc123";

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanCreateQaTests))
            .Returns(true);

            IScenariosApiClient scenariosClient = CreateScenariosClient();

            scenariosClient
            .CreateTestScenario(Arg.Any <CreateScenarioModel>())
            .Returns(new ApiResponse <TestScenario>(HttpStatusCode.OK, new TestScenario()));

            ScenarioController controller = CreateScenarioController(authorizationHelper: authorizationHelper, scenariosClient: scenariosClient);

            // Act
            IActionResult result = await controller.CreateTestScenario(specificationId, new ScenarioCreateViewModel());

            // Assert
            result.Should().BeOfType <OkObjectResult>();
        }
        private async Task <IActionResult> PopulateForm(Specification specification)
        {
            IsAuthorizedtoEdit =
                await _authorizationHelper.DoesUserHavePermission(User, specification,
                                                                  SpecificationActionTypes.CanEditSpecification);

            IActionResult populateResult = await PopulateAllocationLines(specification.Id);

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

            if (AllocationLines.IsNullOrEmpty())
            {
                return(new InternalServerErrorResult($"Failed to load allocation lines for specification id: {specification.Id}"));
            }

            PopulatePolicies(specification);

            PopulateCalculationTypes();

            ApiResponse <IEnumerable <CalculationCurrentVersion> > baselinesQuery = await _specsClient.GetBaselineCalculationsBySpecificationId(specification.Id);

            IActionResult baselinesError = baselinesQuery.IsSuccessOrReturnFailureResult("Calculation baselines");

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

            IEnumerable <string> hiddenAllocationLineIds;

            if (baselinesQuery.Content.AnyWithNullCheck())
            {
                hiddenAllocationLineIds = baselinesQuery.Content.Select(s => s.AllocationLine?.Id).Where(s => !string.IsNullOrWhiteSpace(s));
            }
            else
            {
                hiddenAllocationLineIds = Enumerable.Empty <string>();
            }

            HideAllocationLinesForBaselinesJson = JsonConvert.SerializeObject(hiddenAllocationLineIds);
            AvailableBaselineAllocationLineIds  = AllocationLines.Count() - hiddenAllocationLineIds.Count();

            return(Page());
        }
        public async Task <IActionResult> OnGetAsync(string specificationId, string calculationId)
        {
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));

            Specification specification = await GetSpecification(specificationId);

            if (specification != null)
            {
                IsAuthorizedToEdit = await _authorizationHelper.DoesUserHavePermission(User, specification, SpecificationActionTypes.CanEditSpecification);

                ApiResponse <CalculationCurrentVersion> calculationResult = await _specsClient.GetCalculationById(specificationId, calculationId);

                if (calculationResult == null)
                {
                    _logger.Error("Calculation Result API response returned null for calculation ID '{calculationId}' on specificationId '{specificationId}'", calculationId, specificationId);

                    return(new InternalServerErrorResult("Calculation Result API response returned null"));
                }

                if (calculationResult.StatusCode == HttpStatusCode.NotFound)
                {
                    return(new NotFoundObjectResult("Calculation not found"));
                }
                else if (calculationResult.StatusCode != HttpStatusCode.OK)
                {
                    _logger.Warning($"Unexpected status code from Calculation API call '{calculationResult.StatusCode}'");
                    return(new InternalServerErrorResult($"Unexpected status code from Calculation API call '{calculationResult.StatusCode}'"));
                }

                Calculation calculation = calculationResult.Content;
                if (calculation == null)
                {
                    _logger.Warning("Calculation Result API response content returned null for calculation ID '{calculationId}' on specificationId '{specificationId}'", calculationId, specificationId);

                    return(new InternalServerErrorResult("Calculation content returned null"));
                }

                EditCalculationViewModel = _mapper.Map <EditCalculationViewModel>(calculation);

                return(await PopulateForm(specification, calculationId));
            }
            else
            {
                return(new PreconditionFailedResult("Specification not found"));
            }
        }
示例#24
0
 private void SetupAuthorizedUser(SpecificationActionTypes specificationActionType)
 {
     _authorizationHelper.DoesUserHavePermission(
         _specificationController.User,
         Arg.Any <string>(),
         specificationActionType)
     .Returns(true);
 }
示例#25
0
        public async Task <IActionResult> EditSpecificationStatus(string specificationId, [FromBody] PublishStatusEditModel publishStatusEditModel)
        {
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));
            Guard.ArgumentNotNull(publishStatusEditModel, nameof(publishStatusEditModel));

            if (!await _authorizationHelper.DoesUserHavePermission(User, specificationId, SpecificationActionTypes.CanApproveSpecification))
            {
                return(new ForbidResult());
            }

            ValidatedApiResponse <PublishStatusResult> response = await _specsClient.UpdatePublishStatus(specificationId, publishStatusEditModel);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                return(Ok(response.Content));
            }

            throw new InvalidOperationException($"An error occurred while retrieving code context. Status code={response.StatusCode}");
        }
        private static IAuthorizationHelper CreateMockAuthenticationHelper(bool authUser = true)
        {
            IAuthorizationHelper mockAuthorizationHelper = Substitute.For <IAuthorizationHelper>();

            mockAuthorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <ISpecificationAuthorizationEntity>(), Arg.Is(SpecificationActionTypes.CanMapDatasets))
            .Returns(authUser);

            return(mockAuthorizationHelper);
        }
        public void OnPost_WhenModelIsInvalidAndDatasetDefinitionListReturnedIsNull_ShoulThrowInvalidOperationException()
        {
            // Arrange
            string anyString = "anyString";

            string expectedSpecificationId = "spec123";

            SpecificationSummary expectedSpecification = new SpecificationSummary()
            {
                FundingPeriod = new Reference(anyString, anyString),
                Name          = anyString,
                Description   = anyString
            };

            ISpecsApiClient mockSpecsClient = Substitute.For <ISpecsApiClient>();

            mockSpecsClient
            .GetSpecificationSummary(Arg.Is(expectedSpecificationId))
            .Returns(new ApiResponse <SpecificationSummary>(HttpStatusCode.OK, expectedSpecification));

            IDatasetsApiClient mockDatasetsApiClient = Substitute.For <IDatasetsApiClient>();

            mockDatasetsApiClient
            .GetDataDefinitions()
            .Returns(new ApiResponse <IEnumerable <DatasetDefinition> >(HttpStatusCode.OK));
            mockDatasetsApiClient
            .AssignDatasetSchema(Arg.Any <AssignDatasetSchemaModel>())
            .Returns(HttpStatusCode.OK);

            IAuthorizationHelper mockAuthorizationHelper = Substitute.For <IAuthorizationHelper>();

            mockAuthorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <ISpecificationAuthorizationEntity>(), Arg.Is(SpecificationActionTypes.CanEditSpecification))
            .Returns(true);

            AssignDatasetSchemaPageModel datasetSchemaPageModel = CreatePageModel(specsClient: mockSpecsClient,
                                                                                  authorizationHelper: mockAuthorizationHelper, datasetsClient: mockDatasetsApiClient, mapper: MappingHelper.CreateFrontEndMapper());

            datasetSchemaPageModel.AssignDatasetSchemaViewModel = new AssignDatasetSchemaViewModel();
            datasetSchemaPageModel.ModelState.AddModelError(anyString, anyString);

            // Act
            Func <Task <IActionResult> > postAction = async() => await datasetSchemaPageModel.OnPostAsync(expectedSpecificationId);

            // Assert
            postAction
            .Should()
            .Throw <InvalidOperationException>()
            .Which
            .Message
            .Should().Be(
                $"Unable to retrieve Dataset definition from the response. Specification Id value = {expectedSpecificationId}");
        }
        public async Task OnPost_WhenModelIsInvalidAndUserIsUnauthorizedToEditSpecification_ShouldReturnForbidResult()
        {
            // Arrange
            const string anyString = "any";
            string       expectedSpecificationId = "spec123";
            const string fundingPeriodId         = "2018";
            const string fundingPeriodName       = "1819";

            const string specificationName = "Pe and sports spec";
            const string specDescription   = "test spec";

            SpecificationSummary expectedSpecification = new SpecificationSummary()
            {
                FundingPeriod = new Reference(fundingPeriodId, fundingPeriodName),
                Name          = specificationName,
                Description   = specDescription
            };

            ISpecsApiClient mockSpecsClient = Substitute.For <ISpecsApiClient>();

            mockSpecsClient
            .GetSpecificationSummary(Arg.Is(expectedSpecificationId))
            .Returns(new ApiResponse <SpecificationSummary>(HttpStatusCode.OK, expectedSpecification));

            IDatasetsApiClient mockDatasetsApiClient = Substitute.For <IDatasetsApiClient>();

            mockDatasetsApiClient
            .GetDataDefinitions()
            .Returns(new ApiResponse <IEnumerable <DatasetDefinition> >(HttpStatusCode.OK, GetDummyDataDefinitions()));
            mockDatasetsApiClient
            .AssignDatasetSchema(Arg.Any <AssignDatasetSchemaModel>())
            .Returns(HttpStatusCode.OK);

            IAuthorizationHelper mockAuthorizationHelper = Substitute.For <IAuthorizationHelper>();

            mockAuthorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <ISpecificationAuthorizationEntity>(), Arg.Is(SpecificationActionTypes.CanEditSpecification))
            .Returns(false);

            AssignDatasetSchemaPageModel datasetSchemaPageModel = CreatePageModel(specsClient: mockSpecsClient,
                                                                                  authorizationHelper: mockAuthorizationHelper, datasetsClient: mockDatasetsApiClient, mapper: MappingHelper.CreateFrontEndMapper());

            datasetSchemaPageModel.AssignDatasetSchemaViewModel = new AssignDatasetSchemaViewModel();
            datasetSchemaPageModel.ModelState.AddModelError(anyString, anyString);

            // Act
            IActionResult result = await datasetSchemaPageModel.OnPostAsync(expectedSpecificationId);

            // Assert
            result
            .Should().BeOfType <ForbidResult>();
        }
        public async Task OnPostAsync_GivenUserDoesNotHaveCreateSpecificationPermissionForAnyFundingStream_ThenReturnsForbidResult()
        {
            // Arrange
            IEnumerable <Reference> fundingPeriods = new[]
            {
                new Reference {
                    Id = "fp1", Name = "Funding Period 1"
                },
                new Reference {
                    Id = "fp2", Name = "Funding Period 2"
                }
            };

            IEnumerable <FundingStream> fundingStreams = new[]
            {
                new FundingStream {
                    Id = "fp1", Name = "funding"
                }
            };

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <IEnumerable <string> >(), Arg.Is(FundingStreamActionTypes.CanCreateSpecification))
            .Returns(false);

            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            CreateSpecificationViewModel createModel = new CreateSpecificationViewModel
            {
                Description      = "Test spec",
                FundingPeriodId  = "FY1819",
                FundingStreamIds = new List <string> {
                    "fs1", "fs2"
                },
                Name = "Test spec"
            };

            CreateSpecificationPageModel pageModel = CreatePageModel(authorizationHelper: authorizationHelper, mapper: mapper);

            pageModel.CreateSpecificationViewModel = createModel;

            // Act
            IActionResult result = await pageModel.OnPostAsync();

            // Assert
            result.Should().BeOfType <ForbidResult>();

            pageModel
            .IsAuthorizedToCreate
            .Should().BeFalse();
        }
        public async Task <IActionResult> OnGet(string calculationId)
        {
            if (string.IsNullOrWhiteSpace(calculationId))
            {
                return(new BadRequestObjectResult(ErrorMessages.CalculationIdNullOrEmpty));
            }

            ViewData["GreyBackground"] = ShouldNewEditCalculationPageBeEnabled.ToString();

            ApiResponse <Calculation> calculation = await _calcClient.GetCalculationById(calculationId);

            if (calculation == null || calculation.StatusCode != HttpStatusCode.OK)
            {
                return(new NotFoundObjectResult(ErrorMessages.CalculationNotFoundInCalcsService));
            }

            this.DoesUserHavePermissionToApproveOrEdit = (await _authorizationHelper.DoesUserHavePermission(User, calculation.Content, SpecificationActionTypes.CanEditCalculations)).ToString().ToLowerInvariant();

            ApiResponse <Clients.SpecsClient.Models.CalculationCurrentVersion> specCalculation = await _specsClient.GetCalculationById(calculation.Content.SpecificationId, calculation.Content.CalculationSpecification.Id);

            if (specCalculation == null || specCalculation.StatusCode == HttpStatusCode.NotFound)
            {
                return(new NotFoundObjectResult(ErrorMessages.CalculationNotFoundInSpecsService));
            }

            Calculation             = _mapper.Map <CalculationViewModel>(calculation.Content);
            Calculation.Description = specCalculation.Content.Description;
            SpecificationId         = calculation.Content.SpecificationId;
            EditModel = _mapper.Map <CalculationEditViewModel>(calculation.Content);

            ApiResponse <Clients.SpecsClient.Models.SpecificationSummary> specificationResponse = await _specsClient.GetSpecificationSummary(SpecificationId);

            if (specificationResponse != null && specificationResponse.StatusCode == HttpStatusCode.OK)
            {
                SpecificationName = specificationResponse.Content.Name;
            }
            else
            {
                SpecificationName = "Unknown";
            }

            if (ShouldNewEditCalculationPageBeEnabled)
            {
                ApiResponse <bool> hasCalculationResponse = await _resultsApiClient.HasCalculationResults(Calculation.Id);

                if (hasCalculationResponse != null && hasCalculationResponse.StatusCode == HttpStatusCode.OK)
                {
                    CalculationHasResults = hasCalculationResponse.Content;
                }
            }
            return(Page());
        }