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);
        }
        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);
        }
Esempio n. 3
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);
        }