public async Task <IActionResult> SaveFundingTemplate(string actionName, string controllerName, string template, string fundingStreamId, string fundingPeriodId, string templateVersion)
        {
            Guard.IsNullOrWhiteSpace(actionName, nameof(actionName));
            Guard.IsNullOrWhiteSpace(controllerName, nameof(controllerName));
            Guard.IsNullOrWhiteSpace(fundingStreamId, nameof(fundingStreamId));
            Guard.IsNullOrWhiteSpace(fundingPeriodId, nameof(fundingPeriodId));
            Guard.IsNullOrWhiteSpace(templateVersion, nameof(templateVersion));

            //Already checked for null above when getting body
            if (template.Trim() == string.Empty)
            {
                return(new BadRequestObjectResult("Null or empty funding template was provided."));
            }

            FundingTemplateValidationResult validationResult = await _fundingTemplateValidationService.ValidateFundingTemplate(template, fundingStreamId, fundingPeriodId, templateVersion);

            if (!validationResult.IsValid)
            {
                return(validationResult.AsBadRequest());
            }

            ITemplateMetadataGenerator templateMetadataGenerator = _templateMetadataResolver.GetService(validationResult.SchemaVersion);

            ValidationResult validationGeneratorResult = templateMetadataGenerator.Validate(template);

            if (!validationGeneratorResult.IsValid)
            {
                return(validationGeneratorResult.PopulateModelState());
            }

            string blobName = GetBlobNameFor(validationResult.FundingStreamId, validationResult.FundingPeriodId, validationResult.TemplateVersion);

            try
            {
                byte[] templateFileBytes = Encoding.UTF8.GetBytes(template);

                await SaveFundingTemplateVersion(blobName, templateFileBytes);

                string cacheKey = $"{CacheKeys.FundingTemplatePrefix}{validationResult.FundingStreamId}-{validationResult.FundingPeriodId}-{validationResult.TemplateVersion}".ToLowerInvariant();
                await _cacheProviderPolicy.ExecuteAsync(() => _cacheProvider.RemoveAsync <string>(cacheKey));

                await _cacheProviderPolicy.ExecuteAsync(() => _cacheProvider.RemoveAsync <FundingTemplateContents>($"{CacheKeys.FundingTemplateContents}{validationResult.FundingStreamId}:{validationResult.FundingPeriodId}:{validationResult.TemplateVersion}".ToLowerInvariant()));

                await _cacheProviderPolicy.ExecuteAsync(() => _cacheProvider.RemoveAsync <TemplateMetadataContents>($"{CacheKeys.FundingTemplateContentMetadata}{validationResult.FundingStreamId}:{validationResult.FundingPeriodId}:{validationResult.TemplateVersion}".ToLowerInvariant()));

                await _cacheProviderPolicy.ExecuteAsync(() => _cacheProvider.RemoveAsync <TemplateMetadataDistinctContents>($"{CacheKeys.FundingTemplateContentMetadataDistinct}{validationResult.FundingStreamId}:{validationResult.FundingPeriodId}:{validationResult.TemplateVersion}".ToLowerInvariant()));

                return(new CreatedAtActionResult(actionName, controllerName, new { fundingStreamId = validationResult.FundingStreamId, fundingPeriodId = validationResult.FundingPeriodId, templateVersion = validationResult.TemplateVersion }, string.Empty));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Failed to save funding template '{blobName}' to blob storage");

                return(new InternalServerErrorResult("Error occurred uploading funding template"));
            }
        }
Пример #2
0
        private async Task <TemplateMetadataContents> GetTemplateMetadataContents(string specificationId,
                                                                                  string fundingStreamId)
        {
            ApiResponse <SpecificationSummary> specificationResponse = await _specificationResilience.ExecuteAsync(()
                                                                                                                   => _specifications.GetSpecificationSummaryById(specificationId));

            SpecificationSummary specification = specificationResponse.Content;

            string templateVersion = specification.TemplateIds[fundingStreamId];

            ApiResponse <FundingTemplateContents> templateContentsRequest = await _policiesResilience.ExecuteAsync(()
                                                                                                                   => _policies.GetFundingTemplate(fundingStreamId, specification.FundingPeriod.Id, templateVersion));

            FundingTemplateContents fundingTemplateContents = templateContentsRequest.Content;

            string schemaVersion = fundingTemplateContents.SchemaVersion ?? fundingTemplateContents.Metadata?.SchemaVersion;

            ITemplateMetadataGenerator templateContents = _templateMetadataResolver.GetService(schemaVersion);

            return(templateContents.GetMetadata(fundingTemplateContents.TemplateFileContents));
        }
            private void SetupMocks()
            {
                _validatorFactory = Substitute.For <IIoCValidatorFactory>();
                _validatorFactory.Validate(Arg.Any <object>()).Returns(new ValidationResult());
                _templateRepository   = Substitute.For <ITemplateRepository>();
                _templateVersionFirst = new TemplateVersion
                {
                    Name            = "XXX 20-21",
                    TemplateId      = _command.TemplateId,
                    TemplateJson    = null,
                    Version         = 1,
                    MinorVersion    = 1,
                    MajorVersion    = 0,
                    SchemaVersion   = "1.1",
                    FundingStreamId = "XX",
                    FundingPeriodId = "20-21",
                    Status          = TemplateStatus.Published,
                    Author          = new Reference("111", "FirstTestUser")
                };
                _templateBeforeUpdate = new Template
                {
                    Name          = "Template Name",
                    Description   = "Description",
                    TemplateId    = _command.TemplateId,
                    FundingPeriod = new FundingPeriod
                    {
                        Id   = "20-21",
                        Name = "Test Period",
                        Type = FundingPeriodType.FY
                    },
                    FundingStream = new FundingStream
                    {
                        Id        = "XX",
                        ShortName = "XX",
                        Name      = "FundingSteam"
                    },
                    Current = _templateVersionFirst
                };

                _templateMetadataGenerator = Substitute.For <ITemplateMetadataGenerator>();
                _templateMetadataGenerator.Validate(Arg.Any <string>()).Returns(new ValidationResult());
                _templateMetadataResolver = Substitute.For <ITemplateMetadataResolver>();
                _templateMetadataResolver.GetService(Arg.Any <string>()).Returns(_templateMetadataGenerator);
                _templateValidationService = Substitute.For <IFundingTemplateValidationService>();
                _templateValidationService.ValidateFundingTemplate(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), null).Returns(new FundingTemplateValidationResult {
                });
                _templateRepository.GetTemplate(Arg.Is(_command.TemplateId)).Returns(_templateBeforeUpdate);
                _templateRepository.Update(Arg.Do <Template>(x => _savedTemplate = x)).Returns(HttpStatusCode.OK);

                _versionRepository = Substitute.For <ITemplateVersionRepository>();
                _versionRepository.SaveVersion(Arg.Do <TemplateVersion>(x => _savedTemplateVersion = x)).Returns(HttpStatusCode.OK);

                _searchRepository = Substitute.For <ISearchRepository <TemplateIndex> >();
                _searchRepository.Index(Arg.Any <IEnumerable <TemplateIndex> >()).Returns(Enumerable.Empty <IndexError>());

                _policyRepository = Substitute.For <IPolicyRepository>();
                _policyRepository.GetFundingPeriodById(Arg.Any <string>()).Returns(new FundingPeriod
                {
                    Id   = "2021",
                    Name = "Test Period",
                    Type = FundingPeriodType.FY
                });
                _policyRepository.GetFundingStreamById(Arg.Any <string>()).Returns(new FundingStream
                {
                    Id        = "XX",
                    ShortName = "XX",
                    Name      = "FundingSteam"
                });
                _templateBlobService = Substitute.For <ITemplateBlobService>();
                _templateBlobService.PublishTemplate(Arg.Any <Template>()).Returns(CommandResult.Success());
            }
            private void SetupMocks()
            {
                _validatorFactory = Substitute.For <IIoCValidatorFactory>();
                _validatorFactory.Validate(Arg.Any <object>()).Returns(new ValidationResult());
                _templateRepository    = Substitute.For <ITemplateRepository>();
                _sourceTemplateVersion = new TemplateVersion
                {
                    Name            = "Old Test Name",
                    TemplateId      = _command.CloneFromTemplateId,
                    TemplateJson    = "{ \"Lorem\": \"ipsum\" }",
                    Version         = 12,
                    FundingPeriodId = "19-20",
                    FundingStreamId = "OLD",
                    MinorVersion    = 1,
                    MajorVersion    = 0,
                    SchemaVersion   = "1.1",
                    Status          = TemplateStatus.Draft,
                    Author          = new Reference("111", "FirstTestUser")
                };
                _sourceTemplate = new Template
                {
                    Name          = _sourceTemplateVersion.Name,
                    Description   = "Old description",
                    TemplateId    = _command.CloneFromTemplateId,
                    FundingPeriod = new FundingPeriod
                    {
                        Id   = "2021",
                        Name = "Test Period",
                        Type = FundingPeriodType.FY
                    },
                    FundingStream = new FundingStream
                    {
                        Id        = "XX",
                        ShortName = "XX",
                        Name      = "FundingSteam"
                    },
                    Current = _sourceTemplateVersion
                };

                _templateMetadataGenerator = Substitute.For <ITemplateMetadataGenerator>();
                _templateMetadataGenerator.Validate(Arg.Any <string>()).Returns(new ValidationResult());
                _templateMetadataResolver = Substitute.For <ITemplateMetadataResolver>();
                _templateMetadataResolver.GetService(Arg.Any <string>()).Returns(_templateMetadataGenerator);
                _templateValidationService = Substitute.For <IFundingTemplateValidationService>();
                _templateValidationService.ValidateFundingTemplate(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), null).Returns(new FundingTemplateValidationResult {
                });
                _templateRepository.GetTemplate(Arg.Is(_command.CloneFromTemplateId)).Returns(_sourceTemplate);
                _templateRepository.GetAllTemplates().Returns(new[] { _sourceTemplate });
                _templateRepository.CreateDraft(Arg.Any <Template>()).Returns(HttpStatusCode.OK);

                _versionRepository = Substitute.For <ITemplateVersionRepository>();
                _versionRepository.SaveVersion(Arg.Any <TemplateVersion>()).Returns(HttpStatusCode.OK);

                _policyRepository = Substitute.For <IPolicyRepository>();
                _policyRepository.GetFundingPeriods().Returns(new[] {
                    new FundingPeriod
                    {
                        Id   = "2021",
                        Name = "Test Period",
                        Type = FundingPeriodType.FY
                    },
                    new FundingPeriod
                    {
                        Id   = _command.FundingPeriodId,
                        Name = "Test Funding Period 2"
                    }
                });
                _policyRepository.GetFundingStreams().Returns(new[] {
                    new FundingStream
                    {
                        Id        = "XX",
                        ShortName = "XX",
                        Name      = "FundingSteam"
                    },
                    new FundingStream
                    {
                        Id        = _command.FundingStreamId,
                        Name      = "Funding Stream 2",
                        ShortName = "Stream 2"
                    }
                });
                _policyRepository.GetFundingConfigurations().Returns(new[] { new FundingConfiguration
                                                                             {
                                                                                 FundingStreamId = _command.FundingStreamId,
                                                                                 FundingPeriodId = _command.FundingPeriodId
                                                                             } });

                _templateIndexer = Substitute.For <ISearchRepository <TemplateIndex> >();

                _templateBlobService = Substitute.For <ITemplateBlobService>();
                _templateBlobService.PublishTemplate(Arg.Any <Template>()).Returns(CommandResult.Success());
            }