private async Task <SelectVenueModel> GetVenuesByUkprn(int ukprn)
        {
            var selectVenue = new SelectVenueModel
            {
                LabelText       = "Select course venue",
                HintText        = "Select all that apply.",
                AriaDescribedBy = "Select all that apply.",
                Ukprn           = ukprn
            };

            var venues = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
            {
                ProviderUkprn = ukprn
            });

            selectVenue.VenueItems = venues.Select(v => new VenueItemModel()
            {
                Id        = v.Id.ToString(),
                VenueName = v.VenueName
            }).ToList();

            if (selectVenue.VenueItems.Count == 1)
            {
                selectVenue.HintText        = string.Empty;
                selectVenue.AriaDescribedBy = string.Empty;
            }

            return(selectVenue);
        }
Esempio n. 2
0
            Task ImportFrameworksToCosmos()
            {
                const string csv     = "Framework.csv";
                var          records = ReadCsv <FrameworkRow>(csv).ToList();

                var excluded = records.Where(r => !IsValid(r));

                _logger.LogInformation($"{csv} - Excluded {excluded.Count()} of {records.Count()} rows due to out-of-range {nameof(FrameworkRow.EffectiveTo)}.");

                return(_cosmosDbQueryDispatcher.ExecuteQuery(new UpsertFrameworks()
                {
                    Now = _clock.UtcNow,
                    Records = records
                              .Where(IsValid)
                              .Select(r => new UpsertFrameworksRecord()
                    {
                        FrameworkCode = r.FworkCode,
                        ProgType = r.ProgType,
                        PathwayCode = r.PwayCode,
                        PathwayName = r.PathwayName,
                        NasTitle = r.NASTitle,
                        EffectiveFrom = r.EffectiveFrom,
                        EffectiveTo = r.EffectiveTo.Value,
                        SectorSubjectAreaTier1 = r.SectorSubjectAreaTier1,
                        SectorSubjectAreaTier2 = r.SectorSubjectAreaTier2
                    })
                }));

                bool IsValid(FrameworkRow r) => r.EffectiveTo.HasValue && r.EffectiveTo > _clock.UtcNow.Date;
            }
        public async Task <IActionResult> Index()
        {
            int?UKPRN = Session.GetInt32("UKPRN");

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

            PublishApprenticeshipsViewModel vm = new PublishApprenticeshipsViewModel();

            var apprenticeships = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetApprenticeships
            {
                Predicate = a =>
                            a.ProviderUKPRN == UKPRN &&
                            (a.RecordStatus == (int)ApprenticeshipStatus.BulkUploadPending || a.RecordStatus == (int)ApprenticeshipStatus.BulkUploadReadyToGoLive)
            });

            var bulkUploadPendingApprenticeships       = apprenticeships.Values.Where(a => a.RecordStatus == (int)ApprenticeshipStatus.BulkUploadPending).Select(Apprenticeship.FromCosmosDbModel).ToArray();
            var bulkUploadReadyToGoLiveApprenticeships = apprenticeships.Values.Where(a => a.RecordStatus == (int)ApprenticeshipStatus.BulkUploadReadyToGoLive).Select(Apprenticeship.FromCosmosDbModel).ToArray();

            vm.ListOfApprenticeships = await GetErrorMessages(bulkUploadPendingApprenticeships);

            if (!bulkUploadPendingApprenticeships.Any())
            {
                return(RedirectToAction("PublishYourFile", "BulkUploadApprenticeships", new
                {
                    NumberOfApprenticeships = bulkUploadReadyToGoLiveApprenticeships.Sum(a => a.ApprenticeshipLocations.Count(al => al.RecordStatus == ApprenticeshipStatus.BulkUploadReadyToGoLive))
                }));
            }

            vm.AreAllReadyToBePublished = true;

            return(View("Index", vm));
        }
Esempio n. 4
0
 public Task SyncAllApprenticeships() => WithExclusiveSqlLock(
     nameof(SyncAllApprenticeships),
     () => _cosmosDbQueryDispatcher.ExecuteQuery(
         new ProcessAllApprenticeships()
 {
     ProcessChunk = GetSyncWithBatchingHandler <Apprenticeship>(SyncApprenticeships)
 }));
        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 liveApprenticeships = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetApprenticeships
            {
                Predicate = a =>
                            a.ProviderUKPRN == UKPRN &&
                            a.RecordStatus == (int)ApprenticeshipStatus.Live
            });

            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(new ProviderApprenticeshipsViewModel
            {
                Apprenticeships = liveApprenticeships.Values.Select(Apprenticeship.FromCosmosDbModel).ToList()
            }));
        }
        public async Task <Guid?> GetProviderForCourse(Guid courseId)
        {
            var cacheKey = GetCourseCacheKey(courseId);

            if (!_cache.TryGetValue <Guid?>(cacheKey, out var providerId))
            {
                var ukprn = await _cosmosDbQueryDispatcher.ExecuteQuery(
                    new GetProviderUkprnForCourse()
                {
                    CourseId = courseId
                });

                if (ukprn.HasValue)
                {
                    providerId = await GetProviderIdByUkprn(ukprn);

                    _cache.Set(cacheKey, providerId);
                }
                else
                {
                    providerId = null;
                }
            }

            return(providerId);
        }
Esempio n. 7
0
        public async Task <ProviderInfo> GetProviderInfo(Guid providerId)
        {
            var cacheKey = GetCacheKey(providerId);

            ProviderInfo result = null;

            var cacheResult = await _cache.GetStringAsync(cacheKey);

            if (cacheResult != null)
            {
                try
                {
                    result = Deserialize(cacheResult);
                    _logger.LogDebug($"Got ProviderInfo from cache for provider {providerId}.");
                }
                catch (JsonSerializationException ex)
                {
                    // If we make a breaking change to ProviderInfo serialization could fail;
                    // force a reload in that case
                    _logger.LogWarning(ex, $"Failed deserializing ProviderInfo for provider {providerId}.");
                }
            }

            if (result == null)
            {
                var provider = await _cosmosDbQueryDispatcher.ExecuteQuery(
                    new GetProviderById()
                {
                    ProviderId = providerId
                });

                if (provider == null)
                {
                    return(null);
                }

                result = new ProviderInfo()
                {
                    ProviderId   = provider.Id,
                    Ukprn        = provider.Ukprn,
                    ProviderType = provider.ProviderType,
                    ProviderName = provider.ProviderName
                };

                var entryOptions = new DistributedCacheEntryOptions()
                {
                    SlidingExpiration = _slidingExpiration
                };
                await _cache.SetStringAsync(cacheKey, Serialize(result), entryOptions);

                _logger.LogDebug($"Added ProviderInfo to cache for provider {providerId}.");
            }

            return(result);
        }
        public Task SyncAllKnownProvidersData()
        {
            const int chunkSize = 200;

            return(_cosmosDbQueryDispatcher.ExecuteQuery(new ProcessAllProviders()
            {
                ProcessChunk = async providers =>
                {
                    foreach (var chunk in providers.Buffer(chunkSize))
                    {
                        await SyncProviderData(chunk.Select(p => p.Ukprn));
                    }
                }
            }));
        }
        public async Task <EditVenueFlowModel> CreateModel(Guid venueId)
        {
            var venue = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetVenueById()
            {
                VenueId = venueId
            });

            if (venue == null)
            {
                throw new ResourceDoesNotExistException(ResourceType.Venue, venueId);
            }

            return(new EditVenueFlowModel()
            {
                Email = venue.Email,
                Name = venue.VenueName,
                PhoneNumber = venue.PHONE,
                Website = venue.Website,
                AddressLine1 = venue.AddressLine1,
                AddressLine2 = venue.AddressLine2,
                Town = venue.Town,
                County = venue.County,
                Postcode = venue.Postcode,
                Latitude = venue.Latitude,
                Longitude = venue.Longitude
            });
        }
        public async Task <Success> Handle(Command request, CancellationToken cancellationToken)
        {
            ThrowIfFlowStateNotValid();

            var journeyInstance = _journeyInstanceProvider.GetInstance <AddVenueJourneyModel>();

            var venueId       = Guid.NewGuid();
            var providerUkprn = _providerContextProvider.GetProviderContext().ProviderInfo.Ukprn;

            await _cosmosDbQueryDispatcher.ExecuteQuery(new CreateVenue()
            {
                VenueId       = venueId,
                ProviderUkprn = providerUkprn,
                Name          = journeyInstance.State.Name,
                Email         = journeyInstance.State.Email,
                Telephone     = journeyInstance.State.Telephone,
                Website       = journeyInstance.State.Website,
                AddressLine1  = journeyInstance.State.AddressLine1,
                AddressLine2  = journeyInstance.State.AddressLine2,
                Town          = journeyInstance.State.Town,
                County        = journeyInstance.State.County,
                Postcode      = journeyInstance.State.Postcode,
                Latitude      = journeyInstance.State.Latitude,
                Longitude     = journeyInstance.State.Longitude,
                CreatedBy     = _currentUserProvider.GetCurrentUser(),
                CreatedDate   = _clock.UtcNow
            });

            journeyInstance.UpdateState(state => state.VenueId = venueId);

            // Complete JourneyInstance so state can no longer be changed
            journeyInstance.Complete();

            return(new Success());
        }
Esempio n. 11
0
        public async Task <Success> Handle(Command request, CancellationToken cancellationToken)
        {
            var result = await _cosmosDbQueryDispatcher.ExecuteQuery(new UpdateVenue()
            {
                VenueId      = request.VenueId,
                Name         = _journeyInstance.State.Name,
                Email        = _journeyInstance.State.Email,
                PhoneNumber  = _journeyInstance.State.PhoneNumber,
                Website      = _journeyInstance.State.Website,
                AddressLine1 = _journeyInstance.State.AddressLine1,
                AddressLine2 = _journeyInstance.State.AddressLine2,
                Town         = _journeyInstance.State.Town,
                County       = _journeyInstance.State.County,
                Postcode     = _journeyInstance.State.Postcode,
                Latitude     = _journeyInstance.State.Latitude,
                Longitude    = _journeyInstance.State.Longitude,
                UpdatedDate  = _clock.UtcNow,
                UpdatedBy    = _currentUserProvider.GetCurrentUser()
            });

            var venue = (Venue)result.Value;

            await _sqlDataSync.SyncVenue(venue);

            return(new Success());
        }
Esempio n. 12
0
 public Task SyncAllProviders() => WithExclusiveSqlLock(
     nameof(SyncAllProviders),
     () => _cosmosDbQueryDispatcher.ExecuteQuery(
         new ProcessAllProviders()
 {
     ProcessChunk = GetSyncWithBatchingHandler <Provider>(SyncProviders)
 }));
Esempio n. 13
0
        public async Task <FileStreamResult> GetApprenticeshipBulkUploadErrors(int?UKPRN)
        {
            if (!UKPRN.HasValue)
            {
                return(null);
            }

            var apprenticeships = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetApprenticeships
            {
                Predicate = a =>
                            a.ProviderUKPRN == UKPRN &&
                            ((a.RecordStatus & (int)RecordStatus.BulkUploadPending) > 0 || (a.RecordStatus & (int)RecordStatus.BulkUploadReadyToGoLive) > 0)
            });

            var apprenticeshipBUErrors = apprenticeships.Values.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()
        {
            int UKPRN = 0;

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

            var venues = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
            {
                ProviderUkprn = UKPRN
            });

            var items = venues.Select(v => new VenueSearchResultItemModel(
                                          v.VenueName,
                                          v.AddressLine1,
                                          v.AddressLine2,
                                          v.Town,
                                          v.County,
                                          v.Postcode,
                                          v.Id.ToString()));

            var model = new VenueSearchResultModel(
                searchTerm: UKPRN.ToString(),
                items,
                newItem: null,
                updated: false);

            return(ViewComponent(nameof(ViewComponents.VenueSearchResult.VenueSearchResult), model));
        }
        public async Task <IViewComponentResult> InvokeAsync(ChooseLocationModel model)
        {
            List <SelectListItem> venues = new List <SelectListItem>();

            var UKPRN = Session.GetInt32("UKPRN");

            if (UKPRN.HasValue)
            {
                var result = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
                {
                    ProviderUkprn = UKPRN.Value
                });

                foreach (var venue in result)
                {
                    var item = new SelectListItem {
                        Text = venue.VenueName, Value = venue.Id.ToString()
                    };

                    if (model.DeliveryLocations == null || !model.DeliveryLocations.Any(x => x.LocationId.HasValue && x.LocationId.Value.ToString() == item.Value))
                    {
                        venues.Add(item);
                    }
                }
                ;
            }

            model.Locations = venues;
            return(View("~/ViewComponents/Apprenticeships/ChooseLocation/Default.cshtml", model));
        }
        public static void VenueName <T>(
            this IRuleBuilderInitial <T, string> field,
            int providerUkprn,
            Guid?venueId,
            ICosmosDbQueryDispatcher cosmosDbQueryDispatcher)
        {
            field
            .NotEmpty()
            .WithMessage("Enter location name")
            .MaximumLength(Constants.NameMaxLength)
            .WithMessage($"Location name must be {Constants.NameMaxLength} characters or fewer")
            .MustAsync(async(name, _) =>
            {
                // Venue name must be distinct for this provider

                var providerVenues = await cosmosDbQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
                {
                    ProviderUkprn = providerUkprn
                });

                var otherVenuesWithSameName = providerVenues
                                              .Where(v => v.VenueName.Equals(name, StringComparison.OrdinalIgnoreCase))
                                              .Where(v => v.Id != venueId);

                return(!otherVenuesWithSameName.Any());
            })
            .WithMessage("Location name must not already exist");
        }
Esempio n. 17
0
        public async Task <IViewComponentResult> InvokeAsync(ChooseVenueModel model)
        {
            List <SelectListItem> venues = new List <SelectListItem>();

            var UKPRN = Session.GetInt32("UKPRN");

            if (UKPRN.HasValue)
            {
                var result = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
                {
                    ProviderUkprn = UKPRN.Value
                });

                var defaultItem = new SelectListItem {
                    Text = "Select", Value = ""
                };

                foreach (var venue in result)
                {
                    var item = new SelectListItem {
                        Text = venue.VenueName, Value = venue.Id.ToString()
                    };
                    venues.Add(item);
                }
                ;

                venues.Insert(0, defaultItem);
            }

            model.Venues = venues;
            return(View("~/ViewComponents/Courses/ChooseVenue/Default.cshtml", model));
        }
Esempio n. 18
0
 public Task SyncAllApprenticeships() => WithExclusiveSqlLock(
     nameof(SyncAllApprenticeships),
     () => _cosmosDbQueryDispatcher.ExecuteQuery(
         new ProcessAllApprenticeships()
 {
     ProcessChunk = async chunk =>
     {
         foreach (var c in chunk.Buffer(ApprenticeshipBatchSize))
         {
             await Policy
             .Handle <SqlException>()
             .Retry(3)
             .Execute(() => SyncApprenticeships(c));
         }
     }
 }));
        public async Task <OneOf <ModelWithErrors <ViewModel>, SuccessViewModel> > Handle(Command request, CancellationToken cancellationToken)
        {
            var ukprn = await GetUkprnForCourse(request.CourseId);

            var(course, courseRun) = await GetCourseAndCourseRun(request.CourseId, request.CourseRunId, ukprn);

            if (!request.Confirm)
            {
                var vm = await CreateViewModel(course, courseRun);

                var validationResult = new ValidationResult(new[]
                {
                    new ValidationFailure(nameof(request.Confirm), "Confirm you want to delete the course")
                });
                return(new ModelWithErrors <ViewModel>(vm, validationResult));
            }

            await _cosmosDbQueryDispatcher.ExecuteQuery(new DeleteCourseRunQuery()
            {
                CourseId      = request.CourseId,
                CourseRunId   = request.CourseRunId,
                ProviderUkprn = ukprn,
                UpdatedBy     = _currentUserProvider.GetCurrentUser().UserId,
                UpdatedDate   = _clock.UtcNow,
            });

            // The next page needs this info - stash it in the JourneyModel
            // since it will no longer able to query for it.
            _journeyInstance.UpdateState(new JourneyModel()
            {
                CourseName    = courseRun.CourseName,
                ProviderId    = (await _providerInfoCache.GetProviderIdForUkprn(ukprn)).Value,
                ProviderUkprn = ukprn
            });

            _journeyInstance.Complete();

            return(new SuccessViewModel()
            {
                CourseId = request.CourseId,
                CourseRunId = request.CourseRunId,
                CourseName = courseRun.CourseName
            });
        }
Esempio n. 20
0
        public async Task <ViewModel> Handle(Query request, CancellationToken cancellationToken)
        {
            var provider = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderById()
            {
                ProviderId = request.ProviderId
            });

            if (provider == null)
            {
                throw new ResourceDoesNotExistException(ResourceType.Provider, request.ProviderId);
            }

            var dashboardCounts = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderDashboardCounts
            {
                ProviderId = request.ProviderId,
                Date       = _clock.UtcNow.ToLocalTime().Date
            });

            var courseMigrationReport = await _cosmosDbQueryDispatcher.ExecuteQuery(new CosmosDbQueries.GetCourseMigrationReportForProvider {
                ProviderUkprn = provider.Ukprn
            });

            var bulkUploadFiles = await _binaryStorageProvider.ListFiles($"{provider.Ukprn}/Bulk Upload/Files/");

            var vm = new ViewModel()
            {
                ProviderName                                = provider.ProviderName,
                Ukprn                                       = provider.Ukprn,
                ShowCourses                                 = provider.ProviderType.HasFlag(ProviderType.FE),
                ShowApprenticeships                         = provider.ProviderType.HasFlag(ProviderType.Apprenticeships) && provider.ApprenticeshipQAStatus == ApprenticeshipQAStatus.Passed,
                ShowTLevels                                 = provider.ProviderType.HasFlag(ProviderType.TLevels),
                LiveCourseRunCount                          = dashboardCounts.CourseRunCounts.GetValueOrDefault(CourseStatus.Live),
                PastStartDateCourseRunCount                 = dashboardCounts.PastStartDateCourseRunCount,
                MigrationPendingCourseRunCount              = dashboardCounts.CourseRunCounts.GetValueOrDefault(CourseStatus.MigrationPending) + dashboardCounts.CourseRunCounts.GetValueOrDefault(CourseStatus.MigrationReadyToGoLive),
                BulkUploadPendingCourseRunCount             = dashboardCounts.CourseRunCounts.GetValueOrDefault(CourseStatus.BulkUploadPending),
                BulkUploadReadyToGoLiveCourseRunCount       = dashboardCounts.CourseRunCounts.GetValueOrDefault(CourseStatus.BulkUploadReadyToGoLive),
                BulkUploadCoursesErrorCount                 = dashboardCounts.BulkUploadCoursesErrorCount,
                BulkUploadCourseRunsErrorCount              = dashboardCounts.BulkUploadCourseRunsErrorCount,
                LarslessCourseCount                         = courseMigrationReport?.LarslessCourses?.Count ?? 0,
                ApprenticeshipCount                         = dashboardCounts.ApprenticeshipCounts.GetValueOrDefault(ApprenticeshipStatus.Live),
                BulkUploadPendingApprenticeshipsCount       = dashboardCounts.ApprenticeshipCounts.GetValueOrDefault(ApprenticeshipStatus.BulkUploadPending),
                BulkUploadReadyToGoLiveApprenticeshipsCount = dashboardCounts.ApprenticeshipCounts.GetValueOrDefault(ApprenticeshipStatus.BulkUploadReadyToGoLive),
                ApprenticeshipsBulkUploadErrorCount         = dashboardCounts.ApprenticeshipsBulkUploadErrorCount,
                TLevelCount                                 = dashboardCounts.TLevelCounts.GetValueOrDefault(TLevelStatus.Live),
                VenueCount                                  = dashboardCounts.VenueCount,
                BulkUploadFileCount                         = bulkUploadFiles.Count(),
                BulkUploadInProgress                        = provider.BulkUploadInProgress ?? false,
                IsNewProvider                               = provider.ProviderType == ProviderType.None
            };

            return(vm);
        }
Esempio n. 21
0
        public async Task <IActionResult> Upload()
        {
            _session.SetString("Option", "BulkUpload");
            int?UKPRN;

            if (_session.GetInt32("UKPRN") != null)
            {
                UKPRN = _session.GetInt32("UKPRN").Value;
            }
            else
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }

            var provider = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetProviderByUkprn { Ukprn = UKPRN.Value });

            if (null == provider)
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Failed to look up Provider details." }));
            }

            var courseCounts = _courseService.GetCourseCountsByStatusForUKPRN(new CourseSearchCriteria(UKPRN)).Result;
            var courseErrors = courseCounts.IsSuccess
                ? courseCounts.Value.Where(x => (int)x.Status == (int)RecordStatus.MigrationPending && x.Count > 0 || (int)x.Status == (int)RecordStatus.MigrationReadyToGoLive && x.Count > 0).Count()
                : 500;

            var model = new BulkUploadViewModel
            {
                HasMigrationErrors = courseErrors > 0 ? true : false,
            };

            if (null != provider.BulkUploadStatus)
            {
                model.BulkUploadBackgroundInProgress     = provider.BulkUploadStatus.InProgress;
                model.BulkUploadBackgroundRowCount       = provider.BulkUploadStatus.TotalRowCount;
                model.BulkUploadBackgroundStartTimestamp = provider.BulkUploadStatus.StartedTimestamp;
            }

            return(View(model));
        }
Esempio n. 22
0
        public async Task <ApprenticeshipVenueCorrection[]> AnalyseProviderApprenticeshipVenueReferences(
            [HttpTrigger(methods: "post")] List <int> ukprns,
            [Blob(ReportBlobContainer, Connection = BlobConnectionStringKey)] CloudBlobContainer cloudBlobContainer,
            CancellationToken shutdownCancellationToken)
        {
            await using var reportBlobStream = await GetReportBlobStream(cloudBlobContainer);


            var apprenticeships = await _cosmosDbQueryDispatcher.ExecuteQuery(
                new GetApprenticeships { Predicate = a => ukprns.Contains(a.ProviderUKPRN) });

            var apprenticeshipVenueCorrections = new List <ApprenticeshipVenueCorrection>();

            foreach (var apprenticeship in apprenticeships.Values)
            {
                apprenticeshipVenueCorrections.Add(await Analyse(apprenticeship));
            }

            var counts = AnalysisCounts.GetCounts(apprenticeshipVenueCorrections);

            LogCounts(counts, "Specified providers' apprenticeships analysed.");

            await WriteReport(reportBlobStream, apprenticeshipVenueCorrections);

            return(apprenticeshipVenueCorrections.ToArray());
        }
Esempio n. 23
0
        public async Task <OneOf <NotFound, Success> > Handle(OnboardProviderCommand request, CancellationToken cancellationToken)
        {
            var result = await _cosmosDbQueryDispatcher.ExecuteQuery(new UpdateProviderOnboarded
            {
                ProviderId      = request.ProviderId,
                UpdatedBy       = _currentUserProvider.GetCurrentUser(),
                UpdatedDateTime = _clock.UtcNow.ToLocalTime()
            });

            return(result.Match <OneOf <NotFound, Success> >(
                       notFound => notFound,
                       _ => new Success(),
                       success => success));
        }
        public async Task <ViewModel> Handle(Query request, CancellationToken cancellationToken)
        {
            var providerInfo = await _providerInfoCache.GetProviderInfo(request.ProviderId);

            var results = await _cosmosDbQueryDispatcher.ExecuteQuery(new CosmosQueries.GetAllCoursesForProvider
            {
                ProviderUkprn  = providerInfo.Ukprn,
                CourseStatuses = CourseStatus.BulkUploadReadyToGoLive,
            });

            return(new ViewModel {
                NumberOfCourses = results.SelectMany(c => c.CourseRuns).Count()
            });
        }
Esempio n. 25
0
        public async Task <IActionResult> Index(Guid?apprenticeshipId)
        {
            if (!Session.GetInt32("UKPRN").HasValue)
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }

            if (!apprenticeshipId.HasValue)
            {
                return(View("Error", new ErrorViewModel {
                    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
                }));
            }

            var result = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetApprenticeshipById { ApprenticeshipId = apprenticeshipId.Value });

            if (result == null)
            {
                return(View("Error", new ErrorViewModel {
                    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
                }));
            }

            var apprenticeship = Apprenticeship.FromCosmosDbModel(result);

            if (apprenticeship.ApprenticeshipLocations == null)
            {
                return(View("Error", new ErrorViewModel {
                    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
                }));
            }

            return(View("EditDeliveryMethod", new EditApprenticeshipViewModel
            {
                locations = apprenticeship.ApprenticeshipLocations
            }));
        }
        public async Task Execute(string input)
        {
            var locationIds = new HashSet <Guid>();

            await _cosmosDbQueryDispatcher.ExecuteQuery(new ProcessAllApprenticeships()
            {
                ProcessChunk = async chunk =>
                {
                    foreach (var apprenticeship in chunk)
                    {
                        var duplicateLocationIds = new List <Guid>();

                        foreach (var location in apprenticeship.ApprenticeshipLocations)
                        {
                            if (!locationIds.Add(location.Id))
                            {
                                duplicateLocationIds.Add(location.Id);
                            }
                        }

                        if (duplicateLocationIds.Any())
                        {
                            await _cosmosDbQueryDispatcher.ExecuteQuery(
                                new ReallocateDuplicateApprenticeshipLocationIds()
                            {
                                Apprenticeship       = apprenticeship,
                                DuplicateLocationIds = duplicateLocationIds,
                                UpdatedBy            = nameof(FixDuplicateApprenticeshipLocationIds),
                                UpdatedOn            = _clock.UtcNow
                            });
                            Debugger.Break();
                        }
                    }
                }
            });
        }
Esempio n. 27
0
        public async Task <FileStreamResult> DownloadCurrentApprenticeshipProvisions()
        {
            var UKPRN = _session.GetInt32("UKPRN");

            if (!UKPRN.HasValue)
            {
                return(null);
            }

            var provider = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetProviderByUkprn { Ukprn = UKPRN.Value });

            var providerName = provider?.ProviderName.Replace(" ", "");

            var apprenticeships = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetApprenticeships
            {
                Predicate = a =>
                            a.ProviderUKPRN == UKPRN &&
                            a.RecordStatus == (int)ApprenticeshipStatus.Live
            });

            var csvApprenticeships = await ApprenticeshipsToCsvApprenticeships(apprenticeships.Values.Select(Apprenticeship.FromCosmosDbModel));

            return(CsvApprenticeshipsToFileStream(csvApprenticeships, providerName));
        }
        public async Task <IActionResult> Index(Guid?apprenticeshipid, Apprenticeship request)
        {
            int?UKPRN;

            if (Session.GetInt32("UKPRN") != null)
            {
                UKPRN = Session.GetInt32("UKPRN").Value;
            }
            else
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }

            if (apprenticeshipid.HasValue)
            {
                var result = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetApprenticeshipById { ApprenticeshipId = apprenticeshipid.Value });

                if (result != null)
                {
                    EditApprenticeshipViewModel vm = new EditApprenticeshipViewModel
                    {
                        ApprenticeshipTitle = result.ApprenticeshipTitle,
                        Information         = result.MarketingInformation,
                        WebSite             = result.ContactWebsite,
                        Email        = result.ContactEmail,
                        Telephone    = result.ContactTelephone,
                        ContactUsURL = result.Url
                    };

                    return(View("EditApprenticeship", vm));
                }
            }
            return(View("Error", new ErrorViewModel {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
            }));
        }
Esempio n. 29
0
        public async Task Execute(string input)
        {
            using var listStream = typeof(RemoveApprenticeshipProvidersNotOnRoatp).Assembly.GetManifestResourceStream("Dfc.CourseDirectory.Functions.UkprnsNotOnRoatp.csv");
            using var reader     = new StreamReader(listStream);

            string line;
            var    lines = new List <string>();

            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line);
            }

            var ukprnsToRemoveProviderStatusFrom = new HashSet <int>(lines
                                                                     .Where(line => !string.IsNullOrWhiteSpace(line))
                                                                     .Select(line => int.Parse(line)));

            await _cosmosDbQueryDispatcher.ExecuteQuery(new ProcessAllProviders()
            {
                ProcessChunk = async providers =>
                {
                    foreach (var provider in providers)
                    {
                        if (provider.ProviderType.HasFlag(Core.Models.ProviderType.Apprenticeships) &&
                            ukprnsToRemoveProviderStatusFrom.Contains(provider.Ukprn))
                        {
                            await _cosmosDbQueryDispatcher.ExecuteQuery(new UpdateProviderType()
                            {
                                ProviderId   = provider.Id,
                                ProviderType = provider.ProviderType & (~Core.Models.ProviderType.Apprenticeships)
                            });
                        }
                    }
                }
            });
        }
Esempio n. 30
0
        public async Task <FileStreamResult> DownloadCurrentCourseProvisions()
        {
            var UKPRN = _session.GetInt32("UKPRN");

            if (!UKPRN.HasValue)
            {
                return(null);
            }

            var provider = await _cosmosDbQueryDispatcher.ExecuteQuery(new GetProviderByUkprn { Ukprn = UKPRN.Value });

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

            var courses = getCoursesResult
                          .Value
                          .Value
                          .SelectMany(o => o.Value)
                          .SelectMany(i => i.Value)
                          .Where(c => c.CourseStatus.HasFlag(RecordStatus.Live));

            var csvCourses = CoursesToCsvCourses(courses);

            return(CsvCoursesToFileStream(csvCourses, provider?.ProviderName.Replace(" ", "")));
        }