private void AndTheSavePublishedProviderVersionResponse(HttpStatusCode httpStatusCode,
                                                         PublishedProviderVersion expectedPublishedProviderVersion)
 {
     _publishedProviderVersioningService.Setup(_ =>
                                               _.SaveVersion(expectedPublishedProviderVersion))
     .ReturnsAsync(httpStatusCode);
 }
        public async Task ReturnsTheCurrentPublishedProviderVersionFromEachPublishedProviderTheRepositoryFinds()
        {
            PublishedProviderVersion firstExpectedVersion  = NewPublishedProviderVersion();
            PublishedProviderVersion secondExpectedVersion = NewPublishedProviderVersion();
            PublishedProviderVersion thirdExpectedVersion  = NewPublishedProviderVersion();

            GivenThePublishedProvidersForTheSpecificationId(
                NewPublishedProvider(_ => _.WithCurrent(firstExpectedVersion)),
                NewPublishedProvider(_ => _.WithCurrent(secondExpectedVersion)),
                NewPublishedProvider(_ => _.WithCurrent(thirdExpectedVersion)));

            AndTheSpecificationSummaryIsRetrieved(NewSpecificationSummary(s =>
            {
                s.WithId(_specificationId);
                s.WithFundingPeriodId(_fundingPeriodId);
                s.WithFundingStreamIds(new[] { _fundingStreamId });
            }));

            await WhenThePublishedProvidersAreQueried();

            ThenTheResponseShouldBe <OkObjectResult>(_ =>
                                                     ((IEnumerable <PublishedProviderVersion>)_.Value).SequenceEqual(new[]
            {
                firstExpectedVersion,
                secondExpectedVersion,
                thirdExpectedVersion
            }));
        }
Beispiel #3
0
        public Task DetermineVariations(ProviderVariationContext providerVariationContext, IEnumerable <string> fundingLineCodes)
        {
            Guard.ArgumentNotNull(providerVariationContext, nameof(providerVariationContext));

            PublishedProviderVersion priorState = providerVariationContext.PriorState;

            if (priorState == null ||
                priorState.Provider.Status == Closed ||
                providerVariationContext.UpdatedProvider.Status != Closed ||
                !providerVariationContext.UpdatedProvider.Successor.IsNullOrWhitespace())
            {
                return(Task.CompletedTask);
            }

            if (providerVariationContext.UpdatedTotalFunding != priorState.TotalFunding)
            {
                providerVariationContext.RecordErrors("Unable to run Closure variation as TotalFunding has changed during the refresh funding");

                return(Task.CompletedTask);
            }


            providerVariationContext.QueueVariationChange(new ZeroRemainingProfilesChange(providerVariationContext));
            providerVariationContext.QueueVariationChange(new ZeroInitialPaymentProfilesChange(providerVariationContext));
            providerVariationContext.QueueVariationChange(new ReAdjustFundingValuesForProfileValuesChange(providerVariationContext));

            return(Task.CompletedTask);
        }
        public async Task AssignProfilePatternKeyReturnsBadRequestIfNewPublishedProviderVersionCreationFailed()
        {
            string fundingLineCode            = NewRandomString();
            string existingProfilePatternKey  = NewRandomString();
            string newProfilePatterFundingKey = NewRandomString();

            GivenTheFundingConfiguration(true);
            ProfilePatternKey profilePatternKey = NewProfilePatternKey(_ => _.WithFundingLineCode(fundingLineCode).WithKey(newProfilePatterFundingKey));

            FundingLine fundingLine = NewFundingLine(_ => _.WithFundingLineCode(fundingLineCode));
            PublishedProviderVersion existingPublishedProviderVersion =
                NewPublishedProviderVersion(ppv => ppv
                                            .WithFundingStreamId(_fundingStreamId)
                                            .WithFundingPeriodId(_fundingPeriodId)
                                            .WithProfilePatternKeys(
                                                NewProfilePatternKey(_ => _.WithFundingLineCode(fundingLineCode).WithKey(existingProfilePatternKey)))
                                            .WithFundingLines(fundingLine)
                                            );

            PublishedProvider publishedProvider = NewPublishedProvider(_ => _.WithCurrent(existingPublishedProviderVersion));

            GivenThePublishedProvider(publishedProvider);

            IActionResult result = await WhenProfilePatternKeyIsAssigned(_fundingStreamId, _fundingPeriodId, _providerId, profilePatternKey);

            ThenResultShouldBe(result, HttpStatusCode.BadRequest);
        }
        public async Task GetLatestEarlierPublishedProviderVersion()
        {
            string fundingStreamId = NewRandomString();
            string fundingPeriodId = NewRandomString();
            long   timeStamp       = NewRandomTimeStamp();
            string providerId      = NewRandomString();

            PublishedProviderVersion expectedLatestEarlierDocument = NewPublishedProviderVersion();

            GivenTheLatestEarlierDocument(@$ "SELECT
                              TOP 1 *
                        FROM publishedProviderVersion p
                        WHERE p.documentType = 'PublishedProviderVersion'
                        AND p._ts < @sinceTimeStamp
                        AND p.content.fundingStreamId = @fundingStreamId
                        AND p.content.fundingPeriodId = @fundingPeriodId
                        AND p.content.providerId = @providerId
                        {string.Empty}
                        AND p.deleted = false
                        ORDER BY p._ts DESC",
                                          expectedLatestEarlierDocument,
                                          ("@fundingPeriodId", fundingPeriodId),
                                          ("@fundingStreamId", fundingStreamId),
                                          ("@sinceTimeStamp", timeStamp),
                                          ("@providerId", providerId));

            PublishedProviderVersion actualLatestEarlierDocument = await _repository.GetLatestEarlierPublishedProviderVersion(fundingStreamId,
                                                                                                                              fundingPeriodId,
                                                                                                                              timeStamp,
                                                                                                                              providerId);

            actualLatestEarlierDocument
            .Should()
            .BeSameAs(expectedLatestEarlierDocument);
        }
        public async Task GetLatestEarlierPublishedProviderVersionFromVersion()
        {
            string  fundingStreamId = NewRandomString();
            string  fundingPeriodId = NewRandomString();
            decimal version         = NewRandomInteger();
            string  providerId      = NewRandomString();

            PublishedProviderVersion expectedLatestEarlierDocument = NewPublishedProviderVersion();

            GivenTheLatestEarlierDocument(@$ "SELECT
                              TOP 1 *
                        FROM publishedProviderVersion p
                        WHERE p.documentType = 'PublishedProviderVersion'
                        AND StringToNumber(CONCAT(Tostring(p.content.majorVersion), '.', Tostring(p.content.minorVersion))) < @version
                        AND p.content.fundingStreamId = @fundingStreamId
                        AND p.content.fundingPeriodId = @fundingPeriodId
                        AND p.content.providerId = @providerId
                        {string.Empty}
                        AND p.deleted = false
                        ORDER BY p.content.majorVersion DESC, p.content.minorVersion DESC",
                                          expectedLatestEarlierDocument,
                                          ("@fundingPeriodId", fundingPeriodId),
                                          ("@fundingStreamId", fundingStreamId),
                                          ("@version", version),
                                          ("@providerId", providerId));

            PublishedProviderVersion actualLatestEarlierDocument = await _repository.GetLatestEarlierPublishedProviderVersionFromVersion(fundingStreamId,
                                                                                                                                         fundingPeriodId,
                                                                                                                                         version,
                                                                                                                                         providerId);

            actualLatestEarlierDocument
            .Should()
            .BeSameAs(expectedLatestEarlierDocument);
        }
Beispiel #7
0
        private bool HasNoPaidPeriods(ProviderVariationContext providerVariationContext,
                                      PublishedProviderVersion priorState)
        {
            foreach (ProfileVariationPointer variationPointer in providerVariationContext.VariationPointers ?? ArraySegment <ProfileVariationPointer> .Empty)
            {
                FundingLine fundingLine = priorState?.FundingLines.SingleOrDefault(_ => _.FundingLineCode == variationPointer.FundingLineId);

                if (fundingLine == null)
                {
                    continue;
                }

                YearMonthOrderedProfilePeriods periods = new YearMonthOrderedProfilePeriods(fundingLine);

                int variationPointerIndex = periods.IndexOf(_ => _.Occurrence == variationPointer.Occurrence &&
                                                            _.Type.ToString() == variationPointer.PeriodType &&
                                                            _.Year == variationPointer.Year &&
                                                            _.TypeValue == variationPointer.TypeValue);

                if (variationPointerIndex > 0)
                {
                    return(false);
                }
            }

            return(true);
        }
        public async Task GetsPublishedProviderTransactionForSuppliedSpecificationAndProvider()
        {
            PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(_ =>
                                                                                            _.WithAuthor(new Reference
            {
                Id = Guid.NewGuid().ToString()
            })
                                                                                            .WithFundingLines(NewFundingLine()));

            AndThePublishedFundingRepositoryReturnsPublishedProviderVersions(publishedProviderVersion);

            await WhenGetPublishedProviderTransactionsIsCalled(publishedProviderVersion);

            PublishedProviderTransaction[] expectedPublishedProviderTransaction =
            {
                NewPublishedProviderTransaction(_ => _.WithAuthor(publishedProviderVersion.Author)
                                                .WithPublishedProviderId(publishedProviderVersion.PublishedProviderId)
                                                .WithDate(publishedProviderVersion.Date)
                                                .WithPublishedProviderStatus(publishedProviderVersion.Status)
                                                .WithTotalFunding(publishedProviderVersion.TotalFunding)
                                                .WithFundingLines(publishedProviderVersion.FundingLines.ToArray()))
            };

            ActionResult
            .Should()
            .BeOfType <OkObjectResult>()
            .Which
            .Value
            .Should()
            .BeEquivalentTo(expectedPublishedProviderTransaction);
        }
        public void ThrowsExceptionWhenContentGeneratorReturnsNull()
        {
            // Arrange
            TemplateMetadataContents            templateMetadataContents           = Substitute.For <TemplateMetadataContents>();
            TemplateMapping                     templateMapping                    = Substitute.For <TemplateMapping>();
            IPublishedProviderContentsGenerator publishedProviderContentsGenerator = Substitute.For <IPublishedProviderContentsGenerator>();

            Dictionary <string, GeneratedProviderResult> generatedPublishedProviderData = new Dictionary <string, GeneratedProviderResult>();
            List <PublishedProvider> publishedProvidersToUpdate = new List <PublishedProvider>();

            GeneratedProviderResult generatedProviderResult = new GeneratedProviderResult();

            PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(providerVersion => providerVersion
                                                                                            .WithProviderId(ProviderVersionProviderId)
                                                                                            .WithFundingPeriodId(ProviderVersionFundingPeriodId)
                                                                                            .WithFundingStreamId(ProviderVersionFundingStreamId)
                                                                                            .WithVersion(ProviderVersionVersion));

            PublishedProvider publishedProvider = NewPublishedProvider(provider => provider.WithCurrent(publishedProviderVersion));

            generatedPublishedProviderData.Add(key, generatedProviderResult);
            publishedProvidersToUpdate.Add(publishedProvider);

            // Act
            Func <Task> invocation = async() => await _publishedProviderContentPersistanceService.SavePublishedProviderContents(
                templateMetadataContents, templateMapping, publishedProvidersToUpdate, publishedProviderContentsGenerator);

            // Assert
            ThenExceptionShouldBeThrown($"Generator failed to generate content for published provider version with id: '{publishedProviderVersion.Id}'", invocation);
        }
Beispiel #10
0
 public PaymentFundingLineProfileTotals(
     PublishedProviderVersion publishedProviderVersion,
     string fundingLineId)
 {
     _profileTotals = publishedProviderVersion
                      .FundingLines.Where(_ => _.Type == FundingLineType.Payment)
                      .Where(_ => _.FundingLineCode == fundingLineId)
                      .SelectMany(paymentFundingLine => new YearMonthOrderedProfilePeriods(paymentFundingLine))
                      .GroupBy(orderProfilePeriod => new
     {
         orderProfilePeriod.Year,
         orderProfilePeriod.TypeValue,
         orderProfilePeriod.Occurrence,
         orderProfilePeriod.DistributionPeriodId
     })
                      .Select(grouping => new ProfileTotal
     {
         Occurrence           = grouping.Key.Occurrence,
         Year                 = grouping.Key.Year,
         TypeValue            = grouping.Key.TypeValue,
         Value                = grouping.Sum(profilePeriod => profilePeriod.ProfiledValue),
         PeriodType           = grouping.FirstOrDefault().Type.ToString(),
         DistributionPeriodId = grouping.Key.DistributionPeriodId
     })
                      .ToArray();
 }
        protected override async Task ApplyChanges(IApplyProviderVariations variationsApplications)
        {
            Guard.ArgumentNotNull(variationsApplications, nameof(variationsApplications));

            PublishedProviderVersion predecessor = RefreshState;
            string fundingStreamId = predecessor.FundingStreamId;
            string fundingPeriodId = predecessor.FundingPeriodId;
            string templateVersion = predecessor.TemplateVersion;

            IEnumerable <uint> pupilNumberTemplateCalculationIds = await new PupilNumberCalculationIdProvider(variationsApplications)
                                                                   .GetPupilNumberCalculationIds(fundingStreamId, fundingPeriodId, templateVersion);

            Dictionary <uint, FundingCalculation> predecessorCalculations = predecessor
                                                                            .Calculations
                                                                            .ToDictionary(_ => _.TemplateCalculationId);
            Dictionary <uint, FundingCalculation> successorCalculations = SuccessorRefreshState
                                                                          .Calculations
                                                                          .ToDictionary(_ => _.TemplateCalculationId);

            foreach (uint templateCalculationId in pupilNumberTemplateCalculationIds)
            {
                if (!predecessorCalculations.TryGetValue(templateCalculationId, out FundingCalculation predecessorCalculation) ||
                    !successorCalculations.TryGetValue(templateCalculationId, out FundingCalculation successorCalculation))
                {
                    throw new InvalidOperationException("Cannot move pupil numbers to successor.\n" +
                                                        $"Could not locate both FundingCalculations for id {templateCalculationId}");
                }

                int totalPupilNumber = Convert.ToInt32(successorCalculation.Value) + Convert.ToInt32(predecessorCalculation.Value);

                successorCalculation.Value = totalPupilNumber;
            }
        }
Beispiel #12
0
        public async Task DeletesCosmosDocumentsAndMatchingBlobStoreDocumentsForFeedItems()
        {
            PublishedProviderVersion publishedProviderVersionOne   = NewPublishedProviderVersion();
            PublishedProviderVersion publishedProviderVersionTwo   = NewPublishedProviderVersion();
            PublishedProviderVersion publishedProviderVersionThree = NewPublishedProviderVersion();
            PublishedProviderVersion publishedProviderVersionFour  = NewPublishedProviderVersion();

            GivenThePublishedProviderVersionFeed(NewFeedIterator(
                                                     WithPages(Page(publishedProviderVersionOne, publishedProviderVersionTwo),
                                                               Page <PublishedProviderVersion>(),
                                                               Page(publishedProviderVersionThree, publishedProviderVersionFour))));

            await WhenTheTaskIsRun();

            ThenTheDocumentsWereDeleted(new [] { publishedProviderVersionOne, publishedProviderVersionTwo },
                                        new [] { publishedProviderVersionOne.PartitionKey, publishedProviderVersionTwo.PartitionKey },
                                        true);
            AndTheDocumentsWereDeleted(new [] { publishedProviderVersionThree, publishedProviderVersionFour },
                                       new [] { publishedProviderVersionThree.PartitionKey, publishedProviderVersionFour.PartitionKey },
                                       true);
            AndThePublishedProviderVersionBlobDocumentsWereRemoved(publishedProviderVersionOne,
                                                                   publishedProviderVersionTwo,
                                                                   publishedProviderVersionThree,
                                                                   publishedProviderVersionFour);
        }
Beispiel #13
0
 private void PublishProviderDocument(FeedOptions options, PublishedProviderVersion publishedProviderVersion, string generatedDocumentContent)
 {
     if (options.FeedStorageType == FeedStorageType.File)
     {
         File.WriteAllText(Path.Combine(options.OutputFolderPath, $"{publishedProviderVersion.FundingId}.json"), generatedDocumentContent);
     }
 }
        private static PublishedProviderFundingStructureItem RecursivelyAddFundingLines(
            IEnumerable <Common.TemplateMetadata.Models.FundingLine> fundingLines,
            List <TemplateMappingItem> templateMappingItems,
            int level,
            Common.TemplateMetadata.Models.FundingLine fundingLine,
            PublishedProviderVersion publishedProviderVersion)
        {
            level++;

            List <PublishedProviderFundingStructureItem> innerFundingStructureItems = new List <PublishedProviderFundingStructureItem>();

            // If funding line has calculations, recursively add them to list of inner FundingStructureItems
            if (fundingLine.Calculations != null && fundingLine.Calculations.Any())
            {
                foreach (Common.TemplateMetadata.Models.Calculation calculation in fundingLine.Calculations)
                {
                    innerFundingStructureItems.Add(
                        RecursivelyMapCalculationsToFundingStructureItem(
                            calculation,
                            level,
                            templateMappingItems,
                            publishedProviderVersion));
                }
            }

            // If funding line has more funding lines, recursively add them to list of inner FundingStructureItems
            if (fundingLine.FundingLines != null && fundingLine.FundingLines.Any())
            {
                foreach (Common.TemplateMetadata.Models.FundingLine line in fundingLines)
                {
                    innerFundingStructureItems.Add(RecursivelyAddFundingLines(
                                                       line.FundingLines,
                                                       templateMappingItems,
                                                       level,
                                                       line,
                                                       publishedProviderVersion));
                }
            }

            CalculateFunding.Models.Publishing.FundingLine publishedProviderFundingLine = publishedProviderVersion.FundingLines.FirstOrDefault(_ => _.TemplateLineId == fundingLine.TemplateLineId);
            string calculationValue = null;

            if (publishedProviderFundingLine != null)
            {
                calculationValue = publishedProviderFundingLine.Value.AsFormatCalculationType(CalculationValueFormat.Currency);
            }

            // Add FundingStructureItem
            PublishedProviderFundingStructureItem fundingStructureItem = MapToFundingStructureItem(
                level,
                fundingLine.Name,
                fundingLine.FundingLineCode,
                PublishedProviderFundingStructureType.FundingLine,
                null,
                null,
                innerFundingStructureItems.Any() ? innerFundingStructureItems : null,
                calculationValue);

            return(fundingStructureItem);
        }
Beispiel #15
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);
        }
        protected override Task <ErrorCheck> HasErrors(PublishedProvider publishedProvider, PublishedProvidersContext publishedProvidersContext)
        {
            ErrorCheck errorCheck = new ErrorCheck();

            PublishedProviderVersion publishedProviderVersion = publishedProvider.Current;

            foreach (FundingLine fundingLine in CustomPaymentFundingLinesFor(publishedProviderVersion))
            {
                decimal fundingLineValue = fundingLine.Value.GetValueOrDefault();
                decimal profiledValue    = GetProfiledSum(fundingLine, publishedProviderVersion);

                if (fundingLineValue != profiledValue)
                {
                    errorCheck.AddError(new PublishedProviderError
                    {
                        Identifier           = fundingLine.FundingLineCode,
                        Type                 = PublishedProviderErrorType.FundingLineValueProfileMismatch,
                        SummaryErrorMessage  = "A funding line profile doesn't match allocation value.",
                        DetailedErrorMessage = $"Funding line profile doesn't match allocation value. " +
                                               $"The allocation value is £{fundingLineValue}, but the profile value is set to £{profiledValue}",
                        FundingLineCode = fundingLine.FundingLineCode,
                        FundingStreamId = publishedProviderVersion.FundingStreamId
                    });
                }
            }

            return(Task.FromResult(errorCheck));
        }
        protected virtual bool HasNoProfilingChanges(PublishedProviderVersion priorState,
                                                     PublishedProviderVersion refreshState,
                                                     ProviderVariationContext providerVariationContext)
        {
            IDictionary <string, FundingLine> latestFundingLines =
                refreshState.FundingLines.Where(_ => _.Type == FundingLineType.Payment)
                .ToDictionary(_ => _.FundingLineCode);

            bool hasNoProfilingChanges = true;

            foreach (FundingLine previousFundingLine in priorState.FundingLines.Where(_ => _.Type == FundingLineType.Payment &&
                                                                                      _.Value.HasValue &&
                                                                                      ExtraFundingLinePredicate(refreshState, _)))
            {
                string fundingLineCode = previousFundingLine.FundingLineCode;

                if (!latestFundingLines.TryGetValue(fundingLineCode, out FundingLine latestFundingLine))
                {
                    continue;
                }

                ProfilePeriod[] priorProfiling  = new YearMonthOrderedProfilePeriods(previousFundingLine).ToArray();
                ProfilePeriod[] latestProfiling = new YearMonthOrderedProfilePeriods(latestFundingLine).ToArray();

                if (!priorProfiling.Select(AsLiteral)
                    .SequenceEqual(latestProfiling.Select(AsLiteral)))
                {
                    providerVariationContext.AddAffectedFundingLineCode(fundingLineCode);

                    hasNoProfilingChanges = false;
                }
            }

            return(hasNoProfilingChanges);
        }
        public async Task <PublishedProvider> CreateVersion(PublishedProviderCreateVersionRequest publishedProviderCreateVersionRequest)
        {
            Guard.ArgumentNotNull(publishedProviderCreateVersionRequest.PublishedProvider, nameof(publishedProviderCreateVersionRequest.PublishedProvider));
            Guard.ArgumentNotNull(publishedProviderCreateVersionRequest.NewVersion, nameof(publishedProviderCreateVersionRequest.NewVersion));

            PublishedProviderVersion currentVersion = publishedProviderCreateVersionRequest.PublishedProvider.Current;

            PublishedProviderVersion newVersion = publishedProviderCreateVersionRequest.NewVersion;

            string partitionKey = currentVersion != null ? publishedProviderCreateVersionRequest.PublishedProvider.PartitionKey : string.Empty;

            try
            {
                publishedProviderCreateVersionRequest.PublishedProvider.Current =
                    await _versionRepositoryPolicy.ExecuteAsync(() => _versionRepository.CreateVersion(newVersion, currentVersion, partitionKey));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Failed to create new version for published provider version id: {newVersion.Id}");

                throw;
            }

            return(publishedProviderCreateVersionRequest.PublishedProvider);
        }
Beispiel #19
0
        public void ProcessPublishedProvider(PublishedProviderVersion publishedProviderVersion)
        {
            Guard.ArgumentNotNull(publishedProviderVersion, nameof(publishedProviderVersion));

            if (!publishedProviderVersion.HasCustomProfiles)
            {
                return;
            }

            Dictionary <string, FundingLine> fundingLines = publishedProviderVersion.FundingLines?.Where(_ => _.Type == FundingLineType.Payment)?.ToDictionary(_ => _.FundingLineCode)
                                                            ?? new Dictionary <string, FundingLine>();

            foreach (FundingLineProfileOverrides customProfile in publishedProviderVersion.CustomProfiles)
            {
                string fundingLineCode = customProfile.FundingLineCode;

                if (!fundingLines.TryGetValue(fundingLineCode, out FundingLine fundingLine))
                {
                    throw new InvalidOperationException(
                              $"Custom profile has no matching funding line for {fundingLineCode} on {publishedProviderVersion.Id}");
                }

                fundingLine.DistributionPeriods = customProfile.DistributionPeriods.DeepCopy();
            }
        }
        public Task <HttpStatusCode> UpsertAsync <T>(T entity, string partitionKey = null, bool undelete = false, bool maintainCreatedDate = true) where T : IIdentifiable
        {
            if (typeof(T).Name == "PublishedProviderVersion")
            {
                PublishedProviderVersion publishedProviderVersion = entity as PublishedProviderVersion;
                if (!PublishedProviderVersions.ContainsKey(publishedProviderVersion.SpecificationId))
                {
                    PublishedProviderVersions.TryAdd(publishedProviderVersion.SpecificationId, new ConcurrentDictionary <string, PublishedProviderVersion>());
                }

                PublishedProviderVersions[publishedProviderVersion.SpecificationId][publishedProviderVersion.Id] = publishedProviderVersion;
                return(Task.FromResult(HttpStatusCode.OK));
            }
            else if (typeof(T).Name == "PublishedFundingVersion")
            {
                PublishedFundingVersion publishedFundingVersion = entity as PublishedFundingVersion;
                if (!PublishedFundingVersions.ContainsKey(publishedFundingVersion.SpecificationId))
                {
                    PublishedFundingVersions.TryAdd(publishedFundingVersion.SpecificationId, new ConcurrentDictionary <string, PublishedFundingVersion>());
                }

                PublishedFundingVersions[publishedFundingVersion.SpecificationId][publishedFundingVersion.Id] = publishedFundingVersion;
                return(Task.FromResult(HttpStatusCode.OK));
            }

            return(Task.FromResult(HttpStatusCode.BadRequest));
        }
 private PublishedProviderIndex CreatePublishedProviderIndex(PublishedProviderVersion publishedProviderVersion) =>
 new PublishedProviderIndex
 {
     Id              = publishedProviderVersion.PublishedProviderId,
     ProviderType    = publishedProviderVersion.Provider.ProviderType,
     ProviderSubType = publishedProviderVersion.Provider.ProviderSubType,
     LocalAuthority  = publishedProviderVersion.Provider.Authority,
     FundingStatus   = publishedProviderVersion.Status.ToString(),
     ProviderName    = publishedProviderVersion.Provider.Name,
     UKPRN           = publishedProviderVersion.Provider.UKPRN,
     FundingValue    = Convert.ToDouble(publishedProviderVersion.TotalFunding),
     SpecificationId = publishedProviderVersion.SpecificationId,
     FundingStreamId = publishedProviderVersion.FundingStreamId,
     FundingPeriodId = publishedProviderVersion.FundingPeriodId,
     HasErrors       = publishedProviderVersion.HasErrors,
     UPIN            = publishedProviderVersion.Provider.UPIN,
     URN             = publishedProviderVersion.Provider.URN,
     Errors          = publishedProviderVersion.Errors != null?publishedProviderVersion
                       .Errors
                       .Select(_ => _.SummaryErrorMessage)
                       .Where(_ => !string.IsNullOrEmpty(_))
                       .Distinct()
                       .ToArraySafe()
                           : Array.Empty <string>()
 };
        public async Task GetFundingStructure_GivenNoSpecificationFoundForPublishedProviderVersion_ReturnsNotFound()
        {
            string publishedProviderVersionId = NewRandomString();
            string specificationId            = NewRandomString();
            string fundingPeriodId            = NewRandomString();
            string providerId      = NewRandomString();
            string fundingStreamId = NewRandomString();
            int    templateVersion = NewRandomNumber();

            PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(_ => _
                                                                                            .WithFundingStreamId(fundingStreamId)
                                                                                            .WithFundingPeriodId(fundingPeriodId)
                                                                                            .WithProviderId(providerId)
                                                                                            .WithSpecificationId(specificationId));

            _publishedFundingRepository.GetPublishedProviderVersionById(publishedProviderVersionId)
            .Returns(publishedProviderVersion);
            _specificationService.GetSpecificationSummaryById(specificationId)
            .Returns((SpecificationSummary)null);

            var result = await _service.GetPublishedProviderFundingStructure(publishedProviderVersionId);

            NotFoundObjectResult notFoundObjectResult = result.Should()
                                                        .BeAssignableTo <NotFoundObjectResult>()
                                                        .Which
                                                        .As <NotFoundObjectResult>();

            notFoundObjectResult.Value
            .Should()
            .Be($"Specification not found for SpecificationId - {specificationId}");
        }
        public void UpdatesGeneratedResultIfPreviousVersionFundingLineIsPresent()
        {
            uint templateLineId = NewRandomUint();

            FundingLine generatedResultFundingLine = NewFundingLine(fl => fl
                                                                    .WithTemplateLineId(templateLineId)
                                                                    .WithFundingLineType(FundingLineType.Payment));

            GeneratedProviderResult generatedProviderResult = NewGeneratedProviderResult(_ =>
                                                                                         _.WithFundlines(NewFundingLine(fl => fl
                                                                                                                        .WithTemplateLineId(templateLineId)
                                                                                                                        .WithFundingLineType(FundingLineType.Payment))));

            PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(_ =>
                                                                                            _.WithFundingLines(NewFundingLine(fl => fl.WithTemplateLineId(templateLineId)
                                                                                                                              .WithValue(98990M))));

            bool hasZeroedFundingLine = _fundingLineValueOverride.TryOverridePreviousFundingLineValues(publishedProviderVersion,
                                                                                                       generatedProviderResult);

            hasZeroedFundingLine
            .Should()
            .BeTrue();

            generatedResultFundingLine.Value
            .Should()
            .BeNull();
        }
Beispiel #24
0
        protected override void GivenTheOtherwiseValidVariationContext(Action <ProviderVariationContext> changes = null)
        {
            base.GivenTheOtherwiseValidVariationContext(changes);

            PublishedProvider publishedProvider =
                VariationContext.GetPublishedProviderOriginalSnapShot(VariationContext.ProviderId);

            if (publishedProvider == null)
            {
                return;
            }

            PublishedProviderVersion publishedProviderCurrent = publishedProvider.Current;

            publishedProviderCurrent.FundingLines = new[]
            {
                NewFundingLine(_ => _.WithFundingLineCode(FundingLineCode)
                               .WithFundingLineType(FundingLineType.Payment)
                               .WithValue(new RandomNumberBetween(1, int.MaxValue))
                               .WithDistributionPeriods(NewDistributionPeriod(dp =>
                                                                              dp.WithProfilePeriods(NewProfilePeriod()))))
            };
            publishedProviderCurrent.Provider = NewProvider();

            publishedProvider.Released = publishedProviderCurrent.DeepCopy();
        }
        public async Task GetFundingStructure_GivenNoTemplateVersionForFundingStream_ReturnsServerError()
        {
            string publishedProviderVersionId = NewRandomString();
            string specificationId            = NewRandomString();
            string fundingPeriodId            = NewRandomString();
            string providerId      = NewRandomString();
            string fundingStreamId = NewRandomString();
            int    templateVersion = NewRandomNumber();

            PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(_ => _
                                                                                            .WithFundingStreamId(fundingStreamId)
                                                                                            .WithFundingPeriodId(fundingPeriodId)
                                                                                            .WithProviderId(providerId)
                                                                                            .WithSpecificationId(specificationId));

            SpecificationSummary specificationSummary = NewSpecificationSummary(_ => _.WithId(specificationId));

            _publishedFundingRepository.GetPublishedProviderVersionById(publishedProviderVersionId)
            .Returns(publishedProviderVersion);
            _specificationService.GetSpecificationSummaryById(specificationId)
            .Returns(specificationSummary);

            var result = await _service.GetPublishedProviderFundingStructure(publishedProviderVersionId);

            InternalServerErrorResult notFoundObjectResult = result.Should()
                                                             .BeAssignableTo <InternalServerErrorResult>()
                                                             .Which
                                                             .As <InternalServerErrorResult>();

            notFoundObjectResult.Value
            .Should()
            .Be($"Specification contains no matching template version for funding stream '{fundingStreamId}'");
        }
        public void SetUp()
        {
            _fundingStreamId = NewRandomString();
            _fundingPeriodId = NewRandomString();
            _templateVersion = NewRandomString();

            _cacheKey = $"PupilNumberTemplateCalculationIds:{_fundingStreamId}:{_fundingPeriodId}:{_templateVersion}";

            PublishedProviderVersion refreshState = VariationContext.RefreshState;

            refreshState.FundingStreamId = _fundingStreamId;
            refreshState.TemplateVersion = _templateVersion;
            refreshState.FundingPeriodId = _fundingPeriodId;

            _caching  = new Mock <ICacheProvider>();
            _policies = new Mock <IPoliciesApiClient>();

            VariationsApplication.CacheProvider
            .Returns(_caching.Object);
            VariationsApplication.PoliciesApiClient
            .Returns(_policies.Object);

            Change = new MovePupilNumbersToSuccessorChange(VariationContext);

            VariationContext.SuccessorRefreshState = VariationContext.RefreshState.DeepCopy();
        }
Beispiel #27
0
        private async Task ProfileFundingLineValues(PublishedProviderVersion newPublishedProviderVersion, ProfilePatternKey profilePatternKey)
        {
            string fundingLineCode = profilePatternKey.FundingLineCode;

            FundingLine fundingLine = newPublishedProviderVersion.FundingLines.SingleOrDefault(_ => _.FundingLineCode == fundingLineCode);

            if (fundingLine == null)
            {
                string error = $"Did not locate a funding line with code {fundingLineCode} on published provider version {newPublishedProviderVersion.PublishedProviderId}";

                _logger.Error(error);

                throw new InvalidOperationException(error);
            }

            ApiResponse <IEnumerable <ProfileVariationPointer> > variationPointersResponse =
                await _specificationResiliencePolicy.ExecuteAsync(() =>
                                                                  _specificationsApiClient.GetProfileVariationPointers(newPublishedProviderVersion.SpecificationId));

            IEnumerable <ProfileVariationPointer> profileVariationPointers = variationPointersResponse?
                                                                             .Content?
                                                                             .Where(_ =>
                                                                                    _.FundingLineId == fundingLineCode &&
                                                                                    _.FundingStreamId == newPublishedProviderVersion.FundingStreamId);

            if (ThereArePaidProfilePeriodsOnTheFundingLine(profileVariationPointers))
            {
                await ReProfileFundingLine(newPublishedProviderVersion, profilePatternKey, fundingLineCode, fundingLine);
            }
            else
            {
                await ProfileFundingLine(fundingLine, newPublishedProviderVersion, profilePatternKey);
            }
        }
 private async Task WhenGetPublishedProviderVersionIsCalled(PublishedProviderVersion publishedProviderVersion)
 {
     ActionResult = await _service.GetPublishedProviderVersion(publishedProviderVersion.FundingStreamId,
                                                               publishedProviderVersion.FundingPeriodId,
                                                               publishedProviderVersion.ProviderId,
                                                               publishedProviderVersion.Version.ToString());
 }
Beispiel #29
0
 private async Task ProfileFundingLine(FundingLine fundingLine, PublishedProviderVersion newPublishedProviderVersion, ProfilePatternKey profilePatternKey)
 {
     await _profilingService.ProfileFundingLines(
         new[] { fundingLine },
         newPublishedProviderVersion.FundingStreamId,
         newPublishedProviderVersion.FundingPeriodId,
         new[] { profilePatternKey });
 }
 private void AndTheApiResponseDetailsForCurrentPublishedVersionMetaSupplied(
     PublishedProviderVersion publishedProviderVersion)
 {
     _publishedFundingRepository.GetLatestPublishedProviderVersionBySpecificationId(publishedProviderVersion?.SpecificationId,
                                                                                    publishedProviderVersion?.FundingStreamId,
                                                                                    publishedProviderVersion?.ProviderId)
     .Returns(publishedProviderVersion);
 }