Ejemplo n.º 1
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var errors      = new List <string>();
            var rockContext = new RockContext();

            JobDataMap dataMap         = context.JobDetail.JobDataMap;
            Guid?      systemEmailGuid = dataMap.GetString("NotificationEmailTemplate").AsGuidOrNull();

            if (systemEmailGuid.HasValue)
            {
                var selectedGroupTypes = new List <Guid>();
                if (!string.IsNullOrWhiteSpace(dataMap.GetString("GroupTypes")))
                {
                    selectedGroupTypes = dataMap.GetString("GroupTypes").Split(',').Select(Guid.Parse).ToList();
                }

                var notificationOption = dataMap.GetString("NotifyParentLeaders").ConvertToEnum <NotificationOption>(NotificationOption.None);

                var accountAbilityGroupGuid = dataMap.GetString("AccountabilityGroup").AsGuid();

                var groupRequirementsQry = new GroupRequirementService(rockContext).Queryable();


                // get groups matching of the types provided
                GroupService groupService = new GroupService(rockContext);
                var          groups       = groupService.Queryable().AsNoTracking()
                                            .Where(g => selectedGroupTypes.Contains(g.GroupType.Guid) &&
                                                   g.IsActive == true &&
                                                   groupRequirementsQry.Any(a => (a.GroupId.HasValue && a.GroupId == g.Id) || (a.GroupTypeId.HasValue && a.GroupTypeId == g.GroupTypeId)));

                foreach (var group in groups)
                {
                    // check for members that don't meet requirements
                    var groupMembersWithIssues = groupService.GroupMembersNotMeetingRequirements(group, true);

                    if (groupMembersWithIssues.Count > 0)
                    {
                        // add issues to issue list
                        GroupsMissingRequirements groupMissingRequirements = new GroupsMissingRequirements();
                        groupMissingRequirements.Id   = group.Id;
                        groupMissingRequirements.Name = group.Name;
                        if (group.GroupType != null)
                        {
                            groupMissingRequirements.GroupTypeId   = group.GroupTypeId;
                            groupMissingRequirements.GroupTypeName = group.GroupType.Name;
                        }
                        groupMissingRequirements.AncestorPathName = groupService.GroupAncestorPathName(group.Id);

                        // get list of the group leaders
                        groupMissingRequirements.Leaders = group.Members
                                                           .Where(m => m.GroupRole.ReceiveRequirementsNotifications)
                                                           .Select(m => new GroupMemberResult
                        {
                            Id       = m.Id,
                            PersonId = m.PersonId,
                            FullName = m.Person.FullName
                        })
                                                           .ToList();


                        List <GroupMembersMissingRequirements> groupMembers = new List <GroupMembersMissingRequirements>();

                        foreach (var groupMemberIssue in groupMembersWithIssues)
                        {
                            GroupMembersMissingRequirements groupMember = new GroupMembersMissingRequirements();
                            groupMember.FullName        = groupMemberIssue.Key.Person.FullName;
                            groupMember.Id              = groupMemberIssue.Key.Id;
                            groupMember.PersonId        = groupMemberIssue.Key.PersonId;
                            groupMember.GroupMemberRole = groupMemberIssue.Key.GroupRole.Name;

                            List <MissingRequirement> missingRequirements = new List <MissingRequirement>();

                            // Now find exactly which ISSUE corresponds to the group member based on their role
                            foreach (var issue in groupMemberIssue.Value)
                            {
                                // If the issue is tied to a role, does it match the person's role?
                                // If it does not, skip it.
                                if (issue.Key.GroupRequirement.GroupRoleId != null && issue.Key.GroupRequirement.GroupRoleId != groupMemberIssue.Key.GroupRoleId)
                                {
                                    continue;
                                }

                                MissingRequirement missingRequirement = new MissingRequirement();
                                missingRequirement.Id             = issue.Key.GroupRequirement.GroupRequirementType.Id;
                                missingRequirement.Name           = issue.Key.GroupRequirement.GroupRequirementType.Name;
                                missingRequirement.Status         = issue.Key.MeetsGroupRequirement;
                                missingRequirement.OccurrenceDate = issue.Value;

                                switch (issue.Key.MeetsGroupRequirement)
                                {
                                case MeetsGroupRequirement.Meets:
                                    missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.PositiveLabel;
                                    break;

                                case MeetsGroupRequirement.MeetsWithWarning:
                                    missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.WarningLabel;
                                    break;

                                case MeetsGroupRequirement.NotMet:
                                    missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.NegativeLabel;
                                    break;
                                }

                                missingRequirements.Add(missingRequirement);
                            }

                            groupMember.MissingRequirements = missingRequirements;

                            groupMembers.Add(groupMember);
                        }
                        groupMissingRequirements.GroupMembersMissingRequirements = groupMembers;

                        _groupsMissingRequriements.Add(groupMissingRequirements);

                        // add leaders as people to notify
                        foreach (var leader in group.Members.Where(m => m.GroupRole.ReceiveRequirementsNotifications))
                        {
                            NotificationItem notification = new NotificationItem();
                            notification.GroupId = group.Id;
                            notification.Person  = leader.Person;
                            _notificationList.Add(notification);
                        }

                        // notify parents
                        if (notificationOption != NotificationOption.None)
                        {
                            var parentLeaders = new GroupMemberService(rockContext).Queryable("Person").AsNoTracking()
                                                .Where(m => m.GroupRole.ReceiveRequirementsNotifications);

                            if (notificationOption == NotificationOption.DirectParent)
                            {
                                // just the parent group
                                parentLeaders = parentLeaders.Where(m => m.GroupId == group.ParentGroupId);
                            }
                            else
                            {
                                // all parents in the hierarchy
                                var parentIds = groupService.GetAllAncestorIds(group.Id);
                                parentLeaders = parentLeaders.Where(m => parentIds.Contains(m.GroupId));
                            }

                            foreach (var parentLeader in parentLeaders.ToList())
                            {
                                NotificationItem parentNotification = new NotificationItem();
                                parentNotification.Person  = parentLeader.Person;
                                parentNotification.GroupId = group.Id;
                                _notificationList.Add(parentNotification);
                            }
                        }
                    }
                }

                // send out notifications
                int recipients             = 0;
                var notificationRecipients = _notificationList.GroupBy(p => p.Person.Id).ToList();
                foreach (var recipientId in notificationRecipients)
                {
                    var recipient = _notificationList.Where(n => n.Person.Id == recipientId.Key).Select(n => n.Person).FirstOrDefault();

                    if (!recipient.IsEmailActive || recipient.Email.IsNullOrWhiteSpace() || recipient.EmailPreference == EmailPreference.DoNotEmail)
                    {
                        continue;
                    }

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Person", recipient);
                    var notificationGroupIds = _notificationList
                                               .Where(n => n.Person.Id == recipient.Id)
                                               .Select(n => n.GroupId)
                                               .ToList();
                    var missingRequirements = _groupsMissingRequriements.Where(g => notificationGroupIds.Contains(g.Id)).ToList();
                    mergeFields.Add("GroupsMissingRequirements", missingRequirements);

                    var emailMessage = new RockEmailMessage(systemEmailGuid.Value);
                    emailMessage.AddRecipient(new RockEmailMessageRecipient(recipient, mergeFields));
                    var emailErrors = new List <string>();
                    emailMessage.Send(out emailErrors);
                    errors.AddRange(emailErrors);

                    recipients++;
                }

                // add accountability group members
                if (!accountAbilityGroupGuid.IsEmpty())
                {
                    var accountabilityGroupMembers = new GroupMemberService(rockContext).Queryable().AsNoTracking()
                                                     .Where(m => m.Group.Guid == accountAbilityGroupGuid)
                                                     .Select(m => m.Person);

                    var emailMessage = new RockEmailMessage(systemEmailGuid.Value);
                    foreach (var person in accountabilityGroupMembers)
                    {
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        mergeFields.Add("Person", person);
                        mergeFields.Add("GroupsMissingRequirements", _groupsMissingRequriements);
                        emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields));
                        recipients++;
                    }
                    var emailErrors = new List <string>();
                    emailMessage.Send(out emailErrors);
                    errors.AddRange(emailErrors);
                }

                context.Result = string.Format("{0} requirement notification {1} sent", recipients, "email".PluralizeIf(recipients != 1));

                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append(string.Format("{0} Errors: ", errors.Count()));
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    context.Result += errorMessage;
                    var         exception = new Exception(errorMessage);
                    HttpContext context2  = HttpContext.Current;
                    ExceptionLogService.LogException(exception, context2);
                    throw exception;
                }
            }
            else
            {
                context.Result = "Warning: No NotificationEmailTemplate found";
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            int? fromId   = null;
            Guid?fromGuid = GetAttributeValue(action, "From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            var recipients = new List <RecipientData>();

            string toValue = GetAttributeValue(action, "To");
            Guid   guid    = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            recipients.Add(new RecipientData(toAttributeValue));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    string smsNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var recipient = new RecipientData(smsNumber);
                                    recipients.Add(recipient);

                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        string smsNumber = phoneNumber.Number;
                                        if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                        {
                                            smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                        }

                                        var recipient = new RecipientData(smsNumber);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(new RecipientData(toValue.ResolveMergeFields(mergeFields)));
                }
            }

            string message     = GetAttributeValue(action, "Message");
            Guid   messageGuid = message.AsGuid();

            if (!messageGuid.IsEmpty())
            {
                var attribute = AttributeCache.Read(messageGuid, rockContext);
                if (attribute != null)
                {
                    string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid);
                    if (!string.IsNullOrWhiteSpace(messageAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            message = messageAttributeValue;
                        }
                    }
                }
            }

            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid(), rockContext);
                if (mediumEntity != null)
                {
                    var medium = MediumContainer.GetComponent(mediumEntity.Name);
                    if (medium != null && medium.IsActive)
                    {
                        var transport = medium.Transport;
                        if (transport != null && transport.IsActive)
                        {
                            var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot");

                            foreach (var recipient in recipients)
                            {
                                var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                foreach (var mergeField in recipient.MergeFields)
                                {
                                    recipientMergeFields.Add(mergeField.Key, mergeField.Value);
                                }
                                var mediumData = new Dictionary <string, string>();
                                mediumData.Add("FromValue", fromId.Value.ToString());
                                mediumData.Add("Message", message.ResolveMergeFields(recipientMergeFields));

                                var number = new List <string> {
                                    recipient.To
                                };

                                transport.Send(mediumData, number, appRoot, string.Empty);
                            }
                        }
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Loads the entity drop downs.
        /// </summary>
        private void LoadEntityDropDowns()
        {
            if (_financialTransactionDetailList == null)
            {
                return;
            }

            int?entityTypeQualifierValue = this.GetAttributeValue("EntityTypeQualifierValue").AsIntegerOrNull();
            var rockContext = new RockContext();

            Dictionary <int, int?> entityLookup = _financialTransactionDetailList.Where(a => a.EntityId.HasValue).ToDictionary(k => k.Id, v => v.EntityId);

            if (_transactionEntityType != null)
            {
                if (_transactionEntityType.Id == EntityTypeCache.GetId <GroupMember>())
                {
                    int?groupTypeId           = entityTypeQualifierValue;
                    var groupsWithMembersList = new GroupService(new RockContext()).Queryable().Where(a => a.GroupTypeId == groupTypeId.Value && a.Members.Any() && a.IsActive).OrderBy(a => a.Order).ThenBy(a => a.Name).AsNoTracking()
                                                .Select(a => new
                    {
                        a.Id,
                        a.Name
                    })
                                                .ToList();

                    foreach (var ddlGroup in phTableRows.ControlsOfTypeRecursive <RockDropDownList>().Where(a => a.ID.StartsWith("ddlGroup_")))
                    {
                        ddlGroup.Items.Clear();
                        ddlGroup.Items.Add(new ListItem());
                        foreach (var group in groupsWithMembersList)
                        {
                            ddlGroup.Items.Add(new ListItem(group.Name, group.Id.ToString()));
                        }

                        var financialTransactionDetailId = ddlGroup.ID.Replace("ddlGroup_", string.Empty).AsInteger();
                        var ddlGroupMember = phTableRows.ControlsOfTypeRecursive <RockDropDownList>().Where(a => a.ID == "ddlGroupMember_" + financialTransactionDetailId.ToString()).FirstOrDefault() as RockDropDownList;

                        var         groupMemberId = entityLookup.GetValueOrNull(financialTransactionDetailId);
                        GroupMember groupMember   = null;
                        if (groupMemberId.HasValue)
                        {
                            groupMember = new GroupMemberService(rockContext).Get(groupMemberId.Value);
                        }

                        if (groupMember != null)
                        {
                            ddlGroup.SetValue(groupMember.GroupId.ToString());
                            LoadGroupMembersDropDown(ddlGroup);
                            ddlGroupMember.SetValue(groupMember.Id);
                        }
                        else
                        {
                            // if there is no groupMember, make sure the controls don't have anything selected
                            ddlGroup.SetValue((int?)null);
                            ddlGroupMember.Items.Clear();
                            ddlGroupMember.SetValue(( int? )null);
                        }

                        ddlGroupMember.Visible = ddlGroup.SelectedValue.AsIntegerOrNull().HasValue;
                    }
                }
                else if (_transactionEntityType.Id == EntityTypeCache.GetId <Group>())
                {
                    int? groupTypeId         = entityTypeQualifierValue;
                    bool limitToActiveGroups = this.GetAttributeValue("LimitToActiveGroups").AsBoolean();
                    var  groupQry            = new GroupService(new RockContext()).Queryable().Where(a => a.GroupTypeId == groupTypeId.Value && a.IsActive);
                    if (limitToActiveGroups)
                    {
                        groupQry = groupQry.Where(a => a.IsActive == true);
                    }
                    ;

                    var groupList = groupQry.OrderBy(a => a.Order).ThenBy(a => a.Name).AsNoTracking().Select(a =>
                                                                                                             new
                    {
                        a.Id,
                        a.Name
                    })
                                    .ToList();

                    foreach (var ddlGroup in phTableRows.ControlsOfTypeRecursive <RockDropDownList>().Where(a => a.ID.StartsWith("ddlGroup_")))
                    {
                        ddlGroup.Items.Clear();
                        ddlGroup.Items.Add(new ListItem());
                        foreach (var group in groupList)
                        {
                            ddlGroup.Items.Add(new ListItem(group.Name, group.Id.ToString()));
                        }

                        var financialTransactionDetailId = ddlGroup.ID.Replace("ddlGroup_", string.Empty).AsInteger();

                        var groupId = entityLookup.GetValueOrNull(financialTransactionDetailId);
                        if (groupId.HasValue)
                        {
                            ddlGroup.SetValue(groupId);
                        }
                        else
                        {
                            // if there is no value, make sure the controls don't have anything selected
                            ddlGroup.SetValue(( int? )null);
                        }
                    }
                }
                else if (_transactionEntityType.Id == EntityTypeCache.GetId <DefinedValue>())
                {
                    int?definedTypeId    = entityTypeQualifierValue;
                    var definedValueList = DefinedTypeCache.Get(definedTypeId.Value).DefinedValues;

                    foreach (var ddlDefinedValue in phTableRows.ControlsOfTypeRecursive <DefinedValuePicker>().Where(a => a.ID.StartsWith("ddlDefinedValue_")))
                    {
                        ddlDefinedValue.DefinedTypeId = definedTypeId;

                        var financialTransactionDetailId = ddlDefinedValue.ID.Replace("ddlDefinedValue_", string.Empty).AsInteger();

                        var definedValueId = entityLookup.GetValueOrNull(financialTransactionDetailId);
                        if (definedValueId.HasValue)
                        {
                            ddlDefinedValue.SetValue(definedValueId);
                        }
                        else
                        {
                            // if there is no value, make sure the controls don't have anything selected
                            ddlDefinedValue.SetValue(( int? )null);
                        }
                    }
                }
                else if (_transactionEntityType.SingleValueFieldType != null && _transactionEntityType.SingleValueFieldType.Field is IEntityFieldType)
                {
                    foreach (var entityPicker in phTableRows.ControlsOfTypeRecursive <Control>().Where(a => a.ID != null && a.ID.StartsWith("entityPicker_")))
                    {
                        var financialTransactionDetailId = entityPicker.ID.Replace("entityPicker_", string.Empty).AsInteger();

                        var entityId = entityLookup.GetValueOrNull(financialTransactionDetailId);

                        (_transactionEntityType.SingleValueFieldType.Field as IEntityFieldType).SetEditValueFromEntityId(entityPicker, new Dictionary <string, ConfigurationValue>(), entityId);
                    }
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?  groupGuid    = null;
            Person person       = null;
            Group  group        = null;
            string noteValue    = string.Empty;
            string captionValue = string.Empty;
            bool   isAlert      = false;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (group == null)
                    {
                        errorMessages.Add("The group provided does not exist.");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid group provided.");
                }
            }

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorklowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                }
                else
                {
                    errorMessages.Add("The person could not be found!");
                }
            }

            // get caption
            captionValue = GetAttributeValue(action, "Caption");
            guid         = captionValue.AsGuid();
            if (guid.IsEmpty())
            {
                captionValue = captionValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    captionValue = workflowAttributeValue;
                }
            }

            // get group member note
            noteValue = GetAttributeValue(action, "Note");
            guid      = noteValue.AsGuid();
            if (guid.IsEmpty())
            {
                noteValue = noteValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    noteValue = workflowAttributeValue;
                }
            }

            // get alert type
            string isAlertString = GetAttributeValue(action, "IsAlert");

            guid = isAlertString.AsGuid();
            if (guid.IsEmpty())
            {
                isAlert = isAlertString.AsBoolean();
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    isAlert = workflowAttributeValue.AsBoolean();
                }
            }

            // get note type
            NoteTypeCache noteType     = null;
            Guid          noteTypeGuid = GetAttributeValue(action, "NoteType").AsGuid();

            if (!noteTypeGuid.IsEmpty())
            {
                noteType = NoteTypeCache.Read(noteTypeGuid, rockContext);

                if (noteType == null)
                {
                    errorMessages.Add("The note type provided does not exist.");
                }
            }
            else
            {
                errorMessages.Add("Invalid note type provided.");
            }


            // set note
            if (group != null && person != null && noteType != null)
            {
                var groupMembers = new GroupMemberService(rockContext).Queryable()
                                   .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id).ToList();

                if (groupMembers.Count() > 0)
                {
                    foreach (var groupMember in groupMembers)
                    {
                        NoteService noteservice = new NoteService(rockContext);
                        Note        note        = new Note();
                        noteservice.Add(note);

                        note.NoteTypeId = noteType.Id;
                        note.Text       = noteValue;
                        note.IsAlert    = isAlert;
                        note.Caption    = captionValue;
                        note.EntityId   = groupMember.Id;

                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("{0} is not a member of the group {1}.", person.FullName, group.Name));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid()
        {
            if (_group != null)
            {
                pnlGroupMembers.Visible = true;

                using (new UnitOfWorkScope())
                {
                    lHeading.Text = string.Format("{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize());

                    if (_group.GroupType.Roles.Any())
                    {
                        nbRoleWarning.Visible = false;
                        rFilter.Visible       = true;
                        gGroupMembers.Visible = true;

                        // Remove attribute columns
                        foreach (var column in gGroupMembers.Columns.OfType <AttributeField>().ToList())
                        {
                            gGroupMembers.Columns.Remove(column);
                        }

                        // Add attribute columns
                        int    entityTypeId       = new GroupMember().TypeId;
                        string groupQualifier     = _group.Id.ToString();
                        string groupTypeQualifier = _group.GroupTypeId.ToString();
                        foreach (var attribute in new AttributeService().Queryable()
                                 .Where(a =>
                                        a.EntityTypeId == entityTypeId &&
                                        a.IsGridColumn &&
                                        (a.EntityTypeQualifierColumn.Equals("GroupId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(groupQualifier) ||
                                         a.EntityTypeQualifierColumn.Equals("GroupTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(groupTypeQualifier))
                                        )
                                 .OrderBy(a => a.Order)
                                 .ThenBy(a => a.Name))
                        {
                            string dataFieldExpression = attribute.Key;
                            bool   columnExists        = gGroupMembers.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                            if (!columnExists)
                            {
                                AttributeField boundField = new AttributeField();
                                boundField.DataField      = dataFieldExpression;
                                boundField.HeaderText     = attribute.Name;
                                boundField.SortExpression = string.Empty;
                                int insertPos = gGroupMembers.Columns.IndexOf(gGroupMembers.Columns.OfType <DeleteField>().First());
                                gGroupMembers.Columns.Insert(insertPos, boundField);
                            }
                        }

                        GroupMemberService groupMemberService = new GroupMemberService();
                        var qry = groupMemberService.Queryable("Person,GroupRole")
                                  .Where(m => m.GroupId == _group.Id);

                        // Filter by First Name
                        string firstName = rFilter.GetUserPreference("First Name");
                        if (!string.IsNullOrWhiteSpace(firstName))
                        {
                            qry = qry.Where(m => m.Person.FirstName.StartsWith(firstName));
                        }

                        // Filter by Last Name
                        string lastName = rFilter.GetUserPreference("Last Name");
                        if (!string.IsNullOrWhiteSpace(lastName))
                        {
                            qry = qry.Where(m => m.Person.LastName.StartsWith(lastName));
                        }

                        // Filter by role
                        var roles = new List <int>();
                        foreach (string role in rFilter.GetUserPreference("Role").Split(';'))
                        {
                            if (!string.IsNullOrWhiteSpace(role))
                            {
                                int roleId = int.MinValue;
                                if (int.TryParse(role, out roleId))
                                {
                                    roles.Add(roleId);
                                }
                            }
                        }
                        if (roles.Any())
                        {
                            qry = qry.Where(m => roles.Contains(m.GroupRoleId));
                        }

                        // Filter by Sttus
                        var statuses = new List <GroupMemberStatus>();
                        foreach (string status in rFilter.GetUserPreference("Status").Split(';'))
                        {
                            if (!string.IsNullOrWhiteSpace(status))
                            {
                                statuses.Add(status.ConvertToEnum <GroupMemberStatus>());
                            }
                        }
                        if (statuses.Any())
                        {
                            qry = qry.Where(m => statuses.Contains(m.GroupMemberStatus));
                        }

                        SortProperty sortProperty = gGroupMembers.SortProperty;

                        if (sortProperty != null)
                        {
                            gGroupMembers.DataSource = qry.Sort(sortProperty).ToList();
                        }
                        else
                        {
                            gGroupMembers.DataSource = qry.OrderBy(a => a.Person.LastName).ThenBy(a => a.Person.FirstName).ToList();
                        }

                        gGroupMembers.DataBind();
                    }
                    else
                    {
                        nbRoleWarning.Text = string.Format("{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.",
                                                           _group.GroupType.GroupMemberTerm.Pluralize(), _group.GroupType.GroupTerm, _group.GroupType.Name);
                        nbRoleWarning.Visible = true;
                        rFilter.Visible       = false;
                        gGroupMembers.Visible = false;
                    }
                }
            }
            else
            {
                pnlGroupMembers.Visible = false;
            }
        }
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="item">The item.</param>
        protected void SaveChanges(RepeaterItem item)
        {
            var hfGroupId = item.FindControl("hfGroupId") as HiddenField;
            var cbCommunicationListIsSubscribed = item.FindControl("cbCommunicationListIsSubscribed") as RockCheckBox;
            var tglCommunicationPreference      = item.FindControl("tglCommunicationPreference") as Toggle;
            var nbGroupNotification             = item.FindControl("nbGroupNotification") as NotificationBox;

            nbGroupNotification.Visible = false;

            using (var rockContext = new RockContext())
            {
                int groupId            = hfGroupId.Value.AsInteger();
                var groupMemberService = new GroupMemberService(rockContext);
                var group = new GroupService(rockContext).Get(groupId);
                var groupMemberRecordsForPerson = groupMemberService.Queryable().Where(a => a.GroupId == groupId && a.PersonId == this.CurrentPersonId).ToList();
                if (groupMemberRecordsForPerson.Any())
                {
                    // normally there would be at most 1 group member record for the person, but just in case, mark them all
                    foreach (var groupMember in groupMemberRecordsForPerson)
                    {
                        if (cbCommunicationListIsSubscribed.Checked)
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Inactive)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                if (groupMember.Note == "Unsubscribed")
                                {
                                    groupMember.Note = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Inactive;
                                if (groupMember.Note.IsNullOrWhiteSpace())
                                {
                                    groupMember.Note = "Unsubscribed";
                                }
                            }
                        }

                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.CommunicationPreference = communicationType;
                    }
                }
                else
                {
                    // they are not currently in the Group
                    if (cbCommunicationListIsSubscribed.Checked)
                    {
                        var groupMember = new GroupMember();
                        groupMember.PersonId = this.CurrentPersonId.Value;
                        groupMember.GroupId  = group.Id;
                        int?defaultGroupRoleId = GroupTypeCache.Get(group.GroupTypeId).DefaultGroupRoleId;
                        if (defaultGroupRoleId.HasValue)
                        {
                            groupMember.GroupRoleId = defaultGroupRoleId.Value;
                        }
                        else
                        {
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = "Group has no default group role";
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }

                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.CommunicationPreference = communicationType;

                        if (groupMember.IsValidGroupMember(rockContext))
                        {
                            groupMemberService.Add(groupMember);
                            rockContext.SaveChanges();
                        }
                        else
                        {
                            // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }
                    }
                }

                rockContext.SaveChanges();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            ClearErrorMessage();

            if (Page.IsValid)
            {
                GroupMemberService groupMemberService = new GroupMemberService();
                GroupMember        groupMember;

                int groupMemberId = int.Parse(hfGroupMemberId.Value);

                GroupTypeRole role = new GroupTypeRoleService().Get(ddlGroupRole.SelectedValueAsInt() ?? 0);

                //check to see if the user selected a role
                if (role == null)
                {
                    nbErrorMessage.Title = "Please select a Role";
                    return;
                }

                // if adding a new group member
                if (groupMemberId.Equals(0))
                {
                    groupMember = new GroupMember {
                        Id = 0
                    };
                    groupMember.GroupId = hfGroupId.ValueAsInt();

                    //check to see if the person is alread a member of the gorup/role
                    var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId(
                        hfGroupId.ValueAsInt(), ppGroupMemberPerson.SelectedValue ?? 0, ddlGroupRole.SelectedValueAsId() ?? 0);

                    if (existingGroupMember != null)
                    {
                        //if so, don't add and show error message
                        var person = new PersonService().Get((int)ppGroupMemberPerson.PersonId);

                        nbErrorMessage.Title = "Person already added";
                        nbErrorMessage.Text  = string.Format("{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role. <a href=\"/page/{3}?groupMemberId={4}\">Click here</a> to view existing membership.",
                                                             person.FullName,
                                                             ddlGroupRole.SelectedItem.Text,
                                                             role.GroupType.GroupTerm,
                                                             RockPage.PageId,
                                                             existingGroupMember.Id
                                                             );
                        return;
                    }
                }
                else
                {
                    //load existing group member
                    groupMember = groupMemberService.Get(groupMemberId);
                }

                int memberCountInRole = new GroupMemberService().Queryable()
                                        .Where(m =>
                                               m.GroupId == groupMember.GroupId &&
                                               m.GroupRoleId == role.Id &&
                                               m.GroupMemberStatus == GroupMemberStatus.Active)
                                        .Count();

                bool roleMembershipAboveMax = false;

                //if adding new active group member
                if (groupMemberId.Equals(0) && rblStatus.SelectedValueAsEnum <GroupMemberStatus>() == GroupMemberStatus.Active)
                {
                    // verify that active count has not exceeded the max
                    if (role.MaxCount != null && (memberCountInRole + 1) > role.MaxCount)
                    {
                        roleMembershipAboveMax = true;
                    }
                }

                //if existing group member changing role or status
                else if (groupMemberId > 0 && (groupMember.GroupRoleId != role.Id || groupMember.GroupMemberStatus != rblStatus.SelectedValueAsEnum <GroupMemberStatus>()) &&
                         rblStatus.SelectedValueAsEnum <GroupMemberStatus>() == GroupMemberStatus.Active)
                {
                    // verify that active count has not exceeded the max
                    if (role.MaxCount != null && (memberCountInRole + 1) > role.MaxCount)
                    {
                        roleMembershipAboveMax = true;
                    }
                }

                //show error if above max.. do not proceed
                if (roleMembershipAboveMax)
                {
                    var person = new PersonService().Get((int)ppGroupMemberPerson.PersonId);

                    nbErrorMessage.Title = string.Format("Maximum {0} Exceeded", role.Name.Pluralize());
                    nbErrorMessage.Text  = string.Format("<br />The number of {0} for this {1} is at or above its maximum allowed limit of {2:N0} active {3}.",
                                                         role.Name.Pluralize(), role.GroupType.GroupTerm, role.MaxCount,
                                                         role.MaxCount == 1 ? role.GroupType.GroupMemberTerm : role.GroupType.GroupMemberTerm.Pluralize());

                    return;
                }

                groupMember.PersonId          = ppGroupMemberPerson.PersonId.Value;
                groupMember.GroupRoleId       = role.Id;
                groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum <GroupMemberStatus>();

                groupMember.LoadAttributes();

                Rock.Attribute.Helper.GetEditValues(phAttributes, groupMember);

                if (!Page.IsValid)
                {
                    return;
                }

                if (!groupMember.IsValid)
                {
                    return;
                }

                RockTransactionScope.WrapTransaction(() =>
                {
                    if (groupMember.Id.Equals(0))
                    {
                        groupMemberService.Add(groupMember, CurrentPersonId);
                    }

                    groupMemberService.Save(groupMember, CurrentPersonId);
                    Rock.Attribute.Helper.SaveAttributeValues(groupMember, CurrentPersonId);
                });

                Group group = new GroupService().Get(groupMember.GroupId);
                if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
                {
                    Rock.Security.Role.Flush(group.Id);
                    Rock.Security.Authorization.Flush();
                }
            }

            Dictionary <string, string> qryString = new Dictionary <string, string>();

            qryString["groupId"] = hfGroupId.Value;
            NavigateToParentPage(qryString);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Handles the ItemDataBound event of the rptrGroups control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void rptrGroups_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var group = e.Item.DataItem as Group;
                if (group != null)
                {
                    HyperLink hlEditGroup = e.Item.FindControl("hlEditGroup") as HyperLink;
                    if (hlEditGroup != null)
                    {
                        hlEditGroup.Visible = _allowEdit;
                        var pageParams = new Dictionary <string, string>();
                        pageParams.Add("PersonId", Person.Id.ToString());
                        pageParams.Add("GroupId", group.Id.ToString());
                        hlEditGroup.NavigateUrl = LinkedPageUrl("GroupEditPage", pageParams);
                    }

                    var lReorderIcon = e.Item.FindControl("lReorderIcon") as Control;
                    lReorderIcon.Visible = _showReorderIcon;

                    Repeater rptrMembers = e.Item.FindControl("rptrMembers") as Repeater;
                    if (rptrMembers != null)
                    {
                        // use the _bindGroupsRockContext that is created/disposed in BindFamilies()
                        var members = new GroupMemberService(_bindGroupsRockContext).Queryable("GroupRole,Person", true)
                                      .Where(m =>
                                             m.GroupId == group.Id &&
                                             m.PersonId != Person.Id)
                                      .OrderBy(m => m.GroupRole.Order)
                                      .ToList();

                        var groupHeaderLava = GetAttributeValue("GroupHeaderLava");
                        var groupFooterLava = GetAttributeValue("GroupFooterLava");

                        if (groupHeaderLava.IsNotNullOrWhiteSpace() || groupFooterLava.IsNotNullOrWhiteSpace())
                        {
                            // add header and footer information
                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions {
                                GetLegacyGlobalMergeFields = false
                            });
                            mergeFields.Add("Group", group);
                            mergeFields.Add("GroupMembers", members);

                            Literal lGroupHeader = e.Item.FindControl("lGroupHeader") as Literal;
                            Literal lGroupFooter = e.Item.FindControl("lGroupFooter") as Literal;

                            lGroupHeader.Text = groupHeaderLava.ResolveMergeFields(mergeFields);
                            lGroupFooter.Text = groupFooterLava.ResolveMergeFields(mergeFields);
                        }

                        var orderedMembers = new List <GroupMember>();

                        if (_IsFamilyGroupType)
                        {
                            // Add adult males
                            orderedMembers.AddRange(members
                                                    .Where(m => m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)) &&
                                                           m.Person.Gender == Gender.Male)
                                                    .OrderByDescending(m => m.Person.Age));

                            // Add adult females
                            orderedMembers.AddRange(members
                                                    .Where(m => m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)) &&
                                                           m.Person.Gender != Gender.Male)
                                                    .OrderByDescending(m => m.Person.Age));

                            // Add non-adults
                            orderedMembers.AddRange(members
                                                    .Where(m => !m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)))
                                                    .OrderByDescending(m => m.Person.Age));
                        }
                        else
                        {
                            orderedMembers = members
                                             .OrderBy(m => m.GroupRole.Order)
                                             .ThenBy(m => m.Person.LastName)
                                             .ThenBy(m => m.Person.NickName)
                                             .ToList();
                        }
                        rptrMembers.ItemDataBound += rptrMembers_ItemDataBound;
                        rptrMembers.DataSource     = orderedMembers;
                        rptrMembers.DataBind();
                    }

                    Repeater rptrAddresses = e.Item.FindControl("rptrAddresses") as Repeater;
                    if (rptrAddresses != null)
                    {
                        rptrAddresses.ItemDataBound += rptrAddresses_ItemDataBound;
                        rptrAddresses.ItemCommand   += rptrAddresses_ItemCommand;
                        rptrAddresses.DataSource     = new GroupLocationService(_bindGroupsRockContext).Queryable("Location,GroupLocationTypeValue")
                                                       .Where(l => l.GroupId == group.Id)
                                                       .OrderBy(l => l.GroupLocationTypeValue.Order)
                                                       .ToList();
                        rptrAddresses.DataBind();
                    }

                    Panel       pnlGroupAttributes    = e.Item.FindControl("pnlGroupAttributes") as Panel;
                    HyperLink   hlShowMoreAttributes  = e.Item.FindControl("hlShowMoreAttributes") as HyperLink;
                    PlaceHolder phGroupAttributes     = e.Item.FindControl("phGroupAttributes") as PlaceHolder;
                    PlaceHolder phMoreGroupAttributes = e.Item.FindControl("phMoreGroupAttributes") as PlaceHolder;

                    if (pnlGroupAttributes != null && hlShowMoreAttributes != null && phGroupAttributes != null && phMoreGroupAttributes != null)
                    {
                        hlShowMoreAttributes.Visible = false;
                        phGroupAttributes.Controls.Clear();
                        phMoreGroupAttributes.Controls.Clear();

                        group.LoadAttributes();
                        var attributes = group.GetAuthorizedAttributes(Authorization.VIEW, CurrentPerson)
                                         .Select(a => a.Value)
                                         .OrderBy(a => a.Order)
                                         .ToList();

                        foreach (var attribute in attributes)
                        {
                            if (attribute.IsAuthorized(Authorization.VIEW, CurrentPerson))
                            {
                                string value = attribute.DefaultValue;
                                if (group.AttributeValues.ContainsKey(attribute.Key) && group.AttributeValues[attribute.Key] != null)
                                {
                                    value = group.AttributeValues[attribute.Key].ValueFormatted;
                                }

                                if (!string.IsNullOrWhiteSpace(value))
                                {
                                    var literalControl = new RockLiteral();
                                    literalControl.ID    = string.Format("familyAttribute_{0}", attribute.Id);
                                    literalControl.Label = attribute.Name;
                                    literalControl.Text  = value;

                                    var div = new HtmlGenericControl("div");
                                    div.AddCssClass("col-md-3 col-sm-6");
                                    div.Controls.Add(literalControl);

                                    if (attribute.IsGridColumn)
                                    {
                                        phGroupAttributes.Controls.Add(div);
                                    }
                                    else
                                    {
                                        hlShowMoreAttributes.Visible = true;
                                        phMoreGroupAttributes.Controls.Add(div);
                                    }
                                }
                            }
                        }

                        pnlGroupAttributes.Visible = phGroupAttributes.Controls.Count > 0 || phMoreGroupAttributes.Controls.Count > 0;
                    }
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Binds the groups.
        /// </summary>
        private void BindGroups()
        {
            if (Person != null && Person.Id > 0)
            {
                // If this is a Family GroupType and they belong to multiple families,
                // first make sure that the GroupMember.GroupOrder is set for this Person's Families.
                // This will ensure that other spots that rely on the GroupOrder provide consistent results.
                if (this._IsFamilyGroupType)
                {
                    using (var rockContext = new RockContext())
                    {
                        var memberService     = new GroupMemberService(rockContext);
                        var groupMemberGroups = memberService.Queryable(true)
                                                .Where(m =>
                                                       m.PersonId == Person.Id &&
                                                       m.Group.GroupTypeId == _groupType.Id)
                                                .OrderBy(m => m.GroupOrder ?? int.MaxValue).ThenBy(m => m.Id)
                                                .ToList();

                        if (groupMemberGroups.Count > 1 && memberService.SetGroupMemberGroupOrder(groupMemberGroups))
                        {
                            rockContext.SaveChanges();
                        }
                    }
                }

                // Gind the Groups repeater which will show the Groups with a list of GroupMembers
                using (_bindGroupsRockContext = new RockContext())
                {
                    var memberService = new GroupMemberService(_bindGroupsRockContext);
                    var groups        = memberService.Queryable(true)
                                        .Where(m =>
                                               m.PersonId == Person.Id &&
                                               m.Group.GroupTypeId == _groupType.Id)
                                        .OrderBy(m => m.GroupOrder ?? int.MaxValue).ThenBy(m => m.Id)
                                        .Select(m => m.Group)
                                        .AsNoTracking()
                                        .ToList();

                    if (!groups.Any() && GetAttributeValue("AutoCreateGroup").AsBoolean(true))
                    {
                        // ensure that the person is in a group

                        var groupService = new GroupService(_bindGroupsRockContext);
                        var group        = new Group();
                        group.Name        = Person.LastName;
                        group.GroupTypeId = _groupType.Id;
                        groupService.Add(group);
                        _bindGroupsRockContext.SaveChanges();

                        var groupMember = new GroupMember();
                        groupMember.PersonId    = Person.Id;
                        groupMember.GroupRoleId = _groupType.DefaultGroupRoleId.Value;
                        groupMember.GroupId     = group.Id;
                        group.Members.Add(groupMember);
                        _bindGroupsRockContext.SaveChanges();

                        groups.Add(groupService.Get(group.Id));
                    }

                    rptrGroups.DataSource = groups;

                    _showReorderIcon = groups.Count > 1;
                    rptrGroups.DataBind();
                }
            }
        }
        /// <summary>
        /// Saves the individuals.
        /// </summary>
        /// <param name="newFamilyList">The family list.</param>
        /// <param name="visitorList">The optional visitor list.</param>
        private void SaveIndividuals(List <Group> newFamilyList, List <Group> visitorList = null, List <Note> newNoteList = null)
        {
            if (newFamilyList.Any())
            {
                var rockContext = new RockContext();
                rockContext.WrapTransaction(() =>
                {
                    rockContext.Groups.AddRange(newFamilyList);
                    rockContext.SaveChanges(DisableAuditing);

                    ImportedPeople.AddRange(newFamilyList);

                    foreach (var familyGroups in newFamilyList.GroupBy <Group, string>(g => g.ForeignKey))
                    {
                        bool visitorsExist = visitorList.Any() && familyGroups.Any();
                        foreach (var newFamilyGroup in familyGroups)
                        {
                            foreach (var person in newFamilyGroup.Members.Select(m => m.Person))
                            {
                                // Set notes on this person
                                if (newNoteList.Any(n => n.ForeignKey == person.ForeignKey))
                                {
                                    newNoteList.Where(n => n.ForeignKey == person.ForeignKey).ToList()
                                    .ForEach(n => n.EntityId = person.Id);
                                }

                                // Set attributes on this person
                                foreach (var attributeCache in person.Attributes.Select(a => a.Value))
                                {
                                    var existingValue     = rockContext.AttributeValues.FirstOrDefault(v => v.Attribute.Key == attributeCache.Key && v.EntityId == person.Id);
                                    var newAttributeValue = person.AttributeValues[attributeCache.Key];

                                    // set the new value and add it to the database
                                    if (existingValue == null)
                                    {
                                        existingValue             = new AttributeValue();
                                        existingValue.AttributeId = newAttributeValue.AttributeId;
                                        existingValue.EntityId    = person.Id;
                                        existingValue.Value       = newAttributeValue.Value;

                                        rockContext.AttributeValues.Add(existingValue);
                                    }
                                    else
                                    {
                                        existingValue.Value = newAttributeValue.Value;
                                        rockContext.Entry(existingValue).State = EntityState.Modified;
                                    }
                                }

                                // Set aliases on this person
                                if (!person.Aliases.Any(a => a.AliasPersonId == person.Id))
                                {
                                    person.Aliases.Add(new PersonAlias
                                    {
                                        AliasPersonId   = person.Id,
                                        AliasPersonGuid = person.Guid,
                                        ForeignKey      = person.ForeignKey,
                                        ForeignId       = person.ForeignId
                                    });
                                }

                                person.GivingGroupId = newFamilyGroup.Id;

                                if (visitorsExist)
                                {
                                    var groupTypeRoleService = new GroupTypeRoleService(rockContext);
                                    var ownerRole            = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER));
                                    int inviteeRoleId        = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED)).Id;
                                    int invitedByRoleId      = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED_BY)).Id;
                                    int canCheckInRoleId     = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN)).Id;
                                    int allowCheckInByRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_ALLOW_CHECK_IN_BY)).Id;

                                    // Retrieve or create the group this person is an owner of
                                    var ownerGroup = new GroupMemberService(rockContext).Queryable()
                                                     .Where(m => m.PersonId == person.Id && m.GroupRoleId == ownerRole.Id)
                                                     .Select(m => m.Group).FirstOrDefault();
                                    if (ownerGroup == null)
                                    {
                                        var ownerGroupMember         = new GroupMember();
                                        ownerGroupMember.PersonId    = person.Id;
                                        ownerGroupMember.GroupRoleId = ownerRole.Id;

                                        ownerGroup             = new Group();
                                        ownerGroup.Name        = ownerRole.GroupType.Name;
                                        ownerGroup.GroupTypeId = ownerRole.GroupTypeId.Value;
                                        ownerGroup.Members.Add(ownerGroupMember);
                                        rockContext.Groups.Add(ownerGroup);
                                    }

                                    // Visitor, add relationships to the family members
                                    if (visitorList.Where(v => v.ForeignKey == newFamilyGroup.ForeignKey)
                                        .Any(v => v.Members.Any(m => m.Person.ForeignKey.Equals(person.ForeignKey))))
                                    {
                                        var familyMembers = familyGroups.Except(visitorList).SelectMany(g => g.Members);
                                        foreach (var familyMember in familyMembers)
                                        {
                                            // Add visitor invitedBy relationship
                                            var invitedByMember         = new GroupMember();
                                            invitedByMember.PersonId    = familyMember.Person.Id;
                                            invitedByMember.GroupRoleId = invitedByRoleId;
                                            ownerGroup.Members.Add(invitedByMember);

                                            if (person.Age < 18 && familyMember.Person.Age > 15)
                                            {
                                                // Add visitor allowCheckInBy relationship
                                                var allowCheckinMember         = new GroupMember();
                                                allowCheckinMember.PersonId    = familyMember.Person.Id;
                                                allowCheckinMember.GroupRoleId = allowCheckInByRoleId;
                                                ownerGroup.Members.Add(allowCheckinMember);
                                            }
                                        }
                                    }
                                    else
                                    {   // Family member, add relationships to the visitor(s)
                                        var familyVisitors = visitorList.Where(v => v.ForeignKey == newFamilyGroup.ForeignKey).SelectMany(g => g.Members).ToList();
                                        foreach (var visitor in familyVisitors)
                                        {
                                            // Add invited visitor relationship
                                            var inviteeMember         = new GroupMember();
                                            inviteeMember.PersonId    = visitor.Person.Id;
                                            inviteeMember.GroupRoleId = inviteeRoleId;
                                            ownerGroup.Members.Add(inviteeMember);

                                            if (visitor.Person.Age < 18 && person.Age > 15)
                                            {
                                                // Add canCheckIn visitor relationship
                                                var canCheckInMember         = new GroupMember();
                                                canCheckInMember.PersonId    = visitor.Person.Id;
                                                canCheckInMember.GroupRoleId = canCheckInRoleId;
                                                ownerGroup.Members.Add(canCheckInMember);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Save notes and all changes
                    rockContext.Notes.AddRange(newNoteList);
                    rockContext.SaveChanges(DisableAuditing);
                });
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSaveGroupMember control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSaveGroupMember_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            GroupTypeRole role = new GroupTypeRoleService(rockContext).Get(ddlGroupRole.SelectedValueAsInt() ?? 0);

            var groupMember = groupMemberService.Get(CurrentGroupMemberId);

            if (CurrentGroupMemberId == 0)
            {
                groupMember = new GroupMember {
                    Id = 0
                };
                groupMember.GroupId = _groupId;

                // check to see if the person is alread a member of the gorup/role
                var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId(
                    _groupId, ppGroupMemberPerson.SelectedValue ?? 0, ddlGroupRole.SelectedValueAsId() ?? 0);

                if (existingGroupMember != null)
                {
                    // if so, don't add and show error message
                    var person = new PersonService(rockContext).Get(( int )ppGroupMemberPerson.PersonId);

                    nbGroupMemberErrorMessage.Title = "Person Already In Group";
                    nbGroupMemberErrorMessage.Text  = string.Format(
                        "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role.",
                        person.FullName,
                        ddlGroupRole.SelectedItem.Text,
                        role.GroupType.GroupTerm,
                        RockPage.PageId,
                        existingGroupMember.Id);
                    return;
                }
            }

            groupMember.PersonId    = ppGroupMemberPerson.PersonId.Value;
            groupMember.GroupRoleId = role.Id;

            // set their status.  If HideInactiveGroupMemberStatus is True, and they are already Inactive, keep their status as Inactive;
            bool hideGroupMemberInactiveStatus = GetAttributeValue("HideInactiveGroupMemberStatus").AsBooleanOrNull() ?? false;
            var  selectedStatus = rblStatus.SelectedValueAsEnumOrNull <GroupMemberStatus>();

            if (!selectedStatus.HasValue)
            {
                if (hideGroupMemberInactiveStatus)
                {
                    selectedStatus = GroupMemberStatus.Inactive;
                }
                else
                {
                    selectedStatus = GroupMemberStatus.Active;
                }
            }

            groupMember.GroupMemberStatus = selectedStatus.Value;

            groupMember.LoadAttributes();

            Helper.GetEditValues(phAttributes, groupMember);

            if (!Page.IsValid)
            {
                return;
            }

            // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass.
            // So, make sure a message is displayed in the validation summary
            cvEditGroupMember.IsValid = groupMember.IsValid;

            if (!cvEditGroupMember.IsValid)
            {
                cvEditGroupMember.ErrorMessage = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                return;
            }

            // using WrapTransaction because there are two Saves
            rockContext.WrapTransaction(() =>
            {
                if (groupMember.Id.Equals(0))
                {
                    groupMemberService.Add(groupMember);
                }

                rockContext.SaveChanges();
                groupMember.SaveAttributeValues(rockContext);
            });

            Group group = new GroupService(rockContext).Get(groupMember.GroupId);

            if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
            {
                Role.Flush(group.Id);
            }

            pnlEditGroupMember.Visible = false;
            pnlGroupView.Visible       = true;
            DisplayViewGroup();
            IsEditingGroupMember = false;
        }
        /// <summary>
        /// Loads the individual data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadIndividuals(CSVInstance csvData)
        {
            var lookupContext        = new RockContext();
            var groupTypeRoleService = new GroupTypeRoleService(lookupContext);
            var groupMemberService   = new GroupMemberService(lookupContext);

            // Marital statuses: Married, Single, Separated, etc
            var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues;

            // Connection statuses: Member, Visitor, Attendee, etc
            var connectionStatusTypes      = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues;
            int memberConnectionStatusId   = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id;
            int visitorConnectionStatusId  = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id;
            int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id;

            // Suffix type: Dr., Jr., II, etc
            var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues;

            // Title type: Mr., Mrs. Dr., etc
            var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues;

            // Record statuses: Active, Inactive, Pending
            int?recordStatusActiveId   = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id;
            int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id;
            int?recordStatusPendingId  = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id;

            // Deceased record status reason (others available: No Activity, Moved, etc)
            var recordStatusDeceasedId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED)).Id;

            // Record type: Person
            int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id;

            // Group roles: Owner, Adult, Child, others
            GroupTypeRole ownerRole   = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER));
            int           adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id;
            int           childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id;

            // Phone types: Home, Work, Mobile
            var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues;

            // Personal note type id
            var personalNoteTypeId = new NoteTypeService(lookupContext).Get(new Guid(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE)).Id;

            // School defined type
            var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D"));

            // Look up existing Person attributes
            var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList();
            var schoolAttribute  = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School"));

            // Text field type id
            int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), lookupContext).Id;
            int dateFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.DATE), lookupContext).Id;

            // Attribute entity type id
            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;

            // Visit info category
            var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                    .Where(c => c.Name == "Visit Information").FirstOrDefault();

            // Look for custom attributes in the Individual file
            var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList();
            Dictionary <int, string> customAttributes = allFields
                                                        .Where(f => f.index > SecurityNote)
                                                        .ToDictionary(f => f.index, f => f.node.Name.RemoveWhitespace());

            // Add any attributes if they don't already exist
            if (customAttributes.Any())
            {
                var newAttributes = new List <Rock.Model.Attribute>();
                foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Key == ca.Value)))
                {
                    var newAttribute = new Rock.Model.Attribute();
                    newAttribute.Name        = newAttributePair.Value;
                    newAttribute.Key         = newAttributePair.Value.RemoveWhitespace();
                    newAttribute.Description = newAttributePair.Value + " created by CSV import";
                    newAttribute.EntityTypeQualifierValue  = string.Empty;
                    newAttribute.EntityTypeQualifierColumn = string.Empty;
                    newAttribute.EntityTypeId = PersonEntityTypeId;
                    newAttribute.FieldTypeId  = textFieldTypeId;
                    newAttribute.DefaultValue = string.Empty;
                    newAttribute.IsMultiValue = false;
                    newAttribute.IsGridColumn = false;
                    newAttribute.IsRequired   = false;
                    newAttribute.Order        = 0;
                    newAttributes.Add(newAttribute);
                }

                lookupContext.Attributes.AddRange(newAttributes);
                lookupContext.SaveChanges(DisableAuditing);
                personAttributes.AddRange(newAttributes);
            }

            // Set the supported date formats
            var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" };

            var currentFamilyGroup = new Group();
            var newFamilyList      = new List <Group>();
            var newVisitorList     = new List <Group>();
            var newNoteList        = new List <Note>();

            int completed   = 0;
            int newFamilies = 0;

            ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeople.Count(p => p.Members.Any(m => m.Person.ForeignKey != null))));

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                int  groupRoleId          = adultRoleId;
                bool isFamilyRelationship = true;

                string rowFamilyName = row[FamilyName];
                string rowFamilyKey  = row[FamilyId];
                string rowPersonKey  = row[PersonId];
                int?   rowFamilyId   = rowFamilyKey.AsType <int?>();
                int?   rowPersonId   = rowPersonKey.AsType <int?>();

                // Check that this person isn't already in our data
                var personExists = ImportedPeople.Any(p => p.Members.Any(m => m.Person.ForeignKey == rowPersonKey));
                if (!personExists)
                {
                    #region person create

                    var person = new Person();
                    person.ForeignKey             = rowPersonKey;
                    person.ForeignId              = rowPersonId;
                    person.SystemNote             = string.Format("Imported via Excavator on {0}", ImportDateTime);
                    person.RecordTypeValueId      = personRecordTypeId;
                    person.CreatedByPersonAliasId = ImportPersonAliasId;
                    string firstName = row[FirstName].Left(50);
                    string nickName  = row[NickName].Left(50);
                    person.FirstName  = firstName;
                    person.NickName   = string.IsNullOrWhiteSpace(nickName) ? firstName : nickName;
                    person.MiddleName = row[MiddleName].Left(50);
                    person.LastName   = row[LastName].Left(50);

                    DateTime createdDateValue;
                    if (DateTime.TryParseExact(row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue))
                    {
                        person.CreatedDateTime  = createdDateValue;
                        person.ModifiedDateTime = ImportDateTime;
                    }
                    else
                    {
                        person.CreatedDateTime  = ImportDateTime;
                        person.ModifiedDateTime = ImportDateTime;
                    }

                    DateTime birthDate;
                    if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate))
                    {
                        person.BirthDay   = birthDate.Day;
                        person.BirthMonth = birthDate.Month;
                        person.BirthYear  = birthDate.Year;
                    }

                    DateTime graduationDate;
                    if (DateTime.TryParseExact(row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate))
                    {
                        person.GraduationYear = graduationDate.Year;
                    }

                    DateTime anniversary;
                    if (DateTime.TryParseExact(row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary))
                    {
                        person.AnniversaryDate = anniversary;
                    }

                    string gender = row[Gender];
                    if (gender != null)
                    {
                        switch (gender.Trim().ToLower())
                        {
                        case "m":
                        case "male":
                            person.Gender = Rock.Model.Gender.Male;
                            break;

                        case "f":
                        case "female":
                            person.Gender = Rock.Model.Gender.Female;
                            break;

                        default:
                            person.Gender = Rock.Model.Gender.Unknown;
                            break;
                        }
                    }

                    string prefix = row[Prefix];
                    if (!string.IsNullOrWhiteSpace(prefix))
                    {
                        prefix = prefix.RemoveSpecialCharacters().Trim();
                        person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters())
                                              .Select(s => (int?)s.Id).FirstOrDefault();
                    }

                    string suffix = row[Suffix];
                    if (!string.IsNullOrWhiteSpace(suffix))
                    {
                        suffix = suffix.RemoveSpecialCharacters().Trim();
                        person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters())
                                               .Select(s => (int?)s.Id).FirstOrDefault();
                    }

                    string maritalStatus = row[MaritalStatus];
                    if (!string.IsNullOrWhiteSpace(maritalStatus))
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus)
                                                      .Select(dv => (int?)dv.Id).FirstOrDefault();
                    }
                    else
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown")
                                                      .Select(dv => (int?)dv.Id).FirstOrDefault();
                    }

                    string familyRole = row[FamilyRole];
                    if (!string.IsNullOrWhiteSpace(familyRole))
                    {
                        if (familyRole == "Visitor")
                        {
                            isFamilyRelationship = false;
                        }

                        if (familyRole == "Child" || person.Age < 18)
                        {
                            groupRoleId = childRoleId;
                        }
                    }

                    string connectionStatus = row[ConnectionStatus];
                    if (!string.IsNullOrWhiteSpace(connectionStatus))
                    {
                        if (connectionStatus == "Member")
                        {
                            person.ConnectionStatusValueId = memberConnectionStatusId;
                        }
                        else if (connectionStatus == "Visitor")
                        {
                            person.ConnectionStatusValueId = visitorConnectionStatusId;
                        }
                        else
                        {
                            // look for user-defined connection type or default to Attendee
                            var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == connectionStatus)
                                                       .Select(dv => (int?)dv.Id).FirstOrDefault();

                            person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId;
                            person.RecordStatusValueId     = recordStatusActiveId;
                        }
                    }

                    string recordStatus = row[RecordStatus];
                    if (!string.IsNullOrWhiteSpace(recordStatus))
                    {
                        switch (recordStatus.Trim().ToLower())
                        {
                        case "active":
                            person.RecordStatusValueId = recordStatusActiveId;
                            break;

                        case "inactive":
                            person.RecordStatusValueId = recordStatusInactiveId;
                            break;

                        default:
                            person.RecordStatusValueId = recordStatusPendingId;
                            break;
                        }
                    }

                    string isDeceasedValue = row[IsDeceased];
                    if (!string.IsNullOrWhiteSpace(isDeceasedValue))
                    {
                        switch (isDeceasedValue.Trim().ToLower())
                        {
                        case "y":
                        case "yes":
                            person.IsDeceased = true;
                            person.RecordStatusReasonValueId = recordStatusDeceasedId;
                            person.RecordStatusValueId       = recordStatusInactiveId;
                            break;

                        default:
                            person.IsDeceased = false;
                            break;
                        }
                    }

                    var personNumbers = new Dictionary <string, string>();
                    personNumbers.Add("Home", row[HomePhone]);
                    personNumbers.Add("Mobile", row[MobilePhone]);
                    personNumbers.Add("Work", row[WorkPhone]);
                    string smsAllowed = row[AllowSMS];

                    foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value)))
                    {
                        var extension        = string.Empty;
                        var countryCode      = Rock.Model.PhoneNumber.DefaultCountryCode();
                        var normalizedNumber = string.Empty;
                        var countryIndex     = numberPair.Value.IndexOf('+');
                        int extensionIndex   = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length;
                        if (countryIndex >= 0)
                        {
                            countryCode      = numberPair.Value.Substring(countryIndex, countryIndex + 3).AsNumeric();
                            normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric().TrimStart(new Char[] { '0' });
                            extension        = numberPair.Value.Substring(extensionIndex);
                        }
                        else if (extensionIndex > 0)
                        {
                            normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric();
                            extension        = numberPair.Value.Substring(extensionIndex).AsNumeric();
                        }
                        else
                        {
                            normalizedNumber = numberPair.Value.AsNumeric();
                        }

                        if (!string.IsNullOrWhiteSpace(normalizedNumber))
                        {
                            var currentNumber = new PhoneNumber();
                            currentNumber.CountryCode            = countryCode;
                            currentNumber.CreatedByPersonAliasId = ImportPersonAliasId;
                            currentNumber.Extension         = extension.Left(20);
                            currentNumber.Number            = normalizedNumber.TrimStart(new Char[] { '0' }).Left(20);
                            currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key))
                                                              .Select(v => (int?)v.Id).FirstOrDefault();
                            if (numberPair.Key == "Mobile")
                            {
                                switch (smsAllowed.Trim().ToLower())
                                {
                                case "y":
                                case "yes":
                                case "active":
                                    currentNumber.IsMessagingEnabled = true;
                                    break;

                                default:
                                    currentNumber.IsMessagingEnabled = false;
                                    break;
                                }
                            }

                            person.PhoneNumbers.Add(currentNumber);
                        }
                    }

                    // Map Person attributes
                    person.Attributes      = new Dictionary <string, AttributeCache>();
                    person.AttributeValues = new Dictionary <string, AttributeValueCache>();

                    bool isEmailActive;
                    switch (row[IsEmailActive].Trim().ToLower())
                    {
                    case "n":
                    case "no":
                    case "inactive":
                        isEmailActive = false;
                        break;

                    default:
                        isEmailActive = true;
                        break;
                    }

                    EmailPreference emailPreference;
                    switch (row[AllowBulkEmail].Trim().ToLower())
                    {
                    case "n":
                    case "no":
                    case "inactive":
                        emailPreference = EmailPreference.NoMassEmails;
                        break;

                    default:
                        emailPreference = EmailPreference.EmailAllowed;
                        break;
                    }

                    person.EmailPreference = emailPreference;
                    string primaryEmail = row[Email].Trim().Left(75);
                    if (!string.IsNullOrWhiteSpace(primaryEmail))
                    {
                        if (primaryEmail.IsEmail())
                        {
                            person.Email         = primaryEmail;
                            person.IsEmailActive = isEmailActive;
                        }
                        else
                        {
                            LogException("InvalidPrimaryEmail", string.Format("PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail));
                        }
                    }

                    string schoolName = row[School];
                    if (!string.IsNullOrWhiteSpace(schoolName))
                    {
                        // Add school if it doesn't exist
                        Guid schoolGuid;
                        var  schoolExists = schoolDefinedType.DefinedValues.Any(s => s.Value.Equals(schoolName));
                        if (!schoolExists)
                        {
                            var newSchool = new DefinedValue();
                            newSchool.DefinedTypeId = schoolDefinedType.Id;
                            newSchool.Value         = schoolName;
                            newSchool.Order         = 0;

                            lookupContext.DefinedValues.Add(newSchool);
                            lookupContext.SaveChanges();

                            schoolGuid = newSchool.Guid;
                        }
                        else
                        {
                            schoolGuid = schoolDefinedType.DefinedValues.FirstOrDefault(s => s.Value.Equals(schoolName)).Guid;
                        }

                        AddPersonAttribute(schoolAttribute, person, schoolGuid.ToString().ToUpper());
                    }

                    foreach (var attributePair in customAttributes)
                    {
                        string newAttributeValue = row[attributePair.Key];
                        if (!string.IsNullOrWhiteSpace(newAttributeValue))
                        {
                            // check if this attribute value is a date
                            DateTime valueAsDateTime;
                            if (DateTime.TryParseExact(newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime))
                            {
                                newAttributeValue = valueAsDateTime.ToString("yyyy-MM-dd");
                            }

                            int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value.RemoveWhitespace())
                                                 .Select(a => (int?)a.Id).FirstOrDefault();
                            if (newAttributeId != null)
                            {
                                var newAttribute = AttributeCache.Read((int)newAttributeId);
                                AddPersonAttribute(newAttribute, person, newAttributeValue);
                            }
                        }
                    }

                    // Add notes to timeline
                    var notePairs = new Dictionary <string, string>();
                    notePairs.Add("General", row[GeneralNote]);
                    notePairs.Add("Medical", row[MedicalNote]);
                    notePairs.Add("Security", row[SecurityNote]);

                    foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value)))
                    {
                        var newNote = new Note();
                        newNote.NoteTypeId             = personalNoteTypeId;
                        newNote.CreatedByPersonAliasId = ImportPersonAliasId;
                        newNote.CreatedDateTime        = ImportDateTime;
                        newNote.Text       = notePair.Value;
                        newNote.ForeignKey = rowPersonKey;
                        newNote.ForeignId  = rowPersonId;
                        newNote.Caption    = string.Format("{0} Note", notePair.Key);

                        if (!notePair.Key.Equals("General"))
                        {
                            newNote.IsAlert = true;
                        }

                        newNoteList.Add(newNote);
                    }

                    #endregion person create

                    var groupMember = new GroupMember();
                    groupMember.Person                 = person;
                    groupMember.GroupRoleId            = groupRoleId;
                    groupMember.CreatedDateTime        = ImportDateTime;
                    groupMember.ModifiedDateTime       = ImportDateTime;
                    groupMember.CreatedByPersonAliasId = ImportPersonAliasId;
                    groupMember.GroupMemberStatus      = GroupMemberStatus.Active;

                    if (rowFamilyKey != currentFamilyGroup.ForeignKey)
                    {
                        // person not part of the previous family, see if that family exists or create a new one
                        currentFamilyGroup = ImportedPeople.FirstOrDefault(p => p.ForeignKey == rowFamilyKey);
                        if (currentFamilyGroup == null)
                        {
                            currentFamilyGroup = CreateFamilyGroup(row[FamilyName], rowFamilyKey);
                            newFamilyList.Add(currentFamilyGroup);
                            newFamilies++;
                        }
                        else
                        {
                            lookupContext.Groups.Attach(currentFamilyGroup);
                            lookupContext.Entry(currentFamilyGroup).State = EntityState.Modified;
                        }

                        currentFamilyGroup.Members.Add(groupMember);
                    }
                    else
                    {
                        // person is part of this family group, check if they're a visitor
                        if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1)
                        {
                            currentFamilyGroup.Members.Add(groupMember);
                        }
                        else
                        {
                            var visitorFamily = CreateFamilyGroup(person.LastName + " Family", rowFamilyKey);
                            visitorFamily.Members.Add(groupMember);
                            newFamilyList.Add(visitorFamily);
                            newVisitorList.Add(visitorFamily);
                            newFamilies++;
                        }
                    }

                    completed++;
                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, string.Format("{0:N0} people imported.", completed));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveIndividuals(newFamilyList, newVisitorList, newNoteList);
                        lookupContext.SaveChanges();
                        ReportPartialProgress();

                        // Clear out variables
                        currentFamilyGroup = new Group();
                        newFamilyList.Clear();
                        newVisitorList.Clear();
                        newNoteList.Clear();
                    }
                }
            }

            // Save any changes to new families
            if (newFamilyList.Any())
            {
                SaveIndividuals(newFamilyList, newVisitorList, newNoteList);
            }

            // Save any changes to existing families
            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress(0, string.Format("Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed));
            return(completed);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Bind the grid to the donations that should be visible for the proper context.
        /// </summary>
        protected void BindGrid(bool isExporting = false)
        {
            var   rockContext        = new RockContext();
            var   groupMemberService = new GroupMemberService(rockContext);
            var   financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);
            var   entityTypeIdGroupMember           = EntityTypeCache.GetId <GroupMember>();
            var   hideGridColumns = GetAttributeValue("HideGridColumns").Split(',');
            var   hideGridActions = GetAttributeValue("HideGridActions").Split(',');
            var   mergeFields     = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);
            Group group           = null;
            Dictionary <int, GroupMember> groupMembers;

            //
            // Get the donations for the entire opportunity group or for just the
            // one individual being viewed.
            //
            if (ContextEntity <Group>() != null)
            {
                group = ContextEntity <Group>();

                groupMembers = groupMemberService.Queryable()
                               .Where(m => m.GroupId == group.Id)
                               .ToDictionary(m => m.Id);
            }
            else
            {
                var groupMember = ContextEntity <GroupMember>();
                group = groupMember.Group;

                groupMembers = new Dictionary <int, GroupMember> {
                    { groupMember.Id, groupMember }
                };
            }

            //
            // Get the list of donation entries for the grid that match the list of members.
            //
            var groupMemberIds = groupMembers.Keys.ToList();
            var donations      = financialTransactionDetailService.Queryable()
                                 .Where(d => d.EntityTypeId == entityTypeIdGroupMember && groupMemberIds.Contains(d.EntityId.Value))
                                 .ToList()
                                 .Select(d => new
            {
                IsExporting = isExporting,
                DonorId     = d.Transaction.AuthorizedPersonAlias.PersonId,
                Donor       = d.Transaction.AuthorizedPersonAlias.Person,
                Group       = group,
                Participant = groupMembers[d.EntityId.Value],
                Amount      = d.Amount,
                Address     = d.Transaction.AuthorizedPersonAlias.Person.GetHomeLocation(rockContext).ToStringSafe().ConvertCrLfToHtmlBr(),
                Date        = d.Transaction.TransactionDateTime
            }).AsQueryable();

            //
            // Apply user sorting or default to donor name.
            //
            if (gDonations.SortProperty != null)
            {
                donations = donations.Sort(gDonations.SortProperty);
            }
            else
            {
                donations = donations.Sort(new SortProperty {
                    Property = "Donor.LastName, Donor.NickName"
                });
            }

            gDonations.ObjectList = donations.Select(d => d.Donor)
                                    .DistinctBy(p => p.Id)
                                    .Cast <object>()
                                    .ToDictionary(p => (( Person )p).Id.ToString());

            //
            // Hide any columns they don't want visible to the user.
            //
            gDonations.ColumnsOfType <CurrencyField>()
            .First(c => c.DataField == "Amount")
            .Visible = !hideGridColumns.Contains("Amount");
            gDonations.ColumnsOfType <RockBoundField>()
            .First(c => c.DataField == "Address")
            .Visible = !hideGridColumns.Contains("Donor Address");
            gDonations.ColumnsOfType <RockBoundField>()
            .First(c => c.DataField == "Donor.Email")
            .Visible = !hideGridColumns.Contains("Donor Email");
            gDonations.ColumnsOfType <RockLiteralField>()
            .First(c => c.HeaderText == "Participant")
            .Visible = !hideGridColumns.Contains("Participant") && ContextEntity <GroupMember>() == null;

            //
            // Hide any grid actions they don't want visible to the user.
            //
            gDonations.Actions.ShowCommunicate   = !hideGridActions.Contains("Communicate");
            gDonations.Actions.ShowMergePerson   = !hideGridActions.Contains("Merge Person");
            gDonations.Actions.ShowBulkUpdate    = !hideGridActions.Contains("Bulk Update");
            gDonations.Actions.ShowExcelExport   = !hideGridActions.Contains("Excel Export");
            gDonations.Actions.ShowMergeTemplate = !hideGridActions.Contains("Merge Template");

            //
            // If all the grid actions are hidden, hide the select column too.
            //
            gDonations.ColumnsOfType <SelectField>().First().Visible = gDonations.Actions.ShowCommunicate || gDonations.Actions.ShowMergePerson || gDonations.Actions.ShowBulkUpdate || gDonations.Actions.ShowExcelExport || gDonations.Actions.ShowMergeTemplate;

            gDonations.DataSource = donations.ToList();
            gDonations.DataBind();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Bind the grid to the donations that should be visible for the proper context.
        /// </summary>
        protected void BindGrid()
        {
            var rockContext        = new RockContext();
            var groupMemberService = new GroupMemberService(rockContext);
            var financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);
            var entityTypeIdGroupMember           = EntityTypeCache.GetId <GroupMember>();
            Dictionary <int, GroupMember> groupMembers;

            //
            // Get the donations for the entire opportunity group or for just the
            // one individual being viewed.
            //
            if (ContextEntity <Group>() != null)
            {
                var group = ContextEntity <Group>();

                groupMembers = groupMemberService.Queryable()
                               .Where(m => m.GroupId == group.Id)
                               .ToDictionary(m => m.Id);

                gDonations.Columns.OfType <RockTemplateField>().Where(c => c.HeaderText == "Participant").ToList().ForEach(c => c.Visible = true);
                gDonations.Columns.OfType <DateField>().Where(c => c.HeaderText == "Date").ToList().ForEach(c => c.Visible = false);
            }
            else
            {
                var groupMember = ContextEntity <GroupMember>();

                groupMembers = new Dictionary <int, GroupMember> {
                    { groupMember.Id, groupMember }
                };

                gDonations.Columns.OfType <RockTemplateField>().Where(c => c.HeaderText == "Participant").ToList().ForEach(c => c.Visible = false);
                gDonations.Columns.OfType <DateField>().Where(c => c.HeaderText == "Date").ToList().ForEach(c => c.Visible = true);
            }

            //
            // Get the list of donation entries for the grid that match the list of members.
            //
            var groupMemberIds = groupMembers.Keys.ToList();
            var donations      = financialTransactionDetailService.Queryable()
                                 .Where(d => d.EntityTypeId == entityTypeIdGroupMember && groupMemberIds.Contains(d.EntityId.Value))
                                 .ToList()
                                 .Select(d => new
            {
                DonorId     = d.Transaction.AuthorizedPersonAlias.PersonId,
                Donor       = d.Transaction.AuthorizedPersonAlias.Person,
                Participant = groupMembers[d.EntityId.Value],
                Amount      = d.Amount,
                Address     = d.Transaction.AuthorizedPersonAlias.Person.GetHomeLocation(rockContext).ToStringSafe().ConvertCrLfToHtmlBr(),
                Date        = d.Transaction.TransactionDateTime
            }).AsQueryable();

            //
            // Apply user sorting or default to donor name.
            //
            if (gDonations.SortProperty != null)
            {
                donations = donations.Sort(gDonations.SortProperty);
            }
            else
            {
                donations = donations.Sort(new SortProperty {
                    Property = "Donor.LastName, Donor.NickName"
                });
            }

            gDonations.ObjectList = donations.Select(d => d.Donor)
                                    .DistinctBy(p => p.Id)
                                    .Cast <object>()
                                    .ToDictionary(p => (( Person )p).Id.ToString());

            gDonations.DataSource = donations.ToList();
            gDonations.DataBind();
        }
        /// <summary>
        /// Handles the SaveClick event of the mdAddContact 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 mdAddContact_SaveClick(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var personService      = new PersonService(rockContext);
            var groupService       = new GroupService(rockContext);
            var groupMemberService = new GroupMemberService(rockContext);
            var business           = personService.Get(int.Parse(hfBusinessId.Value));
            int?contactId          = ppContact.PersonId;

            if (contactId.HasValue && contactId.Value > 0)
            {
                // Get the relationship roles to use
                var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int businessContactRoleId      = knownRelationshipGroupType.Roles
                                                 .Where(r =>
                                                        r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT.AsGuid()))
                                                 .Select(r => r.Id)
                                                 .FirstOrDefault();
                int businessRoleId = knownRelationshipGroupType.Roles
                                     .Where(r =>
                                            r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS.AsGuid()))
                                     .Select(r => r.Id)
                                     .FirstOrDefault();
                int ownerRoleId = knownRelationshipGroupType.Roles
                                  .Where(r =>
                                         r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                  .Select(r => r.Id)
                                  .FirstOrDefault();

                if (ownerRoleId > 0 && businessContactRoleId > 0 && businessRoleId > 0)
                {
                    // get the known relationship group of the business contact
                    // add the business as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS
                    var contactKnownRelationshipGroup = groupMemberService.Queryable()
                                                        .Where(g =>
                                                               g.GroupRoleId == ownerRoleId &&
                                                               g.PersonId == contactId.Value)
                                                        .Select(g => g.Group)
                                                        .FirstOrDefault();
                    if (contactKnownRelationshipGroup == null)
                    {
                        // In some cases person may not yet have a know relationship group type
                        contactKnownRelationshipGroup = new Group();
                        groupService.Add(contactKnownRelationshipGroup);
                        contactKnownRelationshipGroup.Name        = "Known Relationship";
                        contactKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                        var ownerMember = new GroupMember();
                        ownerMember.PersonId    = contactId.Value;
                        ownerMember.GroupRoleId = ownerRoleId;
                        contactKnownRelationshipGroup.Members.Add(ownerMember);
                    }
                    var groupMember = new GroupMember();
                    groupMember.PersonId    = int.Parse(hfBusinessId.Value);
                    groupMember.GroupRoleId = businessRoleId;
                    contactKnownRelationshipGroup.Members.Add(groupMember);

                    // get the known relationship group of the business
                    // add the business contact as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT
                    var businessKnownRelationshipGroup = groupMemberService.Queryable()
                                                         .Where(g =>
                                                                g.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)) &&
                                                                g.PersonId == business.Id)
                                                         .Select(g => g.Group)
                                                         .FirstOrDefault();
                    if (businessKnownRelationshipGroup == null)
                    {
                        // In some cases business may not yet have a know relationship group type
                        businessKnownRelationshipGroup = new Group();
                        groupService.Add(businessKnownRelationshipGroup);
                        businessKnownRelationshipGroup.Name        = "Known Relationship";
                        businessKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                        var ownerMember = new GroupMember();
                        ownerMember.PersonId    = int.Parse(hfBusinessId.Value);
                        ownerMember.GroupRoleId = ownerRoleId;
                        businessKnownRelationshipGroup.Members.Add(ownerMember);
                    }
                    var businessGroupMember = new GroupMember();
                    businessGroupMember.PersonId    = contactId.Value;
                    businessGroupMember.GroupRoleId = businessContactRoleId;
                    businessKnownRelationshipGroup.Members.Add(businessGroupMember);

                    rockContext.SaveChanges();
                }
            }

            mdAddContact.Hide();
            hfModalOpen.Value = string.Empty;
            BindContactListGrid(business);
        }
Ejemplo n.º 16
0
        public DataSet GetContributionTransactions(int groupId, int?personId, [FromBody] ContributionStatementOptions options)
        {
            var qry = Get().Where(a => a.TransactionDateTime >= options.StartDate);

            if (options.EndDate.HasValue)
            {
                qry = qry.Where(a => a.TransactionDateTime < options.EndDate.Value);
            }

            var transactionTypeContribution = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid());

            if (transactionTypeContribution != null)
            {
                int transactionTypeContributionId = transactionTypeContribution.Id;
                qry = qry.Where(a => a.TransactionTypeValueId == transactionTypeContributionId);
            }

            if (personId.HasValue)
            {
                // get transactions for a specific person
                qry = qry.Where(a => a.AuthorizedPersonAlias.PersonId == personId.Value);
            }
            else
            {
                // get transactions for all the persons in the specified group that have specified that group as their GivingGroup
                GroupMemberService groupMemberService = new GroupMemberService(( RockContext )Service.Context);
                var personIdList = groupMemberService.GetByGroupId(groupId).Where(a => a.Person.GivingGroupId == groupId).Select(s => s.PersonId).ToList();

                qry = qry.Where(a => personIdList.Contains(a.AuthorizedPersonAlias.PersonId));
            }

            if (options.AccountIds != null)
            {
                qry = qry.Where(a => a.TransactionDetails.Any(x => options.AccountIds.Contains(x.AccountId)));
            }

            var selectQry = qry.Select(a => new
            {
                a.TransactionDateTime,
                CurrencyTypeValueName = a.FinancialPaymentDetail != null ? a.FinancialPaymentDetail.CurrencyTypeValue.Value : string.Empty,
                a.Summary,
                Details = a.TransactionDetails.Select(d => new
                {
                    d.AccountId,
                    AccountName = d.Account.PublicName,
                    d.Summary,
                    d.Amount,
                    AccountOrder = d.Account.Order
                }).OrderBy(x => x.AccountOrder),
            }).OrderBy(a => a.TransactionDateTime);

            DataTable dataTable = new DataTable("contribution_transactions");

            dataTable.Columns.Add("TransactionDateTime", typeof(DateTime));
            dataTable.Columns.Add("CurrencyTypeValueName");
            dataTable.Columns.Add("Summary");
            dataTable.Columns.Add("Amount", typeof(decimal));
            dataTable.Columns.Add("Details", typeof(DataTable));

            var list = selectQry.ToList();

            dataTable.BeginLoadData();
            foreach (var fieldItems in list)
            {
                DataTable detailTable = new DataTable("transaction_details");
                detailTable.Columns.Add("AccountId", typeof(int));
                detailTable.Columns.Add("AccountName");
                detailTable.Columns.Add("Summary");
                detailTable.Columns.Add("Amount", typeof(decimal));
                var transactionDetails = fieldItems.Details.ToList();

                // remove any Accounts that were not included (in case there was a mix of included and not included accounts in the transaction)
                if (options.AccountIds != null)
                {
                    transactionDetails = transactionDetails.Where(a => options.AccountIds.Contains(a.AccountId)).ToList();
                }

                foreach (var detail in transactionDetails)
                {
                    var detailArray = new object[] {
                        detail.AccountId,
                        detail.AccountName,
                        detail.Summary,
                        detail.Amount
                    };

                    detailTable.Rows.Add(detailArray);
                }

                var itemArray = new object[] {
                    fieldItems.TransactionDateTime,
                    fieldItems.CurrencyTypeValueName,
                    fieldItems.Summary,
                    transactionDetails.Sum(a => a.Amount),
                    detailTable
                };

                dataTable.Rows.Add(itemArray);
            }

            dataTable.EndLoadData();

            DataSet dataSet = new DataSet();

            dataSet.Tables.Add(dataTable);

            return(dataSet);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);
            var recipients  = new List <RockPushMessageRecipient>();

            string toValue = GetAttributeValue(action, "To");
            Guid   guid    = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var           personAlias = new PersonAliasService(rockContext).Get(personAliasGuid);
                                List <string> devices     = new PersonalDeviceService(rockContext).Queryable()
                                                            .Where(a => a.PersonAliasId.HasValue && a.PersonAliasId == personAlias.Id && a.NotificationsEnabled)
                                                            .Select(a => a.DeviceRegistrationId)
                                                            .ToList();

                                string deviceIds = String.Join(",", devices);

                                if (devices.Count == 0)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person does not have devices that support notifications", true);
                                }
                                else
                                {
                                    var person    = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    var recipient = new RockPushMessageRecipient(person, deviceIds, mergeFields);
                                    recipients.Add(recipient);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    List <string> devices = new PersonalDeviceService(rockContext).Queryable()
                                                            .Where(p => p.PersonAliasId.HasValue && p.PersonAliasId == person.PrimaryAliasId && p.NotificationsEnabled)
                                                            .Select(p => p.DeviceRegistrationId)
                                                            .ToList();

                                    string deviceIds = String.Join(",", devices);

                                    if (deviceIds.AsBoolean())
                                    {
                                        var recipient = new RockPushMessageRecipient(person, deviceIds, mergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(RockPushMessageRecipient.CreateAnonymous(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

            string message     = GetAttributeValue(action, "Message");
            Guid   messageGuid = message.AsGuid();

            if (!messageGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(messageGuid, rockContext);
                if (attribute != null)
                {
                    string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid);
                    if (!string.IsNullOrWhiteSpace(messageAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            message = messageAttributeValue;
                        }
                    }
                }
            }

            string title     = GetAttributeValue(action, "Title");
            Guid   titleGuid = title.AsGuid();

            if (!titleGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(titleGuid, rockContext);
                if (attribute != null)
                {
                    string titleAttributeValue = action.GetWorklowAttributeValue(titleGuid);
                    if (!string.IsNullOrWhiteSpace(titleAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            title = titleAttributeValue;
                        }
                    }
                }
            }

            string sound     = GetAttributeValue(action, "Sound");
            Guid   soundGuid = sound.AsGuid();

            if (!soundGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(soundGuid, rockContext);
                if (attribute != null)
                {
                    string soundAttributeValue = action.GetWorklowAttributeValue(soundGuid);
                    if (!string.IsNullOrWhiteSpace(soundAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.BooleanFieldType")
                        {
                            sound = soundAttributeValue;
                        }
                    }
                }
            }
            sound = sound.AsBoolean() ? "default" : "";

            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var pushMessage = new RockPushMessage();
                pushMessage.SetRecipients(recipients);
                pushMessage.Title   = title;
                pushMessage.Message = message;
                pushMessage.Sound   = sound;
                pushMessage.Send();
            }

            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            var settings = new SelectSettings(selection);

            var context = (RockContext)serviceInstance.Context;

            //
            // Evaluate the Data View that defines the candidate Groups.
            //
            var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent(settings.DataViewGuid, context);

            var groupService = new GroupService(context);

            var groupQuery = groupService.Queryable();

            if (dataView != null)
            {
                groupQuery = DataComponentSettingsHelper.FilterByDataView(groupQuery, dataView, groupService);
            }
            else
            {
                // Apply a default Group filter to only show Groups that would be visible in a Group List.
                groupQuery = groupQuery.Where(x => x.GroupType.ShowInGroupList);
            }

            var groupKeys = groupQuery.Select(x => x.Id);

            //
            // Construct the Query to return the list of Group Members matching the filter conditions.
            //
            var groupMemberQuery = new GroupMemberService(context).Queryable();

            // Filter By Group.
            groupMemberQuery = groupMemberQuery.Where(x => groupKeys.Contains(x.GroupId));

            // Filter By Group Role Type.
            switch (settings.RoleType)
            {
            case RoleTypeSpecifier.Member:
                groupMemberQuery = groupMemberQuery.Where(x => !x.GroupRole.IsLeader);
                break;

            case RoleTypeSpecifier.Leader:
                groupMemberQuery = groupMemberQuery.Where(x => x.GroupRole.IsLeader);
                break;
            }

            // Filter by Group Member Status.
            if (settings.MemberStatus.HasValue)
            {
                groupMemberQuery = groupMemberQuery.Where(x => x.GroupMemberStatus == settings.MemberStatus.Value);
            }

            //
            // Create a Select Expression to return the Person records referenced by the Group Members.
            //
            var personGroupsQuery = new PersonService(context).Queryable()
                                    .Where(p => groupMemberQuery.Select(gm => gm.PersonId).Contains(p.Id));

            var selectExpression = FilterExpressionExtractor.Extract <Model.Person>(personGroupsQuery, parameterExpression, "p");

            return(selectExpression);
        }
        /// <summary>
        /// Binds the repeater.
        /// </summary>
        protected void BindRepeater()
        {
            if (this.CurrentPersonId == null)
            {
                return;
            }

            int communicationListGroupTypeId            = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_COMMUNICATIONLIST.AsGuid()).Id;
            int?communicationListGroupTypeDefaultRoleId = GroupTypeCache.Get(communicationListGroupTypeId).DefaultGroupRoleId;

            var rockContext = new RockContext();

            var memberOfList = new GroupMemberService(rockContext).GetByPersonId(CurrentPersonId.Value).AsNoTracking().Select(a => a.GroupId).ToList();

            // Get a list of syncs for the communication list groups where the default role is sync'd AND the current person is NOT a member of
            // This is used to filter out the list of communication lists.
            var commGroupSyncsForDefaultRole = new GroupSyncService(rockContext)
                                               .Queryable()
                                               .Where(a => a.Group.GroupTypeId == communicationListGroupTypeId)
                                               .Where(a => a.GroupTypeRoleId == communicationListGroupTypeDefaultRoleId)
                                               .Where(a => !memberOfList.Contains(a.GroupId))
                                               .Select(a => a.GroupId)
                                               .ToList();

            var communicationLists = new GroupService(rockContext)
                                     .Queryable()
                                     .Where(a => a.GroupTypeId == communicationListGroupTypeId && !commGroupSyncsForDefaultRole.Contains(a.Id))
                                     .IsActive()
                                     .ToList();

            var categoryGuids = this.GetAttributeValue(AttributeKey.CommunicationListCategories).SplitDelimitedValues().AsGuidList();
            var viewableCommunicationLists = new List <Group>();

            foreach (var communicationList in communicationLists)
            {
                communicationList.LoadAttributes(rockContext);
                if (!categoryGuids.Any())
                {
                    // if no categories where specified, only show lists that the person has VIEW auth
                    if (communicationList.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson))
                    {
                        viewableCommunicationLists.Add(communicationList);
                    }
                }
                else
                {
                    Guid?categoryGuid = communicationList.GetAttributeValue("Category").AsGuidOrNull();
                    if (categoryGuid.HasValue && categoryGuids.Contains(categoryGuid.Value))
                    {
                        viewableCommunicationLists.Add(communicationList);
                    }
                }
            }

            viewableCommunicationLists = viewableCommunicationLists.OrderBy(a =>
            {
                var name = a.GetAttributeValue("PublicName");
                if (name.IsNullOrWhiteSpace())
                {
                    name = a.Name;
                }

                return(name);
            }).ToList();

            var groupIds = viewableCommunicationLists.Select(a => a.Id).ToList();
            var personId = this.CurrentPersonId.Value;

            showMediumPreference = this.GetAttributeValue(AttributeKey.ShowMediumPreference).AsBoolean();

            personCommunicationListsMember = new GroupMemberService(rockContext)
                                             .Queryable()
                                             .AsNoTracking()
                                             .Where(a => groupIds.Contains(a.GroupId) && a.PersonId == personId)
                                             .GroupBy(a => a.GroupId)
                                             .ToList()
                                             .ToDictionary(k => k.Key, v => v.FirstOrDefault());

            rptCommunicationLists.DataSource = viewableCommunicationLists;
            rptCommunicationLists.DataBind();

            nbNoCommunicationLists.Visible      = !viewableCommunicationLists.Any();
            pnlCommunicationPreferences.Visible = viewableCommunicationLists.Any();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void ShowDetails()
        {
            bool existingOccurrence = _occurrence != null;

            if (!existingOccurrence && !_allowAdd)
            {
                nbNotice.Heading             = "No Occurrences";
                nbNotice.Text                = "<p>There are currently not any active occurrences for selected group to take attendance for.</p>";
                nbNotice.NotificationBoxType = NotificationBoxType.Warning;
                nbNotice.Visible             = true;

                pnlDetails.Visible = false;
            }
            else
            {
                if (existingOccurrence)
                {
                    lOccurrenceDate.Visible = _occurrence.ScheduleId.HasValue;
                    lOccurrenceDate.Text    = _occurrence.Date.ToShortDateString();

                    dpOccurrenceDate.Visible      = !_occurrence.ScheduleId.HasValue;
                    dpOccurrenceDate.SelectedDate = _occurrence.Date;

                    if (_occurrence.LocationId.HasValue)
                    {
                        lLocation.Visible = true;
                        lLocation.Text    = new LocationService(_rockContext).GetPath(_occurrence.LocationId.Value);
                    }
                    else
                    {
                        lLocation.Visible = false;
                    }
                    ddlLocation.Visible = false;

                    lSchedule.Visible   = !string.IsNullOrWhiteSpace(_occurrence.ScheduleName);
                    lSchedule.Text      = _occurrence.ScheduleName;
                    ddlSchedule.Visible = false;
                }
                else
                {
                    lOccurrenceDate.Visible       = false;
                    dpOccurrenceDate.Visible      = true;
                    dpOccurrenceDate.SelectedDate = RockDateTime.Today;

                    int?locationId = PageParameter("LocationId").AsIntegerOrNull();
                    if (locationId.HasValue)
                    {
                        lLocation.Visible   = true;
                        lLocation.Text      = new LocationService(_rockContext).GetPath(locationId.Value);
                        ddlLocation.Visible = false;

                        Schedule schedule   = null;
                        int?     scheduleId = PageParameter("ScheduleId").AsIntegerOrNull();
                        if (scheduleId.HasValue)
                        {
                            schedule = new ScheduleService(_rockContext).Get(scheduleId.Value);
                        }

                        if (schedule != null)
                        {
                            lSchedule.Visible   = true;
                            lSchedule.Text      = schedule.Name;
                            ddlSchedule.Visible = false;
                        }
                        else
                        {
                            BindSchedules(locationId.Value);
                            lSchedule.Visible   = false;
                            ddlSchedule.Visible = ddlSchedule.Items.Count > 1;
                        }
                    }
                    else
                    {
                        lLocation.Visible   = false;
                        ddlLocation.Visible = ddlLocation.Items.Count > 1;

                        lSchedule.Visible   = false;
                        ddlSchedule.Visible = ddlSchedule.Items.Count > 1;
                    }
                }

                lMembers.Text        = _group.GroupType.GroupMemberTerm.Pluralize();
                lPendingMembers.Text = "Pending " + lMembers.Text;

                List <int> attendedIds = new List <int>();

                // Load the attendance for the selected occurrence
                if (existingOccurrence)
                {
                    cbDidNotMeet.Checked = _occurrence.DidNotOccur;

                    // Get the list of people who attended
                    attendedIds = new ScheduleService(_rockContext).GetAttendance(_group, _occurrence)
                                  .Where(a => a.DidAttend.HasValue && a.DidAttend.Value)
                                  .Select(a => a.PersonAlias.PersonId)
                                  .Distinct()
                                  .ToList();
                }

                ppAddPerson.Visible = GetAttributeValue("AllowAddingPerson").AsBoolean();

                // Get the group members
                var groupMemberService = new GroupMemberService(_rockContext);

                // Add any existing active members not on that list
                var unattendedIds = groupMemberService
                                    .Queryable().AsNoTracking()
                                    .Where(m =>
                                           m.GroupId == _group.Id &&
                                           m.GroupMemberStatus == GroupMemberStatus.Active &&
                                           !attendedIds.Contains(m.PersonId))
                                    .Select(m => m.PersonId)
                                    .ToList();

                string template    = GetAttributeValue("LavaTemplate");
                var    mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                // Bind the attendance roster
                _attendees = new PersonService(_rockContext)
                             .Queryable().AsNoTracking()
                             .Where(p => attendedIds.Contains(p.Id) || unattendedIds.Contains(p.Id))
                             .ToList()
                             .Select(p => new GroupAttendanceAttendee()
                {
                    PersonId       = p.Id,
                    NickName       = p.NickName,
                    LastName       = p.LastName,
                    Attended       = attendedIds.Contains(p.Id),
                    CampusIds      = p.GetCampusIds(),
                    MergedTemplate = template.ResolveMergeFields(mergeFields.Union(new Dictionary <string, object>()
                    {
                        { "Person", p }
                    }).ToDictionary(x => x.Key, x => x.Value))
                })
                             .ToList();

                BindAttendees();

                // Bind the pending members
                var pendingMembers = groupMemberService
                                     .Queryable().AsNoTracking()
                                     .Where(m =>
                                            m.GroupId == _group.Id &&
                                            m.GroupMemberStatus == GroupMemberStatus.Pending)
                                     .OrderBy(m => m.Person.LastName)
                                     .ThenBy(m => m.Person.NickName)
                                     .Select(m => new
                {
                    Id       = m.PersonId,
                    FullName = m.Person.NickName + " " + m.Person.LastName
                })
                                     .ToList();

                pnlPendingMembers.Visible   = pendingMembers.Any();
                lvPendingMembers.DataSource = pendingMembers;
                lvPendingMembers.DataBind();
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        /// <param name="groupId">The group id.</param>
        public void ShowDetail(string itemKey, int itemKeyValue, int?groupId)
        {
            if (!itemKey.Equals("groupMemberId"))
            {
                return;
            }

            GroupMember groupMember = null;

            if (!itemKeyValue.Equals(0))
            {
                groupMember = new GroupMemberService().Get(itemKeyValue);
                groupMember.LoadAttributes();
            }
            else
            {
                // only create a new one if parent was specified
                if (groupId.HasValue)
                {
                    groupMember = new GroupMember {
                        Id = 0
                    };
                    groupMember.GroupId           = groupId.Value;
                    groupMember.Group             = new GroupService().Get(groupMember.GroupId);
                    groupMember.GroupRoleId       = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0;
                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                }
            }

            if (groupMember == null)
            {
                return;
            }

            hfGroupId.Value       = groupMember.GroupId.ToString();
            hfGroupMemberId.Value = groupMember.Id.ToString();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            var group = groupMember.Group;

            if (!string.IsNullOrWhiteSpace(group.GroupType.IconCssClass))
            {
                lGroupIconHtml.Text = string.Format("<i class='{0}' ></i>", group.GroupType.IconCssClass);
            }
            else
            {
                lGroupIconHtml.Text = string.Empty;
            }

            if (groupMember.Id.Equals(0))
            {
                lReadOnlyTitle.Text = ActionTitle.Add(groupMember.Group.GroupType.GroupTerm + " " + groupMember.Group.GroupType.GroupMemberTerm).FormatAsHtmlTitle();
            }
            else
            {
                lReadOnlyTitle.Text = groupMember.Person.FullName.FormatAsHtmlTitle();
            }

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized("Edit"))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Group.FriendlyTypeName);
            }

            if (groupMember.IsSystem)
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(Group.FriendlyTypeName);
            }

            btnSave.Visible = !readOnly;

            LoadDropDowns();

            ppGroupMemberPerson.SetValue(groupMember.Person);
            ppGroupMemberPerson.Enabled = !readOnly;

            ddlGroupRole.SetValue(groupMember.GroupRoleId);
            ddlGroupRole.Enabled = !readOnly;

            rblStatus.SetValue((int)groupMember.GroupMemberStatus);
            rblStatus.Enabled = !readOnly;

            groupMember.LoadAttributes();
            phAttributes.Controls.Clear();

            Rock.Attribute.Helper.AddEditControls(groupMember, phAttributes, true);
            if (readOnly)
            {
                Rock.Attribute.Helper.AddDisplayControls(groupMember, phAttributesReadOnly);
                phAttributesReadOnly.Visible = true;
                phAttributes.Visible         = false;
            }
            else
            {
                phAttributesReadOnly.Visible = false;
                phAttributes.Visible         = true;
            }
        }
Ejemplo n.º 22
0
        private void BindGrid()
        {
            string type = PageParameter("SearchType");
            string term = PageParameter("SearchTerm");

            if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term))
            {
                term = term.Trim();
                type = type.Trim();
                var rockContext = new RockContext();

                var personService          = new PersonService(rockContext);
                IQueryable <Person> people = null;

                switch (type.ToLower())
                {
                case ("name"):
                {
                    bool allowFirstNameOnly = false;
                    if (!bool.TryParse(PageParameter("AllowFirstNameOnly"), out allowFirstNameOnly))
                    {
                        allowFirstNameOnly = false;
                    }
                    people = personService.GetByFullName(term, allowFirstNameOnly, true);
                    break;
                }

                case ("phone"):
                {
                    var phoneService         = new PhoneNumberService(rockContext);
                    var phoneNumberPersonIds = phoneService.GetPersonIdsByNumber(term);
                    people = personService.Queryable(new PersonService.PersonQueryOptions {
                            IncludeNameless = true
                        }).Where(p => phoneNumberPersonIds.Contains(p.Id));
                    break;
                }

                case ("address"):
                {
                    var groupMemberService   = new GroupMemberService(rockContext);
                    var groupMemberPersonIds = groupMemberService.GetPersonIdsByHomeAddress(term);
                    people = personService.Queryable().Where(p => groupMemberPersonIds.Contains(p.Id));
                    break;
                }

                case ("email"):
                {
                    var emailSearchTypeValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_EMAIL.AsGuid());
                    var searchKeyQry           = new PersonSearchKeyService(rockContext).Queryable();
                    people = personService.Queryable()
                             .Where(p => (term != "" && p.Email.Contains(term)) ||
                                    searchKeyQry.Any(a => emailSearchTypeValueId.HasValue &&
                                                     a.SearchTypeValueId == emailSearchTypeValueId.Value &&
                                                     a.PersonAlias.PersonId == p.Id &&
                                                     a.SearchValue.Contains(term)));
                    break;
                }

                case ("birthdate"):
                {
                    DateTime?birthDate = Request.QueryString["birthdate"].AsDateTime();
                    int?     personId  = Request.QueryString["person-id"].AsIntegerOrNull();
                    if (birthDate == null)
                    {
                        birthDate = term.AsDateTime();
                    }

                    if (personId.HasValue)
                    {
                        people = personService.Queryable().Where(a => a.Id == personId.Value);
                    }
                    else
                    {
                        people = personService.Queryable().Where(p => p.BirthDate.HasValue && birthDate.HasValue && p.BirthDate == birthDate.Value);
                    }

                    break;
                }
                }

                IEnumerable <int> personIdList = people.Select(p => p.Id);

                // just leave the personIdList as a Queryable if it is over 10000 so that we don't throw a SQL exception due to the big list of ids
                if (people.Count() < 10000)
                {
                    personIdList = personIdList.ToList();
                }

                if (personIdList.Count() == 1)
                {
                    // if there is exactly one result, just redirect to the person page
                    int personId = personIdList.First();
                    Response.Redirect(string.Format("~/Person/{0}", personId), false);
                    Context.ApplicationInstance.CompleteRequest();
                    return;
                }

                // since there is not exactly one person found, show the list of people in the grid

                var familyGroupType   = GroupTypeCache.GetFamilyGroupType();
                int familyGroupTypeId = familyGroupType != null ? familyGroupType.Id : 0;

                var groupLocationTypeHome = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
                int homeAddressTypeId     = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0;

                var birthDateCol = gPeople.ColumnsOfType <DateField>().First(c => c.DataField == "BirthDate");
                var ageCol       = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Age");
                var genderCol    = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Gender");

                var envelopeNumberField = gPeople.ColumnsOfType <RockLiteralField>().First(c => c.ID == "lEnvelopeNumber");
                var spouseCol           = gPeople.ColumnsOfType <RockTemplateField>().First(c => c.HeaderText == "Spouse");

                var personGivingEnvelopeAttribute = AttributeCache.Get(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid());
                if (personGivingEnvelopeAttribute != null)
                {
                    envelopeNumberField.Visible = GlobalAttributesCache.Get().EnableGivingEnvelopeNumber&& this.GetAttributeValue(AttributeKey.ShowEnvelopeNumber).AsBoolean();
                }
                else
                {
                    envelopeNumberField.Visible = false;
                }

                birthDateCol.Visible = GetAttributeValue(AttributeKey.ShowBirthdate).AsBoolean();
                ageCol.Visible       = GetAttributeValue(AttributeKey.ShowAge).AsBoolean();
                genderCol.Visible    = GetAttributeValue(AttributeKey.ShowGender).AsBoolean();
                spouseCol.Visible    = _showSpouse;

                people = personService.Queryable(true).Where(p => personIdList.Contains(p.Id));

                SortProperty sortProperty = gPeople.SortProperty;
                if (sortProperty != null)
                {
                    people = people.Sort(sortProperty);
                }
                else
                {
                    people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
                }

                var personList = people.Select(p => new PersonSearchResult
                {
                    Id                      = p.Id,
                    FirstName               = p.FirstName,
                    NickName                = p.NickName,
                    LastName                = p.LastName,
                    BirthDate               = p.BirthDate,
                    DeceasedDate            = p.DeceasedDate,
                    BirthYear               = p.BirthYear,
                    BirthMonth              = p.BirthMonth,
                    BirthDay                = p.BirthDay,
                    ConnectionStatusValueId = p.ConnectionStatusValueId,
                    RecordStatusValueId     = p.RecordStatusValueId,
                    RecordTypeValueId       = p.RecordTypeValueId,
                    AgeClassification       = p.AgeClassification,
                    SuffixValueId           = p.SuffixValueId,
                    IsDeceased              = p.IsDeceased,
                    Email                   = p.Email,
                    Gender                  = p.Gender,
                    PhotoId                 = p.PhotoId,
                    CampusIds               = p.Members
                                              .Where(m =>
                                                     m.Group.GroupTypeId == familyGroupTypeId &&
                                                     m.Group.CampusId.HasValue)
                                              .Select(m => m.Group.CampusId.Value)
                                              .ToList(),
                    HomeAddresses = p.Members
                                    .Where(m => m.Group.GroupTypeId == familyGroupTypeId)
                                    .SelectMany(m => m.Group.GroupLocations)
                                    .Where(gl => gl.GroupLocationTypeValueId == homeAddressTypeId)
                                    .Select(gl => gl.Location),
                    PhoneNumbers = p.PhoneNumbers
                                   .Where(n => n.NumberTypeValueId.HasValue)
                                   .Select(n => new PersonSearchResultPhone
                    {
                        NumberTypeValueId = n.NumberTypeValueId.Value,
                        Number            = n.NumberFormatted,
                        PhoneTypeName     = n.NumberTypeValue.Value
                    })
                                   .ToList(),
                    TopSignalColor        = p.TopSignalColor,
                    TopSignalIconCssClass = p.TopSignalIconCssClass
                }).ToList();


                if (type.ToLower() == "name")
                {
                    var similarNames = personService.GetSimilarNames(term,
                                                                     personList.Select(p => p.Id).ToList(), true);
                    if (similarNames.Any())
                    {
                        var hyperlinks = new List <string>();
                        foreach (string name in similarNames.Distinct())
                        {
                            var pageRef = CurrentPageReference;
                            pageRef.Parameters["SearchTerm"] = name;
                            hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name));
                        }
                        string altNames = string.Join(", ", hyperlinks);
                        nbNotice.Text    = string.Format("Other Possible Matches: {0}", altNames);
                        nbNotice.Visible = true;
                    }
                }

                _inactiveStatus = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);
                var personIds = personList.Select(a => a.Id).ToList();

                if (envelopeNumberField != null && envelopeNumberField.Visible)
                {
                    _envelopeNumbers = new AttributeValueService(rockContext).Queryable()
                                       .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id)
                                       .Where(a => personIds.Contains(a.EntityId.Value))
                                       .Select(a => new
                    {
                        PersonId = a.EntityId.Value,
                        Value    = a.Value
                    }).ToList().ToDictionary(k => k.PersonId, v => v.Value);
                }

                gPeople.EntityTypeId = EntityTypeCache.GetId <Person>();

                gPeople.DataSource = personList;
                gPeople.DataBind();
            }
        }
Ejemplo n.º 23
0
        private void CreateControls(bool setSelection)
        {
            // Load all the attribute controls
            attributeControls.Clear();
            pnlAttributes.Controls.Clear();
            phDuplicates.Controls.Clear();

            var rockContext      = new RockContext();
            var attributeService = new AttributeService(rockContext);
            var locationService  = new LocationService(rockContext);

            foreach (string categoryGuid in GetAttributeValue("AttributeCategories").SplitDelimitedValues(false))
            {
                Guid guid = Guid.Empty;
                if (Guid.TryParse(categoryGuid, out guid))
                {
                    var category = CategoryCache.Read(guid);
                    if (category != null)
                    {
                        var attributeControl = new NewGroupAttributes();
                        attributeControl.ClearRows();
                        pnlAttributes.Controls.Add(attributeControl);
                        attributeControls.Add(attributeControl);
                        attributeControl.ID         = "groupAttributes_" + category.Id.ToString();
                        attributeControl.CategoryId = category.Id;

                        foreach (var attribute in attributeService.GetByCategoryId(category.Id))
                        {
                            if (attribute.IsAuthorized(Authorization.EDIT, CurrentPerson))
                            {
                                attributeControl.AttributeList.Add(AttributeCache.Read(attribute));
                            }
                        }
                    }
                }
            }

            nfmMembers.ClearRows();
            nfciContactInfo.ClearRows();

            var groupMemberService = new GroupMemberService(rockContext);
            int defaultRoleId      = _groupType.DefaultGroupRoleId ?? _groupType.Roles.Select(r => r.Id).FirstOrDefault();

            var location = new Location();

            acAddress.GetValues(location);

            foreach (var groupMember in GroupMembers)
            {
                string groupMemberGuidString = groupMember.Person.Guid.ToString().Replace("-", "_");

                var groupMemberRow = new NewGroupMembersRow();
                groupMemberRow.GroupTypeId = _groupType.Id;
                nfmMembers.Controls.Add(groupMemberRow);
                groupMemberRow.ID              = string.Format("row_{0}", groupMemberGuidString);
                groupMemberRow.RoleUpdated    += groupMemberRow_RoleUpdated;
                groupMemberRow.DeleteClick    += groupMemberRow_DeleteClick;
                groupMemberRow.PersonGuid      = groupMember.Person.Guid;
                groupMemberRow.RequireGender   = nfmMembers.RequireGender;
                groupMemberRow.RequireGrade    = nfmMembers.RequireGrade;
                groupMemberRow.RoleId          = groupMember.GroupRoleId;
                groupMemberRow.ShowGradeColumn = _isFamilyGroupType;
                groupMemberRow.ShowGradePicker = groupMember.GroupRoleId == _childRoleId;
                groupMemberRow.ValidationGroup = BlockValidationGroup;

                var contactInfoRow = new NewGroupContactInfoRow();
                nfciContactInfo.Controls.Add(contactInfoRow);
                contactInfoRow.ID                 = string.Format("ci_row_{0}", groupMemberGuidString);
                contactInfoRow.PersonGuid         = groupMember.Person.Guid;
                contactInfoRow.IsMessagingEnabled = _SMSEnabled;
                contactInfoRow.PersonName         = groupMember.Person.FullName;

                if (_homePhone != null)
                {
                    var homePhoneNumber = groupMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault();
                    if (homePhoneNumber != null)
                    {
                        contactInfoRow.HomePhoneNumber      = PhoneNumber.FormattedNumber(homePhoneNumber.CountryCode, homePhoneNumber.Number);
                        contactInfoRow.HomePhoneCountryCode = homePhoneNumber.CountryCode;
                    }
                    else
                    {
                        contactInfoRow.HomePhoneNumber      = string.Empty;
                        contactInfoRow.HomePhoneCountryCode = string.Empty;
                    }
                }

                if (_cellPhone != null)
                {
                    var cellPhoneNumber = groupMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault();
                    if (cellPhoneNumber != null)
                    {
                        contactInfoRow.CellPhoneNumber      = PhoneNumber.FormattedNumber(cellPhoneNumber.CountryCode, cellPhoneNumber.Number);
                        contactInfoRow.CellPhoneCountryCode = cellPhoneNumber.CountryCode;
                    }
                    else
                    {
                        contactInfoRow.CellPhoneNumber      = string.Empty;
                        contactInfoRow.CellPhoneCountryCode = string.Empty;
                    }
                }

                contactInfoRow.Email = groupMember.Person.Email;

                if (setSelection)
                {
                    if (groupMember.Person != null)
                    {
                        groupMemberRow.TitleValueId            = groupMember.Person.TitleValueId;
                        groupMemberRow.FirstName               = groupMember.Person.FirstName;
                        groupMemberRow.LastName                = groupMember.Person.LastName;
                        groupMemberRow.SuffixValueId           = groupMember.Person.SuffixValueId;
                        groupMemberRow.Gender                  = groupMember.Person.Gender;
                        groupMemberRow.BirthDate               = groupMember.Person.BirthDate;
                        groupMemberRow.ConnectionStatusValueId = groupMember.Person.ConnectionStatusValueId;
                        groupMemberRow.GradeOffset             = groupMember.Person.GradeOffset;
                    }
                }

                foreach (var attributeControl in attributeControls)
                {
                    var attributeRow = new NewGroupAttributesRow();
                    attributeControl.Controls.Add(attributeRow);
                    attributeRow.ID            = string.Format("{0}_{1}", attributeControl.ID, groupMemberGuidString);
                    attributeRow.AttributeList = attributeControl.AttributeList;
                    attributeRow.PersonGuid    = groupMember.Person.Guid;
                    attributeRow.PersonName    = groupMember.Person.FullName;

                    if (setSelection)
                    {
                        attributeRow.SetEditValues(groupMember.Person);
                    }
                }

                if (Duplicates.ContainsKey(groupMember.Person.Guid))
                {
                    var dupRow = new HtmlGenericControl("div");
                    dupRow.AddCssClass("row");
                    dupRow.ID = string.Format("dupRow_{0}", groupMemberGuidString);
                    phDuplicates.Controls.Add(dupRow);

                    var newPersonCol = new HtmlGenericControl("div");
                    newPersonCol.AddCssClass("col-md-6");
                    newPersonCol.ID = string.Format("newPersonCol_{0}", groupMemberGuidString);
                    dupRow.Controls.Add(newPersonCol);

                    newPersonCol.Controls.Add(PersonHtmlPanel(
                                                  groupMemberGuidString,
                                                  groupMember.Person,
                                                  groupMember.GroupRole,
                                                  location,
                                                  rockContext));

                    LinkButton lbRemoveMember = new LinkButton();
                    lbRemoveMember.ID = string.Format("lbRemoveMember_{0}", groupMemberGuidString);
                    lbRemoveMember.AddCssClass("btn btn-danger btn-xs");
                    lbRemoveMember.Text   = "Remove";
                    lbRemoveMember.Click += lbRemoveMember_Click;
                    newPersonCol.Controls.Add(lbRemoveMember);

                    var dupPersonCol = new HtmlGenericControl("div");
                    dupPersonCol.AddCssClass("col-md-6");
                    dupPersonCol.ID = string.Format("dupPersonCol_{0}", groupMemberGuidString);
                    dupRow.Controls.Add(dupPersonCol);

                    var duplicateHeader = new HtmlGenericControl("h4");
                    duplicateHeader.InnerText = "Possible Duplicate Records";
                    dupPersonCol.Controls.Add(duplicateHeader);

                    foreach (var duplicate in Duplicates[groupMember.Person.Guid])
                    {
                        GroupTypeRole groupTypeRole = null;
                        Location      duplocation   = null;

                        var dupGroupMember = groupMemberService.Queryable()
                                             .Where(a => a.PersonId == duplicate.Id)
                                             .Where(a => a.Group.GroupTypeId == _groupType.Id)
                                             .Select(s => new
                        {
                            s.GroupRole,
                            GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid.Equals(_locationType.Guid)).Select(a => a.Location).FirstOrDefault()
                        })
                                             .FirstOrDefault();
                        if (dupGroupMember != null)
                        {
                            groupTypeRole = dupGroupMember.GroupRole;
                            duplocation   = dupGroupMember.GroupLocation;
                        }

                        dupPersonCol.Controls.Add(PersonHtmlPanel(
                                                      groupMemberGuidString,
                                                      duplicate,
                                                      groupTypeRole,
                                                      duplocation,
                                                      rockContext));
                    }
                }
            }

            ShowPage();
        }
Ejemplo n.º 24
0
        private void BindGrid()
        {
            string type = PageParameter("SearchType");
            string term = PageParameter("SearchTerm");

            if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term))
            {
                term = term.Trim();
                type = type.Trim();
                var rockContext = new RockContext();

                var personService          = new PersonService(rockContext);
                IQueryable <Person> people = null;

                switch (type.ToLower())
                {
                case ("name"):
                {
                    bool allowFirstNameOnly = false;
                    if (!bool.TryParse(PageParameter("allowFirstNameOnly"), out allowFirstNameOnly))
                    {
                        allowFirstNameOnly = false;
                    }
                    people = personService.GetByFullName(term, allowFirstNameOnly, true);
                    break;
                }

                case ("phone"):
                {
                    var phoneService = new PhoneNumberService(rockContext);
                    var personIds    = phoneService.GetPersonIdsByNumber(term);
                    people = personService.Queryable().Where(p => personIds.Contains(p.Id));
                    break;
                }

                case ("address"):
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var personIds2         = groupMemberService.GetPersonIdsByHomeAddress(term);
                    people = personService.Queryable().Where(p => personIds2.Contains(p.Id));
                    break;
                }

                case ("email"):
                {
                    people = personService.Queryable().Where(p => p.Email.Contains(term));
                    break;
                }
                }

                SortProperty sortProperty = gPeople.SortProperty;
                if (sortProperty != null)
                {
                    people = people.Sort(sortProperty);
                }
                else
                {
                    people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
                }

                Guid familyGuid          = new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);
                Guid homeAddressTypeGuid = new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);

                var personList = people.Select(p => new PersonSearchResult
                {
                    Id         = p.Id,
                    FirstName  = p.FirstName,
                    NickName   = p.NickName,
                    LastName   = p.LastName,
                    BirthDate  = p.BirthDate,
                    BirthYear  = p.BirthYear,
                    BirthMonth = p.BirthMonth,
                    BirthDay   = p.BirthDay,
                    ConnectionStatusValueId = p.ConnectionStatusValueId,
                    RecordStatusValueId     = p.RecordStatusValueId,
                    RecordTypeValueId       = p.RecordTypeValueId,
                    SuffixValueId           = p.SuffixValueId,
                    IsDeceased = p.IsDeceased,
                    Email      = p.Email,
                    Gender     = p.Gender,
                    PhotoId    = p.PhotoId,
                    CampusIds  = p.Members
                                 .Where(m =>
                                        m.Group.GroupType.Guid.Equals(familyGuid) &&
                                        m.Group.CampusId.HasValue)
                                 .Select(m => m.Group.CampusId.Value)
                                 .ToList(),
                    HomeAddresses = p.Members
                                    .Where(m => m.Group.GroupType.Guid == familyGuid)
                                    .SelectMany(m => m.Group.GroupLocations)
                                    .Where(gl => gl.GroupLocationTypeValue.Guid.Equals(homeAddressTypeGuid))
                                    .Select(gl => gl.Location)
                }).ToList();

                if (personList.Count == 1)
                {
                    Response.Redirect(string.Format("~/Person/{0}", personList[0].Id), false);
                    Context.ApplicationInstance.CompleteRequest();
                }
                else
                {
                    if (type.ToLower() == "name")
                    {
                        var similiarNames = personService.GetSimiliarNames(term,
                                                                           personList.Select(p => p.Id).ToList(), true);
                        if (similiarNames.Any())
                        {
                            var hyperlinks = new List <string>();
                            foreach (string name in similiarNames.Distinct())
                            {
                                var pageRef = CurrentPageReference;
                                pageRef.Parameters["SearchTerm"] = name;
                                hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name));
                            }
                            string altNames = string.Join(", ", hyperlinks);
                            nbNotice.Text    = string.Format("Other Possible Matches: {0}", altNames);
                            nbNotice.Visible = true;
                        }
                    }

                    _inactiveStatus      = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);
                    gPeople.EntityTypeId = EntityTypeCache.GetId <Person>();

                    gPeople.DataSource = personList;
                    gPeople.DataBind();
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets the merge object list for the current EntitySet
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="fetchCount">The fetch count.</param>
        /// <returns></returns>
        private List <object> GetMergeObjectList(RockContext rockContext, int?fetchCount = null)
        {
            int entitySetId      = hfEntitySetId.Value.AsInteger();
            var entitySetService = new EntitySetService(rockContext);
            var entitySet        = entitySetService.Get(entitySetId);
            Dictionary <int, object> mergeObjectsDictionary = new Dictionary <int, object>();

            // If this EntitySet contains IEntity Items, add those first
            if (entitySet.EntityTypeId.HasValue)
            {
                var qryEntity = entitySetService.GetEntityQuery(entitySetId);

                if (fetchCount.HasValue)
                {
                    qryEntity = qryEntity.Take(fetchCount.Value);
                }

                var  entityTypeCache         = EntityTypeCache.Read(entitySet.EntityTypeId.Value);
                bool isPersonEntityType      = entityTypeCache != null && entityTypeCache.Guid == Rock.SystemGuid.EntityType.PERSON.AsGuid();
                bool isGroupMemberEntityType = entityTypeCache != null && entityTypeCache.Guid == Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid();
                bool combineFamilyMembers    = cbCombineFamilyMembers.Visible && cbCombineFamilyMembers.Checked;

                if ((isGroupMemberEntityType || isPersonEntityType) && combineFamilyMembers)
                {
                    IQueryable <IEntity> qryPersons;
                    if (isGroupMemberEntityType)
                    {
                        qryPersons = qryEntity.OfType <GroupMember>().Select(a => a.Person).Distinct();
                    }
                    else
                    {
                        qryPersons = qryEntity;
                    }

                    Guid familyGroupType       = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                    var  qryFamilyGroupMembers = new GroupMemberService(rockContext).Queryable()
                                                 .Where(a => a.Group.GroupType.Guid == familyGroupType)
                                                 .Where(a => qryPersons.Any(aa => aa.Id == a.PersonId));

                    var qryCombined = qryFamilyGroupMembers.Join(
                        qryPersons,
                        m => m.PersonId,
                        p => p.Id,
                        (m, p) => new { GroupMember = m, Person = p })
                                      .GroupBy(a => a.GroupMember.GroupId)
                                      .Select(x => new
                    {
                        GroupId = x.Key,
                        Persons = x.Select(xx => xx.Person).Distinct()
                    });

                    foreach (var combinedFamilyItem in qryCombined)
                    {
                        object mergeObject;

                        string commaPersonIds = combinedFamilyItem.Persons.Select(a => a.Id).Distinct().ToList().AsDelimited(",");

                        var primaryGroupPerson = combinedFamilyItem.Persons.FirstOrDefault() as Person;

                        if (mergeObjectsDictionary.ContainsKey(primaryGroupPerson.Id))
                        {
                            foreach (var person in combinedFamilyItem.Persons)
                            {
                                if (!mergeObjectsDictionary.ContainsKey(person.Id))
                                {
                                    primaryGroupPerson = person as Person;
                                    break;
                                }
                            }
                        }

                        // if we are combining from a GroupMemberEntityType list add the GroupMember attributes of the primary person in the combined list
                        if (isGroupMemberEntityType)
                        {
                            var groupMember = qryEntity.OfType <GroupMember>().Where(a => a.PersonId == primaryGroupPerson.Id).FirstOrDefault();
                            primaryGroupPerson.AdditionalLavaFields = primaryGroupPerson.AdditionalLavaFields ?? new Dictionary <string, object>();
                            if (groupMember != null)
                            {
                                primaryGroupPerson.AdditionalLavaFields.AddOrIgnore("GroupMember", groupMember);
                            }
                        }

                        if (combinedFamilyItem.Persons.Count() > 1)
                        {
                            var combinedPerson = primaryGroupPerson.ToJson().FromJsonOrNull <MergeTemplateCombinedPerson>();

                            var familyTitle = RockUdfHelper.ufnCrm_GetFamilyTitle(rockContext, null, combinedFamilyItem.GroupId, commaPersonIds, true);
                            combinedPerson.FullName = familyTitle;

                            var firstNameList = combinedFamilyItem.Persons.Select(a => (a as Person).FirstName).ToList();
                            var nickNameList  = combinedFamilyItem.Persons.Select(a => (a as Person).NickName).ToList();

                            combinedPerson.FirstName     = firstNameList.AsDelimited(", ", " & ");
                            combinedPerson.NickName      = nickNameList.AsDelimited(", ", " & ");
                            combinedPerson.LastName      = primaryGroupPerson.LastName;
                            combinedPerson.SuffixValueId = null;
                            combinedPerson.SuffixValue   = null;
                            mergeObject = combinedPerson;
                        }
                        else
                        {
                            mergeObject = primaryGroupPerson;
                        }

                        mergeObjectsDictionary.AddOrIgnore(primaryGroupPerson.Id, mergeObject);
                    }
                }
                else if (isGroupMemberEntityType)
                {
                    foreach (var groupMember in qryEntity.AsNoTracking().OfType <GroupMember>())
                    {
                        var person = groupMember.Person;
                        person.AdditionalLavaFields = new Dictionary <string, object>();
                        person.AdditionalLavaFields.Add("GroupMember", groupMember);
                        mergeObjectsDictionary.AddOrIgnore(groupMember.PersonId, person);
                    }
                }
                else
                {
                    foreach (var item in qryEntity.AsNoTracking())
                    {
                        mergeObjectsDictionary.AddOrIgnore(item.Id, item);
                    }
                }
            }

            var entitySetItemService = new EntitySetItemService(rockContext);

            string[] emptyJson = new string[] { string.Empty, "{}" };
            var      entitySetItemMergeValuesQry = entitySetItemService.GetByEntitySetId(entitySetId, true).Where(a => !emptyJson.Contains(a.AdditionalMergeValuesJson));

            if (fetchCount.HasValue)
            {
                entitySetItemMergeValuesQry = entitySetItemMergeValuesQry.Take(fetchCount.Value);
            }

            // the entityId to use for NonEntity objects
            int nonEntityId = 1;

            // now, add the additional MergeValues regardless of if the EntitySet contains IEntity items or just Non-IEntity items
            foreach (var additionalMergeValuesItem in entitySetItemMergeValuesQry.AsNoTracking())
            {
                object mergeObject;
                int    entityId;
                if (additionalMergeValuesItem.EntityId > 0)
                {
                    entityId = additionalMergeValuesItem.EntityId;
                }
                else
                {
                    // not pointing to an actual EntityId, so use the nonEntityId for ti
                    entityId = nonEntityId++;
                }

                if (mergeObjectsDictionary.ContainsKey(entityId))
                {
                    mergeObject = mergeObjectsDictionary[entityId];
                }
                else
                {
                    if (entitySet.EntityTypeId.HasValue)
                    {
                        // if already have real entities in our list, don't add additional items to the mergeObjectsDictionary
                        continue;
                    }

                    // non-Entity merge object, so just use Dictionary
                    mergeObject = new Dictionary <string, object>();
                    mergeObjectsDictionary.AddOrIgnore(entityId, mergeObject);
                }

                foreach (var additionalMergeValue in additionalMergeValuesItem.AdditionalMergeValues)
                {
                    if (mergeObject is IEntity)
                    {
                        // add the additional fields to AdditionalLavaFields
                        IEntity mergeEntity = (mergeObject as IEntity);
                        mergeEntity.AdditionalLavaFields = mergeEntity.AdditionalLavaFields ?? new Dictionary <string, object>();
                        object mergeValueObject = additionalMergeValue.Value;

                        // if the mergeValueObject is a JArray (JSON Object), convert it into an ExpandoObject or List<ExpandoObject> so that Lava will work on it
                        if (mergeValueObject is JArray)
                        {
                            var jsonOfObject = mergeValueObject.ToJson();
                            try
                            {
                                mergeValueObject = Rock.Lava.RockFilters.FromJSON(jsonOfObject);
                            }
                            catch (Exception ex)
                            {
                                LogException(new Exception("MergeTemplateEntry couldn't do a FromJSON", ex));
                            }
                        }

                        mergeEntity.AdditionalLavaFields.AddOrIgnore(additionalMergeValue.Key, mergeValueObject);
                    }
                    else if (mergeObject is IDictionary <string, object> )
                    {
                        // anonymous object with no fields yet
                        IDictionary <string, object> nonEntityObject = mergeObject as IDictionary <string, object>;
                        nonEntityObject.AddOrIgnore(additionalMergeValue.Key, additionalMergeValue.Value);
                    }
                    else
                    {
                        throw new Exception(string.Format("Unexpected MergeObject Type: {0}", mergeObject));
                    }
                }
            }

            var result = mergeObjectsDictionary.Select(a => a.Value);

            if (fetchCount.HasValue)
            {
                // make sure the result is limited to fetchCount (even though the above queries are also limited to fetch count)
                result = result.Take(fetchCount.Value);
            }

            return(result.ToList());
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Binds the data.
        /// </summary>
        private void BindData()
        {
            ShowRole = GetAttributeValue("ShowRole").AsBoolean();

            if (person != null && person.Id > 0)
            {
                if (ownerRoleGuid != Guid.Empty)
                {
                    using (var rockContext = new RockContext())
                    {
                        var memberService = new GroupMemberService(rockContext);
                        var group         = memberService.Queryable(true)
                                            .Where(m =>
                                                   m.PersonId == person.Id &&
                                                   m.GroupRole.Guid == ownerRoleGuid)
                                            .Select(m => m.Group)
                                            .FirstOrDefault();

                        if (group != null)
                        {
                            lGroupName.Text        = group.Name.Pluralize();
                            lGroupTypeIcon.Text    = string.Format("<i class='{0}'></i>", group.GroupType.IconCssClass);
                            lGroupTypeIcon.Visible = !string.IsNullOrWhiteSpace(group.GroupType.IconCssClass);

                            if (group.IsAuthorized(Authorization.VIEW, CurrentPerson))
                            {
                                int?maxRelationshipsToDisplay = this.GetAttributeValue("MaxRelationshipsToDisplay").AsIntegerOrNull();

                                var roles = new List <int>();
                                if (canCheckInOnly)
                                {
                                    foreach (var role in new GroupTypeRoleService(rockContext)
                                             .Queryable().AsNoTracking()
                                             .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS))))
                                    {
                                        role.LoadAttributes(rockContext);
                                        if (role.Attributes.ContainsKey("CanCheckin"))
                                        {
                                            bool canCheckIn = false;
                                            if (bool.TryParse(role.GetAttributeValue("CanCheckin"), out canCheckIn) && canCheckIn)
                                            {
                                                roles.Add(role.Id);
                                            }
                                        }

                                        if (role.Attributes.ContainsKey("InverseRelationship"))
                                        {
                                            var inverseRoleGuid = role.GetAttributeValue("InverseRelationship").AsGuidOrNull();
                                            if (inverseRoleGuid != null)
                                            {
                                                var groupTypeRole = new GroupTypeRoleService(rockContext)
                                                                    .Queryable().AsNoTracking()
                                                                    .FirstOrDefault(r => r.Guid.Equals(( Guid )inverseRoleGuid));
                                                if (groupTypeRole != null)
                                                {
                                                    groupTypeRole.LoadAttributes(rockContext);
                                                    if (groupTypeRole.Attributes.ContainsKey("CanCheckin"))
                                                    {
                                                        bool canCheckIn = false;
                                                        if (bool.TryParse(groupTypeRole.GetAttributeValue("CanCheckin"), out canCheckIn) && canCheckIn)
                                                        {
                                                            roles.Add(role.Id);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (var role in new GroupTypeRoleService(rockContext)
                                             .Queryable().AsNoTracking()
                                             .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS))))
                                    {
                                        roles.Add(role.Id);
                                    }
                                }

                                IQueryable <GroupMember> qryGroupMembers = new GroupMemberService(rockContext).GetByGroupId(group.Id, true)
                                                                           .Where(m => m.PersonId != person.Id)
                                                                           .Where(m => roles.Contains(m.GroupRoleId))
                                                                           .OrderBy(m => m.Person.LastName)
                                                                           .ThenBy(m => m.Person.FirstName);

                                if (maxRelationshipsToDisplay.HasValue)
                                {
                                    qryGroupMembers = qryGroupMembers.Take(maxRelationshipsToDisplay.Value);
                                }

                                rGroupMembers.ItemDataBound += rptrMembers_ItemDataBound;
                                rGroupMembers.DataSource     = qryGroupMembers.ToList();
                                rGroupMembers.DataBind();
                            }
                            else
                            {
                                lAccessWarning.Text = string.Format("<div class='alert alert-info'>You do not have security rights to view {0}.", group.Name.Pluralize());
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (RegistrantState != null)
            {
                RockContext            rockContext                    = new RockContext();
                var                    personService                  = new PersonService(rockContext);
                var                    registrantService              = new RegistrationRegistrantService(rockContext);
                var                    registrantFeeService           = new RegistrationRegistrantFeeService(rockContext);
                var                    registrationTemplateFeeService = new RegistrationTemplateFeeService(rockContext);
                RegistrationRegistrant registrant = null;
                if (RegistrantState.Id > 0)
                {
                    registrant = registrantService.Get(RegistrantState.Id);
                }

                bool newRegistrant     = false;
                var  registrantChanges = new List <string>();

                if (registrant == null)
                {
                    newRegistrant             = true;
                    registrant                = new RegistrationRegistrant();
                    registrant.RegistrationId = RegistrantState.RegistrationId;
                    registrantService.Add(registrant);
                    registrantChanges.Add("Created Registrant");
                }

                if (!registrant.PersonAliasId.Equals(ppPerson.PersonAliasId))
                {
                    string prevPerson = (registrant.PersonAlias != null && registrant.PersonAlias.Person != null) ?
                                        registrant.PersonAlias.Person.FullName : string.Empty;
                    string newPerson = ppPerson.PersonName;
                    History.EvaluateChange(registrantChanges, "Person", prevPerson, newPerson);
                }
                int?personId = ppPerson.PersonId.Value;
                registrant.PersonAliasId = ppPerson.PersonAliasId.Value;

                // Get the name of registrant for history
                string registrantName = "Unknown";
                if (ppPerson.PersonId.HasValue)
                {
                    var person = personService.Get(ppPerson.PersonId.Value);
                    if (person != null)
                    {
                        registrantName = person.FullName;
                    }
                }

                History.EvaluateChange(registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal());
                registrant.Cost = cbCost.Text.AsDecimal();

                if (!Page.IsValid)
                {
                    return;
                }

                // Remove/delete any registrant fees that are no longer in UI with quantity
                foreach (var dbFee in registrant.Fees.ToList())
                {
                    if (!RegistrantState.FeeValues.Keys.Contains(dbFee.RegistrationTemplateFeeId) ||
                        RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null ||
                        !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId]
                        .Any(f =>
                             f.Option == dbFee.Option &&
                             f.Quantity > 0))
                    {
                        registrantChanges.Add(string.Format("Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}",
                                                            dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option));

                        registrant.Fees.Remove(dbFee);
                        registrantFeeService.Delete(dbFee);
                    }
                }

                // Add/Update any of the fees from UI
                foreach (var uiFee in RegistrantState.FeeValues.Where(f => f.Value != null))
                {
                    foreach (var uiFeeOption in uiFee.Value)
                    {
                        var dbFee = registrant.Fees
                                    .Where(f =>
                                           f.RegistrationTemplateFeeId == uiFee.Key &&
                                           f.Option == uiFeeOption.Option)
                                    .FirstOrDefault();

                        if (dbFee == null)
                        {
                            dbFee = new RegistrationRegistrantFee();
                            dbFee.RegistrationTemplateFeeId = uiFee.Key;
                            dbFee.Option = uiFeeOption.Option;
                            registrant.Fees.Add(dbFee);
                        }

                        var templateFee = dbFee.RegistrationTemplateFee;
                        if (templateFee == null)
                        {
                            templateFee = registrationTemplateFeeService.Get(uiFee.Key);
                        }

                        string feeName = templateFee != null ? templateFee.Name : "Fee";
                        if (!string.IsNullOrWhiteSpace(uiFeeOption.Option))
                        {
                            feeName = string.Format("{0} ({1})", feeName, uiFeeOption.Option);
                        }

                        if (dbFee.Id <= 0)
                        {
                            registrantChanges.Add(feeName + " Fee Added");
                        }

                        History.EvaluateChange(registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity);
                        dbFee.Quantity = uiFeeOption.Quantity;

                        History.EvaluateChange(registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost);
                        dbFee.Cost = uiFeeOption.Cost;
                    }
                }

                if (TemplateState.RequiredSignatureDocumentTemplate != null)
                {
                    var person = new PersonService(rockContext).Get(personId.Value);

                    var documentService        = new SignatureDocumentService(rockContext);
                    var binaryFileService      = new BinaryFileService(rockContext);
                    SignatureDocument document = null;

                    int?signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull();
                    int?binaryFileId        = fuSignedDocument.BinaryFileId;
                    if (signatureDocumentId.HasValue)
                    {
                        document = documentService.Get(signatureDocumentId.Value);
                    }

                    if (document == null && binaryFileId.HasValue)
                    {
                        var instance = new RegistrationInstanceService(rockContext).Get(RegistrationInstanceId);

                        document = new SignatureDocument();
                        document.SignatureDocumentTemplateId = TemplateState.RequiredSignatureDocumentTemplate.Id;
                        document.AppliesToPersonAliasId      = registrant.PersonAliasId.Value;
                        document.AssignedToPersonAliasId     = registrant.PersonAliasId.Value;
                        document.Name = string.Format("{0}_{1}",
                                                      (instance != null ? instance.Name : TemplateState.Name),
                                                      (person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty));
                        document.Status         = SignatureDocumentStatus.Signed;
                        document.LastStatusDate = RockDateTime.Now;
                        documentService.Add(document);
                    }

                    if (document != null)
                    {
                        int?origBinaryFileId = document.BinaryFileId;
                        document.BinaryFileId = binaryFileId;

                        if (origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId)
                        {
                            // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                            var oldBinaryFile = binaryFileService.Get(origBinaryFileId.Value);
                            if (oldBinaryFile != null && !oldBinaryFile.IsTemporary)
                            {
                                oldBinaryFile.IsTemporary = true;
                            }
                        }

                        // ensure the IsTemporary is set to false on binaryFile associated with this document
                        if (document.BinaryFileId.HasValue)
                        {
                            var binaryFile = binaryFileService.Get(document.BinaryFileId.Value);
                            if (binaryFile != null && binaryFile.IsTemporary)
                            {
                                binaryFile.IsTemporary = false;
                            }
                        }
                    }
                }

                if (!registrant.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    registrant.LoadAttributes();
                    foreach (var field in TemplateState.Forms
                             .SelectMany(f => f.Fields
                                         .Where(t =>
                                                t.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                                t.AttributeId.HasValue)))
                    {
                        var attribute = AttributeCache.Read(field.AttributeId.Value);
                        if (attribute != null)
                        {
                            string originalValue = registrant.GetAttributeValue(attribute.Key);
                            var fieldValue       = RegistrantState.FieldValues
                                                   .Where(f => f.Key == field.Id)
                                                   .Select(f => f.Value.FieldValue)
                                                   .FirstOrDefault();
                            string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty;

                            if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                            {
                                string formattedOriginalValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(originalValue))
                                {
                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                                }

                                string formattedNewValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(newValue))
                                {
                                    formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                                }

                                History.EvaluateChange(registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue);
                            }

                            if (fieldValue != null)
                            {
                                registrant.SetAttributeValue(attribute.Key, fieldValue.ToString());
                            }
                        }
                    }

                    registrant.SaveAttributeValues(rockContext);
                });

                if (newRegistrant && TemplateState.GroupTypeId.HasValue && ppPerson.PersonId.HasValue)
                {
                    using (var newRockContext = new RockContext())
                    {
                        var reloadedRegistrant = new RegistrationRegistrantService(newRockContext).Get(registrant.Id);
                        if (reloadedRegistrant != null &&
                            reloadedRegistrant.Registration != null &&
                            reloadedRegistrant.Registration.Group != null &&
                            reloadedRegistrant.Registration.Group.GroupTypeId == TemplateState.GroupTypeId.Value)
                        {
                            int?groupRoleId = TemplateState.GroupMemberRoleId.HasValue ?
                                              TemplateState.GroupMemberRoleId.Value :
                                              reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId;
                            if (groupRoleId.HasValue)
                            {
                                var groupMemberService = new GroupMemberService(newRockContext);
                                var groupMember        = groupMemberService
                                                         .Queryable().AsNoTracking()
                                                         .Where(m =>
                                                                m.GroupId == reloadedRegistrant.Registration.Group.Id &&
                                                                m.PersonId == reloadedRegistrant.PersonId &&
                                                                m.GroupRoleId == groupRoleId.Value)
                                                         .FirstOrDefault();
                                if (groupMember == null)
                                {
                                    groupMember = new GroupMember();
                                    groupMemberService.Add(groupMember);
                                    groupMember.GroupId           = reloadedRegistrant.Registration.Group.Id;
                                    groupMember.PersonId          = ppPerson.PersonId.Value;
                                    groupMember.GroupRoleId       = groupRoleId.Value;
                                    groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus;

                                    newRockContext.SaveChanges();

                                    registrantChanges.Add(string.Format("Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name));
                                }
                                else
                                {
                                    registrantChanges.Add(string.Format("Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name));
                                }

                                reloadedRegistrant.GroupMemberId = groupMember.Id;
                                newRockContext.SaveChanges();
                            }
                        }
                    }
                }

                HistoryService.SaveChanges(
                    rockContext,
                    typeof(Registration),
                    Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(),
                    registrant.RegistrationId,
                    registrantChanges,
                    "Registrant: " + registrantName,
                    null, null);
            }

            NavigateToRegistration();
        }
Ejemplo n.º 28
0
        /// <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, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

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

                    var familyLabels = new List <Guid>();

                    var people = family.GetPeople(true);
                    foreach (var person in people)
                    {
                        var personGroupTypes = person.GetGroupTypes(true);
                        var groupTypes       = new List <CheckInGroupType>();

                        // Get Primary area group types first
                        personGroupTypes.Where(t => checkInState.ConfiguredGroupTypes.Contains(t.GroupType.Id)).ToList().ForEach(t => groupTypes.Add(t));

                        // Then get additional areas
                        personGroupTypes.Where(t => !checkInState.ConfiguredGroupTypes.Contains(t.GroupType.Id)).ToList().ForEach(t => groupTypes.Add(t));

                        var personLabels = new List <Guid>();

                        foreach (var groupType in groupTypes)
                        {
                            groupType.Labels = new List <CheckInLabel>();

                            var groupTypeLabels = GetGroupTypeLabels(groupType.GroupType);

                            var PrinterIPs = new Dictionary <int, string>();

                            foreach (var labelCache in groupTypeLabels.OrderBy(l => l.LabelType).ThenBy(l => l.Order))
                            {
                                person.SetOptions(labelCache);

                                foreach (var group in groupType.GetGroups(true))
                                {
                                    foreach (var location in group.GetLocations(true))
                                    {
                                        if (labelCache.LabelType == KioskLabelType.Family)
                                        {
                                            if (familyLabels.Contains(labelCache.Guid) ||
                                                personLabels.Contains(labelCache.Guid))
                                            {
                                                break;
                                            }
                                            else
                                            {
                                                familyLabels.Add(labelCache.Guid);
                                            }
                                        }
                                        else if (labelCache.LabelType == KioskLabelType.Person)
                                        {
                                            if (personLabels.Contains(labelCache.Guid))
                                            {
                                                break;
                                            }
                                            else
                                            {
                                                personLabels.Add(labelCache.Guid);
                                            }
                                        }

                                        var mergeObjects = new Dictionary <string, object>();
                                        foreach (var keyValue in commonMergeFields)
                                        {
                                            mergeObjects.Add(keyValue.Key, keyValue.Value);
                                        }

                                        mergeObjects.Add("Location", location);
                                        mergeObjects.Add("Group", group);
                                        mergeObjects.Add("Person", person);
                                        mergeObjects.Add("People", people);
                                        mergeObjects.Add("GroupType", groupType);

                                        var groupMembers = groupMemberService.Queryable().AsNoTracking()
                                                           .Where(m =>
                                                                  m.PersonId == person.Person.Id &&
                                                                  m.GroupId == group.Group.Id)
                                                           .ToList();
                                        mergeObjects.Add("GroupMembers", groupMembers);

                                        //string debugInfo = mergeObjects.lavaDebugInfo();
                                        var label = new CheckInLabel(labelCache, mergeObjects, person.Person.Id);
                                        label.FileGuid  = labelCache.Guid;
                                        label.PrintFrom = checkInState.Kiosk.Device.PrintFrom;
                                        label.PrintTo   = checkInState.Kiosk.Device.PrintToOverride;

                                        if (label.PrintTo == PrintTo.Default)
                                        {
                                            label.PrintTo = groupType.GroupType.AttendancePrintTo;
                                        }

                                        if (label.PrintTo == PrintTo.Kiosk)
                                        {
                                            var device = checkInState.Kiosk.Device;
                                            if (device != null)
                                            {
                                                label.PrinterDeviceId = device.PrinterDeviceId;
                                            }
                                        }
                                        else if (label.PrintTo == PrintTo.Location)
                                        {
                                            var deviceId = location.Location.PrinterDeviceId;
                                            if (deviceId != null)
                                            {
                                                label.PrinterDeviceId = deviceId;
                                            }
                                        }

                                        if (label.PrinterDeviceId.HasValue)
                                        {
                                            if (PrinterIPs.ContainsKey(label.PrinterDeviceId.Value))
                                            {
                                                label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value];
                                            }
                                            else
                                            {
                                                var printerDevice = new DeviceService(rockContext).Get(label.PrinterDeviceId.Value);
                                                if (printerDevice != null)
                                                {
                                                    PrinterIPs.Add(printerDevice.Id, printerDevice.IPAddress);
                                                    label.PrinterAddress = printerDevice.IPAddress;
                                                }
                                            }
                                        }

                                        groupType.Labels.Add(label);
                                    }
                                }
                            }
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Determine which group to add the person to
            Group group       = null;
            int?  groupRoleId = null;

            var groupAndRoleValues = (GetAttributeValue(action, "GroupAndRole") ?? string.Empty).Split('|');

            if (groupAndRoleValues.Count() > 1)
            {
                var groupGuid = groupAndRoleValues[1].AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (groupAndRoleValues.Count() > 2)
                    {
                        var groupTypeRoleGuid = groupAndRoleValues[2].AsGuidOrNull();
                        if (groupTypeRoleGuid.HasValue)
                        {
                            var groupRole = new GroupTypeRoleService(rockContext).Get(groupTypeRoleGuid.Value);
                            if (groupRole != null)
                            {
                                groupRoleId = groupRole.Id;
                            }
                        }
                    }

                    if (!groupRoleId.HasValue && group != null)
                    {
                        // use the group's grouptype's default group role if a group role wasn't specified
                        groupRoleId = group.GroupType.DefaultGroupRoleId;
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("No group role was provided and group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorkflowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var status = this.GetAttributeValue(action, "GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active);

                var  groupMemberService = new GroupMemberService(rockContext);
                var  groupMember        = groupMemberService.GetByGroupIdAndPersonIdAndPreferredGroupRoleId(group.Id, person.Id, groupRoleId.Value);
                bool isNew = false;
                if (groupMember == null)
                {
                    groupMember                   = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupId           = group.Id;
                    groupMember.GroupRoleId       = groupRoleId.Value;
                    groupMember.GroupMemberStatus = status;
                    isNew = true;
                }
                else
                {
                    if (GetAttributeValue(action, "UpdateExisting").AsBoolean())
                    {
                        groupMember.GroupRoleId       = groupRoleId.Value;
                        groupMember.GroupMemberStatus = status;
                    }
                    action.AddLogEntry($"{person.FullName} was already a member of the selected group.", true);
                }

                if (groupMember.IsValidGroupMember(rockContext))
                {
                    if (isNew)
                    {
                        groupMemberService.Add(groupMember);
                    }
                    rockContext.SaveChanges();
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Creates the iCalendar object and populates it with events
        /// </summary>
        /// <param name="calendarProps">The calendar props.</param>
        /// <returns></returns>
        private Calendar CreateICalendar(CalendarProps calendarProps, string interactionDeviceType)
        {
            // Get a list of confirmed attendances filtered by calendarProps
            List <Attendance> attendances = GetAttendances(calendarProps);

            // Create the iCalendar
            var icalendar = new Calendar();

            icalendar.AddTimeZone(TimeZoneInfo.Local);
            TimeSpan duration          = TimeSpan.MinValue;
            int      currentScheduleId = -1;

            // Create each of the attendances
            foreach (var attendance in attendances)
            {
                using (var rockContext = new RockContext())
                {
                    var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);

                    var schedule = attendanceOccurrenceService
                                   .Queryable()
                                   .AsNoTracking()
                                   .Where(a => a.Id == attendance.OccurrenceId)
                                   .Select(a => a.Schedule)
                                   .FirstOrDefault();

                    string scheduleName = schedule.Name;

                    // TODO: Construct a description that includes the group leader contact info and the URL to the schedule toolbox.
                    string description = schedule.Description;

                    string locationName = attendanceOccurrenceService
                                          .Queryable()
                                          .AsNoTracking()
                                          .Where(a => a.Id == attendance.OccurrenceId)
                                          .Select(a => a.Location.Name)
                                          .FirstOrDefault() ?? string.Empty;

                    if (schedule.Id != currentScheduleId)
                    {
                        // We have to get the duration from Schedule.iCal for this attendance.
                        // Attendances are ordered by scheduleId so this only happens once for each unique schedule.
                        var serializer = new CalendarSerializer();
                        var ical       = ( CalendarCollection )serializer.Deserialize(schedule.iCalendarContent.ToStreamReader());
                        duration          = ical[0].Events[0].Duration;
                        currentScheduleId = schedule.Id;
                    }

                    var iCalEvent = new Event();
                    iCalEvent.Summary  = scheduleName;
                    iCalEvent.Location = locationName;
                    iCalEvent.DtStart  = new CalDateTime(attendance.StartDateTime, icalendar.TimeZones[0].TzId);
                    iCalEvent.Duration = duration;

                    // Don't set the description prop for outlook to force it to use the X-ALT-DESC property which can have markup.
                    if (interactionDeviceType != "Outlook")
                    {
                        iCalEvent.Description = description.ConvertBrToCrLf().SanitizeHtml();
                    }

                    // HTML version of the description for outlook
                    iCalEvent.AddProperty("X-ALT-DESC;FMTTYPE=text/html", "<html>" + description + "</html>");

                    // classification: "PUBLIC", "PRIVATE", "CONFIDENTIAL"
                    iCalEvent.Class = "PUBLIC";

                    //Add contact info for the group leader
                    int groupId = attendanceOccurrenceService
                                  .Queryable()
                                  .AsNoTracking()
                                  .Where(a => a.Id == attendance.OccurrenceId)
                                  .Select(a => a.GroupId)
                                  .FirstOrDefault() ?? -1;

                    Person groupLeader = new GroupMemberService(rockContext).GetLeaders(groupId).AsNoTracking().Select(m => m.Person).FirstOrDefault() ?? null;

                    if (groupLeader != null)
                    {
                        iCalEvent.Organizer            = new Organizer(string.Format("MAILTO:{0}", groupLeader.Email));
                        iCalEvent.Organizer.CommonName = groupLeader.FullName;

                        // Outlook doesn't seem to use Contacts or Comments
                        string contactName  = !string.IsNullOrEmpty(groupLeader.FullName) ? "Name: " + groupLeader.FullName : string.Empty;
                        string contactEmail = !string.IsNullOrEmpty(groupLeader.Email) ? ", Email: " + groupLeader.Email : string.Empty;
                        string contactInfo  = contactName + contactEmail;

                        iCalEvent.Contacts.Add(contactInfo);
                        iCalEvent.Comments.Add(contactInfo);
                    }

                    icalendar.Events.Add(iCalEvent);
                }
            }

            return(icalendar);
        }