/// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid()
        {
            if (_group != null)
            {
                pnlGroupMembers.Visible = true;

                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;

                    var rockContext = new RockContext();

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

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

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

                    // Filter by role
                    var validGroupTypeRoles = _group.GroupType.Roles.Select(r => r.Id).ToList();
                    var roles = new List <int>();
                    foreach (string role in cblRole.SelectedValues)
                    {
                        if (!string.IsNullOrWhiteSpace(role))
                        {
                            int roleId = int.MinValue;
                            if (int.TryParse(role, out roleId) && validGroupTypeRoles.Contains(roleId))
                            {
                                roles.Add(roleId);
                            }
                        }
                    }
                    if (roles.Any())
                    {
                        qry = qry.Where(m => roles.Contains(m.GroupRoleId));
                    }

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

                    // Filter the query using any configured attribute filters.
                    if (AvailableAttributes != null && AvailableAttributes.Any())
                    {
                        // Get a reference to the parameter accepted by the Query expression.
                        var methodCallExpression = (MethodCallExpression)qry.Expression;

                        var lambdaDelegate = Expression.Lambda <Func <LambdaExpression> >(methodCallExpression.Arguments[1]).Compile();

                        var lambdaExpression = (Expression <Func <GroupMember, bool> >)(lambdaDelegate.Invoke());

                        var queryParameter = lambdaExpression.Parameters[0];

                        // Add a condition for each of the specified attribute values.
                        foreach (var attribute in AvailableAttributes)
                        {
                            var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());

                            if (filterControl != null)
                            {
                                var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues);

                                var entityField = EntityHelper.GetEntityFieldForAttribute(attribute);

                                var filterExpression = EntityFieldFilter.CreateAttributeExpression(groupMemberService, queryParameter, entityField, filterValues);

                                if (filterExpression == null)
                                {
                                    continue;
                                }

                                qry = qry.Where(queryParameter, filterExpression);
                            }
                        }
                    }

                    _inactiveStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);

                    SortProperty sortProperty = gGroupMembers.SortProperty;

                    List <GroupMember> groupMembers = null;

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

                    // Since we're not binding to actual group member list, but are using AttributeField columns,
                    // we need to save the display data into the grid's object list
                    gGroupMembers.ObjectList = new Dictionary <string, object>();
                    groupMembers.ForEach(m => gGroupMembers.ObjectList.Add(m.Id.ToString(), m));

                    gGroupMembers.DataSource = groupMembers.Select(m => new
                    {
                        m.Id,
                        m.Guid,
                        m.PersonId,
                        Name      = m.Person.NickName + " " + m.Person.LastName,
                        GroupRole = m.GroupRole.Name,
                        m.GroupMemberStatus,
                        ConnectionStatus = m.Person.ConnectionStatusValue.Value
                    }).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>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using (var rockContext = new RockContext())
            {
                var relationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                if (relationshipGroupType != null)
                {
                    var ownerRole = relationshipGroupType.Roles
                                    .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                    .FirstOrDefault();

                    var friendRole = relationshipGroupType.Roles
                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_FACEBOOK_FRIEND.AsGuid()))
                                     .FirstOrDefault();

                    if (ownerRole != null && friendRole != null)
                    {
                        var userLoginService   = new UserLoginService(rockContext);
                        var groupMemberService = new GroupMemberService(rockContext);

                        // Convert list of facebook ids into list of usernames
                        var friendUserNames = FacebookIds.Select(i => "FACEBOOK_" + i).ToList();

                        // Get the list of person ids associated with friends usernames
                        var friendPersonIds = userLoginService.Queryable()
                                              .Where(l =>
                                                     l.PersonId.HasValue &&
                                                     l.PersonId != PersonId &&
                                                     friendUserNames.Contains(l.UserName))
                                              .Select(l => l.PersonId.Value)
                                              .Distinct()
                                              .ToList();

                        // Get the person's group id
                        var personGroup = groupMemberService.Queryable()
                                          .Where(m =>
                                                 m.PersonId == PersonId &&
                                                 m.GroupRoleId == ownerRole.Id &&
                                                 m.Group.GroupTypeId == relationshipGroupType.Id)
                                          .Select(m => m.Group)
                                          .FirstOrDefault();

                        // Verify that a 'known relationships' type group existed for the person, if not create it
                        if (personGroup == null)
                        {
                            var groupMember = new GroupMember();
                            groupMember.PersonId    = PersonId;
                            groupMember.GroupRoleId = ownerRole.Id;

                            personGroup             = new Group();
                            personGroup.Name        = relationshipGroupType.Name;
                            personGroup.GroupTypeId = relationshipGroupType.Id;
                            personGroup.Members.Add(groupMember);

                            var groupService = new GroupService(rockContext);
                            groupService.Add(personGroup);
                            rockContext.SaveChanges();
                        }

                        // Get the person's relationship group id
                        var personGroupId = personGroup.Id;

                        // Get all of the friend's relationship group ids
                        var friendGroupIds = groupMemberService.Queryable()
                                             .Where(m =>
                                                    m.Group.GroupTypeId == relationshipGroupType.Id &&
                                                    m.GroupRoleId == ownerRole.Id &&
                                                    friendPersonIds.Contains(m.PersonId))
                                             .Select(m => m.GroupId)
                                             .Distinct()
                                             .ToList();

                        // Find all the existing friend relationships in Rock ( both directions )
                        var existingFriends = groupMemberService.Queryable()
                                              .Where(m =>
                                                     m.Group.GroupTypeId == relationshipGroupType.Id && (
                                                         (friendPersonIds.Contains(m.PersonId) && m.GroupId == personGroupId) ||
                                                         (m.PersonId == PersonId && m.GroupId != personGroupId)
                                                         ))
                                              .ToList();

                        // Create temp group members for current Facebook friends
                        var currentFriends = new List <GroupMember>();

                        // ( Person > Friend )
                        foreach (int personId in friendPersonIds)
                        {
                            var groupMember = new GroupMember();
                            groupMember.GroupId           = personGroupId;
                            groupMember.PersonId          = personId;
                            groupMember.GroupRoleId       = friendRole.Id;
                            groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                            currentFriends.Add(groupMember);
                        }

                        // ( Friend > Person )
                        foreach (int familyId in friendGroupIds)
                        {
                            var groupMember = new GroupMember();
                            groupMember.GroupId           = familyId;
                            groupMember.PersonId          = PersonId;
                            groupMember.GroupRoleId       = friendRole.Id;
                            groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                            currentFriends.Add(groupMember);
                        }

                        //  Add any current friends that do not exist in Rock yet
                        foreach (var groupMember in currentFriends
                                 .Where(f => !existingFriends.Any(e => e.IsEqualTo(f))))
                        {
                            groupMemberService.Add(groupMember);
                        }

                        // Delete any existing friends that are no longer facebook friends
                        foreach (var groupMember in existingFriends
                                 .Where(f => !currentFriends.Any(e => e.IsEqualTo(f))))
                        {
                            groupMemberService.Delete(groupMember);
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
        }
Beispiel #3
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;
            DateTime attendanceDateTime = DateTime.Now;
            bool     addToGroup         = true;

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

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

                if (!groupGuid.HasValue)
                {
                    errorMessages.Add("The group could not be found!");
                }
            }

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

            Guid guid = personAttribute.AsGuid();

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

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

            // get attendance date
            Guid dateTimeAttributeGuid = GetAttributeValue(action, "AttendanceDatetime").AsGuid();

            if (!dateTimeAttributeGuid.IsEmpty())
            {
                string attributeDatetime = action.GetWorklowAttributeValue(dateTimeAttributeGuid);

                if (!string.IsNullOrWhiteSpace(attributeDatetime))
                {
                    if (!DateTime.TryParse(attributeDatetime, out attendanceDateTime))
                    {
                        errorMessages.Add(string.Format("Could not parse the date provided {0}.", attributeDatetime));
                    }
                }
            }

            // get add to group
            addToGroup = GetAttributeValue(action, "AddToGroup").AsBoolean();

            // get location
            Guid locationGuid          = Guid.Empty;
            Guid locationAttributeGuid = GetAttributeValue(action, "Location").AsGuid();

            if (!locationAttributeGuid.IsEmpty())
            {
                var locationAttribute = AttributeCache.Get(locationAttributeGuid, rockContext);

                if (locationAttribute != null)
                {
                    locationGuid = action.GetWorklowAttributeValue(locationAttributeGuid).AsGuid();
                }
            }

            //// get Schedule
            Guid scheduleGuid          = Guid.Empty;
            Guid scheduleAttributeGuid = GetAttributeValue(action, "Schedule").AsGuid();

            if (!scheduleAttributeGuid.IsEmpty())
            {
                var scheduleAttribute = AttributeCache.Get(scheduleAttributeGuid, rockContext);
                if (scheduleAttribute != null)
                {
                    scheduleGuid = action.GetWorklowAttributeValue(scheduleAttributeGuid).AsGuid();
                }
            }

            // set attribute
            if (groupGuid.HasValue && person != null && attendanceDateTime != DateTime.MinValue)
            {
                var group = new GroupService(rockContext).Queryable("GroupType.DefaultGroupRole")
                            .Where(g => g.Guid == groupGuid)
                            .FirstOrDefault();
                if (group != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);

                    // get group member
                    var groupMember = groupMemberService.Queryable()
                                      .Where(m => m.Group.Guid == groupGuid &&
                                             m.PersonId == person.Id)
                                      .FirstOrDefault();
                    if (groupMember == null)
                    {
                        if (addToGroup)
                        {
                            if (group != null)
                            {
                                groupMember                   = new GroupMember();
                                groupMember.GroupId           = group.Id;
                                groupMember.PersonId          = person.Id;
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMember.GroupRole         = group.GroupType.DefaultGroupRole;
                                groupMemberService.Add(groupMember);
                                rockContext.SaveChanges();
                            }
                        }
                        else
                        {
                            action.AddLogEntry(string.Format("{0} was not a member of the group {1} and the action was not configured to add them.", person.FullName, group.Name));
                        }
                    }

                    int?locationId = null;
                    if (locationGuid != Guid.Empty)
                    {
                        var location = new LocationService(rockContext).Queryable().AsNoTracking()
                                       .Where(l => l.Guid == locationGuid)
                                       .FirstOrDefault();

                        if (location != null)
                        {
                            locationId = location.Id;
                        }
                    }

                    int?scheduleId = null;
                    if (scheduleGuid != Guid.Empty)
                    {
                        var schedule = new ScheduleService(rockContext).Queryable().AsNoTracking()
                                       .Where(l => l.Guid == scheduleGuid)
                                       .FirstOrDefault();

                        if (schedule != null)
                        {
                            scheduleId = schedule.Id;
                        }
                    }

                    int?personAliasId = person.PrimaryAliasId;
                    if (personAliasId.HasValue)
                    {
                        new AttendanceService(rockContext).AddOrUpdate(personAliasId.Value, attendanceDateTime.Date, group.Id, locationId, scheduleId, group.CampusId);
                        rockContext.SaveChanges();

                        if (locationId.HasValue)
                        {
                            Rock.CheckIn.KioskLocationAttendance.Remove(locationId.Value);
                        }
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Could not find group matching the guid '{0}'.", groupGuid));
                }
            }

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

            return(true);
        }
        /// <summary>
        /// Gets the person search details.
        /// </summary>
        /// <param name="personSearchResult">The person search result.</param>
        /// <param name="person">The person.</param>
        private void GetPersonSearchDetails(PersonSearchResult personSearchResult, Person person)
        {
            var rockContext = this.Service.Context as Rock.Data.RockContext;

            var appPath = System.Web.VirtualPathUtility.ToAbsolute("~");

            var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
            int adultRoleId     = familyGroupType.Roles.First(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;

            int groupTypeFamilyId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

            // figure out Family, Address, Spouse
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            Guid?recordTypeValueGuid = null;

            if (person.RecordTypeValueId.HasValue)
            {
                recordTypeValueGuid = DefinedValueCache.Get(person.RecordTypeValueId.Value).Guid;
            }

            personSearchResult.ImageHtmlTag     = Person.GetPersonPhotoImageTag(person, 50, 50);
            personSearchResult.Age              = person.Age.HasValue ? person.Age.Value : -1;
            personSearchResult.ConnectionStatus = person.ConnectionStatusValueId.HasValue ? DefinedValueCache.Get(person.ConnectionStatusValueId.Value).Value : string.Empty;
            personSearchResult.Gender           = person.Gender.ConvertToString();
            personSearchResult.Email            = person.Email;

            string imageHtml = string.Format(
                "<div class='person-image' style='background-image:url({0}&width=65);'></div>",
                Person.GetPersonPhotoUrl(person, 200, 200));

            StringBuilder personInfoHtmlBuilder = new StringBuilder();
            int?          groupLocationTypeValueId;
            bool          isBusiness = person.IsBusiness();

            if (isBusiness)
            {
                groupLocationTypeValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK.AsGuid());
            }
            else
            {
                groupLocationTypeValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
            }

            int?personAge = person.Age;

            if (isBusiness)
            {
                personInfoHtmlBuilder.Append("Business");
            }
            else if (person.AgeClassification != AgeClassification.Unknown)
            {
                personInfoHtmlBuilder.Append("<span class='role'>" + person.AgeClassification.ConvertToString() + "</span>");
            }

            if (personAge != null)
            {
                personInfoHtmlBuilder.Append(" <em class='age'>(" + person.FormatAge() + " old)</em>");
            }

            if (person.AgeClassification == AgeClassification.Adult)
            {
                var personService = this.Service as PersonService;
                var spouse        = personService.GetSpouse(person, a => new
                {
                    a.Person.NickName,
                    a.Person.LastName,
                    a.Person.SuffixValueId
                });

                if (spouse != null)
                {
                    string spouseFullName = Person.FormatFullName(spouse.NickName, spouse.LastName, spouse.SuffixValueId);
                    personInfoHtmlBuilder.Append("<p class='spouse'><strong>Spouse:</strong> " + spouseFullName + "</p>");
                    personSearchResult.SpouseName = spouseFullName;
                }
            }

            var primaryLocation = groupMemberService.Queryable()
                                  .Where(a => a.PersonId == person.Id)
                                  .Where(a => a.Group.GroupTypeId == groupTypeFamilyId)
                                  .OrderBy(a => a.GroupOrder ?? int.MaxValue)
                                  .Select(s => s.Group.GroupLocations.Where(a => a.GroupLocationTypeValueId == groupLocationTypeValueId).Select(a => a.Location).FirstOrDefault()
                                          ).AsNoTracking().FirstOrDefault();

            if (primaryLocation != null)
            {
                var    fullStreetAddress = primaryLocation.GetFullStreetAddress();
                string addressHtml       = $"<dl class='address'><dt>Address</dt><dd>{fullStreetAddress.ConvertCrLfToHtmlBr()}</dd></dl>";
                personSearchResult.Address = fullStreetAddress;
                personInfoHtmlBuilder.Append(addressHtml);
            }

            // Generate the HTML for Email and PhoneNumbers
            if (!string.IsNullOrWhiteSpace(person.Email) || person.PhoneNumbers.Any())
            {
                StringBuilder sbEmailAndPhoneHtml = new StringBuilder();
                sbEmailAndPhoneHtml.Append("<div class='margin-t-sm'>");
                sbEmailAndPhoneHtml.Append("<span class='email'>" + person.Email + "</span>");
                string phoneNumberList = "<ul class='phones list-unstyled'>";
                foreach (var phoneNumber in person.PhoneNumbers)
                {
                    var phoneType = DefinedValueCache.Get(phoneNumber.NumberTypeValueId ?? 0);
                    phoneNumberList += string.Format(
                        "<li x-ms-format-detection='none'>{0} <small>{1}</small></li>",
                        phoneNumber.IsUnlisted ? "Unlisted" : phoneNumber.NumberFormatted,
                        phoneType != null ? phoneType.Value : string.Empty);
                }

                sbEmailAndPhoneHtml.Append(phoneNumberList + "</ul></div>");

                personInfoHtmlBuilder.Append(sbEmailAndPhoneHtml.ToString());
            }

            // force the link to open a new scrollable, re-sizable browser window (and make it work in FF, Chrome and IE) http://stackoverflow.com/a/2315916/1755417
            personInfoHtmlBuilder.Append($"<p class='margin-t-sm'><small><a href='/person/{person.Id}' class='cursor-pointer' onclick=\"javascript: window.open('/person/{person.Id}', '_blank', 'scrollbars=1,resizable=1,toolbar=1'); return false;\" data-toggle=\"tooltip\" title=\"View Profile\" tabindex=\"-1\">View Profile</a></small></p>");

            personSearchResult.PickerItemDetailsImageHtml      = imageHtml;
            personSearchResult.PickerItemDetailsPersonInfoHtml = personInfoHtmlBuilder.ToString();
            string itemDetailHtml = $@"
<div class='picker-select-item-details js-picker-select-item-details clearfix' style='display: none;'>
	{imageHtml}
	<div class='contents'>
        {personSearchResult.PickerItemDetailsPersonInfoHtml}
	</div>
</div>
";

            personSearchResult.PickerItemDetailsHtml = itemDetailHtml;
        }
Beispiel #5
0
        /// <summary>
        /// Handles the Click event of the btnMoveGroupMember 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 btnMoveGroupMember_Click(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var groupMemberService = new GroupMemberService(rockContext);
            var groupMember        = groupMemberService.Get(hfGroupMemberId.Value.AsInteger());

            groupMember.LoadAttributes();
            int destGroupId = gpMoveGroupMember.SelectedValue.AsInteger();
            var destGroup   = new GroupService(rockContext).Get(destGroupId);

            var destGroupMember = groupMemberService.Queryable().Where(a =>
                                                                       a.GroupId == destGroupId &&
                                                                       a.PersonId == groupMember.PersonId &&
                                                                       a.GroupRoleId == grpMoveGroupMember.GroupRoleId).FirstOrDefault();

            if (destGroupMember != null)
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("{0} is already in {1}", groupMember.Person, destGroupMember.Group);
                return;
            }

            if (!grpMoveGroupMember.GroupRoleId.HasValue)
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("Please select a Group Role");
                return;
            }

            string canDeleteWarning;

            if (!groupMemberService.CanDelete(groupMember, out canDeleteWarning))
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("Unable to remove {0} from {1}: {2}", groupMember.Person, groupMember.Group, canDeleteWarning);
                return;
            }

            destGroupMember             = new GroupMember();
            destGroupMember.GroupId     = destGroupId;
            destGroupMember.GroupRoleId = grpMoveGroupMember.GroupRoleId.Value;
            destGroupMember.PersonId    = groupMember.PersonId;
            destGroupMember.LoadAttributes();

            foreach (var attribute in groupMember.Attributes)
            {
                if (destGroupMember.Attributes.Any(a => a.Key == attribute.Key && a.Value.FieldTypeId == attribute.Value.FieldTypeId))
                {
                    destGroupMember.SetAttributeValue(attribute.Key, groupMember.GetAttributeValue(attribute.Key));
                }
            }

            rockContext.WrapTransaction(() =>
            {
                groupMemberService.Add(destGroupMember);
                rockContext.SaveChanges();
                destGroupMember.SaveAttributeValues(rockContext);

                // move any Note records that were associated with the old groupMember to the new groupMember record
                if (cbMoveGroupMemberMoveNotes.Checked)
                {
                    destGroupMember.Note        = groupMember.Note;
                    int groupMemberEntityTypeId = EntityTypeCache.GetId <Rock.Model.GroupMember>().Value;
                    var noteService             = new NoteService(rockContext);
                    var groupMemberNotes        = noteService.Queryable().Where(a => a.NoteType.EntityTypeId == groupMemberEntityTypeId && a.EntityId == groupMember.Id);
                    foreach (var note in groupMemberNotes)
                    {
                        note.EntityId = destGroupMember.Id;
                    }

                    rockContext.SaveChanges();
                }

                groupMemberService.Delete(groupMember);
                rockContext.SaveChanges();

                destGroupMember.CalculateRequirements(rockContext, true);
            });

            var queryString = new Dictionary <string, string>();

            queryString.Add("GroupMemberId", destGroupMember.Id.ToString());
            this.NavigateToPage(this.RockPage.Guid, queryString);
        }
Beispiel #6
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            RockContext rockContext                   = new RockContext();
            var         groupMemberService            = new GroupMemberService(rockContext);
            var         groupService                  = new GroupService(rockContext);
            var         groupTypeService              = new GroupTypeService(rockContext);
            var         attributeService              = new AttributeService(rockContext);
            var         attributeValueService         = new AttributeValueService(rockContext);
            var         personService                 = new PersonService(rockContext);
            var         personAliasService            = new PersonAliasService(rockContext);
            var         entityTypeService             = new EntityTypeService(rockContext);
            var         registrationRegistrantService = new RegistrationRegistrantService(rockContext);
            var         eiogmService                  = new EventItemOccurrenceGroupMapService(rockContext);
            var         groupLocationService          = new GroupLocationService(rockContext);
            var         locationService               = new LocationService(rockContext);
            var         signatureDocumentServce       = new SignatureDocumentService(rockContext);
            var         phoneNumberService            = new PhoneNumberService(rockContext);

            int[] signatureDocumentIds = { };
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates")))
            {
                signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse);
            }
            Guid bbGroup          = GetAttributeValue("Group").AsGuid();
            Guid hsmGroupTypeGuid = GetAttributeValue("HSMGroupType").AsGuid();
            int? hsmGroupTypeId   = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault();

            int entityTypeId            = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id;
            var group                   = new GroupService(rockContext).Get(bbGroup);
            var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList();

            hlGroup.NavigateUrl = "/group/" + group.Id;

            var attributeIds = attributeService.Queryable()
                               .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue)))
                               .Select(a => a.Id).ToList();

            var gmTmpqry = groupMemberService.Queryable()
                           .Where(gm => (gm.GroupId == group.Id));

            var qry = gmTmpqry
                      .Join(registrationRegistrantService.Queryable(),
                            obj => obj.Id,
                            rr => rr.GroupMemberId,
                            (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.GroupMember.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)) /*, Location = obj.Location */ })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.RegistrationRegistrant.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)) /*, Location = obj.Location */ });

            var qry2 = gmTmpqry
                       .GroupJoin(
                groupMemberService.Queryable()
                .Join(groupService.Queryable(),
                      gm => new { Id = gm.GroupId, GroupTypeId = 10 },
                      g => new { g.Id, g.GroupTypeId },
                      (gm, g) => new { GroupMember = gm, Group = g })
                .Join(groupLocationService.Queryable(),
                      obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = ( int? )19 },
                      gl => new { gl.GroupId, gl.GroupLocationTypeValueId },
                      (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl })
                .Join(locationService.Queryable(),
                      obj => obj.GroupLocation.LocationId,
                      l => l.Id,
                      (obj, l) => new { GroupMember = obj.GroupMember, Location = l }),
                gm => gm.PersonId,
                glgm => glgm.GroupMember.PersonId,
                (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() }
                )
                       .GroupJoin(signatureDocumentServce.Queryable()
                                  .Join(personAliasService.Queryable(),
                                        sd => sd.AppliesToPersonAliasId,
                                        pa => pa.Id,
                                        (sd, pa) => new { SignatureDocument = sd, Alias = pa }),
                                  obj => obj.GroupMember.PersonId,
                                  sd => sd.Alias.PersonId,
                                  (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds })
                       .GroupJoin(phoneNumberService.Queryable(),
                                  obj => obj.GroupMember.PersonId,
                                  p => p.PersonId,
                                  (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn });


            if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix))))
            {
                string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower();
                qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable();
            }
            decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull();
            decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull();

            if (lowerVal != null && upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal && q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable();
            }
            else if (lowerVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal).AsQueryable();
            }
            else if (upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable();
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var tmp  = qry.ToList();
            var tmp2 = qry2.ToList();

            lStats.Text = "Query Runtime: " + stopwatch.Elapsed;
            stopwatch.Reset();

            stopwatch.Start();

            var newQry = tmp.Select(g => new
            {
                Id                    = g.GroupMember.Id,
                RegisteredBy          = new ModelValue <Person>(g.RegistrationRegistrant.Registration.PersonAlias.Person),
                person                = g.Person,
                Registrant            = new ModelValue <Person>(g.Person),
                Age                   = g.Person.Age,
                GraduationYear        = g.Person.GraduationYear,
                RegistrationId        = g.RegistrationRegistrant.RegistrationId,
                Group                 = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group),
                DOB                   = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "",
                Address               = new ModelValue <Location>(tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()),
                Email                 = g.Person.Email,
                Gender                = g.Person.Gender,         // (B & B Registration)
                GraduationYearProfile = g.Person.GraduationYear, // (Person Profile)
                HomePhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                CellPhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                GroupMemberData       = new Func <GroupMemberAttributes>(() =>
                {
                    GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues);
                    return(gma);
                })(),
                RegistrantData = new Func <RegistrantAttributes>(() =>
                {
                    RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant, g.RegistrationAttributeValues);
                    return(row);
                })(),
                LegalRelease = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name.Contains("MINOR") ? "MINOR (" + sd.SignatureDocument.Status.ToString() + ")" : sd.SignatureDocument.SignatureDocumentTemplate.Name.Contains("ADULT") ? "ADULT (" + sd.SignatureDocument.Status.ToString() + ")" : "").FirstOrDefault(), // (highest level form on record, pulled from forms page in Rock)
                Departure    = "TBD",                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              // (hopefully based on bus, otherwise a dropdown with 1-4)
                Campus       = group.Campus,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       //
                Role         = group.ParentGroup.GroupType.Name.Contains("Serving") ? "Leader" : "Student",                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        //
                HSMGroup     = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList())
            }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable();

            lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed;

            stopwatch.Stop();
            gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields;
            var mergeFields = new List <String>();

            mergeFields.Add("Id");
            mergeFields.Add("RegisteredBy");
            mergeFields.Add("Group");
            mergeFields.Add("Registrant");
            mergeFields.Add("Age");
            mergeFields.Add("GraduationYear");
            mergeFields.Add("DOB");
            mergeFields.Add("Address");
            mergeFields.Add("Email");
            mergeFields.Add("Gender");
            mergeFields.Add("GraduationYearProfile");
            mergeFields.Add("HomePhone");
            mergeFields.Add("CellPhone");
            mergeFields.Add("GroupMemberData");
            mergeFields.Add("RegistrantData");
            mergeFields.Add("LegalRelease");
            mergeFields.Add("Departure");
            mergeFields.Add("Campus");
            mergeFields.Add("Role");
            mergeFields.Add("HSMGroup");
            gReport.CommunicateMergeFields = mergeFields;


            if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix))))
            {
                string poa = GetUserPreference(string.Format("{0}POA", keyPrefix));
                if (poa == "[Blank]")
                {
                    poa = "";
                }
                newQry = newQry.Where(q => q.GroupMemberData.POA == poa);
            }

            SortProperty sortProperty = gReport.SortProperty;

            if (sortProperty != null)
            {
                gReport.SetLinqDataSource(newQry.Sort(sortProperty));
            }
            else
            {
                gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName));
            }
            gReport.DataBind();
        }
Beispiel #7
0
        /// <summary>
        /// Handles the Click event of the btnSaveEditPreferences 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 btnSaveEditPreferences_Click(object sender, EventArgs e)
        {
            var rockContext   = new RockContext();
            var groupMember   = new GroupMemberService(rockContext).Get(hfGroupMemberId.Value.AsInteger());
            var personService = new PersonService(rockContext);
            var person        = personService.Get(groupMember.PersonId);

            int?orphanedPhotoId = null;

            if (person.PhotoId != imgProfilePhoto.BinaryFileId)
            {
                orphanedPhotoId = person.PhotoId;
                person.PhotoId  = imgProfilePhoto.BinaryFileId;

                // add or update the Photo Verify group to have this person as Pending since the photo was changed or deleted
                using (var photoRequestRockContext = new RockContext())
                {
                    GroupMemberService groupMemberService = new GroupMemberService(photoRequestRockContext);
                    Group photoRequestGroup = new GroupService(photoRequestRockContext).Get(Rock.SystemGuid.Group.GROUP_PHOTO_REQUEST.AsGuid());

                    var photoRequestGroupMember = groupMemberService.Queryable().Where(a => a.GroupId == photoRequestGroup.Id && a.PersonId == person.Id).FirstOrDefault();
                    if (photoRequestGroupMember == null)
                    {
                        photoRequestGroupMember             = new GroupMember();
                        photoRequestGroupMember.GroupId     = photoRequestGroup.Id;
                        photoRequestGroupMember.PersonId    = person.Id;
                        photoRequestGroupMember.GroupRoleId = photoRequestGroup.GroupType.DefaultGroupRoleId ?? -1;
                        groupMemberService.Add(photoRequestGroupMember);
                    }

                    photoRequestGroupMember.GroupMemberStatus = GroupMemberStatus.Pending;

                    photoRequestRockContext.SaveChanges();
                }
            }

            // Save the GroupMember Attributes
            groupMember.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues(phGroupMemberAttributes, groupMember);

            // Save selected Person Attributes (The ones picked in Block Settings)
            var personAttributes = this.GetAttributeValue("PersonAttributes").SplitDelimitedValues().AsGuidList().Select(a => AttributeCache.Get(a));

            if (personAttributes.Any())
            {
                person.LoadAttributes(rockContext);
                foreach (var personAttribute in personAttributes)
                {
                    Control attributeControl = phPersonAttributes.FindControl(string.Format("attribute_field_{0}", personAttribute.Id));
                    if (attributeControl != null)
                    {
                        // Save Attribute value to the database
                        string newValue = personAttribute.FieldType.Field.GetEditValue(attributeControl, personAttribute.QualifierValues);
                        Rock.Attribute.Helper.SaveAttributeValue(person, personAttribute, newValue, rockContext);
                    }
                }
            }

            // Save everything else to the database in a db transaction
            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                groupMember.SaveAttributeValues(rockContext);

                if (orphanedPhotoId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(orphanedPhotoId.Value);
                    if (binaryFile != null)
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                        rockContext.SaveChanges();
                    }
                }

                // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                if (imgProfilePhoto.CropBinaryFileId.HasValue)
                {
                    if (imgProfilePhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgProfilePhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }
            });

            ShowView(hfGroupId.Value.AsInteger(), hfGroupMemberId.Value.AsInteger());
        }
Beispiel #8
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();
            }
        }
Beispiel #9
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());
                            }
                        }
                    }
                }
            }
        }
Beispiel #10
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();
        }
Beispiel #11
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();
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            bool requirePasswordReset = dataMap.GetBoolean("RequirePasswordReset");

            int groupsSynced  = 0;
            int groupsChanged = 0;

            try
            {
                // get groups set to sync
                GroupService groupService     = new GroupService(new RockContext());
                var          groupIdsThatSync = groupService.Queryable().Where(g => g.SyncDataViewId != null).Select(a => a.Id).ToList();

                foreach (var syncGroupId in groupIdsThatSync)
                {
                    bool hasGroupChanged = false;

                    // use a fresh rockContext per group so that ChangeTracker doesn't get bogged down
                    using (var rockContext = new RockContext())
                    {
                        var syncGroup = new GroupService(rockContext).Get(syncGroupId);
                        GroupMemberService groupMemberService = new GroupMemberService(rockContext);

                        // increase the timeout just in case the dataview source is slow
                        rockContext.Database.CommandTimeout = 180;

                        var syncSource = new DataViewService(rockContext).Get(syncGroup.SyncDataViewId.Value);

                        // ensure this is a person dataview
                        bool isPersonDataSet = syncSource.EntityTypeId == EntityTypeCache.Read(typeof(Rock.Model.Person)).Id;

                        if (isPersonDataSet)
                        {
                            SortProperty sortById = new SortProperty();
                            sortById.Property  = "Id";
                            sortById.Direction = System.Web.UI.WebControls.SortDirection.Ascending;
                            List <string> errorMessages = new List <string>();

                            var personService       = new PersonService(rockContext);
                            var parameterExpression = personService.ParameterExpression;
                            var whereExpression     = syncSource.GetExpression(personService, parameterExpression, out errorMessages);
                            var sourceItems         = personService.Get(parameterExpression, whereExpression).Select(q => q.Id).ToList();
                            var targetItems         = groupMemberService.Queryable().Where(gm => gm.GroupId == syncGroup.Id).ToList();

                            // delete items from the target not in the source
                            foreach (var targetItem in targetItems.Where(t => !sourceItems.Contains(t.PersonId)))
                            {
                                // made a clone of the person as it will be detached when the group member is deleted. Also
                                // saving the delete before the email is sent in case an exception occurs so the user doesn't
                                // get an email everytime the agent runs.
                                Person recipient = (Person)targetItem.Person.Clone();
                                groupMemberService.Delete(targetItem);

                                rockContext.SaveChanges();

                                hasGroupChanged = true;

                                if (syncGroup.ExitSystemEmailId.HasValue)
                                {
                                    SendExitEmail(syncGroup.ExitSystemEmailId.Value, recipient, syncGroup);
                                }
                            }

                            // add items not in target but in the source
                            foreach (var sourceItem in sourceItems.Where(s => !targetItems.Select(t => t.PersonId).Contains(s)))
                            {
                                // add source to target
                                var newGroupMember = new GroupMember {
                                    Id = 0
                                };
                                newGroupMember.PersonId          = sourceItem;
                                newGroupMember.Group             = syncGroup;
                                newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                newGroupMember.GroupRoleId       = syncGroup.GroupType.DefaultGroupRoleId ?? syncGroup.GroupType.Roles.FirstOrDefault().Id;
                                groupMemberService.Add(newGroupMember);

                                hasGroupChanged = true;

                                if (syncGroup.WelcomeSystemEmailId.HasValue)
                                {
                                    SendWelcomeEmail(syncGroup.WelcomeSystemEmailId.Value, sourceItem, syncGroup, syncGroup.AddUserAccountsDuringSync ?? false, requirePasswordReset);
                                }
                            }

                            if (hasGroupChanged)
                            {
                                groupsChanged++;
                            }

                            groupsSynced++;

                            rockContext.SaveChanges();

                            if (hasGroupChanged && (syncGroup.IsSecurityRole || syncGroup.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid())))
                            {
                                Rock.Security.Role.Flush(syncGroup.Id);
                            }
                        }
                    }
                }

                var resultMessage = string.Empty;
                if (groupsSynced == 0)
                {
                    resultMessage = "No groups to sync";
                }
                else if (groupsSynced == 1)
                {
                    resultMessage = "1 group was sync'ed";
                }
                else
                {
                    resultMessage = string.Format("{0} groups were sync'ed", groupsSynced);
                }

                resultMessage += string.Format(" and {0} groups where changed", groupsChanged);

                context.Result = resultMessage;
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
Beispiel #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>();
            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);
            }

            var showDonorPersonAsLink          = GetAttributeValue("ShowDonorPersonAsLink").AsBoolean();
            var showParticipantPersonLink      = GetAttributeValue("ShowParticipantPersonLink").AsBoolean();
            var showParticipantGroupMemberLink = GetAttributeValue("ShowParticipantGroupMemberLink").AsBoolean();

            //
            // 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,
                DonorName       = ((isExporting || !showDonorPersonAsLink) ? d.Transaction.AuthorizedPersonAlias.Person.FullName : string.Format("<a href=\"{0}\">{1}</a>", DonorPersonLink.Replace("{DonorPersonId}", d.Transaction.AuthorizedPersonAlias.Person.Id.ToString()).Replace("{GroupMemberId}", groupMembers[d.EntityId.Value].Id.ToString()).Replace("{GroupMemberPersonId}", groupMembers[d.EntityId.Value].PersonId.ToString()), d.Transaction.AuthorizedPersonAlias.Person.FullName)),
                Email           = d.Transaction.AuthorizedPersonAlias.Person.Email,
                Participant     = groupMembers[d.EntityId.Value],
                ParticipantName = (isExporting ? groupMembers[d.EntityId.Value].Person.FullName :
                                   ((showParticipantPersonLink || showParticipantGroupMemberLink) ?
                                    (showParticipantPersonLink ? string.Format("<a href=\"{0}\" class=\"pull-right margin-l-sm btn btn-sm btn-default\"><i class=\"fa fa-user\"></i></a>", ParticipantPersonLink.Replace("{DonorPersonId}", d.Transaction.AuthorizedPersonAlias.Person.Id.ToString()).Replace("{GroupMemberId}", groupMembers[d.EntityId.Value].Id.ToString()).Replace("{GroupMemberPersonId}", groupMembers[d.EntityId.Value].PersonId.ToString())) : string.Empty) +
                                    (showParticipantGroupMemberLink ? string.Format("<a href=\"{0}\">{1}</a>", ParticipantGroupMemberLink.Replace("{DonorPersonId}", d.Transaction.AuthorizedPersonAlias.Person.Id.ToString()).Replace("{GroupMemberId}", groupMembers[d.EntityId.Value].Id.ToString()).Replace("{GroupMemberPersonId}", groupMembers[d.EntityId.Value].PersonId.ToString()), groupMembers[d.EntityId.Value].Person.FullName) : string.Empty)
                        : groupMembers[d.EntityId.Value].Person.FullName)
                                   ),
                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());

            if (!GetAttributeValue("ShowDonorAddress").AsBoolean())
            {
                gDonations.Columns[2].Visible = false;
            }

            if (!GetAttributeValue("ShowDonorEmail").AsBoolean())
            {
                gDonations.Columns[3].Visible = false;
            }

            if (!GetAttributeValue("ShowParticipantColumn").AsBoolean())
            {
                gDonations.Columns[4].Visible = false;
            }

            gDonations.Columns[6].Visible = GetAttributeValue("ShowAmount").AsBoolean();

            gDonations.Actions.ShowCommunicate   = GetAttributeValue("ShowCommunicate").AsBoolean();
            gDonations.Actions.ShowMergePerson   = GetAttributeValue("ShowMergePerson").AsBoolean();
            gDonations.Actions.ShowBulkUpdate    = GetAttributeValue("ShowBulkUpdate").AsBoolean();
            gDonations.Actions.ShowExcelExport   = GetAttributeValue("ShowExcelExport").AsBoolean();
            gDonations.Actions.ShowMergeTemplate = GetAttributeValue("ShowMergeTemplate").AsBoolean();

            gDonations.DataSource = donations.ToList();
            gDonations.DataBind();
        }
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void ShowDetails()
        {
            if (CurrentGroup == null)
            {
                NavigateToHomePage();
                return;
            }

            nbNotice.Visible     = false;
            lMembers.Text        = CurrentGroup.GroupType.GroupMemberTerm.Pluralize();
            lPendingMembers.Text = "Pending " + lMembers.Text;

            if (ddlOccurence.SelectedValue.AsInteger() != 0)
            {
                //The drop down stores the time in unix time
                var occurenceDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)
                                    .AddSeconds(ddlOccurence.SelectedValue.AsInteger());

                var attendanceData = new AttendanceService(_rockContext)
                                     .Queryable()
                                     .Where(a => a.GroupId == CurrentGroup.Id && a.StartDateTime == occurenceDate)
                                     .ToList();

                lvMembers.Items.Clear();

                List <GroupMember> groupMembers;

                if (ddlFilter.Visible)
                {
                    groupMembers = GetFilteredMembers(ddlFilter.SelectedValue);
                }
                else
                {
                    groupMembers = CurrentGroupMembers;
                }

                var items = groupMembers
                            .Where(gm => gm.GroupMemberStatus == GroupMemberStatus.Active)
                            .OrderBy(gm => gm.Person.LastName)
                            .ThenBy(gm => gm.Person.NickName)
                            .Select(m => new
                {
                    PersonId = m.PersonId.ToString(),
                    FullName = m.ToString(),
                    Active   = (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).Any() &&
                                (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).FirstOrDefault().DidAttend ?? false)) ? "active" : "",
                    Attended = (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).Any() &&
                                (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).FirstOrDefault().DidAttend ?? false))
                }
                                    )
                            .ToList();

                lvMembers.DataSource = items;
                lvMembers.DataBind();

                cbDidNotMeet.Checked = (
                    attendanceData.Where(a => a.DidAttend == true).Count() <= 0 &&
                    attendanceData.Where(a => a.DidNotOccur == true).Count() > 0
                    );
                if (cbDidNotMeet.Checked)
                {
                    lbDidNotMeet.AddCssClass("active");
                }
            }


            GroupMemberService groupMemberService = new GroupMemberService(_rockContext);
            // Bind the pending members
            var pendingMembers = groupMemberService
                                 .Queryable().AsNoTracking()
                                 .Where(m =>
                                        m.GroupId == CurrentGroup.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();
        }
Beispiel #15
0
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // Get the job setting(s)
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            bool       requirePasswordReset = dataMap.GetBoolean("RequirePasswordReset");

            // Counters for displaying results
            int groupsSynced  = 0;
            int groupsChanged = 0;

            try
            {
                // get groups set to sync
                var groupIdsThatSync = new List <int>();
                using (var rockContext = new RockContext())
                {
                    groupIdsThatSync = new GroupService(rockContext)
                                       .Queryable().AsNoTracking()
                                       .Where(g => g.SyncDataViewId != null)
                                       .Select(a => a.Id)
                                       .ToList();
                }

                foreach (var syncGroupId in groupIdsThatSync)
                {
                    bool hasGroupChanged = false;

                    // Use a fresh rockContext per group so that ChangeTracker doesn't get bogged down
                    using (var rockContext = new RockContext())
                    {
                        // increase the timeout just in case the dataview source is slow
                        rockContext.Database.CommandTimeout = 180;

                        // Get the Group
                        var syncGroup = new GroupService(rockContext)
                                        .Queryable().AsNoTracking()
                                        .FirstOrDefault(t => t.Id == syncGroupId);

                        // Ensure that the group's Sync Data View is a person dataview
                        if (syncGroup.SyncDataView.EntityTypeId == EntityTypeCache.Read(typeof(Person)).Id)
                        {
                            List <string> errorMessages = new List <string>();

                            // Get the person id's from the dataview (source)
                            var personService       = new PersonService(rockContext);
                            var parameterExpression = personService.ParameterExpression;
                            var whereExpression     = syncGroup.SyncDataView.GetExpression(personService, parameterExpression, out errorMessages);
                            var sourcePersonIds     = new PersonService(rockContext)
                                                      .Get(parameterExpression, whereExpression)
                                                      .Select(q => q.Id)
                                                      .ToList();

                            // Get the person id's in the group (target)
                            var targetPersonIds = new GroupMemberService(rockContext)
                                                  .Queryable().AsNoTracking()
                                                  .Where(gm => gm.GroupId == syncGroup.Id)
                                                  .Select(gm => gm.PersonId)
                                                  .ToList();

                            // Delete people from the group that are no longer in the dataview
                            foreach (var personId in targetPersonIds.Where(t => !sourcePersonIds.Contains(t)))
                            {
                                // Use a new context to limit the amount of change-tracking required
                                using (var groupMemberContext = new RockContext())
                                {
                                    // Delete any group members with the person id
                                    var groupMemberService = new GroupMemberService(groupMemberContext);
                                    foreach (var groupMember in groupMemberService
                                             .Queryable()
                                             .Where(m =>
                                                    m.GroupId == syncGroupId &&
                                                    m.PersonId == personId)
                                             .ToList())
                                    {
                                        groupMemberService.Delete(groupMember);
                                    }
                                    groupMemberContext.SaveChanges();

                                    // If the Group has an exit email, and person has an email address, send them the exit email
                                    if (syncGroup.ExitSystemEmail != null)
                                    {
                                        var person = new PersonService(groupMemberContext).Get(personId);
                                        if (person.Email.IsNotNullOrWhitespace())
                                        {
                                            // Send the exit email
                                            var mergeFields = new Dictionary <string, object>();
                                            mergeFields.Add("Group", syncGroup);
                                            mergeFields.Add("Person", person);
                                            var emailMessage = new RockEmailMessage(syncGroup.ExitSystemEmail);
                                            emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                                            emailMessage.Send();
                                        }
                                    }
                                }

                                hasGroupChanged = true;
                            }

                            // Add people to the group that are in the dataview and not currently in the group
                            int groupRoleId = syncGroup.GroupType.DefaultGroupRoleId ?? syncGroup.GroupType.Roles.FirstOrDefault().Id;
                            foreach (var personId in sourcePersonIds.Where(s => !targetPersonIds.Contains(s)))
                            {
                                // Use a new context to limit the amount of change-tracking required
                                using (var groupMemberContext = new RockContext())
                                {
                                    // Add new person to the group
                                    var groupMemberService = new GroupMemberService(groupMemberContext);
                                    var newGroupMember     = new GroupMember {
                                        Id = 0
                                    };
                                    newGroupMember.PersonId          = personId;
                                    newGroupMember.GroupId           = syncGroup.Id;
                                    newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                    newGroupMember.GroupRoleId       = groupRoleId;
                                    groupMemberService.Add(newGroupMember);
                                    groupMemberContext.SaveChanges();

                                    // If the Group has a welcome email, and person has an email address, send them the welcome email and possibly create a login
                                    if (syncGroup.WelcomeSystemEmail != null)
                                    {
                                        var person = new PersonService(groupMemberContext).Get(personId);
                                        if (person.Email.IsNotNullOrWhitespace())
                                        {
                                            // If the group is configured to add a user account for anyone added to the group, and person does not yet have an
                                            // account, add one for them.
                                            string newPassword = string.Empty;
                                            bool   createLogin = syncGroup.AddUserAccountsDuringSync ?? false;
                                            if (createLogin && !person.Users.Any())
                                            {
                                                newPassword = System.Web.Security.Membership.GeneratePassword(9, 1);
                                                string username = Rock.Security.Authentication.Database.GenerateUsername(person.NickName, person.LastName);

                                                UserLogin login = UserLoginService.Create(
                                                    groupMemberContext,
                                                    person,
                                                    AuthenticationServiceType.Internal,
                                                    EntityTypeCache.Read(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                                                    username,
                                                    newPassword,
                                                    true,
                                                    requirePasswordReset);
                                            }

                                            // Send the welcome email
                                            var mergeFields = new Dictionary <string, object>();
                                            mergeFields.Add("Group", syncGroup);
                                            mergeFields.Add("Person", person);
                                            mergeFields.Add("NewPassword", newPassword);
                                            mergeFields.Add("CreateLogin", createLogin);
                                            var emailMessage = new RockEmailMessage(syncGroup.WelcomeSystemEmail);
                                            emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                                            emailMessage.Send();
                                        }
                                    }
                                }

                                hasGroupChanged = true;
                            }

                            // Increment Groups Changed Counter (if people were deleted or added to the group)
                            if (hasGroupChanged)
                            {
                                groupsChanged++;
                            }

                            // Increment the Groups Synced Counter
                            groupsSynced++;

                            // If the group changed, and it was a security group, flush the security for the group
                            if (hasGroupChanged && (syncGroup.IsSecurityRole || syncGroup.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid())))
                            {
                                Rock.Security.Role.Flush(syncGroup.Id);
                            }
                        }
                    }
                }

                // Format the result message
                var resultMessage = string.Empty;
                if (groupsSynced == 0)
                {
                    resultMessage = "No groups to sync";
                }
                else if (groupsSynced == 1)
                {
                    resultMessage = "1 group was sync'ed";
                }
                else
                {
                    resultMessage = string.Format("{0} groups were sync'ed", groupsSynced);
                }
                resultMessage += string.Format(" and {0} groups were changed", groupsChanged);
                context.Result = resultMessage;
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
Beispiel #16
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);
        }
Beispiel #17
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 && checkInState.CheckIn.SearchType != null)
            {
                checkInState.CheckIn.Families = new List <CheckInFamily>();

                if (!string.IsNullOrWhiteSpace(checkInState.CheckIn.SearchValue))
                {
                    var personService = new PersonService(rockContext);
                    var memberService = new GroupMemberService(rockContext);
                    var groupService  = new GroupService(rockContext);

                    int personRecordTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    int familyGroupTypeId  = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;
                    var dvInactive         = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid());

                    IQueryable <int> familyIdQry = null;

                    if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER.AsGuid()))
                    {
                        string numericPhone = checkInState.CheckIn.SearchValue.AsNumeric();

                        var phoneQry = new PhoneNumberService(rockContext).Queryable().AsNoTracking();
                        if (checkInState.CheckInType == null || checkInState.CheckInType.PhoneSearchType == PhoneSearchType.EndsWith)
                        {
                            char[] charArray = numericPhone.ToCharArray();
                            Array.Reverse(charArray);
                            phoneQry = phoneQry.Where(o =>
                                                      o.NumberReversed.StartsWith(new string( charArray )));
                        }
                        else
                        {
                            phoneQry = phoneQry.Where(o =>
                                                      o.Number.Contains(numericPhone));
                        }

                        var tmpQry = phoneQry.Join(personService.Queryable().AsNoTracking(),
                                                   o => new { PersonId = o.PersonId, IsDeceased = false, RecordTypeValueId = personRecordTypeId },
                                                   p => new { PersonId = p.Id, IsDeceased = p.IsDeceased, RecordTypeValueId = p.RecordTypeValueId.Value },
                                                   (pn, p) => new { Person = p, PhoneNumber = pn })
                                     .Join(memberService.Queryable().AsNoTracking(),
                                           pn => pn.Person.Id,
                                           m => m.PersonId,
                                           (o, m) => new { PersonNumber = o.PhoneNumber, GroupMember = m });

                        familyIdQry = groupService.Queryable().Where(g => tmpQry.Any(o => o.GroupMember.GroupId == g.Id) && g.GroupTypeId == familyGroupTypeId)
                                      .Select(g => g.Id)
                                      .Distinct();
                    }
                    else
                    {
                        var familyMemberQry = memberService
                                              .AsNoFilter().AsNoTracking()
                                              .Where(m =>
                                                     m.Group.GroupTypeId == familyGroupTypeId &&
                                                     m.Person.RecordTypeValueId == personRecordTypeId);

                        if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_NAME.AsGuid()))
                        {
                            var personIds = personService.GetByFullName(checkInState.CheckIn.SearchValue, false).AsNoTracking().Select(p => p.Id);
                            familyMemberQry = familyMemberQry.Where(f => personIds.Contains(f.PersonId));
                        }
                        else if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_SCANNED_ID.AsGuid()))
                        {
                            var personIds = new List <int>();

                            var dv = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID.AsGuid());
                            if (dv != null)
                            {
                                var searchValueService = new PersonSearchKeyService(rockContext);
                                var personAliases      = searchValueService.Queryable().AsNoTracking()
                                                         .Where(v =>
                                                                v.SearchTypeValueId == dv.Id &&
                                                                v.SearchValue == checkInState.CheckIn.SearchValue)
                                                         .Select(v => v.PersonAlias);

                                if (personAliases.Any())
                                {
                                    checkInState.CheckIn.CheckedInByPersonAliasId = personAliases.First().Id;
                                    personIds = personAliases.Select(a => a.PersonId).ToList();
                                }
                            }

                            if (personIds.Any())
                            {
                                familyMemberQry = familyMemberQry.Where(f => personIds.Contains(f.PersonId));
                            }
                            else
                            {
                                // if there were no matches, try to find a family check-in identifier. V8 has a "run once" job that moves the family identifiers
                                // to person search values, but in case the job has not yet completed, will still do the check for family ids.
                                var entityIds = new List <int>();

                                var attributeValueService = new AttributeValueService(rockContext);
                                var attr = AttributeCache.Get("8F528431-A438-4488-8DC3-CA42E66C1B37".AsGuid());
                                if (attr != null)
                                {
                                    entityIds = new AttributeValueService(rockContext)
                                                .Queryable().AsNoTracking()
                                                .Where(v =>
                                                       v.AttributeId == attr.Id &&
                                                       v.EntityId.HasValue &&
                                                       ("|" + v.Value + "|").Contains("|" + checkInState.CheckIn.SearchValue + "|"))
                                                .Select(v => v.EntityId.Value)
                                                .ToList();
                                }

                                familyMemberQry = familyMemberQry.Where(f => entityIds.Contains(f.GroupId));
                            }
                        }
                        else if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_FAMILY_ID.AsGuid()))
                        {
                            List <int> searchFamilyIds = checkInState.CheckIn.SearchValue.SplitDelimitedValues().AsIntegerList();
                            familyMemberQry = familyMemberQry.Where(f => searchFamilyIds.Contains(f.GroupId));
                        }
                        else
                        {
                            errorMessages.Add("Invalid Search Type");
                            return(false);
                        }

                        familyIdQry = familyMemberQry
                                      .Select(m => m.GroupId)
                                      .Distinct();
                    }

                    int maxResults = checkInState.CheckInType != null ? checkInState.CheckInType.MaxSearchResults : 100;
                    if (maxResults > 0)
                    {
                        familyIdQry = familyIdQry.Take(maxResults);
                    }

                    // You might think we should do a ToList() on the familyIdQry and use it below,
                    // but through some extensive testing, we discovered that the next SQL query is better
                    // optimized if it has the familyIdQry without being to-listed.  It was over 270% slower
                    // when querying names and 120% slower when querying phone numbers.

                    // Load the family members
                    var familyMembers = memberService
                                        .Queryable().AsNoTracking()
                                        .Where(m => m.Group.GroupTypeId == familyGroupTypeId && familyIdQry.Contains(m.GroupId)).Select(a =>
                                                                                                                                        new {
                        Group               = a.Group,
                        GroupId             = a.GroupId,
                        Order               = a.GroupRole.Order,
                        BirthYear           = a.Person.BirthYear,
                        BirthMonth          = a.Person.BirthMonth,
                        BirthDay            = a.Person.BirthDay,
                        Gender              = a.Person.Gender,
                        NickName            = a.Person.NickName,
                        RecordStatusValueId = a.Person.RecordStatusValueId
                    })
                                        .ToList();

                    // Add each family
                    foreach (int familyId in familyMembers.Select(fm => fm.GroupId).Distinct())
                    {
                        // Get each of the members for this family
                        var familyMemberQry = familyMembers
                                              .Where(m =>
                                                     m.GroupId == familyId &&
                                                     m.NickName != null);

                        if (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeople && dvInactive != null)
                        {
                            familyMemberQry = familyMemberQry
                                              .Where(m =>
                                                     m.RecordStatusValueId != dvInactive.Id);
                        }

                        var thisFamilyMembers = familyMemberQry.ToList();

                        if (thisFamilyMembers.Any())
                        {
                            var group = thisFamilyMembers
                                        .Select(m => m.Group)
                                        .FirstOrDefault();

                            var firstNames = thisFamilyMembers
                                             .OrderBy(m => m.Order)
                                             .ThenBy(m => m.BirthYear)
                                             .ThenBy(m => m.BirthMonth)
                                             .ThenBy(m => m.BirthDay)
                                             .ThenBy(m => m.Gender)
                                             .Select(m => m.NickName)
                                             .ToList();

                            var family = new CheckInFamily();
                            family.Group      = group.Clone(false);
                            family.Caption    = group.ToString();
                            family.FirstNames = firstNames;
                            family.SubCaption = firstNames.AsDelimited(", ");
                            checkInState.CheckIn.Families.Add(family);
                        }
                    }
                }

                return(true);
            }

            errorMessages.Add("Invalid Check-in State");
            return(false);
        }
Beispiel #18
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;
            }
        }
Beispiel #19
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext        = new RockContext();
            var groupMemberService = new GroupMemberService(rockContext);
            var searchPerson       = CurrentPerson;

            // If the person is a group leader, get their coordinator so they can view as them
            var consolidatorCoordinatorGuid =
                org.kcionline.bricksandmortarstudio.SystemGuid.GroupTypeRole.CONSOLIDATION_COORDINATOR.AsGuid();
            var cellGroupType =
                GroupTypeCache.Read(org.kcionline.bricksandmortarstudio.SystemGuid.GroupType.CELL_GROUP.AsGuid());

            if (
                groupMemberService.Queryable()
                .Any(gm => gm.GroupRole.IsLeader && gm.Group.GroupTypeId == cellGroupType.Id))
            {
                var baseGroup =
                    // ReSharper disable once PossibleNullReferenceException
                    groupMemberService.Queryable()
                    .FirstOrDefault(
                        gm => gm.GroupRole.IsLeader && gm.Group.GroupTypeId == cellGroupType.Id)
                    .Group;
                while (baseGroup != null)
                {
                    var coordinator =
                        baseGroup.Members.FirstOrDefault(gm => gm.GroupRole.Guid == consolidatorCoordinatorGuid);
                    if (coordinator != null)
                    {
                        searchPerson = coordinator.Person;
                        break;
                    }
                    baseGroup = baseGroup.ParentGroup;
                }
            }

            // filtering
            var connectionRequests = LineQuery.GetPeopleInLineFollowUpRequests(searchPerson);

            if (drpDates.LowerValue.HasValue)
            {
                connectionRequests = connectionRequests.Where(a => a.CreatedDateTime >= drpDates.LowerValue.Value);
            }

            if (drpDates.UpperValue.HasValue)
            {
                DateTime upperDate = drpDates.UpperValue.Value.Date.AddDays(1);
                connectionRequests = connectionRequests.Where(a => a.CreatedDateTime < upperDate);
            }

            if (!String.IsNullOrEmpty(ddlStatus.SelectedValue))
            {
                connectionRequests = connectionRequests.Where(cr => cr.ConnectionStatus.Name == ddlStatus.SelectedValue);
            }

            if (ppConsolidator.SelectedValue.HasValue)
            {
                connectionRequests =
                    connectionRequests.Where(
                        cr => cr.ConnectorPersonAlias.PersonId == ppConsolidator.SelectedValue.Value);
            }

            // end filtering

            var groupTypeRoleService = new GroupTypeRoleService(rockContext);
            var groupTypeRole        =
                groupTypeRoleService.Get(
                    org.kcionline.bricksandmortarstudio.SystemGuid.GroupTypeRole.CONSOLIDATED_BY.AsGuid());

            var followUps = new List <FollowUp>(connectionRequests.Count());

            foreach (var request in connectionRequests)
            {
                var firstOrDefault =
                    groupMemberService.GetKnownRelationship(request.PersonAlias.PersonId, groupTypeRole.Id)
                    .FirstOrDefault();
                if (firstOrDefault != null)
                {
                    var consolidator = firstOrDefault.Person;
                    followUps.Add(new FollowUp(request, consolidator));
                }
            }

            gList.DataSource = followUps;
            gList.DataBind();
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            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();
        }
        /// <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";
                                }
                            }
                        }

                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());
                        groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);
                    }
                }
                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;
                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());

                        if (groupMember.IsValidGroupMember(rockContext))
                        {
                            groupMemberService.Add(groupMember);
                            rockContext.SaveChanges();
                            groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);
                        }
                        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();
            }
        }
        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();
        }
Beispiel #23
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;

            var guidGroupAttribute = GetAttributeValue(action, "Group").AsGuidOrNull();

            if (guidGroupAttribute.HasValue)
            {
                var attributeGroup = AttributeCache.Get(guidGroupAttribute.Value, rockContext);
                if (attributeGroup != null)
                {
                    var groupGuid = action.GetWorkflowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();

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

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

            // 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()));
            }

            // remove person from group
            if (!errorMessages.Any())
            {
                try
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var groupMembers       = groupMemberService.Queryable().Where(m => m.PersonId == person.Id && m.GroupId == group.Id);

                    foreach (var groupMember in groupMembers)
                    {
                        groupMemberService.Delete(groupMember);
                    }

                    rockContext.SaveChanges();
                }
                catch (Exception ex)
                {
                    errorMessages.Add(string.Format("An error occurred while removing the group member: {0}", ex.Message));
                }
            }

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

            return(true);
        }
Beispiel #24
0
        /// <summary>
        /// Gets the suggestions.
        /// </summary>
        /// <param name="followingSuggestionType">Type of the following suggestion.</param>
        /// <param name="followerPersonIds">The follower person ids.</param>
        /// <returns></returns>
        public override List <PersonEntitySuggestion> GetSuggestions(FollowingSuggestionType followingSuggestionType, List <int> followerPersonIds)
        {
            var suggestions           = new List <PersonEntitySuggestion>();
            var personAliasEntityType = EntityTypeCache.Get(typeof(Rock.Model.PersonAlias));

            bool isAutoFollow = GetAttributeValue(followingSuggestionType, "AutoFollow").AsBoolean();

            // Get the grouptype guid
            Guid?groupTypeGuid = GetAttributeValue(followingSuggestionType, "GroupType").AsGuidOrNull();

            if (groupTypeGuid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var personAliasService = new PersonAliasService(rockContext);

                    // Get all the groupmember records for any follower and the selected group type
                    var followers = groupMemberService.Queryable().AsNoTracking()
                                    .Where(m =>
                                           m.GroupMemberStatus == GroupMemberStatus.Active &&
                                           m.Group != null &&
                                           m.Group.IsActive &&
                                           m.Group.GroupType.Guid.Equals(groupTypeGuid.Value) &&
                                           followerPersonIds.Contains(m.PersonId));

                    // If a specific group or security role was specified, limit groupmembers to only those of the selected group
                    Guid?groupGuid = GetAttributeValue(followingSuggestionType, "Group").AsGuidOrNull();
                    if (!groupGuid.HasValue)
                    {
                        groupGuid = GetAttributeValue(followingSuggestionType, "SecurityRole").AsGuidOrNull();
                    }
                    if (groupGuid.HasValue)
                    {
                        followers = followers.Where(m => m.Group.Guid.Equals(groupGuid.Value));
                    }

                    // If a specific role for the follower was specified, limit groupmembers to only those with the selected role
                    Guid?followerRoleGuid = GetAttributeValue(followingSuggestionType, "FollowerGroupType").AsGuidOrNull();
                    if (followerRoleGuid.HasValue)
                    {
                        followers = followers.Where(m => m.GroupRole.Guid.Equals(followerRoleGuid.Value));
                    }

                    // Run the query to get all the groups that follower is a member of with selected filters
                    var followerPersonGroup = followers
                                              .Select(f => new
                    {
                        f.PersonId,
                        f.GroupId
                    })
                                              .ToList();

                    // Get a unique list of any of the groups that followers belong to
                    var followedGroupIds = followerPersonGroup
                                           .Select(f => f.GroupId)
                                           .Distinct()
                                           .ToList();

                    // Start building query to get the people to follow from any group that contains a follower
                    var followed = groupMemberService
                                   .Queryable().AsNoTracking()
                                   .Where(m => followedGroupIds.Contains(m.GroupId) && m.GroupMemberStatus == GroupMemberStatus.Active);

                    // If a specific role for the people being followed was specified, limit the query to only those with the selected role
                    Guid?followedRoleGuid = GetAttributeValue(followingSuggestionType, "FollowedGroupType").AsGuidOrNull();
                    if (followedRoleGuid.HasValue)
                    {
                        followed = followed.Where(m => m.GroupRole.Guid.Equals(followedRoleGuid.Value));
                    }

                    // Get all the people in any of the groups that contain a follower
                    var followedPersonGroup = followed
                                              .Select(f => new
                    {
                        f.PersonId,
                        f.GroupId
                    })
                                              .ToList();

                    // Get distinct list of people
                    var followedPersonIds = followedPersonGroup
                                            .Select(f => f.PersonId)
                                            .Distinct()
                                            .ToList();

                    // Build a dictionary of the personid->personaliasid
                    var personAliasIds = new Dictionary <int, int>();
                    personAliasService.Queryable().AsNoTracking()
                    .Where(a =>
                           followedPersonIds.Contains(a.PersonId) &&
                           a.PersonId == a.AliasPersonId)
                    .ToList()
                    .ForEach(a => personAliasIds.AddOrIgnore(a.PersonId, a.Id));

                    // Loop through each follower/group combination
                    foreach (var followedGroup in followerPersonGroup)
                    {
                        // Loop through the other people in that group
                        foreach (int followedPersonId in followedPersonGroup
                                 .Where(f =>
                                        f.GroupId == followedGroup.GroupId &&
                                        f.PersonId != followedGroup.PersonId)
                                 .Select(f => f.PersonId))
                        {
                            // If the person has a valid personalias id
                            if (personAliasIds.ContainsKey(followedPersonId))
                            {
                                if (!isAutoFollow)
                                {
                                    // add them to the list of suggestions
                                    suggestions.Add(new PersonEntitySuggestion(followedGroup.PersonId, personAliasIds[followedPersonId]));
                                }
                                else
                                {
                                    // auto-add the follow

                                    var followingService = new FollowingService(rockContext);

                                    int followerPersonAliasId = personAliasIds[followedGroup.PersonId];
                                    int followeePersonAliasId = personAliasIds[followedPersonId];

                                    // if person is not already following the person
                                    bool isFollowing = followingService.Queryable().Where(f =>
                                                                                          f.EntityTypeId == personAliasEntityType.Id &&
                                                                                          f.EntityId == followeePersonAliasId &&
                                                                                          f.PersonAliasId == followerPersonAliasId).Any();
                                    if (!isFollowing)
                                    {
                                        var following = new Following();
                                        following.EntityTypeId  = personAliasEntityType.Id;
                                        following.EntityId      = personAliasIds[followedPersonId];
                                        following.PersonAliasId = personAliasIds[followedGroup.PersonId];
                                        followingService.Add(following);
                                        rockContext.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(suggestions);
        }
Beispiel #25
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();
        }
Beispiel #26
0
        /// <summary>
        /// Gets the suggestions.
        /// </summary>
        /// <param name="followingSuggestionType">Type of the following suggestion.</param>
        /// <param name="followerPersonIds">The follower person ids.</param>
        /// <returns></returns>
        public override List <PersonEntitySuggestion> GetSuggestions(FollowingSuggestionType followingSuggestionType, List <int> followerPersonIds)
        {
            var  suggestions           = new List <PersonEntitySuggestion>();
            var  groupEntityType       = EntityTypeCache.Get(typeof(Rock.Model.Group));
            var  personAliasEntityType = EntityTypeCache.Get(typeof(Rock.Model.PersonAlias));
            bool isAutoFollow          = GetAttributeValue(followingSuggestionType, "AutoFollow").AsBoolean();

            // Get the grouptype guid
            Guid?groupTypeGuid = GetAttributeValue(followingSuggestionType, "GroupType").AsGuidOrNull();

            if (groupTypeGuid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var followingService   = new FollowingService(rockContext);
                    var groupMemberService = new GroupMemberService(rockContext);
                    var personAliasService = new PersonAliasService(rockContext);

                    var followings = followingService.Queryable()
                                     .Where(a => a.EntityTypeId == groupEntityType.Id &&
                                            followerPersonIds.Contains(a.PersonAlias.PersonId))
                                     .Select(f => new
                    {
                        f.PersonAliasId,
                        f.PersonAlias.PersonId,
                        f.EntityId
                    }).Distinct()
                                     .ToList();

                    var followedGroup = followings.Select(a => a.EntityId).Distinct().ToList();
                    // Get all the groupmember records of Followed group
                    var followedGroupMembersQry = groupMemberService.Queryable().AsNoTracking()
                                                  .Where(m =>
                                                         m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                         m.Group != null &&
                                                         m.Group.IsActive &&
                                                         m.Group.GroupType.Guid.Equals(groupTypeGuid.Value) &&
                                                         followedGroup.Contains(m.GroupId));


                    // If a specific role for the people being followed was specified, limit the query to only those with the selected role
                    Guid?groupRoleGuid = GetAttributeValue(followingSuggestionType, "GroupRole").AsGuidOrNull();
                    if (groupRoleGuid.HasValue)
                    {
                        followedGroupMembersQry = followedGroupMembersQry.Where(m => m.GroupRole.Guid.Equals(groupRoleGuid.Value));
                    }

                    var followedGroupMembers = followedGroupMembersQry.ToList();

                    // Run the query to get all the groups that follower is a member of with selected filters
                    var followerPersonGroups = followings
                                               .Select(f => new
                    {
                        GroupMembers = followedGroupMembers.Where(a => a.GroupId == f.EntityId).ToList(),
                        f.PersonAliasId,
                        f.PersonId
                    })
                                               .ToList();

                    var followedMembersList = followedGroupMembers
                                              .Select(a => a.PersonId)
                                              .Distinct()
                                              .ToList();
                    // Build a dictionary of the personid->personaliasid
                    var personAliasIds = new Dictionary <int, int>();
                    personAliasService.Queryable().AsNoTracking()
                    .Where(a =>
                           followedMembersList.Contains(a.PersonId) &&
                           a.PersonId == a.AliasPersonId)
                    .ToList()
                    .ForEach(a => personAliasIds.AddOrIgnore(a.PersonId, a.Id));


                    // Loop through each follower/group combination
                    foreach (var followerPersonGroup in followerPersonGroups)
                    {
                        // Loop through the other people in that group
                        foreach (var member in followerPersonGroup.GroupMembers)
                        {
                            if (!isAutoFollow)
                            {
                                // add them to the list of suggestions
                                suggestions.Add(new PersonEntitySuggestion(followerPersonGroup.PersonId, personAliasIds[member.PersonId]));
                            }
                            else
                            {
                                // auto-add the follow
                                int followeePersonAliasId = personAliasIds[member.PersonId];

                                // if person is not already following the person
                                bool isFollowing = followingService.Queryable().Where(f =>
                                                                                      f.EntityTypeId == personAliasEntityType.Id &&
                                                                                      f.EntityId == followeePersonAliasId &&
                                                                                      f.PersonAliasId == followerPersonGroup.PersonAliasId).Any();
                                if (!isFollowing)
                                {
                                    var following = new Following();
                                    following.EntityTypeId  = personAliasEntityType.Id;
                                    following.EntityId      = followeePersonAliasId;
                                    following.PersonAliasId = followerPersonGroup.PersonAliasId;
                                    followingService.Add(following);
                                    rockContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }

            return(suggestions);
        }
        /// <summary>
        /// Shows the report.
        /// </summary>
        private void ShowMap()
        {
            string mapStylingFormat = @"
                        <style>
                            #map_wrapper {{
                                height: {0}px;
                            }}

                            #map_canvas {{
                                width: 100%;
                                height: 100%;
                                border-radius: 8px;
                            }}
                        </style>";

            lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight"));

            // add styling to map
            string styleCode = "null";

            DefinedValueCache dvcMapStyle = DefinedValueCache.Read(GetAttributeValue("MapStyle").AsGuid());

            if (dvcMapStyle != null)
            {
                styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle");
            }

            var    polygonColorList = GetAttributeValue("PolygonColors").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            string polygonColors    = polygonColorList.AsDelimited(",");

            string latitude    = "39.8282";
            string longitude   = "-98.5795";
            string zoom        = "4";
            var    orgLocation = GlobalAttributesCache.Read().OrganizationLocation;

            if (orgLocation != null && orgLocation.GeoPoint != null)
            {
                latitude  = orgLocation.GeoPoint.Latitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
                longitude = orgLocation.GeoPoint.Longitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
                zoom      = "12";
            }

            var rockContext     = new RockContext();
            var campuses        = CampusCache.All();
            var locationService = new LocationService(rockContext);

            CampusMarkersData = string.Empty;
            if (cbShowCampusLocations.Checked)
            {
                foreach (var campus in campuses)
                {
                    if (campus.LocationId.HasValue)
                    {
                        var location = locationService.Get(campus.LocationId.Value);
                        if (location != null && location.GeoPoint != null)
                        {
                            CampusMarkersData += string.Format("{{ location: new google.maps.LatLng({0},{1}), campusName:'{2}' }},", location.GeoPoint.Latitude, location.GeoPoint.Longitude, campus.Name);
                        }
                    }
                }

                CampusMarkersData.TrimEnd(new char[] { ',' });
            }

            // show geofences if a group was specified
            this.GroupId = this.PageParameter("GroupId").AsIntegerOrNull();
            if (!this.GroupId.HasValue && gpGroupToMap.Visible)
            {
                // if a page parameter wasn't specified, use the selected group from the filter
                this.GroupId = gpGroupToMap.SelectedValue.AsIntegerOrNull();
            }

            var groupMemberService      = new GroupMemberService(rockContext);
            var groupLocationTypeHome   = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
            int groupLocationTypeHomeId = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0;
            var groupTypeFamily         = GroupTypeCache.GetFamilyGroupType();
            int groupTypeFamilyId       = groupTypeFamily != null ? groupTypeFamily.Id : 0;

            // if there is a DataViewId page parameter, use that instead of the Block or Filter dataview setting (the filter control won't be visible if there is a DataViewId page parameter)
            int? dataViewId   = this.PageParameter("DataViewId").AsIntegerOrNull();
            Guid?dataViewGuid = null;

            if (!dataViewId.HasValue)
            {
                dataViewGuid = this.GetAttributeValue("DataView").AsGuidOrNull();
            }

            if (ddlUserDataView.Visible)
            {
                dataViewGuid = ddlUserDataView.SelectedValue.AsGuidOrNull();
            }

            IQueryable <int> qryPersonIds = null;

            if (dataViewId.HasValue || dataViewGuid.HasValue)
            {
                DataView dataView = null;

                // if a DataViewId page parameter was specified, use that, otherwise use the blocksetting or filter selection
                if (dataViewId.HasValue)
                {
                    dataView = new DataViewService(rockContext).Get(dataViewId.Value);
                }
                else
                {
                    dataView = new DataViewService(rockContext).Get(dataViewGuid.Value);
                }

                if (dataView != null)
                {
                    List <string> errorMessages;
                    qryPersonIds = dataView.GetQuery(null, rockContext, null, out errorMessages).OfType <Person>().Select(a => a.Id);
                }
            }

            if (qryPersonIds == null)
            {
                // if no dataview was specified, show nothing
                qryPersonIds = new PersonService(rockContext).Queryable().Where(a => false).Select(a => a.Id);
            }

            var qryGroupMembers = groupMemberService.Queryable();

            var campusIds = cpCampuses.SelectedCampusIds;

            if (campusIds.Any())
            {
                qryGroupMembers = qryGroupMembers.Where(a => a.Group.CampusId.HasValue && campusIds.Contains(a.Group.CampusId.Value));
            }

            var qryLocationGroupMembers = qryGroupMembers
                                          .Where(a => a.Group.GroupTypeId == groupTypeFamilyId)
                                          .Where(a => a.Group.IsActive)
                                          .Select(a => new
            {
                GroupGeoPoint = a.Group.GroupLocations.Where(gl => gl.IsMappedLocation && gl.GroupLocationTypeValueId == groupLocationTypeHomeId && gl.Location.IsActive && gl.Location.GeoPoint != null).Select(x => x.Location.GeoPoint).FirstOrDefault(),
                a.Group.CampusId,
                a.PersonId
            })
                                          .Where(a => (a.GroupGeoPoint != null) && qryPersonIds.Contains(a.PersonId))
                                          .GroupBy(a => new { a.GroupGeoPoint.Latitude, a.GroupGeoPoint.Longitude })
                                          .Select(s => new
            {
                s.Key.Longitude,
                s.Key.Latitude,
                MemberCount = s.Count()
            });

            var locationList = qryLocationGroupMembers.ToList()
                               .Select(a => new LatLongWeighted(a.Latitude.Value, a.Longitude.Value, a.MemberCount))
                               .ToList();

            List <LatLongWeighted> points = locationList;

            // cluster points that are close together
            double?milesPerGrouping = this.GetAttributeValue("PointGrouping").AsDoubleOrNull();

            if (!milesPerGrouping.HasValue)
            {
                // default to a 1/10th of a mile
                milesPerGrouping = 0.10;
            }

            if (milesPerGrouping.HasValue && milesPerGrouping > 0)
            {
                var metersPerLatitudePHX  = 110886.79;
                var metersPerLongitudePHX = 94493.11;

                double metersPerMile = 1609.34;

                var squareLengthHeightMeters = metersPerMile * milesPerGrouping.Value;

                var longitudeRoundFactor = metersPerLongitudePHX / squareLengthHeightMeters;
                var latitudeRoundFactor  = metersPerLatitudePHX / squareLengthHeightMeters;

                points = points.GroupBy(a => new
                {
                    rLat  = Math.Round(a.Lat * latitudeRoundFactor),
                    rLong = Math.Round(a.Lat * longitudeRoundFactor),
                }).Select(a => new LatLongWeighted(a.Average(x => x.Lat), a.Average(x => x.Long), a.Sum(x => x.Weight))).ToList();
            }

            this.HeatMapData = points.Select(a => a.Weight > 1
                ? string.Format("{{location: new google.maps.LatLng({0}, {1}), weight: {2}}}", a.Lat, a.Long, a.Weight)
                : string.Format("new google.maps.LatLng({0}, {1})", a.Lat, a.Long)).ToList().AsDelimited(",\n");

            StyleCode               = styleCode;
            hfPolygonColors.Value   = polygonColors;
            hfCenterLatitude.Value  = latitude.ToString();
            hfCenterLongitude.Value = longitude.ToString();
            hfZoom.Value            = zoom.ToString();
        }
        /// <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);
        }
Beispiel #29
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)
        {
            string cacheKey = "Rock.FindRelationships.Roles";

            ObjectCache cache = Rock.Web.Cache.RockMemoryCache.Default;
            List <int>  roles = cache[cacheKey] as List <int>;

            if (roles == null)
            {
                roles = new List <int>();

                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);
                        }
                    }
                }

                CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
                cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(300);
                cache.Set(cacheKey, roles, cacheItemPolicy);
            }

            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                if (!roles.Any())
                {
                    return(true);
                }

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    bool preventInactive = (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeopele);
                    var  dvInactive      = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid());

                    var groupMemberService = new GroupMemberService(rockContext);

                    var familyMemberIds = family.People.Select(p => p.Person.Id).ToList();

                    // Get the Known Relationship group id's for each person in the family
                    var relationshipGroups = groupMemberService
                                             .Queryable().AsNoTracking()
                                             .Where(g =>
                                                    g.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)) &&
                                                    familyMemberIds.Contains(g.PersonId))
                                             .Select(g => g.GroupId);

                    // Get anyone in any of those groups that has a role with the canCheckIn attribute set
                    foreach (var person in groupMemberService
                             .Queryable().AsNoTracking()
                             .Where(g =>
                                    relationshipGroups.Contains(g.GroupId) &&
                                    roles.Contains(g.GroupRoleId))
                             .Select(g => g.Person)
                             .ToList())
                    {
                        if (!family.People.Any(p => p.Person.Id == person.Id))
                        {
                            if (!preventInactive || dvInactive == null || person.RecordStatusValueId != dvInactive.Id)
                            {
                                var relatedPerson = new CheckInPerson();
                                relatedPerson.Person       = person.Clone(false);
                                relatedPerson.FamilyMember = false;
                                family.People.Add(relatedPerson);
                            }
                        }
                    }

                    return(true);
                }
                else
                {
                    errorMessages.Add("There is not a family that is selected");
                }

                return(false);
            }

            return(false);
        }
Beispiel #30
0
        private void GetPersonSearchDetails(PersonSearchResult personSearchResult, Person person)
        {
            var    rockContext      = this.Service.Context as RockContext;
            string itemDetailFormat = @"
<div class='picker-select-item-details clearfix' style='display: none;'>
	{0}
	<div class='contents'>
        {1}
	</div>
</div>
";

            var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
            int adultRoleId     = familyGroupType.Roles.First(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;

            int groupTypeFamilyId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

            // figure out Family, Address, Spouse
            var groupMemberService = new GroupMemberService(rockContext);

            Guid?recordTypeValueGuid = null;

            if (person.RecordTypeValueId.HasValue)
            {
                recordTypeValueGuid = DefinedValueCache.Read(person.RecordTypeValueId.Value).Guid;
            }

            personSearchResult.ImageHtmlTag     = Person.GetPersonPhotoImageTag(person, 50, 50);
            personSearchResult.Age              = person.Age.HasValue ? person.Age.Value : -1;
            personSearchResult.ConnectionStatus = person.ConnectionStatusValueId.HasValue ? DefinedValueCache.Read(person.ConnectionStatusValueId.Value).Value : string.Empty;
            personSearchResult.Gender           = person.Gender.ConvertToString();
            personSearchResult.Email            = person.Email;

            string imageHtml = string.Format(
                "<div class='person-image' style='background-image:url({0}&width=65);background-size:cover;background-position:50%'></div>",
                Person.GetPersonPhotoUrl(person, 200, 200));

            string personInfoHtml = string.Empty;
            Guid   matchLocationGuid;
            bool   isBusiness;

            if (recordTypeValueGuid.HasValue && recordTypeValueGuid == Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid())
            {
                isBusiness        = true;
                matchLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK.AsGuid();
            }
            else
            {
                isBusiness        = false;
                matchLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();
            }

            var familyGroupMember = groupMemberService.Queryable()
                                    .Where(a => a.PersonId == person.Id)
                                    .Where(a => a.Group.GroupTypeId == groupTypeFamilyId)
                                    .Select(s => new
            {
                s.GroupRoleId,
                GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid == matchLocationGuid).Select(a => a.Location).FirstOrDefault()
            }).FirstOrDefault();

            int?personAge = person.Age;

            if (familyGroupMember != null)
            {
                if (isBusiness)
                {
                    personInfoHtml += "Business";
                }
                else
                {
                    personInfoHtml += familyGroupType.Roles.First(a => a.Id == familyGroupMember.GroupRoleId).Name;
                }

                if (personAge != null)
                {
                    personInfoHtml += " <em>(" + personAge.ToString() + " yrs old)</em>";
                }

                if (familyGroupMember.GroupRoleId == adultRoleId)
                {
                    var personService = this.Service as PersonService;
                    var spouse        = personService.GetSpouse(person, a => new
                    {
                        a.Person.NickName,
                        a.Person.LastName,
                        a.Person.SuffixValueId
                    });

                    if (spouse != null)
                    {
                        string spouseFullName = Person.FormatFullName(spouse.NickName, spouse.LastName, spouse.SuffixValueId);
                        personInfoHtml += "<p><strong>Spouse:</strong> " + spouseFullName + "</p>";
                        personSearchResult.SpouseName = spouseFullName;
                    }
                }
            }
            else
            {
                if (personAge != null)
                {
                    personInfoHtml += personAge.ToString() + " yrs old";
                }
            }

            if (familyGroupMember != null)
            {
                var location = familyGroupMember.GroupLocation;

                if (location != null)
                {
                    string addressHtml = "<h5>Address</h5>" + location.GetFullStreetAddress().ConvertCrLfToHtmlBr();
                    personSearchResult.Address = location.GetFullStreetAddress();
                    personInfoHtml            += addressHtml;
                }
            }

            // Generate the HTML for Email and PhoneNumbers
            if (!string.IsNullOrWhiteSpace(person.Email) || person.PhoneNumbers.Any())
            {
                string emailAndPhoneHtml = "<p class='margin-t-sm'>";
                emailAndPhoneHtml += person.Email;
                string phoneNumberList = string.Empty;
                foreach (var phoneNumber in person.PhoneNumbers)
                {
                    var phoneType = DefinedValueCache.Read(phoneNumber.NumberTypeValueId ?? 0);
                    phoneNumberList += string.Format(
                        "<br>{0} <small>{1}</small>",
                        phoneNumber.IsUnlisted ? "Unlisted" : phoneNumber.NumberFormatted,
                        phoneType != null ? phoneType.Value : string.Empty);
                }

                emailAndPhoneHtml += phoneNumberList + "<p>";

                personInfoHtml += emailAndPhoneHtml;
            }

            personSearchResult.PickerItemDetailsImageHtml      = imageHtml;
            personSearchResult.PickerItemDetailsPersonInfoHtml = personInfoHtml;
            personSearchResult.PickerItemDetailsHtml           = string.Format(itemDetailFormat, imageHtml, personInfoHtml);
        }