private void GivenTheProfilePattern(ReProfileRequest request,
                                     FundingStreamPeriodProfilePattern profilePattern)
 => _profilePatterns.Setup(_ => _.GetProfilePattern(request.FundingStreamId,
                                                    request.FundingPeriodId,
                                                    request.FundingLineCode,
                                                    request.ProfilePatternKey))
 .ReturnsAsync(profilePattern);
示例#2
0
        private static (string key, string name, string description) GetProfilePatternDetails(string fundingLineCode, PublishedProviderVersion latestPublishedProviderVersion, IEnumerable <FundingStreamPeriodProfilePattern> fundingStreamPeriodProfilePatterns)
        {
            string profilePatternKey = latestPublishedProviderVersion.ProfilePatternKeys?
                                       .SingleOrDefault(_ => _.FundingLineCode == fundingLineCode)?.Key;

            bool hasCustomProfileForFundingLine = latestPublishedProviderVersion.FundingLineHasCustomProfile(fundingLineCode);

            FundingStreamPeriodProfilePattern apiProfilePatternKey =
                fundingStreamPeriodProfilePatterns.FirstOrDefault(_ => _.ProfilePatternKey == profilePatternKey && _.FundingLineId == fundingLineCode);

            string profilePatternName;
            string profilePatternDescription;

            if (hasCustomProfileForFundingLine)
            {
                profilePatternName        = "Custom Profile";
                profilePatternDescription = "Custom Profile";
            }
            else
            {
                profilePatternName        = apiProfilePatternKey?.ProfilePatternDisplayName;
                profilePatternDescription = apiProfilePatternKey?.ProfilePatternDescription;
            }

            return(profilePatternKey, profilePatternName, profilePatternDescription);
        }
示例#3
0
        public AllocationProfileResponse ProfileAllocation(
            ProfileRequestBase request,
            FundingStreamPeriodProfilePattern profilePattern,
            decimal fundingValue)
        {
            if (profilePattern == null)
            {
                throw new InvalidOperationException($"Profile pattern is null, {request}");
            }

            IReadOnlyCollection <DeliveryProfilePeriod> profilePeriods = GetProfiledAllocationPeriodsWithPatternApplied(fundingValue,
                                                                                                                        profilePattern.ProfilePattern,
                                                                                                                        profilePattern.RoundingStrategy);

            IReadOnlyCollection <DistributionPeriods> distributionPeriods = GetDistributionPeriodWithPatternApplied(
                profilePeriods);

            return(new AllocationProfileResponse(
                       profilePeriods.ToArray(),
                       distributionPeriods.ToArray())
            {
                ProfilePatternKey = profilePattern.ProfilePatternKey,
                ProfilePatternDisplayName = profilePattern.ProfilePatternDisplayName
            });
        }
        public async Task ProfilesEachProviderFundingValueInTheSuppliedBatches()
        {
            decimal fundingValueOne   = NewRandomFundingValue();
            decimal fundingValueTwo   = NewRandomFundingValue();
            decimal fundingValueThree = NewRandomFundingValue();

            ProfileBatchRequest request = NewProfileBatchRequest(_ => _.WithFundingValues(fundingValueOne,
                                                                                          fundingValueTwo,
                                                                                          fundingValueThree));

            FundingStreamPeriodProfilePattern profilePattern = NewProfilePattern();

            AllocationProfileResponse allocationProfileResponseOne   = NewAllocationProfileResponse();
            AllocationProfileResponse allocationProfileResponseTwo   = NewAllocationProfileResponse();
            AllocationProfileResponse allocationProfileResponseThree = NewAllocationProfileResponse();

            GivenTheValidationResult(request, NewValidationResult());
            AndTheProfilePattern(request, profilePattern);
            AndTheProfilingResponse(request, profilePattern, fundingValueOne, allocationProfileResponseOne);
            AndTheProfilingResponse(request, profilePattern, fundingValueTwo, allocationProfileResponseTwo);
            AndTheProfilingResponse(request, profilePattern, fundingValueThree, allocationProfileResponseThree);

            OkObjectResult result = await WhenTheBatchProfileRequestIsProcessed(request) as OkObjectResult;

            result?.Value
            .Should()
            .BeEquivalentTo(new[]
            {
                new BatchAllocationProfileResponse(request.GetFundingValueKey(fundingValueOne), fundingValueOne, allocationProfileResponseOne),
                new BatchAllocationProfileResponse(request.GetFundingValueKey(fundingValueTwo), fundingValueTwo, allocationProfileResponseTwo),
                new BatchAllocationProfileResponse(request.GetFundingValueKey(fundingValueThree), fundingValueThree, allocationProfileResponseThree)
            });
        }
        private async Task <FundingStreamPeriodProfilePattern> GetProfilePatternByProviderTypes(ProfileRequestBase profileRequest)
        {
            FundingStreamPeriodProfilePattern profilePattern = null;

            string profilePatternCacheKey = GetProfilePatternCacheKeyByProviderTypes(profileRequest);

            profilePattern = await _cachingResilience.ExecuteAsync(() => _cacheProvider.GetAsync <FundingStreamPeriodProfilePattern>(profilePatternCacheKey));

            if (profilePattern == null)
            {
                profilePattern = await _profilePatternRepositoryResilience.ExecuteAsync(() =>
                                                                                        _profilePatternRepository.GetProfilePattern(profileRequest.FundingPeriodId,
                                                                                                                                    profileRequest.FundingStreamId,
                                                                                                                                    profileRequest.FundingLineCode,
                                                                                                                                    profileRequest.ProviderType,
                                                                                                                                    profileRequest.ProviderSubType));

                if (profilePattern != null)
                {
                    await _cachingResilience.ExecuteAsync(() => _cacheProvider.SetAsync(profilePatternCacheKey, profilePattern, DateTimeOffset.Now.AddMinutes(30)));
                }
            }

            return(profilePattern ?? await GetProfilePatternByIdOrDefault(profileRequest));
        }
        public async Task CalculateProfileService_ShouldCorrectlyProfileEdgeCaseAllocationJustWithinPatternMonths()
        {
            // arrange
            FundingStreamPeriodProfilePattern pattern = TestResource.FromJson <FundingStreamPeriodProfilePattern>(
                NamespaceResourcesResideIn, "Resources.PESPORTSPREM.json");

            // first period rouonds down
            ProfileRequest peSportsPremReq1 = new ProfileRequest(
                fundingStreamId: "PSG",
                fundingPeriodId: "AY-1819",
                fundingLineCode: "FL1",
                fundingValue: 1000);

            IProfilePatternRepository mockProfilePatternRepository = Substitute.For <IProfilePatternRepository>();

            mockProfilePatternRepository
            .GetProfilePattern(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(pattern);

            ICalculateProfileService calculateProfileService = GetCalculateProfileServiceWithMockedDependencies(mockProfilePatternRepository);

            // act
            IActionResult responseResult = await calculateProfileService.ProcessProfileAllocationRequest(peSportsPremReq1);

            // assert
            responseResult
            .Should().BeOfType <OkObjectResult>();

            OkObjectResult            responseAsOkObjectResult = responseResult as OkObjectResult;
            AllocationProfileResponse response = responseAsOkObjectResult.Value as AllocationProfileResponse;

            response.DeliveryProfilePeriods.ToArray().FirstOrDefault(q => q.TypeValue == "October").ProfileValue.Should().Be(583.00M);
            response.DeliveryProfilePeriods.ToArray().FirstOrDefault(q => q.TypeValue == "April").ProfileValue.Should().Be(417.00M);
            response.DeliveryProfilePeriods.Length.Should().Be(3);
        }
 public BatchProfileRequestContext(FundingStreamPeriodProfilePattern profilePattern,
                                   ProfileBatchRequest request,
                                   int pageSize) : base(request.FundingValues, pageSize)
 {
     Request        = request;
     ProfilePattern = profilePattern;
 }
        public async Task CalculateProfileService_ShouldCorrectlyProfileFullLengthAllocationWithRoundUp()
        {
            // arrange
            FundingStreamPeriodProfilePattern pattern = TestResource.FromJson <FundingStreamPeriodProfilePattern>(
                NamespaceResourcesResideIn, "Resources.DSG.json");

            // first period rouonds down
            ProfileRequest peSportsPremReq1 = new ProfileRequest(
                fundingStreamId: "DSG",
                fundingPeriodId: "FY-2021",
                fundingLineCode: "DSG-002",
                fundingValue: 10000543);

            IProfilePatternRepository mockProfilePatternRepository = Substitute.For <IProfilePatternRepository>();

            mockProfilePatternRepository
            .GetProfilePattern(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(pattern);

            ICalculateProfileService calculateProfileService = GetCalculateProfileServiceWithMockedDependencies(mockProfilePatternRepository);

            // act
            IActionResult responseResult = await calculateProfileService.ProcessProfileAllocationRequest(peSportsPremReq1);

            // assert
            responseResult
            .Should().BeOfType <OkObjectResult>();

            OkObjectResult            responseAsOkObjectResult = responseResult as OkObjectResult;
            AllocationProfileResponse response = responseAsOkObjectResult.Value as AllocationProfileResponse;

            response.DeliveryProfilePeriods.ToArray().FirstOrDefault(q => q.TypeValue == "April").ProfileValue.Should().Be(400021M);
            response.DeliveryProfilePeriods.ToArray().LastOrDefault(q => q.TypeValue == "March").ProfileValue.Should().Be(400039M);
            response.DeliveryProfilePeriods.Length.Should().Be(25);
        }
        public void GuardsAgainstProfiledAmountsAndCarryOverNotBeingSameAsFundingValueInTheSuppliedRequestAfterReProfiling()
        {
            ReProfileRequest          request         = NewReProfileRequest();
            AllocationProfileResponse profileResponse = NewAllocationProfileResponse();

            string key = NewRandomString();

            FundingStreamPeriodProfilePattern profilePattern = NewFundingStreamPeriodProfilePattern(_ =>
                                                                                                    _.WithReProfilingConfiguration(NewProfilePatternReProfilingConfiguration(cfg =>
                                                                                                                                                                             cfg.WithIsEnabled(true)
                                                                                                                                                                             .WithIncreasedAmountStrategyKey(key))));

            GivenTheProfilePattern(request, profilePattern);
            AndTheReProfilingStrategy(key);
            AndTheProfiling(request, profilePattern, profileResponse);
            AndTheReProfilingStrategyResponse(profileResponse, request, profilePattern, NewReProfileStrategyResult());

            _service
            .Awaiting(_ => _.ReProfile(request))
            .Should()
            .Throw <InvalidOperationException>()
            .Which
            .Message
            .Should()
            .Be($"Profile amounts (0) and carry over amount (0) does not equal funding line total requested ({request.FundingLineTotal}) from strategy.");
        }
        private IReProfilingStrategy GetReProfilingStrategy(ReProfileRequest reProfileRequest,
                                                            FundingStreamPeriodProfilePattern profilePattern)
        {
            string key = profilePattern.GetReProfilingStrategyKeyForFundingAmountChange(reProfileRequest.FundingLineTotalChange);

            return(_reProfilingStrategyLocator.GetStrategy(key));
        }
 private void AndTheProfilePatternWasCached(FundingStreamPeriodProfilePattern pattern)
 {
     _caching.Verify(_ => _.SetAsync(PatternCacheKeyFor(pattern.Id),
                                     pattern,
                                     It.IsAny <DateTimeOffset>(),
                                     null),
                     Times.Once);
 }
 private void AndTheProfilePattern(ProfileBatchRequest request,
                                   FundingStreamPeriodProfilePattern profilePattern)
 => _profilePatterns.Setup(_ => _.GetProfilePattern(request.FundingPeriodId,
                                                    request.FundingStreamId,
                                                    request.FundingLineCode,
                                                    request.ProviderType,
                                                    request.ProviderSubType))
 .ReturnsAsync(profilePattern);
 private void AndTheReProfilingStrategyResponse(AllocationProfileResponse profileResponse,
                                                ReProfileRequest request,
                                                FundingStreamPeriodProfilePattern profilePattern,
                                                ReProfileStrategyResult response)
 => _reProfilingStrategy.Setup(_ => _.ReProfile(It.Is <ReProfileContext>(ctx =>
                                                                         ReferenceEquals(ctx.Request, request) &&
                                                                         ReferenceEquals(ctx.ProfilePattern, profilePattern) &&
                                                                         ReferenceEquals(ctx.ProfileResult, profileResponse))))
 .Returns(response);
示例#14
0
        private static FundingStreamPeriodProfilePatternDocument ConvertToModel(Stream fileStream)
        {
            using (var sr = new StreamReader(fileStream))
            {
                FundingStreamPeriodProfilePattern pattern =
                    JsonConvert.DeserializeObject <FundingStreamPeriodProfilePattern>(sr.ReadToEnd());

                return(FundingStreamPeriodProfilePatternDocument.CreateFromPattern(pattern));
            }
        }
        public async Task FailsValidationIfPatternWithSameKeyExists()
        {
            CreateProfilePatternRequest       request = NewCreateRequest(_ => _.WithPattern(NewProfilePattern()));
            FundingStreamPeriodProfilePattern pattern = request.Pattern;

            GivenTheExistingProfilePattern(pattern);

            await WhenTheRequestIsValidated(request);

            ThenTheValidationResultsContainsTheErrors(("Id", $"{pattern.Id} is already in use. Please choose a unique profile pattern id"));
        }
 private void AndTheProfiling(ReProfileRequest request,
                              FundingStreamPeriodProfilePattern profilePattern,
                              AllocationProfileResponse response)
 => _profiling.Setup(_ => _.ProfileAllocation(It.Is <ProfileRequest>(req =>
                                                                     req.FundingStreamId == request.FundingStreamId &&
                                                                     req.FundingPeriodId == request.FundingPeriodId &&
                                                                     req.FundingLineCode == request.FundingLineCode &&
                                                                     req.FundingValue == request.FundingLineTotal &&
                                                                     req.ProfilePatternKey == request.ProfilePatternKey),
                                              profilePattern,
                                              request.FundingLineTotal))
 .Returns(response);
        public async Task GetDelegatesToCosmos()
        {
            FundingStreamPeriodProfilePattern expectedProfilePattern = NewProfilePattern();

            GivenTheProfilePattern(expectedProfilePattern);

            FundingStreamPeriodProfilePattern actualProfilePattern = await WhenTheProfilePatternIsQueried(expectedProfilePattern.Id);

            actualProfilePattern
            .Should()
            .BeSameAs(expectedProfilePattern);
        }
示例#18
0
        public async Task CreatesDDLMatchingSpecificationFundingAndReCreatesSchemaObjectsInQaRepository()
        {
            string specificationId         = NewRandomString();
            string fundingStreamId         = NewRandomString();
            string fundingPeriodId         = NewRandomString();
            string templateVersion         = NewRandomString();
            string schemaVersion           = NewRandomString();
            string fundingTemplateContents = NewRandomString();

            Calculation calculationOne   = NewCalculation();
            Calculation calculationTwo   = NewCalculation();
            Calculation calculationThree = NewCalculation();
            Calculation calculationFour  = NewCalculation(_ => _.WithCalculations(calculationOne));
            Calculation calculationFive  = NewCalculation(_ => _.WithCalculations(calculationTwo));

            string fundingLineOneCode = NewRandomString();
            string fundingLineTwoCode = NewRandomString();

            SpecificationSummary specificationSummary = NewSpecificationSummary(_ => _.WithId(specificationId)
                                                                                .WithFundingStreamIds(fundingStreamId)
                                                                                .WithFundingPeriodId(fundingPeriodId)
                                                                                .WithTemplateIds((fundingStreamId, templateVersion)));
            FundingTemplateContents fundingTemplate = NewFundingTemplateContents(_ => _.WithSchemaVersion(schemaVersion)
                                                                                 .WithTemplateFileContents(fundingTemplateContents));
            TemplateMetadataContents templateMetadataContents = NewTemplateMetadataContents(_ => _.WithFundingLines(
                                                                                                NewFundingLine(fl => fl.WithCalculations(calculationFour,
                                                                                                                                         calculationFive)
                                                                                                               .WithFundingLineCode(fundingLineOneCode)
                                                                                                               .WithFundingLines(NewFundingLine(fl1 => fl1.WithCalculations(calculationThree)
                                                                                                                                                .WithFundingLineCode(fundingLineTwoCode)))
                                                                                                               )));

            FundingStreamPeriodProfilePattern profilePatternOne = NewFundingStreamPeriodProfilePattern(_ =>
                                                                                                       _.WithFundingPeriodId(fundingPeriodId)
                                                                                                       .WithFundingStreamId(fundingStreamId)
                                                                                                       .WithFundingLineId(fundingLineOneCode));
            FundingStreamPeriodProfilePattern profilePatternTwo = NewFundingStreamPeriodProfilePattern(_ =>
                                                                                                       _.WithFundingPeriodId(fundingPeriodId)
                                                                                                       .WithFundingStreamId(fundingStreamId)
                                                                                                       .WithFundingLineId(fundingLineTwoCode));

            GivenTheSpecification(specificationId, specificationSummary);
            AndTheFundingTemplate(fundingStreamId, fundingPeriodId, templateVersion, fundingTemplate);
            AndTheTemplateMetadataContents(schemaVersion, fundingTemplateContents, templateMetadataContents);
            AndTheProfiling(fundingStreamId, fundingPeriodId, profilePatternOne, profilePatternTwo);

            await WhenTheSchemaIsRecreated(specificationId, fundingStreamId);

            ThenTheTotalNumberOfDDLScriptsExecutedWas(32);
        }
        public void ProfileRequestValidator_ShouldReturnPatternWithValidRequestAAC1920()
        {
            // arrange
            FundingStreamPeriodProfilePattern pattern = new FundingStreamPeriodProfilePattern(
                "AY-1819",
                "PSG",
                "FL1",
                new DateTime(2019, 8, 1),
                new DateTime(2020, 7, 31),
                false,
                new[]
            {
                new ProfilePeriodPattern(
                    PeriodType.CalendarMonth,
                    "Aug",
                    new DateTime(2019, 8, 1),
                    new DateTime(2019, 8, 31),
                    2019,
                    1,
                    "FY1920",
                    12.56m),

                new ProfilePeriodPattern(
                    PeriodType.CalendarMonth,
                    "Apr",
                    new DateTime(2020, 4, 1),
                    new DateTime(2020, 4, 30),
                    2020,
                    1,
                    "FY2021",
                    12.56m)
            },
                "FSP-ProfilePattern1",
                "FSP-ProfilePatternDescription1",
                RoundingStrategy.RoundDown);

            ProfileRequest request = new ProfileRequest(
                "PSG",
                "AY-1819",
                "FL1",
                200);

            // act
            ProfileValidationResult validationResult = ProfileRequestValidator.ValidateRequestAgainstPattern(request, pattern);

            // assert
            validationResult
            .Code
            .Should().Be(HttpStatusCode.OK);
        }
        public static ProfileValidationResult ValidateRequestAgainstPattern(ProfileRequest request,
                                                                            FundingStreamPeriodProfilePattern profilePattern)
        {
            if (profilePattern == null)
            {
                if (string.IsNullOrEmpty(request.FundingPeriodId))
                {
                    return(ProfileValidationResult.BadRequest);
                }

                return(ProfileValidationResult.NotFound);
            }
            return(ProfileValidationResult.Ok);
        }
        public async Task GetByKeyComponentsDelegatesToCosmos()
        {
            FundingStreamPeriodProfilePattern expectedProfilePattern = NewProfilePattern();

            GivenTheProfilePattern(expectedProfilePattern);

            FundingStreamPeriodProfilePattern actualProfilePattern = await WhenTheProfilePatternIsQueried(expectedProfilePattern.FundingPeriodId,
                                                                                                          expectedProfilePattern.FundingStreamId,
                                                                                                          expectedProfilePattern.FundingLineId,
                                                                                                          expectedProfilePattern.ProfilePatternKey);

            actualProfilePattern
            .Should()
            .BeSameAs(expectedProfilePattern);
        }
        public async Task CalculateProfileService_ShouldCorrectlyCalculateNormalPESportsPremium()
        {
            // arrange
            FundingStreamPeriodProfilePattern pattern = TestResource.FromJson <FundingStreamPeriodProfilePattern>(
                NamespaceResourcesResideIn, "Resources.PESPORTSPREM.json");

            ProfileRequest peSportsPremReq = new ProfileRequest(
                fundingStreamId: "PSG",
                fundingPeriodId: "AY-1819",
                fundingLineCode: "FL1",
                fundingValue: 200);

            IProfilePatternRepository mockProfilePatternRepository = Substitute.For <IProfilePatternRepository>();

            mockProfilePatternRepository
            .GetProfilePattern(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(pattern);

            ICalculateProfileService calculateProfileService = GetCalculateProfileServiceWithMockedDependencies(mockProfilePatternRepository);

            // act
            IActionResult responseResult = await calculateProfileService.ProcessProfileAllocationRequest(peSportsPremReq);

            // assert
            responseResult
            .Should()
            .BeOfType <OkObjectResult>();

            OkObjectResult            responseAsOkObjectResult = responseResult as OkObjectResult;
            AllocationProfileResponse response = responseAsOkObjectResult.Value as AllocationProfileResponse;

            DeliveryProfilePeriod deliveryProfilePeriodReturnedForOct = response.DeliveryProfilePeriods.ToArray().FirstOrDefault(q => q.TypeValue == "October");
            DeliveryProfilePeriod deliveryProfilePeriodReturnedForApr = response.DeliveryProfilePeriods.ToArray().FirstOrDefault(q => q.TypeValue == "April");

            response.DeliveryProfilePeriods.Length.Should().Be(3);

            deliveryProfilePeriodReturnedForOct
            .Should().NotBeNull();
            deliveryProfilePeriodReturnedForOct
            .ProfileValue
            .Should().Be(117M);

            deliveryProfilePeriodReturnedForApr
            .Should().NotBeNull();
            deliveryProfilePeriodReturnedForApr
            .ProfileValue
            .Should().Be(83M);
        }
示例#23
0
        public async Task ProfilePatternQueryRepository_ShouldGetFundingStreamPeriodProfilePatternByIdIfExists()
        {
            // arrange
            FundingStreamPeriodProfilePattern fundingStreamPeriodProfilePattern = _fundingStreamPeriodProfilePatternBuilder.Build();
            var fundingStreamPeriodProfilePatternId = fundingStreamPeriodProfilePattern.Id;

            _mockCosmoRepository.Setup(x => x.ReadDocumentByIdAsync <FundingStreamPeriodProfilePattern>(fundingStreamPeriodProfilePatternId))
            .ReturnsAsync(new DocumentEntity <FundingStreamPeriodProfilePattern>(fundingStreamPeriodProfilePattern));

            // act
            var profilePattern = await _repository.GetProfilePattern(fundingStreamPeriodProfilePatternId);

            // assert
            profilePattern.Id.Should().Be(fundingStreamPeriodProfilePatternId);
            _mockCosmoRepository.Verify(x => x.ReadDocumentByIdAsync <FundingStreamPeriodProfilePattern>(It.Is <string>(id => id == fundingStreamPeriodProfilePatternId)), Times.Once);
        }
示例#24
0
        public async Task ProfilePatternQueryRepository_ShouldSaveGivenFundingStreamPeriodProfilePattern()
        {
            // arrange
            FundingStreamPeriodProfilePattern fundingStreamPeriodProfilePattern = _fundingStreamPeriodProfilePatternBuilder.Build();
            var fundingStreamPeriodProfilePatternId = fundingStreamPeriodProfilePattern.Id;

            _mockCosmoRepository.Setup(x => x.UpsertAsync(It.IsAny <FundingStreamPeriodProfilePattern>(), null, false, true))
            .ReturnsAsync(HttpStatusCode.OK);

            // act
            var result = await _repository.SaveFundingStreamPeriodProfilePattern(fundingStreamPeriodProfilePattern);

            // assert
            result.Should().Be(HttpStatusCode.OK);
            _mockCosmoRepository.Verify(x => x.UpsertAsync(It.Is <FundingStreamPeriodProfilePattern>(f => f.Id == fundingStreamPeriodProfilePatternId), null, false, true), Times.Once);
        }
示例#25
0
        public async Task ProfilePatternQueryRepository_ShouldDeleteFundingStreamPeriodProfilePatternById()
        {
            // arrange
            FundingStreamPeriodProfilePattern fundingStreamPeriodProfilePattern = _fundingStreamPeriodProfilePatternBuilder.Build();
            var fundingStreamPeriodProfilePatternId = fundingStreamPeriodProfilePattern.Id;

            _mockCosmoRepository.Setup(x => x.DeleteAsync <FundingStreamPeriodProfilePattern>(fundingStreamPeriodProfilePatternId, null, false))
            .ReturnsAsync(HttpStatusCode.OK);

            // act
            var result = await _repository.DeleteProfilePattern(fundingStreamPeriodProfilePatternId);

            // assert
            result.Should().Be(HttpStatusCode.OK);
            _mockCosmoRepository.Verify(x => x.DeleteAsync <FundingStreamPeriodProfilePattern>(It.Is <string>(id => id == fundingStreamPeriodProfilePatternId), null, false), Times.Once);
        }
        public async Task <IActionResult> ProcessProfileAllocationBatchRequest(ProfileBatchRequest profileBatchRequest)
        {
            Guard.ArgumentNotNull(profileBatchRequest, nameof(ProfileBatchRequest));

            ValidationResult validationResult = await _batchRequestValidation.ValidateAsync(profileBatchRequest);

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

            try
            {
                FundingStreamPeriodProfilePattern profilePattern = await GetProfilePattern(profileBatchRequest);

                if (profilePattern == null)
                {
                    _logger.Error("Unable to find profile pattern for FundingStream = {fundingStreamId}, FundingPeriodId={FundingPeriodId}, FundingLineCode={FundingLineCode}, ProfilePatternKey={ProfilePatternKey}, ProviderType={ProviderType}, ProviderSubType={ProviderSubType}",
                                  profileBatchRequest.FundingStreamId,
                                  profileBatchRequest.FundingPeriodId,
                                  profileBatchRequest.FundingLineCode,
                                  profileBatchRequest.ProfilePatternKey,
                                  profileBatchRequest.ProviderType,
                                  profileBatchRequest.ProviderSubType);
                }

                BatchProfileRequestContext batchProfileRequestContext = new BatchProfileRequestContext(profilePattern,
                                                                                                       profileBatchRequest,
                                                                                                       5);

                IProducerConsumer producerConsumer = _producerConsumerFactory.CreateProducerConsumer(ProduceProviderFundingValues,
                                                                                                     ProfileProviderFundingValues,
                                                                                                     10,
                                                                                                     10,
                                                                                                     _logger);

                await producerConsumer.Run(batchProfileRequestContext);

                return(new OkObjectResult(batchProfileRequestContext.Responses.ToArray()));
            }
            catch (Exception ex)
            {
                LogError(ex, profileBatchRequest);

                throw;
            }
        }
        public async Task <IActionResult> ProcessProfileAllocationRequest(ProfileRequest profileRequest)
        {
            Guard.ArgumentNotNull(profileRequest, nameof(profileRequest));

            _logger.Information($"Retrieved a request {profileRequest}");

            try
            {
                FundingStreamPeriodProfilePattern profilePattern = await GetProfilePattern(profileRequest);

                if (profilePattern == null)
                {
                    _logger.Error("Unable to find profile pattern for FundingStream = {fundingStreamId}, FundingPeriodId={FundingPeriodId}, FundingLineCode={FundingLineCode}, ProfilePatternKey={ProfilePatternKey}, ProviderType={ProviderType}, ProviderSubType={ProviderSubType}",
                                  profileRequest.FundingStreamId,
                                  profileRequest.FundingPeriodId,
                                  profileRequest.FundingLineCode,
                                  profileRequest.ProfilePatternKey,
                                  profileRequest.ProviderType,
                                  profileRequest.ProviderSubType);
                }

                ProfileValidationResult validationResult =
                    ProfileRequestValidator.ValidateRequestAgainstPattern(profileRequest, profilePattern);

                if (validationResult.Code != HttpStatusCode.OK)
                {
                    _logger.Information($"Returned status code of {validationResult.Code} for {profileRequest}");

                    return(new StatusCodeResult((int)validationResult.Code));
                }

                AllocationProfileResponse profilingResult = ProfileAllocation(profileRequest, profilePattern, profileRequest.FundingValue);
                profilingResult.ProfilePatternKey         = profilePattern.ProfilePatternKey;
                profilingResult.ProfilePatternDisplayName = profilePattern.ProfilePatternDisplayName;

                _logger.Information($"Returned Ok for {profileRequest}");

                return(new OkObjectResult(profilingResult));
            }
            catch (Exception ex)
            {
                LogError(ex, profileRequest);

                throw;
            }
        }
示例#28
0
        public void FailsValidationIfSameStrategyDoesntExist()
        {
            string increaseKey = NewRandomString();
            string decreaseKey = NewRandomString();
            string sameKey     = NewRandomString();

            FundingStreamPeriodProfilePattern pattern = NewFundingStreamPeriodProfilePattern(_ => _.WithProfilePatternReProfilingConfiguration(
                                                                                                 NewProfilePatternReProfilingConfiguration(rp => rp.WithDecreasedAmountStrategyKey(decreaseKey)
                                                                                                                                           .WithIncreasedAmountStrategyKey(increaseKey)
                                                                                                                                           .WithSameAmountStrategyKey(sameKey))));

            GivenTheStrategiesExist(increaseKey, decreaseKey);

            ValidationResult validationResult = WhenThePatternIsValidated(pattern);

            ThenTheValidationResultsAre(validationResult, ("ReProfilingConfiguration.SameAmountStrategyKey", "No matching strategy exists"));
        }
示例#29
0
        public async Task ProfilePatternQueryRepository_ShouldGetFundingStreamPeriodProfilePatternByProviderType()
        {
            // arrange
            string fundingPeriodId = NewRandomString();
            string fundingStreamId = NewRandomString();
            string fundingLineCode = NewRandomString();
            string providerType    = "Acade";
            string providerSubType = "11ACA";

            string queryText = null;
            IEnumerable <CosmosDbQueryParameter> parameters = Enumerable.Empty <CosmosDbQueryParameter>();

            FundingStreamPeriodProfilePattern fundingStreamPeriodProfilePattern = _fundingStreamPeriodProfilePatternBuilder
                                                                                  .WithProviderTypeSubTypes(new[] { new ProviderTypeSubType {
                                                                                                                        ProviderType = providerType, ProviderSubType = providerSubType
                                                                                                                    } })
                                                                                  .Build();
            var fundingStreamPeriodProfilePatternId = fundingStreamPeriodProfilePattern.Id;

            _mockCosmoRepository.Setup(x => x.QuerySql <FundingStreamPeriodProfilePattern>(It.IsAny <CosmosDbQuery>(), -1, null))
            .ReturnsAsync(new List <FundingStreamPeriodProfilePattern> {
                fundingStreamPeriodProfilePattern
            })
            .Callback <CosmosDbQuery, int, int?>((query, itemsPerPage, maxItemrs) => { queryText = query.QueryText; parameters = query.Parameters; });

            // act
            var profilePattern = await _repository.GetProfilePattern(fundingPeriodId, fundingStreamId, fundingLineCode, providerType, providerSubType);

            // assert
            profilePattern.Id.Should().Be(fundingStreamPeriodProfilePatternId);
            profilePattern.ProviderTypeSubTypes.First().ProviderType.Should().Be(providerType);
            profilePattern.ProviderTypeSubTypes.First().ProviderSubType.Should().Be(providerSubType);
            _mockCosmoRepository.Verify(x => x.QuerySql <FundingStreamPeriodProfilePattern>(It.IsAny <CosmosDbQuery>(), -1, null), Times.Once);
            queryText.Should().Be(@"SELECT 
                                *
                              FROM profilePeriodPattern p
                              WHERE p.documentType = 'FundingStreamPeriodProfilePattern'
                              AND p.deleted = false
                              AND p.content.fundingStreamId = @fundingStreamId
                              AND p.content.fundingPeriodId = @fundingPeriodId
                              AND p.content.fundingLineId = @fundingLineCode");
            parameters.Single(p => p.Name == "@fundingStreamId").Value.Should().Be(fundingStreamId);
            parameters.Single(p => p.Name == "@fundingPeriodId").Value.Should().Be(fundingPeriodId);
            parameters.Single(p => p.Name == "@fundingLineCode").Value.Should().Be(fundingLineCode);;
        }
        public async Task GetQueriesCosmosAndCachesResultIfNotCached()
        {
            FundingStreamPeriodProfilePattern expectedPattern = NewProfilePattern();

            GivenTheProfilePattern(expectedPattern);

            IActionResult result = await WhenTheProfilePatternIsQueried(expectedPattern.Id);

            result
            .Should()
            .BeOfType <OkObjectResult>();

            ((OkObjectResult)(result)).Value
            .Should()
            .BeSameAs(expectedPattern);

            AndTheProfilePatternWasCached(expectedPattern);
        }