Ejemplo n.º 1
0
        /// <summary>
        /// Handles the Click event of the btnSaveMatrixItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnSaveMatrixItem_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            var attributeMatrixItemService          = new AttributeMatrixItemService(rockContext);
            AttributeMatrixItem attributeMatrixItem = null;
            int attributeMatrixItemId = _hfMatrixItemId.Value.AsInteger();

            if (attributeMatrixItemId > 0)
            {
                attributeMatrixItem = attributeMatrixItemService.Get(attributeMatrixItemId);
            }

            if (attributeMatrixItem == null)
            {
                attributeMatrixItem = new AttributeMatrixItem();
                attributeMatrixItem.AttributeMatrix = new AttributeMatrixService(rockContext).Get(this.AttributeMatrixGuid.Value);
                attributeMatrixItemService.Add(attributeMatrixItem);
            }

            attributeMatrixItem.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(_phMatrixItemAttributes, attributeMatrixItem);
            rockContext.SaveChanges();
            attributeMatrixItem.SaveAttributeValues(rockContext);

            _gMatrixItems.Visible      = true;
            _pnlEditMatrixItem.Visible = false;

            BindGrid(this.AttributeMatrixGuid);
        }
        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);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Edits the matrix item.
        /// </summary>
        /// <param name="matrixItemId">The matrix item identifier.</param>
        private void EditMatrixItem(int matrixItemId)
        {
            _hfMatrixItemId.Value = matrixItemId.ToString();

            // make a temp attributeMatrixItem to see what Attributes they have
            AttributeMatrixItem attributeMatrixItem = null;

            using (var rockContext = new RockContext())
            {
                if (matrixItemId > 0)
                {
                    attributeMatrixItem = new AttributeMatrixItemService(rockContext).Get(matrixItemId);
                }

                if (attributeMatrixItem == null)
                {
                    attributeMatrixItem = new AttributeMatrixItem();
                    attributeMatrixItem.AttributeMatrix = new AttributeMatrixService(rockContext).Get(this.AttributeMatrixGuid.Value);
                }

                if (this.AttributeMatrixTemplateId.HasValue && attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplateId != this.AttributeMatrixTemplateId)
                {
                    attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplateId = this.AttributeMatrixTemplateId.Value;
                    attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplate   = new AttributeMatrixTemplateService(rockContext).Get(attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplateId);
                }

                attributeMatrixItem.LoadAttributes();
            }

            _phMatrixItemAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls(attributeMatrixItem, _phMatrixItemAttributes, true, GetValidationGroupForAttributeControls());

            _gMatrixItems.Visible      = false;
            _pnlEditMatrixItem.Visible = true;
        }
Ejemplo n.º 4
0
        protected void Distribute_Click(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            RockContext    rockContext    = new RockContext();
            HistoryService historyService = new HistoryService(rockContext);
            var            keys           = (( string )e.RowKeyValue).SplitDelimitedValues();
            var            personId       = keys[0].AsInteger();
            var            matrixId       = keys[1].AsInteger();
            var            scheduleGuid   = keys[2].AsGuid();

            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            var matrix = attributeMatrixItemService.Get(matrixId);

            matrix.LoadAttributes();
            var category = new CategoryService(rockContext).Get(GetAttributeValue("HistoryCategory").AsGuid());

            History history = new History()
            {
                CategoryId          = category.Id,
                EntityTypeId        = EntityTypeCache.GetId <Person>().Value,
                EntityId            = personId,
                RelatedEntityTypeId = EntityTypeCache.GetId <AttributeMatrixItem>().Value,
                RelatedEntityId     = matrixId,
                Verb        = "Distributed",
                Caption     = "Medication Distributed",
                Summary     = string.Format("<span class=\"field-name\">{0}</span> was distributed at <span class=\"field-name\">{1}</span>", matrix.GetAttributeValue("Medication"), Rock.RockDateTime.Now),
                RelatedData = scheduleGuid.ToString()
            };

            historyService.Add(history);
            rockContext.SaveChanges();
            BindGrid();
        }
Ejemplo n.º 5
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;
                }
            }
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Handles the Click event of the deleteField control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        private void gMatrixItems_DeleteClick(object sender, RowEventArgs e)
        {
            int attributeMatrixItemId = e.RowKeyId;
            var rockContext           = new RockContext();
            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            AttributeMatrixItem        attributeMatrixItem        = attributeMatrixItemService.Get(attributeMatrixItemId);

            if (attributeMatrixItem != null)
            {
                var attributeMatrix = attributeMatrixItem.AttributeMatrix;
                attributeMatrixItemService.Delete(attributeMatrixItem);
                rockContext.SaveChanges();

                BindGrid(this.AttributeMatrixGuid);
            }
        }
Ejemplo n.º 8
0
        protected void mdEdit_SaveClick(object sender, EventArgs e)
        {
            RockContext rockContext  = new RockContext();
            NoteService noteService  = new NoteService(rockContext);
            var         keys         = (ddlMatrixItem.SelectedValue).SplitDelimitedValues();
            var         personId     = keys[0].AsInteger();
            var         matrixId     = keys[1].AsInteger();
            var         scheduleGuid = keys[2].AsGuid();

            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            var matrix = attributeMatrixItemService.Get(matrixId);

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


            var noteId = hfNoteId.ValueAsInt();
            var note   = noteService.Get(noteId);

            if (note == null)
            {
                note = new Note
                {
                    NoteTypeId  = noteType.Id,
                    EntityId    = personId,
                    ForeignId   = matrixId,
                    ForeignGuid = scheduleGuid,
                    Caption     = "Medication Distributed"
                };
                noteService.Add(note);
            }

            note.Text = string.Format(
                "<span class=\"field-name\">{0}</span> was distributed at <span class=\"field-name\">{1}</span>",
                matrix.GetAttributeValue("Medication"),
                dtpDateTime.SelectedDateTime.Value);

            note.CreatedDateTime = dtpDateTime.SelectedDateTime.Value;

            rockContext.SaveChanges(true);

            mdEdit.Hide();
            ShowNotesModal(hfPersonId.ValueAsInt());
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Edits the matrix item.
        /// </summary>
        /// <param name="matrixItemId">The matrix item identifier.</param>
        private void EditMatrixItem(int matrixItemId)
        {
            _hfMatrixItemId.Value = matrixItemId.ToString();

            // make a temp attributeMatrixItem to see what Attributes they have
            AttributeMatrixItem attributeMatrixItem = null;

            using (var rockContext = new RockContext())
            {
                if (matrixItemId > 0)
                {
                    attributeMatrixItem = new AttributeMatrixItemService(rockContext).Get(matrixItemId);
                }

                if (attributeMatrixItem == null)
                {
                    attributeMatrixItem = new AttributeMatrixItem();
                    attributeMatrixItem.AttributeMatrix = new AttributeMatrixService(rockContext).Get(this.AttributeMatrixGuid.Value);
                }

                if (this.AttributeMatrixTemplateId.HasValue && attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplateId != this.AttributeMatrixTemplateId)
                {
                    attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplateId = this.AttributeMatrixTemplateId.Value;
                    attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplate   = new AttributeMatrixTemplateService(rockContext).Get(attributeMatrixItem.AttributeMatrix.AttributeMatrixTemplateId);
                }

                attributeMatrixItem.LoadAttributes();
            }

            _phMatrixItemAttributes.Controls.Clear();

            // set the validation group on the controls and save button
            string validationGroup = GetValidationGroupForAttributeControls();

            Rock.Attribute.Helper.AddEditControls(attributeMatrixItem, _phMatrixItemAttributes, true, validationGroup);

            // Make sure to set the validategroup on the save button to match, just in case it changed since CreateChildControls
            _btnSaveMatrixItem.ValidationGroup = validationGroup;

            _gMatrixItems.Visible      = false;
            _pnlEditMatrixItem.Visible = true;
        }
Ejemplo n.º 10
0
        protected void Distribute_Click(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            RockContext rockContext  = new RockContext();
            NoteService noteService  = new NoteService(rockContext);
            var         keys         = (( string )e.RowKeyValue).SplitDelimitedValues();
            var         personId     = keys[0].AsInteger();
            var         matrixId     = keys[1].AsInteger();
            var         scheduleGuid = keys[2].AsGuid();

            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            var matrix = attributeMatrixItemService.Get(matrixId);

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

            Note history = new Note()
            {
                NoteTypeId  = noteType.Id,
                EntityId    = personId,
                ForeignId   = matrixId,
                Caption     = "Medication Distributed",
                Text        = string.Format("<span class=\"field-name\">{0}</span> was distributed at <span class=\"field-name\">{1}</span>", matrix.GetAttributeValue("Medication"), Rock.RockDateTime.Now),
                ForeignGuid = scheduleGuid
            };

            noteService.Add(history);
            rockContext.SaveChanges();

            //for clicking distribute after the fact
            if (dpDate.SelectedDate.HasValue && dpDate.SelectedDate.Value.Date != Rock.RockDateTime.Today)
            {
                history.CreatedDateTime = dpDate.SelectedDate.Value;
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <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;
            }
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Migrates a baptism record from a Attribute Matrix Item to a Step
        /// </summary>
        /// <param name="itemId">Matrix Item Id</param>
        /// <param name="personId">The Person Id of the person who was baptized.</param>
        /// <returns></returns>
        private bool MigrateBaptismItem(int itemId, int personId)
        {
            using (var context = new RockContext())
            {
                var matrixItem = new AttributeMatrixItemService(context).Get(itemId);

                var person = new PersonService(context).Get(personId);

                if (matrixItem == null)
                {
                    results["Fail"] += String.Format("Failed Migration {0} - {1}, baptism matrix item not found.",
                                                     itemId,
                                                     person != null ? person.FullName : "Unknown") + Environment.NewLine;
                    return(false);
                }



                matrixItem.LoadAttributes(context);
                var campusGuid      = matrixItem.GetAttributeValue("BaptismLocation").AsGuidOrNull();
                var baptismDate     = matrixItem.GetAttributeValue("BaptismDate").AsDateTime();
                var baptizedBy      = matrixItem.GetAttributeValue("BaptizedBy");
                var baptismTypeGuid = matrixItem.GetAttributeValue("BaptismType").AsGuidOrNull();


                var stepService = new StepService(context);



                var step = stepService.Queryable()
                           .Where(s => s.ForeignId == itemId)
                           .Where(s => s.PersonAlias.PersonId == personId)
                           .SingleOrDefault();

                if (step == null)
                {
                    step = new Step()
                    {
                        StepTypeId    = BaptismStepType.Id,
                        PersonAliasId = person.PrimaryAliasId.Value,
                        ForeignId     = matrixItem.Id
                    };

                    stepService.Add(step);
                }

                if (baptismDate >= new DateTime(1753, 1, 1))     //datetime minimum date
                {
                    step.StartDateTime     = baptismDate;
                    step.CompletedDateTime = baptismDate;
                }

                step.StepStatusId = StepStatus.Id;

                if (campusGuid.HasValue)
                {
                    step.CampusId = CampusCache.Get(campusGuid.Value).Id;
                }

                context.SaveChanges();
                step.LoadAttributes(context);

                step.SetAttributeValue("BaptismType", baptismTypeGuid);

                if (baptizedBy.IsNotNullOrWhiteSpace())
                {
                    step.SetAttributeValue("BaptizedBy", baptizedBy);
                }
                else
                {
                    step.SetAttributeValue("BaptizedBy", null);
                }

                step.SaveAttributeValues(context);

                results["Success"] += String.Format("Successfully migrated baptism item {0}-{1} for {2}.",
                                                    matrixItem.Id,
                                                    baptismTypeGuid.HasValue ? DefinedValueCache.Get(baptismTypeGuid.Value).Value : "Unknown Type",
                                                    person != null ? person.FullName : "Unknown") + Environment.NewLine;

                return(true);
            }
        }
Ejemplo n.º 15
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);
        }