Beispiel #1
0
 protected WorkflowImport()
 {
     rockContext                 = new RockContext();
     arenaContext                = new ArenaDataContext();
     workflowService             = new WorkflowService(rockContext);
     workflowActivityService     = new WorkflowActivityService(rockContext);
     workflowActivityTypeService = new WorkflowActivityTypeService(rockContext);
     workflowActionService       = new WorkflowActionService(rockContext);
     definedValueService         = new DefinedValueService(rockContext);
     personAliasService          = new PersonAliasService(rockContext);
 }
        private List <WorkflowAction> GetActiveForms(RockContext rockContext)
        {
            var formActions = RockPage.GetSharedItem("ActiveForms") as List <WorkflowAction>;

            if (formActions == null)
            {
                formActions = new WorkflowActionService(rockContext).GetActiveForms(CurrentPerson);
                RockPage.SaveSharedItem("ActiveForms", formActions);
            }

            return(formActions);
        }
Beispiel #3
0
        private List <WorkflowAction> GetActiveForms(RockContext rockContext)
        {
            var formActions = RockPage.GetSharedItem("ActiveForms") as List <WorkflowAction>;

            if (formActions == null)
            {
                formActions = new WorkflowActionService(rockContext).GetActiveForms(CurrentPerson);
                RockPage.SaveSharedItem("ActiveForms", formActions);
            }

            // find first form for each activity
            var firstForms = new List <WorkflowAction>();

            foreach (var activityId in formActions.Select(a => a.ActivityId).Distinct().ToList())
            {
                firstForms.Add(formActions.First(a => a.ActivityId == activityId));
            }

            return(firstForms);
        }
Beispiel #4
0
        private int GetNotificationCount()
        {
            var lastChecked = GetUserPreference("LastViewedDashboard").AsDateTime();

            if (!lastChecked.HasValue)
            {
                lastChecked = RockDateTime.Now.AddMonths(-3);
            }
            RockContext rockContext = new RockContext();

            //Any workflow assigned to the person where we have active forms.
            var workflowCount = new WorkflowActionService(rockContext).GetActiveForms(CurrentPerson).Where(a => a.CreatedDateTime > lastChecked.Value).DistinctBy(a => a.Activity.WorkflowId).Count();

            //Connections - If a new connecion was made, a connection was just transfered, or a future followup just came up
            DateTime midnightToday      = RockDateTime.Today.AddDays(1);
            var      connectionRequests = new ConnectionRequestService(rockContext).Queryable()
                                          .Where(r => r.ConnectorPersonAlias != null && r.ConnectorPersonAlias.PersonId == CurrentPersonId)
                                          .Where(r => (r.ConnectionState == ConnectionState.Active && (r.CreatedDateTime > lastChecked.Value || r.ConnectionRequestActivities.Where(a => a.CreatedDateTime > lastChecked.Value && a.ConnectionActivityType.Name == "Transferred").Any())) ||
                                                 (r.ConnectionState == ConnectionState.FutureFollowUp && r.FollowupDate.HasValue && r.FollowupDate.Value < midnightToday) && r.FollowupDate.Value > lastChecked.Value)
                                          .Count();

            return(workflowCount + connectionRequests);
        }
Beispiel #5
0
        /// <summary>
        /// Updates the email status.
        /// </summary>
        /// <param name="actionGuid">The action unique identifier.</param>
        /// <param name="status">The status.</param>
        /// <param name="emailEventType">Type of the email event.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="ProcessWorkflow">if set to <c>true</c> [process workflow].</param>
        public static void UpdateEmailStatus(Guid actionGuid, string status, string emailEventType, RockContext rockContext, bool ProcessWorkflow)
        {
            var action = new WorkflowActionService(rockContext).Get(actionGuid);

            if (action != null && action.Activity != null)
            {
                string attrKey = action.ActionTypeCache.Guid.ToString() + "_EmailStatus";

                action.Activity.LoadAttributes(rockContext);
                string currentStatus = action.Activity.GetAttributeValue(attrKey);

                // Sometimes Clicked events are reported before opens. If this is the case, do not update the status from clicked to opened.
                bool updateStatus = true;
                if (status == OPENED_STATUS && currentStatus == CLICKED_STATUS)
                {
                    updateStatus = false;
                }

                if (!string.IsNullOrWhiteSpace(emailEventType) && (emailEventType != status || !updateStatus))
                {
                    action.AddLogEntry(string.Format("Email Event Type: {0}", emailEventType), true);
                }

                if (updateStatus)
                {
                    action.Activity.SetAttributeValue(attrKey, status);
                    action.Activity.SaveAttributeValues(rockContext);
                    action.AddLogEntry(string.Format("Email Status Updated to '{0}'", status), true);
                }

                Guid?activityGuid = null;
                switch (status)
                {
                case OPENED_STATUS:
                {
                    activityGuid = GetActionAttributeValue(action, "OnOpenActivity").AsGuid();
                    break;
                }

                case CLICKED_STATUS:
                {
                    activityGuid = GetActionAttributeValue(action, "OnClickedActivity").AsGuid();
                    break;
                }

                case FAILED_STATUS:
                {
                    activityGuid = GetActionAttributeValue(action, "OnFailedActivity").AsGuid();
                    break;
                }
                }

                if (activityGuid.HasValue)
                {
                    var workflow     = action.Activity.Workflow;
                    var activityType = WorkflowActivityTypeCache.Get(activityGuid.Value);
                    if (workflow != null && activityType != null)
                    {
                        WorkflowActivity.Activate(activityType, workflow);
                        action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));

                        if (ProcessWorkflow)
                        {
                            List <string> workflowErrors;
                            new WorkflowService(rockContext).Process(workflow, out workflowErrors);
                        }
                    }
                }
            }
        }
Beispiel #6
0
        private void GetData()
        {
            var rockContext = new RockContext();

            int personId = CurrentPerson != null ? CurrentPerson.Id : 0;

            // Get all of the workflow types
            var allWorkflowTypes = new WorkflowTypeService(rockContext).Queryable("ActivityTypes")
                                   .OrderBy(w => w.Name)
                                   .ToList();

            // Get the authorized activities in all workflow types
            var authorizedActivityTypes = AuthorizedActivityTypes(allWorkflowTypes);

            // Get the workflow types that contain authorized activity types
            var workflowTypeIds = allWorkflowTypes
                                  .Where(w => w.ActivityTypes.Any(a => authorizedActivityTypes.Contains(a.Id)))
                                  .Select(w => w.Id)
                                  .Distinct()
                                  .ToList();

            // Create variable for storing authorized types and the count of active form actions
            var workflowTypeCounts = new Dictionary <int, int>();

            List <Workflow> workflows = null;

            if (RoleFilter.HasValue && RoleFilter.Value)
            {
                workflows = new WorkflowService(rockContext).Queryable()
                            .Where(w =>
                                   w.ActivatedDateTime.HasValue &&
                                   !w.CompletedDateTime.HasValue &&
                                   w.InitiatorPersonAlias.PersonId == personId)
                            .ToList();

                workflowTypeIds.ForEach(id =>
                                        workflowTypeCounts.Add(id, workflows.Where(w => w.WorkflowTypeId == id).Count()));
            }
            else
            {
                // Get all the active forms for any of the authorized activities
                var activeForms = new WorkflowActionService(rockContext).Queryable("ActionType.ActivityType.WorkflowType, Activity.Workflow")
                                  .Where(a =>
                                         a.ActionType.WorkflowFormId.HasValue &&
                                         !a.CompletedDateTime.HasValue &&
                                         a.Activity.ActivatedDateTime.HasValue &&
                                         !a.Activity.CompletedDateTime.HasValue &&
                                         a.Activity.Workflow.ActivatedDateTime.HasValue &&
                                         !a.Activity.Workflow.CompletedDateTime.HasValue &&
                                         authorizedActivityTypes.Contains(a.ActionType.ActivityTypeId) &&
                                         (
                                             (a.Activity.AssignedPersonAlias != null && a.Activity.AssignedPersonAlias.PersonId == personId) ||
                                             (a.Activity.AssignedGroup != null && a.Activity.AssignedGroup.Members.Any(m => m.PersonId == personId))
                                         )
                                         )
                                  .ToList();

                // Get any workflow types that have authorized activites and get the form count
                workflowTypeIds.ForEach(w =>
                                        workflowTypeCounts.Add(w, activeForms.Where(a => a.Activity.Workflow.WorkflowTypeId == w).Count()));

                workflows = activeForms
                            .Select(a => a.Activity.Workflow)
                            .Distinct()
                            .ToList();
            }

            var displayedTypes = new List <WorkflowType>();

            foreach (var workflowType in allWorkflowTypes.Where(w => workflowTypeCounts.Keys.Contains(w.Id)))
            {
                if (workflowTypeCounts[workflowType.Id] > 0)
                {
                    // Always show any types that have active assignments assigned to user
                    displayedTypes.Add(workflowType);
                }
                else
                {
                    // If there are not any active assigned activities, and not filtering by active, then also
                    // show any types that user is authorized to edit
                    if ((!StatusFilter.HasValue || !StatusFilter.Value) &&
                        workflowType.IsAuthorized(Authorization.EDIT, CurrentPerson))
                    {
                        displayedTypes.Add(workflowType);
                    }
                }
            }

            // Create a query to return workflow type, the count of active action forms, and the selected class
            var qry = displayedTypes
                      .Select(w => new
            {
                WorkflowType = w,
                Count        = workflowTypeCounts[w.Id],
                Class        = (SelectedWorkflowTypeId.HasValue && SelectedWorkflowTypeId.Value == w.Id) ? "active" : ""
            });

            rptWorkflowTypes.DataSource = qry.ToList();
            rptWorkflowTypes.DataBind();

            WorkflowType selectedWorkflowType = null;

            if (SelectedWorkflowTypeId.HasValue)
            {
                selectedWorkflowType = allWorkflowTypes
                                       .Where(w => w.Id == SelectedWorkflowTypeId.Value)
                                       .FirstOrDefault();

                AddAttributeColumns(selectedWorkflowType);
            }

            if (selectedWorkflowType != null && workflowTypeCounts.Keys.Contains(selectedWorkflowType.Id))
            {
                gWorkflows.DataSource = workflows.Where(w => w.WorkflowTypeId == selectedWorkflowType.Id).ToList();
                gWorkflows.DataBind();
                gWorkflows.Visible = true;

                lWorkflow.Text = workflows.Where(w => w.WorkflowTypeId == selectedWorkflowType.Id).Select(w => w.WorkflowType.Name).FirstOrDefault() + " Workflows";
            }
            else
            {
                gWorkflows.Visible = false;
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            var service     = new WorkflowService(rockContext);

            ParseControls(rockContext, true);

            Workflow dbWorkflow = null;

            if (Workflow != null)
            {
                dbWorkflow = service.Get(Workflow.Id);

                if (dbWorkflow != null)
                {
                    if (!dbWorkflow.CompletedDateTime.HasValue && Workflow.CompletedDateTime.HasValue)
                    {
                        dbWorkflow.AddLogEntry("Workflow Manually Completed.");
                        dbWorkflow.CompletedDateTime = Workflow.CompletedDateTime;
                    }
                    else if (dbWorkflow.CompletedDateTime.HasValue && !Workflow.CompletedDateTime.HasValue)
                    {
                        dbWorkflow.AddLogEntry("Workflow Manually Re-Activated.");
                        dbWorkflow.CompletedDateTime = null;
                    }

                    if (dbWorkflow.Name.Trim() != Workflow.Name.Trim())
                    {
                        dbWorkflow.AddLogEntry(string.Format("Workflow name manually changed from '{0}' to '{0}'.", dbWorkflow.Name, tbName.Text));
                        dbWorkflow.Name = Workflow.Name;
                    }

                    if (dbWorkflow.Status.Trim() != Workflow.Status.Trim())
                    {
                        dbWorkflow.AddLogEntry(string.Format("Workflow status manually changed from '{0}' to '{0}'.", dbWorkflow.Status, tbStatus.Text));
                        dbWorkflow.Status = Workflow.Status;
                    }

                    if (!dbWorkflow.InitiatorPersonAliasId.Equals(Workflow.InitiatorPersonAliasId))
                    {
                        dbWorkflow.AddLogEntry(string.Format("Workflow status manually changed from '{0}' to '{0}'.",
                                                             dbWorkflow.InitiatorPersonAlias != null ? dbWorkflow.InitiatorPersonAlias.Person.FullName : "",
                                                             Workflow.InitiatorPersonAlias != null ? Workflow.InitiatorPersonAlias.Person.FullName : ""));
                        dbWorkflow.InitiatorPersonAlias   = Workflow.InitiatorPersonAlias;
                        dbWorkflow.InitiatorPersonAliasId = Workflow.InitiatorPersonAliasId;
                    }

                    if (!Page.IsValid || !dbWorkflow.IsValid)
                    {
                        return;
                    }

                    foreach (var activity in Workflow.Activities)
                    {
                        if (!activity.IsValid)
                        {
                            return;
                        }
                        foreach (var action in activity.Actions)
                        {
                            if (!action.IsValid)
                            {
                                return;
                            }
                        }
                    }

                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.SaveChanges();

                        dbWorkflow.LoadAttributes(rockContext);
                        foreach (var attributeValue in Workflow.AttributeValues)
                        {
                            dbWorkflow.SetAttributeValue(attributeValue.Key, Workflow.GetAttributeValue(attributeValue.Key));
                        }
                        dbWorkflow.SaveAttributeValues(rockContext);

                        WorkflowActivityService workflowActivityService = new WorkflowActivityService(rockContext);
                        WorkflowActionService workflowActionService     = new WorkflowActionService(rockContext);

                        var activitiesInUi = new List <Guid>();
                        var actionsInUI    = new List <Guid>();
                        foreach (var activity in Workflow.Activities)
                        {
                            activitiesInUi.Add(activity.Guid);
                            foreach (var action in activity.Actions)
                            {
                                actionsInUI.Add(action.Guid);
                            }
                        }

                        // delete WorkflowActions that were removed in the UI
                        foreach (var action in workflowActionService.Queryable()
                                 .Where(a =>
                                        a.Activity.WorkflowId.Equals(dbWorkflow.Id) &&
                                        !actionsInUI.Contains(a.Guid)))
                        {
                            workflowActionService.Delete(action);
                        }

                        // delete WorkflowActivities that aren't assigned in the UI anymore
                        foreach (var activity in workflowActivityService.Queryable()
                                 .Where(a =>
                                        a.WorkflowId.Equals(dbWorkflow.Id) &&
                                        !activitiesInUi.Contains(a.Guid)))
                        {
                            workflowActivityService.Delete(activity);
                        }

                        rockContext.SaveChanges();

                        // add or update WorkflowActivities(and Actions) that are assigned in the UI
                        foreach (var editorWorkflowActivity in Workflow.Activities)
                        {
                            // Add or Update the activity type
                            WorkflowActivity workflowActivity = dbWorkflow.Activities.FirstOrDefault(a => a.Guid.Equals(editorWorkflowActivity.Guid));
                            if (workflowActivity == null)
                            {
                                workflowActivity = new WorkflowActivity();
                                workflowActivity.ActivityTypeId = editorWorkflowActivity.ActivityTypeId;
                                dbWorkflow.Activities.Add(workflowActivity);
                            }

                            workflowActivity.AssignedPersonAliasId = editorWorkflowActivity.AssignedPersonAliasId;
                            workflowActivity.AssignedGroupId       = editorWorkflowActivity.AssignedGroupId;
                            workflowActivity.ActivatedDateTime     = editorWorkflowActivity.ActivatedDateTime;
                            workflowActivity.LastProcessedDateTime = editorWorkflowActivity.LastProcessedDateTime;

                            if (!workflowActivity.CompletedDateTime.HasValue && editorWorkflowActivity.CompletedDateTime.HasValue)
                            {
                                workflowActivity.AddLogEntry("Activity Manually Completed.");
                                workflowActivity.CompletedDateTime = RockDateTime.Now;
                            }
                            if (workflowActivity.CompletedDateTime.HasValue && !editorWorkflowActivity.CompletedDateTime.HasValue)
                            {
                                workflowActivity.AddLogEntry("Activity Manually Re-Activated.");
                                workflowActivity.CompletedDateTime = null;
                            }


                            // Save Activity Type
                            rockContext.SaveChanges();

                            // Save ActivityType Attributes
                            workflowActivity.LoadAttributes(rockContext);
                            foreach (var attributeValue in editorWorkflowActivity.AttributeValues)
                            {
                                workflowActivity.SetAttributeValue(attributeValue.Key, editorWorkflowActivity.GetAttributeValue(attributeValue.Key));
                            }
                            workflowActivity.SaveAttributeValues(rockContext);

                            foreach (var editorWorkflowAction in editorWorkflowActivity.Actions)
                            {
                                WorkflowAction workflowAction = workflowActivity.Actions.FirstOrDefault(a => a.Guid.Equals(editorWorkflowAction.Guid));
                                if (workflowAction == null)
                                {
                                    // New action
                                    workflowAction = new WorkflowAction();
                                    workflowAction.ActionTypeId = editorWorkflowAction.ActionTypeId;
                                    workflowActivity.Actions.Add(workflowAction);
                                }

                                workflowAction.LastProcessedDateTime = editorWorkflowAction.LastProcessedDateTime;
                                workflowAction.FormAction            = editorWorkflowAction.FormAction;

                                if (!workflowAction.CompletedDateTime.HasValue && editorWorkflowAction.CompletedDateTime.HasValue)
                                {
                                    workflowAction.AddLogEntry("Action Manually Completed.");
                                    workflowAction.CompletedDateTime = RockDateTime.Now;
                                }
                                if (workflowAction.CompletedDateTime.HasValue && !editorWorkflowAction.CompletedDateTime.HasValue)
                                {
                                    workflowAction.AddLogEntry("Action Manually Re-Activated.");
                                    workflowAction.CompletedDateTime = null;
                                }
                            }

                            // Save action updates
                            rockContext.SaveChanges();
                        }
                    });
                }

                Workflow = service
                           .Queryable("WorkflowType,Activities.ActivityType,Activities.Actions.ActionType")
                           .FirstOrDefault(w => w.Id == Workflow.Id);

                var errorMessages = new List <string>();
                service.Process(Workflow, out errorMessages);
            }

            ShowReadonlyDetails();
        }
        /// <summary>
        /// Job that will close workflows.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            var    workflowTypeGuids = dataMap.GetString("WorkflowTypes").Split(',').Select(Guid.Parse).ToList();
            int?   expirationAge     = dataMap.GetString("ExpirationAge").AsIntegerOrNull();
            bool   lastUsed          = dataMap.GetString("ExpirationCalcLastUsed").AsBoolean();
            string closeStatus       = dataMap.GetString("CloseStatus");

            var rockContext           = new RockContext();
            var workflowService       = new WorkflowService(rockContext);
            var workflowActionService = new WorkflowActionService(rockContext);


            var qry = workflowService.Queryable().AsNoTracking()
                      .Where(w => workflowTypeGuids.Contains(w.WorkflowType.Guid) &&
                             w.ActivatedDateTime.HasValue &&
                             !w.CompletedDateTime.HasValue);



            if (expirationAge.HasValue)
            {
                var expirationDate = RockDateTime.Now.AddMinutes(0 - expirationAge.Value);

                if (!lastUsed)
                {
                    qry = qry.Where(w => w.CreatedDateTime <= expirationDate);
                }
                else
                {
                    var formEntityTypeId = EntityTypeCache.GetId(typeof(Rock.Workflow.Action.UserEntryForm));
                    qry = qry.Where(w =>
                                    w.Activities
                                    .Where(a => a.CompletedDateTime == null)
                                    .SelectMany(a => a.Actions)
                                    .Where(ac => ac.CompletedDateTime == null && ac.CreatedDateTime <= expirationDate && ac.ActionType.EntityTypeId == formEntityTypeId)
                                    .Any());
                }
            }

            // Get a list of workflows to expire so we can open a new context in the loop
            var workflowIds = qry.Select(w => w.Id).ToList();

            foreach (var workflowId in workflowIds)
            {
                rockContext     = new RockContext();
                workflowService = new WorkflowService(rockContext);

                var workflow = workflowService.Get(workflowId);

                if (workflow.IsNull())
                {
                    continue;
                }

                workflow.MarkComplete();
                workflow.Status = closeStatus;

                rockContext.SaveChanges();
            }

            context.Result = string.Format("{0} workflows were closed", workflowIds.Count);
        }