public async Task <UpdateTransferApprovalForSenderRequest> Map(TransferRequestForSenderViewModel source)
 {
     return(await Task.FromResult(new UpdateTransferApprovalForSenderRequest
     {
         TransferSenderId = _encodingService.Decode(source.AccountHashedId, EncodingType.AccountId),
         TransferRequestId = _encodingService.Decode(source.TransferRequestHashedId, EncodingType.TransferRequestId),
         CohortId = _encodingService.Decode(source.HashedCohortReference, EncodingType.CohortReference),
         TransferReceiverId = _encodingService.Decode(source.TransferReceiverPublicHashedAccountId, EncodingType.PublicAccountId),
         TransferApprovalStatus = source.ApprovalConfirmed.Value ? TransferApprovalStatus.Approved : TransferApprovalStatus.Rejected,
         UserInfo = _authenticationService.UserInfo
     }));
 }
        public async Task <IActionResult> ProcessConfirmEmployer(ConfirmEmployerViewModel viewModel)
        {
            if (!viewModel.Confirm.HasValue)
            {
                ModelState.AddModelError("confirm-yes", "Select whether to secure funds for this employer or not");
                return(View("ConfirmEmployer", viewModel));
            }

            try
            {
                if (!viewModel.Confirm.Value)
                {
                    return(RedirectToRoute(RouteNames.ProviderChooseEmployer, new
                    {
                        viewModel.UkPrn
                    }));
                }

                var reservationId = Guid.NewGuid();

                await _mediator.Send(new CacheReservationEmployerCommand
                {
                    Id                               = reservationId,
                    AccountId                        = _encodingService.Decode(viewModel.AccountPublicHashedId, EncodingType.PublicAccountId),
                    AccountLegalEntityId             = _encodingService.Decode(viewModel.AccountLegalEntityPublicHashedId, EncodingType.PublicAccountLegalEntityId),
                    AccountLegalEntityName           = viewModel.AccountLegalEntityName,
                    AccountLegalEntityPublicHashedId = viewModel.AccountLegalEntityPublicHashedId,
                    UkPrn                            = viewModel.UkPrn,
                    AccountName                      = viewModel.AccountName
                });

                return(RedirectToRoute(RouteNames.ProviderApprenticeshipTraining, new
                {
                    Id = reservationId,
                    EmployerAccountId = viewModel.AccountPublicHashedId,
                    viewModel.UkPrn
                }));
            }
            catch (ValidationException e)
            {
                foreach (var member in e.ValidationResult.MemberNames)
                {
                    ModelState.AddModelError(member.Split('|')[0], member.Split('|')[1]);
                }

                return(View("ConfirmEmployer", viewModel));
            }
            catch (ReservationLimitReachedException)
            {
                return(View("ReservationLimitReached"));
            }
        }
        public async Task <IActionResult> EmployerManage(ReservationsRouteModel routeModel)
        {
            var reservations = new List <ReservationViewModel>();

            var decodedAccountId   = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId);
            var reservationsResult = await _mediator.Send(new GetReservationsQuery { AccountId = decodedAccountId });

            foreach (var reservation in reservationsResult.Reservations)
            {
                var accountLegalEntityPublicHashedId = _encodingService.Encode(reservation.AccountLegalEntityId,
                                                                               EncodingType.PublicAccountLegalEntityId);

                var apprenticeUrl = reservation.Status == ReservationStatus.Pending && !reservation.IsExpired
                    ? _urlHelper.GenerateAddApprenticeUrl(
                    reservation.Id,
                    accountLegalEntityPublicHashedId,
                    reservation.Course.Id,
                    routeModel.UkPrn,
                    reservation.StartDate,
                    routeModel.CohortReference,
                    routeModel.EmployerAccountId)
                    : string.Empty;

                var viewModel = new ReservationViewModel(reservation, apprenticeUrl, routeModel.UkPrn);
                reservations.Add(viewModel);
            }

            return(View(ViewNames.EmployerManage, new ManageViewModel
            {
                Reservations = reservations,
                BackLink = _urlHelper.GenerateDashboardUrl(routeModel.EmployerAccountId)
            }));
        }
Esempio n. 4
0
        private async Task <ApprenticeshipTrainingViewModel> BuildApprenticeshipTrainingViewModel(
            bool isProvider,
            string accountLegalEntityPublicHashedId,
            string courseId = null,
            TrainingDateModel selectedTrainingDate = null,
            bool?routeModelFromReview = false,
            string cohortRef          = "",
            uint?ukPrn       = null,
            string accountId = "")

        {
            var accountLegalEntityId = _encodingService.Decode(
                accountLegalEntityPublicHashedId,
                EncodingType.PublicAccountLegalEntityId);
            var dates = await _trainingDateService.GetTrainingDates(accountLegalEntityId);

            var coursesResult = await _mediator.Send(new GetCoursesQuery());

            return(new ApprenticeshipTrainingViewModel
            {
                RouteName = isProvider ? RouteNames.ProviderCreateApprenticeshipTraining : RouteNames.EmployerCreateApprenticeshipTraining,
                PossibleStartDates = dates.Select(startDateModel => new TrainingDateViewModel(startDateModel, startDateModel.Equals(selectedTrainingDate))).OrderBy(model => model.StartDate),
                Courses = coursesResult.Courses?.Select(course => new CourseViewModel(course, courseId)),
                CourseId = courseId,
                AccountLegalEntityPublicHashedId = accountLegalEntityPublicHashedId,
                IsProvider = isProvider,
                CohortRef = cohortRef,
                FromReview = routeModelFromReview,
                BackLink = isProvider ?
                           GetProviderBackLinkForApprenticeshipTrainingView(routeModelFromReview, cohortRef, ukPrn, accountId)
                    : routeModelFromReview.HasValue && routeModelFromReview.Value ? RouteNames.EmployerReview : RouteNames.EmployerSelectCourse
            });
        }
Esempio n. 5
0
        public void HandleMqttMessage(MqttApplicationMessageReceivedEventArgs eventArguments)
        {
            var message = eventArguments.ApplicationMessage;

            if (message.Topic.ToLower() ==
                $"{_weatherAdapterInitializationArgument.TopicPrefix}weather/{_weatherAdapterInitializationArgument.Identifier}")
            {
                var decodedString = _encodingService.Decode(eventArguments.ApplicationMessage.Payload);
                try
                {
                    var payload = _jsonSerializerService.Deserialize <WeatherAdapterPayload>(decodedString);
                    if (payload != null)
                    {
                        _status = new WeatherStatus
                        {
                            Temperature = payload.Temperature,
                            Humidity    = payload.Humidity,
                            Pressure    = payload.Pressure,
                            TimeStamp   = DateTime.Now
                        };

                        Console.WriteLine($"Serialized: {decodedString}");
                        Console.WriteLine(_status);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deserialize failed");
                    Console.WriteLine(e);
                    Console.WriteLine(e.StackTrace);
                    // log message
                }
            }
        }
Esempio n. 6
0
 public string Decode(
     [Service] IEncodingService encodingService,
     string value,
     EncodingType type)
 {
     return(encodingService.Decode(value, type));
 }
Esempio n. 7
0
        public async Task <DownloadViewModel> Map(DownloadRequest request)
        {
            var decodedAccountId =
                _encodingService.Decode(request.AccountHashedId, EncodingType.AccountId);

            var downloadViewModel         = new DownloadViewModel();
            var getApprenticeshipsRequest = new GetApprenticeshipsRequest
            {
                AccountId    = decodedAccountId,
                SearchTerm   = request.SearchTerm,
                ProviderName = request.SelectedProvider,
                CourseName   = request.SelectedCourse,
                Status       = request.SelectedStatus,
                EndDate      = request.SelectedEndDate,
                Alert        = request.SelectedAlert,
                ApprenticeConfirmationStatus = request.SelectedApprenticeConfirmation,
                PageNumber = 0
            };

            var result = await _client.GetApprenticeships(getApprenticeshipsRequest);

            var csvContent = result.Apprenticeships.Select(c => (ApprenticeshipDetailsCsvModel)c).ToList();

            downloadViewModel.Content = _createCsvService.GenerateCsvContent(csvContent, true);
            downloadViewModel.Request = getApprenticeshipsRequest;
            downloadViewModel.Name    = $"{"Manageyourapprentices"}_{_currentDateTime.UtcNow:yyyyMMddhhmmss}.csv";
            return(await Task.FromResult(downloadViewModel));
        }
Esempio n. 8
0
        public async Task <IActionResult> Manage(ReservationsRouteModel routeModel)
        {
            var    employerAccountIds = new List <long>();
            var    reservations       = new List <ReservationViewModel>();
            string viewName;

            if (routeModel.UkPrn.HasValue)
            {
                var trustedEmployersResponse = await _mediator.Send(new GetTrustedEmployersQuery { UkPrn = routeModel.UkPrn.Value });

                if (!trustedEmployersResponse.Employers.Any())
                {
                    return(View("NoPermissions"));
                }

                employerAccountIds.AddRange(trustedEmployersResponse.Employers.Select(employer => employer.AccountId));
                viewName = ViewNames.ProviderManage;
            }
            else
            {
                var decodedAccountId = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId);
                employerAccountIds.Add(decodedAccountId);
                viewName = ViewNames.EmployerManage;
            }

            foreach (var employerAccountId in employerAccountIds)
            {
                var reservationsResult = await _mediator.Send(new GetReservationsQuery { AccountId = employerAccountId });

                foreach (var reservation in reservationsResult.Reservations)
                {
                    var accountLegalEntityPublicHashedId = _encodingService.Encode(reservation.AccountLegalEntityId,
                                                                                   EncodingType.PublicAccountLegalEntityId);

                    var apprenticeUrl = reservation.Status == ReservationStatus.Pending && !reservation.IsExpired
                        ? _urlHelper.GenerateAddApprenticeUrl(
                        reservation.Id,
                        accountLegalEntityPublicHashedId,
                        reservation.Course.Id,
                        routeModel.UkPrn,
                        reservation.StartDate,
                        routeModel.CohortReference,
                        routeModel.EmployerAccountId)
                        : string.Empty;

                    var viewModel = new ReservationViewModel(reservation, apprenticeUrl, routeModel.UkPrn);

                    reservations.Add(viewModel);
                }
            }

            return(View(viewName, new ManageViewModel
            {
                Reservations = reservations,
                BackLink = _urlHelper.GenerateDashboardUrl(routeModel.EmployerAccountId)
            }));
        }
Esempio n. 9
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var attribute = GetAutoDecodeAttribute(bindingContext);

            if (attribute == null)
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            try
            {
                var encodedValue = bindingContext.ValueProvider.GetValue(attribute.Source).FirstValue;

                if (GetTargetType(bindingContext) == typeof(long))
                {
                    var decodedValue = _encodingService.Decode(encodedValue, attribute.EncodingType);
                    bindingContext.Result = ModelBindingResult.Success(decodedValue);
                }
                else if (GetTargetType(bindingContext) == typeof(int))
                {
                    var decodedValue = (int)_encodingService.Decode(encodedValue, attribute.EncodingType);
                    bindingContext.Result = ModelBindingResult.Success(decodedValue);
                }
                else
                {
                    bindingContext.Result = ModelBindingResult.Failed();
                }
            }
            catch
            {
                bindingContext.Result = ModelBindingResult.Failed();
            }

            return(Task.CompletedTask);
        }
        private BulkUploadAddDraftApprenticeshipRequest MapTo(CsvRecord record)
        {
            var dateOfBirth      = GetValidDate(record.DateOfBirth, "yyyy-MM-dd");
            var learnerStartDate = GetValidDate(record.StartDate, "yyyy-MM-dd");
            var learnerEndDate   = GetValidDate(record.EndDate, "yyyy-MM");

            return(new BulkUploadAddDraftApprenticeshipRequest
            {
                Uln = record.ULN,
                FirstName = record.GivenNames,
                LastName = record.FamilyName,
                DateOfBirth = dateOfBirth,
                Cost = int.Parse(record.TotalPrice),
                ProviderRef = record.ProviderRef,
                StartDate = new DateTime(learnerStartDate.Value.Year, learnerStartDate.Value.Month, 1),
                EndDate = learnerEndDate,
                CourseCode = record.StdCode,
                LegalEntityId = _encodingService.Decode(record.AgreementId, EncodingType.PublicAccountLegalEntityId),
                CohortId = _encodingService.Decode(record.CohortRef, EncodingType.CohortReference),
                Email = record.EmailAddress
            });
        }
        public async Task <IActionResult> Start(ReservationsRouteModel routeModel)
        {
            try
            {
                var viewModel = new EmployerStartViewModel
                {
                    FindApprenticeshipTrainingUrl = _config.FindApprenticeshipTrainingUrl,
                    ApprenticeshipFundingRulesUrl = _config.ApprenticeshipFundingRulesUrl
                };

                var accountId = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId);

                var response = await _mediator.Send(new GetAccountFundingRulesQuery { AccountId = accountId });

                var activeGlobalRuleType = response?.ActiveRule;

                if (activeGlobalRuleType == null)
                {
                    return(View("Index", viewModel));
                }

                switch (activeGlobalRuleType)
                {
                case GlobalRuleType.FundingPaused:
                    return(View("EmployerFundingPaused", GenerateLimitReachedBackLink(routeModel)));

                case GlobalRuleType.ReservationLimit:
                    return(View("ReservationLimitReached", GenerateLimitReachedBackLink(routeModel)));

                default:
                    return(View("Index", viewModel));
                }
            }
            catch (ValidationException e)
            {
                _logger.LogInformation(e, e.Message);
                return(RedirectToRoute(RouteNames.Error500));
            }
        }
        public Task <TResponse> Get <TResponse>(IGetApiRequest request)
        {
            var accountLegalEntityPublicHashedId = _httpContextAccessor.HttpContext.GetRouteValue("AccountLegalEntityPublicHashedId").ToString();
            var accountLegalEntityId             = _encodingService.Decode(accountLegalEntityPublicHashedId, EncodingType.PublicAccountLegalEntityId);

            if (typeof(TResponse) == typeof(Cohort))
            {
                var cohortRequest = (GetCohortRequest)request;

                return(Task.FromResult((TResponse)CreateCohort(cohortRequest.CohortId, accountLegalEntityId)));
            }

            throw new NotImplementedException();
        }
        public async Task <DeleteConfirmationViewModel> Map(DeleteConfirmationRequest source)
        {
            long apprenticeshipId = 0;

            try
            {
                apprenticeshipId = _encodingService.Decode(source.DraftApprenticeshipHashedId, EncodingType.ApprenticeshipId);
                var commitmentId = _encodingService.Decode(source.CohortReference, EncodingType.CohortReference);
                var draftApprenticeshipResponse = await _commitmentApiClient.GetDraftApprenticeship(commitmentId, apprenticeshipId, CancellationToken.None);

                return(new DeleteConfirmationViewModel
                {
                    ProviderId = source.ProviderId,
                    CohortReference = source.CohortReference,
                    DraftApprenticeshipHashedId = source.DraftApprenticeshipHashedId,
                    ApprenticeshipName = $"{draftApprenticeshipResponse.FirstName} {draftApprenticeshipResponse.LastName}",
                    DateOfBirth = draftApprenticeshipResponse.DateOfBirth
                });
            }
            catch (RestHttpClientException restEx)
            {
                _logger.LogError(restEx, $"Error mapping apprenticeship {source.DraftApprenticeshipHashedId} to DeleteConfirmationViewModel");

                if (restEx.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    throw new DraftApprenticeshipNotFoundException(
                              $"DraftApprenticeship Id: {apprenticeshipId} not found", restEx);
                }
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error mapping apprenticeship {source.DraftApprenticeshipHashedId} to DeleteConfirmationViewModel");
                throw;
            }
        }
Esempio n. 14
0
        public async Task <ChangeProviderInformViewModel> Map(ChangeProviderInformRequest source)
        {
            var apprenticeshipId = _encodingService.Decode(source.ApprenticeshipHashedId, EncodingType.ApprenticeshipId);

            var apprenticeship = await _commitmentsApiClient.GetApprenticeship(apprenticeshipId, CancellationToken.None);

            var result = new ChangeProviderInformViewModel
            {
                AccountHashedId        = source.AccountHashedId,
                ApprenticeshipHashedId = source.ApprenticeshipHashedId,
                ApprenticeshipStatus   = apprenticeship.Status
            };

            return(result);
        }
Esempio n. 15
0
        public async Task <AgreementNotSignedViewModel> Map(LegalEntitySignedAgreementViewModel source)
        {
            var accountId = _encodingService.Decode(source.AccountHashedId, EncodingType.AccountId);

            var account = await _employerAccountsService.GetAccount(accountId);

            return(new AgreementNotSignedViewModel
            {
                AccountHashedId = source.AccountHashedId,
                AccountLegalEntityPublicHashedId = source.AccountLegalEntityPublicHashedId,
                CohortRef = source.CohortRef,
                HasSignedMinimumRequiredAgreementVersion = source.HasSignedMinimumRequiredAgreementVersion,
                LegalEntityId = source.LegalEntityId,
                LegalEntityName = source.LegalEntityName,
                TransferConnectionCode = source.TransferConnectionCode,
                EncodedPledgeApplicationId = source.EncodedPledgeApplicationId,
                CanContinueAnyway = (account.ApprenticeshipEmployerType == ApprenticeshipEmployerType.Levy)
            });
        }
        public async Task <GetAccountLegalEntityResult> Handle(GetAccountLegalEntityQuery query, CancellationToken cancellationToken)
        {
            var validationResult = await _validator.ValidateAsync(query);

            if (!validationResult.IsValid())
            {
                throw new ValidationException(validationResult.ConvertToDataAnnotationsValidationResult(), null, null);
            }

            var legalEntityId = _encodingService.Decode(
                query.AccountLegalEntityPublicHashedId,
                EncodingType.PublicAccountLegalEntityId);

            var legalEntity = await _providerService.GetAccountLegalEntityById(legalEntityId);

            return(new GetAccountLegalEntityResult
            {
                LegalEntity = legalEntity
            });
        }
        protected override async Task Handle(RevokePermissionsCommand command, CancellationToken cancellationToken)
        {
            long accountLegalEntityId = _encodingService.Decode(command.AccountLegalEntityPublicHashedId, EncodingType.PublicAccountLegalEntityId);

            var accountProviderLegalEntity = await _db.Value.AccountProviderLegalEntities
                                             .Include(x => x.AccountProvider)
                                             .Include(x => x.AccountLegalEntity)
                                             .Include(x => x.Permissions)
                                             .Where(x => x.AccountProvider.ProviderUkprn == command.Ukprn)
                                             .Where(x => x.AccountLegalEntity.Id == accountLegalEntityId)
                                             .SingleOrDefaultAsync(cancellationToken);

            if (accountProviderLegalEntity == null)
            {
                return;
            }

            accountProviderLegalEntity.RevokePermissions(
                user: null,
                operationsToRevoke: command.OperationsToRevoke);
        }
        private async Task <IEnumerable <Apprenticeship> > MergeBulkCreatedReservationIdsOnToApprenticeships(IList <Apprenticeship> apprenticeships, Commitment commitment)
        {
            BulkCreateReservationsRequest BuildBulkCreateRequest()
            {
                return(new BulkCreateReservationsRequest
                {
                    Count = (uint)apprenticeships.Count, TransferSenderId = commitment.TransferSenderId
                });
            }

            BulkCreateReservationsResult bulkReservations;

            try
            {
                bulkReservations = await _reservationsApiClient.BulkCreateReservations(
                    _encodingService.Decode(commitment.AccountLegalEntityPublicHashedId, EncodingType.PublicAccountLegalEntityId),
                    BuildBulkCreateRequest(), CancellationToken.None);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Failed calling BulkCreateReservations endpoint");
                throw;
            }

            if (bulkReservations.ReservationIds.Length != apprenticeships.Count)
            {
                _logger.Info($"The number of bulk reservations did not match the number of apprentices");
                throw new InvalidOperationException(
                          $"The number of bulk reservations ({bulkReservations.ReservationIds.Length}) does not equal the number of apprenticeships ({apprenticeships.Count})");
            }

            return(apprenticeships.Zip(bulkReservations.ReservationIds, (a, r) =>
            {
                a.ReservationId = r;
                return a;
            }));
        }
Esempio n. 19
0
        public async Task <ApprenticeshipDetailsRequestViewModel> Map(ApprenticeshipDetailsRequest source)
        {
            try
            {
                var apprenticeshipId = _encodingService.Decode(source.ApprenticeshipHashedId, EncodingType.ApprenticeshipId);

                var apprenticeshipTask        = _commitmentsApiClient.GetApprenticeship(apprenticeshipId, CancellationToken.None);
                var priceEpisodesTask         = _commitmentsApiClient.GetPriceEpisodes(apprenticeshipId, CancellationToken.None);
                var apprenticeshipUpdatesTask = _commitmentsApiClient.GetApprenticeshipUpdates(apprenticeshipId, new GetApprenticeshipUpdatesRequest()
                {
                    Status = ApprenticeshipUpdateStatus.Pending
                }, CancellationToken.None);
                var apprenticeshipDataLocksStatusTask = _commitmentsApiClient.GetApprenticeshipDatalocksStatus(apprenticeshipId, CancellationToken.None);
                var changeofPartyRequestsTask         = _commitmentsApiClient.GetChangeOfPartyRequests(apprenticeshipId, CancellationToken.None);

                await Task.WhenAll(apprenticeshipTask, priceEpisodesTask, apprenticeshipUpdatesTask, apprenticeshipDataLocksStatusTask, changeofPartyRequestsTask);

                var apprenticeship                = apprenticeshipTask.Result;
                var priceEpisodes                 = priceEpisodesTask.Result;
                var apprenticeshipUpdates         = apprenticeshipUpdatesTask.Result;
                var apprenticeshipDataLocksStatus = apprenticeshipDataLocksStatusTask.Result;
                var changeofPartyRequests         = changeofPartyRequestsTask.Result;

                var getTrainingProgramme = await _commitmentsApiClient.GetTrainingProgramme(apprenticeship.CourseCode, CancellationToken.None);

                PendingChanges pendingChange = GetPendingChanges(apprenticeshipUpdates);

                var statusText = MapApprenticeshipStatus(apprenticeship.Status);

                bool dataLockCourseTriaged        = apprenticeshipDataLocksStatus.DataLocks.HasDataLockCourseTriaged();
                bool dataLockCourseChangedTraiged = apprenticeshipDataLocksStatus.DataLocks.HasDataLockCourseChangeTriaged();
                bool dataLockPriceTriaged         = apprenticeshipDataLocksStatus.DataLocks.HasDataLockPriceTriaged();

                bool enableEdit = EnableEdit(apprenticeship, pendingChange, dataLockCourseTriaged, dataLockCourseChangedTraiged, dataLockPriceTriaged);

                var pendingChangeOfProviderRequest  = changeofPartyRequests.ChangeOfPartyRequests?.Where(x => x.ChangeOfPartyType == ChangeOfPartyRequestType.ChangeProvider && x.Status == ChangeOfPartyRequestStatus.Pending).FirstOrDefault();
                var approvedChangeOfProviderRequest = changeofPartyRequests.ChangeOfPartyRequests?.Where(x => x.ChangeOfPartyType == ChangeOfPartyRequestType.ChangeProvider && x.Status == ChangeOfPartyRequestStatus.Approved).FirstOrDefault();
                var pendingChangeOfEmployerRequest  = changeofPartyRequests.ChangeOfPartyRequests?.Where(x => x.ChangeOfPartyType == ChangeOfPartyRequestType.ChangeEmployer && x.Status == ChangeOfPartyRequestStatus.Pending).FirstOrDefault();
                var approvedChangeOfEmployerRequest = changeofPartyRequests.ChangeOfPartyRequests?.Where(x => x.ChangeOfPartyType == ChangeOfPartyRequestType.ChangeEmployer && x.Status == ChangeOfPartyRequestStatus.Approved).FirstOrDefault();

                var result = new ApprenticeshipDetailsRequestViewModel
                {
                    HashedApprenticeshipId = source.ApprenticeshipHashedId,
                    AccountHashedId        = source.AccountHashedId,
                    ApprenticeName         = $"{apprenticeship.FirstName} {apprenticeship.LastName}",
                    ULN                  = apprenticeship.Uln,
                    DateOfBirth          = apprenticeship.DateOfBirth,
                    StartDate            = apprenticeship.StartDate,
                    EndDate              = apprenticeship.EndDate,
                    StopDate             = apprenticeship.StopDate,
                    PauseDate            = apprenticeship.PauseDate,
                    CompletionDate       = apprenticeship.CompletionDate,
                    TrainingName         = getTrainingProgramme.TrainingProgramme.Name,
                    TrainingType         = getTrainingProgramme.TrainingProgramme.ProgrammeType,
                    Cost                 = priceEpisodes.PriceEpisodes.GetPrice(),
                    ApprenticeshipStatus = apprenticeship.Status,
                    Status               = statusText,
                    ProviderName         = apprenticeship.ProviderName,
                    PendingChanges       = pendingChange,
                    EmployerReference    = apprenticeship.EmployerReference,
                    CohortReference      = _encodingService.Encode(apprenticeship.CohortId, EncodingType.CohortReference),
                    EnableEdit           = enableEdit,
                    CanEditStatus        = (apprenticeship.Status == ApprenticeshipStatus.Live ||
                                            apprenticeship.Status == ApprenticeshipStatus.WaitingToStart ||
                                            apprenticeship.Status == ApprenticeshipStatus.Paused),
                    EndpointAssessorName = apprenticeship.EndpointAssessorName,
                    MadeRedundant        = apprenticeship.MadeRedundant,
                    HasPendingChangeOfProviderRequest       = pendingChangeOfProviderRequest != null,
                    PendingChangeOfProviderRequestWithParty = pendingChangeOfProviderRequest?.WithParty,
                    HasApprovedChangeOfProviderRequest      = approvedChangeOfProviderRequest != null,
                    HashedNewApprenticeshipId = approvedChangeOfProviderRequest?.NewApprenticeshipId != null
                            ? _encodingService.Encode(approvedChangeOfProviderRequest.NewApprenticeshipId.Value, EncodingType.ApprenticeshipId)
                            : null,
                    IsContinuation = apprenticeship.ContinuationOfId.HasValue,
                    HashedPreviousApprenticeshipId = apprenticeship.ContinuationOfId.HasValue
                            ? _encodingService.Encode(apprenticeship.ContinuationOfId.Value, EncodingType.ApprenticeshipId)
                            : null,
                    HasPendingChangeOfEmployerRequest       = pendingChangeOfEmployerRequest != null,
                    PendingChangeOfEmployerRequestWithParty = pendingChangeOfEmployerRequest?.WithParty,
                    HasApprovedChangeOfEmployerRequest      = approvedChangeOfEmployerRequest != null,
                    PendingDataLockChange  = dataLockPriceTriaged || dataLockCourseChangedTraiged,
                    PendingDataLockRestart = dataLockCourseTriaged
                };

                return(result);
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error mapping for accountId {source.AccountHashedId}  and apprenticeship {source.ApprenticeshipHashedId} to ApprenticeshipDetailsRequestViewModel");
                throw;
            }
        }
        public async Task <IActionResult> SelectReservation(
            ReservationsRouteModel routeModel,
            SelectReservationViewModel viewModel)
        {
            var backUrl = _urlHelper.GenerateCohortDetailsUrl(routeModel.UkPrn, routeModel.EmployerAccountId,
                                                              viewModel.CohortReference, journeyData: viewModel.JourneyData);

            try
            {
                var apprenticeshipTrainingRouteName = RouteNames.EmployerSelectCourseRuleCheck;
                CacheReservationEmployerCommand cacheReservationEmployerCommand;
                Guid?userId = null;
                if (routeModel.UkPrn.HasValue)
                {
                    var response = await _mediator.Send(new GetProviderCacheReservationCommandQuery
                    {
                        AccountLegalEntityPublicHashedId = routeModel.AccountLegalEntityPublicHashedId,
                        CohortRef = routeModel.CohortReference,
                        CohortId  = _encodingService.Decode(routeModel.CohortReference, EncodingType.CohortReference),
                        UkPrn     = routeModel.UkPrn.Value
                    });

                    cacheReservationEmployerCommand = response.Command;

                    apprenticeshipTrainingRouteName = RouteNames.ProviderApprenticeshipTrainingRuleCheck;
                }
                else
                {
                    var userAccountIdClaim = HttpContext.User.Claims.First(c =>
                                                                           c.Type.Equals(EmployerClaims.IdamsUserIdClaimTypeIdentifier));
                    userId = Guid.Parse(userAccountIdClaim.Value);

                    cacheReservationEmployerCommand = await BuildEmployerReservationCacheCommand(
                        routeModel.EmployerAccountId, routeModel.AccountLegalEntityPublicHashedId,
                        viewModel.CohortReference, viewModel.ProviderId, viewModel.JourneyData);
                }

                var redirectResult = await CheckCanAutoReserve(cacheReservationEmployerCommand.AccountId,
                                                               viewModel.TransferSenderId, viewModel.JourneyData,
                                                               cacheReservationEmployerCommand.AccountLegalEntityPublicHashedId,
                                                               routeModel.UkPrn ?? viewModel.ProviderId, viewModel.CohortReference,
                                                               routeModel.EmployerAccountId, userId);

                if (!string.IsNullOrEmpty(redirectResult))
                {
                    if (redirectResult == RouteNames.Error500)
                    {
                        return(RedirectToRoute(redirectResult));
                    }

                    return(Redirect(redirectResult));
                }

                var availableReservationsResult = await _mediator.Send(
                    new GetAvailableReservationsQuery { AccountId = cacheReservationEmployerCommand.AccountId });

                if (availableReservationsResult.Reservations != null &&
                    availableReservationsResult.Reservations.Any())
                {
                    viewModel.AvailableReservations = availableReservationsResult.Reservations
                                                      .Select(reservation => new AvailableReservationViewModel(reservation));
                    viewModel.AccountId = cacheReservationEmployerCommand.AccountId;
                    viewModel.BackLink  = backUrl;
                    return(View(ViewNames.Select, viewModel));
                }

                await _mediator.Send(cacheReservationEmployerCommand);

                routeModel.Id = cacheReservationEmployerCommand.Id;

                return(RedirectToRoute(apprenticeshipTrainingRouteName, routeModel));
            }
            catch (ValidationException e)
            {
                _logger.LogWarning(e, "Validation error trying to render select reservation.");
                return(RedirectToRoute(RouteNames.Error500));
            }
            catch (ProviderNotAuthorisedException e)
            {
                _logger.LogWarning(e,
                                   $"Provider (UKPRN: {e.UkPrn}) does not has access to create a reservation for legal entity for account (Id: {e.AccountId}).");
                return(View("NoPermissions", backUrl));
            }
            catch (ReservationLimitReachedException)
            {
                return(View("ReservationLimitReached", backUrl));
            }
            catch (GlobalReservationRuleException)
            {
                if (routeModel.UkPrn.HasValue)
                {
                    return(View("ProviderFundingPaused", backUrl));
                }

                return(View("EmployerFundingPaused", backUrl));
            }
            catch (AccountLegalEntityNotFoundException e)
            {
                _logger.LogWarning($"Account legal entity not found [{e.AccountLegalEntityPublicHashedId}].");
                return(RedirectToRoute(RouteNames.Error404));
            }
            catch (AccountLegalEntityInvalidException ex)
            {
                _logger.LogWarning(ex.Message);
                return(RedirectToRoute(RouteNames.Error500));
            }
            catch (TransferSenderNotAllowedException e)
            {
                _logger.LogWarning(e,
                                   $"AccountId: {e.AccountId} does not have sender id {e.TransferSenderId} allowed).");
                return(RedirectToRoute(RouteNames.Error500));
            }
            catch (EmployerAgreementNotSignedException e)
            {
                _logger.LogWarning(e, $"AccountId: {e.AccountId} does not have a signed agreement for ALE {e.AccountLegalEntityId}).");

                var routeName = RouteNames.EmployerTransactorSignAgreement;
                if (routeModel.UkPrn.HasValue)
                {
                    routeName = RouteNames.ProviderEmployerAgreementNotSigned;
                }
                else
                {
                    if (_userClaimsService.UserIsInRole(routeModel.EmployerAccountId,
                                                        EmployerUserRole.Owner, User.Claims))
                    {
                        routeName = RouteNames.EmployerOwnerSignAgreement;
                    }
                }

                routeModel.IsFromSelect = true;
                routeModel.PreviousPage = backUrl;

                return(RedirectToRoute(routeName, routeModel));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error trying to render select reservation.");
                return(RedirectToRoute(RouteNames.Error500));
            }
        }
Esempio n. 21
0
        public async Task <ApprenticeshipDetailsRequestViewModel> Map(ApprenticeshipDetailsRequest source)
        {
            try
            {
                var apprenticeshipId = _encodingService.Decode(source.ApprenticeshipHashedId, EncodingType.ApprenticeshipId);

                var apprenticeshipTask        = _commitmentsApiClient.GetApprenticeship(apprenticeshipId, CancellationToken.None);
                var priceEpisodesTask         = _commitmentsApiClient.GetPriceEpisodes(apprenticeshipId, CancellationToken.None);
                var apprenticeshipUpdatesTask = _commitmentsApiClient.GetApprenticeshipUpdates(apprenticeshipId, new GetApprenticeshipUpdatesRequest()
                {
                    Status = ApprenticeshipUpdateStatus.Pending
                }, CancellationToken.None);
                var apprenticeshipDataLocksStatusTask = _commitmentsApiClient.GetApprenticeshipDatalocksStatus(apprenticeshipId, CancellationToken.None);
                var changeofPartyRequestsTask         = _commitmentsApiClient.GetChangeOfPartyRequests(apprenticeshipId, CancellationToken.None);
                var changeOfProviderChainTask         = _commitmentsApiClient.GetChangeOfProviderChain(apprenticeshipId, CancellationToken.None);

                await Task.WhenAll(apprenticeshipTask, priceEpisodesTask, apprenticeshipUpdatesTask, apprenticeshipDataLocksStatusTask, changeofPartyRequestsTask, changeOfProviderChainTask);

                var apprenticeship                = apprenticeshipTask.Result;
                var priceEpisodes                 = priceEpisodesTask.Result;
                var apprenticeshipUpdates         = apprenticeshipUpdatesTask.Result;
                var apprenticeshipDataLocksStatus = apprenticeshipDataLocksStatusTask.Result;
                var changeofPartyRequests         = changeofPartyRequestsTask.Result;
                var changeOfProviderChain         = changeOfProviderChainTask.Result;

                var currentTrainingProgramme = await GetTrainingProgramme(apprenticeship.CourseCode, apprenticeship.StandardUId);

                PendingChanges pendingChange = GetPendingChanges(apprenticeshipUpdates);

                bool dataLockCourseTriaged        = apprenticeshipDataLocksStatus.DataLocks.HasDataLockCourseTriaged();
                bool dataLockCourseChangedTraiged = apprenticeshipDataLocksStatus.DataLocks.HasDataLockCourseChangeTriaged();
                bool dataLockPriceTriaged         = apprenticeshipDataLocksStatus.DataLocks.HasDataLockPriceTriaged();

                bool enableEdit = EnableEdit(apprenticeship, pendingChange, dataLockCourseTriaged, dataLockCourseChangedTraiged, dataLockPriceTriaged);

                var pendingChangeOfProviderRequest = changeofPartyRequests.ChangeOfPartyRequests?
                                                     .Where(x => x.ChangeOfPartyType == ChangeOfPartyRequestType.ChangeProvider && x.Status == ChangeOfPartyRequestStatus.Pending).FirstOrDefault();

                var result = new ApprenticeshipDetailsRequestViewModel
                {
                    HashedApprenticeshipId = source.ApprenticeshipHashedId,
                    AccountHashedId        = source.AccountHashedId,
                    ApprenticeName         = $"{apprenticeship.FirstName} {apprenticeship.LastName}",
                    ULN                  = apprenticeship.Uln,
                    DateOfBirth          = apprenticeship.DateOfBirth,
                    StartDate            = apprenticeship.StartDate,
                    EndDate              = apprenticeship.EndDate,
                    StopDate             = apprenticeship.StopDate,
                    PauseDate            = apprenticeship.PauseDate,
                    CompletionDate       = apprenticeship.CompletionDate,
                    TrainingName         = currentTrainingProgramme.Name,
                    Version              = apprenticeship.Version,
                    TrainingType         = currentTrainingProgramme.ProgrammeType,
                    Cost                 = priceEpisodes.PriceEpisodes.GetPrice(),
                    ApprenticeshipStatus = apprenticeship.Status,
                    ProviderName         = apprenticeship.ProviderName,
                    PendingChanges       = pendingChange,
                    EmployerReference    = apprenticeship.EmployerReference,
                    CohortReference      = _encodingService.Encode(apprenticeship.CohortId, EncodingType.CohortReference),
                    EnableEdit           = enableEdit,
                    EndpointAssessorName = apprenticeship.EndpointAssessorName,
                    MadeRedundant        = apprenticeship.MadeRedundant,
                    HasPendingChangeOfProviderRequest       = pendingChangeOfProviderRequest != null,
                    PendingChangeOfProviderRequestWithParty = pendingChangeOfProviderRequest?.WithParty,
                    HasContinuation         = apprenticeship.HasContinuation,
                    TrainingProviderHistory = changeOfProviderChain?.ChangeOfProviderChain
                                              .Select(copc => new TrainingProviderHistory
                    {
                        ProviderName           = copc.ProviderName,
                        FromDate               = copc.StartDate.Value,
                        ToDate                 = copc.StopDate.HasValue ? copc.StopDate.Value : copc.EndDate.Value,
                        HashedApprenticeshipId = _encodingService.Encode(copc.ApprenticeshipId, EncodingType.ApprenticeshipId),
                        ShowLink               = apprenticeship.Id != copc.ApprenticeshipId
                    })
                                              .ToList(),

                    PendingDataLockChange  = dataLockPriceTriaged || dataLockCourseChangedTraiged,
                    PendingDataLockRestart = dataLockCourseTriaged,
                    ConfirmationStatus     = apprenticeship.ConfirmationStatus,
                    Email = apprenticeship.Email,
                    EmailShouldBePresent = apprenticeship.EmailShouldBePresent,
                    HasNewerVersions     = await HasNewerVersions(currentTrainingProgramme),
                    Option         = apprenticeship.Option,
                    VersionOptions = currentTrainingProgramme.Options
                };

                return(result);
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error mapping for accountId {source.AccountHashedId}  and apprenticeship {source.ApprenticeshipHashedId} to ApprenticeshipDetailsRequestViewModel");
                throw;
            }
        }
        public async Task <IndexViewModel> Map(IndexRequest source)
        {
            var decodedAccountId = _encodingService.Decode(source.AccountHashedId, EncodingType.AccountId);

            var response = await _client.GetApprenticeships(new GetApprenticeshipsRequest
            {
                AccountId     = decodedAccountId,
                PageNumber    = source.PageNumber,
                PageItemCount = Constants.ApprenticesSearch.NumberOfApprenticesPerSearchPage,
                SortField     = source.SortField,
                ReverseSort   = source.ReverseSort,
                SearchTerm    = source.SearchTerm,
                ProviderName  = source.SelectedProvider,
                CourseName    = source.SelectedCourse,
                Status        = source.SelectedStatus,
                EndDate       = source.SelectedEndDate,
                Alert         = source.SelectedAlert,
                ApprenticeConfirmationStatus = source.SelectedApprenticeConfirmation
            });

            var statusFilters = new[]
            {
                ApprenticeshipStatus.WaitingToStart,
                ApprenticeshipStatus.Live,
                ApprenticeshipStatus.Paused,
                ApprenticeshipStatus.Stopped,
                ApprenticeshipStatus.Completed
            };

            var alertFilters = new[]
            {
                Alerts.ChangesForReview,
                Alerts.ChangesPending,
                Alerts.ChangesRequested
            };

            var filterModel = new ApprenticesFilterModel
            {
                TotalNumberOfApprenticeships                = response.TotalApprenticeships,
                TotalNumberOfApprenticeshipsFound           = response.TotalApprenticeshipsFound,
                TotalNumberOfApprenticeshipsWithAlertsFound = response.TotalApprenticeshipsWithAlertsFound,
                PageNumber       = response.PageNumber,
                SortField        = source.SortField,
                ReverseSort      = source.ReverseSort,
                SearchTerm       = source.SearchTerm,
                SelectedProvider = source.SelectedProvider,
                SelectedCourse   = source.SelectedCourse,
                SelectedStatus   = source.SelectedStatus,
                SelectedAlert    = source.SelectedAlert,
                SelectedApprenticeConfirmation = source.SelectedApprenticeConfirmation,
                SelectedEndDate = source.SelectedEndDate,
                StatusFilters   = statusFilters,
                AlertFilters    = alertFilters
            };

            if (response.TotalApprenticeships >= Constants.ApprenticesSearch.NumberOfApprenticesRequiredForSearch)
            {
                var filters = await _client.GetApprenticeshipsFilterValues(
                    new GetApprenticeshipFiltersRequest { EmployerAccountId = decodedAccountId });

                filterModel.ProviderFilters = filters.ProviderNames;
                filterModel.CourseFilters   = filters.CourseNames;
                filterModel.EndDateFilters  = filters.EndDates;
            }

            var apprenticeships = new List <ApprenticeshipDetailsViewModel>();

            foreach (var apprenticeshipDetailsResponse in response.Apprenticeships)
            {
                var apprenticeship = await _modelMapper.Map <ApprenticeshipDetailsViewModel>(apprenticeshipDetailsResponse);

                apprenticeships.Add(apprenticeship);
            }

            return(new IndexViewModel
            {
                AccountHashedId = source.AccountHashedId,
                Apprenticeships = apprenticeships,
                FilterModel = filterModel
            });
        }
Esempio n. 23
0
        private void GetLicenseAttributeInfo()
        {
            object[] attibutes     = null;
            bool     foundAttibute = false;

            if (_options != null && String.IsNullOrEmpty(_options.DllHash) == false && String.IsNullOrEmpty(_options.PublicKey) == false)
            {
                try
                {
                    publicKey = encodingService.Decode(_options.PublicKey);
                    dllCheck  = encodingService.Decode(_options.DllHash);

                    foundAttibute = true;
                }
                catch
                {
                    GetLicenseAttributeInfoFailed();
                }
            }
            else
            {
                if (instance != null)
                {
                    Assembly assembly = Assembly.GetAssembly(instance.GetType());
                    attibutes = assembly.GetCustomAttributes(true);
                }
                else
                {
                    try
                    {
                        attibutes = Assembly.GetEntryAssembly().GetCustomAttributes(true);
                    }
                    catch
                    {
                        GetLicenseAttributeInfoFailed();
                    }
                }

                foreach (object o in attibutes)
                {
                    if (o.GetType() == typeof(LicenseAttribute))
                    {
                        if (String.IsNullOrEmpty(((LicenseAttribute)o).Key) || String.IsNullOrEmpty(((LicenseAttribute)o).Check))
                        {
                            GetLicenseAttributeInfoFailed();
                        }

                        try
                        {
                            publicKey = encodingService.Decode(((LicenseAttribute)o).Key);
                            dllCheck  = encodingService.Decode(((LicenseAttribute)o).Check);
                        }
                        catch
                        {
                            GetLicenseAttributeInfoFailed();
                        }

                        foundAttibute = true;
                        break;
                    }
                }
            }

            if (!foundAttibute)
            {
                GetLicenseAttributeInfoFailed();
            }
        }
        public async Task <IActionResult> ProviderConfirmed(ProviderSearchConfirmationViewModel postedModel)
        {
            if (!postedModel.Confirmed.HasValue)
            {
                ModelState.AddModelError("Confirmation", "Please choose an option");
                return(View("ConfirmProvider", postedModel));
            }

            if (!postedModel.Confirmed.Value)
            {
                return(RedirectToAction("Index"));
            }

            var providerAttributes = await _employerEmailDetailsRepository.GetAllAttributes();

            if (providerAttributes == null)
            {
                _logger.LogError($"Unable to load Provider Attributes from the database.");
                return(RedirectToAction("Error", "Error"));
            }

            var providerAttributesModel = providerAttributes.Select(s => new ProviderAttributeModel {
                Name = s.AttributeName
            }).ToList();

            var idClaim = HttpContext.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);

            if (null == idClaim)
            {
                _logger.LogError($"User id not found in user claims.");
                return(RedirectToAction("Error", "Error"));
            }

            var newSurveyModel = new SurveyModel
            {
                AccountId    = _encodingService.Decode(postedModel.EncodedAccountId, EncodingType.AccountId),
                Ukprn        = postedModel.ProviderId,
                UserRef      = new Guid(idClaim?.Value),
                Submitted    = false, //employerEmailDetail.CodeBurntDate != null,
                ProviderName = postedModel.ProviderName,
                Attributes   = providerAttributesModel
            };

            await _sessionService.Set(idClaim.Value, newSurveyModel);

            // Make sure the user exists.
            var emailAddressClaim = HttpContext.User.FindFirst(CLAIMTYPE_EMAILADDRESS);
            var firstNameClaim    = HttpContext.User.FindFirst(CLAIMTYPE_FIRSTNAME);
            var user = new User()
            {
                UserRef      = new Guid(idClaim?.Value),
                EmailAddress = emailAddressClaim?.Value,
                FirstName    = firstNameClaim?.Value,
            };
            await _employerEmailDetailsRepository.UpsertIntoUsers(user);

            // Make sure the provider exists and is active.
            await _trainingProviderService.UpsertTrainingProvider(newSurveyModel.Ukprn, newSurveyModel.ProviderName);

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 25
0
        public async Task <ConfirmEditApprenticeshipViewModel> Map(EditApprenticeshipRequestViewModel source)
        {
            source.ApprenticeshipId = _encodingService.Decode(source.HashedApprenticeshipId, EncodingType.ApprenticeshipId);
            source.AccountId        = _encodingService.Decode(source.AccountHashedId, EncodingType.AccountId);

            var apprenticeshipTask = _commitmentApi.GetApprenticeship(source.ApprenticeshipId);
            var priceEpisodesTask  = _commitmentApi.GetPriceEpisodes(source.ApprenticeshipId);

            await Task.WhenAll(apprenticeshipTask, priceEpisodesTask);

            var apprenticeship = apprenticeshipTask.Result;
            var priceEpisodes  = priceEpisodesTask.Result;

            var currentPrice = priceEpisodes.PriceEpisodes.GetPrice();

            var vm = new ConfirmEditApprenticeshipViewModel
            {
                AccountHashedId        = source.AccountHashedId,
                ApprenticeshipHashedId = source.HashedApprenticeshipId,
                OriginalApprenticeship = new ConfirmEditApprenticeshipViewModel()
                {
                    ULN = apprenticeship.Uln
                },
                ProviderName = apprenticeship.ProviderName
            };

            if (source.FirstName != apprenticeship.FirstName || source.LastName != apprenticeship.LastName)
            {
                vm.FirstName = source.FirstName;
                vm.LastName  = source.LastName;
            }
            vm.OriginalApprenticeship.FirstName = apprenticeship.FirstName;
            vm.OriginalApprenticeship.LastName  = apprenticeship.LastName;

            if (source.Email != apprenticeship.Email)
            {
                vm.Email = source.Email;
            }
            vm.OriginalApprenticeship.Email = apprenticeship.Email;

            if (source.DateOfBirth.Date != apprenticeship.DateOfBirth)
            {
                vm.BirthDay   = source.BirthDay;
                vm.BirthMonth = source.BirthMonth;
                vm.BirthYear  = source.BirthYear;
            }
            vm.OriginalApprenticeship.BirthDay   = apprenticeship.DateOfBirth.Day;
            vm.OriginalApprenticeship.BirthMonth = apprenticeship.DateOfBirth.Month;
            vm.OriginalApprenticeship.BirthYear  = apprenticeship.DateOfBirth.Year;

            if (source.Cost != currentPrice)
            {
                vm.Cost = source.Cost;
            }
            vm.OriginalApprenticeship.Cost = currentPrice;
            vm.EmployerReference           = source.EmployerReference;
            vm.OriginalApprenticeship.EmployerReference = apprenticeship.EmployerReference;

            if (source.StartDate.Date != apprenticeship.StartDate)
            {
                vm.StartMonth = source.StartMonth;
                vm.StartYear  = source.StartYear;
            }
            vm.OriginalApprenticeship.StartMonth = apprenticeship.StartDate.Month;
            vm.OriginalApprenticeship.StartYear  = apprenticeship.StartDate.Year;

            if (source.EndDate.Date != apprenticeship.EndDate)
            {
                vm.EndMonth = source.EndMonth;
                vm.EndYear  = source.EndYear;
            }
            vm.OriginalApprenticeship.EndMonth = apprenticeship.EndDate.Month;
            vm.OriginalApprenticeship.EndYear  = apprenticeship.EndDate.Year;

            if (source.Version != apprenticeship.Version || source.CourseCode != apprenticeship.CourseCode)
            {
                vm.Version = source.Version;
            }
            vm.OriginalApprenticeship.Version = apprenticeship.Version;

            if (source.CourseCode != apprenticeship.CourseCode)
            {
                var courseDetails = !string.IsNullOrEmpty(source.Version)
                       ? await _commitmentApi.GetTrainingProgrammeVersionByCourseCodeAndVersion(source.CourseCode, source.Version)
                       : await _commitmentApi.GetTrainingProgramme(source.CourseCode);

                vm.CourseCode = source.CourseCode;
                vm.CourseName = courseDetails?.TrainingProgramme.Name;
            }
            vm.OriginalApprenticeship.CourseCode = apprenticeship.CourseCode;
            vm.OriginalApprenticeship.CourseName = apprenticeship.CourseName;

            vm.Option = source.Option == string.Empty ? "TBC" : source.Option;
            vm.OriginalApprenticeship.Option = apprenticeship.Option == string.Empty ? "TBC" : apprenticeship.Option;

            if (source.HasOptions)
            {
                vm.ReturnToChangeOption = source.HasOptions;
            }
            else
            {
                vm.ReturnToChangeVersion = !string.IsNullOrEmpty(vm.Version) && string.IsNullOrEmpty(vm.CourseCode) && !vm.StartDate.HasValue;
            }

            return(vm);
        }
Esempio n. 26
0
        public override async Task OnActionExecutionAsync(
            ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            if (_serviceParameters.AuthenticationType != AuthenticationType.Employer)
            {
                await next();

                return;
            }

            if (_serviceParameters.AuthenticationType == AuthenticationType.Employer &&
                context.HttpContext.Request.Query.ContainsKey("transferSenderId"))
            {
                if (context.RouteData.Values["controller"].ToString().Equals("SelectReservations", StringComparison.CurrentCultureIgnoreCase) &&
                    context.RouteData.Values["action"].ToString().Equals("SelectReservation", StringComparison.CurrentCultureIgnoreCase)
                    )
                {
                    await next();

                    return;
                }

                context.Result = new RedirectToRouteResult(RouteNames.Error500, null);
                return;
            }

            if (!context.RouteData.Values.TryGetValue("employerAccountId", out var employerAccountId))
            {
                context.Result = new RedirectToRouteResult(RouteNames.Error500, null);
                return;
            }

            var decodedAccountId = _encodingService.Decode(employerAccountId?.ToString(), EncodingType.AccountId);
            var result           = await _mediator.Send(new GetLegalEntitiesQuery
            {
                AccountId = decodedAccountId
            });

            if (result.AccountLegalEntities.Any(entity =>
                                                !entity.IsLevy &&
                                                entity.AgreementType != AgreementType.NonLevyExpressionOfInterest) ||
                !result.AccountLegalEntities.Any())
            {
                var homeLink = _urlHelper.GenerateDashboardUrl(employerAccountId?.ToString());

                var model = new NonEoiHoldingViewModel
                {
                    HomeLink = homeLink
                };

                var viewResult = new ViewResult
                {
                    ViewName = "NonEoiHolding",
                    ViewData = new ViewDataDictionary(((Controller)context.Controller).ViewData)
                    {
                        Model = model
                    }
                };
                context.Result = viewResult;
                return;
            }

            await next();
        }
        public async Task <ProviderSearchViewModel> GetTrainingProviderSearchViewModel(
            string encodedAccountId,
            string selectedProviderName,
            string selectedFeedbackStatus,
            int pageSize,
            int pageIndex,
            string sortColumn,
            string sortDirection)
        {
            ProviderSearchViewModel model = new ProviderSearchViewModel();

            model.AccountId              = _encodingService.Decode(encodedAccountId, EncodingType.AccountId);
            model.EncodedAccountId       = encodedAccountId;
            model.SelectedProviderName   = selectedProviderName;
            model.SelectedFeedbackStatus = selectedFeedbackStatus;
            model.SortColumn             = sortColumn;
            model.SortDirection          = sortDirection;

            // Select all the providers for this employer.

            var providers = await SelectAllProvidersForAccount(model.AccountId);

            // Augment the provider records with feedback data. Urgh.
            // We need to do this so that the date filtering will work.

            await AugmentProviderRecordsWithFeedbackStatus(model.AccountId, providers);

            // Initialise the filter options.

            model.UnfilteredTotalRecordCount = providers.Count;
            model.ProviderNameFilter         = providers.Select(p => p.ProviderName).OrderBy(p => p).ToList();
            model.FeedbackStatusFilter       = new string[] { NOT_YET_SUBMITTED };

            // Apply filters.

            var filteredProviders = providers.AsQueryable();

            filteredProviders = ApplyProviderNameFilter(filteredProviders, selectedProviderName);
            filteredProviders = ApplyFeedbackStatusFilter(filteredProviders, selectedFeedbackStatus);

            // Sort

            if (PagingState.SortDescending == model.SortDirection)
            {
                if (!string.IsNullOrWhiteSpace(model.SortColumn) && model.SortColumn.Equals("FeedbackStatus", StringComparison.InvariantCultureIgnoreCase))
                {
                    filteredProviders = filteredProviders.OrderByDescending(p => p.FeedbackStatus);
                }
                else if (!string.IsNullOrWhiteSpace(model.SortColumn) && model.SortColumn.Equals("DateSubmitted", StringComparison.InvariantCultureIgnoreCase))
                {
                    filteredProviders = filteredProviders.OrderByDescending(p => p.DateSubmitted);
                }
                else
                {
                    filteredProviders = filteredProviders.OrderByDescending(p => p.ProviderName);
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(model.SortColumn) && model.SortColumn.Equals("FeedbackStatus", StringComparison.InvariantCultureIgnoreCase))
                {
                    filteredProviders = filteredProviders.OrderBy(p => p.FeedbackStatus);
                }
                else if (!string.IsNullOrWhiteSpace(model.SortColumn) && model.SortColumn.Equals("DateSubmitted", StringComparison.InvariantCultureIgnoreCase))
                {
                    filteredProviders = filteredProviders.OrderBy(p => p.DateSubmitted);
                }
                else
                {
                    filteredProviders = filteredProviders.OrderBy(p => p.ProviderName);
                }
            }

            // Page

            var pagedFilteredProviders = filteredProviders.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            model.TrainingProviders = new PaginatedList <ProviderSearchViewModel.EmployerTrainingProvider>(pagedFilteredProviders, filteredProviders.Count(), pageIndex, pageSize, 6);

            return(model);
        }