public IActionResult Index()
        {
            PublishApprenticeshipsViewModel vm = new PublishApprenticeshipsViewModel();
            int?UKPRN = Session.GetInt32("UKPRN");

            if (!UKPRN.HasValue)
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }
            var apprenticeships = _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.Value.ToString()).Result.Value.Where(x => x.RecordStatus == RecordStatus.BulkUploadPending);

            var getApprenticeships = _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.Value.ToString()).Result.Value.Where(x => x.ProviderUKPRN == UKPRN);

            vm.ListOfApprenticeships = apprenticeships;
            vm.ListOfApprenticeships = GetErrorMessages(vm.ListOfApprenticeships);

            if (!getApprenticeships.Any(x => x.RecordStatus == RecordStatus.BulkUploadPending))
            {
                vm.AreAllReadyToBePublished = true;
            }

            if (vm.AreAllReadyToBePublished)
            {
                return(RedirectToAction("PublishYourFile", "BulkUploadApprenticeships", new { NumberOfApprenticeships = apprenticeships.SelectMany(s => s.ApprenticeshipLocations.Where(cr => cr.RecordStatus == RecordStatus.BulkUploadReadyToGoLive)).Count() }));
            }
            return(View("Index", vm));
        }
Example #2
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
                                                     ILogger log,
                                                     [Inject] IApprenticeshipService apprenticeshipService)
        {
            string fromQuery = req.Query["UKPRN"];
            List <Apprenticeship> persisted = null;

            if (string.IsNullOrWhiteSpace(fromQuery))
            {
                return(new BadRequestObjectResult($"Empty or missing UKPRN value."));
            }

            if (!int.TryParse(fromQuery, out int UKPRN))
            {
                return(new BadRequestObjectResult($"Invalid UKPRN value, expected a valid integer"));
            }

            try
            {
                persisted = (List <Apprenticeship>) await apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN);

                if (persisted == null)
                {
                    return(new NotFoundObjectResult(UKPRN));
                }

                var tribalProviders = (List <TribalProvider>)apprenticeshipService.ApprenticeshipsToTribalProviders(persisted);
                return(new OkObjectResult(tribalProviders));
            }
            catch (Exception e)
            {
                return(new InternalServerErrorObjectResult(e));
            }
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
                                                     ILogger log,
                                                     [Inject] IApprenticeshipService apprenticeshipService)
        {
            List <Apprenticeship> persisted = null;


            try
            {
                persisted = (List <Apprenticeship>) await apprenticeshipService.GetUpdatedApprenticeships();

                if (persisted == null)
                {
                    return(new EmptyResult());
                }
                var listOfProviderUKPRN = persisted.Select(x => x.ProviderUKPRN.ToString())
                                          .Distinct()
                                          .ToList();
                List <Apprenticeship> totalList = new List <Apprenticeship>();
                foreach (var ukprn in listOfProviderUKPRN)
                {
                    var results = apprenticeshipService.GetApprenticeshipByUKPRN(int.Parse(ukprn)).Result;
                    if (results.Any())
                    {
                        totalList.AddRange((List <Apprenticeship>)results);
                    }
                }
                var providers = apprenticeshipService.ApprenticeshipsToTribalProviders(totalList);
                return(new OkObjectResult(providers));
            }
            catch (Exception e)
            {
                return(new InternalServerErrorObjectResult(e));
            }
        }
Example #4
0
        public FileStreamResult DownloadCurrentApprenticeshipProvisions()
        {
            int?   UKPRN;
            string providerName = String.Empty;

            if (_session.GetInt32("UKPRN").HasValue)
            {
                UKPRN = _session.GetInt32("UKPRN").Value;
                var providerSearchResult = _providerService.GetProviderByPRNAsync(UKPRN.Value.ToString()).Result.Value;
                providerName = providerSearchResult.FirstOrDefault()?.ProviderName.Replace(" ", "");
            }
            else
            {
                return(null);
            }

            var apprenticeships = _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.ToString())
                                  .Result
                                  .Value
                                  .Where((y => (int)y.RecordStatus == (int)RecordStatus.Live));

            var csvApprenticeships = ApprenticeshipsToCsvApprenticeships(apprenticeships);

            return(CsvApprenticeshipsToFileStream(csvApprenticeships, providerName));
        }
        public FileStreamResult GetApprenticeshipBulkUploadErrors(int?UKPRN)
        {
            if (!UKPRN.HasValue)
            {
                return(null);
            }

            var apprenticeships = _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.ToString())
                                  .Result.Value.Where((y => ((int)y.RecordStatus & (int)RecordStatus.BulkUploadPending) > 0 ||
                                                       ((int)y.RecordStatus & (int)RecordStatus.BulkUploadReadyToGoLive) > 0));
            //.Where((y => ((int)y. & (int)RecordStatus.BulkUploadPending) > 0
            //|| ((int)y.CourseStatus & (int)RecordStatus.BulkUploadReadyToGoLive) > 0));

            var apprenticeshipBUErrors = apprenticeships.Where(x => x.BulkUploadErrors != null).SelectMany(y => y.BulkUploadErrors).ToList();


            IEnumerable <string> headers  = new string[] { "Row Number,Column Name,Error Description" };
            IEnumerable <string> csvlines = apprenticeshipBUErrors.Select(i => string.Join(",", new string[] { i.LineNumber.ToString(), i.Header, i.Error.Replace(',', ' ') }));
            string report = string.Join(Environment.NewLine, headers.Concat(csvlines));

            byte[]       data = Encoding.ASCII.GetBytes(report);
            MemoryStream ms   = new MemoryStream(data)
            {
                Position = 0
            };

            FileStreamResult result = new FileStreamResult(ms, MediaTypeNames.Text.Plain);
            DateTime         d      = DateTime.Now;

            result.FileDownloadName = $"Bulk_upload_errors_{UKPRN}_{d.Day.TwoChars()}_{d.Month.TwoChars()}_{d.Year}_{d.Hour.TwoChars()}_{d.Minute.TwoChars()}.csv";
            return(result);
        }
        public async Task <IActionResult> Index(Guid?apprenticeshipId, string message)
        {
            int?UKPRN = Session.GetInt32("UKPRN");

            if (!UKPRN.HasValue)
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }
            var result = await _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.ToString());

            ProviderApprenticeshipsViewModel model = new ProviderApprenticeshipsViewModel();

            if (result.IsSuccess)
            {
                var allLiveProviderApprenticeships =
                    result.Value.Where(x => x.RecordStatus == RecordStatus.Live);

                model.Apprenticeships = new List <Apprenticeship>();
                foreach (var apprenticeship in allLiveProviderApprenticeships)
                {
                    model.Apprenticeships.Add(apprenticeship);
                }
            }

            if (apprenticeshipId.HasValue)
            {
                var linkMessage =
                    $"<a id=\"apprenticeshiplink\" class=\"govuk-link\" href=\"#\" data-apprenticeshipid=\"{apprenticeshipId.Value}\">{message}</a>";
                if (!string.IsNullOrEmpty(message))
                {
                    ViewBag.Message = linkMessage;
                }
                ViewBag.ApprenticeshipId = apprenticeshipId.Value;
            }

            return(View(model));
        }
        public async Task <IActionResult> CheckForCoursesOrApprenticeships(Guid VenueId)
        {
            int?UKPRN = Session.GetInt32("UKPRN");

            if (!UKPRN.HasValue)
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }

            var coursesByUKPRN = (await _courseService.GetYourCoursesByUKPRNAsync(new CourseSearchCriteria(UKPRN))).Value;

            var apprenticeships = await _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.ToString());

            var liveApprenticeships     = apprenticeships.Value?.Where(x => x.RecordStatus == RecordStatus.Live);
            var apprenticeshipLocations = liveApprenticeships.SelectMany(x => x.ApprenticeshipLocations).Where(x => (x.VenueId == VenueId || x.LocationGuidId == VenueId)).ToList();

            var courses = coursesByUKPRN.Value.SelectMany(o => o.Value).SelectMany(i => i.Value).ToList();

            var liveCourseRuns = courses.SelectMany(x => x.CourseRuns).Where(x => x.RecordStatus == Services.Models.RecordStatus.Live && x.VenueId == VenueId).ToList();

            var migrationPendingCourseRuns = courses.SelectMany(x => x.CourseRuns).Where(x => x.RecordStatus == Services.Models.RecordStatus.MigrationPending && x.VenueId == VenueId).ToList();

            var bulkUploadPendingCourseRuns = courses.SelectMany(x => x.CourseRuns).Where(x => x.RecordStatus == Services.Models.RecordStatus.BulkUploadPending && x.VenueId == VenueId).ToList();

            var migrationReadyForLiveCourseRuns = courses.SelectMany(x => x.CourseRuns).Where(x => x.RecordStatus == Services.Models.RecordStatus.MigrationReadyToGoLive && x.VenueId == VenueId).ToList();

            var bulkUploadReadyForLiveCourseRuns = courses.SelectMany(x => x.CourseRuns).Where(x => x.RecordStatus == Services.Models.RecordStatus.BulkUploadReadyToGoLive && x.VenueId == VenueId).ToList();

            var model = new DeleteVenueCheckViewModel()
            {
                LiveCoursesExist         = liveCourseRuns?.Count() > 0,
                PendingCoursesExist      = migrationPendingCourseRuns?.Count() > 0 || bulkUploadPendingCourseRuns?.Count() > 0 || migrationReadyForLiveCourseRuns?.Count() > 0 || bulkUploadReadyForLiveCourseRuns?.Count() > 0,
                LiveApprenticeshipsExist = apprenticeshipLocations?.Count() > 0
            };

            return(Ok(model));
        }
        public async Task <IActionResult> PublishYourFile()
        {
            int?sUKPRN = HttpContext.Session.GetInt32("UKPRN");

            if (!sUKPRN.HasValue)
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }

            var numberOfApprenticeships = 0;

            var model = new ApprenticeshipsPublishYourFileViewModel();

            var result = await _apprenticeshipService.GetApprenticeshipByUKPRN(sUKPRN.ToString());

            if (result.IsSuccess)
            {
                numberOfApprenticeships =
                    result.Value.Where(x => x.RecordStatus == RecordStatus.BulkUploadReadyToGoLive).Count();
            }
            model.NumberOfApprenticeships = numberOfApprenticeships;

            return(View("../BulkUploadApprenticeships/PublishYourFile/Index", model));
        }
        public async Task <IViewComponentResult> InvokeAsync(DashboardModel model)
        {
            var actualModel = model ?? new DashboardModel();

            int UKPRN = 0;

            if (Session.GetInt32("UKPRN").HasValue)
            {
                UKPRN = Session.GetInt32("UKPRN").Value;
            }

            var allVenues = await _venueService.SearchAsync(new VenueSearchCriteria(UKPRN.ToString(), ""));

            try
            {
                var getCoursesResult         = _courseService.GetYourCoursesByUKPRNAsync(new CourseSearchCriteria(UKPRN)).Result;
                IEnumerable <Course> courses = getCoursesResult
                                               .Value
                                               .Value
                                               .SelectMany(o => o.Value)
                                               .SelectMany(i => i.Value);

                IEnumerable <CourseRun> bulkUploadReadyToGoLive = courses.SelectMany(c => c.CourseRuns)
                                                                  .Where(x => x.RecordStatus == RecordStatus.BulkUploadReadyToGoLive);

                IEnumerable <Course> validCourses = courses.Where(c => c.IsValid);

                IEnumerable <CourseValidationResult> results = _courseService.CourseValidationMessages(validCourses.Where(x => ((int)x.CourseStatus & (int)RecordStatus.Live) > 0), ValidationMode.DataQualityIndicator).Value;

                IEnumerable <string> courseMessages = results.SelectMany(c => c.Issues);
                IEnumerable <string> runMessages    = results.SelectMany(c => c.RunValidationResults).SelectMany(r => r.Issues);
                IEnumerable <string> messages       = courseMessages.Concat(runMessages)
                                                      .GroupBy(i => i)
                                                      .Select(g => $"{ g.LongCount() } { g.Key }");

                IEnumerable <Course>    bulkUploadCoursesPending = courses.Where(x => ((int)x.CourseStatus & (int)RecordStatus.BulkUploadPending) > 0);
                IEnumerable <CourseRun> bulkUploadRunsPending    = courses.SelectMany(c => c.CourseRuns)
                                                                   .Where(x => x.RecordStatus == RecordStatus.BulkUploadPending);


                IEnumerable <CourseRun> migrationPendingCourses = courses.SelectMany(c => c.CourseRuns).Where(x => x.RecordStatus == RecordStatus.MigrationPending || x.RecordStatus == RecordStatus.MigrationReadyToGoLive);

                IEnumerable <Course> inValidCourses = courses.Where(c => c.IsValid == false);

                var getApprenticeshipResult = _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.ToString()).Result;



                var ApprenticeshipBulkUploadReadyToGoLive = _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.ToString()).Result.Value.Where(x => x.RecordStatus == RecordStatus.BulkUploadReadyToGoLive);

                actualModel.ApprenticeshipBulkUploadReadyToGoLiveCount = ApprenticeshipBulkUploadReadyToGoLive.Count();

                actualModel.BulkUploadPendingCount       = bulkUploadRunsPending.Count();
                actualModel.BulkUploadReadyToGoLiveCount = bulkUploadReadyToGoLive.Count();
                actualModel.BulkUploadTotalCount         = bulkUploadCoursesPending.Count() + bulkUploadReadyToGoLive.Count();


                IEnumerable <Services.BlobStorageService.BlobFileInfo> list = _blobStorageService.GetFileList(UKPRN + "/Bulk Upload/Files/").OrderByDescending(x => x.DateUploaded).ToList();
                if (list.Any())
                {
                    actualModel.FileUploadDate = list.FirstOrDefault().DateUploaded.Value;
                }

                var courseMigrationReportResult = await _courseService.GetCourseMigrationReport(UKPRN);

                var larslessCoursesCount = courseMigrationReportResult.IsSuccess
                    ? courseMigrationReportResult.Value.LarslessCourses.Count()
                    : 0;

                actualModel.DisplayMigrationButton = false;
                //list.Any() to see if any bulkupload files exist. If they do we don't want to show migration error.
                if ((migrationPendingCourses.Count() > 0 || larslessCoursesCount > 0) && !list.Any())
                {
                    actualModel.DisplayMigrationButton = true;
                }

                actualModel.BulkUpLoadHasErrors = bulkUploadCoursesPending?.SelectMany(c => c.BulkUploadErrors).Count() + bulkUploadRunsPending?.SelectMany(r => r.BulkUploadErrors).Count() > 0;

                string BulkUpLoadErrorMessage = actualModel.BulkUploadTotalCount.ToString() + WebHelper.GetCourseTextToUse(actualModel.BulkUploadTotalCount) + " uploaded in a file on "
                                                + actualModel.FileUploadDate?.ToString("dd/MM/yyyy") + " have "
                                                + (bulkUploadCoursesPending?.SelectMany(c => c.BulkUploadErrors).Count() + bulkUploadRunsPending?.SelectMany(r => r.BulkUploadErrors).Count()).ToString()
                                                + " errors. Fix these to publish all of your courses.";

                string BulkUpLoadNoErrorMessage = "Your bulk upload is complete." + actualModel.BulkUploadTotalCount.ToString() + WebHelper.GetCourseTextToUse(actualModel.BulkUploadPendingCount) + " have been uploaded on " + actualModel.FileUploadDate?.ToString("dd/MM/yyyy") + " and ready to publish to the course directory.";
                actualModel.FileCount = list.Count();

                int MigrationLiveCount = courses.Where(x => x.CourseStatus == RecordStatus.Live && x.CreatedBy == "DFC – Course Migration Tool")
                                         .SelectMany(c => c.CourseRuns)
                                         .Count(x => x.RecordStatus == RecordStatus.Live && x.CreatedBy == "DFC – Course Migration Tool");

                actualModel.BulkUploadMessage = (actualModel.BulkUploadTotalCount > 0 & actualModel.BulkUploadPendingCount == 0) ? BulkUpLoadNoErrorMessage : BulkUpLoadErrorMessage;


                actualModel.ValidationMessages = messages;
                actualModel.VenueCount         = 0;
                if (allVenues.Value != null)
                {
                    actualModel.VenueCount = allVenues.Value.Value.Count(x => x.Status == VenueStatus.Live);
                }

                actualModel.PublishedCourseCount = courses
                                                   .SelectMany(c => c.CourseRuns)
                                                   .Count(x => x.RecordStatus == RecordStatus.Live);

                var result = await _apprenticeshipService.GetApprenticeshipByUKPRN(UKPRN.ToString());

                var appResult = await _apprenticeshipService.GetApprenticeshipDashboardCounts(UKPRN);

                if (appResult.IsSuccess)
                {
                    var counts = appResult.Value;
                    IEnumerable <Services.BlobStorageService.BlobFileInfo> appList = _blobStorageService.GetFileList(UKPRN + "/Apprenticeship Bulk Upload/Files/").OrderByDescending(x => x.DateUploaded).ToList();
                    if (list.Any())
                    {
                        counts.FileUploadDate = list.FirstOrDefault().DateUploaded.Value;
                    }

                    var appMessages = GenerateApprenticeshipDQIMessages(counts);

                    if (!string.IsNullOrWhiteSpace(appMessages))
                    {
                        actualModel.ApprenticeshipMessages  = appMessages;
                        actualModel.ApprenticeshipHasErrors = true;
                    }

                    if (counts.TotalErrors != null && counts.TotalErrors > 0)
                    {
                        actualModel.ApprenticeshipBulkUploadHasErrors = true;
                    }
                    else
                    {
                        actualModel.ApprenticeshipBulkUploadHasErrors = false;
                    }
                }

                // provider has no apprenticeship but pending bulkupload
                if (!appResult.IsSuccess)
                {
                    var counts = appResult.Value;

                    if (counts == null && actualModel.ApprenticeshipBulkUploadReadyToGoLiveCount > 0)
                    {
                        //var appMessages =  actualModel.ApprenticeshipBulkUploadReadyToGoLiveCount.ToString() + WebHelper.GetCourseTextToUse(actualModel.ApprenticeshipBulkUploadReadyToGoLiveCount) + " uploaded on " + actualModel.FileUploadDate?.ToString("dd/MM/yyyy") + " have no errors, but are not listed on the Course directory because you have not published them.";
                        var appMessages = "Your bulk upload is complete." + actualModel.ApprenticeshipBulkUploadReadyToGoLiveCount.ToString() + WebHelper.GetApprenticeshipsTextToUse(actualModel.ApprenticeshipBulkUploadReadyToGoLiveCount) + " have been uploaded on " + actualModel.FileUploadDate?.ToString("dd/MM/yyyy") + "and ready to publish to the course directory.";
                        if (!string.IsNullOrWhiteSpace(appMessages))
                        {
                            actualModel.ApprenticeshipMessages = appMessages;
                        }
                    }
                }

                actualModel.PublishedApprenticeshipsCount = result.Value.Count(x => x.RecordStatus == RecordStatus.Live);

                var provider = FindProvider(UKPRN);

                if (null != provider)
                {
                    if (null != provider.BulkUploadStatus)
                    {
                        actualModel.BulkUploadBackgroundInProgress     = provider.BulkUploadStatus.InProgress;
                        actualModel.BulkUploadBackgroundRowCount       = provider.BulkUploadStatus.TotalRowCount;
                        actualModel.BulkUploadBackgroundStartTimestamp = provider.BulkUploadStatus.StartedTimestamp;
                        actualModel.BulkUploadPublishInProgress        = provider.BulkUploadStatus.PublishInProgress;
                    }
                    actualModel.ProviderType = provider.ProviderType;
                }
                actualModel.EnvironmentType = _environmentHelper.GetEnvironmentType();

                var providerId = _providerContextProvider.GetProviderContext().ProviderInfo.ProviderId;

                actualModel.ProviderQACurrentStatus = await _sqlQueryDispatcher.ExecuteQuery(
                    new GetProviderApprenticeshipQAStatus()
                {
                    ProviderId = providerId
                }) ?? Core.Models.ApprenticeshipQAStatus.NotStarted;
            }
            catch (Exception)
            {
                //@ToDo: decide how to handle this - should at least be logged. Caused by NPE during call to course service
                List <string> errors = new List <string>()
                {
                    "There was a system problem whilst obtaining course data from the course directory. Please wait a few moments and refresh your browser page."
                };
                actualModel.ValidationMessages = errors;
            }
            return(View("~/ViewComponents/Dashboard/Default.cshtml", actualModel));
        }