コード例 #1
0
        public IActionResult ManualConfirmPost(AddOrganisationManualViewModel viewModel)
        {
            ControllerHelper.ThrowIfUserAccountRetiredOrEmailNotVerified(User, dataRepository);

            ValidateManuallyEnteredOrganisationDetails(viewModel);

            if (viewModel.HasAnyErrors())
            {
                return(RedirectToAction("ManualConfirmGet", "AddOrganisationManualConfirm", viewModel));
            }

            User user = ControllerHelper.GetGpgUserFromAspNetUser(User, dataRepository);

            Organisation organisation = organisationService.CreateOrganisationFromManualDataEntry(
                viewModel.GetSectorType(),
                viewModel.OrganisationName,
                viewModel.PoBox,
                viewModel.Address1,
                viewModel.Address2,
                viewModel.Address3,
                viewModel.TownCity,
                viewModel.County,
                viewModel.Country,
                viewModel.PostCode,
                viewModel.GetIsUkAddressAsBoolean(),
                null, // TODO ASK USER FOR COMPANY NUMBER
                viewModel.SicCodes,
                user);

            UserOrganisation userOrganisation = registrationRepository.CreateRegistration(organisation, user, Url);

            return(RedirectToConfirmationPage(userOrganisation));
        }
        public void RemoveRegistration(UserOrganisation userOrgToUnregister, User actionByUser)
        {
            if (userOrgToUnregister is null)
            {
                throw new ArgumentNullException(nameof(userOrgToUnregister));
            }

            if (actionByUser is null)
            {
                throw new ArgumentNullException(nameof(actionByUser));
            }

            Organisation sourceOrg = userOrgToUnregister.Organisation;

            // Remove the user registration from the organisation
            sourceOrg.UserOrganisations.Remove(userOrgToUnregister);

            // We extract these two variables BEFORE deleting the UserOrganisations to prevent an Entity Framework error:
            // "Attempted to update or delete an entity that does not exist in the store."
            Organisation organisationToLog = userOrgToUnregister.Organisation;
            string       status            = (userOrgToUnregister.UserId == actionByUser.UserId) ? "Unregistered self" : "Unregistered";

            // Remove user organisation
            dataRepository.Delete(userOrgToUnregister);

            // Save changes to database
            dataRepository.SaveChanges();

            auditLogger.AuditChangeToOrganisation(
                AuditedAction.RegistrationLog,
                organisationToLog,
                new { Status = status },
                userOrgToUnregister.User);
        }
 private void ValidateUserOrganisationForRemoval(UserOrganisation userOrg)
 {
     if (userOrg == null)
     {
         throw new ArgumentException("There is no association between user and organisation.");
     }
 }
        public IActionResult SendPinWarning(long userId, long organisationId)
        {
            UserOrganisation userOrganisation = dataRepository.GetAll <UserOrganisation>()
                                                .FirstOrDefault(uo => uo.UserId == userId && uo.OrganisationId == organisationId);

            return(View("../Admin/SendPinWarning", userOrganisation));
        }
コード例 #5
0
        public static User GetRegisteredUserAlreadyLinkedToAnOrganisation(UserOrganisation userOrganisation)
        {
            User user = GetNotAdminUserWithVerifiedEmailAddress();

            user.UserOrganisations = new[] { userOrganisation };
            return(user);
        }
コード例 #6
0
        public static void ThrowIfUserDoesNotHavePermissionsForGivenOrganisation(ClaimsPrincipal aspDotNetUser, IDataRepository dataRepository, long organisationId)
        {
            User gpgUser = GetGpgUserFromAspNetUser(aspDotNetUser, dataRepository);

            Organisation     dbOrg   = dataRepository.Get <Organisation>(organisationId);
            UserOrganisation userOrg = gpgUser.UserOrganisations.FirstOrDefault(uo => uo.OrganisationId == organisationId);

            // If there's no organisation with the ID provided
            if (dbOrg == null)
            {
                throw new PageNotFoundException();
            }

            // If the organisation isn't active
            if (dbOrg.Status != OrganisationStatuses.Active)
            {
                throw new UserNotRegisteredToReportForOrganisationException();
            }

            // If the UserOrganisation doesn't exist
            if (userOrg == null)
            {
                throw new UserNotRegisteredToReportForOrganisationException();
            }

            // If organisation exists, but isn't active
            if (!userOrg.PINConfirmedDate.HasValue)
            {
                throw new UserNotRegisteredToReportForOrganisationException();
            }
        }
 private static void DecideRegistrationMethod(UserOrganisation userOrganisation)
 {
     if (userOrganisation.Organisation.Status == OrganisationStatuses.Pending)
     {
         // Organisations will have the "Pending" status if they have been added via manual data entry (and thus should be manually reviewed)
         // (Organisations will be "Active" if they already exist in our database, or if they are imported from CoHo)
         userOrganisation.Method = RegistrationMethods.Manual;
     }
     else if (userOrganisation.Organisation.SectorType == SectorTypes.Public)
     {
         userOrganisation.Method = RegistrationMethods.Manual;
     }
     else if (FeatureFlagHelper.IsFeatureEnabled(FeatureFlag.PrivateManualRegistration))
     {
         userOrganisation.Method = RegistrationMethods.Manual;
     }
     else if (userOrganisation.Organisation.GetLatestAddress()?.IsUkAddress != true)
     {
         userOrganisation.Method = RegistrationMethods.Manual;
     }
     else
     {
         userOrganisation.Method = RegistrationMethods.PinInPost;
     }
 }
コード例 #8
0
        public async Task <List <ReportInfoModel> > GetAllEditableReportsAsync(UserOrganisation userOrg,
                                                                               DateTime currentSnapshotDate)
        {
            var currentYear = currentSnapshotDate.Year;
            var startYear   = currentYear - (SubmissionOptions.EditableReportCount - 1);

            if (startYear < _sharedBusinessLogic.SharedOptions.FirstReportingYear)
            {
                startYear = _sharedBusinessLogic.SharedOptions.FirstReportingYear;
            }

            var reportInfos = new List <ReportInfoModel>();

            for (var snapshotYear = startYear; snapshotYear <= currentYear; snapshotYear++)
            {
                var report = await GetReturnFromDatabaseAsync(userOrg.OrganisationId, snapshotYear);

                var reportInfo = report != null
                    ? await GetReportInfoModelWithLockedDraftAsync(report.Organisation, report.Modified, snapshotYear)
                    : await GetReportInfoModelWithLockedDraftAsync(userOrg.Organisation, null, snapshotYear);

                reportInfos.Add(reportInfo);
            }

            return(reportInfos);
        }
コード例 #9
0
        public async Task DraftFile_GetDraftFile_Returns_A_Valid_DraftAsync()
        {
            // Arrange
            User         mockedUser         = UserHelper.GetNotAdminUserWithVerifiedEmailAddress();
            Organisation mockedOrganisation = OrganisationHelper.GetPublicOrganisation();

            mockedOrganisation.OrganisationId = new Random().Next(1000, 9999);
            UserOrganisation mockedUserOrganisation = UserOrganisationHelper.LinkUserWithOrganisation(mockedUser, mockedOrganisation);
            Return           mockedReturn           = ReturnHelper.GetSubmittedReturnForOrganisationAndYear(mockedUserOrganisation, ConfigHelpers.SharedOptions.FirstReportingYear);

            OrganisationHelper.LinkOrganisationAndReturn(mockedOrganisation, mockedReturn);

            var testDraftFileBL       = new DraftFileBusinessLogic(null, new SystemFileRepository(new StorageOptions()));
            var sharedBusinessLogic   = UiTestHelper.DIContainer.Resolve <ISharedBusinessLogic>();
            var testSubmissionService = new SubmissionService(sharedBusinessLogic, Mock.Of <ISubmissionBusinessLogic>(), Mock.Of <IScopeBusinessLogic>(), testDraftFileBL);
            var testPresenter         = new SubmissionPresenter(testSubmissionService, ConfigHelpers.SubmissionOptions, null);

            // Act
            Draft actualDraft = await testPresenter.GetDraftFileAsync(
                mockedOrganisation.OrganisationId,
                mockedOrganisation.SectorType.GetAccountingStartDate().Year,
                mockedUser.UserId);

            // Assert
            Assert.NotNull(actualDraft);
            Assert.True(actualDraft.IsUserAllowedAccess);
            Assert.AreEqual(mockedUser.UserId, actualDraft.LastWrittenByUserId);

            // Clean up
            await testDraftFileBL.DiscardDraftAsync(actualDraft);
        }
コード例 #10
0
        private IActionResult RedirectToConfirmationPage(UserOrganisation userOrganisation)
        {
            string confirmationId          = $"{userOrganisation.UserId}:{userOrganisation.OrganisationId}";
            string encryptedConfirmationId = Encryption.EncryptQuerystring(confirmationId);

            return(RedirectToAction("Confirmation", "AddOrganisationConfirmation", new { confirmationId = encryptedConfirmationId }));
        }
コード例 #11
0
        public async Task ReportCountIsControlledBySubmissionOptions(SectorTypes testSector, int testEditableReportCount)
        {
            // Arrange
            var testConfig = new SubmissionOptions {
                EditableReportCount = testEditableReportCount
            };
            var testOrg = new Organisation {
                OrganisationId = 1, SectorType = testSector
            };
            var testUserOrg = new UserOrganisation {
                Organisation = testOrg
            };
            DateTime testSnapshotDate = mockSharedBusinessLogic.GetAccountingStartDate(testOrg.SectorType);

            var mockService = new Mock <SubmissionPresenter>(
                mockDataRepo.Object,
                mockScopeBL.Object,
                null,
                mockDraftFileBL.Object,
                MoqHelpers.CreateIOptionsSnapshotMock(testConfig));

            // Call the real functions unless overridden
            mockService.CallBase = true;

            // Act
            SubmissionPresenter    testService   = mockService.Object;
            List <ReportInfoModel> actualResults = await testService.GetAllEditableReportsAsync(testUserOrg, testSnapshotDate);

            // Assert
            Assert.AreEqual(
                testEditableReportCount,
                actualResults.Count,
                $"Expected editable report count to be {testEditableReportCount}");
        }
コード例 #12
0
        private async Task LogAsync(UserOrganisation logUserOrg, string status, string actionByEmailAddress)
        {
            var logOrg     = logUserOrg.Organisation;
            var logUser    = logUserOrg.User;
            var logAddress = logUserOrg.Address;

            if (logUser.EmailAddress.StartsWithI(SharedOptions.TestPrefix))
            {
                return;
            }

            await WriteAsync(
                new RegisterLogModel
            {
                StatusDate          = VirtualDateTime.Now,
                Status              = status,
                ActionBy            = actionByEmailAddress,
                Details             = "",
                Sector              = logOrg.SectorType,
                Organisation        = logOrg.OrganisationName,
                CompanyNo           = logOrg.CompanyNumber,
                Address             = logAddress.GetAddressString(),
                SicCodes            = logOrg.GetLatestSicCodeIdsString(),
                UserFirstname       = logUser.Firstname,
                UserLastname        = logUser.Lastname,
                UserJobtitle        = logUser.JobTitle,
                UserEmail           = logUser.EmailAddress,
                ContactFirstName    = logUser.ContactFirstName,
                ContactLastName     = logUser.ContactLastName,
                ContactJobTitle     = logUser.ContactJobTitle,
                ContactOrganisation = logUser.ContactOrganisation,
                ContactPhoneNumber  = logUser.ContactPhoneNumber
            });
        }
コード例 #13
0
        public async Task AdminUnconfirmedPinsController_POST_When_PIN_has_expired_create_new_PIN_and_send_email()
        {
            // Arrange

            // This PIN format is intentionally different for testing purposes to make sure
            // it doesn't clash with the new PIN that is generated
            var expiredPIN = "1111";

            var organisationId = 100;

            Core.Entities.Organisation organisation = createOrganisation(organisationId, "Company1", 12345678);
            User             user             = CreateUser(1, "*****@*****.**");
            UserOrganisation userOrganisation = CreateUserOrganisation(organisation, user.UserId, VirtualDateTime.Now);

            userOrganisation.PIN         = expiredPIN;
            userOrganisation.PINSentDate = VirtualDateTime.Now.AddYears(-1);

            User govEqualitiesOfficeUser = UserHelper.GetGovEqualitiesOfficeUser();

            govEqualitiesOfficeUser.EmailVerifiedDate = VirtualDateTime.Now;

            var routeData = new RouteData();

            routeData.Values.Add("Action", "SendPin");
            routeData.Values.Add("Controller", "AdminUnconfirmedPinsController");

            var controller = UiTestHelper.GetController <AdminUnconfirmedPinsController>(
                govEqualitiesOfficeUser.UserId,
                routeData,
                organisation,
                user,
                userOrganisation,
                govEqualitiesOfficeUser);

            var mockNotifyEmailQueue = new Mock <IQueue>();

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

            // Act
            await controller.SendPin(user.UserId, organisationId);

            // Assert
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(user.EmailAddress))),
                Times.Once(),
                "Expected the user's email address to be in the email send queue");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.TemplateId.Contains(EmailTemplates.SendPinEmail))),
                Times.Once,
                $"Expected the correct templateId to be in the email send queue, expected {EmailTemplates.SendPinEmail}");

            // Check that a new PIN has been created
            Assert.That(userOrganisation.PIN, Is.Not.EqualTo(expiredPIN));
            Assert.NotNull(userOrganisation.PIN);

            // Check that the PINSentDate has been updated
            Assert.That(userOrganisation.PINSentDate.Value.Date, Is.EqualTo(VirtualDateTime.Now.Date));
        }
コード例 #14
0
        public IActionResult Confirmation(string confirmationId)
        {
            ControllerHelper.ThrowIfUserAccountRetiredOrEmailNotVerified(User, dataRepository);

            UserOrganisation userOrganisation = LoadUserOrganisationWithConfirmationId(confirmationId);

            return(View("Confirmation", userOrganisation));
        }
        public async Task AdminController_ManualChanges_POST_Fix_Database_Error_Missing_Latest_Return_Works_When_Run_In_Test_Mode_Async()
        {
            // Arrange
            User notAdminUser    = UserHelper.GetDatabaseAdmin();
            var  adminController = UiTestHelper.GetController <AdminController>(notAdminUser.UserId, null, null);

            #region Set up organisation missing the latest return link so it's picked up by the test

            Core.Entities.Organisation organisation_MissingLatestReturn     = OrganisationHelper.GetPrivateOrganisation("EmployerReference985");
            UserOrganisation           userOrganisation_MissingLatestReturn =
                UserOrganisationHelper.LinkUserWithOrganisation(notAdminUser, organisation_MissingLatestReturn);
            Return return_MissingLatestReturn = ReturnHelper.GetSubmittedReturnForOrganisationAndYear(
                userOrganisation_MissingLatestReturn,
                VirtualDateTime.Now.AddYears(-1).Year);
            organisation_MissingLatestReturn.Returns.Add(return_MissingLatestReturn); // latest return indeed exists for this organisation
            organisation_MissingLatestReturn.LatestRegistration = userOrganisation_MissingLatestReturn;
            organisation_MissingLatestReturn.LatestReturn       = null;               // missing latest return -link-

            #endregion

            Mock <IDataRepository> configurableDataRepository = AutoFacExtensions.ResolveAsMock <IDataRepository>();

            configurableDataRepository
            .Setup(x => x.Get <User>(It.IsAny <long>()))
            .Returns(notAdminUser);

            configurableDataRepository
            .Setup(x => x.GetAll <Core.Entities.Organisation>())
            .Returns(new[] { organisation_MissingLatestReturn }.AsQueryable());

            var manualChangesViewModel = new ManualChangesViewModel {
                Command = FixDatabaseErrorsCommand
            };

            // Act
            IActionResult manualChangesResult = await adminController.ManualChanges(manualChangesViewModel);

            // Assert
            Assert.NotNull(manualChangesResult, "Expected a Result");

            var manualChangesViewResult = manualChangesResult as ViewResult;
            Assert.NotNull(manualChangesViewResult, "Expected ViewResult");

            var actualManualChangesViewModel = manualChangesViewResult.Model as ManualChangesViewModel;
            Assert.NotNull(actualManualChangesViewModel, "Expected ManualChangesViewModel");

            Assert.Multiple(
                () => {
                Assert.AreEqual("SUCCESSFULLY TESTED 'Fix database errors': 1 items", actualManualChangesViewModel.SuccessMessage);
                Assert.AreEqual(
                    "No organisations missing a latest registration\r\n001: Organisation 'EmployerReference985:Org123' missing a latest return will be fixed\r\nNo organisations missing a latest scope\r\n",
                    actualManualChangesViewModel.Results);
                Assert.AreEqual("Fix database errors", actualManualChangesViewModel.LastTestedCommand);
                Assert.IsNull(actualManualChangesViewModel.LastTestedInput);
                Assert.True(actualManualChangesViewModel.Tested, "Must be tested=true as this case is running in TEST mode");
                Assert.IsNull(actualManualChangesViewModel.Comment);
            });
        }
コード例 #16
0
        public async Task RegistrationController_VerifyEmail_GET_Success()
        {
            //ARRANGE:
            //1.Arrange the test setup variables
            var user = new User {
                UserId = 1, EmailAddress = "*****@*****.**", EmailVerifiedDate = null
            };

            var organisation = new Core.Entities.Organisation {
                OrganisationId = 1
            };
            var userOrganisation = new UserOrganisation {
                OrganisationId   = organisation.OrganisationId,
                Organisation     = organisation,
                UserId           = 1,
                PINConfirmedDate = VirtualDateTime.Now,
                PIN = "0"
            };

            //Set user email address verified code and expired sent date
            var routeData = new RouteData();

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

            //ARRANGE:
            //1.Arrange the test setup variables
            var model = new VerifyViewModel();

            model.EmailAddress = "*****@*****.**";
            model.Resend       = false;

            //Set model as if email

            // model.Sent = true;
            model.UserId = 1;

            // model.WrongCode = false;

            //var controller = UiTestHelper.GetController<RegistrationController>();
            var controller = UiTestHelper.GetController <RegistrationController>(1, routeData, user /*, userOrganisation*/);

            controller.Bind(model);

            //ACT:
            //2.Run and get the result of the test

            var result = await controller.VerifyEmail(model) as ViewResult;

            //ASSERT:
            Assert.NotNull(result, "Expected ViewResult");
            Assert.That(result.GetType() == typeof(ViewResult), "Incorrect resultType returned");
            Assert.That(result.ViewName == "VerifyEmail", "Incorrect view returned,Verification is incomplete");
            Assert.That(
                result.Model != null && result.Model.GetType() == typeof(VerifyViewModel),
                "Expected VerifyViewModel or Incorrect resultType returned");
            Assert.That(result.ViewData.ModelState.IsValid, "Model is Invalid");
        }
コード例 #17
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);
        }
コード例 #18
0
        public static Return GetSubmittedReturnForOrganisationAndYear(UserOrganisation userOrganisation, int snapshotYear)
        {
            Return result = GetSubmittedReturnWithAllDataPoints(userOrganisation.User);

            result.Organisation   = userOrganisation.Organisation;
            result.OrganisationId = userOrganisation.Organisation.OrganisationId;
            result.AccountingDate = userOrganisation.Organisation.SectorType.GetAccountingStartDate(snapshotYear);
            return(result);
        }
        public void RegisterController_ReviewRequest_POST_ManualRegistration_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 userOrg = new UserOrganisation {
                UserId         = 1,
                OrganisationId = 1,
                AddressId      = address.AddressId,
                Address        = address,
                User           = user,
                Organisation   = org
            };

            var routeData = new RouteData();

            routeData.Values.Add("Action", "OrganisationType");
            routeData.Values.Add("Controller", "Register");

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

            var model = new OrganisationViewModel {
                ReviewCode = userOrg.GetReviewCode()
            };

            controller.StashModel(model);

            //ACT:
            var result = controller.ReviewRequest(model, "approve") as RedirectToActionResult;

            //ASSERT:
            Assert.That(result != null, "Expected RedirectToActionResult");
            Assert.That(result.ActionName == "RequestAccepted", "Expected redirect to RequestAccepted");
            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);
        }
コード例 #20
0
        /// <summary>
        ///     Creates a new Empty Return
        /// </summary>
        /// <param name="userOrganisation"></param>
        /// <param name="snapshotYear"></param>
        public static Return GetNewReturnForOrganisationAndYear(UserOrganisation userOrganisation, int snapshotYear)
        {
            var newReturn = new Return();

            newReturn.Organisation   = userOrganisation.Organisation;
            newReturn.OrganisationId = userOrganisation.OrganisationId;
            newReturn.AccountingDate = userOrganisation.Organisation.SectorType.GetAccountingStartDate(snapshotYear);

            return(newReturn);
        }
コード例 #21
0
        public async Task AdminUnconfirmedPinsController_POST_When_PIN_is_still_valid_send_email()
        {
            // Arrange

            var organisationId = 100;
            var pin            = "6A519E7";

            Core.Entities.Organisation organisation = createOrganisation(organisationId, "Company1", 12345678);
            User             user             = CreateUser(1, "*****@*****.**");
            UserOrganisation userOrganisation = CreateUserOrganisation(organisation, user.UserId, VirtualDateTime.Now);

            userOrganisation.PIN         = pin;
            userOrganisation.PINSentDate = VirtualDateTime.Now.AddDays(-1);

            User govEqualitiesOfficeUser = UserHelper.GetGovEqualitiesOfficeUser();

            govEqualitiesOfficeUser.EmailVerifiedDate = VirtualDateTime.Now;

            var routeData = new RouteData();

            routeData.Values.Add("Action", "SendPin");
            routeData.Values.Add("Controller", "AdminUnconfirmedPinsController");

            var controller = UiTestHelper.GetController <AdminUnconfirmedPinsController>(
                govEqualitiesOfficeUser.UserId,
                routeData,
                organisation,
                user,
                userOrganisation,
                govEqualitiesOfficeUser);

            var mockNotifyEmailQueue = new Mock <IQueue>();

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

            // Act
            await controller.SendPin(user.UserId, organisationId);

            // Assert
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(user.EmailAddress))),
                Times.Once(),
                "Expected the user's email address to be in the email send queue");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.TemplateId.Contains(EmailTemplates.SendPinEmail))),
                Times.Once,
                $"Expected the correct templateId to be in the email send queue, expected {EmailTemplates.SendPinEmail}");

            // Check that the same PIN has been used
            Assert.That(userOrganisation.PIN, Is.EqualTo(pin));

            // Check that the PINSentDate has been updated
            Assert.That(userOrganisation.PINSentDate.Value.Date, Is.EqualTo(VirtualDateTime.Now.Date));
        }
コード例 #22
0
        public OrganisationDomain AssociateUserWithOrganisation(int userId, int organisationId)
        {
            OrganisationDomain response = null;

            try
            {
                // check organisation actually exists before creating association in database
                var orgEntity = Context.Organisations.FirstOrDefault(o => o.Id == organisationId);

                if (orgEntity == null)
                {
                    throw new UseCaseException()
                          {
                              UserErrorMessage = $"The supplied organisation ID '{organisationId}' was not found",
                              DevErrorMessage  = $"The [organisations] table does not contain an organisation with ID = {organisationId}"
                          };
                }

                var userOrg = Context.UserOrganisations.FirstOrDefault(u => u.UserId == userId);

                // check if an association already exists and modify this one if it does
                if (userOrg != null)
                {
                    userOrg.OrganisationId = organisationId;
                    Context.UserOrganisations.Update(userOrg);
                }
                else
                {
                    // create new organisation <-> user association
                    userOrg = new UserOrganisation()
                    {
                        CreatedAt      = DateTime.UtcNow,
                        UserId         = userId,
                        OrganisationId = organisationId
                    };
                    Context.UserOrganisations.Add(userOrg);
                }

                Context.SaveChanges();
                response = _mapper.ToDomain(orgEntity);
            }
            catch (DbUpdateException e)
            {
                HandleDbUpdateException(e);
            }
            catch (Exception e)
            {
                LoggingHandler.LogError(e.Message);
                LoggingHandler.LogError(e.StackTrace);
                throw;
            }

            return(response);
        }
コード例 #23
0
        public IActionResult DeclareScope(string id)
        {
            //Ensure user has completed the registration process
            IActionResult checkResult = CheckUserRegisteredOk(out User currentUser);

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

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

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

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

            // Ensure this user is registered fully for this organisation
            if (userOrg.PINConfirmedDate == null)
            {
                return(new HttpForbiddenResult(
                           $"User {currentUser?.EmailAddress} has not completed registration for employer {userOrg.Organisation.EmployerReference}"));
            }

            //Get the current snapshot date
            DateTime snapshotDate = userOrg.Organisation.SectorType.GetAccountingStartDate().AddYears(-1);

            if (snapshotDate.Year < Global.FirstReportingYear)
            {
                return(new HttpBadRequestResult($"Snapshot year {snapshotDate.Year} is invalid"));
            }

            ScopeStatuses scopeStatus =
                ScopeBusinessLogic.GetLatestScopeStatusForSnapshotYear(organisationId, snapshotDate.Year);

            if (scopeStatus.IsAny(ScopeStatuses.InScope, ScopeStatuses.OutOfScope))
            {
                return(new HttpBadRequestResult("Explicit scope is already set"));
            }

            // build the view model
            var model = new DeclareScopeModel {
                OrganisationId = userOrg.OrganisationId, OrganisationName = userOrg.Organisation.OrganisationName, SnapshotDate = snapshotDate
            };

            return(View(model));
        }
コード例 #24
0
        public static bool SendPinInPost(this RegisterController controller, UserOrganisation userOrg, string pin, DateTime sendDate, bool test = false)
        {
            var returnUrl = controller.Url.Action("ActivateService", "Register", null, "https");

            var imagePath = new System.UriBuilder(controller.Request.Url.AbsoluteUri)
            {
                Path = controller.Url.Content(@"~/Content/img/")
            }.Uri.ToString();

            return(GovNotifyAPI.SendPinInPost(imagePath, returnUrl, userOrg.User.Fullname, userOrg.User.JobTitle, userOrg.Organisation.OrganisationName, userOrg.Address.GetList(), pin, sendDate, sendDate.AddDays(Properties.Settings.Default.PinInPostExpiryDays), test));
        }
コード例 #25
0
        public static Return GetSubmittedReturnForOrganisationAndYear(UserOrganisation userOrganisation,
                                                                      int snapshotYear,
                                                                      bool optedOutOfReportingPayQuarters = false)
        {
            Return result = GetSubmittedReturnWithAllDataPoints(userOrganisation.User);

            result.Organisation   = userOrganisation.Organisation;
            result.OrganisationId = userOrganisation.Organisation.OrganisationId;
            result.AccountingDate = userOrganisation.Organisation.SectorType.GetAccountingStartDate(snapshotYear);
            result.OptedOutOfReportingPayQuarters = optedOutOfReportingPayQuarters;
            return(result);
        }
        public void RemoveOrganisation_POST_When_Removal_Complete_Which_Creates_Orphan_Organisation_Then_Email_GEO()
        {
            // Arrange

            User             user             = CreateUser(1, "*****@*****.**");
            Organisation     organisation     = createPrivateOrganisation(100, "Company1", 12345678);
            UserOrganisation userOrganisation = CreateUserOrganisation(organisation, user.UserId, VirtualDateTime.Now);

            var routeData = new RouteData();

            routeData.Values.Add("Action", "RemoveOrganisation");
            routeData.Values.Add("Controller", "Organisation");

            var testModel = new RemoveOrganisationModel
            {
                EncOrganisationId = Encryption.EncryptQuerystring(organisation.OrganisationId.ToString()),
                EncUserId         = Encryption.EncryptQuerystring(user.UserId.ToString())
            };

            var controller = UiTestHelper.GetController <OrganisationController>(
                user.UserId,
                routeData,
                user,
                organisation,
                userOrganisation);

            organisation.OrganisationScopes.Add(new OrganisationScope
            {
                Status       = ScopeRowStatuses.Active,
                ScopeStatus  = ScopeStatuses.InScope,
                SnapshotDate = SectorTypes.Private.GetAccountingStartDate()
            });

            UiTestHelper.MockBackgroundJobsApi
            .Setup(q => q.AddEmailToQueue(It.IsAny <NotifyEmail>()));

            // Act
            var result = controller.RemoveOrganisation(testModel) as RedirectToActionResult;

            // Assert
            UiTestHelper.MockBackgroundJobsApi.Verify(
                x => x.AddEmailToQueue(It.Is <NotifyEmail>(inst => inst.EmailAddress.Contains(user.EmailAddress))),
                Times.Once(),
                "Expected the current user's email address to be in the email send queue");
            UiTestHelper.MockBackgroundJobsApi.Verify(
                x => x.AddEmailToQueue(
                    It.Is <NotifyEmail>(inst => inst.TemplateId.Contains(EmailTemplates.RemovedUserFromOrganisationEmail))),
                Times.Exactly(1),
                $"Expected the correct templateId to be in the email send queue, expected {EmailTemplates.RemovedUserFromOrganisationEmail}");

            Assert.NotNull(result, "redirectResult should not be null");
            Assert.AreEqual("RemoveOrganisationCompleted", result.ActionName, "Expected the ViewName to be 'RemoveOrganisationCompleted'");
        }
        public void BeforeEach()
        {
            organisation     = CreateOrganisation();
            user             = CreateUser();
            userOrganisation = CreateUserOrganisation(organisation, user.UserId);
            validReturn      = CreateReturn(organisation.OrganisationId);

            govEqualitiesOfficeUser = UserHelper.GetGovEqualitiesOfficeUser();
            govEqualitiesOfficeUser.EmailVerifiedDate = VirtualDateTime.Now;

            routeData = new RouteData();
        }
コード例 #28
0
        public void WhenOnManageOrganisationPage_IfHasSubmittedBeforeTheDeadline_ThenReportStatusSubmitted()
        {
            UserOrganisation userOrg = UserOrganisationHelper.LinkUserWithOrganisation(user, organisationInScope);
            Return           ret     = ReturnHelper.GetSubmittedReturnForOrganisationAndYear(userOrg, ReportingYear);

            OrganisationHelper.LinkOrganisationAndReturn(organisationInScope, ret);

            var viewModel = new ManageOrganisationDetailsForYearViewModel(organisationInScope, ReportingYear, null);

            string reportTagText = viewModel.GetReportTagText();

            Assert.AreEqual("Report submitted", reportTagText);
        }
コード例 #29
0
        private IActionResult FoundPostWithCompanyNumber(AddOrganisationFoundViewModel viewModel)
        {
            // IsUkAddress can be set by a hidden input (in which case it will be bound automatically)
            // Or it can be set by a GovUk_Radio button (in which case we need to use ParseAndValidate to get the value)
            // So, if the value hasn't already been bound, ParseAndValidate it
            if (!viewModel.IsUkAddress.HasValue)
            {
                viewModel.ParseAndValidateParameters(Request, m => m.IsUkAddress);
            }

            // If IsUkAddress still doesn't has a value on, then show an error
            if (!viewModel.IsUkAddress.HasValue)
            {
                PopulateViewModelBasedOnCompanyNumber(viewModel);
                return(View("Found", viewModel));
            }

            Organisation existingOrganisation = dataRepository.GetAll <Organisation>()
                                                .Where(o => o.CompanyNumber == viewModel.CompanyNumber)
                                                .Where(o => o.Status == OrganisationStatuses.Active) // Only redirect the user to an Active organisation (i.e. don't do this for Retired or Deleted organisations)
                                                .FirstOrDefault();

            // We expect an ID for organisations that are in our database
            // We expect a Company Number for organisations that are not in our database (but are in the Companies House API)
            // If we've been given a Company Number, but the organisation IS in our database,
            //   then redirect to this same page, but using the correct ID
            if (existingOrganisation != null)
            {
                return(RedirectToAction(
                           "FoundGet",
                           "AddOrganisationFound",
                           new
                {
                    id = existingOrganisation.GetEncryptedId(),
                    query = viewModel.Query,
                    sector = viewModel.Sector
                }));
            }

            User user = ControllerHelper.GetGpgUserFromAspNetUser(User, dataRepository);

            Organisation organisation = organisationService.ImportOrganisationFromCompaniesHouse(viewModel.CompanyNumber, user);

            organisationService.UpdateIsUkAddressIfItIsNotAlreadySet(organisation.OrganisationId, viewModel.GetIsUkAddressAsBoolean());

            UserOrganisation userOrganisation = registrationRepository.CreateRegistration(organisation, user, Url);

            return(RedirectToConfirmationPage(userOrganisation));
        }
コード例 #30
0
        private AddOrganisationAlreadyRegisteringViewModel CreateAlreadyRegisteringViewModel(
            AddOrganisationFoundViewModel foundViewModel,
            UserOrganisation existingUserOrganisation)
        {
            var alreadyRegisteringViewModel = new AddOrganisationAlreadyRegisteringViewModel
            {
                Id    = foundViewModel.Id,
                Query = foundViewModel.Query
            };

            // UserOrganisation
            alreadyRegisteringViewModel.ExistingUserOrganisation = existingUserOrganisation;

            return(alreadyRegisteringViewModel);
        }