/// <summary> /// Deletes or Archives (Soft-Deletes) GroupMember record depending on GroupType.EnableGroupHistory and if the GroupMember has history snapshots /// </summary> /// <param name="item">The item.</param> /// <returns></returns> public override bool Delete(GroupMember item) { var rockContext = this.Context as RockContext; int?groupTypeId = item.Group?.GroupTypeId; if (!groupTypeId.HasValue) { groupTypeId = new GroupService(rockContext).GetSelect(item.GroupId, a => a.GroupTypeId); } var groupTypeCache = GroupTypeCache.Get(groupTypeId.Value); if (groupTypeCache?.EnableGroupHistory == true) { var groupMemberHistoricalService = new GroupMemberHistoricalService(rockContext); if (groupMemberHistoricalService.Queryable().Any(a => a.GroupMemberId == item.Id)) { // if the group's GroupType has GroupHistory enabled, and this group member has group member history snapshots, then we need to Archive instead of Delete this.Archive(item, null, false); return(true); } } // As discussed in https://github.com/SparkDevNetwork/Rock/issues/4697, we are going to delete // the association from any group member assignments that have a reference to this group member. var groupMemberAssignmentService = new GroupMemberAssignmentService(this.Context as RockContext); foreach (var groupMemberAssignment in groupMemberAssignmentService.Queryable().Where(a => a.GroupMemberId == item.Id)) { groupMemberAssignmentService.Delete(groupMemberAssignment); } return(base.Delete(item)); }
/// <summary> /// Shows the view. /// </summary> /// <param name = "groupId" > The group identifier.</param> protected void ShowView(int?groupId, int?groupMemberId, Guid?groupGuid) { var rockContext = new RockContext(); Group group = null; GroupMember groupMember = null; int fundraisingOpportunityTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FUNDRAISINGOPPORTUNITY).Id; pnlView.Visible = true; hfGroupId.Value = groupId.ToStringSafe(); hfGroupMemberId.Value = groupMemberId.ToStringSafe(); hfGroupGuid.Value = groupGuid.ToStringSafe(); if (groupId.HasValue) { group = new GroupService(rockContext).Get(groupId.Value); } else if (groupGuid.HasValue) { group = new GroupService(rockContext).Get(groupGuid.Value); } else { groupMember = new GroupMemberService(rockContext).Get(groupMemberId ?? 0); group = groupMember.Group; } if (group == null || (group.GroupTypeId != fundraisingOpportunityTypeId && group.GroupType.InheritedGroupTypeId != fundraisingOpportunityTypeId)) { pnlView.Visible = false; return; } lTitle.Text = group.Name.FormatAsHtmlTitle(); BindGroupMembersProgressGrid(group, groupMember, rockContext); }
/// <summary> /// Show the block content. /// </summary> protected void ShowDetails() { var group = ContextEntity <Group>(); var groupMember = ContextEntity <GroupMember>(); if (groupMember != null) { group = groupMember.Group; } pnlDetails.Visible = false; // // Only show the panel and content if the group type is a fundraising opportunity. // var rockContext = new RockContext(); var groupService = new GroupService(rockContext); var groupTypeIdFundraising = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FUNDRAISINGOPPORTUNITY.AsGuid()).Id; var fundraisingGroupTypeIdList = new GroupTypeService(rockContext).Queryable().Where(a => a.Id == groupTypeIdFundraising || a.InheritedGroupTypeId == groupTypeIdFundraising).Select(a => a.Id).ToList(); if (group != null && fundraisingGroupTypeIdList.Contains(group.GroupTypeId)) { pnlDetails.Visible = true; BindGrid(); } }
/// <summary> /// Binds the filter. /// </summary> public void BindFilter() { var rockContext = new RockContext(); int groupId = hfGroupId.Value.AsInteger(); var group = new GroupService(rockContext).Get(groupId); var groupTypeCache = GroupTypeCache.Get(group.GroupTypeId); gfGroupMembers.UserPreferenceKeyPrefix = string.Format("{0}-", groupId); tbFirstName.Text = gfGroupMembers.GetUserPreference("First Name"); tbLastName.Text = gfGroupMembers.GetUserPreference("Last Name"); sdrDateAdded.DelimitedValues = gfGroupMembers.GetUserPreference("Date Added"); sdrDateRemoved.DelimitedValues = gfGroupMembers.GetUserPreference("Date Removed"); cblRole.Items.Clear(); if (groupTypeCache != null) { foreach (var role in groupTypeCache.Roles) { cblRole.Items.Add(new ListItem(role.Name, role.Id.ToString())); } } List <int> selectedGroupRoleIds = gfGroupMembers.GetUserPreference("Group Role").FromJsonOrNull <List <int> >() ?? new List <int>(); cblRole.SetValues(selectedGroupRoleIds); cblGroupMemberStatus.BindToEnum <GroupMemberStatus>(); List <GroupMemberStatus> selectedGroupMemberStatuses = gfGroupMembers.GetUserPreference("Group Member Status").FromJsonOrNull <List <GroupMemberStatus> >() ?? new List <GroupMemberStatus>(); cblGroupMemberStatus.SetValues(selectedGroupMemberStatuses.Select(a => a.ConvertToInt())); }
/// <summary> /// Gets the selection. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="controls">The controls.</param> /// <returns></returns> public override string GetSelection(Type entityType, Control[] controls) { var groupTypePicker = (controls[0] as GroupTypePicker); var cblRoles = (controls[1] as RockCheckBoxList); var ddlGroupStatus = (controls[2] as RockDropDownList); var ddlMemberStatus = (controls[3] as RockDropDownList); int groupTypeId = groupTypePicker.SelectedValueAsId() ?? 0; Guid?groupTypeGuid = null; var groupType = GroupTypeCache.Get(groupTypeId); if (groupType != null) { groupTypeGuid = groupType.Guid; } var rolesGuidCommaList = cblRoles.SelectedValues.AsDelimited(","); var memberStatusValue = ddlMemberStatus.SelectedValue; var groupStatus = ddlGroupStatus.SelectedValue; return(groupTypeGuid.ToString() + "|" + rolesGuidCommaList + "|" + memberStatusValue + "|" + groupStatus); }
/// <summary> /// Gets the checkin area descendants. /// </summary> /// <param name="parentCheckinAreaGroupTypeId">The parent checkin area group type identifier.</param> /// <returns></returns> public List <GroupTypeCache> GetCheckinAreaDescendants(int parentCheckinAreaGroupTypeId) { List <GroupTypeCache> checkinAreaDescendants = new List <GroupTypeCache>(); BuildCheckinAreaDescendants(GroupTypeCache.Get(parentCheckinAreaGroupTypeId), ref checkinAreaDescendants); return(checkinAreaDescendants); }
/// <summary> /// Save this child as a person in a family /// </summary> /// <param name="familyId">The family to add this child to</param> /// <param name="rockContext">The RockContext</param> /// <returns></returns> public Person SaveAsPerson(int familyId, RockContext rockContext) { var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY); var childRoleId = familyGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var person = new Person(); person.FirstName = this.FirstName; person.LastName = this.LastName; person.BirthDay = this.DateOfBirth.Day; person.BirthMonth = this.DateOfBirth.Month; person.BirthYear = this.DateOfBirth.Year; person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; person.ConnectionStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_WEB_PROSPECT.AsGuid()).Id; person.RecordStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; if (this.Grade.HasValue) { person.GraduationYear = Person.GraduationYearFromGradeOffset(DefinedValueCache.Get(this.Grade.Value).Value.AsInteger()); } PersonService.AddPersonToFamily(person, true, familyId, childRoleId, rockContext); SaveAttributes(person); return(person); }
/// <summary> /// Initializes a new instance of the <see cref="DefinedValueFieldAttribute" /> class. /// </summary> /// <param name="groupTypeGuid">The group type GUID.</param> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <param name="required">if set to <c>true</c> [required].</param> /// <param name="defaultValue">The default value.</param> /// <param name="category">The category.</param> /// <param name="order">The order.</param> /// <param name="key">The key.</param> public GroupRoleFieldAttribute(string groupTypeGuid = "", string name = "", string description = "", bool required = true, string defaultValue = "", string category = "", int order = 0, string key = null) : base(name, description, required, defaultValue, category, order, key, typeof(Rock.Field.Types.GroupRoleFieldType).FullName) { if (!string.IsNullOrWhiteSpace(groupTypeGuid)) { Guid guid = Guid.Empty; if (Guid.TryParse(groupTypeGuid, out guid)) { var groupType = GroupTypeCache.Get(guid); if (groupType != null) { var configValue = new Field.ConfigurationValue(groupType.Id.ToString()); FieldConfigurationValues.Add("grouptype", configValue); if (string.IsNullOrWhiteSpace(Name)) { Name = groupType.Name + " Role"; if (string.IsNullOrWhiteSpace(Key)) { Key = Name.Replace(" ", string.Empty); } } } } } }
/// <summary> /// Creates the control(s) necessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id) { ListControl editControl; editControl = new Rock.Web.UI.Controls.RockDropDownList { ID = id }; editControl.Items.Add(new ListItem()); if (configurationValues != null && configurationValues.ContainsKey(GROUP_TYPE_KEY)) { Guid?groupTypeGuid = configurationValues.GetValueOrNull(GROUP_TYPE_KEY).AsGuidOrNull(); if (groupTypeGuid != null) { var groupType = GroupTypeCache.Get(groupTypeGuid.Value); if (groupType != null) { var locationTypeValues = groupType.LocationTypeValues; if (locationTypeValues != null) { foreach (var locationTypeValue in locationTypeValues) { editControl.Items.Add(new ListItem(locationTypeValue.Value, locationTypeValue.Id.ToString())); } } } } } return(editControl); }
/// <summary> /// Gets the device group types. /// </summary> /// <param name="deviceId">The device identifier.</param> /// <returns></returns> private List <GroupTypeCache> GetDeviceGroupTypes(int deviceId, RockContext rockContext) { var locationService = new LocationService(rockContext); var groupLocationService = new GroupLocationService(rockContext); // Get all locations (and their children) associated with device var locationIds = locationService .GetByDevice(deviceId, true) .Select(l => l.Id) .ToList(); var locationGroupTypes = groupLocationService .Queryable().AsNoTracking() .Where(l => locationIds.Contains(l.LocationId)) .Where(gl => gl.Group.GroupType.TakesAttendance) .Select(gl => gl.Group.GroupTypeId) .ToList() .Select(a => GroupTypeCache.Get(a)).ToList(); // get all distinct group types var groupTypes = new Dictionary <int, GroupTypeCache>(); foreach (var groupType in locationGroupTypes) { groupTypes.AddOrIgnore(groupType.Id, groupType); } return(groupTypes .Select(g => g.Value) .OrderBy(g => g.Order) .ToList()); }
/// <summary> /// Populates the group roles. /// </summary> /// <param name="checkboxList"></param> /// <param name="groupTypeGuid"></param> private void PopulateRelationshipTypesSelector(RockCheckBoxList checkboxList, Guid?groupTypeGuid) { bool showSelector = false; checkboxList.Items.Clear(); var groupType = GroupTypeCache.Get(groupTypeGuid.GetValueOrDefault()); if (groupType != null) { var selectableRoles = new GroupTypeRoleService(new RockContext()).GetByGroupTypeId(groupType.Id); // Exclude the Owner Role from the list of selectable Roles because a Person cannot be related to themselves. var ownerGuid = GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid(); selectableRoles = selectableRoles.Where(x => x.Guid != ownerGuid); checkboxList.Items.Clear(); foreach (var item in selectableRoles) { checkboxList.Items.Add(new ListItem(item.Name, item.Guid.ToString())); } showSelector = checkboxList.Items.Count > 0; } checkboxList.Visible = showSelector; }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType"></param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { if (!string.IsNullOrWhiteSpace(selection)) { var values = JsonConvert.DeserializeObject <List <string> >(selection); if (values.Count >= 3) { var groupType = GroupTypeCache.Get(values[0].AsGuid()); if (groupType != null) { string selectedProperty = values[1]; var entityFields = GetGroupAttributes(groupType.Id); var entityField = entityFields.FindFromFilterSelection(selectedProperty); if (entityField != null) { return(GetAttributeExpression(serviceInstance, parameterExpression, entityField, values.Skip(2).ToList())); } } } } return(null); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="context">The context.</param> /// <param name="entityIdProperty">The entity identifier property.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection) { var qryGroupService = new GroupService(context).Queryable(); Expression <Func <Rock.Model.GroupMember, bool> > memberWhereGroupType = a => 1 == 1; Expression <Func <Rock.Model.GroupMember, bool> > memberWhereGroupRoles = a => 1 == 1; Expression <Func <Rock.Model.GroupMember, bool> > memberWhereStatus = a => 1 == 1; string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 3) { GroupMemberService groupMemberService = new GroupMemberService(context); int?groupTypeId = null; Guid groupTypeGuid = selectionValues[1].AsGuid(); var groupType = GroupTypeCache.Get(groupTypeGuid); if (groupType != null) { groupTypeId = groupType.Id; } if (groupTypeId.HasValue) { memberWhereGroupType = xx => xx.Group.GroupTypeId == groupTypeId; } var groupRoleGuids = selectionValues[2].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => n.AsGuid()).ToList(); List <int> groupRoleIds = null; if (groupRoleGuids.Count() > 0) { groupRoleIds = new GroupTypeRoleService(context).Queryable().Where(a => groupRoleGuids.Contains(a.Guid)).Select(a => a.Id).ToList(); memberWhereGroupRoles = xx => groupRoleIds.Contains(xx.GroupRoleId); } GroupMemberStatus?groupMemberStatus = selectionValues[3].ConvertToEnumOrNull <GroupMemberStatus>(); if (groupMemberStatus.HasValue) { memberWhereStatus = xx => xx.GroupMemberStatus == groupMemberStatus.Value; } } var memberListQuery = qryGroupService.Select(p => p.Members.AsQueryable() .Where(memberWhereGroupType) .Where(memberWhereGroupRoles) .Where(memberWhereStatus) .Select(m => new MemberInfo { NickName = m.Person.NickName, LastName = m.Person.LastName, SuffixValueId = m.Person.SuffixValueId, PersonId = m.PersonId, GroupMemberId = m.Id }).OrderBy(a => a.LastName).ThenBy(a => a.NickName)); var selectChildrenExpression = SelectExpressionExtractor.Extract(memberListQuery, entityIdProperty, "p"); return(selectChildrenExpression); }
protected void btnOptOutIn_Click(object sender, EventArgs e) { if (CurrentPerson != null && _optOutGroupGuid.HasValue) { using (var rockContext = new RockContext()) { bool optIn = lbOptInOut.Text == "Opt in to the Directory"; if (_showFamily) { var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); foreach (var familyMember in new GroupService(rockContext) .Queryable().AsNoTracking() .Where(g => g.GroupTypeId == familyGroupType.Id && g.Members.Any(m => m.PersonId == CurrentPerson.Id)) .SelectMany(g => g.Members) .Select(m => m.Person)) { OptInOutPerson(rockContext, CurrentPerson, optIn); } } else { OptInOutPerson(rockContext, CurrentPerson, optIn); } rockContext.SaveChanges(); } BindData(); } }
/// <summary> /// Deletes or Archives (Soft-Deletes) GroupMember record depending on GroupType.EnableGroupHistory and if the GroupMember has history snapshots /// </summary> /// <param name="item">The item.</param> /// <returns></returns> public override bool Delete(GroupMember item) { var rockContext = this.Context as RockContext; int?groupTypeId = item.Group?.GroupTypeId; if (!groupTypeId.HasValue) { groupTypeId = new GroupService(rockContext).GetSelect(item.GroupId, a => a.GroupTypeId); } var groupTypeCache = GroupTypeCache.Get(groupTypeId.Value); if (groupTypeCache?.EnableGroupHistory == true) { var groupMemberHistoricalService = new GroupMemberHistoricalService(rockContext); if (groupMemberHistoricalService.Queryable().Any(a => a.GroupMemberId == item.Id)) { // if the group's GroupType has GroupHistory enabled, and this group member has group member history snapshots, then we need to Archive instead of Delete this.Archive(item, null, false); return(true); } } return(base.Delete(item)); }
/// <summary> /// Binds the checkbox lists. /// </summary> private void BindCheckBoxLists() { // roles... var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); cblRoles.DataSource = familyGroupType.Roles; cblRoles.DataBind(); // connection status... // NOTE: if we want to bind and preselect one or more items based on an attribute, we can do it like this //var statuses = DefinedTypeCache.Get( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS.AsGuid() ).DefinedValues // .OrderBy( v => v.Order ) // .ThenBy( v => v.Value ) // .Select( v => new ListItem // { // Value = v.Id.ToString(), // Text = v.Value.Pluralize(), // Selected = ( v.GetAttributeValue( "PreSelected" ) ).AsBoolean(false) // } ) // .ToList(); //foreach ( var item in statuses) //{ // cblConnectionStatus.Items.Add( item ); //} // otherwise we can just bind like this for now dvpConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS.AsGuid()).Id; }
protected void btnDeactivate_Click(object sender, EventArgs e) { int id = hfMemberId.Value.AsInteger(); if (id > 0) { _rockContext = new RockContext(); int?groupTypeId = new GroupService(_rockContext).Get(id).GroupTypeId; var groupTypeCache = GroupTypeCache.Get(groupTypeId.Value); if (groupTypeCache.EnableGroupHistory == true) { archiveMember(id); } else { deactivateMember(id); } } mdMember.Hide(); hfMemberId.Value = null; GetGroupMembers(); BindData(); }
/// <summary> /// Formats the selection. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override string FormatSelection(Type entityType, string selection) { string s = "Group Type Attendance"; string[] options = selection.Split('|'); if (options.Length >= 4) { var groupType = GroupTypeCache.Get(options[0].AsGuid()); ComparisonType comparisonType = options[1].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo); bool includeChildGroups = options.Length > 4 ? options[4].AsBoolean() : false; string dateRangeText; int? lastXWeeks = options[3].AsIntegerOrNull(); if (lastXWeeks.HasValue) { dateRangeText = " in last " + (lastXWeeks.Value * 7).ToString() + " days"; } else { dateRangeText = SlidingDateRangePicker.FormatDelimitedValues(options[3].Replace(',', '|')); } s = string.Format( "Attended '{0}'{4} {1} {2} times. Date Range: {3}", groupType != null ? groupType.Name : "?", comparisonType.ConvertToString(), options[2], dateRangeText, includeChildGroups ? " (or child group types) " : string.Empty); } return(s); }
/// <summary> /// Gets the available group types. /// </summary> /// <returns></returns> private List <int> GetAvailableGroupTypes() { var groupTypeIds = new List <int>(); var groupTypeService = new GroupTypeService(new RockContext()); var qry = groupTypeService.Queryable().Where(t => t.ShowInGroupList); List <Guid> includeGroupTypeGuids = GetAttributeValue("IncludeGroupTypes").SplitDelimitedValues().Select(a => Guid.Parse(a)).ToList(); if (includeGroupTypeGuids.Count > 0) { _groupTypesCount = includeGroupTypeGuids.Count; qry = qry.Where(t => includeGroupTypeGuids.Contains(t.Guid)); } List <Guid> excludeGroupTypeGuids = GetAttributeValue("ExcludeGroupTypes").SplitDelimitedValues().Select(a => Guid.Parse(a)).ToList(); if (excludeGroupTypeGuids.Count > 0) { qry = qry.Where(t => !excludeGroupTypeGuids.Contains(t.Guid)); } foreach (int groupTypeId in qry.Select(t => t.Id)) { var groupType = GroupTypeCache.Get(groupTypeId); if (groupType != null && groupType.IsAuthorized(Authorization.VIEW, CurrentPerson)) { groupTypeIds.Add(groupTypeId); } } groupTypeIds = qry.Select(t => t.Id).ToList(); return(groupTypeIds); }
/// <summary> /// Sets the panel title and icon. /// </summary> private void SetPanelTitleAndIcon() { List <int> groupTypeIds = GetAvailableGroupTypes(); // automatically set the panel title and icon based on group type // If there's only one group type, use it's 'group term' in the panel title. if (groupTypeIds.Count == 1) { var singleGroupType = GroupTypeCache.Get(groupTypeIds.FirstOrDefault()); lTitle.Text = string.Format("{0}", singleGroupType.GroupTerm.Pluralize()); iIcon.AddCssClass(singleGroupType.IconCssClass); } else { lTitle.Text = BlockName; iIcon.AddCssClass("fa fa-users"); } // if a SetPanelTitle is specified in block settings, use that instead string customSetPanelTitle = this.GetAttributeValue("SetPanelTitle"); if (!string.IsNullOrEmpty(customSetPanelTitle)) { lTitle.Text = customSetPanelTitle; } // if a SetPanelIcon is specified in block settings, use that instead string customSetPanelIcon = this.GetAttributeValue("SetPanelIcon"); if (!string.IsNullOrEmpty(customSetPanelIcon)) { iIcon.Attributes["class"] = customSetPanelIcon; } }
/// <summary> /// Sets the selection. /// </summary> /// <param name="entityType"></param> /// <param name="controls">The controls.</param> /// <param name="selection">The selection.</param> public override void SetSelection(Type entityType, Control[] controls, string selection) { if (!string.IsNullOrWhiteSpace(selection)) { var values = JsonConvert.DeserializeObject <List <string> >(selection); if (controls.Length > 0 && values.Count > 0) { var groupType = GroupTypeCache.Get(values[0].AsGuid()); if (groupType != null) { var containerControl = controls[0] as DynamicControlsPanel; if (containerControl.Controls.Count > 0) { GroupTypePicker groupTypePicker = containerControl.Controls[0] as GroupTypePicker; groupTypePicker.SelectedGroupTypeId = groupType.Id; EnsureSelectedGroupTypeControls(groupTypePicker); } if (containerControl.Controls.Count > 1 && values.Count > 1) { DropDownList ddlProperty = containerControl.Controls[1] as DropDownList; var entityFields = GetGroupAttributes(groupType.Id); var panelControls = new List <Control>(); panelControls.AddRange(containerControl.Controls.OfType <Control>()); SetEntityFieldSelection(entityFields, ddlProperty, values.Skip(1).ToList(), panelControls); } } } } }
/// <summary> /// Gets the recipient person identifier expression. /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="entityIdProperty">The entity identifier property.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public Expression GetRecipientPersonIdExpression(System.Data.Entity.DbContext dbContext, MemberExpression entityIdProperty, string selection) { var rockContext = dbContext as RockContext; if (rockContext != null) { var qryGroupService = new GroupService(rockContext).Queryable(); Expression <Func <Rock.Model.GroupMember, bool> > memberWhereGroupType = a => 1 == 1; Expression <Func <Rock.Model.GroupMember, bool> > memberWhereGroupRoles = a => 1 == 1; Expression <Func <Rock.Model.GroupMember, bool> > memberWhereStatus = a => 1 == 1; string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 3) { GroupMemberService groupMemberService = new GroupMemberService(rockContext); int?groupTypeId = null; Guid groupTypeGuid = selectionValues[1].AsGuid(); var groupType = GroupTypeCache.Get(groupTypeGuid); if (groupType != null) { groupTypeId = groupType.Id; } if (groupTypeId.HasValue) { memberWhereGroupType = xx => xx.Group.GroupTypeId == groupTypeId; } var groupRoleGuids = selectionValues[2].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => n.AsGuid()).ToList(); List <int> groupRoleIds = null; if (groupRoleGuids.Count() > 0) { groupRoleIds = new GroupTypeRoleService(rockContext).Queryable().Where(a => groupRoleGuids.Contains(a.Guid)).Select(a => a.Id).ToList(); memberWhereGroupRoles = xx => groupRoleIds.Contains(xx.GroupRoleId); } GroupMemberStatus?groupMemberStatus = selectionValues[3].ConvertToEnumOrNull <GroupMemberStatus>(); if (groupMemberStatus.HasValue) { memberWhereStatus = xx => xx.GroupMemberStatus == groupMemberStatus.Value; } } var memberListQuery = qryGroupService.Select(p => p.Members.AsQueryable() .Where(memberWhereGroupType) .Where(memberWhereGroupRoles) .Where(memberWhereStatus) .Select(m => m.PersonId)); var selectChildrenExpression = SelectExpressionExtractor.Extract(memberListQuery, entityIdProperty, "p"); return(selectChildrenExpression); } return(null); }
/// <summary> /// Gets any group type role limit warnings based on GroupTypeRole restrictions /// </summary> /// <param name="warningMessageHtml">The warning message HTML.</param> /// <returns></returns> public bool GetGroupTypeRoleLimitWarnings(out string warningMessageHtml) { var roleLimitWarnings = new StringBuilder(); var group = this; var groupType = GroupTypeCache.Get(group.GroupTypeId); if (groupType?.Roles != null && groupType.Roles.Any()) { var groupMemberService = new GroupMemberService(new RockContext()); foreach (var role in groupType.Roles.Where(a => a.MinCount.HasValue || a.MaxCount.HasValue)) { int curCount = groupMemberService.Queryable().Where(m => m.GroupId == group.Id && m.GroupRoleId == role.Id && m.GroupMemberStatus == GroupMemberStatus.Active).Count(); if (role.MinCount.HasValue && role.MinCount.Value > curCount) { string format = "The <strong>{1}</strong> role is currently below its minimum requirement of {2:N0} active {3}.<br/>"; roleLimitWarnings.AppendFormat(format, role.Name.Pluralize().ToLower(), role.Name.ToLower(), role.MinCount, role.MinCount == 1 ? groupType.GroupMemberTerm.ToLower() : groupType.GroupMemberTerm.Pluralize().ToLower()); } if (role.MaxCount.HasValue && role.MaxCount.Value < curCount) { string format = "The <strong>{1}</strong> role is currently above its maximum limit of {2:N0} active {3}.<br/>"; roleLimitWarnings.AppendFormat(format, role.Name.Pluralize().ToLower(), role.Name.ToLower(), role.MaxCount, role.MaxCount == 1 ? groupType.GroupMemberTerm.ToLower() : groupType.GroupMemberTerm.Pluralize().ToLower()); } } } warningMessageHtml = roleLimitWarnings.ToString(); return(!string.IsNullOrEmpty(warningMessageHtml)); }
/// <summary> /// Gets the number of available spots in the group. /// </summary> /// <param name="group">The group whose capacity needs to be checked.</param> /// <param name="groupRoleId">The group role identifier to check, if <c>null</c> then the default group role is checked.</param> /// <returns>The number of available spots remaining, or <c>null</c> if capacity is not enforced.</returns> private int?GetAvailableSpotsInGroup(Group group, int?groupRoleId) { var groupType = GroupTypeCache.Get(group.GroupTypeId); if (groupType == null || groupType.GroupCapacityRule == GroupCapacityRule.None) { return(null); } int capacity = int.MaxValue; // Check the overall group capacity. if (group.GroupCapacity.HasValue) { var activeCount = group.Members .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active) .Count(); capacity = Math.Max(0, Math.Min(capacity, group.GroupCapacity.Value - activeCount)); } var role = groupType.Roles.FirstOrDefault(r => r.Id == (groupRoleId ?? groupType.DefaultGroupRoleId ?? 0)); if (role != null && role.MaxCount.HasValue) { var activeCount = group.Members .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active && m.GroupRoleId == role.Id) .Count(); capacity = Math.Max(0, Math.Min(capacity, group.GroupCapacity.Value - activeCount)); } return(capacity < int.MaxValue ? capacity : ( int? )null); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="groupId">The group identifier.</param> /// <param name="groupMemberId">The group member identifier.</param> public void ShowDetail(int groupId, int?groupMemberId) { hfGroupId.Value = groupId.ToString(); hfGroupMemberId.Value = groupMemberId.ToString(); pnlMembers.Visible = !groupMemberId.HasValue; int groupTypeId = new GroupService(new RockContext()).GetSelect(groupId, a => a.GroupTypeId); bool showMembersGrid = this.GetAttributeValue("ShowMembersGrid").AsBoolean(); // only show this block if GroupHistory is enabled var groupType = GroupTypeCache.Get(groupTypeId); if (groupType != null && groupType.EnableGroupHistory == false) { this.Visible = false; return; } if (groupMemberId.HasValue) { // if groupMemberId is 0, we are adding a new group member, so don't show group member history (and don't show the member's grid either) if (groupMemberId == 0) { this.Visible = false; return; } ShowGroupMemberHistory(groupMemberId.Value); } else if (showMembersGrid) { BindFilter(); BindMembersGrid(); } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The workflow action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { var checkInState = GetCheckInState(entity, out errorMessages); if (checkInState != null) { var groupService = new GroupService(rockContext); foreach (var family in checkInState.CheckIn.Families.Where(f => f.Selected).ToList()) { foreach (var person in family.People) { var checkinGroupTypes = new List <CheckInGroupType>(); foreach (var id in checkInState.ConfiguredGroupTypes) { var cgt = new CheckInGroupType(); cgt.GroupType = GroupTypeCache.Get(id); checkinGroupTypes.Add(cgt); var groups = groupService.Queryable().Where(g => g.GroupTypeId == id); List <CheckInGroup> checkinGroups = new List <CheckInGroup>(); foreach (var group in groups) { var cg = new CheckInGroup(); cg.Group = group; group.LoadAttributes(); checkinGroups.Add(cg); var groupLocations = group.GroupLocations; List <CheckInLocation> checkinLocations = new List <CheckInLocation>(); foreach (var groupLocation in groupLocations) { var cl = new CheckInLocation(); cl.Location = groupLocation.Location; checkinLocations.Add(cl); var schedules = new List <CheckInSchedule>(); foreach (var schedule in groupLocation.Schedules.ToList()) { if (!schedule.WasCheckInActive(RockDateTime.Now)) { continue; } var cs = new CheckInSchedule(); cs.Schedule = schedule; schedules.Add(cs); } cl.Schedules = schedules; } cg.Locations = checkinLocations; } cgt.Groups = checkinGroups; } person.GroupTypes = checkinGroupTypes; } } return(true); } errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null."); return(false); }
/// <summary> /// Gets the checkin area descendants path. /// </summary> /// <param name="rootCheckinAreaGroupTypeId">The root checkin area group type identifier.</param> /// <returns></returns> public List <CheckinAreaPath> GetCheckinAreaDescendantsPath(int rootCheckinAreaGroupTypeId) { var rootCheckinAreaGroupType = GroupTypeCache.Get(rootCheckinAreaGroupTypeId); List <GroupTypeCache> checkinAreaDescendants = GetCheckinAreaDescendants(rootCheckinAreaGroupTypeId).OrderBy(a => a.Id).ToList(); var checkinAreaDescendantsPath = checkinAreaDescendants.Select(a => new CheckinAreaPath(a, rootCheckinAreaGroupType)).ToList(); return(checkinAreaDescendantsPath); }
/// <summary> /// Utility method to look up a person by phone /// </summary> /// <param name="phoneNumber">The phone number.</param> /// <returns></returns> public static int CdrPersonLookupFromPhone(string phoneNumber) { var rockContext = new RockContext(); var personService = new PersonService(rockContext); var groupMemberService = new GroupMemberService(rockContext); // give preference to people with the phone in the mobile phone type // first look for a person with the phone number as a mobile phone order by family role then age var mobilePhoneType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE); var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY); // Get all people phone number var peopleWithMobileNumber = personService.Queryable() .Where(p => p.PhoneNumbers.Any(n => (n.CountryCode + n.Number) == phoneNumber.Replace("+", "") && n.NumberTypeValueId == mobilePhoneType.Id) ) .Select(p => p.Id); // Find first person ordered by role (adult first), then by birthdate (oldest first) var fromPerson = groupMemberService.Queryable() .Where(m => m.Group.GroupTypeId == familyGroupType.Id && peopleWithMobileNumber.Contains(m.PersonId)) .OrderBy(m => m.GroupRole.Order) .ThenBy(m => m.Person.BirthDate ?? DateTime.MinValue) .Select(m => m.Person) .FirstOrDefault(); // if no match then look for the phone in any phone type ordered by family role then age if (fromPerson == null) { var peopleWithAnyNumber = personService.Queryable() .Where(p => p.PhoneNumbers.Any(n => (n.CountryCode + n.Number) == phoneNumber.Replace("+", "") && n.NumberTypeValueId == mobilePhoneType.Id) ) .Select(p => p.Id); fromPerson = groupMemberService.Queryable() .Where(m => m.Group.GroupTypeId == familyGroupType.Id && peopleWithMobileNumber.Contains(m.PersonId)) .OrderBy(m => m.GroupRole.Order) .ThenBy(m => m.Person.BirthDate ?? DateTime.MinValue) .Select(m => m.Person).FirstOrDefault(); } if (fromPerson != null && fromPerson.PrimaryAliasId.HasValue) { return(fromPerson.PrimaryAliasId.Value); } return(-1); }
/// <summary> /// Processes for family. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="family">The family.</param> /// <param name="preventInactive">if set to <c>true</c> [prevent inactive]. Use CurrentCheckInState.CheckInType.PreventInactivePeople</param> /// <returns></returns> public static bool ProcessForFamily(RockContext rockContext, CheckInFamily family, bool preventInactive) { var dvInactive = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()); var roles = GetRoles(rockContext); var groupMemberService = new GroupMemberService(rockContext); var familyMemberIds = family.People.Select(p => p.Person.Id).ToList(); var knownRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()); if (knownRelationshipGroupType != null) { var ownerRole = knownRelationshipGroupType.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()); if (ownerRole != null) { // Get the Known Relationship group id's for each person in the family var relationshipGroupIds = groupMemberService .Queryable().AsNoTracking() .Where(g => g.GroupRoleId == ownerRole.Id && familyMemberIds.Contains(g.PersonId)) .Select(g => g.GroupId); // Get anyone in any of those groups that has a role with the canCheckIn attribute set var personIds = groupMemberService .Queryable().AsNoTracking() .Where(g => relationshipGroupIds.Contains(g.GroupId) && roles.Contains(g.GroupRoleId)) .Select(g => g.PersonId) .ToList(); if (personIds.Any()) { foreach (var person in new PersonService(rockContext) .Queryable().AsNoTracking() .Where(p => personIds.Contains(p.Id)) .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); }
protected void lbCreateNewRockGroup_Click(object sender, EventArgs e) { var eb = rocks.kfs.Eventbrite.Eventbrite.Api(Settings.GetAccessToken(), Settings.GetOrganizationId().ToLong(0)); var ebEventToCreate = ddlEventbriteEvents.SelectedValue.AsLong(); var EbEvent = eb.GetEventById(ebEventToCreate); var parentGroupGuid = GetAttributeValue("NewGroupParent").AsGuidOrNull(); var groupTypeGuid = GetAttributeValue("NewGroupType").AsGuidOrNull(); Group newGroup = null; if (parentGroupGuid.HasValue && groupTypeGuid.HasValue) { using (var rockContext = new RockContext()) { var groupService = new GroupService(rockContext); var groupType = GroupTypeCache.Get(groupTypeGuid.Value, rockContext); var parentGroup = groupService.Get(parentGroupGuid.Value); if (groupType != null && parentGroup != null && parentGroup.GroupType.ChildGroupTypes.Select(gt => gt.Id).Contains(groupType.Id)) { newGroup = new Group { IsActive = true, CreatedByPersonAliasId = CurrentPersonAlias.Id, CreatedDateTime = RockDateTime.Now, Description = EbEvent.Summary != null ? EbEvent.Summary : "", Name = string.Format("{0} - {1}", EbEvent.Start.Local, EbEvent.Name.Text.ToString()), ParentGroupId = parentGroup.Id, GroupTypeId = groupType.Id }; groupService.Add(newGroup); rockContext.SaveChanges(); } else { nbLinkNew.Text = "There is an error with your New Group Type or New Group Parent configuration. If the settings are set properly, please ensure the New Group Parent group type allows child groups of the New Group Type specified."; nbLinkNew.Visible = true; return; } } } var linked = false; if (newGroup != null) { linked = rocks.kfs.Eventbrite.Eventbrite.LinkEvents(newGroup.Id, EbEvent.Id); } if (linked) { ShowDetail(); loadEvents(); } else { nbLinkNew.Text = "Failed to link new group. You must manually associate group via the group detail page or try again."; nbLinkNew.Visible = true; } }