private void AndGetProviderByIdFromProviderVersion()
 {
     _providersApiClient
     .GetProviderByIdFromProviderVersion(_providerVersionId, _providerId)
     .Returns(new ApiResponse <ProvidersModels.ProviderVersionSearchResult>(
                  HttpStatusCode.OK,
                  NewProvidersProviderVersionSearchResultBuilder(_ => _.WithProviderId(_providerId))));
 }
Example #2
0
        public async Task <IActionResult> GetPublishedProviderInformation(string publishedProviderVersion)
        {
            Guard.ArgumentNotNull(publishedProviderVersion, nameof(publishedProviderVersion));

            string blobName = $"{publishedProviderVersion}.json";

            ProviderVersionSystemCacheKey providerVersionFileSystemCacheKey = new ProviderVersionSystemCacheKey(blobName);

            if (_cacheSettings.IsEnabled && _fileSystemCache.Exists(providerVersionFileSystemCacheKey))
            {
                await using Stream providerVersionDocumentStream = _fileSystemCache.Get(providerVersionFileSystemCacheKey);

                ProviderVersionSearchResult cachedProviderVersionSearchResult = providerVersionDocumentStream.AsPoco <ProviderVersionSearchResult>();

                return(new OkObjectResult(cachedProviderVersionSearchResult));
            }

            (string providerVersionId, string providerId)results =
                await _publishedFundingRepositoryPolicy.ExecuteAsync(() => _publishedFundingRepository.GetPublishedProviderId(publishedProviderVersion));

            if (string.IsNullOrEmpty(results.providerVersionId) || string.IsNullOrEmpty(results.providerId))
            {
                _logger.Error($"Failed to retrieve published provider with publishedProviderVersion: {publishedProviderVersion}");

                return(new NotFoundResult());
            }

            ApiResponse <ProvidersApiClientModel.Search.ProviderVersionSearchResult> apiResponse =
                await _providersApiClientPolicy.ExecuteAsync(() =>
                                                             _providersApiClient.GetProviderByIdFromProviderVersion(results.providerVersionId, results.providerId));

            if (apiResponse?.Content == null || !apiResponse.StatusCode.IsSuccess())
            {
                string errorMessage = $"Failed to retrieve GetProviderByIdFromProviderVersion with " +
                                      $"providerVersionId: {results.providerVersionId} and providerId: {results.providerId}";

                _logger.Error(errorMessage);

                return(new InternalServerErrorResult(errorMessage));
            }

            ProviderVersionSearchResult providerVersionSearchResult = _mapper.Map <ProviderVersionSearchResult>(apiResponse.Content);

            if (_cacheSettings.IsEnabled)
            {
                if (!_fileSystemCache.Exists(providerVersionFileSystemCacheKey))
                {
                    await using MemoryStream stream = new MemoryStream(providerVersionSearchResult.AsJsonBytes());

                    _fileSystemCache.Add(providerVersionFileSystemCacheKey, stream, ensureFolderExists: true);
                }
            }

            return(new OkObjectResult(providerVersionSearchResult));
        }
        public async Task <IActionResult> GetProviderById(string providerVersionId, string providerId)
        {
            ApiResponse <ProviderVersionSearchResult> result =
                await _providersApiClient.GetProviderByIdFromProviderVersion(providerVersionId, providerId);


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

            if (result.StatusCode == HttpStatusCode.BadRequest)
            {
                return(BadRequest(result.Content));
            }

            if (result.StatusCode == HttpStatusCode.NotFound)
            {
                return(new NotFoundObjectResult("Provider was not found"));
            }

            return(new InternalServerErrorResult("There was an error processing your request. Please try again."));
        }
        public async Task PreviewCalculationResult_GivenCachedAggregateValuesExist_CalculateProviderResultsCallReceived()
        {
            IAllocationModel allocationModel = Substitute.For <IAllocationModel>();

            _calculationEngine
            .GenerateAllocationModel(Arg.Any <Assembly>())
            .Returns(allocationModel);

            ProviderVersionSearchResult providerVersionSearchResult = new ProviderVersionSearchResult
            {
                UKPRN = providerId
            };

            IEnumerable <string> dataDefinitionRelationshipIds = new List <string>();

            SpecificationSummary specificationSummary = new SpecificationSummary
            {
                DataDefinitionRelationshipIds = dataDefinitionRelationshipIds,
                ProviderVersionId             = providerVersionId
            };

            _specificationsApiClient
            .GetSpecificationSummaryById(Arg.Is(specificationId))
            .Returns(new ApiResponse <SpecificationSummary>(HttpStatusCode.OK, specificationSummary));

            _providersApiClient
            .GetProviderByIdFromProviderVersion(Arg.Is(providerVersionId), Arg.Is(providerId))
            .Returns(new ApiResponse <ProviderVersionSearchResult>(HttpStatusCode.OK, providerVersionSearchResult));

            CalculationSummaryModel previewCalculationSummaryModel = new CalculationSummaryModel();

            IEnumerable <CalculationSummaryModel> calculationSummaryModels = new List <CalculationSummaryModel>
            {
                new CalculationSummaryModel(),
                new CalculationSummaryModel()
            };

            List <CalculationSummaryModel> expectedCalculationSummaryModels = calculationSummaryModels.ToList();

            expectedCalculationSummaryModels.Add(previewCalculationSummaryModel);

            _calculationsRepository
            .GetCalculationSummariesForSpecification(Arg.Is(specificationId))
            .Returns(calculationSummaryModels);

            Dictionary <string, ProviderSourceDataset> sourceDatasets = new Dictionary <string, ProviderSourceDataset>();

            Dictionary <string, Dictionary <string, ProviderSourceDataset> > providerSourceDatasets = new Dictionary <string, Dictionary <string, ProviderSourceDataset> >
            {
                { providerId, sourceDatasets }
            };

            _providerSourceDatasetsRepository
            .GetProviderSourceDatasetsByProviderIdsAndRelationshipIds(
                Arg.Is(specificationId),
                Arg.Is <IEnumerable <string> >(_ => _ != null && _.Count() == 1 && _.FirstOrDefault() == providerId),
                Arg.Is <IEnumerable <string> >(_ => _ != null && _.SequenceEqual(dataDefinitionRelationshipIds)))
            .Returns(providerSourceDatasets);

            IEnumerable <CalculationAggregation> calculationAggregations = new List <CalculationAggregation>();

            _calculationAggregationService
            .BuildAggregations(Arg.Is <BuildAggregationRequest>(_ => _ != null && _.SpecificationId == specificationId))
            .Returns(calculationAggregations);

            PreviewCalculationRequest previewCalculationRequest = new PreviewCalculationRequest
            {
                AssemblyContent = MockData.GetMockAssembly(),
                PreviewCalculationSummaryModel = previewCalculationSummaryModel
            };

            IActionResult actionResult =
                await _calculationEnginePreviewService.PreviewCalculationResult(specificationId, providerId, previewCalculationRequest);

            _calculationEngine
            .Received(1)
            .CalculateProviderResults(
                Arg.Is(allocationModel),
                specificationId,
                Arg.Is <IEnumerable <CalculationSummaryModel> >(_ => _.SequenceEqual(expectedCalculationSummaryModels)),
                Arg.Is <ProviderSummary>(_ => _.UKPRN == providerId),
                Arg.Is <Dictionary <string, ProviderSourceDataset> >(_ => _.SequenceEqual(sourceDatasets)),
                Arg.Is <IEnumerable <CalculationAggregation> >(_ => _.SequenceEqual(calculationAggregations)));
        }
Example #5
0
        public async Task <PublishedProvider> CreateMissingPublishedProviderForPredecessor(PublishedProvider predecessor, string successorId, string providerVersionId)
        {
            ApiResponse <ProviderVersionSearchResult> apiResponse = await _providersApiClientPolicy.ExecuteAsync(() =>
                                                                                                                 _providersApiClient.GetProviderByIdFromProviderVersion(providerVersionId, successorId));

            ProviderVersionSearchResult providerVersionSearchResult = apiResponse?.Content;

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

            PublishedProviderVersion predecessorProviderVersion = predecessor.Current;

            PublishedProvider missingProvider = CreatePublishedProvider(_mapper.Map <Provider>(providerVersionSearchResult),
                                                                        predecessorProviderVersion.FundingPeriodId,
                                                                        predecessorProviderVersion.FundingStreamId,
                                                                        predecessorProviderVersion.SpecificationId,
                                                                        "Created by the system as not in scope but referenced as a successor provider",
                                                                        predecessorProviderVersion.FundingLines.DeepCopy(),
                                                                        predecessorProviderVersion.Calculations.DeepCopy());

            foreach (ProfilePeriod profilePeriod in missingProvider.Current.FundingLines.SelectMany(_ =>
                                                                                                    _.DistributionPeriods.SelectMany(dp => dp.ProfilePeriods)))
            {
                profilePeriod.ProfiledValue = 0;
            }

            return(missingProvider);
        }
Example #6
0
        public async Task <IActionResult> PreviewCalculationResult(
            string specificationId,
            string providerId,
            PreviewCalculationRequest previewCalculationRequest)
        {
            Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));
            Guard.IsNullOrWhiteSpace(providerId, nameof(providerId));
            Guard.ArgumentNotNull(previewCalculationRequest, nameof(previewCalculationRequest));

            Assembly         assembly        = Assembly.Load(previewCalculationRequest.AssemblyContent);
            IAllocationModel allocationModel = _calculationEngine.GenerateAllocationModel(assembly);

            SpecificationSummary specificationSummary = await GetSpecificationSummary(specificationId);

            ApiResponse <ProviderVersionSearchResult> providerVersionSearchResultApiResponse =
                await _providersApiClientPolicy.ExecuteAsync(() => _providersApiClient.GetProviderByIdFromProviderVersion(
                                                                 specificationSummary.ProviderVersionId,
                                                                 providerId));

            ProviderVersionSearchResult providerVersionSearchResult = providerVersionSearchResultApiResponse.Content;

            if (providerVersionSearchResult == null)
            {
                return(new NotFoundResult());
            }

            ProviderSummary providerSummary = _mapper.Map <ProviderSummary>(providerVersionSearchResult);

            List <CalculationSummaryModel>        calculationSummaries     = new List <CalculationSummaryModel>();
            IEnumerable <CalculationSummaryModel> specCalculationSummaries = await GetCalculationSummaries(specificationId);

            calculationSummaries.AddRange(specCalculationSummaries);
            calculationSummaries.Add(previewCalculationRequest.PreviewCalculationSummaryModel);

            Dictionary <string, Dictionary <string, ProviderSourceDataset> > providerSourceDatasets =
                await _providerSourceDatasetsRepository.GetProviderSourceDatasetsByProviderIdsAndRelationshipIds(
                    specificationId,
                    new[] { providerId },
                    specificationSummary.DataDefinitionRelationshipIds);

            Dictionary <string, ProviderSourceDataset> providerSourceDataset = providerSourceDatasets[providerId];

            BuildAggregationRequest buildAggregationRequest = new BuildAggregationRequest
            {
                SpecificationId = specificationId,
                GenerateCalculationAggregationsOnly = true,
                BatchCount = 100
            };
            IEnumerable <CalculationAggregation> calculationAggregations =
                await _calculationAggregationService.BuildAggregations(buildAggregationRequest);

            ProviderResult providerResult = _calculationEngine.CalculateProviderResults(
                allocationModel,
                specificationId,
                calculationSummaries,
                providerSummary,
                providerSourceDataset,
                calculationAggregations
                );

            return(new OkObjectResult(providerResult));
        }