public async Task <Guid?> GetProviderForCourse(Guid courseId)
        {
            var cacheKey = GetCourseCacheKey(courseId);

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

                if (course != null)
                {
                    providerId = course.ProviderId;
                    _cache.Set(cacheKey, providerId);
                }
                else
                {
                    providerId = null;
                }
            }

            return(providerId);
        }
Example #2
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var providerId = _providerContextProvider.GetProviderContext().ProviderInfo.ProviderId;

            var qaStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderApprenticeshipQAStatus()
            {
                ProviderId = providerId
            });

            var submission = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestApprenticeshipQASubmissionForProvider()
            {
                ProviderId = providerId
            });

            var providerInfo = await _providerInfoCache.GetProviderInfo(providerId);

            var vm = new QANotificationsViewModel()
            {
                ProviderType         = providerInfo.ProviderType,
                Status               = qaStatus.ValueOrDefault(),
                HidePassedNotication = submission.Match(none => qaStatus == ApprenticeshipQAStatus.Passed, sub => sub.HidePassedNotification)
            };

            return(View("~/Features/NewApprenticeshipProvider/QANotifications.cshtml", vm));
        }
Example #3
0
        public async Task <IActionResult> Index(Guid?apprenticeshipid)
        {
            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 _sqlQueryDispatcher.ExecuteQuery(new GetApprenticeship { ApprenticeshipId = apprenticeshipid.Value });

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

                    return(View("EditApprenticeship", vm));
                }
            }

            return(NotFound());
        }
Example #4
0
        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 _sqlQueryDispatcher.ExecuteQuery(new GetApprenticeshipsForProvider()
            {
                ProviderId = _providerContextProvider.GetProviderId(withLegacyFallback: true)
            });

            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.Select(Apprenticeship.FromSqlModel).ToList()
            }));
        }
        public async Task <FlowModel> Initialize(Guid apprenticeshipId)
        {
            var maybeProviderId = await _providerOwnershipCache.GetProviderForApprenticeship(apprenticeshipId);

            if (!maybeProviderId.HasValue)
            {
                throw new InvalidStateException(InvalidStateReason.ApprenticeshipDoesNotExist);
            }

            var providerId = maybeProviderId.Value;

            var qaStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderApprenticeshipQAStatus()
            {
                ProviderId = providerId
            });

            var maybeLatestSubmission = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestApprenticeshipQASubmissionForProvider()
            {
                ProviderId = providerId
            });

            if (maybeLatestSubmission.Value is None)
            {
                throw new InvalidStateException(InvalidStateReason.NoValidApprenticeshipQASubmission);
            }

            var latestSubmission = maybeLatestSubmission.AsT1;

            var submissionApprenticeship = latestSubmission.Apprenticeships
                                           .SingleOrDefault(a => a.ApprenticeshipId == apprenticeshipId);

            if (submissionApprenticeship == null)
            {
                throw new InvalidStateException(InvalidStateReason.NoValidApprenticeshipQASubmission);
            }

            var latestAssessment = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestApprenticeshipQAApprenticeshipAssessmentForSubmission()
            {
                ApprenticeshipQASubmissionId = latestSubmission.ApprenticeshipQASubmissionId,
                ApprenticeshipId             = apprenticeshipId
            });

            return(new FlowModel()
            {
                ApprenticeshipId = apprenticeshipId,
                ProviderId = providerId,
                ComplianceComments = latestAssessment.Match(_ => string.Empty, v => v.ComplianceComments),
                ComplianceFailedReasons = latestAssessment.Match(_ => ApprenticeshipQAApprenticeshipComplianceFailedReasons.None, v => v.ComplianceFailedReasons),
                CompliancePassed = latestAssessment.Match(_ => null, v => v.CompliancePassed),
                StyleComments = latestAssessment.Match(_ => string.Empty, v => v.StyleComments),
                StyleFailedReasons = latestAssessment.Match(_ => ApprenticeshipQAApprenticeshipStyleFailedReasons.None, v => v.StyleFailedReasons),
                StylePassed = latestAssessment.Match(_ => null, v => v.StylePassed),
                IsReadOnly = !(qaStatus == ApprenticeshipQAStatus.Submitted || qaStatus == ApprenticeshipQAStatus.InProgress),
            });
        }
        public async Task <OneOf <ModelWithErrors <ViewModel>, Success> > Handle(
            Command request,
            CancellationToken cancellationToken)
        {
            ThrowIfFlowStateNotValid();

            var tLevelId    = Guid.NewGuid();
            var currentUser = _currentUserProvider.GetCurrentUser();
            var now         = _clock.UtcNow;

            var result = await _sqlQueryDispatcher.ExecuteQuery(
                new CreateTLevel()
            {
                CreatedBy          = currentUser,
                CreatedOn          = now,
                EntryRequirements  = _journeyInstance.State.EntryRequirements,
                HowYoullBeAssessed = _journeyInstance.State.HowYoullBeAssessed,
                HowYoullLearn      = _journeyInstance.State.HowYoullLearn,
                LocationVenueIds   = _journeyInstance.State.LocationVenueIds,
                ProviderId         = request.ProviderId,
                StartDate          = _journeyInstance.State.StartDate.Value,
                TLevelDefinitionId = _journeyInstance.State.TLevelDefinitionId.Value,
                TLevelId           = tLevelId,
                Website            = _journeyInstance.State.Website,
                WhatYouCanDoNext   = _journeyInstance.State.WhatYouCanDoNext,
                WhatYoullLearn     = _journeyInstance.State.WhatYoullLearn,
                WhoFor             = _journeyInstance.State.WhoFor,
                YourReference      = _journeyInstance.State.YourReference
            });

            if (result.Value is CreateTLevelFailedReason reason)
            {
                if (reason == CreateTLevelFailedReason.TLevelAlreadyExistsForDate)
                {
                    var vm = await CreateViewModel();

                    var validationResult = new ValidationResult(new[]
                    {
                        new ValidationFailure(
                            nameof(ViewModel.StartDate),
                            "T Level already exists, enter a new start date")
                    });

                    return(new ModelWithErrors <ViewModel>(vm, validationResult));
                }

                throw new NotImplementedException(
                          $"Unknown {nameof(CreateTLevelFailedReason)}: '{reason}'.");
            }

            _journeyInstance.UpdateState(state => state.SetCreatedTLevel(tLevelId));

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

            return(new Success());
        }
Example #7
0
        public async Task <JourneyModel> Initialize(Guid apprenticeshipId)
        {
            var maybeProviderId = await _providerOwnershipCache.GetProviderForApprenticeship(apprenticeshipId);

            if (!maybeProviderId.HasValue)
            {
                throw new ResourceDoesNotExistException(ResourceType.Apprenticeship, apprenticeshipId);
            }

            var providerId = maybeProviderId.Value;

            var qaStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderApprenticeshipQAStatus()
            {
                ProviderId = providerId
            });

            var latestSubmission = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestApprenticeshipQASubmissionForProvider()
            {
                ProviderId = providerId
            });

            if (latestSubmission == null)
            {
                throw new InvalidStateException(InvalidStateReason.NoValidApprenticeshipQASubmission);
            }

            var submissionApprenticeship = latestSubmission.Apprenticeships
                                           .SingleOrDefault(a => a.ApprenticeshipId == apprenticeshipId);

            if (submissionApprenticeship == null)
            {
                throw new InvalidStateException(InvalidStateReason.NoValidApprenticeshipQASubmission);
            }

            var latestAssessment = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestApprenticeshipQAApprenticeshipAssessmentForSubmission()
            {
                ApprenticeshipQASubmissionId = latestSubmission.ApprenticeshipQASubmissionId,
                ApprenticeshipId             = apprenticeshipId
            });

            return(new JourneyModel()
            {
                ApprenticeshipId = apprenticeshipId,
                ProviderId = providerId,
                ComplianceComments = latestAssessment?.ComplianceComments,
                ComplianceFailedReasons = latestAssessment?.ComplianceFailedReasons,
                CompliancePassed = latestAssessment?.CompliancePassed,
                StyleComments = latestAssessment?.StyleComments,
                StyleFailedReasons = latestAssessment?.StyleFailedReasons,
                StylePassed = latestAssessment?.StylePassed,
                IsReadOnly = !(qaStatus == ApprenticeshipQAStatus.Submitted || qaStatus == ApprenticeshipQAStatus.InProgress),
            });
        }
Example #8
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);
        }
        public async Task <ViewModel> Handle(Query request, CancellationToken cancellationToken)
        {
            var providerContext = _providerContextProvider.GetProviderContext();

            var counts = await _sqlQueryDispatcher.ExecuteQuery(new GetProviderDashboardCounts()
            {
                ProviderId = providerContext.ProviderInfo.ProviderId,
                Date       = _clock.UtcNow.Date
            });

            var qaStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderApprenticeshipQAStatus()
            {
                ProviderId = providerContext.ProviderInfo.ProviderId,
            });

            var providerType = providerContext.ProviderInfo.ProviderType;

            var venueUploadStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestUnpublishedVenueUploadForProvider()
            {
                ProviderId = providerContext.ProviderInfo.ProviderId
            });

            var courseUploadStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestUnpublishedCourseUploadForProvider()
            {
                ProviderId = providerContext.ProviderInfo.ProviderId
            });

            var apprenticeshipUploadStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestUnpublishedApprenticeshipUploadForProvider()
            {
                ProviderId = providerContext.ProviderInfo.ProviderId
            });

            return(new ViewModel()
            {
                PublishedApprenticeshipsCount = counts.ApprenticeshipCounts.GetValueOrDefault(ApprenticeshipStatus.Live, 0),
                PublishedCourseCount = counts.CourseRunCount,
                PublishedVenueCount = counts.VenueCount,
                ShowApprenticeships = providerType.HasFlag(ProviderType.Apprenticeships) && qaStatus == ApprenticeshipQAStatus.Passed,
                ShowCourses = providerType.HasFlag(ProviderType.FE),
                VenueUploadInProgress = venueUploadStatus != null && (venueUploadStatus.UploadStatus == UploadStatus.Processing || venueUploadStatus.UploadStatus == UploadStatus.Created),
                UnpublishedVenueCount = counts.UnpublishedVenueCount,
                UnpublishedCourseCount = counts.UnpublishedCourseCount,
                CourseUploadInProgress = courseUploadStatus != null && (courseUploadStatus.UploadStatus == UploadStatus.Processing || courseUploadStatus.UploadStatus == UploadStatus.Created),
                ApprenticeshipUploadInProgress = apprenticeshipUploadStatus != null && (apprenticeshipUploadStatus.UploadStatus == UploadStatus.Processing || apprenticeshipUploadStatus.UploadStatus == UploadStatus.Created),
                UnpublishedApprenticeshipCount = counts.UnpublishedApprenticeshipCount
            });
        }
        public async Task <ViewModel> Handle(Query request, CancellationToken cancellationToken)
        {
            var provider = await _cosmosDbQueryDispatcher.ExecuteQuery(
                new Core.DataStore.CosmosDb.Queries.GetProviderById()
            {
                ProviderId = request.ProviderId
            });

            if (provider == null)
            {
                throw new InvalidStateException(InvalidStateReason.ProviderDoesNotExist);
            }

            var qaStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderApprenticeshipQAStatus()
            {
                ProviderId = request.ProviderId
            });

            var maybeLatestSubmission = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestApprenticeshipQASubmissionForProvider()
            {
                ProviderId = request.ProviderId
            });

            var latestSubmission = maybeLatestSubmission.Value as ApprenticeshipQASubmission;

            var canComplete = qaStatus == ApprenticeshipQAStatus.InProgress && latestSubmission.Passed != null;

            return(new ViewModel()
            {
                ApprenticeshipAssessments = latestSubmission?.Apprenticeships
                                            .Select(a => new ViewModelApprenticeshipSubmission()
                {
                    ApprenticeshipId = a.ApprenticeshipId,
                    ApprenticeshipTitle = a.ApprenticeshipTitle,
                    AssessmentCompleted = latestSubmission.ApprenticeshipAssessmentsPassed != null
                })
                                            .ToList(),
                ApprenticeshipQAStatus = qaStatus.ValueOrDefault(),
                HaveSubmission = latestSubmission != null,
                CanComplete = canComplete,
                ProviderAssessmentCompleted = latestSubmission?.ProviderAssessmentPassed != null,
                ProviderId = request.ProviderId,
                ProviderName = provider.ProviderName,
                SubmissionPassed = latestSubmission?.Passed
            });
        }
        public async Task <ViewModel> Handle(Query request, CancellationToken cancellationToken)
        {
            var cosmosProvider = await _cosmosDbQueryDispatcher.ExecuteQuery(new CosmosQueries.GetProviderById()
            {
                ProviderId = request.ProviderId
            });

            var sqlProvider = await _sqlQueryDispatcher.ExecuteQuery(new SqlQueries.GetProviderById()
            {
                ProviderId = request.ProviderId
            });

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

            var currentUser = _currentUserProvider.GetCurrentUser();

            var providerTLevelDefinitions = cosmosProvider.ProviderType.HasFlag(ProviderType.TLevels)
                ? await _sqlQueryDispatcher.ExecuteQuery(new SqlQueries.GetTLevelDefinitionsForProvider {
                ProviderId = request.ProviderId
            })
                : Enumerable.Empty <SqlModels.TLevelDefinition>();

            return(new ViewModel()
            {
                ProviderId = request.ProviderId,
                ProviderName = cosmosProvider.ProviderName,
                CourseDirectoryStatus = cosmosProvider.ProviderStatus,
                Ukprn = cosmosProvider.Ukprn,
                TradingName = cosmosProvider.Alias,
                DisplayName = sqlProvider.DisplayName,
                CanChangeDisplayName = sqlProvider.HaveAlias && AuthorizationRules.CanUpdateProviderDisplayName(currentUser),
                ProviderType = cosmosProvider.ProviderType,
                CanChangeProviderType = AuthorizationRules.CanUpdateProviderType(currentUser),
                MarketingInformation = cosmosProvider.MarketingInformation != null?
                                       Html.SanitizeHtml(cosmosProvider.MarketingInformation) :
                                           null,
                                           ShowMarketingInformation = cosmosProvider.ProviderType.HasFlag(ProviderType.Apprenticeships),
                                           CanUpdateMarketingInformation = AuthorizationRules.CanUpdateProviderMarketingInformation(currentUser),
                                           ProviderTLevelDefinitions = providerTLevelDefinitions.Select(d => new TLevelDefinitionViewModel
                {
                    TLevelDefinitionId = d.TLevelDefinitionId,
                    Name = d.Name
                })
            });
        }
        private async Task <ViewModel> CreateViewModel(IReadOnlyCollection <CourseUploadRow> rows)
        {
            var learningDelivery = (await _sqlQueryDispatcher.ExecuteQuery(new GetLearningDeliveries()
            {
                LearnAimRefs = rows.Select(x => x.LearnAimRef).Distinct().ToArray()
            }));

            return(new ViewModel()
            {
                RowGroups = rows
                            .GroupBy(t => t.CourseId)
                            .Select(g => new ViewModelRowGroup()
                {
                    CourseId = g.Key,
                    LearnAimRef = g.Select(r => r.LearnAimRef).Distinct().Single(),
                    LearnAimRefTitle = learningDelivery[g.Select(r => r.LearnAimRef).Distinct().Single()].LearnAimRefTitle,
                    CourseRows = g
                                 .Select(r => new ViewModelRow()
                    {
                        CourseName = r.CourseName,
                        StartDate = r.StartDate,
                        DeliveryMode = r.DeliveryMode
                    })
                                 .OrderBy(r => r.StartDate)
                                 .ThenBy(r => r.DeliveryMode)
                                 .ToArray()
                })
                            .OrderBy(g => g.LearnAimRef)
                            .ThenBy(g => g.CourseId)
                            .ToArray(),
                RowCount = rows.Count
            });
        }
Example #13
0
        public async Task <ViewModel> Handle(Query request, CancellationToken cancellationToken)
        {
            var results = await _sqlQueryDispatcher.ExecuteQuery(new GetVenuesByProvider { ProviderId = request.ProviderId });

            return(new ViewModel
            {
                Venues = results
                         .Select(r => new VenueViewModel
                {
                    VenueId = r.VenueId,
                    VenueName = r.VenueName,
                    ProviderVenueRef = r.ProviderVenueRef,
                    AddressParts = new[]
                    {
                        r.AddressLine1,
                        r.AddressLine2,
                        r.Town,
                        r.County,
                        r.Postcode
                    }.Where(part => !string.IsNullOrWhiteSpace(part)).ToArray()
                })
                         .OrderBy(v => v.VenueName)
                         .ToArray()
            });
        }
Example #14
0
        private async Task <ViewModel> CreateViewModel(int rowNumber)
        {
            var providerId = _providerContextProvider.GetProviderId();

            var rootRow = await _fileUploadProcessor.GetCourseUploadRowDetailForProvider(providerId, rowNumber);

            if (rootRow == null)
            {
                throw new ResourceDoesNotExistException(ResourceType.CourseUploadRow, rowNumber);
            }

            var rowGroup = await _fileUploadProcessor.GetCourseUploadRowGroupForProvider(providerId, rootRow.CourseId);

            var deliveryModes = DeduceDeliveryModes();

            var groupErrors = rowGroup.First().Errors
                              .Where(e => Core.DataManagement.Errors.GetCourseErrorComponent(e) == CourseErrorComponent.Course)
                              .ToArray();

            var learnAimRef      = rowGroup.Select(r => r.LearnAimRef).Distinct().Single();
            var learningDelivery = (await _sqlQueryDispatcher.ExecuteQuery(new GetLearningDeliveries()
            {
                LearnAimRefs = new[] { learnAimRef }
            }))[learnAimRef];

            return(new ViewModel()
            {
                DeliveryModes = deliveryModes,
                LearnAimRef = learnAimRef,
                LearnAimRefTitle = learningDelivery.LearnAimRefTitle,
                RowNumber = rowNumber,
                GroupErrorFields = groupErrors.Select(e => Core.DataManagement.Errors.MapCourseErrorToFieldGroup(e)).Distinct().ToArray()
            });

            IReadOnlyCollection <CourseDeliveryMode> DeduceDeliveryModes()
            {
                var deliveryModes = new HashSet <CourseDeliveryMode>();

                var allRowsHaveValidDeliveryMode = true;

                foreach (var row in rowGroup)
                {
                    var rowDeliveryMode = ParsedCsvCourseRow.ResolveDeliveryMode(row.DeliveryMode);

                    if (rowDeliveryMode != null)
                    {
                        deliveryModes.Add(rowDeliveryMode.Value);
                    }
                    else
                    {
                        allRowsHaveValidDeliveryMode = false;
                        break;
                    }
                }

                return((allRowsHaveValidDeliveryMode ? deliveryModes : (IEnumerable <CourseDeliveryMode>)_allDeliveryModes)
                       .OrderBy(dm => (int)dm)
                       .ToArray());
            }
        }
        public async Task <EditTLevelJourneyModel> CreateModel(Guid tLevelId)
        {
            var tLevel = await _sqlQueryDispatcher.ExecuteQuery(new GetTLevel()
            {
                TLevelId = tLevelId
            });

            if (tLevel == null)
            {
                throw new ResourceDoesNotExistException(ResourceType.TLevel, tLevelId);
            }

            return(new EditTLevelJourneyModel()
            {
                EntryRequirements = tLevel.EntryRequirements,
                HowYoullBeAssessed = tLevel.HowYoullBeAssessed,
                HowYoullLearn = tLevel.HowYoullLearn,
                LocationVenueIds = tLevel.Locations.Select(l => l.VenueId).ToArray(),
                StartDate = tLevel.StartDate,
                ProviderId = tLevel.ProviderId,
                TLevelId = tLevel.TLevelId,
                TLevelDefinitionId = tLevel.TLevelDefinition.TLevelDefinitionId,
                TLevelName = tLevel.TLevelDefinition.Name,
                Website = tLevel.Website,
                WhatYouCanDoNext = tLevel.WhatYouCanDoNext,
                WhatYoullLearn = tLevel.WhatYoullLearn,
                WhoFor = tLevel.WhoFor,
                YourReference = tLevel.YourReference,
                IsValid = true
            });
        }
Example #16
0
        public async Task <IViewComponentResult> InvokeAsync(ChooseVenueModel model)
        {
            var providerId = _providerContextProvider.GetProviderId(withLegacyFallback: true);

            List <SelectListItem> venues = new List <SelectListItem>();

            var result = await _sqlQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
            {
                ProviderId = providerId
            });

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

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

            venues.Insert(0, defaultItem);

            model.Venues = venues;
            return(View("~/ViewComponents/Courses/ChooseVenue/Default.cshtml", model));
        }
Example #17
0
        public async Task <Guid?> GetProviderForTLevel(Guid tLevelId)
        {
            var cacheKey = GetTLevelCacheKey(tLevelId);

            if (!_cache.TryGetValue <Guid?>(cacheKey, out var providerId))
            {
                var tLevel = await _sqlQueryDispatcher.ExecuteQuery(
                    new GetTLevel()
                {
                    TLevelId = tLevelId
                });

                if (tLevel != null)
                {
                    providerId = tLevel.ProviderId;
                    _cache.Set(cacheKey, providerId);
                }
                else
                {
                    providerId = null;
                }
            }

            return(providerId);
        }
 public Task RecordSignIn(AuthenticatedUserInfo userInfo) =>
 _sqlQueryDispatcher.ExecuteQuery(new CreateUserSignIn()
 {
     User              = userInfo,
     SignedInUtc       = _clock.UtcNow,
     CurrentProviderId = userInfo.CurrentProviderId
 });
        private async Task <ViewModel> CreateViewModel(int rowNumber)
        {
            var row = await _fileUploadProcessor.GetCourseUploadRowDetailForProvider(_providerContextProvider.GetProviderId(), rowNumber);

            if (row == null)
            {
                throw new ResourceDoesNotExistException(ResourceType.CourseUploadRow, rowNumber);
            }

            var learningDelivery = (await _sqlQueryDispatcher.ExecuteQuery(new GetLearningDeliveries()
            {
                LearnAimRefs = new[] { row.LearnAimRef }
            }))[row.LearnAimRef];

            return(new ViewModel()
            {
                RowNumber = rowNumber,
                CourseName = row.CourseName,
                DeliveryMode = row.DeliveryMode,
                ErrorFields = row.Errors
                              .Where(e => Core.DataManagement.Errors.GetCourseErrorComponent(e) == CourseErrorComponent.CourseRun)
                              .Select(e => Core.DataManagement.Errors.MapCourseErrorToFieldGroup(e))
                              .Distinct()
                              .ToArray(),
                StartDate = row.StartDate,
                LearnAimRef = row.LearnAimRef,
                LearnAimRefTitle = learningDelivery.LearnAimRefTitle
            });
        }
        public async Task Run(string learnAimRef, ILogger log)
        {
            if (string.IsNullOrWhiteSpace(learnAimRef))
            {
                log.LogError($"{nameof(PurgeLarsFromDatabaseAndSearch)} failed with invalid {nameof(learnAimRef)} {{{nameof(learnAimRef)}}}.", learnAimRef);
            }

            log.LogInformation($"{nameof(PurgeLarsFromDatabaseAndSearch)} invoked for {nameof(learnAimRef)} {{{nameof(learnAimRef)}}}.", learnAimRef);

            var deletedResult = await _sqlQueryDispatcher.ExecuteQuery(new DeleteLarsLearningDelivery(learnAimRef));

            deletedResult.Switch(
                _ => log.LogInformation($"{nameof(PurgeLarsFromDatabaseAndSearch)} successfully deleted {nameof(learnAimRef)}: {{{nameof(learnAimRef)}}} from database.", learnAimRef),
                _ => log.LogWarning($"{nameof(PurgeLarsFromDatabaseAndSearch)} failed to find {nameof(learnAimRef)} {{{nameof(learnAimRef)}}} in database.", learnAimRef));

            try
            {
                await _searchClient.GetDocumentAsync <dynamic>(learnAimRef);

                await _searchClient.DeleteDocumentsAsync("LearnAimRef", new[] { learnAimRef }, new IndexDocumentsOptions { ThrowOnAnyError = true });

                log.LogInformation($"{nameof(PurgeLarsFromDatabaseAndSearch)} successfully deleted {nameof(learnAimRef)} {{{nameof(learnAimRef)}}} from search index.", learnAimRef);
            }
            catch (RequestFailedException ex)
                when(ex.Status == StatusCodes.Status404NotFound)
                {
                    log.LogWarning($"{nameof(PurgeLarsFromDatabaseAndSearch)} failed to find {nameof(learnAimRef)} {{{nameof(learnAimRef)}}} in search.", learnAimRef);
                }
        }
Example #21
0
        internal async Task <UploadStatus> RevalidateApprenticeshipUploadIfRequired(
            ISqlQueryDispatcher sqlQueryDispatcher,
            Guid apprenticeshipUploadId)
        {
            var apprenticeshipUpload = await sqlQueryDispatcher.ExecuteQuery(new GetApprenticeshipUpload()
            {
                ApprenticeshipUploadId = apprenticeshipUploadId
            });

            if (apprenticeshipUpload == null)
            {
                throw new ArgumentException("Apprenticeship upload does not exist.", nameof(apprenticeshipUploadId));
            }

            var toBeRevalidated = await GetApprenticeshipUploadRowsRequiringRevalidation(sqlQueryDispatcher, apprenticeshipUpload);

            if (toBeRevalidated.Count == 0)
            {
                return(apprenticeshipUpload.UploadStatus);
            }

            var rowsCollection = new ApprenticeshipDataUploadRowInfoCollection(
                toBeRevalidated.Select(r => new ApprenticeshipDataUploadRowInfo(CsvApprenticeshipRow.FromModel(r), r.RowNumber, r.ApprenticeshipId)));

            var(uploadStatus, _) = await ValidateApprenticeshipUploadRows(sqlQueryDispatcher, apprenticeshipUploadId, apprenticeshipUpload.ApprenticeshipUploadId, rowsCollection);

            return(uploadStatus);
        }
Example #22
0
        public static void StartDate <T>(
            this IRuleBuilderInitial <T, DateInput> field,
            Guid?tLevelId,
            Guid providerId,
            Guid tLevelDefinitionId,
            ISqlQueryDispatcher sqlQueryDispatcher)
        {
            field
            .Cascade(CascadeMode.Stop)
            .NotEmpty()
            .WithMessage("Enter a start date")
            .Apply(builder => Rules.Date(builder, displayName: "Start date"))
            .CustomAsync(async(v, ctx, _) =>
            {
                var existingTLevels = await sqlQueryDispatcher.ExecuteQuery(
                    new GetTLevelsForProvider()
                {
                    ProviderId = providerId
                });

                if (existingTLevels.Any(tl =>
                                        tl.TLevelDefinition.TLevelDefinitionId == tLevelDefinitionId &&
                                        tl.StartDate == v.Value &&
                                        tl.TLevelId != tLevelId))
                {
                    ctx.AddFailure("Start date already exists");
                }
            });
        }
        public async Task <Response> Handle(Query request, CancellationToken cancellationToken)
        {
            var providerContext = _providerContextProvider.GetProviderContext();

            var apprenticeships = await _sqlQueryDispatcher.ExecuteQuery(new GetApprenticeshipsForProvider()
            {
                ProviderId = providerContext.ProviderInfo.ProviderId
            });

            var allRegions = await _regionCache.GetAllRegions();

            var rows = apprenticeships
                       .OrderBy(x => x.Standard.StandardCode)
                       .ThenBy(x => x.Standard.Version)
                       .SelectMany(app => CsvApprenticeshipRow.FromModel(app, allRegions))
                       .ToList();

            var fileName = FileNameHelper.SanitizeFileName(
                $"{providerContext.ProviderInfo.ProviderName}_apprenticeships_{_clock.UtcNow:yyyyMMddHHmm}.csv");

            return(new Response()
            {
                FileName = fileName,
                Rows = rows
            });
        }
Example #24
0
        public async Task <OneOf <NotFound, ViewModel> > Handle(Query request, CancellationToken cancellationToken)
        {
            var result = await _sqlQueryDispatcher.ExecuteQuery(new GetTLevel { TLevelId = request.TLevelId });

            if (result == null)
            {
                return(new NotFound());
            }

            return(new ViewModel
            {
                TLevelId = result.TLevelId,
                TLevelDefinitionName = result.TLevelDefinition.Name,
                CreatedOn = result.CreatedOn,
                UpdatedOn = result.UpdatedOn,
                YourReference = result.YourReference,
                StartDate = result.StartDate,
                LocationVenueNames = result.Locations.Select(l => l.VenueName).ToArray(),
                Website = result.Website,
                WhoFor = result.WhoFor,
                EntryRequirements = result.EntryRequirements,
                WhatYoullLearn = result.WhatYoullLearn,
                HowYoullLearn = result.HowYoullLearn,
                HowYoullBeAssessed = result.HowYoullBeAssessed,
                WhatYouCanDoNext = result.WhatYouCanDoNext
            });
        }
        public async Task <IViewComponentResult> InvokeAsync(ChooseLocationModel model)
        {
            var providerId = _providerContextProvider.GetProviderId(withLegacyFallback: true);

            List <SelectListItem> venues = new List <SelectListItem>();

            var result = await _sqlQueryDispatcher.ExecuteQuery(new GetVenuesByProvider()
            {
                ProviderId = providerId
            });

            foreach (var venue in result)
            {
                if (model.DeliveryLocations == null || !model.DeliveryLocations.Any(x => x.VenueId == venue.VenueId))
                {
                    var item = new SelectListItem {
                        Text = venue.VenueName, Value = venue.VenueId.ToString()
                    };
                    venues.Add(item);
                }
            }
            ;

            model.Locations = venues;
            return(View("~/ViewComponents/Apprenticeships/ChooseLocation/Default.cshtml", model));
        }
        public async Task <TResponse> Handle(
            TRequest request,
            CancellationToken cancellationToken,
            RequestHandlerDelegate <TResponse> next)
        {
            var providerId = _descriptor.GetProviderId(request);

            var qaStatus = await _sqlQueryDispatcher.ExecuteQuery(
                new GetProviderApprenticeshipQAStatus()
            {
                ProviderId = providerId
            });

            var effectiveQaStatus = qaStatus.ValueOrDefault();

            var isPermitted = effectiveQaStatus.HasFlag(ApprenticeshipQAStatus.UnableToComplete) ?
                              _descriptor.PermittedStatuses.Contains(ApprenticeshipQAStatus.UnableToComplete) :
                              _descriptor.PermittedStatuses.Contains(effectiveQaStatus);

            if (!isPermitted)
            {
                throw new InvalidStateException(InvalidStateReason.InvalidApprenticeshipQAStatus);
            }

            return(await next());
        }
Example #27
0
        public async Task <ViewModel> Handle(Query request, CancellationToken cancellationToken)
        {
            var results = await _sqlQueryDispatcher.ExecuteQuery(new GetQAStatusReport());

            var infos = (from r in results
                         select new ReportModel()
            {
                ProviderId = r.ProviderId,
                ProviderName = r.ProviderName,
                Ukprn = r.Ukprn,
                Email = r.Email,
                PassedQAOn = r.PassedQAOn.HasValue ? r.PassedQAOn.Value.ToString("dd MMM yyyy") : null,
                FailedQAOn = r.FailedQAOn.HasValue ? r.FailedQAOn.Value.ToString("dd MMM yyyy") : null,
                UnableToCompleteReasons = r.UnableToCompleteReasons.HasValue ? string.Join(",", EnumHelper.SplitFlags(r.UnableToCompleteReasons.Value).ToList().Select(x => x.ToDescription()).ToList()) : null,
                UnableToCompleteOn = r.UnabletoCompleteOn.HasValue ? r.UnabletoCompleteOn.Value.ToString("dd MMM yyyy") : null,
                Notes = r.Notes,
                QAStatus = r.QAStatus.HasValue ? r.QAStatus.Value.ToDescription() : null,
                PassedQA = r.QAStatus == ApprenticeshipQAStatus.Passed ? "Yes" : "No",
                FailedQA = r.QAStatus == ApprenticeshipQAStatus.Failed ? "Yes" : "No",
                UnableToComplete = r.QAStatus.HasValue ? (r.QAStatus.Value.HasFlag(ApprenticeshipQAStatus.UnableToComplete) ? "Yes" : "No") : "No"
            }).ToList();

            return(new ViewModel()
            {
                Report = infos
            });
        }
Example #28
0
        public async Task <EditVenueJourneyModel> CreateModel(Guid venueId)
        {
            var venue = await _sqlQueryDispatcher.ExecuteQuery(new GetVenue()
            {
                VenueId = venueId
            });

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

            return(new EditVenueJourneyModel()
            {
                ProviderVenueRef = venue.ProviderVenueRef,
                Email = venue.Email,
                Name = venue.VenueName,
                PhoneNumber = venue.Telephone,
                Website = venue.Website,
                AddressLine1 = venue.AddressLine1,
                AddressLine2 = venue.AddressLine2,
                Town = venue.Town,
                County = venue.County,
                Postcode = venue.Postcode,
                Latitude = Convert.ToDouble(venue.Latitude),
                Longitude = Convert.ToDouble(venue.Longitude)
            });
        }
        public async Task <Response> Handle(Query request, CancellationToken cancellationToken)
        {
            var providerContext = _providerContextProvider.GetProviderContext();

            var courses = await _sqlQueryDispatcher.ExecuteQuery(new GetCoursesForProvider()
            {
                ProviderId = providerContext.ProviderInfo.ProviderId
            });

            var allRegions = await _regionCache.GetAllRegions();

            var rows = courses.OrderBy(x => x.LearnAimRef)
                       .ThenBy(x => x.CourseId)
                       .SelectMany(course => CsvCourseRow.FromModel(course, allRegions))
                       .ToList();

            var fileName = FileNameHelper.SanitizeFileName(
                $"{providerContext.ProviderInfo.ProviderName}_courses_{_clock.UtcNow:yyyyMMddHHmm}.csv");

            return(new Response()
            {
                FileName = fileName,
                Rows = rows
            });
        }
        public async Task <CommandResponse> Handle(
            Command request,
            CancellationToken cancellationToken)
        {
            var currentUser = _currentUserProvider.GetCurrentUser();

            if (currentUser.IsHelpdesk)
            {
                throw new NotAuthorizedException();
            }

            var maybeSubmission = await _sqlQueryDispatcher.ExecuteQuery(
                new GetLatestApprenticeshipQASubmissionForProvider()
            {
                ProviderId = request.ProviderId
            });

            var submission = maybeSubmission.Match(
                notfound => throw new InvalidStateException(InvalidStateReason.InvalidApprenticeshipQASubmission),
                found => found);

            // Cannot hide passed notification if qa status is not passed
            if (submission.Passed != true)
            {
                throw new InvalidStateException(InvalidStateReason.InvalidApprenticeshipQAStatus);
            }

            // Cannot hide notification if it has already been hidden
            if (submission.HidePassedNotification)
            {
                throw new InvalidStateException();
            }

            // Hide notification
            var hideDialog = await _sqlQueryDispatcher.ExecuteQuery(
                new UpdateHidePassedNotification()
            {
                ApprenticeshipQASubmissionId = submission.ApprenticeshipQASubmissionId,
                HidePassedNotification       = true
            });

            return(hideDialog.Match(
                       notfound => throw new InvalidStateException(InvalidStateReason.InvalidApprenticeshipQASubmission),
                       success => success));
        }