Inheritance: ObservableObject
Exemplo n.º 1
0
        public void Complete_ShouldRenderDefaultViewWithModelIdWhenModelIsNotValid()
        {
            var memberIdProviderStub      = new Mock <IMemberIdProvider>();
            var memberServiceStub         = new Mock <IMemberService>();
            var mapperStub                = new Mock <IMapper>();
            var pendingWorkoutServiceStub = new Mock <IPendingWorkoutService>();
            var modelViewFactoryStub      = new Mock <IModelViewFactory>();
            var dataModelFactoryStub      = new Mock <IDataModelFactory>();

            var sut = new CompleteWorkoutController(memberIdProviderStub.Object,
                                                    memberServiceStub.Object,
                                                    mapperStub.Object,
                                                    pendingWorkoutServiceStub.Object,
                                                    modelViewFactoryStub.Object,
                                                    dataModelFactoryStub.Object);

            var model = new CompleteViewModel();

            model.Id = new Guid();

            sut
            .WithModelErrors()
            .WithCallTo(c => c.Complete(model))
            .ShouldRenderDefaultView();
        }
Exemplo n.º 2
0
        public ActionResult Complete(CompleteViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                var time = new TimeSpan(0, model.Minutes, model.Seconds);

                var pending = this.pendingWorkoutService.GetById(model.Id);

                this.pendingWorkoutService.MarkPendingAsCompleted(pending);

                var workout = this.dataModelFactory.CreateWorkout();

                workout.Member             = pending.Member;
                workout.WorkoutInformation = pending.DailyWorkout.WorkoutInformation;
                workout.Time = time;

                var member = this.memberService.GetById(pending.Member.Id);

                this.memberService.AddWorkout(member, workout);

                return(this.RedirectToAction("All"));
            }

            return(this.View(model.Id));
        }
Exemplo n.º 3
0
 private LocatorService()
 {
     _home     = new HomeViewModel();
     _window   = new WindowViewModel();
     _register = new RegisterViewModel();
     _payment  = new PaymentViewModel();
     _complete = new CompleteViewModel();
 }
Exemplo n.º 4
0
        public void RegisterController_ActivateService_POST_CorrectPIN_ServiceActivated()
        {
            //ARRANGE:
            //create a user who does exist in the db
            var user = new User {
                UserId = 1, EmailAddress = "*****@*****.**", EmailVerifiedDate = VirtualDateTime.Now
            };
            var org = new Organisation {
                OrganisationId = 1, SectorType = SectorTypes.Private, Status = OrganisationStatuses.Pending
            };

            //TODO: Refactoring to user the same Helpers (ie AddScopeStatus.AddScopeStatus)
            org.OrganisationScopes.Add(
                new OrganisationScope {
                Organisation = org,
                ScopeStatus  = ScopeStatuses.InScope,
                SnapshotDate = org.SectorType.GetAccountingStartDate(VirtualDateTime.Now.Year),
                Status       = ScopeRowStatuses.Active
            });

            var address = new OrganisationAddress {
                AddressId = 1, OrganisationId = 1, Organisation = org, Status = AddressStatuses.Pending
            };
            var pin     = "ASDFG";
            var userOrg = new UserOrganisation {
                UserId         = 1,
                OrganisationId = 1,
                PINSentDate    = VirtualDateTime.Now,
                PIN            = pin,
                AddressId      = address.AddressId,
                Address        = address
            };

            var routeData = new RouteData();

            routeData.Values.Add("Action", nameof(RegisterController.ActivateService));
            routeData.Values.Add("Controller", "Register");

            var controller = UiTestHelper.GetController <RegisterController>(user.UserId, routeData, user, org, address, userOrg);

            controller.ReportingOrganisationId = org.OrganisationId;

            var model = new CompleteViewModel {
                PIN = pin
            };

            //ACT:
            var result = controller.ActivateService(model) as RedirectToActionResult;

            //ASSERT:
            Assert.That(result != null, "Expected RedirectToActionResult");
            Assert.That(result.ActionName == "ServiceActivated", "Expected redirect to ServiceActivated");
            Assert.That(userOrg.PINConfirmedDate > DateTime.MinValue);
            Assert.That(userOrg.Organisation.Status == OrganisationStatuses.Active);
            Assert.That(userOrg.Organisation.GetLatestAddress().AddressId == address.AddressId);
            Assert.That(address.Status == AddressStatuses.Active);
        }
Exemplo n.º 5
0
        public ActionResult Complete_Order()
        {
            var model = new CompleteViewModel
            {
                CartCount = 0
            };

            return(View(model));
        }
        /// <summary>
        /// Display success
        /// </summary>
        /// <param name="project">name of the created project</param>
        /// <returns>Model with prop for linking to created project. NOTE: DEPLOY NEED TIME - 3-4 MINS</returns>
        public IActionResult Complete(string project)
        {
            var model = new CompleteViewModel()
            {
                ProjectUrl = $"https://{project}.netlify.com"
            };

            return(View(model));
        }
        public IActionResult Complete(CompleteViewModel model)
        {
            var apprenticeship = _session.GetObject <Apprenticeship>("selectedApprenticeship");

            model.ApprenticeshipName = apprenticeship.ApprenticeshipTitle;

            _session.Remove("selectedApprenticeship");
            _session.Remove("ApprenticeshipMode");
            return(View("../Apprenticeships/Complete/Index", model));
        }
Exemplo n.º 8
0
        public ActionResult Complete()
        {
            var subDomain = TempData["SubDomain"] as string;

            var viewModel = new CompleteViewModel
            {
                SubDomain = subDomain
            }.WithConfig(configuration);

            return(View(viewModel));
        }
Exemplo n.º 9
0
        public ActionResult StoreAdditionalInfo(CompleteViewModel completeViewModel)
        {
            var viewModel = completeViewModel.WithConfig(configuration);

            if (!ModelState.IsValid)
            {
                return(View("Complete", viewModel));
            }

            return(View("Complete", viewModel));
        }
Exemplo n.º 10
0
        public static CompleteViewModel GetCompleteViewModel(Interview interview, Exam exam, Candidate candidate)
        {
            var viewModel = new CompleteViewModel();

            viewModel.InterviewId          = interview.Id;
            viewModel.Score                = interview.Score;
            viewModel.CandidateName        = candidate.FirstName + " " + candidate.LastName;
            viewModel.CandidateDescription = candidate.Description;
            viewModel.ExamLogo             = exam.Logo;
            viewModel.ExamTypeLogo         = MediaManager.GetIconForExamType(exam.Type);
            viewModel.Type = exam.Type;

            return(viewModel);
        }
Exemplo n.º 11
0
        public ActionResult DownloadFile(CompleteViewModel vm)
        {
            List <int> measurementIds = vm.DownloadViewModel.DownloadViewModelList.Where(x => x.Checked).Select(x => x.MeasurementId).ToList <int>();

            string fs = DataHelper.Download(measurementIds, vm.FilterSettings, vm.DownloadViewModel.DownloadStl, vm.DownloadViewModel.DownloadVtk, vm.DownloadViewModel.DownloadCsv);

            Response.Cookies.Add(new HttpCookie("OPD_download_done", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:ff")));
            if (fs == null)
            {
                return(null);
            }
            byte[] fileBytes = System.IO.File.ReadAllBytes(fs);
            return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, System.IO.Path.GetFileName(fs)));
        }
Exemplo n.º 12
0
        public async Task <ActionResult> Complete(string requestId)
        {
            ScanRequestHandler scanner = new ScanRequestHandler();
            bool result = await scanner.TryGetScanResult(requestId);

            if (!result)
            {
                //The processing  has not yet finished
                //Add a refresh header, to refresh the page in 5 seconds.
                Response.Headers.Add("Refresh", "5");
                var model = new CompleteViewModel();
                return(View(model));
            }

            return(RedirectToAction("Report", new { requestId = requestId }));
        }
Exemplo n.º 13
0
        public IActionResult ActivateService()
        {
            //Ensure user has completed the registration process
            User          currentUser;
            IActionResult checkResult = CheckUserRegisteredOk(out currentUser);

            if (checkResult != null)
            {
                return(checkResult);
            }

            //Get the user organisation
            UserOrganisation userOrg = DataRepository.GetAll <UserOrganisation>()
                                       .FirstOrDefault(uo => uo.UserId == currentUser.UserId && uo.OrganisationId == ReportingOrganisationId);

            if (userOrg == null)
            {
                throw new AuthenticationException();
            }

            //Ensure they havent entered wrong pin too many times
            TimeSpan remaining = userOrg.ConfirmAttemptDate == null
                ? TimeSpan.Zero
                : userOrg.ConfirmAttemptDate.Value.AddMinutes(Global.LockoutMinutes) - VirtualDateTime.Now;

            if (userOrg.ConfirmAttempts >= Global.MaxPinAttempts && remaining > TimeSpan.Zero)
            {
                return(View("CustomError", new ErrorViewModel(1113, new { remainingTime = remaining.ToFriendly(maxParts: 2) })));
            }

            remaining = userOrg.PINSentDate == null
                ? TimeSpan.Zero
                : userOrg.PINSentDate.Value.AddDays(Global.PinInPostMinRepostDays) - VirtualDateTime.Now;
            var model = new CompleteViewModel();

            model.PIN         = null;
            model.AllowResend = remaining <= TimeSpan.Zero;
            model.Remaining   = remaining.ToFriendly(maxParts: 2);

            //Show the PIN textbox and button
            return(View("ActivateService", model));
        }
Exemplo n.º 14
0
        public ActionResult Data(CompleteViewModel vm)
        {
            vm.FilterViewModel = JsonConvert.DeserializeObject <FilterViewModel>(vm.FilterSettings);

            String baseSql = @"
                                SELECT
                                pa.measurement_id as MeasurementId
                                ,sa.material as Material
                                ,sa.production_process as Process
                                ,count(*) as NumberFilteredParticles
                                ,max(meas.voxel_size) as VoxelSize
                                ,meas.example_stack_image as ExampleImageFromStack
                                ,meas.doi_url  as RawImageDownloadURL
                                from particles pa
                                inner join sample sa on pa.sample_id = sa.sample_id
                                inner join measurement meas on pa.measurement_id = meas.measurement_id
                                inner join v_calculatedparameters v_calc on v_calc.particle_id = pa.particle_id
                                /**where**/
                                group by pa.measurement_id,sa.material,sa.production_process;
                             ";

            DynamicParameters parameters = new DynamicParameters();
            SqlBuilder        sqlBuilder = new SqlBuilder();
            var sql = sqlBuilder.AddTemplate(baseSql);

            sqlBuilder.addBaseFilters(vm.FilterViewModel);

            sqlBuilder.Where("sa.material in @material", new { material = vm.SearchViewModel.Where(i => i.Checked).Select(i => i.Material).ToList() });

            List <DataViewModel> data;

            using (var connection = new MySqlConnection(DatabaseHelper.getDbConnectionString()))
            {
                data = connection.Query <DataViewModel>(sql.RawSql, sql.Parameters).ToList();
            }

            return(PartialView(new CompleteViewModel()
            {
                DataViewModel = data,
                FilterSettings = JsonConvert.SerializeObject(vm.FilterViewModel, Formatting.Indented)
            }));
        }
Exemplo n.º 15
0
        public void Complete_ShouldRedirectToCorrectActionWhenModelIsValid()
        {
            var memberIdProviderStub      = new Mock <IMemberIdProvider>();
            var memberServiceStub         = new Mock <IMemberService>();
            var mapperStub                = new Mock <IMapper>();
            var pendingWorkoutServiceStub = new Mock <IPendingWorkoutService>();
            var modelViewFactoryStub      = new Mock <IModelViewFactory>();
            var dataModelFactoryStub      = new Mock <IDataModelFactory>();

            var sut = new CompleteWorkoutController(memberIdProviderStub.Object,
                                                    memberServiceStub.Object,
                                                    mapperStub.Object,
                                                    pendingWorkoutServiceStub.Object,
                                                    modelViewFactoryStub.Object,
                                                    dataModelFactoryStub.Object);

            var model = new CompleteViewModel();

            model.Id      = new Guid();
            model.Minutes = 15;
            model.Seconds = 10;
            var pending = new PendingWorkout();

            pending.Member       = new Member();
            pending.DailyWorkout = new DailyWorkout
            {
                WorkoutInformation = new WorkoutInformation()
            };

            var workout = new Workout();

            pendingWorkoutServiceStub.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(pending);
            pendingWorkoutServiceStub.Setup(x => x.MarkPendingAsCompleted(It.IsAny <PendingWorkout>()));
            dataModelFactoryStub.Setup(x => x.CreateWorkout()).Returns(workout);
            memberServiceStub.Setup(x => x.AddWorkout(It.IsAny <Member>(), It.IsAny <Workout>()));


            sut
            .WithCallTo(c => c.Complete(model))
            .ShouldRedirectTo(c => c.All());
        }
Exemplo n.º 16
0
        public ActionResult Download(CompleteViewModel vm)
        {
            vm.FilterViewModel = JsonConvert.DeserializeObject <FilterViewModel>(vm.FilterSettings);

            String baseSql = @"
                                SELECT 
                                meas.measurement_id as MeasurementId
                                ,max(pa.filename) as FileName
                                ,max(sa.material) as Material
                                from particles pa
                                inner join sample sa on pa.sample_id = sa.sample_id
                                inner join measurement meas on pa.measurement_id = meas.measurement_id
                                inner join v_calculatedparameters v_calc on v_calc.particle_id = pa.particle_id
                                /**where**/
                                group by meas.measurement_id
                            ";

            DynamicParameters parameters = new DynamicParameters();
            SqlBuilder        sqlBuilder = new SqlBuilder();
            var sql = sqlBuilder.AddTemplate(baseSql);

            sqlBuilder.Where("meas.measurement_id in @measurementId", new { measurementId = vm.DataViewModel.Where(i => i.Checked).Select(i => i.MeasurementId).ToList() });
            sqlBuilder.addBaseFilters(vm.FilterViewModel);

            List <DownloadViewModelList> download;

            using (var connection = new MySqlConnection(DatabaseHelper.getDbConnectionString()))
            {
                download = connection.Query <DownloadViewModelList>(sql.RawSql, sql.Parameters).ToList();
            }

            return(PartialView(new CompleteViewModel()
            {
                DownloadViewModel = new DownloadViewModel()
                {
                    DownloadViewModelList = download
                },
                FilterSettings = JsonConvert.SerializeObject(vm.FilterViewModel, Formatting.Indented)
            }));
        }
Exemplo n.º 17
0
        //
        // GET: /Checkout/Complete
        public ActionResult Complete(int id, int CartCount)
        {
            // Validate customer owns this order
            bool isValid = db.Orders.Any(
                o => o.OrderId == id &&
                o.Email == User.Identity.Name);

            var model = new CompleteViewModel
            {
                OrderId   = id,
                CartCount = CartCount
            };

            if (isValid)
            {
                return(View(model));
            }
            else
            {
                return(View("Error"));
            }
        }
Exemplo n.º 18
0
        public ActionResult Search(CompleteViewModel vm)
        {
            String baseSql = @"
                                SELECT
                                sa.material as Material
                                ,meas.measurement_id as MeasurementId
                                ,count(*) as NumberFilteredParticles
                                ,sa.sem_example_image as SEMExample
                                ,sa.sem_example_detail_image as SEMExampleDetail
                                ,sa.particle_size_distribution_image as ParticleSizeDistribution
                                from 
                                particles pa
                                inner join sample sa on pa.sample_id = sa.sample_id
                                inner join measurement meas on pa.measurement_id = meas.measurement_id
                                inner join v_calculatedparameters v_calc on v_calc.particle_id = pa.particle_id
                                /**where**/
                                group by sa.material,meas.measurement_id,sa.sem_example_image,sa.sem_example_detail_image,sa.particle_size_distribution_image
                             ";

            DynamicParameters parameters = new DynamicParameters();
            SqlBuilder        sqlBuilder = new SqlBuilder();
            var sql = sqlBuilder.AddTemplate(baseSql);

            sqlBuilder.addBaseFilters(vm.FilterViewModel);

            List <SearchViewModel> search;

            using (var connection = new MySqlConnection(DatabaseHelper.getDbConnectionString()))
            {
                search = connection.Query <SearchViewModel>(sql.RawSql, sql.Parameters).ToList();
            }

            return(PartialView(new CompleteViewModel()
            {
                SearchViewModel = search,
                FilterSettings = JsonConvert.SerializeObject(vm.FilterViewModel, Formatting.Indented)
            }));
        }
        public async Task RegistrationController_POST_When_User_Added_To_Private_Organisation_Then_Email_Existing_Users()
        {
            // Arrange
            var organisationId = 100;

            Core.Entities.Organisation organisation = createPrivateOrganisation(organisationId, "Company1", 12345678);
            User             existingUser1          = CreateUser(1, "*****@*****.**");
            User             existingUser2          = CreateUser(2, "*****@*****.**");
            User             newUser = CreateUser(3, "*****@*****.**");
            UserOrganisation existingUserOrganisation1 = CreateUserOrganisation(organisation, existingUser1.UserId, VirtualDateTime.Now);
            UserOrganisation existingUserOrganisation2 = CreateUserOrganisation(organisation, existingUser2.UserId, VirtualDateTime.Now);
            UserOrganisation newUserOrganisation       = CreateUserOrganisation(organisation, newUser.UserId, VirtualDateTime.Now);

            newUserOrganisation.PIN = "B5EC243";
            newUserOrganisation.PINConfirmedDate = null;
            newUserOrganisation.PINSentDate      = VirtualDateTime.Now.AddDays(100000);

            var routeData = new RouteData();

            routeData.Values.Add("Action", "ActivateService");
            routeData.Values.Add("Controller", "Registration");

            var testModel = new CompleteViewModel {
                PIN = "B5EC243", OrganisationId = organisationId
            };

            var controller = UiTestHelper.GetController <RegistrationController>(
                newUser.UserId,
                routeData,
                organisation,
                existingUser1,
                existingUser2,
                newUser,
                existingUserOrganisation1,
                existingUserOrganisation2,
                newUserOrganisation);

            controller.ReportingOrganisationId = organisationId;

            var mockNotifyEmailQueue = new Mock <IQueue>();

            mockNotifyEmailQueue
            .Setup(q => q.AddMessageAsync(It.IsAny <SendEmailRequest>()));

            // Act
            await controller.ActivateService(testModel);

            //ASSERT:
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(existingUser1.EmailAddress))),
                Times.Once(),
                "Expected the existingUser1's email address to be in the email send queue");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(existingUser2.EmailAddress))),
                Times.Once(),
                "Expected the existingUser2's email address to be in the email send queue");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.TemplateId.Contains(EmailTemplates.UserAddedToOrganisationEmail))),
                Times.Exactly(2),
                $"Expected the correct templateId to be in the email send queue, expected {EmailTemplates.UserAddedToOrganisationEmail}");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(newUser.EmailAddress))),
                Times.Never,
                "Do not expect new user's email address to be in the email send queue");
        }
Exemplo n.º 20
0
        public IActionResult ActivateService(CompleteViewModel model)
        {
            //Ensure user has completed the registration process
            User          currentUser;
            IActionResult checkResult = CheckUserRegisteredOk(out currentUser);

            if (checkResult != null)
            {
                return(checkResult);
            }

            //Ensure they have entered a PIN
            if (!ModelState.IsValid)
            {
                this.CleanModelErrors <CompleteViewModel>();
                return(View("ActivateService", model));
            }

            //Get the user organisation
            UserOrganisation userOrg = DataRepository.GetAll <UserOrganisation>()
                                       .FirstOrDefault(uo => uo.UserId == currentUser.UserId && uo.OrganisationId == ReportingOrganisationId);

            ActionResult result1;

            TimeSpan remaining = userOrg.ConfirmAttemptDate == null
                ? TimeSpan.Zero
                : userOrg.ConfirmAttemptDate.Value.AddMinutes(Global.LockoutMinutes) - VirtualDateTime.Now;

            if (userOrg.ConfirmAttempts >= Global.MaxPinAttempts && remaining > TimeSpan.Zero)
            {
                return(View("CustomError", new ErrorViewModel(1113, new { remainingTime = remaining.ToFriendly(maxParts: 2) })));
            }

            var updateSearchIndex = false;

            if (PinMatchesPinInDatabase(userOrg, model.PIN))
            {
                //Set the user org as confirmed
                userOrg.PINConfirmedDate = VirtualDateTime.Now;

                //Set the pending organisation to active
                //Make sure the found organisation is active or pending

                if (userOrg.Organisation.Status.IsAny(OrganisationStatuses.Pending, OrganisationStatuses.Active))
                {
                    userOrg.Organisation.SetStatus(
                        OrganisationStatuses.Active,
                        OriginalUser == null ? currentUser.UserId : OriginalUser.UserId,
                        "PIN Confirmed");
                    updateSearchIndex = true;
                }
                else
                {
                    CustomLogger.Warning(
                        $"Attempt to PIN activate a {userOrg.Organisation.Status} organisation",
                        $"Organisation: '{userOrg.Organisation.OrganisationName}' Reference: '{userOrg.Organisation.EmployerReference}' User: '******'");
                    return(View("CustomError", new ErrorViewModel(1149)));
                }

                //Retire the old address
                OrganisationAddress latestAddress = userOrg.Organisation.GetLatestAddress();
                if (latestAddress != null && latestAddress.AddressId != userOrg.Address.AddressId)
                {
                    latestAddress.SetStatus(
                        AddressStatuses.Retired,
                        OriginalUser == null ? currentUser.UserId : OriginalUser.UserId,
                        "Replaced by PIN in post");
                    updateSearchIndex = true;
                }

                //Activate the address the pin was sent to
                userOrg.Address.SetStatus(
                    AddressStatuses.Active,
                    OriginalUser == null ? currentUser.UserId : OriginalUser.UserId,
                    "PIN Confirmed");
                userOrg.ConfirmAttempts = 0;

                model.AccountingDate = userOrg.Organisation.SectorType.GetAccountingStartDate();
                model.OrganisationId = userOrg.OrganisationId;
                this.StashModel(model);

                result1 = RedirectToAction("ServiceActivated");

                //Send notification email to existing users
                EmailSendingServiceHelpers.SendUserAddedEmailToExistingUsers(userOrg.Organisation, userOrg.User, emailSendingService);
            }
            else
            {
                userOrg.ConfirmAttempts++;
                AddModelError(3015, "PIN");
                result1 = View("ActivateService", model);
            }

            userOrg.ConfirmAttemptDate = VirtualDateTime.Now;

            //Save the changes
            DataRepository.SaveChanges();

            //Log the registration
            auditLogger.AuditChangeToOrganisation(
                AuditedAction.RegistrationLog,
                userOrg.Organisation,
                new
            {
                Status        = "PIN Confirmed",
                Sector        = userOrg.Organisation.SectorType,
                Organisation  = userOrg.Organisation.OrganisationName,
                CompanyNo     = userOrg.Organisation.CompanyNumber,
                Address       = userOrg.Address.GetAddressString(),
                SicCodes      = userOrg.Organisation.GetSicCodeIdsString(),
                UserFirstname = userOrg.User.Firstname,
                UserLastname  = userOrg.User.Lastname,
                UserJobtitle  = userOrg.User.JobTitle,
                UserEmail     = userOrg.User.EmailAddress,
                userOrg.User.ContactFirstName,
                userOrg.User.ContactLastName,
                userOrg.User.ContactJobTitle,
                userOrg.User.ContactOrganisation,
                userOrg.User.ContactPhoneNumber
            },
                User);

            //Prompt the user with confirmation
            return(result1);
        }
Exemplo n.º 21
0
        public async Task <IActionResult> ActivateService(CompleteViewModel model)
        {
            //Ensure user has completed the registration process

            var checkResult = await CheckUserRegisteredOkAsync();

            if (checkResult != null)
            {
                return(checkResult);
            }

            //Ensure they have entered a PIN
            if (!ModelState.IsValid)
            {
                this.CleanModelErrors <CompleteViewModel>();
                return(View("ActivateService", model));
            }

            //Get the user organisation
            var userOrg = await SharedBusinessLogic.DataRepository.FirstOrDefaultAsync <UserOrganisation>(uo =>
                                                                                                          uo.UserId == VirtualUser.UserId && uo.OrganisationId == ReportingOrganisationId);

            ActionResult result1;

            var remaining = userOrg.ConfirmAttemptDate == null
                ? TimeSpan.Zero
                : userOrg.ConfirmAttemptDate.Value.AddMinutes(SharedBusinessLogic.SharedOptions.LockoutMinutes) -
                            VirtualDateTime.Now;

            if (userOrg.ConfirmAttempts >= SharedBusinessLogic.SharedOptions.MaxPinAttempts && remaining > TimeSpan.Zero
                )
            {
                return(View("CustomError",
                            WebService.ErrorViewModelFactory.Create(1113,
                                                                    new { remainingTime = remaining.ToFriendly(maxParts: 2) })));
            }

            var updateSearchIndex = false;

            if (PinMatchesPinInDatabase(userOrg, model.PIN))
            {
                //Set the user org as confirmed
                userOrg.PINConfirmedDate = VirtualDateTime.Now;

                //Set the pending organisation to active
                //Make sure the found organisation is active or pending

                if (userOrg.Organisation.Status.IsAny(OrganisationStatuses.Pending, OrganisationStatuses.Active))
                {
                    userOrg.Organisation.SetStatus(
                        OrganisationStatuses.Active,
                        OriginalUser == null ? VirtualUser.UserId : OriginalUser.UserId,
                        "PIN Confirmed");
                    updateSearchIndex = true;
                }
                else
                {
                    Logger.LogWarning(
                        $"Attempt to PIN activate a {userOrg.Organisation.Status} organisation",
                        $"Organisation: '{userOrg.Organisation.OrganisationName}' Reference: '{userOrg.Organisation.EmployerReference}' User: '******'");
                    return(View("CustomError", WebService.ErrorViewModelFactory.Create(1149)));
                }

                //Set the latest registration
                userOrg.Organisation.LatestRegistration = userOrg;

                //Retire the old address
                if (userOrg.Organisation.LatestAddress != null &&
                    userOrg.Organisation.LatestAddress.AddressId != userOrg.Address.AddressId)
                {
                    userOrg.Organisation.LatestAddress.SetStatus(
                        AddressStatuses.Retired,
                        OriginalUser == null ? VirtualUser.UserId : OriginalUser.UserId,
                        "Replaced by PIN in post");
                    updateSearchIndex = true;
                }

                //Activate the address the pin was sent to
                userOrg.Address.SetStatus(
                    AddressStatuses.Active,
                    OriginalUser == null ? VirtualUser.UserId : OriginalUser.UserId,
                    "PIN Confirmed");
                userOrg.Organisation.LatestAddress = userOrg.Address;
                userOrg.ConfirmAttempts            = 0;

                model.AccountingDate =
                    _registrationService.SharedBusinessLogic.GetAccountingStartDate(userOrg.Organisation.SectorType);
                model.OrganisationId = userOrg.OrganisationId;
                StashModel(model);

                result1 = RedirectToAction("ServiceActivated");

                //Send notification email to existing users
                _registrationService.SharedBusinessLogic.NotificationService.SendUserAddedEmailToExistingUsers(
                    userOrg.Organisation, userOrg.User);
            }
            else
            {
                userOrg.ConfirmAttempts++;
                AddModelError(3015, "PIN");
                result1 = View("ActivateService", model);
            }

            userOrg.ConfirmAttemptDate = VirtualDateTime.Now;

            //Save the changes
            await SharedBusinessLogic.DataRepository.SaveChangesAsync();

            //Log the registration
            if (!userOrg.User.EmailAddress.StartsWithI(SharedBusinessLogic.SharedOptions.TestPrefix))
            {
                await _registrationService.RegistrationLog.WriteAsync(
                    new RegisterLogModel
                {
                    StatusDate          = VirtualDateTime.Now,
                    Status              = "PIN Confirmed",
                    ActionBy            = VirtualUser.EmailAddress,
                    Details             = "",
                    Sector              = userOrg.Organisation.SectorType,
                    Organisation        = userOrg.Organisation.OrganisationName,
                    CompanyNo           = userOrg.Organisation.CompanyNumber,
                    Address             = userOrg?.Address.GetAddressString(),
                    SicCodes            = userOrg.Organisation.GetLatestSicCodeIdsString(),
                    UserFirstname       = userOrg.User.Firstname,
                    UserLastname        = userOrg.User.Lastname,
                    UserJobtitle        = userOrg.User.JobTitle,
                    UserEmail           = userOrg.User.EmailAddress,
                    ContactFirstName    = userOrg.User.ContactFirstName,
                    ContactLastName     = userOrg.User.ContactLastName,
                    ContactJobTitle     = userOrg.User.ContactJobTitle,
                    ContactOrganisation = userOrg.User.ContactOrganisation,
                    ContactPhoneNumber  = userOrg.User.ContactPhoneNumber
                });
            }

            //Add this organisation to the search index
            if (updateSearchIndex)
            {
                await _registrationService.SearchBusinessLogic.UpdateSearchIndexAsync(userOrg.Organisation);
            }

            //Prompt the user with confirmation
            return(result1);
        }
Exemplo n.º 22
0
 public CompleteView(CompleteViewModel viewModel)
 {
     InitializeComponent();
     this.viewModel = viewModel;
     DataContext    = this.viewModel;
 }
Exemplo n.º 23
0
        public async Task <IActionResult> ActivateService(string id)
        {
            //Ensure user has completed the registration process
            var checkResult = await CheckUserRegisteredOkAsync();

            if (checkResult != null)
            {
                return(checkResult);
            }

            // Decrypt org id
            if (!id.DecryptToId(out var organisationId))
            {
                return(new HttpBadRequestResult($"Cannot decrypt organisation id {id}"));
            }

            // Check the user has permission for this organisation
            var userOrg = VirtualUser.UserOrganisations.FirstOrDefault(uo => uo.OrganisationId == organisationId);

            if (userOrg == null)
            {
                return(new HttpForbiddenResult(
                           $"User {VirtualUser?.EmailAddress} is not registered for organisation id {organisationId}"));
            }

            // Ensure this organisation needs activation on the users account
            if (userOrg.PINConfirmedDate != null)
            {
                throw new Exception(
                          $"Attempt to activate organisation {userOrg.OrganisationId}:'{userOrg.Organisation.OrganisationName}' for {VirtualUser.EmailAddress} by '{(OriginalUser == null ? VirtualUser.EmailAddress : OriginalUser.EmailAddress)}' which has already been activated");
            }

            // begin ActivateService journey
            ReportingOrganisationId = organisationId;

            //Ensure they havent entered wrong pin too many times
            var remaining = userOrg.ConfirmAttemptDate == null
                ? TimeSpan.Zero
                : userOrg.ConfirmAttemptDate.Value.AddMinutes(SharedBusinessLogic.SharedOptions.LockoutMinutes) -
                            VirtualDateTime.Now;

            if (userOrg.ConfirmAttempts >= SharedBusinessLogic.SharedOptions.MaxPinAttempts && remaining > TimeSpan.Zero
                )
            {
                return(View("CustomError",
                            WebService.ErrorViewModelFactory.Create(1113,
                                                                    new { remainingTime = remaining.ToFriendly(maxParts: 2) })));
            }

            remaining = userOrg.PINSentDate == null
                ? TimeSpan.Zero
                : userOrg.PINSentDate.Value.AddDays(SharedBusinessLogic.SharedOptions.PinInPostMinRepostDays) -
                        VirtualDateTime.Now;
            var model = new CompleteViewModel();

            model.PIN         = null;
            model.AllowResend = remaining <= TimeSpan.Zero;
            model.Remaining   = remaining.ToFriendly(maxParts: 2);

            //If the email address is a test email then simulate sending
            if (userOrg.User.EmailAddress.StartsWithI(SharedBusinessLogic.SharedOptions.TestPrefix))
            {
                model.PIN = "ABCDEF";
            }

            //Show the PIN textbox and button
            return(View("ActivateService", model));
        }