Exemplo n.º 1
0
        private async Task <IActionResult> LoadViewModel(string view)
        {
            var username = GetUsernameFromClaim();

            Logger.LogInformation($"Load View Model for CertificateCheckViewModel for {username}");

            var viewModel = new CertificateCheckViewModel();

            CheckAndSetRedirectToCheck(viewModel);

            if (!TryGetCertificateSession("CertificateCheckViewModel", username, out var certSession))
            {
                return(RedirectToAction("Index", "Search"));
            }

            var certificate = await CertificateApiClient.GetCertificate(certSession.CertificateId);

            Logger.LogInformation($"Got Certificate for CertificateCheckViewModel requested by {username} with Id {certificate.Id}");

            viewModel.FromCertificate(certificate);
            viewModel.SetStandardHasVersionsAndOptions(certSession);

            Logger.LogInformation($"Got View Model of type CertificateCheckViewModel requested by {username}");

            return(View(view, viewModel));
        }
        private async Task <IActionResult> LoadViewModel(string view)
        {
            var username = GetUsernameFromClaim();

            Logger.LogDebug($"Load View Model for CertificateOptionViewModel for {username}");

            var viewModel = new CertificateOptionViewModel();

            CheckAndSetRedirectToCheck(viewModel);

            if (!TryGetCertificateSession("CertificateOptionViewModel", username, out CertificateSession certSession))
            {
                return(RedirectToAction("Index", "Search"));
            }

            var certificate = await CertificateApiClient.GetCertificate(certSession.CertificateId);

            if (certSession.Options == null || !certSession.Options.Any())
            {
                return(RedirectToAction("Index", "Search"));
            }

            if (certSession.Options.Count == 1)
            {
                return(RedirectToAction("Declare", "CertificateDeclaration"));
            }

            Logger.LogDebug($"Got Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id}");

            viewModel.FromCertificate(certificate, certSession.Options);

            Logger.LogDebug($"Got View Model of type CertificateOptionViewModel requested by {username}");

            return(View(view, viewModel));
        }
        private async Task <IActionResult> LoadViewModel(string view, bool?isFromStandard)
        {
            var username = ContextAccessor.HttpContext.User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn")?.Value;

            Logger.LogInformation($"Load View Model for CertificateOptionViewModel for {username}");

            var viewModel = new CertificateOptionViewModel {
                IsFromStandard = isFromStandard ?? false
            };

            var query = ContextAccessor.HttpContext.Request.Query;

            if (query.ContainsKey("redirecttocheck") && bool.Parse(query["redirecttocheck"]))
            {
                Logger.LogInformation($"RedirectToCheck for CertificateOptionViewModel is true");
                SessionService.Set("redirecttocheck", "true");
                viewModel.BackToCheckPage = true;
            }
            else
            {
                SessionService.Remove("redirecttocheck");
            }

            var sessionString = SessionService.Get("CertificateSession");

            if (sessionString == null)
            {
                Logger.LogInformation($"Session for CertificateOptionViewModel requested by {username} has been lost. Redirecting to Search Index");
                return(RedirectToAction("Index", "Search"));
            }
            var certSession = JsonConvert.DeserializeObject <CertificateSession>(sessionString);

            var certificate = await CertificateApiClient.GetCertificate(certSession.CertificateId);

            if (!certSession.Options.Any())
            {
                if (ContextAccessor.HttpContext.Request.Query.ContainsKey("fromback"))
                {
                    if (certificate.IsPrivatelyFunded)
                    {
                        return(RedirectToAction("StandardCode", "CertificatePrivateStandardCode"));
                    }
                    return(RedirectToAction("Declare", "CertificateDeclaration"));
                }

                return(RedirectToAction("Grade", "CertificateGrade"));
            }

            Logger.LogInformation($"Got Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id}");

            viewModel.FromCertificate(certificate, certSession.Options);

            Logger.LogInformation($"Got View Model of type CertificateOptionViewModel requested by {username}");

            return(View(view, viewModel));
        }
Exemplo n.º 4
0
        private async Task <IActionResult> LoadViewModel(string view)
        {
            var username = GetUsernameFromClaim();

            Logger.LogDebug($"Load View Model for CertificateVersionViewModel for {username}");

            var viewModel = new CertificateVersionViewModel();

            CheckAndSetRedirectToCheck(viewModel);

            if (!TryGetCertificateSession("CertificateVersionViewModel", username, out CertificateSession certSession))
            {
                return(RedirectToAction("Index", "Search"));
            }

            var certificate = await CertificateApiClient.GetCertificate(certSession.CertificateId, includeLogs : true);

            if (certSession.Versions == null || certSession.Versions.Count == 0)
            {
                return(RedirectToAction("Index", "Search"));
            }

            if (certSession.Versions.Count == 1)
            {
                // Only 1 version no need for a selection
                var singularStandard = certSession.Versions.First();
                var options          = await _standardVersionClient.GetStandardOptions(singularStandard.StandardUId);

                if (options != null & options.HasOptions())
                {
                    certSession.StandardUId = singularStandard.StandardUId;
                    certSession.Options     = options.CourseOption.ToList();
                    SessionService.Set(nameof(CertificateSession), certSession);
                    return(RedirectToAction("Option", "CertificateOption"));
                }

                return(RedirectToAction("Declare", "CertificateDeclaration"));
            }

            Logger.LogDebug($"Got Certificate for CertificateVersionViewModel requested by {username} with Id {certificate.Id}");

            viewModel.FromCertificate(certificate, certSession.Versions);

            var attemptedStandardVersion = SessionService.Get("AttemptedStandardVersion");

            if (attemptedStandardVersion != null)
            {
                viewModel.StandardUId = attemptedStandardVersion;
                SessionService.Remove("AttemptedStandardVersion");
            }

            Logger.LogDebug($"Got View Model of type CertificateVersionViewModel requested by {username}");

            return(View(view, viewModel));
        }
Exemplo n.º 5
0
        public async Task GetCertificate()
        {
            // arrange
            long   uln                  = 1234567890;
            string lastname             = "Bloggs";
            string standard             = "1";
            string certificateReference = "123456790";

            var certificateData = Builder <CertificateData> .CreateNew().With(cd => cd.CertificateReference = certificateReference)
                                  .With(cd => cd.Standard        = Builder <Standard> .CreateNew().With(s => s.StandardCode = 1).Build())
                                  .With(cd => cd.Learner         = Builder <Learner> .CreateNew().Build())
                                  .With(cd => cd.LearningDetails = Builder <LearningDetails> .CreateNew().Build())
                                  .With(cd => cd.PostalContact   = Builder <PostalContact> .CreateNew().Build())
                                  .Build();

            var status = new Status {
                CurrentStatus = "Submitted"
            };
            var created = new Created {
                CreatedAt = DateTime.UtcNow.AddHours(-1), CreatedBy = "Test"
            };
            var submitted = new Submitted {
                SubmittedAt = DateTime.UtcNow, SubmittedBy = "Test"
            };

            var expectedResponse = new Certificate {
                CertificateData = certificateData, Status = status, Created = created, Submitted = submitted
            };

            _MockHttp.When(HttpMethod.Get, $"{apiBaseAddress}/api/v1/certificate/{uln}/{lastname}/{standard}")
            .Respond(HttpStatusCode.OK, "application/json", JsonConvert.SerializeObject(expectedResponse));

            // act
            var request = new GetCertificateRequest {
                Uln = uln, FamilyName = lastname, Standard = standard
            };
            var actual = await _ApiClient.GetCertificate(request);

            // assert
            Assert.That(actual.Error, Is.Null);
            Assert.That(actual.Certificate, Is.Not.Null);
        }
        private async Task <IActionResult> SaveViewModel(CertificateOptionViewModel vm, string returnToIfModelNotValid, RedirectToActionResult nextAction, string action)
        {
            var username = GetUsernameFromClaim();

            Logger.LogDebug($"Save View Model for CertificateOptionViewModel for {username} with values: {GetModelValues(vm)}");

            var certificate = await CertificateApiClient.GetCertificate(vm.Id);

            var certData = JsonConvert.DeserializeObject <CertificateData>(certificate.CertificateData);

            SessionService.RemoveRedirectedFromVersion();

            var sessionString = SessionService.Get(nameof(CertificateSession));

            if (sessionString == null)
            {
                Logger.LogDebug($"Session for CertificateOptionViewModel requested by {username} has been lost. Redirecting to Search Index");
                return(RedirectToAction("Index", "Search"));
            }
            var certSession = JsonConvert.DeserializeObject <CertificateSession>(sessionString);

            if (!ModelState.IsValid)
            {
                vm.Options = certSession.Options;
                Logger.LogDebug($"Model State not valid for CertificateOptionViewModel requested by {username} with Id {certificate.Id}. Errors: {ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)}");
                return(View(returnToIfModelNotValid, vm));
            }

            var updatedCertificate = vm.GetCertificateFromViewModel(certificate, certData);

            try
            {
                await CertificateApiClient.UpdateCertificate(new UpdateCertificateRequest(updatedCertificate) { Username = username, Action = action });
            }
            catch
            {
                Logger.LogError($"Unable to update certificate with Id {certificate.Id}.");
                return(RedirectToAction("Error", "Home"));
            }

            Logger.LogDebug($"Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id} updated.");

            if (SessionService.GetRedirectToCheck())
            {
                Logger.LogDebug($"Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id} redirecting back to Certificate Check.");
                return(new RedirectToActionResult("Check", "CertificateCheck", null));
            }

            Logger.LogDebug($"Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id} redirecting to {nextAction.ControllerName} {nextAction.ActionName}");
            return(nextAction);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Grade(CertificateGradeViewModel vm)
        {
            var certificate = await CertificateApiClient.GetCertificate(vm.Id);

            if (certificate.IsPrivatelyFunded)
            {
                return(await SaveViewModel(vm,
                                           returnToIfModelNotValid : "~/Views/Certificate/Grade.cshtml",
                                           nextAction : RedirectToAction("LearnerStartDate", "CertificatePrivateLearnerStartDate"),
                                           action : CertificateActions.Grade));
            }
            return(await SaveViewModel(vm,
                                       returnToIfModelNotValid : "~/Views/Certificate/Grade.cshtml",
                                       nextAction : RedirectToAction("Date", "CertificateDate"), action : CertificateActions.Grade));
        }
        private async Task <IActionResult> SaveViewModel(CertificateOptionViewModel vm, string returnToIfModelNotValid, RedirectToActionResult nextAction, string action)
        {
            var username = ContextAccessor.HttpContext.User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn")?.Value;

            Logger.LogInformation($"Save View Model for CertificateOptionViewModel for {username} with values: {GetModelValues(vm)}");

            var certificate = await CertificateApiClient.GetCertificate(vm.Id);

            var certData = JsonConvert.DeserializeObject <CertificateData>(certificate.CertificateData);

            var sessionString = SessionService.Get("CertificateSession");

            if (sessionString == null)
            {
                Logger.LogInformation($"Session for CertificateOptionViewModel requested by {username} has been lost. Redirecting to Search Index");
                return(RedirectToAction("Index", "Search"));
            }
            var certSession = JsonConvert.DeserializeObject <CertificateSession>(sessionString);

            if (!ModelState.IsValid)
            {
                vm.FamilyName = certData.LearnerFamilyName;
                vm.GivenNames = certData.LearnerGivenNames;
                vm.Options    = certSession.Options;
                Logger.LogInformation($"Model State not valid for CertificateOptionViewModel requested by {username} with Id {certificate.Id}. Errors: {ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)}");
                return(View(returnToIfModelNotValid, vm));
            }

            var updatedCertificate = vm.GetCertificateFromViewModel(certificate, certData);

            await CertificateApiClient.UpdateCertificate(new UpdateCertificateRequest(updatedCertificate) { Username = username, Action = action });

            Logger.LogInformation($"Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id} updated.");

            if (SessionService.Exists("redirecttocheck") && bool.Parse(SessionService.Get("redirecttocheck")))
            {
                Logger.LogInformation($"Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id} redirecting back to Certificate Check.");
                return(new RedirectToActionResult("Check", "CertificateCheck", null));
            }

            Logger.LogInformation($"Certificate for CertificateOptionViewModel requested by {username} with Id {certificate.Id} redirecting to {nextAction.ControllerName} {nextAction.ActionName}");
            return(nextAction);
        }
        public async Task GetCertificateExample()
        {
            long   uln      = 1234567890;
            string lastName = "Blogs";
            string standard = "1";

            GetCertificateRequest certificateToGet = new GetCertificateRequest
            {
                Uln        = uln,
                FamilyName = lastName,
                Standard   = standard,
            };

            if (certificateToGet.IsValid(out _))
            {
                // NOTE: The External API performs validation, however it is a good idea to check beforehand
                await _CertificateApiClient.GetCertificate(certificateToGet);
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Check(CertificateCheckViewModel vm)
        {
            // This is the final step in the process so get the latest version of the certificate!
            if (vm is null)
            {
                vm = new CertificateCheckViewModel();
            }
            vm.FromCertificate(await CertificateApiClient.GetCertificate(vm.Id));

            var result = _validator.Validate(vm);

            if (!result.IsValid)
            {
                return(await Check());
            }

            return(await SaveViewModel(vm,
                                       returnToIfModelNotValid : "~/Views/Certificate/Check.cshtml",
                                       nextAction : RedirectToAction("Confirm", "CertificateConfirmation"), action : CertificateActions.Submit));
        }
        public async Task GetCertificateExample()
        {
            const string filePath = @"CsvFiles\getCertificates.csv";

            IEnumerable <GetCertificateRequest> certificates;

            using (TextReader textReader = File.OpenText(filePath))
            {
                using (CsvReader csv = new CsvReader(textReader))
                {
                    csv.Configuration.HeaderValidated   = null;
                    csv.Configuration.MissingFieldFound = null;
                    certificates = csv.GetRecords <GetCertificateRequest>().ToList();
                }
            }

            // NOTE: The External API performs validation, however it is a good idea to check beforehand.
            bool invalidDataSupplied = certificates.Any(c => !c.IsValid(out _));

            if (invalidDataSupplied)
            {
                throw new InvalidOperationException("The supplied CSV file contains invalid data. Please correct and then try again.");
            }
            else
            {
                // NOTE: The External API does not have an batch delete (for safety reasons). You'll have to loop.
                foreach (var request in certificates)
                {
                    var response = await _CertificateApiClient.GetCertificate(request);

                    if (response is null)
                    {
                        // NOTE: You may want to deal with bad records separately
                    }
                }
            }
        }
Exemplo n.º 12
0
        private async Task <IActionResult> SaveViewModel(CertificateVersionViewModel vm, RedirectToActionResult nextAction, string action)
        {
            var username        = GetUsernameFromClaim();
            var epaoid          = GetEpaOrgIdFromClaim();
            var redirectToCheck = SessionService.GetRedirectToCheck();

            Logger.LogDebug($"Save View Model for CertificateVersionViewModel for {username} with values: {GetModelValues(vm)}");

            var certificate = await CertificateApiClient.GetCertificate(vm.Id);

            var certData = JsonConvert.DeserializeObject <CertificateData>(certificate.CertificateData);

            if (!TryGetCertificateSession("CertificateVersionViewModel", username, out var certSession))
            {
                return(RedirectToAction("Index", "Search"));
            }

            if (!ModelState.IsValid)
            {
                Logger.LogDebug($"Model State not valid for CertificateVersionViewModel requested by {username} with Id {certificate.Id}. Errors: {ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)}");
                return(View("~/Views/Certificate/Version.cshtml", vm));
            }

            var standardVersion = await _standardVersionClient.GetStandardVersionById(vm.StandardUId);

            var approvedStandardVersions = await _standardVersionClient.GetEpaoRegisteredStandardVersions(epaoid, certSession.StandardCode);

            var options = await _standardVersionClient.GetStandardOptions(vm.StandardUId);

            if (!approvedStandardVersions.Any(v => v.StandardUId == vm.StandardUId))
            {
                SessionService.Set("AttemptedStandardVersion", vm.StandardUId);

                return(RedirectToAction("NotApprovedToAssess", "CertificateVersionNotApproved", redirectToCheck ? new { redirectToCheck } : null));
            }

            var versionChanged = certificate.StandardUId != vm.StandardUId;
            // Edge case to cater to back buttons where user can change version without setting an option
            var optionNotSet = string.IsNullOrEmpty(certData.CourseOption) && options != null && options.HasOptions();

            if (!versionChanged && !optionNotSet && redirectToCheck)
            {
                // if version hasn't changed, and option set if required, don't need to update options.
                return(new RedirectToActionResult("Check", "CertificateCheck", null));
            }

            certSession.StandardUId = vm.StandardUId;

            // To pass in to inherited method.
            vm.SelectedStandardVersion = standardVersion;
            vm.SelectedStandardOptions = options;
            var updatedCertificate = vm.GetCertificateFromViewModel(certificate, certData);

            try
            {
                await CertificateApiClient.UpdateCertificate(new UpdateCertificateRequest(updatedCertificate) { Username = username, Action = action });
            }
            catch
            {
                Logger.LogError($"Unable to update certificate with Id {certificate.Id}.");
                return(RedirectToAction("Error", "Home"));
            }

            Logger.LogDebug($"Certificate for CertificateVersionViewModel requested by {username} with Id {certificate.Id} updated.");

            if (options != null && options.HasOptions())
            {
                certSession.Options = options.CourseOption.ToList();
                SessionService.Set(nameof(CertificateSession), certSession);

                if (options.OnlyOneOption())
                {
                    if (redirectToCheck)
                    {
                        return(new RedirectToActionResult("Check", "CertificateCheck", null));
                    }

                    return(new RedirectToActionResult("Declare", "CertificateDeclaration", null));
                }

                object routeValues = null;
                if (redirectToCheck)
                {
                    routeValues = new { redirecttocheck = true };
                }

                SessionService.SetRedirectedFromVersion(true);
                return(new RedirectToActionResult("Option", "CertificateOption", routeValues));
            }
            else
            {
                certSession.Options = null;
                SessionService.Set(nameof(CertificateSession), certSession);
            }

            if (redirectToCheck)
            {
                Logger.LogDebug($"Certificate for CertificateVersionViewModel requested by {username} with Id {certificate.Id} redirecting back to Certificate Check.");
                return(new RedirectToActionResult("Check", "CertificateCheck", null));
            }

            Logger.LogDebug($"Certificate for CertificateVersionViewModel requested by {username} with Id {certificate.Id} redirecting to {nextAction.ControllerName} {nextAction.ActionName}");
            return(nextAction);
        }