public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var attributeMatrixGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "AttributeMatrix").AsGuid()).AsGuidOrNull();
            var itemGuid            = GetActionAttributeValue(action, "ItemGuid").ResolveMergeFields(GetMergeFields(action)).AsGuidOrNull();

            if (attributeMatrixGuid.HasValue && itemGuid.HasValue)
            {
                // Load the matrix
                AttributeMatrix matrix = attributeMatrixService.Get(attributeMatrixGuid.Value);

                AttributeMatrixItem item = matrix.AttributeMatrixItems.Where(i => i.Guid == itemGuid.Value).FirstOrDefault();

                if (item != null)
                {
                    matrix.AttributeMatrixItems.Remove(item);
                    attributeMatrixItemService.Delete(item);
                }
            }

            return(true);
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var attributeMatrixGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "AttributeMatrix").AsGuid()).AsGuidOrNull();
            var itemAttributes      = GetActionAttributeValue(action, "ItemAttributes").AsDictionaryOrNull();

            if (attributeMatrixGuid.HasValue && itemAttributes != null)
            {
                // Load the matrix
                AttributeMatrix matrix = attributeMatrixService.Get(attributeMatrixGuid.Value);

                // Create the new item
                AttributeMatrixItem item = new AttributeMatrixItem();
                item.AttributeMatrix = matrix;
                item.LoadAttributes();

                foreach (var attribute in item.Attributes)
                {
                    if (itemAttributes.ContainsKey(attribute.Key))
                    {
                        item.SetAttributeValue(attribute.Key, itemAttributes[attribute.Key].ResolveMergeFields(GetMergeFields(action)));
                    }
                }
                matrix.AttributeMatrixItems.Add(item);
                rockContext.SaveChanges();
                item.SaveAttributeValues(rockContext);
            }

            return(true);
        }
Beispiel #3
0
        /// <summary>
        /// Gets the edit value as the IEntity.Id
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public int?GetEditValueAsEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            Guid guid = GetEditValue(control, configurationValues).AsGuid();
            var  item = new AttributeMatrixService(new RockContext()).Get(guid);

            return(item != null ? item.Id : ( int? )null);
        }
        private void BindLava(IQueryable <GroupMember> members, List <Person> familyMembers, RockContext rockContext)
        {
            var items = new List <LavaData>();
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            foreach (var person in familyMembers)
            {
                //Get all the camp group members for this person
                List <GroupMember> medicalMembers = members.Where(m => m.PersonId == person.Id).ToList();

                if (!medicalMembers.Any())
                {
                    continue;
                }

                person.LoadAttributes();
                var attribute       = person.GetAttributeValue(GetAttributeValue("MedicationMatrixKey"));
                var attributeMatrix = attributeMatrixService.Get(attribute.AsGuid());

                LavaData data = new LavaData
                {
                    Person      = person,
                    Groups      = medicalMembers.Select(m => m.Group).ToList(),
                    Medications = attributeMatrix
                };
                items.Add(data);
            }
            var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);

            mergeObjects.Add("Items", items);
            ltLava.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeObjects);
        }
Beispiel #5
0
        /// <summary>
        /// Sets the edit value from IEntity.Id value
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id">The identifier.</param>
        public void SetEditValueFromEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id)
        {
            var    item      = new AttributeMatrixService(new RockContext()).Get(id ?? 0);
            string guidValue = item != null?item.Guid.ToString() : string.Empty;

            SetEditValue(control, configurationValues, guidValue);
        }
Beispiel #6
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            AttributeMatrixEditor attributeMatrixEditor = control as AttributeMatrixEditor;

            if (attributeMatrixEditor != null)
            {
                var rockContext = new RockContext();
                AttributeMatrixTemplate attributeMatrixTemplate = null;
                if (attributeMatrixEditor.AttributeMatrixTemplateId.HasValue)
                {
                    attributeMatrixTemplate = new AttributeMatrixTemplateService(rockContext).Get(attributeMatrixEditor.AttributeMatrixTemplateId.Value);
                }

                if (attributeMatrixTemplate != null)
                {
                    var             attributeMatrixService = new AttributeMatrixService(rockContext);
                    AttributeMatrix attributeMatrix        = null;
                    Guid?           attributeMatrixGuid    = value.AsGuidOrNull();
                    if (attributeMatrixGuid.HasValue)
                    {
                        attributeMatrix = attributeMatrixService.Get(attributeMatrixGuid.Value);
                    }

                    if (attributeMatrix == null)
                    {
                        // Create the AttributeMatrix now and save it even though they haven't hit save yet. We'll need the AttributeMatrix record to exist so that we can add AttributeMatrixItems to it
                        // If this ends up creating an orphan, we can clean up it up later
                        attributeMatrix = new AttributeMatrix {
                            Guid = Guid.NewGuid()
                        };
                        attributeMatrix.AttributeMatrixTemplateId = attributeMatrixEditor.AttributeMatrixTemplateId.Value;
                        attributeMatrix.AttributeMatrixItems      = new List <AttributeMatrixItem>();
                        attributeMatrixService.Add(attributeMatrix);
                        rockContext.SaveChanges();
                    }

                    // If the AttributeMatrixTemplateId jwas changed since the last time the attributeMatrix was saved, change it and wipe out the items
                    if (attributeMatrix.AttributeMatrixTemplateId != attributeMatrixEditor.AttributeMatrixTemplateId.Value)
                    {
                        attributeMatrix.AttributeMatrixTemplateId = attributeMatrixEditor.AttributeMatrixTemplateId.Value;

                        var attributeMatrixItemService = new AttributeMatrixItemService(rockContext);

                        // If the AttributeMatrixTemplateId changed, all the values in the AttributeMatrixItems
                        // are referring to attributes from the old template, so wipe them out. All of them.
                        foreach (var attributeMatrixItem in attributeMatrix.AttributeMatrixItems.ToList())
                        {
                            attributeMatrixItemService.Delete(attributeMatrixItem);
                        }

                        attributeMatrix.AttributeMatrixItems.Clear();
                        rockContext.SaveChanges();
                    }

                    attributeMatrixEditor.AttributeMatrixGuid = attributeMatrix.Guid;
                }
            }
        }
Beispiel #7
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var attributeGuid       = GetActionAttributeValue(action, "AttributeMatrix").AsGuidOrNull();
            var attributeMatrixGuid = action.GetWorkflowAttributeValue(attributeGuid.HasValue ? attributeGuid.Value : Guid.Empty).AsGuidOrNull();
            var itemAttributes      = GetActionAttributeValue(action, "ItemAttributes").AsDictionaryOrNull();

            if (attributeGuid.HasValue && itemAttributes != null)
            {
                // Load the matrix
                AttributeMatrix matrix = attributeMatrixService.Get(attributeMatrixGuid.HasValue ? attributeMatrixGuid.Value : Guid.Empty);

                // If the matrix is null, create it first
                if (matrix == null)
                {
                    var attribute = AttributeCache.Get(GetActionAttributeValue(action, "AttributeMatrix").AsGuid());
                    matrix = new AttributeMatrix();
                    matrix.AttributeMatrixItems      = new List <AttributeMatrixItem>();
                    matrix.AttributeMatrixTemplateId = attribute.QualifierValues["attributematrixtemplate"]?.Value?.AsInteger() ?? 0;
                    attributeMatrixService.Add(matrix);

                    // Persist it and make sure it gets saved
                    rockContext.SaveChanges();
                    if (attribute.EntityTypeId == new Rock.Model.Workflow().TypeId)
                    {
                        action.Activity.Workflow.SetAttributeValue(attribute.Key, matrix.Guid.ToString());
                    }
                    else if (attribute.EntityTypeId == new WorkflowActivity().TypeId)
                    {
                        action.Activity.SetAttributeValue(attribute.Key, matrix.Guid.ToString());
                    }
                }

                // Create the new item
                AttributeMatrixItem item = new AttributeMatrixItem();
                item.AttributeMatrix = matrix;
                item.LoadAttributes();

                foreach (var attribute in item.Attributes)
                {
                    if (itemAttributes.ContainsKey(attribute.Key))
                    {
                        item.SetAttributeValue(attribute.Key, itemAttributes[attribute.Key].ResolveMergeFields(GetMergeFields(action)));
                    }
                }
                matrix.AttributeMatrixItems.Add(item);
                rockContext.SaveChanges();
                item.SaveAttributeValues(rockContext);
            }

            return(true);
        }
Beispiel #8
0
        /// <summary>
        /// Handles the GridReorder event of the gMatrixItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        private void gMatrixItems_GridReorder(object sender, GridReorderEventArgs e)
        {
            var rockContext     = new RockContext();
            var attributeMatrix = new AttributeMatrixService(rockContext).Get(this.AttributeMatrixGuid.Value);
            var service         = new AttributeMatrixItemService(rockContext);
            var items           = service.Queryable().Where(a => a.AttributeMatrixId == attributeMatrix.Id).OrderBy(i => i.Order).ToList();

            service.Reorder(items, e.OldIndex, e.NewIndex);
            rockContext.SaveChanges();

            BindGrid(this.AttributeMatrixGuid);
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        /// <param name="attributeMatrixGuid">The attribute matrix unique identifier.</param>
        private void BindGrid(Guid?attributeMatrixGuid)
        {
            if (attributeMatrixGuid.HasValue)
            {
                var rockContext     = new RockContext();
                var attributeMatrix = new AttributeMatrixService(rockContext).Get(attributeMatrixGuid.Value);
                if (attributeMatrix == null)
                {
                    return;
                }

                var attributeMatrixItemList = attributeMatrix.AttributeMatrixItems.OrderBy(a => a.Order).ThenBy(a => a.Id).ToList();

                foreach (var attributeMatrixItem in attributeMatrixItemList)
                {
                    attributeMatrixItem.LoadAttributes();
                }

                _gMatrixItems.DataSource  = attributeMatrixItemList;
                _gMatrixItems.RowItemText = "Item";
                _gMatrixItems.DataBind();

                _gMatrixItems.Actions.ShowAdd = true;
                _hfRowCount.Value             = attributeMatrixItemList.Count.ToString();

                if (attributeMatrix.AttributeMatrixTemplate.MinimumRows.HasValue && attributeMatrixItemList.Count < attributeMatrix.AttributeMatrixTemplate.MinimumRows.Value)
                {
                    string itemPhrase = attributeMatrix.AttributeMatrixTemplate.MinimumRows.Value > 1 ? "items are" : "item is";
                    _nbWarning.Text    = $"At least {attributeMatrix.AttributeMatrixTemplate.MinimumRows.Value} {itemPhrase} required.";
                    _nbWarning.Visible = true;
                }
                else if (attributeMatrix.AttributeMatrixTemplate.MaximumRows.HasValue && attributeMatrixItemList.Count >= attributeMatrix.AttributeMatrixTemplate.MaximumRows.Value)
                {
                    string itemPhrase = attributeMatrix.AttributeMatrixTemplate.MaximumRows.Value > 1 ? "items are" : "item is";
                    _nbWarning.Text = $"No more than {attributeMatrix.AttributeMatrixTemplate.MaximumRows.Value} {itemPhrase} allowed.";

                    // only show the warning if they are actually over the limit
                    _nbWarning.Visible = attributeMatrix.AttributeMatrixTemplate.MaximumRows.HasValue && (attributeMatrixItemList.Count > attributeMatrix.AttributeMatrixTemplate.MaximumRows.Value);

                    // if they are at or over the limit, don't show the Add button
                    _gMatrixItems.Actions.ShowAdd = true;
                }
                else
                {
                    _nbWarning.Visible = false;
                }
            }
        }
        private void BindGrid(IQueryable <GroupMember> members, List <Person> familyMembers, RockContext rockContext)
        {
            var gridData = new List <GridData>();
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            foreach (var person in familyMembers)
            {
                //Get all the camp group members for this person
                List <GroupMember> medicalMembers = members.Where(m => m.PersonId == person.Id).ToList();

                if (!medicalMembers.Any())
                {
                    continue;
                }

                GridData data = new GridData
                {
                    Id          = person.PrimaryAlias.Guid,
                    Name        = person.FullName,
                    Group       = string.Join("<br>", medicalMembers.Select(m => m.Group.Name)),
                    Medications = "No Medication Information"
                };
                person.LoadAttributes();
                var attribute       = person.GetAttributeValue(GetAttributeValue("MedicationMatrixKey"));
                var attributeMatrix = attributeMatrixService.Get(attribute.AsGuid());
                if (attributeMatrix != null)
                {
                    var lava     = attributeMatrix.AttributeMatrixTemplate.FormattedLava;
                    var template = attributeMatrix.AttributeMatrixTemplate;
                    template.LoadAttributes();
                    AttributeMatrixItem tempAttributeMatrixItem = new AttributeMatrixItem();
                    tempAttributeMatrixItem.AttributeMatrix = attributeMatrix;
                    tempAttributeMatrixItem.LoadAttributes();
                    Dictionary <string, object> mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, null, new Rock.Lava.CommonMergeFieldsOptions {
                        GetLegacyGlobalMergeFields = false
                    });
                    mergeFields.Add("AttributeMatrix", attributeMatrix);
                    mergeFields.Add("ItemAttributes", tempAttributeMatrixItem.Attributes.Select(a => a.Value).OrderBy(a => a.Order).ThenBy(a => a.Name));
                    mergeFields.Add("AttributeMatrixItems", attributeMatrix.AttributeMatrixItems.OrderBy(a => a.Order));
                    var medications = lava.ResolveMergeFields(mergeFields);
                    data.Medications = medications;
                }
                gridData.Add(data);
            }

            gGrid.DataSource = gridData;
            gGrid.DataBind();
        }
Beispiel #11
0
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed)
        {
            using (var rockContext = new RockContext())
            {
                var             attributeMatrixService = new AttributeMatrixService(rockContext);
                AttributeMatrix attributeMatrix        = null;
                Guid?           attributeMatrixGuid    = value.AsGuidOrNull();
                if (attributeMatrixGuid.HasValue)
                {
                    attributeMatrix = attributeMatrixService.GetNoTracking(attributeMatrixGuid.Value);
                }

                if (attributeMatrix != null)
                {
                    if (configurationValues.ContainsKey(ATTRIBUTE_MATRIX_TEMPLATE))
                    {
                        // set the AttributeMatrixTemplateId just in case it was changed since the last time the attributeMatrix was saved
                        int attributeMatrixTemplateId = configurationValues[ATTRIBUTE_MATRIX_TEMPLATE].Value.AsInteger();
                        if (attributeMatrix.AttributeMatrixTemplateId != attributeMatrixTemplateId)
                        {
                            attributeMatrix.AttributeMatrixTemplateId = attributeMatrixTemplateId;
                            attributeMatrix.AttributeMatrixTemplate   = new AttributeMatrixTemplateService(rockContext).GetNoTracking(attributeMatrix.AttributeMatrixTemplateId);

                            // If the AttributeMatrixTemplateId changed, all the values in the AttributeMatrixItems
                            // are referring to attributes from the old template, so wipe them out. All of them.
                            attributeMatrix.AttributeMatrixItems.Clear();
                        }
                    }

                    // make a temp attributeMatrixItem to see what Attributes they have
                    AttributeMatrixItem tempAttributeMatrixItem = new AttributeMatrixItem();
                    tempAttributeMatrixItem.AttributeMatrix = attributeMatrix;
                    tempAttributeMatrixItem.LoadAttributes();

                    var lavaTemplate = attributeMatrix.AttributeMatrixTemplate.FormattedLava;
                    Dictionary <string, object> mergeFields = Lava.LavaHelper.GetCommonMergeFields(parentControl?.RockBlock()?.RockPage, null, new Lava.CommonMergeFieldsOptions {
                        GetLegacyGlobalMergeFields = false
                    });
                    mergeFields.Add("AttributeMatrix", attributeMatrix);
                    mergeFields.Add("ItemAttributes", tempAttributeMatrixItem.Attributes.Select(a => a.Value).OrderBy(a => a.Order).ThenBy(a => a.Name));
                    mergeFields.Add("AttributeMatrixItems", attributeMatrix.AttributeMatrixItems.OrderBy(a => a.Order));
                    return(lavaTemplate.ResolveMergeFields(mergeFields));
                }
            }

            return(base.FormatValue(parentControl, value, configurationValues, condensed));
        }
Beispiel #12
0
        /// <summary>
        /// Reads new values entered by the user for the field
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public override string GetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            AttributeMatrixEditor attributeMatrixEditor = control as AttributeMatrixEditor;

            if (attributeMatrixEditor != null && configurationValues.ContainsKey(ATTRIBUTE_MATRIX_TEMPLATE))
            {
                int?attributeMatrixTemplateId = configurationValues[ATTRIBUTE_MATRIX_TEMPLATE]?.Value.AsIntegerOrNull();
                if (attributeMatrixTemplateId.HasValue)
                {
                    if (attributeMatrixEditor.AttributeMatrixGuid.HasValue)
                    {
                        var rockContext     = new RockContext();
                        var attributeMatrix = new AttributeMatrixService(rockContext).Get(attributeMatrixEditor.AttributeMatrixGuid.Value);
                        return(attributeMatrix.Guid.ToString());
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            RockContext rockContext = new RockContext();
            AttributeMatrixTemplateService attributeMatrixTemplateService = new AttributeMatrixTemplateService(rockContext);
            AttributeMatrixService         attributeMatrixService         = new AttributeMatrixService(rockContext);

            var matrixFieldTypeId = FieldTypeCache.Get <MatrixFieldType>().Id;

            var qry = attributeMatrixTemplateService.Queryable()
                      .Select(a => new
            {
                a.Id,
                a.Name,
                a.Description,
                a.IsActive
            }).Sort(gList.SortProperty ?? new SortProperty {
                Property = "Name"
            });

            gList.SetLinqDataSource(qry);
            gList.DataBind();
        }
Beispiel #14
0
        /// <summary>
        /// Cleanups the orphaned attributes.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        /// <returns></returns>
        private int CleanupOrphanedAttributes(JobDataMap dataMap)
        {
            int recordsDeleted = 0;

            // Cleanup AttributeMatrix records that are no longer associated with an attribute value
            using (RockContext rockContext = new RockContext())
            {
                AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
                AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);

                var matrixFieldTypeId = FieldTypeCache.Read <MatrixFieldType>().Id;
                // get a list of attribute Matrix Guids that are actually in use
                var usedAttributeMatrices = new AttributeValueService(rockContext).Queryable().Where(a => a.Attribute.FieldTypeId == matrixFieldTypeId).Select(a => a.Value).ToList().AsGuidList();

                // clean up any orphaned attribute matrices
                var dayAgo = RockDateTime.Now.AddDays(-1);
                var orphanedAttributeMatrices = attributeMatrixService.Queryable().Where(a => (a.CreatedDateTime < dayAgo) && !usedAttributeMatrices.Contains(a.Guid)).ToList();
                if (orphanedAttributeMatrices.Any())
                {
                    recordsDeleted += orphanedAttributeMatrices.Count;
                    attributeMatrixItemService.DeleteRange(orphanedAttributeMatrices.SelectMany(a => a.AttributeMatrixItems));
                    attributeMatrixService.DeleteRange(orphanedAttributeMatrices);
                    rockContext.SaveChanges();
                }
            }

            // clean up other orphaned entity attributes
            Type rockContextType = typeof(Rock.Data.RockContext);

            foreach (var cachedType in EntityTypeCache.All().Where(e => e.IsEntity))
            {
                Type entityType = cachedType.GetEntityType();
                if (entityType != null &&
                    typeof(IEntity).IsAssignableFrom(entityType) &&
                    typeof(IHasAttributes).IsAssignableFrom(entityType) &&
                    !entityType.Namespace.Equals("Rock.Rest.Controllers"))
                {
                    try
                    {
                        bool ignore = false;
                        if (entityType.Assembly != rockContextType.Assembly)
                        {
                            // If the model is from a custom project, verify that it is using RockContext, if not, ignore it since an
                            // exception will occur due to the AttributeValue query using RockContext.
                            var entityContextType = Reflection.SearchAssembly(entityType.Assembly, typeof(System.Data.Entity.DbContext));
                            ignore = (entityContextType.Any() && !entityContextType.First().Value.Equals(rockContextType));
                        }

                        if (!ignore)
                        {
                            var classMethod = this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
                                              .First(m => m.Name == "CleanupOrphanedAttributeValuesForEntityType");
                            var genericMethod = classMethod.MakeGenericMethod(entityType);
                            var result        = genericMethod.Invoke(this, null) as int?;
                            if (result.HasValue)
                            {
                                recordsDeleted += (int)result;
                            }
                        }
                    }
                    catch { }
                }
            }

            return(recordsDeleted);
        }
Beispiel #15
0
        protected override void OnLoad(EventArgs e)
        {
            nbAlert.Visible = false;

            if (CurrentPerson == null)
            {
                nbAlert.Visible = true;
                nbAlert.Text    = "Please log in to continue.";
                return;
            }
            if (!Page.IsPostBack)
            {
                RockContext rockContext   = new RockContext();
                var         familyMembers = CurrentPerson.GetFamilies().SelectMany(f => f.Members).Select(m => m.Person).ToList();

                AddCaretakees(familyMembers, rockContext);


                var groupTypeStrings = GetAttributeValue("GroupTypes").SplitDelimitedValues();
                var groupTypeIds     = new List <int>();
                foreach (var groupType in groupTypeStrings)
                {
                    var groupTypeCache = GroupTypeCache.Get(groupType.AsGuid());
                    if (groupTypeCache != null)
                    {
                        groupTypeIds.Add(groupTypeCache.Id);
                    }
                }

                var groups = new GroupService(rockContext).Queryable()
                             .Where(g => g.IsActive && !g.IsArchived && groupTypeIds.Contains(g.GroupTypeId));
                if (!groups.Any())
                {
                    nbAlert.Visible = true;
                    nbAlert.Text    = "Please configure this block.";
                    return;
                }

                var members = groups.SelectMany(g => g.Members);


                var gridData = new List <GridData>();
                AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);
                foreach (var person in familyMembers)
                {
                    //Get all the camp group members for this person
                    List <GroupMember> medicalMembers = members.Where(m => m.PersonId == person.Id).ToList();

                    if (!medicalMembers.Any())
                    {
                        continue;
                    }

                    GridData data = new GridData
                    {
                        Id          = person.PrimaryAlias.Guid,
                        Name        = person.FullName,
                        Group       = string.Join("<br>", medicalMembers.Select(m => m.Group.Name)),
                        Medications = "No Medication Information"
                    };
                    person.LoadAttributes();
                    var attribute       = person.GetAttributeValue(GetAttributeValue("MedicationMatrixKey"));
                    var attributeMatrix = attributeMatrixService.Get(attribute.AsGuid());
                    if (attributeMatrix != null)
                    {
                        var lava     = attributeMatrix.AttributeMatrixTemplate.FormattedLava;
                        var template = attributeMatrix.AttributeMatrixTemplate;
                        template.LoadAttributes();
                        AttributeMatrixItem tempAttributeMatrixItem = new AttributeMatrixItem();
                        tempAttributeMatrixItem.AttributeMatrix = attributeMatrix;
                        tempAttributeMatrixItem.LoadAttributes();
                        Dictionary <string, object> mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, null, new Rock.Lava.CommonMergeFieldsOptions {
                            GetLegacyGlobalMergeFields = false
                        });
                        mergeFields.Add("AttributeMatrix", attributeMatrix);
                        mergeFields.Add("ItemAttributes", tempAttributeMatrixItem.Attributes.Select(a => a.Value).OrderBy(a => a.Order).ThenBy(a => a.Name));
                        mergeFields.Add("AttributeMatrixItems", attributeMatrix.AttributeMatrixItems.OrderBy(a => a.Order));
                        var medications = lava.ResolveMergeFields(mergeFields);
                        data.Medications = medications;
                    }
                    gridData.Add(data);
                }

                gGrid.DataSource = gridData;
                gGrid.DataBind();
            }
        }
        /// <summary>
        /// Job that will send scheduled group SMS messages.
        ///
        /// 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)
        {
            var dataMap                         = context.JobDetail.JobDataMap;
            int?commandTimeout                  = dataMap.GetString("CommandTimeout").AsIntegerOrNull();
            int?lastRunBuffer                   = dataMap.GetString("LastRunBuffer").AsIntegerOrNull();
            var enabledLavaCommands             = dataMap.GetString("EnabledLavaCommands");
            var JobStartDateTime                = RockDateTime.Now;
            var dateAttributes                  = new List <AttributeValue>();
            var dAttributeMatrixItemAndGroupIds = new Dictionary <int, int>(); // Key: AttributeMatrixItemId   Value: GroupId
            int communicationsSent              = 0;
            var smsMediumType                   = EntityTypeCache.Get("Rock.Communication.Medium.Sms");
            var dateAttributeId                 = Rock.Web.Cache.AttributeCache.Get(KFSConst.Attribute.MATRIX_ATTRIBUTE_SMS_SEND_DATE.AsGuid()).Id;
            var recurrenceAttributeId           = Rock.Web.Cache.AttributeCache.Get(KFSConst.Attribute.MATRIX_ATTRIBUTE_SMS_SEND_RECURRENCE.AsGuid()).Id;
            var fromNumberAttributeId           = Rock.Web.Cache.AttributeCache.Get(KFSConst.Attribute.MATRIX_ATTRIBUTE_SMS_FROM_NUMBER.AsGuid()).Id;
            var messageAttributeId              = Rock.Web.Cache.AttributeCache.Get(KFSConst.Attribute.MATRIX_ATTRIBUTE_SMS_MESSAGE.AsGuid()).Id;

            try
            {
                using (var rockContext = new RockContext())
                {
                    // get the last run date or yesterday
                    DateTime?lastStartDateTime = null;

                    // get job type id
                    int jobId = context.JobDetail.Description.AsInteger();

                    // load job
                    var job = new ServiceJobService(rockContext)
                              .GetNoTracking(jobId);

                    if (job != null && job.Guid != Rock.SystemGuid.ServiceJob.JOB_PULSE.AsGuid())
                    {
                        lastStartDateTime = job.LastRunDateTime?.AddSeconds(0.0d - ( double )(job.LastRunDurationSeconds + lastRunBuffer));
                    }
                    var beginDateTime = lastStartDateTime ?? JobStartDateTime.AddDays(-1);

                    // get the date attributes
                    dateAttributes = new AttributeValueService(rockContext)
                                     .Queryable().AsNoTracking()
                                     .Where(d => d.AttributeId == dateAttributeId &&
                                            d.EntityId.HasValue &&
                                            d.ValueAsDateTime >= beginDateTime &&
                                            d.ValueAsDateTime <= JobStartDateTime)
                                     .ToList();
                }

                foreach (var d in dateAttributes)
                {
                    // Use a new context to limit the amount of change-tracking required
                    using (var rockContext = new RockContext())
                    {
                        var attributeMatrixId = new AttributeMatrixItemService(rockContext)
                                                .GetNoTracking(d.EntityId.Value)
                                                .AttributeMatrixId;

                        var attributeMatrixGuid = new AttributeMatrixService(rockContext)
                                                  .GetNoTracking(attributeMatrixId)
                                                  .Guid
                                                  .ToString();

                        var attributeValue = new AttributeValueService(rockContext)
                                             .Queryable().AsNoTracking()
                                             .FirstOrDefault(a => a.Value.Equals(attributeMatrixGuid, StringComparison.CurrentCultureIgnoreCase));

                        if (attributeValue != null && attributeValue.EntityId.HasValue)
                        {
                            dAttributeMatrixItemAndGroupIds.Add(d.EntityId.Value, attributeValue.EntityId.Value);
                        }
                    }
                }

                foreach (var attributeMatrixItemAndGroupId in dAttributeMatrixItemAndGroupIds)
                {
                    // Use a new context to limit the amount of change-tracking required
                    using (var rockContext = new RockContext())
                    {
                        rockContext.Database.CommandTimeout = commandTimeout;

                        var fromNumberGuid = new AttributeValueService(rockContext)
                                             .GetByAttributeIdAndEntityId(fromNumberAttributeId, attributeMatrixItemAndGroupId.Key)
                                             .Value;
                        var fromNumber = DefinedValueCache.Get(fromNumberGuid.AsGuid());

                        var message = new AttributeValueService(rockContext)
                                      .GetByAttributeIdAndEntityId(messageAttributeId, attributeMatrixItemAndGroupId.Key)
                                      .Value;

                        var attachments = new List <BinaryFile>();

                        var group = new GroupService(rockContext)
                                    .GetNoTracking(attributeMatrixItemAndGroupId.Value);

                        if (!message.IsNullOrWhiteSpace() && smsMediumType != null)
                        {
                            var recipients = new GroupMemberService(rockContext)
                                             .GetByGroupId(attributeMatrixItemAndGroupId.Value).AsNoTracking()
                                             .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                             .ToList();

                            if (recipients.Any())
                            {
                                var communicationService = new CommunicationService(rockContext);

                                var communication = new Rock.Model.Communication();
                                communication.Status                 = CommunicationStatus.Transient;
                                communication.ReviewedDateTime       = JobStartDateTime;
                                communication.ReviewerPersonAliasId  = group.ModifiedByPersonAliasId;
                                communication.SenderPersonAliasId    = group.ModifiedByPersonAliasId;
                                communication.CreatedByPersonAliasId = group.ModifiedByPersonAliasId;
                                communicationService.Add(communication);

                                communication.EnabledLavaCommands = enabledLavaCommands;
                                var personIdHash = new HashSet <int>();
                                foreach (var groupMember in recipients)
                                {
                                    // Use a new context to limit the amount of change-tracking required
                                    using (var groupMemberContext = new RockContext())
                                    {
                                        if (!personIdHash.Contains(groupMember.PersonId))
                                        {
                                            var person = new PersonService(groupMemberContext)
                                                         .GetNoTracking(groupMember.PersonId);

                                            if (person != null && person.PrimaryAliasId.HasValue)
                                            {
                                                personIdHash.Add(groupMember.PersonId);
                                                var communicationRecipient = new CommunicationRecipient();
                                                communicationRecipient.PersonAliasId         = person.PrimaryAliasId;
                                                communicationRecipient.AdditionalMergeValues = new Dictionary <string, object>();
                                                communicationRecipient.AdditionalMergeValues.Add("GroupMember", groupMember);
                                                //communicationRecipient.AdditionalMergeValues.Add( "Group", group );
                                                communication.Recipients.Add(communicationRecipient);
                                            }
                                        }
                                    }
                                }

                                communication.IsBulkCommunication     = false;
                                communication.CommunicationType       = CommunicationType.SMS;
                                communication.CommunicationTemplateId = null;

                                foreach (var recipient in communication.Recipients)
                                {
                                    recipient.MediumEntityTypeId = smsMediumType.Id;
                                }

                                communication.SMSMessage            = message;
                                communication.SMSFromDefinedValueId = fromNumber.Id;
                                communication.Subject = string.Empty;
                                communication.Status  = CommunicationStatus.Approved;

                                rockContext.SaveChanges();

                                Rock.Model.Communication.Send(communication);

                                communicationsSent = communicationsSent + personIdHash.Count;

                                var recurrence = new AttributeValueService(rockContext)
                                                 .GetByAttributeIdAndEntityId(recurrenceAttributeId, attributeMatrixItemAndGroupId.Key);

                                if (recurrence != null && !string.IsNullOrWhiteSpace(recurrence.Value))
                                {
                                    var sendDate = new AttributeValueService(rockContext)
                                                   .GetByAttributeIdAndEntityId(dateAttributeId, attributeMatrixItemAndGroupId.Key);

                                    switch (recurrence.Value)
                                    {
                                    case "1":
                                        sendDate.Value = sendDate.ValueAsDateTime.Value.AddDays(7).ToString();
                                        break;

                                    case "2":
                                        sendDate.Value = sendDate.ValueAsDateTime.Value.AddDays(14).ToString();
                                        break;

                                    case "3":
                                        sendDate.Value = sendDate.ValueAsDateTime.Value.AddMonths(1).ToString();
                                        break;

                                    case "4":
                                        sendDate.Value = sendDate.ValueAsDateTime.Value.AddDays(1).ToString();
                                        break;

                                    default:
                                        break;
                                    }
                                    rockContext.SaveChanges();
                                }
                            }
                        }
                    }
                }

                if (communicationsSent > 0)
                {
                    context.Result = string.Format("Sent {0} {1}", communicationsSent, "communication".PluralizeIf(communicationsSent > 1));
                }
                else
                {
                    context.Result = "No communications to send";
                }
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);
            var matrixAttributeMedicationKey   = GetAttributeValue(action, "MatrixAttributeMedicationKey");
            var matrixAttributeInstructionsKey = GetAttributeValue(action, "MatrixAttributeInstructionsKey");
            var matrixAttributeScheduleKey     = GetAttributeValue(action, "MatrixAttributeScheduleKey");

            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);
            GroupMemberService     groupMemberService     = new GroupMemberService(rockContext);

            if (checkInState != null)
            {
                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    var commonMergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

                    var people = family.GetPeople(true);
                    foreach (var person in people.Where(p => p.Selected))
                    {
                        foreach (var groupType in person.GroupTypes)
                        {
                            groupType.Labels = new List <CheckInLabel>();


                            foreach (var group in groupType.Groups)
                            {
                                List <string> medicationText   = (( string )GetAttributeValue(action, "MedicationText")).Split(',').ToList();
                                List <string> instructionsText = (( string )GetAttributeValue(action, "InstructionsText")).Split(',').ToList();

                                List <MedInfo> medInfos = new List <MedInfo>();
                                if (medicationText.Count == instructionsText.Count)
                                {
                                    for (int i = 0; i < medicationText.Count; i++)
                                    {
                                        medInfos.Add(new MedInfo {
                                            Medication = medicationText[i], Instructions = instructionsText[i]
                                        });
                                    }
                                }

                                group.Group.LoadAttributes();
                                var groupGuid         = group.Group.GetAttributeValue(GetAttributeValue(action, "GroupAttributeKey"));
                                var registrationGroup = new GroupService(rockContext).Get(groupGuid.AsGuid());
                                if (registrationGroup == null)
                                {
                                    continue;
                                }

                                var groupMember = groupMemberService.GetByGroupIdAndPersonId(registrationGroup.Id, person.Person.Id).FirstOrDefault();

                                var medicationKey    = GetAttributeValue(action, "MatrixAttributeKey");
                                var medicationMatrix = person.Person.GetAttributeValue(medicationKey);


                                var attributeMatrix = attributeMatrixService.Get(medicationMatrix.AsGuid());

                                var labelCache = KioskLabel.Get(new Guid(GetAttributeValue(action, "MedicationLabel")));

                                //Set up merge fields so we can use the lava from the merge fields
                                var mergeObjects = new Dictionary <string, object>();
                                foreach (var keyValue in commonMergeFields)
                                {
                                    mergeObjects.Add(keyValue.Key, keyValue.Value);
                                }

                                mergeObjects.Add("RegistrationGroup", registrationGroup);
                                mergeObjects.Add("RegistrationGroupMember", groupMember);
                                mergeObjects.Add("Group", group);
                                mergeObjects.Add("Person", person);
                                mergeObjects.Add("People", people);
                                mergeObjects.Add("GroupType", groupType);

                                if (attributeMatrix == null || attributeMatrix.AttributeMatrixItems.Count == 0)
                                {
                                    // Add a No Medication Information label for anyone without data
                                    var checkInLabel = new CheckInLabel(labelCache, mergeObjects);

                                    var index = 0;
                                    foreach (string mergeFieldText in medicationText)
                                    {
                                        checkInLabel.MergeFields.Add(mergeFieldText, index == 0 ? "No Medication Information Found" : "");
                                        checkInLabel.MergeFields.Add(instructionsText[index], "");
                                        index++;
                                    }
                                    addLabel(checkInLabel, checkInState, groupType, group, rockContext);
                                }
                                else
                                {
                                    var items = attributeMatrix.AttributeMatrixItems.ToList();
                                    var index = 0;

                                    while (index < items.Count)
                                    {
                                        var checkInLabel = new CheckInLabel(labelCache, mergeObjects);

                                        foreach (var med in medInfos)
                                        {
                                            if (items.Count > index)
                                            {
                                                items[index].LoadAttributes();

                                                string scheduleText = "";
                                                string separator    = "";
                                                var    schedule     = items[index].GetAttributeValue(matrixAttributeScheduleKey).SplitDelimitedValues();
                                                foreach (var scheduleGuid in schedule)
                                                {
                                                    scheduleText += separator + DefinedValueCache.Get(scheduleGuid);
                                                    separator     = ", ";
                                                }

                                                checkInLabel.MergeFields.Add(med.Medication,
                                                                             items[index].GetAttributeValue(matrixAttributeMedicationKey)
                                                                             + " - "
                                                                             + scheduleText
                                                                             );

                                                checkInLabel.MergeFields.Add(med.Instructions, items[index].GetAttributeValue(matrixAttributeInstructionsKey));
                                            }
                                            else
                                            {
                                                checkInLabel.MergeFields.Add(med.Medication, "");
                                                checkInLabel.MergeFields.Add(med.Instructions, "");
                                            }

                                            index++;
                                        }

                                        addLabel(checkInLabel, checkInState, groupType, group, rockContext);
                                    }
                                }
                            }
                        }
                    }
                }
                return(true);
            }

            errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null.");
            return(false);
        }
        private List <MedicalItem> GetMedicalItems(bool overrideHideDistributed = false)
        {
            RockContext                rockContext                = new RockContext();
            GroupService               groupService               = new GroupService(rockContext);
            AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
            AttributeValueService      attributeValueService      = new AttributeValueService(rockContext);
            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            NoteService                noteService                = new NoteService(rockContext);

            var groupIdStrings = GetAttributeValue("GroupIds").SplitDelimitedValues();
            var groupIds       = new List <int>();

            foreach (var id in groupIdStrings)
            {
                groupIds.Add(id.AsInteger());
            }

            var groups = groupService.GetByIds(groupIds);

            if (cpCampus.SelectedCampusId != null && cpCampus.SelectedCampusId != 0)
            {
                groups = groups.Where(g => g.CampusId == cpCampus.SelectedCampusId);
            }

            var groupTypeIds = groups.ToList().Select(g => g.GroupTypeId.ToString()).Distinct();

            var personEntityid      = EntityTypeCache.GetId <Rock.Model.Person>().Value;
            var groupMemberEntityid = EntityTypeCache.GetId <Rock.Model.GroupMember>().Value;
            var key = GetAttributeValue("MedicationMatrixKey");

            var days       = GetAttributeValue(AttributeKey.Days).AsIntegerOrNull() ?? 14;
            var cutoffDate = Rock.RockDateTime.Today.AddDays(-days);

            var lastMedicationCheckinAttribute = AttributeCache.Get(Constants.PERSON_ATTRIBUTE_LASTMEDICATIONCHECKIN.AsGuid());


            var allowedPersonIds = attributeValueService.GetByAttributeId(lastMedicationCheckinAttribute.Id)
                                   .Where(av => av.ValueAsDateTime != null && av.ValueAsDateTime >= cutoffDate)
                                   .Select(av => av.EntityId);

            var groupMembers = groups
                               .SelectMany(g => g.Members)
                               .Where(gm => allowedPersonIds.Contains(gm.PersonId));

            AttributeService attributeService = new AttributeService(rockContext);

            List <int> attributeIds = attributeService.Queryable()
                                      .Where(a =>
                                             a.EntityTypeId == personEntityid &&
                                             a.Key == key)
                                      .Select(a => a.Id).ToList();

            if (attributeIds == null)
            {
                nbAlert.Visible = true;
                nbAlert.Text    = "Medication attribute not found";
                return(null);
            }

            List <int> filterAttributeIds = null;
            var        filterAttributeKey = GetAttributeValue("GroupMemberAttributeFilter");

            if (!string.IsNullOrWhiteSpace(filterAttributeKey))
            {
                filterAttributeIds = attributeService.Queryable()
                                     .Where(a =>
                                            (groupIdStrings.Contains(a.EntityTypeQualifierValue) || groupTypeIds.Contains(a.EntityTypeQualifierValue)) &&
                                            a.Key == filterAttributeKey &&
                                            a.EntityTypeId == groupMemberEntityid)
                                     .Select(a => a.Id).ToList();
            }

            var attributeMatrixItemEntityId = EntityTypeCache.GetId <AttributeMatrixItem>();

            var qry = groupMembers
                      .Join(
                attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)),
                m => m.PersonId,
                av => av.EntityId.Value,
                (m, av) => new { Person = m.Person, Member = m, AttributeValue = av.Value }
                )
                      .Join(
                attributeMatrixService.Queryable(),
                m => m.AttributeValue,
                am => am.Guid.ToString(),
                (m, am) => new { Person = m.Person, Member = m.Member, AttributeMatrix = am }
                )
                      .Join(
                attributeMatrixItemService.Queryable(),
                m => m.AttributeMatrix.Id,
                ami => ami.AttributeMatrixId,
                (m, ami) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = ami, TemplateId = ami.AttributeMatrix.AttributeMatrixTemplateId }
                )
                      .Join(
                attributeService.Queryable(),
                m => new { TemplateIdString = m.TemplateId.ToString(), EntityTypeId = attributeMatrixItemEntityId },
                a => new { TemplateIdString = a.EntityTypeQualifierValue, EntityTypeId = a.EntityTypeId },
                (m, a) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = m.AttributeMatrixItem, Attribute = a }
                )
                      .Join(
                attributeValueService.Queryable(),
                m => new { EntityId = m.AttributeMatrixItem.Id, AttributeId = m.Attribute.Id },
                av => new { EntityId = av.EntityId ?? 0, AttributeId = av.AttributeId },
                (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = av, MatrixItemId = m.AttributeMatrixItem.Id, FilterValue = "" }
                );

            if (filterAttributeIds != null && pnlAttribute.Visible && !string.IsNullOrWhiteSpace(ddlAttribute.SelectedValue))
            {
                var filterValue = ddlAttribute.SelectedValue;
                qry = qry
                      .Join(
                    attributeValueService.Queryable().Where(av => filterAttributeIds.Contains(av.AttributeId)),
                    m => new { Id = m.Member.Id, Value = filterValue },
                    av => new { Id = av.EntityId ?? 0, Value = av.Value },
                    (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = m.AttributeValue, MatrixItemId = m.MatrixItemId, FilterValue = av.Value });
            }
            var members = qry.ToList().GroupBy(a => a.Person).ToList();

            var firstDay = (dpDate.SelectedDate ?? Rock.RockDateTime.Today).Date;
            var nextday  = firstDay.AddDays(1);

            var personIds = members.Select(m => m.Key.Id);
            var attributeMatrixEntityTypeId = EntityTypeCache.GetId <AttributeMatrixItem>().Value;

            var noteType = NoteTypeCache.Get(GetAttributeValue("NoteType").AsGuid());

            if (noteType == null)
            {
                return(new List <MedicalItem>());
            }

            var noteItems = noteService.Queryable()
                            .Where(n => n.NoteTypeId == noteType.Id)
                            .Where(n => personIds.Contains(n.EntityId ?? 0))
                            .Where(h => h.CreatedDateTime >= firstDay && h.CreatedDateTime < nextday)
                            .Where(h => h.ForeignId != null)
                            .ToList();

            foreach (var member in members)
            {
                if (!string.IsNullOrWhiteSpace(tbName.Text) &&
                    !member.Key.FullName.ToLower().Contains(tbName.Text.ToLower()) &&
                    !member.Key.FullNameReversed.ToLower().Contains(tbName.Text.ToLower()))
                {
                    continue;
                }

                var medicines = member.GroupBy(m => m.MatrixItemId);
                foreach (var medicine in medicines)
                {
                    var scheduleAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Schedule");
                    if (scheduleAtt == null || scheduleAtt.AttributeValue.Value == null)
                    {
                        continue;
                    }
                    var schedules = scheduleAtt.AttributeValue.Value.SplitDelimitedValues();
                    foreach (var schedule in schedules)
                    {
                        if (ddlSchedule.SelectedValue != "" && ddlSchedule.SelectedValue.AsGuid() != schedule.AsGuid())
                        {
                            continue;
                        }

                        var medicalItem = new MedicalItem()
                        {
                            Person          = member.Key.FullNameReversed,
                            GroupMemberId   = member.Key.Id,
                            GroupMember     = member.Key.Members.FirstOrDefault(),
                            PersonId        = member.Key.Id,
                            FilterAttribute = member.FirstOrDefault().FilterValue,
                        };

                        if (!string.IsNullOrWhiteSpace(schedule))
                        {
                            var dv = DefinedValueCache.Get(schedule.AsGuid());
                            if (dv != null)
                            {
                                medicalItem.Schedule     = dv.Value;
                                medicalItem.ScheduleGuid = dv.Guid;
                            }
                        }

                        var medAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Medication");
                        if (medAtt != null)
                        {
                            medicalItem.Medication = medAtt.AttributeValue.Value;
                        }

                        var instructionAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Instructions");
                        if (instructionAtt != null)
                        {
                            medicalItem.Instructions = instructionAtt.AttributeValue.Value;
                        }
                        medicalItem.Key = string.Format("{0}|{1}|{2}", medicalItem.PersonId, medicine.Key, medicalItem.ScheduleGuid);

                        var notes = noteItems
                                    .Where(n => n.EntityId == medicalItem.PersonId && n.ForeignId == medicine.Key && n.ForeignGuid == medicalItem.ScheduleGuid);

                        if (notes.Any())
                        {
                            medicalItem.Distributed = true;
                            medicalItem.History     = string.Join("<br>", notes.Select(n => n.Text));
                        }

                        medicalItems.Add(medicalItem);
                    }
                }
                if (overrideHideDistributed == false && cbHideDistributed.Checked == true)
                {
                    medicalItems = medicalItems.Where(i => i.Distributed == false).ToList();
                }
            }

            SortProperty sortProperty = gGrid.SortProperty;

            if (sortProperty != null)
            {
                if (sortProperty.Property == "Person")
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        medicalItems = medicalItems.OrderBy(mi => mi.Person).ToList();
                    }
                    else
                    {
                        medicalItems = medicalItems.OrderByDescending(mi => mi.Person).ToList();
                    }
                }
            }
            else
            {
                medicalItems       = medicalItems.OrderBy(mi => mi.Person).ToList();
                gGrid.SortProperty = new SortProperty()
                {
                    Property = "Person"
                };
            }

            return(medicalItems);
        }
Beispiel #19
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var sourceMatrixAttributeGuid = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "SourceAttributeMatrix").AsGuid()).AsGuidOrNull();
            var targetMatrixAttributeGuid = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "TargetAttributeMatrix").AsGuid()).AsGuidOrNull();

            if (sourceMatrixAttributeGuid.HasValue)
            {
                // Load the source matrix
                AttributeMatrix sourceMatrix = attributeMatrixService.Get(sourceMatrixAttributeGuid.Value);
                AttributeMatrix targetMatrix = null;

                if (targetMatrixAttributeGuid.HasValue)
                {
                    // Just delete all the existing items and add new items from the source attribute
                    targetMatrix = attributeMatrixService.Get(targetMatrixAttributeGuid.Value);
                    targetMatrix.AttributeMatrixItems.Clear();
                }
                else
                {
                    targetMatrix = new AttributeMatrix();
                    targetMatrix.AttributeMatrixItems      = new List <AttributeMatrixItem>();
                    targetMatrix.AttributeMatrixTemplateId = sourceMatrix.AttributeMatrixTemplateId;
                    attributeMatrixService.Add(targetMatrix);
                }

                // Now copy all the items from the source to the target
                foreach (var sourceItem in sourceMatrix.AttributeMatrixItems)
                {
                    var targetItem = new AttributeMatrixItem();
                    sourceItem.LoadAttributes();
                    targetItem.AttributeMatrix = targetMatrix;
                    targetItem.LoadAttributes();
                    foreach (var attribute in sourceItem.AttributeValues)
                    {
                        targetItem.SetAttributeValue(attribute.Key, attribute.Value.Value);
                    }
                    targetMatrix.AttributeMatrixItems.Add(targetItem);
                    rockContext.SaveChanges(true);
                    targetItem.SaveAttributeValues(rockContext);
                }


                // Now store the target attribute
                var targetAttribute = AttributeCache.Get(GetActionAttributeValue(action, "TargetAttributeMatrix").AsGuid(), rockContext);
                if (targetAttribute.EntityTypeId == new Rock.Model.Workflow().TypeId)
                {
                    action.Activity.Workflow.SetAttributeValue(targetAttribute.Key, targetMatrix.Guid.ToString());
                }
                else if (targetAttribute.EntityTypeId == new WorkflowActivity().TypeId)
                {
                    action.Activity.SetAttributeValue(targetAttribute.Key, targetMatrix.Guid.ToString());
                }
            }

            return(true);
        }
        private List <MedicalItem> GetMedicalItems()
        {
            RockContext  rockContext    = new RockContext();
            GroupService groupService   = new GroupService(rockContext);
            var          groupIdStrings = GetAttributeValue("GroupIds").SplitDelimitedValues();
            var          groupIds       = new List <int>();

            foreach (var id in groupIdStrings)
            {
                groupIds.Add(id.AsInteger());
            }

            var groups = groupService.GetByIds(groupIds);

            var groupTypeIds = groups.ToList().Select(g => g.GroupTypeId.ToString()).Distinct();

            var groupEntityid = EntityTypeCache.GetId <Rock.Model.GroupMember>();
            var key           = GetAttributeValue("MedicationMatrixKey");

            AttributeService attributeService = new AttributeService(rockContext);

            List <int> attributeIds = attributeService.Queryable()
                                      .Where(a =>
                                             (groupIdStrings.Contains(a.EntityTypeQualifierValue) || groupTypeIds.Contains(a.EntityTypeQualifierValue)) &&
                                             a.Key == key &&
                                             a.EntityTypeId == groupEntityid)
                                      .Select(a => a.Id).ToList();

            if (attributeIds == null)
            {
                nbAlert.Visible = true;
                nbAlert.Text    = "Medication attribute not found";
                return(null);
            }

            List <int> filterAttributeIds = null;
            var        filterAttributeKey = GetAttributeValue("GroupMemberAttributeFilter");

            if (!string.IsNullOrWhiteSpace(filterAttributeKey))
            {
                filterAttributeIds = attributeService.Queryable()
                                     .Where(a =>
                                            (groupIdStrings.Contains(a.EntityTypeQualifierValue) || groupTypeIds.Contains(a.EntityTypeQualifierValue)) &&
                                            a.Key == filterAttributeKey &&
                                            a.EntityTypeId == groupEntityid)
                                     .Select(a => a.Id).ToList();
            }

            var attributeMatrixItemEntityId = EntityTypeCache.GetId <AttributeMatrixItem>();

            AttributeValueService      attributeValueService      = new AttributeValueService(rockContext);
            AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            HistoryService             historyService             = new HistoryService(rockContext);

            var qry = new GroupMemberService(rockContext).Queryable()
                      .Join(
                attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)),
                m => m.Id,
                av => av.EntityId.Value,
                (m, av) => new { Member = m, AttributeValue = av.Value }
                )
                      .Join(
                attributeMatrixService.Queryable(),
                m => m.AttributeValue,
                am => am.Guid.ToString(),
                (m, am) => new { Member = m.Member, AttributeMatrix = am }
                )
                      .Join(
                attributeMatrixItemService.Queryable(),
                m => m.AttributeMatrix.Id,
                ami => ami.AttributeMatrixId,
                (m, ami) => new { Member = m.Member, AttributeMatrixItem = ami, TemplateId = ami.AttributeMatrix.AttributeMatrixTemplateId }
                )
                      .Join(
                attributeService.Queryable(),
                m => new { TemplateIdString = m.TemplateId.ToString(), EntityTypeId = attributeMatrixItemEntityId },
                a => new { TemplateIdString = a.EntityTypeQualifierValue, EntityTypeId = a.EntityTypeId },
                (m, a) => new { Member = m.Member, AttributeMatrixItem = m.AttributeMatrixItem, Attribute = a }
                )
                      .Join(
                attributeValueService.Queryable(),
                m => new { EntityId = m.AttributeMatrixItem.Id, AttributeId = m.Attribute.Id },
                av => new { EntityId = av.EntityId ?? 0, AttributeId = av.AttributeId },
                (m, av) => new { Member = m.Member, Attribute = m.Attribute, AttributeValue = av, MatrixItemId = m.AttributeMatrixItem.Id, FilterValue = "" }
                ).
                      Where(obj => groupIds.Contains(obj.Member.GroupId));

            if (filterAttributeIds != null && pnlAttribute.Visible && !string.IsNullOrWhiteSpace(ddlAttribute.SelectedValue))
            {
                var filterValue = ddlAttribute.SelectedValue;
                qry = qry
                      .Join(
                    attributeValueService.Queryable().Where(av => filterAttributeIds.Contains(av.AttributeId)),
                    m => new { Id = m.Member.Id, Value = filterValue },
                    av => new { Id = av.EntityId ?? 0, Value = av.Value },
                    (m, av) => new { Member = m.Member, Attribute = m.Attribute, AttributeValue = m.AttributeValue, MatrixItemId = m.MatrixItemId, FilterValue = av.Value });
            }
            var members = qry.ToList().GroupBy(a => a.Member).ToList();

            var firstDay = (dpDate.SelectedDate ?? Rock.RockDateTime.Today).Date;
            var nextday  = firstDay.AddDays(1);

            var personIds = members.Select(m => m.Key.PersonId);
            var attributeMatrixEntityTypeId = EntityTypeCache.GetId <AttributeMatrixItem>().Value;

            var historyItems = historyService.Queryable()
                               .Where(h => personIds.Contains(h.EntityId))
                               .Where(h => h.RelatedEntityTypeId == attributeMatrixEntityTypeId)
                               .Where(h => h.CreatedDateTime >= firstDay && h.CreatedDateTime < nextday)
                               .ToList();

            foreach (var member in members)
            {
                if (!string.IsNullOrWhiteSpace(tbName.Text) &&
                    !member.Key.Person.FullName.ToLower().Contains(tbName.Text.ToLower()) &&
                    !member.Key.Person.FullNameReversed.ToLower().Contains(tbName.Text.ToLower()))
                {
                    continue;
                }

                var medicines = member.GroupBy(m => m.MatrixItemId);
                foreach (var medicine in medicines)
                {
                    var scheduleAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Schedule");
                    var schedules   = scheduleAtt.AttributeValue.Value.SplitDelimitedValues();
                    foreach (var schedule in schedules)
                    {
                        if (ddlSchedule.SelectedValue != "" && ddlSchedule.SelectedValue.AsGuid() != schedule.AsGuid())
                        {
                            continue;
                        }

                        var medicalItem = new MedicalItem()
                        {
                            Person          = member.Key.Person.FullNameReversed,
                            GroupMemberId   = member.Key.Id,
                            GroupMember     = member.FirstOrDefault().Member,
                            PersonId        = member.Key.Person.Id,
                            FilterAttribute = member.FirstOrDefault().FilterValue
                        };

                        if (!string.IsNullOrWhiteSpace(schedule))
                        {
                            var dv = DefinedValueCache.Read(schedule.AsGuid());
                            if (dv != null)
                            {
                                medicalItem.Schedule     = dv.Value;
                                medicalItem.ScheduleGuid = dv.Guid;
                            }
                        }

                        var medAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Medication");
                        if (medAtt != null)
                        {
                            medicalItem.Medication = medAtt.AttributeValue.Value;
                        }

                        var instructionAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Instructions");
                        if (instructionAtt != null)
                        {
                            medicalItem.Instructions = instructionAtt.AttributeValue.Value;
                        }
                        medicalItem.Key = string.Format("{0}|{1}|{2}", medicalItem.PersonId, medicine.Key, medicalItem.ScheduleGuid);

                        var history = historyItems.Where(h => h.EntityId == medicalItem.PersonId && h.RelatedEntityId == medicine.Key && (string.IsNullOrWhiteSpace(h.RelatedData) || h.RelatedData.AsGuid() == medicalItem.ScheduleGuid));
                        if (history.Any())
                        {
                            medicalItem.Distributed = true;
                            medicalItem.History     = string.Join("<br>", history.Select(h => h.Summary));
                        }
                        medicalItems.Add(medicalItem);
                    }
                }
            }

            SortProperty sortProperty = gGrid.SortProperty;

            if (sortProperty != null)
            {
                if (sortProperty.Property == "Person")
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        medicalItems = medicalItems.OrderBy(mi => mi.Person).ToList();
                    }
                    else
                    {
                        medicalItems = medicalItems.OrderByDescending(mi => mi.Person).ToList();
                    }
                }
            }
            else
            {
                medicalItems       = medicalItems.OrderBy(mi => mi.Person).ToList();
                gGrid.SortProperty = new SortProperty()
                {
                    Property = "Person"
                };
            }

            return(medicalItems);
        }