示例#1
0
        public void GetCurrentPeriod_Success()
        {
            var httpClientMock       = new Mock <IBespokeHttpClient>();
            var serialisationService = new JsonSerializationService();
            var rp = new ReturnPeriod()
            {
                CollectionName   = "ILR1819",
                PeriodNumber     = 1,
                CalendarMonth    = 8,
                CalendarYear     = 2018,
                StartDateTimeUtc = new DateTime(2018, 8, 22),
                EndDateTimeUtc   = new DateTime(2018, 9, 04)
            };

            httpClientMock.Setup(x => x.GetDataAsync("testurl/api/returns-calendar/ILR1819/current")).ReturnsAsync(() => serialisationService.Serialize(rp));

            var pollyRegistryMock = new Mock <IReadOnlyPolicyRegistry <string> >();

            pollyRegistryMock.Setup(x => x.Get <IAsyncPolicy>("HttpRetryPolicy")).Returns(Policy.NoOpAsync);
            var apiSettings = new ApiSettings()
            {
                JobManagementApiBaseUrl = "testurl/api"
            };

            var service = new CollectionManagementService(httpClientMock.Object, apiSettings, new JsonSerializationService());
            var data    = service.GetCurrentPeriodAsync("ILR1819").Result;

            data.Should().NotBeNull();
            data.PeriodNumber.Should().Be(1);
        }
示例#2
0
        public async Task <IActionResult> IndividualCollectionsSubmit(ManageReturnPeriodViewModel model)
        {
            var openDateTime  = model.OpeningDate.Add(TimeSpan.Parse(model.OpeningTime));
            var closeDateTime = model.ClosingDate.Add(TimeSpan.Parse(model.ClosingTime));

            if (openDateTime > closeDateTime)
            {
                ModelState.AddModelError("Summary", "Error - close date time should be greater than the open date time.");
                return(View("IndividualPeriod", model));
            }

            var returnPeriod = new ReturnPeriod()
            {
                ReturnPeriodId = model.ReturnPeriodId,
                OpenDate       = _dateTimeProvider.ConvertUkToUtc(openDateTime),
                CloseDate      = _dateTimeProvider.ConvertUkToUtc(closeDateTime)
            };

            if (ModelState.IsValid && await _collectionsService.UpdateReturnPeriod(returnPeriod))
            {
                return(RedirectToAction("Index", new { collectionId = model.CollectionId }));
            }

            ModelState.AddModelError("Summary", "Error updating return period.");
            return(View("IndividualPeriod", model));
        }
        public async Task <string> GetTemplate(long jobId, JobStatusType status, JobType jobType, DateTime dateTimeJobSubmittedUtc)
        {
            using (IJobQueueDataContext context = _contextFactory())
            {
                var job = await context.FileUploadJobMetaData.SingleOrDefaultAsync(x => x.JobId == jobId);

                ReturnPeriod period = null;
                if (job != null)
                {
                    period = await GetReturnPeriod(job.CollectionName, dateTimeJobSubmittedUtc);
                }

                var emailTemplate = await
                                    context.JobEmailTemplate.SingleOrDefaultAsync(
                    x => x.JobType == (short)jobType && x.JobStatus == (short)status && x.Active.Value);

                if (emailTemplate == null)
                {
                    return(string.Empty);
                }

                if (period != null)
                {
                    return(emailTemplate.TemplateOpenPeriod);
                }

                return(emailTemplate.TemplateClosePeriod ?? emailTemplate.TemplateOpenPeriod);
            }
        }
示例#4
0
        public ICollection <ProviderSubmissionModel> Build(ProviderSubmissionsReferenceData referenceData)
        {
            ReturnPeriod period = referenceData.ILRPeriodsAdjustedTimes.Single(x => x.PeriodNumber == referenceData.ReturnPeriod);

            var organisationNameLookup = referenceData.OrgDetails.ToDictionary(o => o.Ukprn, o => o.Name);
            var fileDetailsLookup      = referenceData.FileDetails.ToDictionary(f => f.Filename, f => f, StringComparer.OrdinalIgnoreCase);
            var actualReturnersLookup  = new HashSet <long>(referenceData.ActualReturners);
            var modelUkprns            = new HashSet <long>(referenceData.FileDetails.Select(m => m.Ukprn));

            var providerSubmissionModels = referenceData.ProviderReturns
                                           .Select(p =>
            {
                var ukprn = p.Ukprn;

                var providerSubmissionModel = new ProviderSubmissionModel();

                providerSubmissionModel.Ukprn        = p.Ukprn;
                providerSubmissionModel.ReturnPeriod = p.ReturnPeriod;

                providerSubmissionModel.Expected     = referenceData.ExpectedReturns.Any(x => x.Ukprn == ukprn && ReturnExpected(x, period.StartDateTimeUtc, period.EndDateTimeUtc));
                providerSubmissionModel.Returned     = actualReturnersLookup.Contains(ukprn);
                providerSubmissionModel.LatestReturn = $"R{providerSubmissionModel.ReturnPeriod.ToString().PadLeft(2, '0')}";
                providerSubmissionModel.Returned     = providerSubmissionModel.ReturnPeriod == referenceData.ReturnPeriod;

                providerSubmissionModel.Name = organisationNameLookup.GetValueOrDefault(ukprn);

                var fileDetails = fileDetailsLookup.GetValueOrDefault(p.FileName.Replace(".ZIP", ".XML"));

                if (fileDetails != null)
                {
                    providerSubmissionModel.SubmittedDateTime = fileDetails.SubmittedTime;
                    providerSubmissionModel.TotalErrors       = fileDetails.TotalErrorCount;
                    providerSubmissionModel.TotalInvalid      = fileDetails.TotalInvalidLearnersSubmitted;
                    providerSubmissionModel.TotalValid        = fileDetails.TotalValidLearnersSubmitted;
                    providerSubmissionModel.TotalWarnings     = fileDetails.TotalWarningCount;
                }

                return(providerSubmissionModel);
            }).ToList();

            foreach (var org in referenceData.ExpectedReturns.Where(o => !modelUkprns.Contains(o.Ukprn)))
            {
                providerSubmissionModels.Add(new ProviderSubmissionModel
                {
                    Expected          = ReturnExpected(org, period.StartDateTimeUtc, period.EndDateTimeUtc),
                    LatestReturn      = string.Empty,
                    Name              = organisationNameLookup.GetValueOrDefault(org.Ukprn),
                    Returned          = false,
                    SubmittedDateTime = DateTime.MinValue,
                    TotalErrors       = 0,
                    TotalInvalid      = 0,
                    TotalValid        = 0,
                    TotalWarnings     = 0,
                    Ukprn             = org.Ukprn
                });
            }

            return(providerSubmissionModels);
        }
示例#5
0
        public async Task <ReturnPeriod> GetRecentlyClosedPeriodAsync(CancellationToken cancellationToken = default)
        {
            ReturnPeriod period = await _httpClientService.GetAsync <ReturnPeriod>($"{_baseUrl}/api/returns-calendar/closed", cancellationToken);

            AssertPeriodResponseValid(period);

            return(period);
        }
        public ReturnPeriod Convert(Data.Entities.ReturnPeriod data)
        {
            if (data == null)
            {
                return(null);
            }

            var period = new ReturnPeriod()
            {
                PeriodNumber     = data.PeriodNumber,
                EndDateTimeUtc   = data.EndDateTimeUtc,
                StartDateTimeUtc = data.StartDateTimeUtc,
                CalendarMonth    = data.CalendarMonth,
                CalendarYear     = data.CalendarYear,
                CollectionName   = data.Collection.Name
            };

            return(period);
        }
        public IEnumerable <ProviderSubmissionModel> BuildModel(
            List <ProviderSubmissionModel> models,
            IDictionary <long, string> orgDetails,
            List <OrganisationCollectionModel> expectedReturners,
            IEnumerable <long> actualReturners,
            IEnumerable <ReturnPeriod> periods,
            int currentPeriod)
        {
            ReturnPeriod period = periods.Single(x => x.PeriodNumber == currentPeriod);

            foreach (ProviderSubmissionModel providerSubmissionModel in models)
            {
                providerSubmissionModel.Expected = expectedReturners.Any(x => x.Ukprn == providerSubmissionModel.Ukprn && x.Expected(period.StartDateTimeUtc, period.EndDateTimeUtc));
                providerSubmissionModel.Returned = actualReturners.Any(x => x == providerSubmissionModel.Ukprn);
                GetLatestReturn(providerSubmissionModel, currentPeriod);
            }

            foreach (var org in expectedReturners)
            {
                if (models.Any(x => x.Ukprn == org.Ukprn))
                {
                    continue;
                }

                orgDetails.TryGetValue(org.Ukprn, out var orgName);

                models.Add(new ProviderSubmissionModel
                {
                    Expected          = org.Expected(period.StartDateTimeUtc, period.EndDateTimeUtc),
                    LatestReturn      = string.Empty,
                    Name              = orgName ?? string.Empty,
                    Returned          = false,
                    SubmittedDateTime = DateTime.MinValue,
                    TotalErrors       = 0,
                    TotalInvalid      = 0,
                    TotalValid        = 0,
                    TotalWarnings     = 0,
                    Ukprn             = org.Ukprn
                });
            }

            return(models);
        }
示例#8
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        public static void Main()
        {
            try
            {
                IServiceFabricConfigurationService serviceFabricConfigurationService = new ServiceFabricConfigurationService();
                ReturnPeriod returnPeriod = null;

                // License Aspose.Cells
                SoftwareLicenceSection softwareLicenceSection = serviceFabricConfigurationService.GetConfigSectionAs <SoftwareLicenceSection>(nameof(SoftwareLicenceSection));
                if (!string.IsNullOrEmpty(softwareLicenceSection.AsposeLicence))
                {
                    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(softwareLicenceSection.AsposeLicence.Replace("&lt;", "<").Replace("&gt;", ">"))))
                    {
                        new Aspose.Cells.License().SetLicense(ms);
                    }
                }

                // Setup Autofac
                ContainerBuilder builder = DIComposition.BuildContainer(serviceFabricConfigurationService);

                // Register the Autofac magic for Service Fabric support.
                builder.RegisterServiceFabricSupport();

                // Register the stateless service.
                builder.RegisterStatelessService <ServiceFabric.Common.Stateless>("ESFA.DC.PeriodEnd2021.ReportService.StatelessType");

                using (var container = builder.Build())
                {
                    ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(ServiceFabric.Common.Stateless).Name);

                    // Prevents this host process from terminating so services keep running.
                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceHostInitializationFailed(e + Environment.NewLine + (e.InnerException?.ToString() ?? "No inner exception"));
                throw;
            }
        }
        public async Task <ReturnPeriod> GetPeriodAsync(string collectionName, DateTime dateTimeUtc)
        {
            var data = await _collectionsManagementContext.ReturnPeriods.Include(x => x.Collection).Where(x =>
                                                                                                          x.Collection.Name == collectionName &&
                                                                                                          dateTimeUtc >= x.StartDateTimeUtc &&
                                                                                                          dateTimeUtc <= x.EndDateTimeUtc)
                       .FirstOrDefaultAsync();

            if (data != null)
            {
                var period = new ReturnPeriod()
                {
                    PeriodNumber     = data.PeriodNumber,
                    EndDateTimeUtc   = data.EndDateTimeUtc,
                    StartDateTimeUtc = data.StartDateTimeUtc,
                    CalendarMonth    = data.CalendarMonth,
                    CalendarYear     = data.CalendarYear,
                    CollectionName   = data.Collection.Name
                };
                return(period);
            }

            return(null);
        }
        /// <summary>
        /// Creates a context provider...
        /// </summary>
        /// <param name="onInstance">on instance.</param>
        /// <param name="forDataSource">for data source.</param>
        /// <param name="usingSourceForResults">if set to <c>true</c> [using source for results].</param>
        /// <param name="depositArtefacts">if set to <c>true</c> [deposit artefacts].</param>
        /// <param name="returnPeriod">The return period.</param>
        /// <returns>
        /// a connection context provider
        /// </returns>
        public IContainSessionContext Create(string onInstance, string thisUser, string thisPassword, IInputDataSource forDataSource, bool runMode, bool usingSourceForResults, bool depositArtefacts, ReturnPeriod returnPeriod)
        {
            var sourceLocation = CreateFor(onInstance, forDataSource.DBName, thisUser, thisPassword);

            var provider = new SessionContextContainer
            {
                Year = forDataSource.OperatingYear,
                //Master = CreateFor(onInstance, "master", thisUser, thisPassword),
                SourceLocation           = sourceLocation,
                ProcessingLocation       = CreateFor(onInstance, forDataSource.DBName, thisUser, thisPassword),
                RunMode                  = runMode ? TypeOfRunMode.Lite : TypeOfRunMode.Full,
                UsingSourceForResults    = usingSourceForResults,
                DepositRulebaseArtefacts = depositArtefacts,
                ReturnPeriod             = returnPeriod
            };

            provider.ResultsDestination = usingSourceForResults
                ? sourceLocation
                : CreateFor(onInstance, forDataSource.DBName, thisUser, thisPassword);

            return(provider);
        }
示例#11
0
        /// <summary>
        /// Does the secondary pass.
        /// </summary>
        /// <param name="onContent">on content.</param>
        /// <param name="withYear">with year.</param>
        /// <param name="andLocalServerName">and Local Server Name.</param>
        /// <returns>
        /// a de-tokenised string
        /// </returns>
        public static string DoSecondaryPass(string onContent, BatchOperatingYear withYear, IConnectionDetail usingConnection, ReturnPeriod returnPeriod, string fileName = "", string ukprn = "")
        {
            var unsupportedReturnPeriod = onContent.Contains(ForReturnPeriod) && It.IsInRange(returnPeriod, ReturnPeriod.None);

            unsupportedReturnPeriod
            .AsGuard <NotSupportedException, Localised>(Localised.UnsupportedReturnPeriod);

            return(onContent
                   .Replace(ForTargetDataStore, usingConnection.DBName)
                   .Replace(ForReturnPeriod, $"{returnPeriod}")
                   .Replace(ForOperatingYear, withYear.AsString())
                   .Replace(SecondaryPass.ForLocalServer, usingConnection.Container)
                   .Replace(SecondaryPass.ForContractPeriod, withYear.AsString())
                   .Replace(SecondaryPass.FileName, fileName)
                   .Replace(SecondaryPass.UKPRNToChange, ukprn));
        }