Ejemplo n.º 1
0
        public async Task ArtifactsPublishedActionHelper_ReturnsFalse_WhenWorkflowStateIdDoesNotMatchConditionalStateId()
        {
            // non-matching State IDs
            const int conditionalStateId = 1 + WorkflowStateId;
            var       states             = new List <SqlWorkFlowStateInformation> {
                new SqlWorkFlowStateInformation {
                    WorkflowStateId = WorkflowStateId, ArtifactId = 0, EndRevision = 0, ItemId = 0, ItemTypeId = 0, LockedByUserId = 0, Name = "", ProjectId = 0, Result = 0, StartRevision = 0, WorkflowId = 0, WorkflowName = "", WorkflowStateName = ""
                }
            };
            var emailNotification =
                new EmailNotificationAction
            {
                ConditionalStateId = conditionalStateId,
                PropertyTypeId     = PropertyTypeId
            };

            emailNotification.Emails.Add("");
            var notificationActions = new List <EmailNotificationAction> {
                emailNotification
            };

            _repositoryMock.Setup(m => m.GetWorkflowPropertyTransitionsForArtifactsAsync(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <IEnumerable <int> >())).ReturnsAsync(_triggers);
            _repositoryMock.Setup(m => m.GetWorkflowStatesForArtifactsAsync(It.IsAny <int>(), It.IsAny <IEnumerable <int> >(), It.IsAny <int>(), It.IsAny <bool>())).ReturnsAsync(states);
            _repositoryMock.Setup(m => m.GetProjectNameByIdsAsync(It.IsAny <IEnumerable <int> >())).ReturnsAsync(_projects);
            _repositoryMock.Setup(m => m.GetInstancePropertyTypeIdsMap(It.IsAny <IEnumerable <int> >())).ReturnsAsync(_instancePropertyTypeIds);

            var actionsParserMock = new Mock <IActionsParser>();

            actionsParserMock.Setup(m => m.GetNotificationActions(It.IsAny <IEnumerable <SqlWorkflowEvent> >())).Returns(notificationActions);
            var actionHelper = new ArtifactsPublishedActionHelper(actionsParserMock.Object);

            var result = await actionHelper.HandleAction(_tenantInformation, _messageWithModifiedProperties, _repositoryMock.Object);

            Assert.IsFalse(result);
        }
Ejemplo n.º 2
0
        internal static async Task <List <string> > GetEmailValues(int revisionId, int artifactId,
                                                                   EmailNotificationAction notificationAction, IUsersRepository usersRepository)
        {
            var emails = new List <string>();

            if (notificationAction.PropertyTypeId.HasValue && notificationAction.PropertyTypeId.Value > 0)
            {
                var userInfos =
                    await usersRepository.GetUserInfoForWorkflowArtifactForAssociatedUserProperty
                        (artifactId,
                        notificationAction.PropertyTypeId.Value,
                        revisionId);

                // Make sure that email is provided
                emails.AddRange(from userInfo in userInfos
                                where !string.IsNullOrWhiteSpace(userInfo?.Email)
                                select userInfo.Email);
            }
            else
            {
                // Take email from list of provided emails
                emails.AddRange(notificationAction.Emails ?? new List <string>());
            }
            return(emails);
        }
Ejemplo n.º 3
0
        public async Task GetEmailValues_ReturnsEmails_WhenEmailNotificationActionHasPropertyTypeId()
        {
            // arrange
            const int numEmails = 7;
            var       emailNotificationAction = new EmailNotificationAction
            {
                PropertyTypeId = 123
            };
            var userInfos = new List <UserInfo>();

            for (int i = 0; i < numEmails; i++)
            {
                var userInfo = new UserInfo()
                {
                    Email = $"email{i}"
                };
                userInfos.Add(userInfo);
            }
            _mockUsersRepository.Setup(m => m.GetUserInfoForWorkflowArtifactForAssociatedUserProperty(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <IDbTransaction>())).ReturnsAsync(userInfos);

            // act
            var emails = await WorkflowEventsMessagesHelper.GetEmailValues(_revisionId, 456, emailNotificationAction, _mockUsersRepository.Object);

            // assert
            Assert.AreEqual(numEmails, emails.Count);
        }
Ejemplo n.º 4
0
        private EmailNotificationAction ToEmailNotificationAction(XmlEmailNotificationAction emailNotification)
        {
            var action = new EmailNotificationAction
            {
                PropertyTypeId = emailNotification.PropertyTypeId,
                Message        = emailNotification.Message
            };

            action.Emails.AddRange(emailNotification.Emails);
            return(action);
        }
Ejemplo n.º 5
0
        public List <EmailNotificationAction> GetNotificationActions(IEnumerable <SqlWorkflowEvent> sqlArtifactTriggers)
        {
            var notifications = new List <EmailNotificationAction>();

            foreach (var workflowEvent in sqlArtifactTriggers)
            {
                var triggersXml = workflowEvent.Triggers;
                var xmlWorkflowEventTriggers = new XmlWorkflowEventTriggers();
                if (!string.IsNullOrWhiteSpace(triggersXml))
                {
                    try
                    {
                        Log.Debug($"Deserializing triggers: {triggersXml}");
                        var triggersFromXml = SerializationHelper.FromXml <XmlWorkflowEventTriggers>(triggersXml);
                        if (triggersFromXml != null)
                        {
                            xmlWorkflowEventTriggers = triggersFromXml;
                        }
                        else
                        {
                            Log.Debug($"Invalid triggers XML: {triggersXml}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"Deserialization failed for triggers: {triggersXml}", ex);
                    }
                }
                var triggersWithEmailActions = xmlWorkflowEventTriggers.Triggers.Where(trigger => trigger.Action.ActionType == ActionTypes.EmailNotification);
                foreach (var trigger in triggersWithEmailActions)
                {
                    var action = (XmlEmailNotificationAction)trigger.Action;
                    XmlStateCondition condition = null;
                    if (trigger.Condition?.ConditionType == ConditionTypes.State)
                    {
                        condition = (XmlStateCondition)trigger.Condition;
                    }
                    var emailNotification = new EmailNotificationAction
                    {
                        ConditionalStateId  = condition?.StateId,
                        EventPropertyTypeId = workflowEvent.EventPropertyTypeId ?? 0,
                        PropertyTypeId      = action.PropertyTypeId,
                        Message             = action.Message
                    };
                    emailNotification.Emails.AddRange(action.Emails);
                    notifications.Add(emailNotification);
                }
            }
            return(notifications);
        }
Ejemplo n.º 6
0
        public async Task GetEmailValues_ReturnsEmails_WhenEmailNotificationActionContainsEmails()
        {
            // arrange
            const int numEmails = 5;
            var       emailNotificationAction = new EmailNotificationAction();

            for (int i = 0; i < numEmails; i++)
            {
                emailNotificationAction.Emails.Add($"email{i}");
            }

            // act
            var emails = await WorkflowEventsMessagesHelper.GetEmailValues(_revisionId, 123, emailNotificationAction, _mockUsersRepository.Object);

            // assert
            Assert.AreEqual(numEmails, emails.Count);
        }
Ejemplo n.º 7
0
        private static async Task <IWorkflowMessage> GetNotificationMessage(int userId,
                                                                            int revisionId,
                                                                            long transactionId,
                                                                            IBaseArtifactVersionControlInfo artifactInfo,
                                                                            string projectName,
                                                                            EmailNotificationAction notificationAction,
                                                                            string artifactUrl,
                                                                            string blueprintUrl,
                                                                            IUsersRepository usersRepository)
        {
            string messageHeader   = I18NHelper.FormatInvariant("You are being notified because artifact with Id: {0} has been created.", artifactInfo.Id);
            var    artifactPartUrl = artifactUrl ?? ServerUriHelper.GetArtifactUrl(artifactInfo.Id, true);

            if (artifactPartUrl == null)
            {
                return(null);
            }
            var baseUrl = blueprintUrl ?? ServerUriHelper.GetBaseHostUri()?.ToString();
            var emails  = await GetEmailValues(revisionId, artifactInfo.Id, notificationAction, usersRepository);

            var notificationMessage = new NotificationMessage
            {
                TransactionId          = transactionId,
                ArtifactName           = artifactInfo.Name,
                ProjectName            = projectName,
                Subject                = I18NHelper.FormatInvariant("Artifact {0} has been created.", artifactInfo.Id),
                From                   = notificationAction.FromDisplayName,
                To                     = emails,
                Message                = notificationAction.Message,
                RevisionId             = revisionId,
                UserId                 = userId,
                ArtifactTypeId         = artifactInfo.ItemTypeId,
                ArtifactId             = artifactInfo.Id,
                ArtifactUrl            = artifactPartUrl,
                ArtifactTypePredefined = (int)artifactInfo.PredefinedType,
                ProjectId              = artifactInfo.ProjectId,
                Header                 = messageHeader,
                BlueprintUrl           = baseUrl
            };

            return(notificationMessage);
        }
Ejemplo n.º 8
0
        public async Task ArtifactsPublishedActionHelper_ReturnsFalse_WhenPropertyTypeIdDoesNotMatchNotificationPropertyTypeId()
        {
            // non-matching PropertyChange Type IDs
            const int notificationPropertyTypeId = 1 + PropertyTypeId;
            var       emailNotification          = new EmailNotificationAction
            {
                ConditionalStateId = WorkflowStateId,
                PropertyTypeId     = notificationPropertyTypeId
            };

            emailNotification.Emails.Add("");
            var notificationActions = new List <EmailNotificationAction>
            {
                emailNotification
            };
            var message = new ArtifactsPublishedMessage {
                Artifacts = new[] { new PublishedArtifactInformation {
                                        ModifiedProperties = new List <PublishedPropertyInformation> {
                                            new PublishedPropertyInformation {
                                                TypeId = PropertyTypeId
                                            }
                                        }
                                    } }
            };

            _repositoryMock.Setup(m => m.GetWorkflowPropertyTransitionsForArtifactsAsync(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <IEnumerable <int> >())).ReturnsAsync(_triggers);
            _repositoryMock.Setup(m => m.GetWorkflowStatesForArtifactsAsync(It.IsAny <int>(), It.IsAny <IEnumerable <int> >(), It.IsAny <int>(), It.IsAny <bool>())).ReturnsAsync(_states);
            _repositoryMock.Setup(m => m.GetProjectNameByIdsAsync(It.IsAny <IEnumerable <int> >())).ReturnsAsync(_projects);
            _repositoryMock.Setup(m => m.GetInstancePropertyTypeIdsMap(It.IsAny <IEnumerable <int> >())).ReturnsAsync(_instancePropertyTypeIds);
            var actionsParserMock = new Mock <IActionsParser>();

            actionsParserMock.Setup(m => m.GetNotificationActions(It.IsAny <IEnumerable <SqlWorkflowEvent> >())).Returns(notificationActions);
            var actionHelper = new ArtifactsPublishedActionHelper(actionsParserMock.Object);

            var result = await actionHelper.HandleAction(_tenantInformation, message, _repositoryMock.Object);

            Assert.IsFalse(result);
        }
        public static bool NotifyAllOnActionOfBaseArticle(string categoryStr, BaseArticle baseArticle, EmailNotificationAction action, List <Object> parameters = null)
        {
            if (action == EmailNotificationAction.UNKNOWN)
            {
                return(false);
            }

            var      categoryID = baseArticle.categoryID;
            Category category   = null;

            if (baseArticle.categoryID == null || baseArticle.categoryID <= 0)
            {
                category = InfrastructureCategoryDbContext.getInstance().findCategoryByID(categoryID);
            }



            // get createdBy
            Account owner = AccountDbContext.getInstance().findAccountByID(SessionPersister.account.AccountID);



            // analyze category for interested accounts (by account group)
            List <AccountGroup> accountGroups         = AccountGroupDbContext.getInstance().findGroups();
            List <AccountGroup> filteredAccountGroups = new List <AccountGroup>();

            foreach (var group in accountGroups)
            {
                List <int> categoryIDs = group.getAccessibleCategoryListInt();
                if (category != null && categoryIDs.Contains(category.ItemID))
                {
                    filteredAccountGroups.Add(group);
                }
            }


            List <Account> accounts = AccountDbContext.getInstance().findAccountsByAccountGroupsToEmailNotify(filteredAccountGroups, baseArticle);

            // filter...
            List <Account> filteredAccounts = new List <Account>();

            if (action == EmailNotificationAction.CREATE ||
                action == EmailNotificationAction.EDIT ||
                action == EmailNotificationAction.EDITPROPERTIES ||
                action == EmailNotificationAction.CREATENEWVERSION)
            {
                foreach (var acc in accounts)
                {
                    if (acc.isRoleSuperadmin() || acc.isRoleEditor())
                    {
                        filteredAccounts.Add(acc);
                    }
                }
            }
            if (action == EmailNotificationAction.DELETE)
            {
                foreach (var acc in accounts)
                {
                    if (acc.isRoleSuperadmin() || acc.isRoleEditor())
                    {
                        filteredAccounts.Add(acc);
                    }
                }
            }

            if (action == EmailNotificationAction.SUBMITFORAPPROVAL)
            {
                foreach (var acc in accounts)
                {
                    if (acc.isRoleSuperadmin() || acc.isRoleEditor() || acc.isRoleApprover())
                    {
                        filteredAccounts.Add(acc);
                    }
                }
            }

            if (action == EmailNotificationAction.APPROVE ||
                action == EmailNotificationAction.UNAPPROVE)
            {
                foreach (var acc in accounts)
                {
                    if (acc.isRoleSuperadmin() || acc.isRoleEditor() || acc.isRoleApprover() || acc.isRolePublisher())
                    {
                        filteredAccounts.Add(acc);
                    }
                }
            }

            if (action == EmailNotificationAction.PUBLISH ||
                action == EmailNotificationAction.UNPUBLISH)
            {
                foreach (var acc in accounts)
                {
                    if (acc.isRoleSuperadmin() || acc.isRoleEditor() || acc.isRoleApprover() || acc.isRolePublisher())
                    {
                        filteredAccounts.Add(acc);
                    }
                }
            }

            foreach (var acc in filteredAccounts)
            {
                // send to owner?
                if (owner != null && owner.AccountID == acc.AccountID &&
                    owner.ShouldEmailNotifyBaseArticleChangesByOwn())
                {
                    SendEmail(categoryStr, owner, acc, baseArticle, category, action);
                    continue;
                }

                // send to all?
                if (acc.ShouldEmailNotifyBaseArticleChanges())
                {
                    SendEmail(categoryStr, owner, acc, baseArticle, category, action);
                    continue;
                }
            }

            return(true);
        }
        public static void SendEmail(string categoryStr, Account owner, Account account, BaseArticle baseArticle, Category category, EmailNotificationAction action)
        {
            var dict    = MakeNotificationInfo(categoryStr, owner, account, baseArticle, category, action);
            var body    = dict["body"];
            var subject = dict["subject"];

            Thread email = new Thread(delegate()
            {
                EmailHelper.SendEmail(
                    new List <string> {
                    account.Email
                },
                    body,
                    subject
                    );
            });

            email.IsBackground = true;
            email.Start();
        }
        public static System.Collections.Generic.Dictionary <string, string> MakeNotificationInfo(string categoryStr, Account owner, Account account, BaseArticle baseArticle, Category category, EmailNotificationAction action)
        {
            Dictionary <string, string> dict = new Dictionary <string, string>();

            var item_cat      = "Item";
            var item_url      = "";
            var articleID     = baseArticle.ArticleID;
            var baseArticleID = baseArticle.BaseArticleID;
            var name          = baseArticle.Name;

            if (categoryStr.Equals("Article"))
            {
                item_cat = "Article";
                if (account.isRolePublisher())
                {
                    item_url = "/ArticlePublisher/DetailsLocale?baseArticleID=" + baseArticle.BaseArticleID + "&version=" + baseArticle.Version + "&lang=" + baseArticle.Lang;
                }
                else if (account.isRoleApprover())
                {
                    item_url = "/ArticleApprover/DetailsLocale?baseArticleID=" + baseArticle.BaseArticleID + "&version=" + baseArticle.Version + "&lang=" + baseArticle.Lang;
                }
                else if (account.isRoleEditor())
                {
                    item_url = "/ArticleEditor/DetailsLocale?baseArticleID=" + baseArticle.BaseArticleID + "&version=" + baseArticle.Version + "&lang=" + baseArticle.Lang;
                }
            }
            else if (categoryStr.Equals("Content Page"))
            {
                item_cat = "Content Page";
                item_url = "/ContentPageEditor/DetailsLocale?baseArticleID=" + baseArticle.BaseArticleID + "&version=" + baseArticle.Version + "&lang=" + baseArticle.Lang;
            }

            item_url = ServerHelper.GetSiteRoot() + item_url;

            var item_action_tag         = "";
            var item_action_description = "";

            switch (action)
            {
            case EmailNotificationAction.CREATE:
                item_action_tag         = "Created";
                item_action_description = "{0} {1} has been created by {2}.";
                break;

            case EmailNotificationAction.EDIT:
                item_action_tag         = "Edited";
                item_action_description = "{0} {1}'s contents has been edited by {2}.";
                break;

            case EmailNotificationAction.EDITPROPERTIES:
                item_action_tag         = "Properties Edited";
                item_action_description = "{0} {1}'s properties has been edited by {2}.";
                break;

            case EmailNotificationAction.DELETE:
                item_action_tag         = "Deleted";
                item_action_description = "{0} {1} has been deleted by {2}.";
                break;

            case EmailNotificationAction.CREATENEWVERSION:
                item_action_tag         = "Created New Version";
                item_action_description = "A new version of {0} {1} has been created by {2}.";
                break;

            case EmailNotificationAction.SUBMITFORAPPROVAL:
                item_action_tag         = "Submitted for Approval";
                item_action_description = "{0} {1} has been submitted for approval by {2}.";
                break;

            case EmailNotificationAction.APPROVE:
                item_action_tag         = "Approved";
                item_action_description = "{0} {1} has been approved by {2}.";
                break;

            case EmailNotificationAction.UNAPPROVE:
                item_action_tag         = "Unapproved";
                item_action_description = "{0} {1} has been unapproved by {2}.";
                break;

            case EmailNotificationAction.PUBLISH:
                item_action_tag         = "Published";
                item_action_description = "{0} {1} has been published by {2}.";
                break;

            case EmailNotificationAction.UNPUBLISH:
                item_action_tag         = "Unpublished";
                item_action_description = "{0} {1} has been unpublished by {2}.";
                break;

            default:
                break;
            }

            var item_subject = String.Format("[GSL - {0} {1}] ({2}) {3}",
                                             item_cat,
                                             baseArticleID,
                                             item_action_tag,
                                             name
                                             );


            var item_action_description_impl = string.Format(
                item_action_description,
                item_cat,
                baseArticleID,
                owner.Username
                );


            var item_body = string.Format(
                "Dear {0} {1}, <br/><br/>" +
                "<p>{2}</p>" +
                "<p><a href='{3}'>{4}</a></p>" +
                "<hr />" +
                "<p>Geminis CMS Team</p>",
                account.Firstname,
                account.Lastname,
                item_action_description_impl,
                item_url,
                item_subject
                );

            dict.Add("subject", item_subject);
            dict.Add("body", item_body);

            return(dict);
        }
        private static async Task <IWorkflowMessage> GetNotificationMessage(int userId,
                                                                            int revisionId,
                                                                            long transactionId,
                                                                            IBaseArtifactVersionControlInfo artifactInfo,
                                                                            string projectName,
                                                                            EmailNotificationAction notificationAction,
                                                                            string artifactUrl,
                                                                            string blueprintUrl,
                                                                            IUsersRepository usersRepository,
                                                                            IDbTransaction transaction)
        {
            string messageHeader   = I18NHelper.FormatInvariant("You are being notified because of an update to the artifact with Id: {0}.", artifactInfo.Id);
            var    artifactPartUrl = artifactUrl ?? ServerUriHelper.GetArtifactUrl(artifactInfo.Id, true);

            if (artifactPartUrl == null)
            {
                return(null);
            }
            var baseUrl = blueprintUrl ?? ServerUriHelper.GetBaseHostUri()?.ToString();
            var emails  = new List <string>();

            if (notificationAction.PropertyTypeId.HasValue && notificationAction.PropertyTypeId.Value > 0)
            {
                var userInfos =
                    await usersRepository.GetUserInfoForWorkflowArtifactForAssociatedUserProperty
                        (artifactInfo.Id,
                        notificationAction.PropertyTypeId.Value,
                        revisionId,
                        transaction);

                // Make sure that email is provided
                emails.AddRange(from userInfo in userInfos where !string.IsNullOrWhiteSpace(userInfo?.Email) select userInfo.Email);
            }
            else
            {
                // Take email from list of provided emails
                emails.AddRange(notificationAction.Emails ?? new List <string>());
            }

            var notificationMessage = new NotificationMessage
            {
                TransactionId          = transactionId,
                ArtifactName           = artifactInfo.Name,
                ProjectName            = projectName,
                Subject                = I18NHelper.FormatInvariant("Artifact {0} has been updated.", artifactInfo.Id),
                From                   = notificationAction.FromDisplayName,
                To                     = emails,
                Message                = notificationAction.Message,
                RevisionId             = revisionId,
                UserId                 = userId,
                ArtifactTypeId         = artifactInfo.ItemTypeId,
                ArtifactId             = artifactInfo.Id,
                ArtifactUrl            = artifactPartUrl,
                ArtifactTypePredefined = (int)artifactInfo.PredefinedType,
                ProjectId              = artifactInfo.ProjectId,
                Header                 = messageHeader,
                BlueprintUrl           = baseUrl
            };

            return(notificationMessage);
        }
Ejemplo n.º 13
0
        public void TestInitialize()
        {
            _repositoryMock    = new Mock <IArtifactsPublishedRepository>();
            _tenantInformation = new TenantInformation
            {
                BlueprintConnectionString = "",
                TenantId = ""
            };
            _triggers = new List <SqlWorkflowEvent>
            {
                new SqlWorkflowEvent
                {
                    CurrentStateId          = 0,
                    VersionItemId           = 0,
                    EventPropertyTypeId     = 0,
                    EventType               = 0,
                    HolderId                = 0,
                    RequiredNewStateId      = 0,
                    RequiredPreviousStateId = 0,
                    Triggers                = "",
                    WorkflowId              = 0
                },
                new SqlWorkflowEvent
                {
                    CurrentStateId          = 1,
                    VersionItemId           = 0,
                    EventPropertyTypeId     = 0,
                    EventType               = 0,
                    HolderId                = 0,
                    RequiredNewStateId      = 0,
                    RequiredPreviousStateId = 0,
                    Triggers                = "",
                    WorkflowId              = 0
                }
            };
            _states = new List <SqlWorkFlowStateInformation>
            {
                new SqlWorkFlowStateInformation
                {
                    WorkflowStateId   = WorkflowStateId,
                    ArtifactId        = 0,
                    EndRevision       = 0,
                    ItemId            = 0,
                    ItemTypeId        = 0,
                    LockedByUserId    = 0,
                    Name              = "",
                    ProjectId         = 0,
                    Result            = 0,
                    StartRevision     = 0,
                    WorkflowId        = 0,
                    WorkflowName      = "",
                    WorkflowStateName = ""
                }
            };
            _projects = new List <SqlProject>
            {
                new SqlProject
                {
                    ItemId = 0,
                    Name   = ""
                }
            };
            _instancePropertyTypeIds = new Dictionary <int, List <int> > {
                { 0, new List <int> {
                      0
                  } }
            };
            var emailNotification = new EmailNotificationAction
            {
                ConditionalStateId = WorkflowStateId,
                PropertyTypeId     = PropertyTypeId
            };

            emailNotification.Emails.Add("");
            _notificationActions = new List <EmailNotificationAction> {
                emailNotification
            };

            _messageWithModifiedProperties = new ArtifactsPublishedMessage
            {
                Artifacts = new[]
                {
                    new PublishedArtifactInformation
                    {
                        ModifiedProperties = new List <PublishedPropertyInformation>
                        {
                            new PublishedPropertyInformation
                            {
                                TypeId = PropertyTypeId
                            }
                        }
                    }
                }
            };
        }