/// <summary>
 /// Deletes the specified item.
 /// </summary>
 /// <param name="item">The item.</param>
 /// <returns></returns>
 public override bool Delete( WorkflowActivityType item )
 {
     var activityService = new WorkflowActivityService( (RockContext)this.Context );
     foreach ( var activity in activityService.Queryable().Where( a => a.ActivityTypeId == item.Id ) )
     {
         activityService.Delete( activity );
     }
     return base.Delete( item );
 }
        /// <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>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            using (var rockContext = new RockContext())
            {
                var contextEntity = this.ContextEntity();

                var workflowService         = new WorkflowService(rockContext);
                var workflowActivityService = new WorkflowActivityService(rockContext);
                var attributeService        = new AttributeService(rockContext);
                var attributeValueService   = new AttributeValueService(rockContext);
                var personAliasService      = new PersonAliasService(rockContext);
                var entityTypeService       = new EntityTypeService(rockContext);

                Guid homeBoundPersonWorkflow = GetAttributeValue("HomeboundPersonWorkflow").AsGuid();

                int    entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id;
                string status       = (contextEntity != null ? "Completed" : "Active");

                var workflowType           = new WorkflowTypeService(rockContext).Get(homeBoundPersonWorkflow);
                var workflowTypeIdAsString = workflowType.Id.ToString();

                var attributeIds = attributeService.Queryable()
                                   .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString)
                                   .Select(a => a.Id).ToList();

                // Look up the activity type for "Visitation"
                var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault();

                var activityAttributeIds = attributeService.Queryable()
                                           .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString)
                                           .Select(a => a.Id).ToList();


                var wfTmpqry = workflowService.Queryable().AsNoTracking()
                               .Where(w => (w.WorkflowType.Guid == homeBoundPersonWorkflow) && (w.Status == "Active" || w.Status == status));

                if (contextEntity != null)
                {
                    var personGuid       = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList();
                    var validWorkflowIds = new AttributeValueService(rockContext).Queryable()
                                           .Where(av => av.Attribute.Key == "HomeboundPerson" && personGuid.Contains(av.Value)).Select(av => av.EntityId);
                    wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id));
                    gReport.Columns[10].Visible = true;
                }

                var visits = workflowActivityService.Queryable()
                             .Join(
                    attributeValueService.Queryable(),
                    wa => wa.Id,
                    av => av.EntityId.Value,
                    (wa, av) => new { WorkflowActivity = wa, AttributeValue = av })
                             .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId))
                             .GroupBy(wa => wa.WorkflowActivity)
                             .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                             .ToList();

                var workflows = wfTmpqry.Join(
                    attributeValueService.Queryable(),
                    obj => obj.Id,
                    av => av.EntityId.Value,
                    (obj, av) => new { Workflow = obj, AttributeValue = av })
                                .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                                .GroupBy(obj => obj.Workflow)
                                .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                                .ToList();

                var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { WorkflowObjects = wf, VisitationActivities = wa })
                          .Select(obj => new { Workflow = obj.WorkflowObjects.Workflow, AttributeValues = obj.WorkflowObjects.AttributeValues, VisitationActivities = obj.VisitationActivities }).ToList();


                if (contextEntity == null)
                {
                    // Make sure they aren't deceased
                    qry = qry.AsQueryable().Where(w => !
                                                  (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ?
                                                   personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased :
                                                   false)).ToList();
                }

                var newQry = qry.Select(w => new
                {
                    Id       = w.Workflow.Id,
                    Workflow = w.Workflow,
                    Name     = w.Workflow.Name,
                    Address  = new Func <string>(() =>
                    {
                        PersonAlias p         = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid());
                        Location homeLocation = p.Person.GetHomeLocation();
                        if (homeLocation == null)
                        {
                            return("");
                        }
                        return(homeLocation.Street1 +
                               homeLocation.City + " " +
                               homeLocation.State + ", " +
                               homeLocation.PostalCode);
                    })(),
                    HomeboundPerson = new Func <Person>(() =>
                    {
                        return(personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person);
                    })(),
                    Age         = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.Age,
                    StartDate   = w.AttributeValues.Where(av => av.AttributeKey == "StartDate").Select(av => av.ValueAsDateTime).FirstOrDefault(),
                    Description = w.AttributeValues.Where(av => av.AttributeKey == "HomeboundResidentDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                    Visits      = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(),
                    LastVisitor = new Func <string>(() => {
                        var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault();
                        if (visitor != null)
                        {
                            return(visitor.ValueFormatted);
                        }
                        return("N/A");
                    })(),
                    LastVisitDate  = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                    LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                    EndDate        = w.AttributeValues.Where(av => av.AttributeKey == "EndDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                    Status         = w.Workflow.Status,
                    Communion      = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(),
                    Actions        = ""
                }).OrderBy(w => w.Name).ToList().AsQueryable();

                SortProperty sortProperty = gReport.SortProperty;
                if (sortProperty != null)
                {
                    gReport.SetLinqDataSource(newQry.Sort(sortProperty));
                }
                else
                {
                    gReport.SetLinqDataSource(newQry.OrderBy(p => p.Name));
                }
                gReport.DataBind();
            }
        }
        /// <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 )
        {
            ParseControls( true );

            var rockContext = new RockContext();
            var service = new WorkflowTypeService( rockContext );

            WorkflowType workflowType = null;

            int? workflowTypeId = hfWorkflowTypeId.Value.AsIntegerOrNull();
            if ( workflowTypeId.HasValue )
            {
                workflowType = service.Get( workflowTypeId.Value );
            }

            if ( workflowType == null )
            {
                workflowType = new WorkflowType();
            }

            var validationErrors = new List<string>();

            // check for unique prefix
            string prefix = tbNumberPrefix.UntrimmedText;
            if ( !string.IsNullOrWhiteSpace( prefix ) &&
                prefix.ToUpper() != ( workflowType.WorkflowIdPrefix ?? string.Empty ).ToUpper() )
            {
                if ( service.Queryable().AsNoTracking()
                    .Any( w =>
                        w.Id != workflowType.Id &&
                        w.WorkflowIdPrefix == prefix ) )
                {
                    validationErrors.Add( "Workflow Number Prefix is already being used by another workflow type.  Please use a unique prefix." );
                }
                else
                {
                    workflowType.WorkflowIdPrefix = prefix;
                }
            }
            else
            {
                workflowType.WorkflowIdPrefix = prefix;
            }

            workflowType.IsActive = cbIsActive.Checked;
            workflowType.Name = tbName.Text;
            workflowType.Description = tbDescription.Text;
            workflowType.CategoryId = cpCategory.SelectedValueAsInt();
            workflowType.WorkTerm = tbWorkTerm.Text;
            workflowType.ModifiedByPersonAliasId = CurrentPersonAliasId;
            workflowType.ModifiedDateTime = RockDateTime.Now;

            int? mins = tbProcessingInterval.Text.AsIntegerOrNull();
            if ( mins.HasValue )
            {
                workflowType.ProcessingIntervalSeconds = mins.Value * 60;
            }
            else
            {
                workflowType.ProcessingIntervalSeconds = null;
            }

            workflowType.IsPersisted = cbIsPersisted.Checked;
            workflowType.LoggingLevel = ddlLoggingLevel.SelectedValueAsEnum<WorkflowLoggingLevel>();
            workflowType.IconCssClass = tbIconCssClass.Text;
            workflowType.SummaryViewText = ceSummaryViewText.Text;
            workflowType.NoActionMessage = ceNoActionMessage.Text;

            if ( validationErrors.Any() )
            {
                nbValidationError.Text = string.Format( "Please Correct the Following<ul><li>{0}</li></ul>",
                    validationErrors.AsDelimited( "</li><li>" ) );
                nbValidationError.Visible = true;

                return;
            }

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

            foreach(var activityType in ActivityTypesState)
            {
                if (!activityType.IsValid)
                {
                    return;
                }
                foreach(var actionType in activityType.ActionTypes)
                {
                    if ( !actionType.IsValid )
                    {
                        return;
                    }
                }
            }

            rockContext.WrapTransaction( () =>
            {
                // Save the entity field changes to workflow type
                if ( workflowType.Id.Equals( 0 ) )
                {
                    service.Add( workflowType );
                }
                rockContext.SaveChanges();

                // Save the workflow type attributes
                SaveAttributes( new Workflow().TypeId, "WorkflowTypeId", workflowType.Id.ToString(), AttributesState, rockContext );

                WorkflowActivityTypeService workflowActivityTypeService = new WorkflowActivityTypeService( rockContext );
                WorkflowActivityService workflowActivityService = new WorkflowActivityService( rockContext );
                WorkflowActionService workflowActionService = new WorkflowActionService( rockContext );
                WorkflowActionTypeService workflowActionTypeService = new WorkflowActionTypeService( rockContext );
                WorkflowActionFormService workflowFormService = new WorkflowActionFormService( rockContext );
                WorkflowActionFormAttributeService workflowFormAttributeService = new WorkflowActionFormAttributeService( rockContext );

                // delete WorkflowActionTypes that aren't assigned in the UI anymore
                List<WorkflowActionType> actionTypesInDB = workflowActionTypeService.Queryable().Where( a => a.ActivityType.WorkflowTypeId.Equals( workflowType.Id ) ).ToList();
                List<WorkflowActionType> actionTypesInUI = new List<WorkflowActionType>();

                foreach ( var workflowActivity in ActivityTypesState )
                {
                    foreach ( var workflowAction in workflowActivity.ActionTypes )
                    {
                        actionTypesInUI.Add( workflowAction );
                    }
                }

                var deletedActionTypes = from actionType in actionTypesInDB
                                         where !actionTypesInUI.Select( u => u.Guid ).Contains( actionType.Guid )
                                         select actionType;
                foreach ( var actionType in deletedActionTypes.ToList() )
                {
                    if ( actionType.WorkflowForm != null )
                    {
                        workflowFormService.Delete( actionType.WorkflowForm );
                    }

                    // Delete any workflow actions of this type
                    int loopCounter = 0;
                    foreach ( var action in workflowActionService.Queryable().Where( a => a.ActionTypeId == actionType.Id ) )
                    {
                        workflowActionService.Delete( action );
                        loopCounter++;
                        if ( loopCounter > 100 )
                        {
                            rockContext.SaveChanges();
                            loopCounter = 0;
                        }
                    }
                    rockContext.SaveChanges();

                    workflowActionTypeService.Delete( actionType );
                }
                rockContext.SaveChanges();

                // delete WorkflowActivityTypes that aren't assigned in the UI anymore
                List<WorkflowActivityType> activityTypesInDB = workflowActivityTypeService.Queryable().Where( a => a.WorkflowTypeId.Equals( workflowType.Id ) ).ToList();
                var deletedActivityTypes = from activityType in activityTypesInDB
                                           where !ActivityTypesState.Select( u => u.Guid ).Contains( activityType.Guid )
                                           select activityType;
                foreach ( var activityType in deletedActivityTypes.ToList() )
                {
                    // Delete any workflow activities of this type
                    int loopCounter = 0;
                    foreach ( var activity in workflowActivityService.Queryable().Where( a => a.ActivityTypeId == activityType.Id ) )
                    {
                        workflowActivityService.Delete( activity );
                        loopCounter++;
                        if ( loopCounter > 100 )
                        {
                            rockContext.SaveChanges();
                            loopCounter = 0;
                        }
                    }
                    rockContext.SaveChanges();

                    workflowActivityTypeService.Delete( activityType );
                }
                rockContext.SaveChanges();

                // add or update WorkflowActivityTypes(and Actions) that are assigned in the UI
                int workflowActivityTypeOrder = 0;
                foreach ( var editorWorkflowActivityType in ActivityTypesState )
                {
                    // Add or Update the activity type
                    WorkflowActivityType workflowActivityType = workflowType.ActivityTypes.FirstOrDefault( a => a.Guid.Equals( editorWorkflowActivityType.Guid ) );
                    if ( workflowActivityType == null )
                    {
                        workflowActivityType = new WorkflowActivityType();
                        workflowActivityType.Guid = editorWorkflowActivityType.Guid;
                        workflowType.ActivityTypes.Add( workflowActivityType );
                    }
                    workflowActivityType.IsActive = editorWorkflowActivityType.IsActive;
                    workflowActivityType.Name = editorWorkflowActivityType.Name;
                    workflowActivityType.Description = editorWorkflowActivityType.Description;
                    workflowActivityType.IsActivatedWithWorkflow = editorWorkflowActivityType.IsActivatedWithWorkflow;
                    workflowActivityType.Order = workflowActivityTypeOrder++;

                    // Save Activity Type
                    rockContext.SaveChanges();

                    // Save ActivityType Attributes
                    if ( ActivityAttributesState.ContainsKey( workflowActivityType.Guid ) )
                    {
                        SaveAttributes( new WorkflowActivity().TypeId, "ActivityTypeId", workflowActivityType.Id.ToString(), ActivityAttributesState[workflowActivityType.Guid], rockContext );
                    }

                    // Because the SaveAttributes above may have flushed the cached entity attribute cache, and it would get loaded again with
                    // a different context, manually reload the cache now with our context to prevent a database lock conflict (when database is
                    // configured without snapshot isolation turned on)
                    AttributeCache.LoadEntityAttributes( rockContext );

                    int workflowActionTypeOrder = 0;
                    foreach ( var editorWorkflowActionType in editorWorkflowActivityType.ActionTypes )
                    {
                        WorkflowActionType workflowActionType = workflowActivityType.ActionTypes.FirstOrDefault( a => a.Guid.Equals( editorWorkflowActionType.Guid ) );
                        if ( workflowActionType == null )
                        {
                            // New action
                            workflowActionType = new WorkflowActionType();
                            workflowActionType.Guid = editorWorkflowActionType.Guid;
                            workflowActivityType.ActionTypes.Add( workflowActionType );
                        }
                        workflowActionType.CriteriaAttributeGuid = editorWorkflowActionType.CriteriaAttributeGuid;
                        workflowActionType.CriteriaComparisonType = editorWorkflowActionType.CriteriaComparisonType;
                        workflowActionType.CriteriaValue = editorWorkflowActionType.CriteriaValue;
                        workflowActionType.Name = editorWorkflowActionType.Name;
                        workflowActionType.EntityTypeId = editorWorkflowActionType.EntityTypeId;
                        workflowActionType.IsActionCompletedOnSuccess = editorWorkflowActionType.IsActionCompletedOnSuccess;
                        workflowActionType.IsActivityCompletedOnSuccess = editorWorkflowActionType.IsActivityCompletedOnSuccess;
                        workflowActionType.Attributes = editorWorkflowActionType.Attributes;
                        workflowActionType.AttributeValues = editorWorkflowActionType.AttributeValues;
                        workflowActionType.Order = workflowActionTypeOrder++;

                        if ( workflowActionType.WorkflowForm != null && editorWorkflowActionType.WorkflowForm == null )
                        {
                            // Form removed
                            workflowFormService.Delete( workflowActionType.WorkflowForm );
                            workflowActionType.WorkflowForm = null;
                        }

                        if ( editorWorkflowActionType.WorkflowForm != null )
                        {
                            if ( workflowActionType.WorkflowForm == null )
                            {
                                workflowActionType.WorkflowForm = new WorkflowActionForm();
                            }

                            workflowActionType.WorkflowForm.NotificationSystemEmailId = editorWorkflowActionType.WorkflowForm.NotificationSystemEmailId;
                            workflowActionType.WorkflowForm.IncludeActionsInNotification = editorWorkflowActionType.WorkflowForm.IncludeActionsInNotification;
                            workflowActionType.WorkflowForm.AllowNotes = editorWorkflowActionType.WorkflowForm.AllowNotes;
                            workflowActionType.WorkflowForm.Header = editorWorkflowActionType.WorkflowForm.Header;
                            workflowActionType.WorkflowForm.Footer = editorWorkflowActionType.WorkflowForm.Footer;
                            workflowActionType.WorkflowForm.Actions = editorWorkflowActionType.WorkflowForm.Actions;
                            workflowActionType.WorkflowForm.ActionAttributeGuid = editorWorkflowActionType.WorkflowForm.ActionAttributeGuid;

                            var editorGuids = editorWorkflowActionType.WorkflowForm.FormAttributes
                                .Select( a => a.Attribute.Guid )
                                .ToList();

                            foreach ( var formAttribute in workflowActionType.WorkflowForm.FormAttributes
                                .Where( a => !editorGuids.Contains( a.Attribute.Guid ) ).ToList() )
                            {
                                workflowFormAttributeService.Delete( formAttribute );
                            }

                            int attributeOrder = 0;
                            foreach ( var editorAttribute in editorWorkflowActionType.WorkflowForm.FormAttributes.OrderBy( a => a.Order ) )
                            {
                                int attributeId = AttributeCache.Read( editorAttribute.Attribute.Guid, rockContext ).Id;

                                var formAttribute = workflowActionType.WorkflowForm.FormAttributes
                                    .Where( a => a.AttributeId == attributeId )
                                    .FirstOrDefault();

                                if ( formAttribute == null )
                                {
                                    formAttribute = new WorkflowActionFormAttribute();
                                    formAttribute.Guid = editorAttribute.Guid;
                                    formAttribute.AttributeId = attributeId;
                                    workflowActionType.WorkflowForm.FormAttributes.Add( formAttribute );
                                }

                                formAttribute.Order = attributeOrder++;
                                formAttribute.IsVisible = editorAttribute.IsVisible;
                                formAttribute.IsReadOnly = editorAttribute.IsReadOnly;
                                formAttribute.IsRequired = editorAttribute.IsRequired;
                                formAttribute.HideLabel = editorAttribute.HideLabel;
                                formAttribute.PreHtml = editorAttribute.PreHtml;
                                formAttribute.PostHtml = editorAttribute.PostHtml;
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                foreach ( var activityType in workflowType.ActivityTypes )
                {
                    foreach ( var workflowActionType in activityType.ActionTypes )
                    {
                        workflowActionType.SaveAttributeValues( rockContext );
                    }
                }

            } );

            var qryParams = new Dictionary<string, string>();
            qryParams["workflowTypeId"] = workflowType.Id.ToString();
            NavigateToPage( RockPage.Guid, qryParams );
        }
Beispiel #5
0
        private IQueryable <HospitalRow> GetQuery(RockContext rockContext)
        {
            var contextEntity = this.ContextEntity();

            var workflowService         = new WorkflowService(rockContext);
            var workflowActivityService = new WorkflowActivityService(rockContext);
            var attributeService        = new AttributeService(rockContext);
            var attributeValueService   = new AttributeValueService(rockContext);
            var personAliasService      = new PersonAliasService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var entityTypeService       = new EntityTypeService(rockContext);


            int    entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id;
            string status       = (contextEntity != null ? "Completed" : "Active");

            Guid hospitalWorkflow = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid();

            var workflowType           = new WorkflowTypeService(rockContext).Get(hospitalWorkflow);
            var workflowTypeIdAsString = workflowType.Id.ToString();

            var attributeIds = attributeService.Queryable()
                               .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString)
                               .Select(a => a.Id).ToList();

            // Look up the activity type for "Visitation"
            var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault();

            var activityAttributeIds = attributeService.Queryable()
                                       .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString)
                                       .Select(a => a.Id).ToList();

            var wfTmpqry = workflowService.Queryable().AsNoTracking()
                           .Where(w => (w.WorkflowType.Guid == hospitalWorkflow) && (w.Status == "Active" || w.Status == status));

            var visitQry = workflowActivityService.Queryable()
                           .Join(
                attributeValueService.Queryable(),
                wa => wa.Id,
                av => av.EntityId.Value,
                (wa, av) => new { WorkflowActivity = wa, AttributeValue = av })
                           .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(wa => wa.WorkflowActivity)
                           .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });

            if (contextEntity != null)
            {
                var personGuid       = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList();
                var validWorkflowIds = new AttributeValueService(rockContext).Queryable()
                                       .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId);
                wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id));
                visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId));
                gReport.Columns[10].Visible = true;
            }

            var visits = visitQry.ToList();

            var workflows = wfTmpqry.Join(
                attributeValueService.Queryable(),
                obj => obj.Id,
                av => av.EntityId.Value,
                (obj, av) => new { Workflow = obj, AttributeValue = av })
                            .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                            .GroupBy(obj => obj.Workflow)
                            .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                            .ToList();

            var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { Workflow = wf, WorkflowActivities = wa })
                      .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList();


            if (contextEntity == null)
            {
                // Make sure they aren't deceased
                qry = qry.AsQueryable().Where(w => !
                                              (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ?
                                               personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased :
                                               false)).ToList();
            }

            var newQry = qry.Select(w => new HospitalRow
            {
                Id              = w.Workflow.Id,
                Workflow        = w.Workflow,
                Name            = w.Workflow.Name,
                Hospital        = w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).FirstOrDefault(),
                HospitalAddress = new Func <string>(() =>
                {
                    DefinedValueCache dv = DefinedValueCache.Get(w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.Value).FirstOrDefault().AsGuid());
                    return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " +
                           dv.AttributeValues["Qualifier2"].ValueFormatted + " " +
                           dv.AttributeValues["Qualifier3"].ValueFormatted + ", " +
                           dv.AttributeValues["Qualifier4"].ValueFormatted);
                })(),
                PersonToVisit = new Func <Person>(() =>
                {
                    PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid());
                    if (pa != null)
                    {
                        return(pa.Person);
                    }
                    return(new Person());
                })(),
                Age = new Func <int?>(() =>
                {
                    PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid());
                    if (pa != null)
                    {
                        return(pa.Person.Age);
                    }
                    return(null);
                })(),
                Room        = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                AdmitDate   = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(),
                Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                Visits      = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(),
                LastVisitor = new Func <string>(() => {
                    var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault();
                    if (visitor != null)
                    {
                        return(visitor.ValueFormatted);
                    }
                    return("N/A");
                })(),
                LastVisitDate  = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                DischargeDate  = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                Status         = w.Workflow.Status,
                Communion      = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(),
                Actions        = ""
            }).ToList().AsQueryable().OrderBy(p => p.Hospital).ThenBy(p => p.PersonToVisit.LastName);

            return(newQry);
        }
Beispiel #6
0
        private void BindGrids()
        {
            SortProperty workflowSort = workflowReportTable.SortProperty;

            BindFilters();

            var ids = viewableWorkflowTypes.Select(vwt => vwt.Id).ToList();
            IQueryable <Workflow> viewableWorkflows;

            if (ids.Contains(workflowTypeFilter))
            {
                viewableWorkflows = workServ.Queryable().Where(awd => awd.WorkflowTypeId == workflowTypeFilter);
            }
            else
            {
                viewableWorkflows = workServ.Queryable().Where(awd => ids.Contains(awd.WorkflowTypeId));
            }

            var lastAssignedWorkflowActivities = from ws in viewableWorkflows
                                                 join was in workActServ.Queryable() on ws.Id equals was.WorkflowId into wj
                                                 select wj.Where(o => o.AssignedGroupId != null || o.AssignedPersonAliasId != null).OrderByDescending(o => o.ActivatedDateTime).FirstOrDefault();

            IQueryable <WorkflowActivity> filteredWorkflowActivities = lastAssignedWorkflowActivities.Where(x => x != null);

            if (workerFilter == -1)
            {
                if (campusFilter != -1)
                {
                    filteredWorkflowActivities = (from vwd in filteredWorkflowActivities.ToList()
                                                  where (vwd.AssignedPersonAlias != null && vwd.AssignedPersonAlias.Person.GetFamilies(_rockContext).FirstOrDefault().CampusId == campusFilter) ||
                                                  (vwd.AssignedGroup != null && vwd.AssignedGroup.CampusId == campusFilter)
                                                  select vwd).AsQueryable();
                }
            }
            else
            {
                filteredWorkflowActivities = from vwd in filteredWorkflowActivities
                                             where vwd.AssignedPersonAliasId == workerFilter ||
                                             (vwd.AssignedGroup != null && vwd.AssignedGroup.Members.Select(x => x.Person.Aliases.Select(y => y.Id).Contains(workerFilter)).Contains(true))
                                             select vwd;
            }

            if (statusFilter != "-1")
            {
                filteredWorkflowActivities = filteredWorkflowActivities.Where(x => x.Workflow.Status == statusFilter);
            }

            DateTime?dMin = dateRange.LowerValue;
            DateTime dMax = (dateRange.UpperValue ?? DateTime.Now).Date.AddHours(23).AddMinutes(59).AddSeconds(59);

            filteredWorkflowActivities = filteredWorkflowActivities.Where(ws => ws.CreatedDateTime > dMin && ws.CreatedDateTime < dMax);


            IQueryable <WorkflowData> filteredWorkflowData = filteredWorkflowActivities.Select(x => new WorkflowData {
                Activity = x, Workflow = x.Workflow
            });

            List <WorkflowData> wrtData;

            if (rddlGroupBy.SelectedValue == "")
            {
                if (workflowSort != null)
                {
                    wrtData = filteredWorkflowData.Sort(workflowSort).ToList();
                }
                else
                {
                    wrtData = filteredWorkflowData.ToList().AsQueryable().OrderBy("Completed").ThenBy("WorkflowTypeName").ThenBy("AssignedEntityName").ToList();
                }
            }
            else
            {
                wrtData = filteredWorkflowData.ToList();
            }

            IEnumerable <GroupedWorkflowData> gwrtData;

            DateTime oneMonthAgo    = DateTime.Now.AddMonths(-1);
            DateTime twoMonthsAgo   = DateTime.Now.AddMonths(-2);
            DateTime threeMonthsAgo = DateTime.Now.AddMonths(-3);

            switch (rddlGroupBy.SelectedValue)
            {
            case "1":
                workflowReportTable.Visible        = false;
                workflowGroupedReportTable.Visible = true;
                workflowGroupedReportTableItemName = "Workflow";

                gwrtData = wrtData.GroupBy(x => x.WorkflowTypeId).Select(grp => new GroupedWorkflowData
                {
                    GroupedItem               = grp.FirstOrDefault().WorkflowTypeName,
                    Count                     = grp.Count(),
                    OneMonthOldStats          = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) > oneMonthAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt < 30).Count(),
                    TwoMonthsOldStats         = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < oneMonthAgo && (x.CreatedDateTime ?? DateTime.Now) > twoMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 30 && x.AgeInt < 60).Count(),
                    ThreeMonthsOldStats       = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < twoMonthsAgo && (x.CreatedDateTime ?? DateTime.Now) > threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 60 && x.AgeInt < 90).Count(),
                    OlderThanThreeMonthsStats = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 90).Count(),
                    TotalStats                = "Open: " + grp.Where(x => x.Completed == 0).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1).Count()
                }).OrderBy(x => x.GroupedItem);

                workflowGroupedReportTable.DataSource = gwrtData.ToList();
                workflowGroupedReportTable.DataBind();
                break;

            case "2":
                workflowReportTable.Visible        = false;
                workflowGroupedReportTable.Visible = true;
                workflowGroupedReportTableItemName = "Campus";

                gwrtData = wrtData.GroupBy(x => x.CampusId).Select(grp => new GroupedWorkflowData
                {
                    GroupedItem               = grp.FirstOrDefault().CampusName,
                    Count                     = grp.Count(),
                    OneMonthOldStats          = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) > oneMonthAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt < 30).Count(),
                    TwoMonthsOldStats         = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < oneMonthAgo && (x.CreatedDateTime ?? DateTime.Now) > twoMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 30 && x.AgeInt < 60).Count(),
                    ThreeMonthsOldStats       = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < twoMonthsAgo && (x.CreatedDateTime ?? DateTime.Now) > threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 60 && x.AgeInt < 90).Count(),
                    OlderThanThreeMonthsStats = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 90).Count(),
                    TotalStats                = "Open: " + grp.Where(x => x.Completed == 0).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1).Count()
                }).OrderBy(x => x.GroupedItem);

                workflowGroupedReportTable.DataSource = gwrtData.ToList();
                workflowGroupedReportTable.DataBind();
                break;

            case "3":
                workflowReportTable.Visible        = false;
                workflowGroupedReportTable.Visible = true;
                workflowGroupedReportTableItemName = "Assigned Worker";

                gwrtData = wrtData.GroupBy(x => x.AssignedEntityName).Select(grp => new GroupedWorkflowData
                {
                    GroupedItem               = grp.FirstOrDefault().AssignedEntityName,
                    Count                     = grp.Count(),
                    OneMonthOldStats          = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) > oneMonthAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt < 30).Count(),
                    TwoMonthsOldStats         = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < oneMonthAgo && (x.CreatedDateTime ?? DateTime.Now) > twoMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 30 && x.AgeInt < 60).Count(),
                    ThreeMonthsOldStats       = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < twoMonthsAgo && (x.CreatedDateTime ?? DateTime.Now) > threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 60 && x.AgeInt < 90).Count(),
                    OlderThanThreeMonthsStats = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 90).Count(),
                    TotalStats                = "Open: " + grp.Where(x => x.Completed == 0).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1).Count()
                }).OrderBy(x => x.GroupedItem);

                workflowGroupedReportTable.DataSource = gwrtData.ToList();
                workflowGroupedReportTable.DataBind();
                break;

            case "4":
                workflowReportTable.Visible        = false;
                workflowGroupedReportTable.Visible = true;
                workflowGroupedReportTableItemName = "Status";

                gwrtData = wrtData.GroupBy(x => x.Status).Select(grp => new GroupedWorkflowData
                {
                    GroupedItem               = grp.FirstOrDefault().Status,
                    Count                     = grp.Count(),
                    OneMonthOldStats          = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) > oneMonthAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt < 30).Count(),
                    TwoMonthsOldStats         = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < oneMonthAgo && (x.CreatedDateTime ?? DateTime.Now) > twoMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 30 && x.AgeInt < 60).Count(),
                    ThreeMonthsOldStats       = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < twoMonthsAgo && (x.CreatedDateTime ?? DateTime.Now) > threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 60 && x.AgeInt < 90).Count(),
                    OlderThanThreeMonthsStats = "Open: " + grp.Where(x => x.Completed == 0 && (x.CreatedDateTime ?? DateTime.Now) < threeMonthsAgo).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1 && x.AgeInt >= 90).Count(),
                    TotalStats                = "Open: " + grp.Where(x => x.Completed == 0).Count() + "<br/>Closed: " + grp.Where(x => x.Completed == 1).Count()
                }).OrderBy(x => x.GroupedItem);

                workflowGroupedReportTable.DataSource = gwrtData.ToList();
                workflowGroupedReportTable.DataBind();
                break;

            default:
                workflowReportTable.Visible        = true;
                workflowGroupedReportTable.Visible = false;

                workflowReportTable.DataSource   = wrtData;
                workflowReportTable.DataKeyNames = new string[] { "Id" };
                workflowReportTable.DataBind();
                break;
            }

            doStats(wrtData);
        }
        public IQueryable <NursingHomeRow> GetQuery(RockContext rockContext)
        {
            var contextEntity = this.ContextEntity();

            var workflowService         = new WorkflowService(rockContext);
            var workflowActivityService = new WorkflowActivityService(rockContext);
            var attributeService        = new AttributeService(rockContext);
            var attributeValueService   = new AttributeValueService(rockContext);
            var personAliasService      = new PersonAliasService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var entityTypeService       = new EntityTypeService(rockContext);
            var groupMemberService      = new GroupMemberService(rockContext);
            var groupService            = new GroupService(rockContext);

            Guid  nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid();
            Guid  nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid();
            Guid  volunteerGroup  = GetAttributeValue("VolunteerGroup").AsGuid();
            Group groupId         = new Group();

            List <DefinedValueCache>  facilities    = DefinedTypeCache.Get(nursingHomeList).DefinedValues;
            Dictionary <Guid, string> volunteerList = new Dictionary <Guid, string>();

            groupId = groupService.GetByGuid(volunteerGroup);

            var groupMemberEntityTypeId = EntityTypeCache.Get(typeof(GroupMember)).Id;

            var groupMemberAttributeQry = attributeService.Queryable()
                                          .Where(a => a.EntityTypeId == groupMemberEntityTypeId)
                                          .Select(a => a.Id);

            var groupMemberAttributeValueQry = attributeValueService.Queryable()
                                               .Where(av => groupMemberAttributeQry.Contains(av.AttributeId));

            if (groupId.IsNotNull())
            {
                var groupMemberList = groupMemberService.Queryable()
                                      .Where(a => a.GroupId == groupId.Id && a.GroupMemberStatus == GroupMemberStatus.Active)
                                      .GroupJoin(groupMemberAttributeValueQry,
                                                 gm => gm.Id,
                                                 av => av.EntityId,
                                                 (gm, av) => new { GroupMember = gm, GroupMemberAttributeValues = av })
                                      .ToList();

                var groupMembers = new List <GroupMember>();

                foreach (var set in groupMemberList)
                {
                    var groupMember = set.GroupMember;

                    groupMember.Attributes = set.GroupMemberAttributeValues
                                             .ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));

                    groupMember.AttributeValues = set.GroupMemberAttributeValues
                                                  .ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));

                    groupMembers.Add(groupMember);
                }

                foreach (var nursingHome in facilities)
                {
                    foreach (var groupMember in groupMembers)
                    {
                        if (groupMember.GetAttributeValue("NursingHomes").IsNotNullOrWhiteSpace())
                        {
                            if (groupMember.GetAttributeValue("NursingHomes").ToLower().Contains(nursingHome.Guid.ToString().ToLower()))
                            {
                                if (volunteerList.ContainsKey(nursingHome.Guid))
                                {
                                    volunteerList[nursingHome.Guid] = volunteerList[nursingHome.Guid] + ", " + groupMember.EntityStringValue;
                                }

                                else
                                {
                                    volunteerList.Add(nursingHome.Guid, groupMember.EntityStringValue);
                                }
                            }
                        }
                    }
                }
            }
            int    entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id;
            string status       = (contextEntity != null ? "Completed" : "Active");

            var workflowType           = new WorkflowTypeService(rockContext).Get(nursingHomeAdmissionWorkflow);
            var workflowTypeIdAsString = workflowType.Id.ToString();

            var attributeIds = attributeService.Queryable()
                               .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString)
                               .Select(a => a.Id).ToList();

            // Look up the activity type for "Visitation"
            var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault();

            var activityAttributeIds = attributeService.Queryable()
                                       .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString)
                                       .Select(a => a.Id).ToList();

            var wfTmpqry = workflowService.Queryable().AsNoTracking()
                           .Where(w => (w.WorkflowType.Guid == nursingHomeAdmissionWorkflow) && (w.Status == "Active" || w.Status == status));

            var visitQry = workflowActivityService.Queryable()
                           .Join(
                attributeValueService.Queryable(),
                wa => wa.Id,
                av => av.EntityId.Value,
                (wa, av) => new { WorkflowActivity = wa, AttributeValue = av })
                           .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(wa => wa.WorkflowActivity)
                           .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });

            if (contextEntity != null)
            {
                var personGuid       = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList();
                var validWorkflowIds = new AttributeValueService(rockContext).Queryable()
                                       .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId);
                wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id));
                visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId));
                gReport.Columns[10].Visible = true;
            }

            var visits = visitQry.ToList();

            var workflows = wfTmpqry.Join(
                attributeValueService.Queryable(),
                obj => obj.Id,
                av => av.EntityId.Value,
                (obj, av) => new { Workflow = obj, AttributeValue = av })
                            .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                            .GroupBy(obj => obj.Workflow)
                            .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                            .ToList();

            var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (Workflow, wa) => new { Workflow = Workflow, WorkflowActivities = wa })
                      .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList();

            if (contextEntity == null)
            {
                // Make sure they aren't deceased
                qry = qry.AsQueryable().Where(w => !
                                              (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ?
                                               personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased :
                                               false)).ToList();
            }

            var newQry = qry.Select(w => new NursingHomeRow
            {
                Id          = w.Workflow.Id,
                Workflow    = w.Workflow,
                NursingHome = new Func <string>(() =>
                {
                    if (w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).Any())
                    {
                        return(facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).Select(dv => dv.Value).FirstOrDefault());
                    }
                    return("N/A");
                })(),
                Person = new Func <Person>(() =>
                {
                    AttributeValue personAliasAV = w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").FirstOrDefault();
                    if (personAliasAV != null)
                    {
                        PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid());

                        return(pa != null ? pa.Person : new Person());
                    }
                    return(new Person());
                })(),
                Address = new Func <string>(() =>
                {
                    DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault();
                    if (dv != null)
                    {
                        return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " +
                               dv.AttributeValues["Qualifier2"].ValueFormatted + " " +
                               dv.AttributeValues["Qualifier3"].ValueFormatted + ", " +
                               dv.AttributeValues["Qualifier4"].ValueFormatted);
                    }
                    return("");
                })(),
                PastoralMinister = new Func <string>(() =>
                {
                    DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault();
                    if (dv != null && (dv.AttributeValues.ContainsKey("PastoralMinister") || dv.AttributeValues.ContainsKey("Qualifier6")))
                    {
                        return(dv.AttributeValues.ContainsKey("PastoralMinister") ? dv.AttributeValues["PastoralMinister"].ValueFormatted : dv.AttributeValues["Qualifier6"].ValueFormatted);
                    }
                    return("");
                })(),
                Volunteers = new Func <string>(() =>
                {
                    String vList = "";
                    if (volunteerList.TryGetValue(w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid(), out vList))
                    {
                        return(vList);
                    }
                    else
                    {
                        return("");
                    }
                })(),
                Room        = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                AdmitDate   = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(),
                Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                Visits      = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(),
                LastVisitor = new Func <string>(() =>
                {
                    var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault();
                    if (visitor != null)
                    {
                        return(visitor.ValueFormatted);
                    }
                    return("N/A");
                })(),
                LastVisitDate  = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                DischargeDate  = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                Status         = w.Workflow.Status,
                Communion      = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(),
                Actions        = ""
            }).ToList().AsQueryable().OrderBy(p => p.NursingHome).ThenBy(p => p.Person.FullName);

            return(newQry);
        }
        /// <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>
        /// Updates the Workflows to us the new To person
        /// </summary>
        protected void UpdateWorkflows()
        {
            //Get the selected people
            FromPersonId = ppFrom.PersonId;
            ToPersonId = ppTo.PersonId;

            if (ppTo.PersonId != null)
            {
                // Create Needed Services
                WorkflowActivityService workflowActivityService = new WorkflowActivityService(rockContext);

                //Get Workflows from From person
                var assigned = workflowActivityService.Queryable().Where(a => a.AssignedPersonAliasId == FromPersonId);

                //Set each Workflow in From person to To person
                foreach (var x in assigned)
                {
                    x.AssignedPersonAliasId = ToPersonId;
                    x.ModifiedDateTime = DateTime.Now;
                    x.ModifiedByPersonAliasId = CurrentPersonAliasId;

                }

                //Save changes
                rockContext.SaveChanges();

                //Update UI
                nbSuccess.Visible = true;
                nbWarningMessage.Visible = false;
            }
        }
        /// <summary>
        /// Returns the number of Workflows and Connection Requests for the selected Fron person, then populates grids.
        /// </summary>
        protected void UpdateUi()
        {
            // Get the selected person
            FromPersonId = ppFrom.PersonId;

            // Construct List
            var workflowResultList = new List<WorkflowActivity>();
            var connectionRequestResultList = new List<ConnectionRequest>();

            // Create Needed Services
            WorkflowActivityService workflowActivityService = new WorkflowActivityService(rockContext);
            ConnectionRequestService connectionRequestService = new ConnectionRequestService(rockContext);

            // Get Workflows from From person
            var assignedWorkflows =
                workflowActivityService.Queryable()
                    .Where(
                        a =>
                            a.AssignedPersonAliasId == FromPersonId && a.CompletedDateTime == null &&
                            a.Workflow.CompletedDateTime == null);

            // Get Connection Requests from From person
            var assignedConnectionRequests =
                connectionRequestService.Queryable()
                    .Where(
                        b =>
                            b.ConnectorPersonAliasId == FromPersonId && b.ConnectionState != ConnectionState.Connected &&
                            b.ConnectionState != ConnectionState.Inactive);

            // UI Updates
            if (ppFrom.PersonId != null)
            {
                foreach (var workflow in assignedWorkflows)
                {
                    workflowResultList.Add(workflow);
                }

                foreach (var connectionRequest in assignedConnectionRequests)
                {
                    connectionRequestResultList.Add(connectionRequest);
                }

                lbCount.Text = assignedWorkflows.Count() + " open workflows assigned to this person.<br />" +
                               assignedConnectionRequests.Count() + " open Connection Requests assigned to this person.";

                gWorkflows.DataSource = workflowResultList;
                gWorkflows.DataBind();

                gConnections.DataSource = connectionRequestResultList;
                gConnections.DataBind();

                if (assignedWorkflows.Any())
                {
                    btnSaveWorkflows.Visible = true;
                    ppTo.Visible = true;
                }

                if (assignedConnectionRequests.Any())
                {
                    btnSaveConnections.Visible = true;
                    ppTo.Visible = true;
                }
            }

            else
            {
                nbSuccess.Visible = false;
                nbWarningMessage.Visible = false;
            }
        }
Beispiel #11
0
        /// <summary>
        /// Returns the number of Workflows and Connection Requests for the selected Fron person, then populates grids.
        /// </summary>
        protected void UpdateUi()
        {
            // Get the selected person
            FromPersonId = ppFrom.PersonId;

            // Construct List
            var workflowResultList          = new List <WorkflowActivity>();
            var connectionRequestResultList = new List <ConnectionRequest>();

            // Create Needed Services
            WorkflowActivityService  workflowActivityService  = new WorkflowActivityService(rockContext);
            ConnectionRequestService connectionRequestService = new ConnectionRequestService(rockContext);

            // Get Workflows from From person
            var assignedWorkflows =
                workflowActivityService.Queryable()
                .Where(
                    a =>
                    a.AssignedPersonAliasId == FromPersonId && a.CompletedDateTime == null &&
                    a.Workflow.CompletedDateTime == null);


            // Get Connection Requests from From person
            var assignedConnectionRequests =
                connectionRequestService.Queryable()
                .Where(
                    b =>
                    b.ConnectorPersonAliasId == FromPersonId && b.ConnectionState != ConnectionState.Connected &&
                    b.ConnectionState != ConnectionState.Inactive);

            // UI Updates
            if (ppFrom.PersonId != null)
            {
                foreach (var workflow in assignedWorkflows)
                {
                    workflowResultList.Add(workflow);
                }

                foreach (var connectionRequest in assignedConnectionRequests)
                {
                    connectionRequestResultList.Add(connectionRequest);
                }


                lbCount.Text = assignedWorkflows.Count() + " open workflows assigned to this person.<br />" +
                               assignedConnectionRequests.Count() + " open Connection Requests assigned to this person.";

                gWorkflows.DataSource = workflowResultList;
                gWorkflows.DataBind();

                gConnections.DataSource = connectionRequestResultList;
                gConnections.DataBind();



                if (assignedWorkflows.Any())
                {
                    btnSaveWorkflows.Visible = true;
                    ppTo.Visible             = true;
                }

                if (assignedConnectionRequests.Any())
                {
                    btnSaveConnections.Visible = true;
                    ppTo.Visible = true;
                }
            }

            else
            {
                nbSuccess.Visible        = false;
                nbWarningMessage.Visible = false;
            }
        }