Пример #1
0
        public async Task GetFundingStreamById_GivenFundingStreamnWasNotFound_ReturnsNotFound()
        {
            // Arrange
            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "fundingStreamId", new StringValues(FundingStreamId) }
            });

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Query
            .Returns(queryStringValues);

            ILogger logger = CreateLogger();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetFundingStreamById(Arg.Is(FundingStreamId))
            .Returns((FundingStream)null);

            IFundingService fundingService = CreateService(specificationsRepository: specificationsRepository, logger: logger);

            // Act
            IActionResult result = await fundingService.GetFundingStreamById(request);

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

            logger
            .Received(1)
            .Error(Arg.Is($"No funding stream was found for funding stream id : {FundingStreamId}"));
        }
Пример #2
0
        public async Task GetFundingStreams_GivenFundingStreamsReturned_ReturnsOKWithResults()
        {
            // Arrange
            ILogger logger = CreateLogger();

            IEnumerable <FundingStream> fundingStreams = new[]
            {
                new FundingStream(),
                new FundingStream()
            };

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetFundingStreams()
            .Returns(fundingStreams);

            IFundingService fundingService = CreateService(logger: logger, specificationsRepository: specificationsRepository);

            // Act
            IActionResult result = await fundingService.GetFundingStreams();

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

            OkObjectResult objectResult = result as OkObjectResult;

            IEnumerable <FundingStream> values = objectResult.Value as IEnumerable <FundingStream>;

            values
            .Count()
            .Should()
            .Be(2);
        }
Пример #3
0
        private FM35Global RunFunding(FundingDto actorModel, CancellationToken cancellationToken)
        {
            if (ExecutionContext is ExecutionContext executionContextObj)
            {
                executionContextObj.JobId   = "-1";
                executionContextObj.TaskKey = ActorId.ToString();
            }

            ILogger logger = LifetimeScope.Resolve <ILogger>();

            IExternalDataCache externalDataCache;
            FM35Global         results;

            try
            {
                logger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} starting");

                externalDataCache = BuildExternalDataCache(actorModel.ExternalDataCache);

                logger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} finished getting input data");

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                logger.LogError($"Error while processing {nameof(FM35Actor)}", ex);
                throw;
            }

            using (var childLifetimeScope = LifetimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
            }))
            {
                ExecutionContext executionContext = (ExecutionContext)childLifetimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = actorModel.JobId.ToString();
                executionContext.TaskKey = ActorId.ToString();
                ILogger jobLogger = childLifetimeScope.Resolve <ILogger>();

                try
                {
                    jobLogger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} started processing");
                    IFundingService <FM35LearnerDto, FM35Global> fundingService = childLifetimeScope.Resolve <IFundingService <FM35LearnerDto, FM35Global> >();

                    var learners = BuildLearners <FM35LearnerDto>(actorModel.ValidLearners);

                    results = fundingService.ProcessFunding(actorModel.UKPRN, learners, cancellationToken);
                    jobLogger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} completed processing");
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    jobLogger.LogError($"Error while processing {nameof(FM35Actor)}", ex);
                    throw;
                }
            }

            externalDataCache = null;

            return(results);
        }
        public async Task GetFundingStreams_WhenServiceReturnsOkResult_ShouldReturnOkResultWithFundingStreams()
        {
            Models.Specs.FundingStream fundingStream = new Models.Specs.FundingStream()
            {
                AllocationLines = new List <Models.Specs.AllocationLine>()
                {
                    new Models.Specs.AllocationLine()
                    {
                        Id                 = "id",
                        Name               = "name",
                        ShortName          = "short-name",
                        FundingRoute       = Models.Specs.FundingRoute.LA,
                        IsContractRequired = true
                    }
                },
                Name      = "name",
                Id        = "id",
                ShortName = "short-name",
                RequireFinancialEnvelopes = true,
                PeriodType = new Models.Specs.PeriodType
                {
                    Id         = "p1",
                    Name       = "period 1",
                    StartDay   = 1,
                    EndDay     = 31,
                    StartMonth = 8,
                    EndMonth   = 7
                }
            };

            Mapper.Reset();
            MapperConfigurationExpression mappings = new MapperConfigurationExpression();

            mappings.AddProfile <ExternalApiMappingProfile>();
            Mapper.Initialize(mappings);
            IMapper mapper = Mapper.Instance;

            OkObjectResult specServiceOkObjectResult = new OkObjectResult(new[]
            {
                fundingStream
            });

            IFundingService mockFundingService = Substitute.For <IFundingService>();

            mockFundingService.GetFundingStreams().Returns(specServiceOkObjectResult);

            FundingStreamService fundingStreamService = new FundingStreamService(mockFundingService, mapper);

            // Act
            IActionResult result = await fundingStreamService.GetFundingStreams();

            // Assert
            result
            .Should().NotBeNull()
            .And
            .Subject.Should().BeOfType <OkObjectResult>();

            OkObjectResult okObjectResult = result as OkObjectResult;

            IEnumerable <FundingStream> fundingStreamResults = okObjectResult.Value as IEnumerable <FundingStream>;

            fundingStreamResults.Count().Should().Be(1);

            fundingStreamResults.First().Name.Should().Be("name");
            fundingStreamResults.First().Id.Should().Be("id");
            fundingStreamResults.First().ShortName.Should().Be("short-name");
            fundingStreamResults.First().RequireFinancialEnvelopes.Should().BeTrue();
            fundingStreamResults.First().PeriodType.Id.Should().Be("p1");
            fundingStreamResults.First().PeriodType.Name.Should().Be("period 1");
            fundingStreamResults.First().PeriodType.StartDay.Should().Be(1);
            fundingStreamResults.First().PeriodType.StartMonth.Should().Be(8);
            fundingStreamResults.First().PeriodType.EndDay.Should().Be(31);
            fundingStreamResults.First().PeriodType.EndMonth.Should().Be(7);
            fundingStreamResults.First().AllocationLines.First().Id.Should().Be("id");
            fundingStreamResults.First().AllocationLines.First().Name.Should().Be("name");
            fundingStreamResults.First().AllocationLines.First().ShortName.Should().Be("short-name");
            fundingStreamResults.First().AllocationLines.First().FundingRoute.Should().Be("LA");
            fundingStreamResults.First().AllocationLines.First().ContractRequired.Should().Be("Y");
        }
 public FundingController(IFundingService fundingService)
 {
     _fundingService = fundingService;
 }
Пример #6
0
 public TaskProviderService(IKeyValuePersistenceService keyValuePersistenceService, IPopulationService populationService, IPagingService <ILearner> learnerPerActorService, IFundingService <ILearner, FM35Global> fundingService, IJsonSerializationService jsonSerializationService)
 {
     _keyValuePersistenceService = keyValuePersistenceService;
     _populationService          = populationService;
     _learnerPerActorService     = learnerPerActorService;
     _fundingService             = fundingService;
     _jsonSerializationService   = jsonSerializationService;
 }
Пример #7
0
 public AcceptChannelMessageHandler(IChannelLoggingService channelLoggingService, IFundingService fundingService, ICommitmentTransactionService commitmentService)
 {
     _channelLoggingService = channelLoggingService;
     _fundingService        = fundingService;
     _commitmentService     = commitmentService;
 }
Пример #8
0
 public FundingMessageSignedHandler(IChannelLoggingService channelLoggingService, IFundingService fundingService,
                                    ICommitmentTransactionService commitmentService, IChannelService channelService, IBlockchainMonitorService blockchainMonitorService)
 {
     _channelLoggingService    = channelLoggingService;
     _fundingService           = fundingService;
     _commitmentService        = commitmentService;
     _channelService           = channelService;
     _blockchainMonitorService = blockchainMonitorService;
 }
        public async Task GetTimePeriods_WhenServiceReturns200OkResult_ShouldReturnOkResultWithFundingPeriods()
        {
            // Arrange
            Models.Specs.Period fundingPeriod1 = new Models.Specs.Period()
            {
                Id        = "AYCode",
                Name      = "AcademicYear",
                StartDate = DateTimeOffset.Now,
                EndDate   = DateTimeOffset.Now.AddYears(1)
            };
            Models.Specs.Period fundingPeriod2 = new Models.Specs.Period()
            {
                Id        = "FYCode",
                Name      = "FinalYear",
                StartDate = DateTimeOffset.Now,
                EndDate   = DateTimeOffset.Now.AddYears(1)
            };

            Mapper.Reset();
            MapperConfigurationExpression mappings = new MapperConfigurationExpression();

            mappings.AddProfile <ExternalApiMappingProfile>();
            Mapper.Initialize(mappings);
            IMapper mapper = Mapper.Instance;

            OkObjectResult specServiceOkObjectResult = new OkObjectResult(new List <Models.Specs.Period>
            {
                fundingPeriod1,
                fundingPeriod2
            });

            IFundingService mockFundingService = Substitute.For <IFundingService>();

            mockFundingService.GetFundingPeriods(Arg.Any <HttpRequest>()).Returns(specServiceOkObjectResult);

            TimePeriodsService serviceUnderTest = new TimePeriodsService(mockFundingService, mapper);

            // Act
            IActionResult result = await serviceUnderTest.GetFundingPeriods(Substitute.For <HttpRequest>());

            // Assert
            result
            .Should().NotBeNull()
            .And
            .Subject.Should().BeOfType <OkObjectResult>();

            OkObjectResult resultCasted = result as OkObjectResult;

            resultCasted.Value
            .Should().NotBeNull()
            .And
            .Subject.Should().BeOfType <List <V1.Models.Period> >();

            List <V1.Models.Period> resultPeriods = resultCasted.Value as List <V1.Models.Period>;

            resultPeriods
            .Count
            .Should()
            .Be(2);

            resultPeriods.ElementAt(0).Id.Should().Be("AYCode");
            resultPeriods.ElementAt(0).Name.Should().Be("AcademicYear");
            resultPeriods.ElementAt(0).StartYear.Should().Be(DateTimeOffset.Now.Year);
            resultPeriods.ElementAt(0).EndYear.Should().Be(DateTimeOffset.Now.Year + 1);
            resultPeriods.ElementAt(1).Id.Should().Be("FYCode");
            resultPeriods.ElementAt(1).Name.Should().Be("FinalYear");
            resultPeriods.ElementAt(1).StartYear.Should().Be(DateTimeOffset.Now.Year);
            resultPeriods.ElementAt(1).EndYear.Should().Be(DateTimeOffset.Now.Year + 1);
        }
Пример #10
0
 /// <summary>
 /// Instantiates a new insatance of the controller.
 /// </summary>
 /// <param name="fundingService"></param>
 /// <param name="mapper"></param>
 public FundingController(IFundingService fundingService, IMapper mapper)
 {
     _fundingService = fundingService;
     _mapper         = mapper;
 }
        private FM25Global RunFunding(FundingDto actorModel, CancellationToken cancellationToken)
        {
            if (ExecutionContext is ExecutionContext executionContextObj)
            {
                executionContextObj.JobId   = "-1";
                executionContextObj.TaskKey = ActorId.ToString();
            }

            ILogger logger = LifetimeScope.Resolve <ILogger>();

            IExternalDataCache externalDataCache;
            FM25Global         condensedResults;

            try
            {
                logger.LogDebug($"{nameof(FM25Actor)} {ActorId} starting");

                externalDataCache = BuildExternalDataCache(actorModel.ExternalDataCache);

                logger.LogDebug($"{nameof(FM25Actor)} {ActorId} finished getting input data");

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                logger.LogError($"Error while processing {nameof(FM25Actor)}", ex);
                throw;
            }

            using (var childLifetimeScope = LifetimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
            }))
            {
                ExecutionContext executionContext = (ExecutionContext)childLifetimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = actorModel.JobId.ToString();
                executionContext.TaskKey = ActorId.ToString();
                ILogger jobLogger = childLifetimeScope.Resolve <ILogger>();

                try
                {
                    jobLogger.LogDebug($"{nameof(FM25Actor)} {ActorId} {GC.GetGeneration(actorModel)} started processing");

                    IEnumerable <FM25Global>          fm25Results;
                    IEnumerable <PeriodisationGlobal> fm25PeriodisationResults;

                    using (var fundingServiceLifetimeScope = childLifetimeScope.BeginLifetimeScope(c =>
                    {
                        c.RegisterInstance(new FM25RulebaseProvider()).As <IRulebaseStreamProvider <FM25LearnerDto> >();
                    }))
                    {
                        jobLogger.LogDebug("FM25 Rulebase Starting");

                        IFundingService <FM25LearnerDto, IEnumerable <FM25Global> > fundingService = fundingServiceLifetimeScope.Resolve <IFundingService <FM25LearnerDto, IEnumerable <FM25Global> > >();

                        var learners = BuildLearners <FM25LearnerDto>(actorModel.ValidLearners);

                        fm25Results = fundingService.ProcessFunding(actorModel.UKPRN, learners, cancellationToken).ToList();

                        jobLogger.LogDebug("FM25 Rulebase Finishing");
                    }

                    using (var fundingServiceLifetimeScope = childLifetimeScope.BeginLifetimeScope(c =>
                    {
                        c.RegisterInstance(new FM25PeriodisationRulebaseProvider()).As <IRulebaseStreamProvider <FM25Global> >();
                    }))
                    {
                        jobLogger.LogDebug("FM25 Periodisation Rulebase Starting");

                        IFundingService <FM25Global, IEnumerable <PeriodisationGlobal> > periodisationService = fundingServiceLifetimeScope.Resolve <IFundingService <FM25Global, IEnumerable <PeriodisationGlobal> > >();

                        fm25PeriodisationResults = periodisationService.ProcessFunding(actorModel.UKPRN, fm25Results, cancellationToken).ToList();

                        jobLogger.LogDebug("FM25 Periodisation Rulebase Finishing");

                        IFM25FundingOutputCondenserService <FM25Global, PeriodisationGlobal> condenser = fundingServiceLifetimeScope.Resolve <IFM25FundingOutputCondenserService <FM25Global, PeriodisationGlobal> >();

                        condensedResults = condenser.CondensePeriodisationResults(fm25Results, fm25PeriodisationResults);
                    }

                    jobLogger.LogDebug($"{nameof(FM25Actor)} {ActorId} {GC.GetGeneration(actorModel)} completed processing");
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    jobLogger.LogError($"Error while processing {nameof(FM25Actor)}", ex);
                    throw;
                }
            }

            externalDataCache = null;

            return(condensedResults);
        }
        public async Task SaveFundingStream_GivenAllocationLinesWithProviderLookups_ReturnsOK()
        {
            //Arrange
            StringBuilder yaml = new StringBuilder();

            yaml.AppendLine("shortName: GIAS Test");
            yaml.AppendLine("allocationLines:");
            yaml.AppendLine("- fundingRoute: Provider");
            yaml.AppendLine("  isContractRequired: true");
            yaml.AppendLine("  shortName: 16 - 18 Tships Burs Fund");
            yaml.AppendLine("  id: 1618T - 001");
            yaml.AppendLine("  name: 16 - 18 Traineeships Bursary Funding");
            yaml.AppendLine("  providerLookups:");
            yaml.AppendLine("  - providerType: test1");
            yaml.AppendLine("    providerSubType: test2");
            yaml.AppendLine("- fundingRoute: Provider");
            yaml.AppendLine("  isContractRequired: true");
            yaml.AppendLine("  shortName: 16 - 18 Tships Prog Fund");
            yaml.AppendLine("  id: 1618T - 002");
            yaml.AppendLine("  name: 16 - 18 Traineeships Programme Funding");
            yaml.AppendLine("periodType:");
            yaml.AppendLine("  startDay: 1");
            yaml.AppendLine("  startMonth: 8");
            yaml.AppendLine("  endDay: 31");
            yaml.AppendLine("  endMonth: 7");
            yaml.AppendLine("  id: AY");
            yaml.AppendLine("  name: Schools Academic Year");
            yaml.AppendLine("id: GIASTEST");
            yaml.AppendLine("name: GIAS Test");

            byte[]       byteArray = Encoding.UTF8.GetBytes(yaml.ToString());
            MemoryStream stream    = new MemoryStream(byteArray);

            IHeaderDictionary headerDictionary = new HeaderDictionary
            {
                { "yaml-file", new StringValues(yamlFile) }
            };

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Headers
            .Returns(headerDictionary);

            request
            .Body
            .Returns(stream);

            ILogger logger = CreateLogger();

            HttpStatusCode statusCode = HttpStatusCode.Created;

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .SaveFundingStream(Arg.Any <FundingStream>())
            .Returns(statusCode);

            ICacheProvider cacheProvider = CreateCacheProvider();

            cacheProvider
            .KeyExists <FundingStream[]>(Arg.Is(CacheKeys.AllFundingStreams))
            .Returns(true);

            IFundingService service = CreateService(logger: logger, specificationsRepository: specificationsRepository, cacheProvider: cacheProvider);

            //Act
            IActionResult result = await service.SaveFundingStream(request);

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

            logger
            .Received(1)
            .Information(Arg.Is($"Successfully saved file: {yamlFile} to cosmos db"));

            await specificationsRepository
            .Received(1)
            .SaveFundingStream(Arg.Is <FundingStream>(f => f.AllocationLines.First().ProviderLookups.Count() == 1 && f.AllocationLines.First().ProviderLookups.First().ProviderType == "test1" && f.AllocationLines.First().ProviderLookups.First().ProviderSubType == "test2"));

            await cacheProvider
            .Received(1)
            .KeyDeleteAsync <FundingStream[]>(CacheKeys.AllFundingStreams);
        }