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'");
        }
Пример #2
0
        public async Task RemoveOrganisation_POST_When_User_Org_Removed_Then_Sends_User_Email()
        {
            // Arrange
            User user1 = CreateUser(1, "*****@*****.**");
            User user2 = CreateUser(2, "*****@*****.**");

            Core.Entities.Organisation organisation      = createPrivateOrganisation(100, "Company1", 12345678);
            UserOrganisation           userOrganisation1 = CreateUserOrganisation(organisation, user1.UserId, VirtualDateTime.Now);
            UserOrganisation           userOrganisation2 = CreateUserOrganisation(organisation, user2.UserId, VirtualDateTime.Now);

            var routeData = new RouteData();

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

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

            var controller = UiTestHelper.GetController <ManageOrganisationsController>(
                user1.UserId,
                routeData,
                user1,
                user2,
                organisation,
                userOrganisation1,
                userOrganisation2);

            organisation.LatestScope = new OrganisationScope {
                ScopeStatus = ScopeStatuses.InScope
            };

            var mockNotifyEmailQueue = new Mock <IQueue>();

            var mockEmailQueue = new Mock <IQueue>();

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

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

            // Assert$
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(user1.EmailAddress))),
                Times.Once(),
                "Expected the current user's email address to be in the email send queue");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(
                    It.Is <SendEmailRequest>(inst => inst.TemplateId.Contains(EmailTemplates.RemovedUserFromOrganisationEmail))),
                Times.Exactly(2),
                $"Expected the correct templateId to be in the email send queue, expected {EmailTemplates.RemovedUserFromOrganisationEmail}");
            mockNotifyEmailQueue.Verify(
                x => x.AddMessageAsync(It.Is <SendEmailRequest>(inst => inst.EmailAddress.Contains(user2.EmailAddress))),
                Times.Once(),
                "Expected the other user of the same organisation's email address to be in the email send queue");

            mockEmailQueue.Verify(
                x => x.AddMessageAsync(
                    It.Is <QueueWrapper>(
                        inst => inst.Message.Contains(ConfigHelpers.EmailOptions.GEODistributionList) &&
                        inst.Type == typeof(OrphanOrganisationTemplate).FullName)),
                Times.Never,
                $"Didnt expect the GEO Email addresses using {nameof(OrphanOrganisationTemplate)} to be in the email send queue");

            Assert.NotNull(result, "redirectResult should not be null");
            Assert.AreEqual("RemoveOrganisationCompleted", result.ActionName, "Expected the ViewName to be 'RemoveOrganisationCompleted'");
        }
Пример #3
0
        public IActionResult RemoveOrganisation(RemoveOrganisationModel model)
        {
            // Ensure user has completed the registration process
            IActionResult checkResult = CheckUserRegisteredOk(out User currentUser);

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

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

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

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

            // Decrypt user id
            if (!model.EncUserId.DecryptToId(out long userIdToRemove))
            {
                return(new HttpBadRequestResult($"Cannot decrypt user id '{model.EncUserId}'"));
            }

            Organisation sourceOrg        = userOrgToUnregister.Organisation;
            User         userToUnregister = currentUser;

            if (currentUser.UserId != userIdToRemove)
            {
                // Ensure the other user has registered this organisation
                UserOrganisation otherUserOrg =
                    sourceOrg.UserOrganisations.FirstOrDefault(uo => uo.OrganisationId == organisationId && uo.UserId == userIdToRemove);
                if (otherUserOrg == null)
                {
                    return(new HttpForbiddenResult($"User {userIdToRemove} is not registered for employer id {organisationId}"));
                }

                userToUnregister    = otherUserOrg.User;
                userOrgToUnregister = otherUserOrg;
            }

            // Remove the registration
            User         actionByUser = IsImpersonatingUser == false ? currentUser : OriginalUser;
            Organisation orgToRemove  = userOrgToUnregister.Organisation;

            RegistrationRepository.RemoveRegistration(userOrgToUnregister, actionByUser);

            // Email user that has been unregistered
            emailSendingService.SendRemovedUserFromOrganisationEmail(
                userToUnregister.EmailAddress,
                orgToRemove.OrganisationName,
                userToUnregister.Fullname);

            // Email the other users of the organisation
            IEnumerable <string> emailAddressesForOrganisation = orgToRemove.UserOrganisations.Select(uo => uo.User.EmailAddress);

            foreach (string emailAddress in emailAddressesForOrganisation)
            {
                emailSendingService.SendRemovedUserFromOrganisationEmail(
                    emailAddress,
                    orgToRemove.OrganisationName,
                    userToUnregister.Fullname);
            }

            // Send the notification to GEO for each newly orphaned organisation
            if (orgToRemove.GetIsOrphan())
            {
                emailSendingService.SendGeoOrphanOrganisationEmail(orgToRemove.OrganisationName);
            }

            //Make sure this organisation is no longer selected
            if (ReportingOrganisationId == organisationId)
            {
                ReportingOrganisationId = 0;
            }

            this.StashModel(model);

            return(RedirectToAction("RemoveOrganisationCompleted"));
        }
Пример #4
0
        public IActionResult RemoveOrganisation(string orgId, string userId)
        {
            //Ensure user has completed the registration process
            IActionResult checkResult = CheckUserRegisteredOk(out User currentUser);

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

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

            // Check the current user has remove 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}"));
            }

            // Decrypt user id
            if (!userId.DecryptToId(out long userIdToRemove))
            {
                return(new HttpBadRequestResult($"Cannot decrypt user id {userId}"));
            }

            User userToRemove = currentUser;

            if (currentUser.UserId != userIdToRemove)
            {
                // Check the other user has permission to see this organisation
                UserOrganisation otherUserOrg =
                    userOrg.Organisation.UserOrganisations.FirstOrDefault(
                        uo => uo.OrganisationId == organisationId && uo.UserId == userIdToRemove);
                if (otherUserOrg == null)
                {
                    return(new HttpForbiddenResult($"User {userIdToRemove} is not registered for employer id {organisationId}"));
                }

                userToRemove = otherUserOrg.User;
            }

            //Make sure they are fully registered for one before requesting another
            if (userOrg.IsAwaitingActivationPIN())
            {
                TimeSpan remainingTime = userOrg.PINSentDate.Value.AddMinutes(Global.LockoutMinutes) - VirtualDateTime.Now;
                if (remainingTime > TimeSpan.Zero)
                {
                    return(View("CustomError", new ErrorViewModel(3023, new { remainingTime = remainingTime.ToFriendly(maxParts: 2) })));
                }
            }

            // build the view model
            var model = new RemoveOrganisationModel
            {
                EncOrganisationId   = orgId,
                EncUserId           = userId,
                OrganisationName    = userOrg.Organisation.OrganisationName,
                OrganisationAddress = userOrg.Organisation.GetLatestAddress().GetAddressLines(),
                UserName            = userToRemove.Fullname
            };

            //Return the confirmation page
            return(View("ConfirmRemove", model));
        }
        public async Task <IActionResult> RemoveOrganisation(RemoveOrganisationModel model)
        {
            // Ensure user has completed the registration process
            var checkResult = await CheckUserRegisteredOkAsync();

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

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

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

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

            // Decrypt user id
            if (!model.EncUserId.DecryptToId(out var userIdToRemove))
            {
                return(new HttpBadRequestResult($"Cannot decrypt user id '{model.EncUserId}'"));
            }

            var sourceOrg        = userOrgToUnregister.Organisation;
            var userToUnregister = VirtualUser;

            if (VirtualUser.UserId != userIdToRemove)
            {
                // Ensure the other user has registered this organisation
                var otherUserOrg =
                    sourceOrg.UserOrganisations.FirstOrDefault(uo =>
                                                               uo.OrganisationId == organisationId && uo.UserId == userIdToRemove);
                if (otherUserOrg == null)
                {
                    return(new HttpForbiddenResult(
                               $"User {userIdToRemove} is not registered for organisation id {organisationId}"));
                }

                userToUnregister    = otherUserOrg.User;
                userOrgToUnregister = otherUserOrg;
            }

            // Remove the registration
            var actionByUser = IsImpersonatingUser == false ? VirtualUser : OriginalUser;
            var orgToRemove  = userOrgToUnregister.Organisation;
            await _registrationService.RegistrationBusinessLogic.RemoveRegistrationAsync(userOrgToUnregister,
                                                                                         actionByUser);

            // Email user that has been unregistered
            SharedBusinessLogic.NotificationService.SendRemovedUserFromOrganisationEmail(
                userToUnregister.EmailAddress,
                orgToRemove.OrganisationName,
                userToUnregister.Fullname);

            // Email the other users of the organisation
            var emailAddressesForOrganisation = orgToRemove.UserOrganisations.Select(uo => uo.User.EmailAddress);

            foreach (var emailAddress in emailAddressesForOrganisation)
            {
                SharedBusinessLogic.NotificationService.SendRemovedUserFromOrganisationEmail(
                    emailAddress,
                    orgToRemove.OrganisationName,
                    userToUnregister.Fullname);
            }

            // Send the notification to GEO for each newly orphaned organisation
            if (!userToUnregister.EmailAddress.StartsWithI(SharedBusinessLogic.SharedOptions.TestPrefix))
            {
                var sendEmails = new List <Task>();
                var testEmail  = !SharedBusinessLogic.SharedOptions.IsProduction();
                if (_registrationService.OrganisationBusinessLogic.GetOrganisationIsOrphan(orgToRemove))
                {
                    sendEmails.Add(
                        SharedBusinessLogic.SendEmailService.SendGEOOrphanOrganisationNotificationAsync(
                            orgToRemove.OrganisationName, testEmail));
                }

                await Task.WhenAll(sendEmails);
            }

            //Make sure this organisation is no longer selected
            if (ReportingOrganisationId == organisationId)
            {
                ReportingOrganisationId = 0;
            }

            StashModel(model);

            return(RedirectToAction("RemoveOrganisationCompleted"));
        }
        public async Task <IActionResult> RemoveOrganisation(string orgId, string userId)
        {
            //Ensure user has completed the registration process
            var checkResult = await CheckUserRegisteredOkAsync();

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

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

            // Check the current user has remove 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}"));
            }

            // Decrypt user id
            if (!userId.DecryptToId(out var userIdToRemove))
            {
                return(new HttpBadRequestResult($"Cannot decrypt user id {userId}"));
            }

            var userToRemove = VirtualUser;

            if (VirtualUser.UserId != userIdToRemove)
            {
                // Check the other user has permission to see this organisation
                var otherUserOrg =
                    userOrg.Organisation.UserOrganisations.FirstOrDefault(
                        uo => uo.OrganisationId == organisationId && uo.UserId == userIdToRemove);
                if (otherUserOrg == null)
                {
                    return(new HttpForbiddenResult(
                               $"User {userIdToRemove} is not registered for organisation id {organisationId}"));
                }

                userToRemove = otherUserOrg.User;
            }

            //Make sure they are fully registered for one before requesting another
            if (userOrg.PINConfirmedDate == null && userOrg.PINSentDate != null)
            {
                var remainingTime =
                    userOrg.PINSentDate.Value.AddMinutes(SharedBusinessLogic.SharedOptions.LockoutMinutes) -
                    VirtualDateTime.Now;
                if (remainingTime > TimeSpan.Zero)
                {
                    return(View("CustomError",
                                WebService.ErrorViewModelFactory.Create(3023,
                                                                        new { remainingTime = remainingTime.ToFriendly(maxParts: 2) })));
                }
            }

            // build the view model
            var model = new RemoveOrganisationModel
            {
                EncOrganisationId   = orgId,
                EncUserId           = userId,
                OrganisationName    = userOrg.Organisation.OrganisationName,
                OrganisationAddress = userOrg.Organisation.LatestAddress.GetAddressString(),
                UserName            = userToRemove.Fullname
            };

            //Return the confirmation page
            return(View("ConfirmRemove", model));
        }