/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</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 ) { string[] selectionValues = selection.Split( '|' ); if ( selectionValues.Length >= 1 ) { List<Guid> registrationTemplateGuids = selectionValues[0].Split( ',' ).AsGuidList(); var registrationInstanceService = new RegistrationInstanceService( (RockContext)serviceInstance.Context ); var registrationInstanceIds = registrationInstanceService.Queryable().Where( ri => registrationTemplateGuids.Contains( ri.RegistrationTemplate.Guid ) ).Select( ri => ri.Id ).Distinct().ToList(); RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService( (RockContext)serviceInstance.Context ); bool includeInactiveRegistrationInstances = false; if ( selectionValues.Length >= 2 ) { includeInactiveRegistrationInstances = selectionValues[1].AsBooleanOrNull() ?? true; ; } else { // if options where saved before this option was added, set to false, even though it would have included inactive before includeInactiveRegistrationInstances = false; } var registrationRegistrantServiceQry = registrationRegistrantService.Queryable(); if ( registrationTemplateGuids.Count > 0 ) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => registrationInstanceIds.Contains( xx.Registration.RegistrationInstanceId ) ); } if ( selectionValues.Length >= 3 ) { string slidingDelimitedValues = selectionValues[2].Replace( ',', '|' ); DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( slidingDelimitedValues ); if ( dateRange.Start.HasValue ) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => xx.CreatedDateTime >= dateRange.Start.Value ); } if ( dateRange.End.HasValue ) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => xx.CreatedDateTime < dateRange.End.Value ); } } var qry = new PersonService( (RockContext)serviceInstance.Context ).Queryable() .Where( p => registrationRegistrantServiceQry.Any( xx => xx.PersonAlias.PersonId == p.Id ) ); Expression extractedFilterExpression = FilterExpressionExtractor.Extract<Rock.Model.Person>( qry, parameterExpression, "p" ); return extractedFilterExpression; } return null; }
void lbDeleteRegistrant_Click( object sender, EventArgs e ) { var lb = sender as LinkButton; if ( lb != null ) { int? registrantId = lb.ID.Substring( 19 ).AsIntegerOrNull(); if ( registrantId.HasValue ) { var rockContext = new RockContext(); var registrantService = new RegistrationRegistrantService( rockContext ); RegistrationRegistrant registrant = registrantService.Get( registrantId.Value ); if ( registrant != null ) { if ( !registrant.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { mdDeleteWarning.Show( "You are not authorized to delete this registrant.", ModalAlertType.Information ); return; } string errorMessage; if ( !registrantService.CanDelete( registrant, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } registrantService.Delete( registrant ); rockContext.SaveChanges(); } // Reload registration ShowReadonlyDetails( GetRegistration( RegistrationId ) ); } } }
/// <summary> /// Handles the RowSelected event of the gRegistrants control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gRegistrants_RowSelected( object sender, RowEventArgs e ) { using ( var rockContext = new RockContext() ) { var registrantService = new RegistrationRegistrantService( rockContext ); var registrant = registrantService.Get( e.RowKeyId ); if ( registrant != null ) { var qryParams = new Dictionary<string, string>(); qryParams.Add( "RegistrationId", registrant.RegistrationId.ToString() ); string url = LinkedPageUrl( "RegistrationPage", qryParams ); url += "#" + e.RowKeyValue; Response.Redirect( url, false ); } } }
private string GetContent() { Guid eventItemOccurrenceGuid = Guid.Empty; RockContext rockContext = new RockContext(); // get the calendarItem id if (!string.IsNullOrWhiteSpace(RequestContext.GetPageParameter("EventOccurrenceGuid"))) { eventItemOccurrenceGuid = RequestContext.GetPageParameter("EventOccurrenceGuid").AsGuid(); } var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext); var qry = eventItemOccurrenceService .Queryable("EventItem, EventItem.Photo, Campus, Linkages") .Where(i => i.Guid == eventItemOccurrenceGuid); var eventItemOccurrence = qry.FirstOrDefault(); if (eventItemOccurrence == null) { return("<Rock:NotificationBox NotificationType=\"Warning\" Text=\"We could not find that event.\" />"); } var mergeFields = new Dictionary <string, object> { { "RegistrationUrl", RegistrationUrl }, { "EventItemOccurrence", eventItemOccurrence }, { "Event", eventItemOccurrence?.EventItem }, { "CurrentPerson", RequestContext.CurrentPerson } }; //var campusEntityType = EntityTypeCache.Get( "Rock.Model.Campus" ); var contextCampus = RequestContext.GetContextEntity <Campus>(); if (contextCampus != null) { mergeFields.Add("CampusContext", contextCampus); } // determine registration status (Register, Full, or Join Wait List) for each unique registration instance Dictionary <int, string> registrationStatusLabels = new Dictionary <int, string>(); foreach (var registrationInstance in eventItemOccurrence.Linkages.Select(a => a.RegistrationInstance).Distinct().ToList()) { int?maxRegistrantCount = null; var currentRegistrationCount = 0; if (registrationInstance != null) { maxRegistrantCount = registrationInstance.MaxAttendees; } int?registrationSpotsAvailable = null; if (maxRegistrantCount.HasValue) { currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable() .AsNoTracking() .Where(r => r.Registration.RegistrationInstanceId == registrationInstance.Id && r.OnWaitList == false) .Count(); registrationSpotsAvailable = maxRegistrantCount - currentRegistrationCount; } string registrationStatusLabel = "Register"; if (registrationSpotsAvailable.HasValue && registrationSpotsAvailable.Value < 1) { if (registrationInstance.RegistrationTemplate.WaitListEnabled) { registrationStatusLabel = "Join Wait List"; } else { registrationStatusLabel = "Full"; } } registrationStatusLabels.Add(registrationInstance.Id, registrationStatusLabel); } // Status of first registration instance mergeFields.Add("RegistrationStatusLabel", registrationStatusLabels.Values.FirstOrDefault()); // Status of each registration instance mergeFields.Add("RegistrationStatusLabels", registrationStatusLabels); return(Template.ResolveMergeFields(mergeFields)); }
/// <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 ); } 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 ( !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> /// Binds the registrants grid. /// </summary> private void BindRegistrantsGrid() { int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { // Start query for registrants var qry = new RegistrationRegistrantService( rockContext ) .Queryable( "PersonAlias.Person.PhoneNumbers.NumberTypeValue,Fees.RegistrationTemplateFee,GroupMember.Group" ).AsNoTracking() .Where( r => r.Registration.RegistrationInstanceId == instanceId.Value && r.PersonAlias != null && r.PersonAlias.Person != null ); // Filter by daterange if ( drpRegistrantDateRange.LowerValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value >= drpRegistrantDateRange.LowerValue.Value ); } if ( drpRegistrantDateRange.UpperValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value <= drpRegistrantDateRange.UpperValue.Value ); } // Filter by first name if ( !string.IsNullOrWhiteSpace( tbRegistrantFirstName.Text ) ) { string rfname = tbRegistrantFirstName.Text; qry = qry.Where( r => r.PersonAlias.Person.NickName.StartsWith( rfname ) || r.PersonAlias.Person.FirstName.StartsWith( rfname ) ); } // Filter by last name if ( !string.IsNullOrWhiteSpace( tbRegistrantLastName.Text ) ) { string rlname = tbRegistrantLastName.Text; qry = qry.Where( r => r.PersonAlias.Person.LastName.StartsWith( rlname ) ); } bool preloadCampusValues = false; var registrantAttributes = new List<AttributeCache>(); var personAttributes = new List<AttributeCache>(); var groupMemberAttributes = new List<AttributeCache>(); var registrantAttributeIds = new List<int>(); var personAttributesIds = new List<int>(); var groupMemberAttributesIds = new List<int>(); if ( RegistrantFields != null ) { // Filter by any selected foreach ( var personFieldType in RegistrantFields .Where( f => f.FieldSource == RegistrationFieldSource.PersonField && f.PersonFieldType.HasValue ) .Select( f => f.PersonFieldType.Value ) ) { switch ( personFieldType ) { case RegistrationPersonFieldType.Campus: { preloadCampusValues = true; var ddlCampus = phRegistrantFormFieldFilters.FindControl( "ddlCampus" ) as RockDropDownList; if ( ddlCampus != null ) { var campusId = ddlCampus.SelectedValue.AsIntegerOrNull(); if ( campusId.HasValue ) { var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); qry = qry.Where( r => r.PersonAlias.Person.Members.Any( m => m.Group.GroupType.Guid == familyGroupTypeGuid && m.Group.CampusId.HasValue && m.Group.CampusId.Value == campusId ) ); } } break; } case RegistrationPersonFieldType.Email: { var tbEmailFilter = phRegistrantFormFieldFilters.FindControl( "tbEmailFilter" ) as RockTextBox; if ( tbEmailFilter != null && !string.IsNullOrWhiteSpace( tbEmailFilter.Text ) ) { qry = qry.Where( r => r.PersonAlias.Person.Email != null && r.PersonAlias.Person.Email.Contains( tbEmailFilter.Text ) ); } break; } case RegistrationPersonFieldType.Birthdate: { var drpBirthdateFilter = phRegistrantFormFieldFilters.FindControl( "drpBirthdateFilter" ) as DateRangePicker; if ( drpBirthdateFilter != null ) { if ( drpBirthdateFilter.LowerValue.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.BirthDate.HasValue && r.PersonAlias.Person.BirthDate.Value >= drpBirthdateFilter.LowerValue.Value ); } if ( drpBirthdateFilter.UpperValue.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.BirthDate.HasValue && r.PersonAlias.Person.BirthDate.Value <= drpBirthdateFilter.UpperValue.Value ); } } break; } case RegistrationPersonFieldType.Gender: { var ddlGenderFilter = phRegistrantFormFieldFilters.FindControl( "ddlGenderFilter" ) as RockDropDownList; if ( ddlGenderFilter != null ) { var gender = ddlGenderFilter.SelectedValue.ConvertToEnumOrNull<Gender>(); if ( gender.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.Gender == gender ); } } break; } case RegistrationPersonFieldType.MaritalStatus: { var ddlMaritalStatusFilter = phRegistrantFormFieldFilters.FindControl( "ddlMaritalStatusFilter" ) as RockDropDownList; if ( ddlMaritalStatusFilter != null ) { var maritalStatusId = ddlMaritalStatusFilter.SelectedValue.AsIntegerOrNull(); if ( maritalStatusId.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.MaritalStatusValueId.HasValue && r.PersonAlias.Person.MaritalStatusValueId.Value == maritalStatusId.Value ); } } break; } case RegistrationPersonFieldType.MobilePhone: { var tbPhoneFilter = phRegistrantFormFieldFilters.FindControl( "tbPhoneFilter" ) as RockTextBox; if ( tbPhoneFilter != null && !string.IsNullOrWhiteSpace( tbPhoneFilter.Text ) ) { string numericPhone = tbPhoneFilter.Text.AsNumeric(); qry = qry.Where( r => r.PersonAlias.Person.PhoneNumbers != null && r.PersonAlias.Person.PhoneNumbers.Any( n => n.Number.Contains( numericPhone ) ) ); } break; } } } // Get all the registrant attributes selected to be on grid registrantAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.RegistrationAttribute ) .Select( f => f.Attribute ) .ToList(); registrantAttributeIds = registrantAttributes.Select( a => a.Id ).Distinct().ToList(); // Filter query by any configured registrant attribute filters if ( registrantAttributes != null && registrantAttributes.Any() ) { var attributeValueService = new AttributeValueService( rockContext ); var parameterExpression = attributeValueService.ParameterExpression; foreach ( var attribute in registrantAttributes ) { var filterControl = phRegistrantFormFieldFilters.FindControl( "filter_" + attribute.Id.ToString() ); if ( filterControl != null ) { var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter ); var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression ); if ( expression != null ) { var attributeValues = attributeValueService .Queryable() .Where( v => v.Attribute.Id == attribute.Id ); attributeValues = attributeValues.Where( parameterExpression, expression, null ); qry = qry .Where( r => attributeValues.Select( v => v.EntityId ).Contains( r.Id ) ); } } } } // Get all the person attributes selected to be on grid personAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.PersonAttribute ) .Select( f => f.Attribute ) .ToList(); personAttributesIds = personAttributes.Select( a => a.Id ).Distinct().ToList(); // Filter query by any configured person attribute filters if ( personAttributes != null && personAttributes.Any() ) { var attributeValueService = new AttributeValueService( rockContext ); var parameterExpression = attributeValueService.ParameterExpression; foreach ( var attribute in personAttributes ) { var filterControl = phRegistrantFormFieldFilters.FindControl( "filter_" + attribute.Id.ToString() ); if ( filterControl != null ) { var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter ); var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression ); if ( expression != null ) { var attributeValues = attributeValueService .Queryable() .Where( v => v.Attribute.Id == attribute.Id ); attributeValues = attributeValues.Where( parameterExpression, expression, null ); qry = qry .Where( r => attributeValues.Select( v => v.EntityId ).Contains( r.PersonAlias.PersonId ) ); } } } } // Get all the group member attributes selected to be on grid groupMemberAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.GroupMemberAttribute ) .Select( f => f.Attribute ) .ToList(); groupMemberAttributesIds = groupMemberAttributes.Select( a => a.Id ).Distinct().ToList(); // Filter query by any configured person attribute filters if ( groupMemberAttributes != null && groupMemberAttributes.Any() ) { var attributeValueService = new AttributeValueService( rockContext ); var parameterExpression = attributeValueService.ParameterExpression; foreach ( var attribute in groupMemberAttributes ) { var filterControl = phRegistrantFormFieldFilters.FindControl( "filter_" + attribute.Id.ToString() ); if ( filterControl != null ) { var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter ); var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression ); if ( expression != null ) { var attributeValues = attributeValueService .Queryable() .Where( v => v.Attribute.Id == attribute.Id ); attributeValues = attributeValues.Where( parameterExpression, expression, null ); qry = qry .Where( r => r.GroupMemberId.HasValue && attributeValues.Select( v => v.EntityId ).Contains( r.GroupMemberId.Value ) ); } } } } } // Sort the query IOrderedQueryable<RegistrationRegistrant> orderedQry = null; SortProperty sortProperty = gRegistrants.SortProperty; if ( sortProperty != null ) { orderedQry = qry.Sort( sortProperty ); } else { orderedQry = qry .OrderBy( r => r.PersonAlias.Person.LastName ) .ThenBy( r => r.PersonAlias.Person.NickName ); } // Set the grids LinqDataSource which will run query and set results for current page gRegistrants.SetLinqDataSource<RegistrationRegistrant>( orderedQry ); if ( RegistrantFields != null ) { // Get the query results for the current page var currentPageRegistrants = gRegistrants.DataSource as List<RegistrationRegistrant>; if ( currentPageRegistrants != null ) { // Get all the registrant ids in current page of query results var registrantIds = currentPageRegistrants .Select( r => r.Id ) .Distinct() .ToList(); // Get all the person ids in current page of query results var personIds = currentPageRegistrants .Select( r => r.PersonAlias.PersonId ) .Distinct() .ToList(); // Get all the group member ids and the group id in current page of query results var groupMemberIds = new List<int>(); GroupLinks = new Dictionary<int,string>(); foreach( var groupMember in currentPageRegistrants .Where( m => m.GroupMember != null && m.GroupMember.Group != null ) .Select( m => m.GroupMember ) ) { groupMemberIds.Add( groupMember.Id ); GroupLinks.AddOrIgnore( groupMember.GroupId, string.Format( "<a href='{0}'>{1}</a>", LinkedPageUrl( "GroupDetailPage", new Dictionary<string, string> { { "GroupId", groupMember.GroupId.ToString() } } ), groupMember.Group.Name ) ); } // If the campus column was selected to be displayed on grid, preload all the people's // campuses so that the databind does not need to query each row if ( preloadCampusValues ) { PersonCampusIds = new Dictionary<int, List<int>>(); Guid familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); foreach ( var personCampusList in new GroupMemberService( rockContext ) .Queryable().AsNoTracking() .Where( m => m.Group.GroupType.Guid == familyGroupTypeGuid && personIds.Contains( m.PersonId ) ) .GroupBy( m => m.PersonId ) .Select( m => new { PersonId = m.Key, CampusIds = m .Where( g => g.Group.CampusId.HasValue ) .Select( g => g.Group.CampusId.Value ) .ToList() } ) ) { PersonCampusIds.Add( personCampusList.PersonId, personCampusList.CampusIds ); } } // If there are any attributes that were selected to be displayed, we're going // to try and read all attribute values in one query and then put them into a // custom grid ObjectList property so that the AttributeField columns don't need // to do the LoadAttributes and querying of values for each row/column if ( personAttributesIds.Any() || groupMemberAttributesIds.Any() || registrantAttributeIds.Any() ) { // Query the attribute values for all rows and attributes var attributeValues = new AttributeValueService( rockContext ) .Queryable( "Attribute" ).AsNoTracking() .Where( v => v.EntityId.HasValue && ( ( personAttributesIds.Contains( v.AttributeId ) && personIds.Contains( v.EntityId.Value ) ) || ( groupMemberAttributesIds.Contains( v.AttributeId ) && groupMemberIds.Contains( v.EntityId.Value ) ) || ( registrantAttributeIds.Contains( v.AttributeId ) && registrantIds.Contains( v.EntityId.Value ) ) ) ) .ToList(); // Get the attributes to add to each row's object var attributes = new Dictionary<string, AttributeCache>(); RegistrantFields .Where( f => f.Attribute != null ) .Select( f => f.Attribute ) .ToList() .ForEach( a => attributes .Add( a.Id.ToString() + a.Key, a ) ); // Initialize the grid's object list gRegistrants.ObjectList = new Dictionary<string, object>(); // Loop through each of the current page's registrants and build an attribute // field object for storing attributes and the values for each of the registrants foreach ( var registrant in currentPageRegistrants ) { // Create a row attribute object var attributeFieldObject = new AttributeFieldObject(); // Add the attributes to the attribute object attributeFieldObject.Attributes = attributes; // Add any person attribute values to object attributeValues .Where( v => personAttributesIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.PersonAlias.PersonId ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, v ) ); // Add any group member attribute values to object if ( registrant.GroupMemberId.HasValue ) { attributeValues .Where( v => groupMemberAttributesIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.GroupMemberId.Value ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, v ) ); } // Add any registrant attribute values to object attributeValues .Where( v => registrantAttributeIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.PersonAlias.PersonId ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, v ) ); // Add row attribute object to grid's object list gRegistrants.ObjectList.Add( registrant.Id.ToString(), attributeFieldObject ); } } } } gRegistrants.DataBind(); } } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</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 ) { string[] selectionValues = selection.Split( '|' ); if ( selectionValues.Length >= 3 ) { int? registrationTemplateId = selectionValues[0].AsIntegerOrNull(); Guid? registrationInstanceGuid = selectionValues[1].AsGuidOrNull(); var registrationType = selectionValues[2]; var rockContext = (RockContext) serviceInstance.Context; IQueryable<RegistrationRegistrant> registrantQuery; IQueryable<Registration> registrationQuery; IQueryable<Rock.Model.Person> qry; if ( registrationTemplateId == null ) { // no registration template id selected, so return nothing return Expression.Constant( false ); } // Registrant if ( registrationType == null || registrationType == "2" ) { registrantQuery = new RegistrationRegistrantService( rockContext ).Queryable() .Where( r => r.Registration.RegistrationInstance.RegistrationTemplateId == registrationTemplateId ); if ( registrationInstanceGuid != null ) { registrantQuery = registrantQuery.Where( r => r.Registration.RegistrationInstance.Guid == registrationInstanceGuid ); } qry = new PersonService( rockContext ).Queryable() .Where( p => registrantQuery.Where( xx => xx.PersonAlias.PersonId == p.Id ).Count() == 1 ); } // Registrar else { registrationQuery = new RegistrationService( rockContext ).Queryable() .Where( r => r.RegistrationInstance.RegistrationTemplateId == registrationTemplateId ); if ( registrationInstanceGuid != null ) { registrationQuery = registrationQuery.Where( r => r.RegistrationInstance.Guid == registrationInstanceGuid ); } qry = new PersonService( rockContext ).Queryable() .Where( p => registrationQuery.Where( xx => xx.PersonAlias.PersonId == p.Id ).Count() == 1 ); } Expression result = FilterExpressionExtractor.Extract<Rock.Model.Person>( qry, parameterExpression, "p" ); return result; } return null; }
/// <summary> /// Handles the Click event of the lbPlaceInGroup 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 lbPlaceInGroup_Click( object sender, EventArgs e ) { var col = gGroupPlacements.Columns.OfType<GroupPickerField>().FirstOrDefault(); if ( col != null ) { var placements = new Dictionary<int, List<int>>(); var colIndex = gGroupPlacements.Columns.IndexOf( col ).ToString(); foreach ( GridViewRow row in gGroupPlacements.Rows ) { GroupPicker gp = row.FindControl( "groupPicker_" + colIndex.ToString() ) as GroupPicker; if ( gp != null ) { int? groupId = gp.SelectedValueAsInt(); if ( groupId.HasValue ) { int registrantId = (int)gGroupPlacements.DataKeys[row.RowIndex].Value; placements.AddOrIgnore( groupId.Value, new List<int>() ); placements[groupId.Value].Add( registrantId ); } } } using ( var rockContext = new RockContext() ) { var groupMemberService = new GroupMemberService( rockContext ); // Get all the registrants that were selected var registrantIds = placements.SelectMany( p => p.Value ).ToList(); var registrants = new RegistrationRegistrantService( rockContext ) .Queryable( "PersonAlias" ).AsNoTracking() .Where( r => registrantIds.Contains( r.Id ) ) .ToList(); // Get any groups that were selected var groupIds = placements.Keys.ToList(); foreach ( var group in new GroupService( rockContext ) .Queryable( "GroupType" ).AsNoTracking() .Where( g => groupIds.Contains( g.Id ) ) ) { foreach ( int registrantId in placements[group.Id] ) { int? roleId = group.GroupType.DefaultGroupRoleId; if ( !roleId.HasValue ) { roleId = group.GroupType.Roles .OrderBy( r => r.Order ) .Select( r => r.Id ) .FirstOrDefault(); } var registrant = registrants.FirstOrDefault( r => r.Id == registrantId ); if ( registrant != null && roleId.HasValue && roleId.Value > 0 ) { var groupMember = new GroupMember(); groupMember.PersonId = registrant.PersonAlias.PersonId; groupMember.GroupId = group.Id; groupMember.GroupRoleId = roleId.Value; groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMemberService.Add( groupMember ); } } } rockContext.SaveChanges(); } } BindGroupPlacementGrid(); }
private void lbResendDocumentRequest_Click( object sender, EventArgs e ) { var lb = sender as LinkButton; if ( lb != null ) { int? registrantId = lb.ID.Substring( 24 ).AsIntegerOrNull(); if ( registrantId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrant = new RegistrationRegistrantService( rockContext ).Get( registrantId.Value ); if ( registrant != null && registrant.PersonAlias != null && registrant.PersonAlias.Person != null && Registration != null && Registration.RegistrationInstance != null && Registration.RegistrationInstance.RegistrationTemplate != null ) { var assignedTo = registrant.PersonAlias.Person; string email = Registration.ConfirmationEmail; if ( string.IsNullOrWhiteSpace( email ) && Registration.PersonAlias != null && Registration.PersonAlias.Person != null ) { email = Registration.PersonAlias.Person.Email; } Guid? adultRole = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid(); var registrantIsAdult = adultRole.HasValue && new GroupMemberService( rockContext ) .Queryable().AsNoTracking() .Any( m => m.PersonId == registrant.PersonId && m.GroupRole.Guid.Equals( adultRole.Value ) ); if ( !registrantIsAdult && Registration.PersonAlias != null && Registration.PersonAlias.Person != null ) { assignedTo = Registration.PersonAlias.Person; } else { if ( !string.IsNullOrWhiteSpace( registrant.PersonAlias.Person.Email ) ) { email = registrant.PersonAlias.Person.Email; } } var sendErrorMessages = new List<string>(); if ( new SignatureDocumentTemplateService( rockContext ).SendDocument( Registration.RegistrationInstance.RegistrationTemplate.RequiredSignatureDocumentTemplate, registrant.PersonAlias.Person, assignedTo, Registration.RegistrationInstance.Name, email, out sendErrorMessages ) ) { rockContext.SaveChanges(); maSignatureRequestSent.Show( "A Signature Request Has Been Sent.", Rock.Web.UI.Controls.ModalAlertType.Information ); } else { string errorMessage = string.Format( "Unable to send a signature request: <ul><li>{0}</li></ul>", sendErrorMessages.AsDelimited( "</li><li>" ) ); maSignatureRequestSent.Show( errorMessage, Rock.Web.UI.Controls.ModalAlertType.Alert ); } } } } } ShowReadonlyDetails( GetRegistration( RegistrationId ) ); }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindGroupMembersGrid( bool isExporting = false ) { 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(); if ( _group != null && _group.RequiredSignatureDocumentTemplateId.HasValue ) { Signers = new SignatureDocumentService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.SignatureDocumentTemplateId == _group.RequiredSignatureDocumentTemplateId.Value && d.Status == SignatureDocumentStatus.Signed && d.BinaryFileId.HasValue && d.AppliesToPersonAlias != null ) .OrderByDescending( d => d.LastStatusDate ) .Select( d => d.AppliesToPersonAlias.PersonId ) .ToList(); } GroupMemberService groupMemberService = new GroupMemberService( rockContext ); var qry = groupMemberService.Queryable( "Person,GroupRole", true ).AsNoTracking() .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 ) || m.Person.NickName.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 ( var roleId in cblRole.SelectedValues.AsIntegerList() ) { if ( validGroupTypeRoles.Contains( roleId ) ) { roles.Add( roleId ); } } if ( roles.Any() ) { qry = qry.Where( m => roles.Contains( m.GroupRoleId ) ); } // Filter by Group Member Status var statuses = new List<GroupMemberStatus>(); foreach ( string status in cblGroupMemberStatus.SelectedValues ) { if ( !string.IsNullOrWhiteSpace( status ) ) { statuses.Add( status.ConvertToEnum<GroupMemberStatus>() ); } } if ( statuses.Any() ) { qry = qry.Where( m => statuses.Contains( m.GroupMemberStatus ) ); } var genders = new List<Gender>(); foreach ( var item in cblGenderFilter.SelectedValues ) { var gender = item.ConvertToEnum<Gender>(); genders.Add( gender ); } if ( genders.Any() ) { qry = qry.Where( m => genders.Contains( m.Person.Gender ) ); } // Filter by Campus if ( cpCampusFilter.SelectedCampusId.HasValue ) { Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ); int campusId = cpCampusFilter.SelectedCampusId.Value; var qryFamilyMembersForCampus = new GroupMemberService( rockContext ).Queryable().Where( a => a.Group.GroupType.Guid == familyGuid && a.Group.CampusId == campusId ); qry = qry.Where( a => qryFamilyMembersForCampus.Any( f => f.PersonId == a.PersonId ) ); } // Filter by Registration var instanceId = ddlRegistration.SelectedValueAsInt(); if ( instanceId.HasValue ) { var registrants = new RegistrationRegistrantService( rockContext ) .Queryable().AsNoTracking() .Where( r => r.Registration != null && r.Registration.RegistrationInstanceId == instanceId.Value && r.PersonAlias != null ) .Select( r => r.PersonAlias.PersonId ); qry = qry.Where( m => registrants.Contains( m.PersonId ) ); } // Filter by signed documents if ( Signers != null ) { if ( ddlSignedDocument.SelectedValue.AsBooleanOrNull() == true ) { qry = qry.Where( m => Signers.Contains( m.PersonId ) ); } else if ( ddlSignedDocument.SelectedValue.AsBooleanOrNull() == false ) { qry = qry.Where( m => !Signers.Contains( m.PersonId ) ); } } // Filter query by any configured attribute filters if ( AvailableAttributes != null && AvailableAttributes.Any() ) { var attributeValueService = new AttributeValueService( rockContext ); var parameterExpression = attributeValueService.ParameterExpression; 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, Rock.Reporting.FilterMode.SimpleFilter ); var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression ); if ( expression != null ) { var attributeValues = attributeValueService .Queryable() .Where( v => v.Attribute.Id == attribute.Id ); attributeValues = attributeValues.Where( parameterExpression, expression, null ); qry = qry.Where( w => attributeValues.Select( v => v.EntityId ).Contains( w.Id ) ); } } } } _inactiveStatus = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ); SortProperty sortProperty = gGroupMembers.SortProperty; bool hasGroupRequirements = new GroupRequirementService( rockContext ).Queryable().Where( a => a.GroupId == _group.Id ).Any(); // If there are group requirements that that member doesn't meet, show an icon in the grid bool includeWarnings = false; var groupMemberIdsThatLackGroupRequirements = new GroupService( rockContext ).GroupMembersNotMeetingRequirements( _group.Id, includeWarnings ).Select( a => a.Key.Id ); List<GroupMember> groupMembersList = null; if ( sortProperty != null && sortProperty.Property != "FirstAttended" && sortProperty.Property != "LastAttended" ) { groupMembersList = qry.Sort( sortProperty ).ToList(); } else { groupMembersList = qry.OrderBy( a => a.GroupRole.Order ).ThenBy( a => a.Person.LastName ).ThenBy( a => a.Person.FirstName ).ToList(); } // If there is a required signed document that member has not signed, show an icon in the grid var personIdsThatHaventSigned = new List<int>(); if ( Signers != null ) { var memberPersonIds = groupMembersList.Select( m => m.PersonId ).ToList(); personIdsThatHaventSigned = memberPersonIds.Where( i => !Signers.Contains( i ) ).ToList(); } // Since we're not binding to actual group member list, but are using AttributeField columns, // we need to save the group members into the grid's object list gGroupMembers.ObjectList = new Dictionary<string, object>(); groupMembersList.ForEach( m => gGroupMembers.ObjectList.Add( m.Id.ToString(), m ) ); gGroupMembers.EntityTypeId = EntityTypeCache.Read( Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid() ).Id; var homePhoneType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME ); var cellPhoneType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ); // If exporting to Excel, the selectAll option will be true, and home location should be calculated var homeLocations = new Dictionary<int, Location>(); if ( isExporting ) { foreach ( var m in groupMembersList ) { homeLocations.Add( m.Id, m.Person.GetHomeLocation( rockContext ) ); } } var groupMemberIds = groupMembersList.Select( m => m.Id ).ToList(); // Get all the group members with any associated registrations _groupMembersWithRegistrations = new RegistrationRegistrantService( rockContext ) .Queryable().AsNoTracking() .Where( r => r.Registration != null && r.Registration.RegistrationInstance != null && r.GroupMemberId.HasValue && groupMemberIds.Contains( r.GroupMemberId.Value ) ) .ToList() .GroupBy( r => r.GroupMemberId.Value ) .Select( g => new { GroupMemberId = g.Key, Registrations = g.ToList() .Select( r => new { Id = r.Registration.Id, Name = r.Registration.RegistrationInstance.Name } ).Distinct() .ToDictionary( r => r.Id, r => r.Name ) } ) .ToDictionary( r => r.GroupMemberId, r => r.Registrations ); var registrationField = gGroupMembers.ColumnsOfType<RockTemplateFieldUnselected>().FirstOrDefault(); if ( registrationField != null ) { registrationField.Visible = _groupMembersWithRegistrations.Any(); } var connectionStatusField = gGroupMembers.ColumnsOfType<DefinedValueField>().FirstOrDefault( a => a.DataField == "ConnectionStatusValueId" ); if ( connectionStatusField != null ) { connectionStatusField.Visible = _group.GroupType.ShowConnectionStatus; } string photoFormat = "<div class=\"photo-icon photo-round photo-round-xs pull-left margin-r-sm js-person-popover\" personid=\"{0}\" data-original=\"{1}&w=50\" style=\"background-image: url( '{2}' ); background-size: cover; background-repeat: no-repeat;\"></div>"; var attendanceFirstLast = new Dictionary<int, DateRange>(); bool showAttendance = GetAttributeValue( "ShowAttendance" ).AsBoolean() && _group.GroupType.TakesAttendance; gGroupMembers.ColumnsOfType<DateField>().First( a => a.DataField == "FirstAttended" ).Visible = showAttendance; gGroupMembers.ColumnsOfType<DateField>().First( a => a.DataField == "LastAttended" ).Visible = showAttendance; if ( showAttendance ) { foreach ( var attendance in new AttendanceService( rockContext ) .Queryable().AsNoTracking() .Where( a => a.GroupId.HasValue && a.GroupId.Value == _group.Id && a.DidAttend.HasValue && a.DidAttend.Value ) .GroupBy( a => a.PersonAlias.PersonId ) .Select( g => new { PersonId = g.Key, FirstAttended = g.Min( a => a.StartDateTime ), LastAttended = g.Max( a => a.StartDateTime ) } ) .ToList() ) { attendanceFirstLast.Add( attendance.PersonId, new DateRange( attendance.FirstAttended, attendance.LastAttended ) ); } } bool showDateAdded = GetAttributeValue( "ShowDateAdded" ).AsBoolean(); gGroupMembers.ColumnsOfType<DateField>().First( a => a.DataField == "DateTimeAdded" ).Visible = showDateAdded; var dataSource = groupMembersList.Select( m => new { m.Id, m.Guid, m.PersonId, m.Person.NickName, m.Person.LastName, Name = ( isExporting ? m.Person.LastName + ", " + m.Person.NickName : string.Format( photoFormat, m.PersonId, m.Person.PhotoUrl, ResolveUrl( "~/Assets/Images/person-no-photo-male.svg" ) ) + m.Person.NickName + " " + m.Person.LastName + ( ( hasGroupRequirements && groupMemberIdsThatLackGroupRequirements.Contains( m.Id ) ) ? " <i class='fa fa-exclamation-triangle text-warning'></i>" : string.Empty ) + ( !string.IsNullOrEmpty( m.Note ) ? " <i class='fa fa-file-text-o text-info'></i>" : string.Empty ) + ((personIdsThatHaventSigned.Contains( m.PersonId )) ? " <i class='fa fa-pencil-square-o text-danger'></i>" : string.Empty)), m.Person.BirthDate, m.Person.Age, m.Person.ConnectionStatusValueId, m.DateTimeAdded, FirstAttended = attendanceFirstLast.Where( a => a.Key == m.PersonId ).Select( a => a.Value.Start ).FirstOrDefault(), LastAttended = attendanceFirstLast.Where( a => a.Key == m.PersonId ).Select( a => a.Value.End ).FirstOrDefault(), Email = m.Person.Email, HomePhone = isExporting && homePhoneType != null ? m.Person.PhoneNumbers .Where( p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == homePhoneType.Id ) .Select( p => p.NumberFormatted ) .FirstOrDefault() : string.Empty, CellPhone = isExporting && cellPhoneType != null ? m.Person.PhoneNumbers .Where( p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == cellPhoneType.Id ) .Select( p => p.NumberFormatted ) .FirstOrDefault() : string.Empty, HomeAddress = homeLocations.ContainsKey( m.Id ) && homeLocations[m.Id] != null ? homeLocations[m.Id].FormattedAddress : string.Empty, Latitude = homeLocations.ContainsKey( m.Id ) && homeLocations[m.Id] != null ? homeLocations[m.Id].Latitude : (double?)null, Longitude = homeLocations.ContainsKey( m.Id ) && homeLocations[m.Id] != null ? homeLocations[m.Id].Longitude : (double?)null, GroupRole = m.GroupRole.Name, m.GroupMemberStatus, RecordStatusValueId = m.Person.RecordStatusValueId, IsDeceased = m.Person.IsDeceased } ).ToList(); if ( sortProperty != null ) { if ( sortProperty.Property == "FirstAttended" ) { if ( sortProperty.Direction == SortDirection.Descending ) { dataSource = dataSource.OrderByDescending( a => a.FirstAttended ?? DateTime.MinValue ).ToList(); } else { dataSource = dataSource.OrderBy( a => a.FirstAttended ?? DateTime.MinValue ).ToList(); } } if ( sortProperty.Property == "LastAttended" ) { if ( sortProperty.Direction == SortDirection.Descending ) { dataSource = dataSource.OrderByDescending( a => a.LastAttended ?? DateTime.MinValue ).ToList(); } else { dataSource = dataSource.OrderBy( a => a.LastAttended ?? DateTime.MinValue ).ToList(); } } } gGroupMembers.DataSource = dataSource; 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> /// 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 registrantService = new RegistrationRegistrantService( rockContext ); var registrantFeeService = new RegistrationRegistrantFeeService( rockContext ); RegistrationRegistrant registrant = null; if ( RegistrantState.Id > 0 ) { registrant = registrantService.Get( RegistrantState.Id ); } if ( registrant == null ) { registrant = new RegistrationRegistrant(); registrant.RegistrationId = RegistrantState.RegistrationId; registrantService.Add( registrant ); } registrant.PersonAliasId = ppPerson.PersonAliasId.Value; 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 ) ) { 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 ); } dbFee.Quantity = uiFeeOption.Quantity; dbFee.Cost = uiFeeOption.Cost; } } 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 ) ) ) { // Find the registrant's value var fieldValue = RegistrantState.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() ); } } registrant.SaveAttributeValues( rockContext ); } } ); NavigateToRegistration(); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var 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(); var group = new GroupService(rockContext).Get(bbGroup); if (group.Name.Contains("Week 2")) { cmpCampus.Visible = true; } Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").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 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 .GroupJoin(registrationRegistrantService.Queryable(), obj => obj.Id, rr => rr.GroupMemberId, (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr }) .GroupJoin(attributeValueService.Queryable(), obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 }, av => new { PersonId = av.EntityId, av.AttributeId }, (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() }) .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)), School = obj.School /*, Location = obj.Location */ }) .GroupJoin(attributeValueService.Queryable(), obj => obj.RegistrationRegistrant.FirstOrDefault().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)), School = obj.School /*, 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.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal && q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable(); } else if (lowerVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal).AsQueryable(); } else if (upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable(); } else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue)) { if (group.Name.Contains("Week 2")) { qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampusdoyouwanttodepartforcampfromandroomwith" && ra.Value == cmpCampus.SelectedValue).Any()).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.Select(rr => rr.Registration.PersonAlias.Person).FirstOrDefault()), Registrant = new ModelValue <Person>(g.Person), Age = g.Person.Age, GraduationYear = g.Person.GraduationYear, RegistrationId = g.RegistrationRegistrant.Select(rr => rr.RegistrationId).FirstOrDefault(), 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 <Rock.Model.Location>((Rock.Model.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.FirstOrDefault(), g.RegistrationAttributeValues); return(row); })(), School = string.IsNullOrEmpty(g.School)?"":DefinedValueCache.Read(g.School.AsGuid()) != null?DefinedValueCache.Read(g.School.AsGuid()).Value:"", 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 + " (" + sd.SignatureDocument.Status.ToString() + ")").FirstOrDefault(), Departure = g.GroupMemberAttributeValues.Where(av => av.AttributeKey == "Departure").Select(av => av.Value).FirstOrDefault(), Campus = group.Campus, // Role = group.ParentGroup.GroupType.Name.Contains("Serving") || group.Name.ToLower().Contains("leader")? "Leader":"Student", // MSMGroup = 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()), Person = g.Person, AddressStreet = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null?gm.Location.Street1:"").FirstOrDefault(), AddressCityStateZip = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null ? gm.Location.City + ", " + gm.Location.State + " " + gm.Location.PostalCode : "").FirstOrDefault(), RegistrantName = g.Person.FullName, }).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("MSMGroup"); 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(); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="groupMemberId">The group member identifier.</param> /// <param name="groupId">The group id.</param> public void ShowDetail(int groupMemberId, int?groupId) { // autoexpand the person picker if this is an add var personPickerStartupScript = @"Sys.Application.add_load(function () { // if the person picker is empty then open it for quick entry var personPicker = $('.js-authorizedperson'); var currentPerson = personPicker.find('.picker-selectedperson').html(); if (currentPerson != null && currentPerson.length == 0) { $(personPicker).find('a.picker-label').trigger('click'); } });"; this.Page.ClientScript.RegisterStartupScript(this.GetType(), "StartupScript", personPickerStartupScript, true); var rockContext = new RockContext(); GroupMember groupMember = null; if (!groupMemberId.Equals(0)) { groupMember = new GroupMemberService(rockContext).Get(groupMemberId); pdAuditDetails.SetEntity(groupMember, ResolveRockUrl("~")); } else { // only create a new one if parent was specified if (groupId.HasValue) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = groupId.Value; groupMember.Group = new GroupService(rockContext).Get(groupMember.GroupId); groupMember.GroupRoleId = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0; groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMember.DateTimeAdded = RockDateTime.Now; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } } if (groupMember == null) { if (groupMemberId > 0) { nbErrorMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning; nbErrorMessage.Title = "Warning"; nbErrorMessage.Text = "Group Member not found. Group Member may have been moved to another group or deleted."; } else { nbErrorMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Danger; nbErrorMessage.Title = "Invalid Request"; nbErrorMessage.Text = "An incorrect querystring parameter was used. A valid GroupMemberId or GroupId parameter is required."; } pnlEditDetails.Visible = false; return; } pnlEditDetails.Visible = true; hfGroupId.Value = groupMember.GroupId.ToString(); hfGroupMemberId.Value = groupMember.Id.ToString(); if (IsUserAuthorized(Authorization.ADMINISTRATE)) { cbIsNotified.Checked = groupMember.IsNotified; cbIsNotified.Visible = true; cbIsNotified.Help = "If this box is unchecked and a <a href=\"http://www.rockrms.com/Rock/BookContent/7/#servicejobsrelatingtogroups\">group leader notification job</a> is enabled then a notification will be sent to the group's leaders when this group member is saved."; } else { cbIsNotified.Visible = false; } // render UI based on Authorized and IsSystem bool readOnly = false; var group = groupMember.Group; if (!string.IsNullOrWhiteSpace(group.GroupType.IconCssClass)) { lGroupIconHtml.Text = string.Format("<i class='{0}' ></i>", group.GroupType.IconCssClass); } else { lGroupIconHtml.Text = "<i class='fa fa-user' ></i>"; } if (groupMember.Id.Equals(0)) { lReadOnlyTitle.Text = ActionTitle.Add(groupMember.Group.GroupType.GroupTerm + " " + groupMember.Group.GroupType.GroupMemberTerm).FormatAsHtmlTitle(); btnSaveThenAdd.Visible = true; } else { lReadOnlyTitle.Text = groupMember.Person.FullName.FormatAsHtmlTitle(); btnSaveThenAdd.Visible = false; } if (groupMember.DateTimeAdded.HasValue) { hfDateAdded.Text = string.Format("Added: {0}", groupMember.DateTimeAdded.Value.ToShortDateString()); hfDateAdded.Visible = true; } else { hfDateAdded.Text = string.Empty; hfDateAdded.Visible = false; } // user has to have EDIT Auth to the Block OR the group nbEditModeMessage.Text = string.Empty; if (!IsUserAuthorized(Authorization.EDIT) && !group.IsAuthorized(Authorization.EDIT, this.CurrentPerson)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Group.FriendlyTypeName); } if (groupMember.IsSystem) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(Group.FriendlyTypeName); } btnSave.Visible = !readOnly; if (readOnly || groupMember.Id == 0) { // hide the ShowMoveDialog if this is readOnly or if this is a new group member (can't move a group member that doesn't exist yet) btnShowMoveDialog.Visible = false; } LoadDropDowns(); ShowRequiredDocumentStatus(rockContext, groupMember, group); ppGroupMemberPerson.SetValue(groupMember.Person); ppGroupMemberPerson.Enabled = !readOnly; if (groupMember.Id != 0) { // once a group member record is saved, don't let them change the person ppGroupMemberPerson.Enabled = false; } ddlGroupRole.SetValue(groupMember.GroupRoleId); ddlGroupRole.Enabled = !readOnly; tbNote.Text = groupMember.Note; tbNote.ReadOnly = readOnly; rblStatus.SetValue((int)groupMember.GroupMemberStatus); rblStatus.Enabled = !readOnly; rblStatus.Label = string.Format("{0} Status", group.GroupType.GroupMemberTerm); var registrations = new RegistrationRegistrantService(rockContext) .Queryable().AsNoTracking() .Where(r => r.Registration != null && r.Registration.RegistrationInstance != null && r.GroupMemberId.HasValue && r.GroupMemberId.Value == groupMember.Id) .Select(r => new { Id = r.Registration.Id, Name = r.Registration.RegistrationInstance.Name }) .ToList(); if (registrations.Any()) { rcwLinkedRegistrations.Visible = true; rptLinkedRegistrations.DataSource = registrations; rptLinkedRegistrations.DataBind(); } else { rcwLinkedRegistrations.Visible = false; } if (groupMember.Group.RequiredSignatureDocumentTemplate != null) { fuSignedDocument.Label = groupMember.Group.RequiredSignatureDocumentTemplate.Name; if (groupMember.Group.RequiredSignatureDocumentTemplate.BinaryFileType != null) { fuSignedDocument.BinaryFileTypeGuid = groupMember.Group.RequiredSignatureDocumentTemplate.BinaryFileType.Guid; } var signatureDocument = new SignatureDocumentService(rockContext) .Queryable().AsNoTracking() .Where(d => d.SignatureDocumentTemplateId == groupMember.Group.RequiredSignatureDocumentTemplateId.Value && d.AppliesToPersonAlias != null && d.AppliesToPersonAlias.PersonId == groupMember.PersonId && d.LastStatusDate.HasValue && d.Status == SignatureDocumentStatus.Signed && d.BinaryFile != null) .OrderByDescending(d => d.LastStatusDate.Value) .FirstOrDefault(); if (signatureDocument != null) { hfSignedDocumentId.Value = signatureDocument.Id.ToString(); fuSignedDocument.BinaryFileId = signatureDocument.BinaryFileId; } fuSignedDocument.Visible = true; } else { fuSignedDocument.Visible = false; } groupMember.LoadAttributes(); phAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls(groupMember, phAttributes, true, string.Empty, true); if (readOnly) { Rock.Attribute.Helper.AddDisplayControls(groupMember, phAttributesReadOnly); phAttributesReadOnly.Visible = true; phAttributes.Visible = false; } else { phAttributesReadOnly.Visible = false; phAttributes.Visible = true; } var groupHasRequirements = group.GroupRequirements.Any(); pnlRequirements.Visible = groupHasRequirements; btnReCheckRequirements.Visible = groupHasRequirements; ShowGroupRequirementsStatuses(); }
private void DisplayDetails() { int eventItemOccurrenceId = 0; RockContext rockContext = new RockContext(); // get the calendarItem id if ( !string.IsNullOrWhiteSpace( PageParameter( "EventOccurrenceId" ) ) ) { eventItemOccurrenceId = Convert.ToInt32( PageParameter( "EventOccurrenceId" ) ); } if ( eventItemOccurrenceId > 0 ) { var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext ); var qry = eventItemOccurrenceService .Queryable( "EventItem, EventItem.Photo, Campus, Linkages" ) .Where( i => i.Id == eventItemOccurrenceId ); var eventItemOccurrence = qry.FirstOrDefault(); var mergeFields = new Dictionary<string, object>(); mergeFields.Add( "RegistrationPage", LinkedPageRoute( "RegistrationPage" ) ); var campusEntityType = EntityTypeCache.Read( "Rock.Model.Campus" ); var contextCampus = RockPage.GetCurrentContext( campusEntityType ) as Campus; if ( contextCampus != null ) { mergeFields.Add( "CampusContext", contextCampus ); } // determine if the registration is full var maxRegistrantCount = 0; var currentRegistrationCount = 0; var linkage = eventItemOccurrence.Linkages.FirstOrDefault(); if (linkage != null ) { if (linkage.RegistrationInstance != null ) { if ( linkage.RegistrationInstance.MaxAttendees != 0 ) { maxRegistrantCount = linkage.RegistrationInstance.MaxAttendees; } } if ( maxRegistrantCount != 0 ) { currentRegistrationCount = new RegistrationRegistrantService( rockContext ).Queryable().AsNoTracking() .Where( r => r.Registration.RegistrationInstanceId == linkage.RegistrationInstanceId && r.OnWaitList == false ) .Count(); } } mergeFields.Add( "RegistrationStatusLabel", (maxRegistrantCount - currentRegistrationCount > 0) ? "Register" : "Join Wait List"); mergeFields.Add( "EventItemOccurrence", eventItemOccurrence ); mergeFields.Add( "Event", eventItemOccurrence != null ? eventItemOccurrence.EventItem : null ); mergeFields.Add( "CurrentPerson", CurrentPerson ); lOutput.Text = GetAttributeValue( "LavaTemplate" ).ResolveMergeFields( mergeFields ); if ( GetAttributeValue( "SetPageTitle" ).AsBoolean() ) { string pageTitle = eventItemOccurrence != null ? eventItemOccurrence.EventItem.Name : "Event"; RockPage.PageTitle = pageTitle; RockPage.BrowserTitle = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name ); RockPage.Header.Title = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name ); } // show debug info if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) ) { lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); } } else { lOutput.Text = "<div class='alert alert-warning'>No event was available from the querystring.</div>"; } }
/// <summary> /// Handles the Click event of the DeleteGroupMember control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param> protected void DeleteGroupMember_Click( object sender, Rock.Web.UI.Controls.RowEventArgs e ) { RockContext rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); RegistrationRegistrantService registrantService = new RegistrationRegistrantService( rockContext ); GroupMember groupMember = groupMemberService.Get( e.RowKeyId ); if ( groupMember != null ) { string errorMessage; if ( !groupMemberService.CanDelete( groupMember, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } int groupId = groupMember.GroupId; foreach ( var registrant in registrantService.Queryable().Where( r => r.GroupMemberId == groupMember.Id ) ) { registrant.GroupMemberId = null; } groupMemberService.Delete( groupMember ); rockContext.SaveChanges(); Group group = new GroupService( rockContext ).Get( groupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { // person removed from SecurityRole, Flush Rock.Security.Role.Flush( group.Id ); } } BindGroupMembersGrid(); }
/// <summary> /// Saves the registration. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="hasPayment">if set to <c>true</c> [has payment].</param> /// <returns></returns> private Registration SaveRegistration( RockContext rockContext, bool hasPayment ) { var registrationService = new RegistrationService( rockContext ); var registrantService = new RegistrationRegistrantService( rockContext ); var registrantFeeService = new RegistrationRegistrantFeeService( rockContext ); var personService = new PersonService( rockContext ); var groupService = new GroupService( rockContext ); // variables to keep track of the family that new people should be added to int? singleFamilyId = null; var multipleFamilyGroupIds = new Dictionary<Guid, int>(); var dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); var dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); var familyGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ); var adultRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var childRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); bool newRegistration = false; Registration registration = null; Person registrar = null; var registrationChanges = new List<string>(); if ( RegistrationState.RegistrationId.HasValue ) { registration = registrationService.Get( RegistrationState.RegistrationId.Value ); } if ( registration == null ) { newRegistration = true; registration = new Registration(); registrationService.Add( registration ); registrationChanges.Add( "Created Registration" ); } else { if ( registration.PersonAlias != null && registration.PersonAlias.Person != null ) { registrar = registration.PersonAlias.Person; } } registration.RegistrationInstanceId = RegistrationInstanceState.Id; // If the Registration Instance linkage specified a group, load it now Group group = null; if ( GroupId.HasValue ) { group = new GroupService( rockContext ).Get( GroupId.Value ); if ( group != null && ( !registration.GroupId.HasValue || registration.GroupId.Value != group.Id ) ) { registration.GroupId = group.Id; History.EvaluateChange( registrationChanges, "Group", string.Empty, group.Name ); } } bool newRegistrar = newRegistration || registration.FirstName == null || !registration.FirstName.Equals( RegistrationState.FirstName, StringComparison.OrdinalIgnoreCase ) || registration.LastName == null || !registration.LastName.Equals( RegistrationState.LastName, StringComparison.OrdinalIgnoreCase ); History.EvaluateChange( registrationChanges, "First Name", registration.FirstName, RegistrationState.FirstName ); registration.FirstName = RegistrationState.FirstName; History.EvaluateChange( registrationChanges, "Last Name", registration.LastName, RegistrationState.LastName ); registration.LastName = RegistrationState.LastName; History.EvaluateChange( registrationChanges, "Confirmation Email", registration.ConfirmationEmail, RegistrationState.ConfirmationEmail ); registration.ConfirmationEmail = RegistrationState.ConfirmationEmail; History.EvaluateChange( registrationChanges, "Discount Code", registration.DiscountCode, RegistrationState.DiscountCode ); registration.DiscountCode = RegistrationState.DiscountCode; History.EvaluateChange( registrationChanges, "Discount Percentage", registration.DiscountPercentage, RegistrationState.DiscountPercentage ); registration.DiscountPercentage = RegistrationState.DiscountPercentage; History.EvaluateChange( registrationChanges, "Discount Amount", registration.DiscountAmount, RegistrationState.DiscountAmount ); registration.DiscountAmount = RegistrationState.DiscountAmount; if ( newRegistrar ) { if ( CurrentPerson != null && CurrentPerson.NickName == null ) { CurrentPerson.NickName = CurrentPerson.FirstName; } // If the 'your name' value equals the currently logged in person, use their person alias id if ( CurrentPerson != null && ( CurrentPerson.NickName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) || CurrentPerson.FirstName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ) && CurrentPerson.LastName.Trim().Equals( registration.LastName.Trim(), StringComparison.OrdinalIgnoreCase ) ) { registrar = CurrentPerson; registration.PersonAliasId = CurrentPerson.PrimaryAliasId; // If email that logged in user used is different than their stored email address, update their stored value if ( !string.IsNullOrWhiteSpace( registration.ConfirmationEmail ) && !registration.ConfirmationEmail.Trim().Equals( CurrentPerson.Email.Trim(), StringComparison.OrdinalIgnoreCase ) && ( !cbUpdateEmail.Visible || cbUpdateEmail.Checked ) ) { var person = personService.Get( CurrentPerson.Id ); if ( person != null ) { var personChanges = new List<string>(); History.EvaluateChange( personChanges, "Email", person.Email, registration.ConfirmationEmail ); person.Email = registration.ConfirmationEmail; HistoryService.SaveChanges( new RockContext(), typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, personChanges, true, CurrentPersonAliasId ); } } } else { // otherwise look for one and one-only match by name/email var personMatches = personService.GetByMatch( registration.FirstName, registration.LastName, registration.ConfirmationEmail ); if ( personMatches.Count() == 1 ) { registrar = personMatches.First(); registration.PersonAliasId = registrar.PrimaryAliasId; } else { registrar = null; registration.PersonAlias = null; registration.PersonAliasId = null; } } } // Set the family guid for any other registrants that were selected to be in the same family if ( registrar != null ) { var family = registrar.GetFamilies( rockContext ).FirstOrDefault(); if ( family != null ) { multipleFamilyGroupIds.AddOrIgnore( RegistrationState.FamilyGuid, family.Id ); if ( !singleFamilyId.HasValue ) { singleFamilyId = family.Id; } } } // Make sure there's an actual person associated to registration if ( !registration.PersonAliasId.HasValue ) { // If a match was not found, create a new person var person = new Person(); person.FirstName = registration.FirstName; person.LastName = registration.LastName; person.IsEmailActive = true; person.Email = registration.ConfirmationEmail; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { person.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { person.RecordStatusValueId = dvcRecordStatus.Id; } registrar = SavePerson( rockContext, person, RegistrationState.FamilyGuid, CampusId, null, adultRoleId, childRoleId, multipleFamilyGroupIds, ref singleFamilyId ); registration.PersonAliasId = registrar != null ? registrar.PrimaryAliasId : (int?)null; History.EvaluateChange( registrationChanges, "Registrar", string.Empty, registrar.FullName ); } else { if ( newRegistration ) { History.EvaluateChange( registrationChanges, "Registrar", string.Empty, registration.ToString() ); } } // if this registration was marked as temporary (started from another page, then specified in the url), set IsTemporary to False now that we are done if ( registration.IsTemporary ) { registration.IsTemporary = false; } // Save the registration ( so we can get an id ) rockContext.SaveChanges(); RegistrationState.RegistrationId = registration.Id; try { Task.Run( () => HistoryService.SaveChanges( new RockContext(), typeof( Registration ), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registration.Id, registrationChanges, true, CurrentPersonAliasId ) ); // Get each registrant foreach ( var registrantInfo in RegistrationState.Registrants.ToList() ) { var registrantChanges = new List<string>(); var personChanges = new List<string>(); var familyChanges = new List<string>(); RegistrationRegistrant registrant = null; Person person = null; string firstName = registrantInfo.GetFirstName( RegistrationTemplate ); string lastName = registrantInfo.GetLastName( RegistrationTemplate ); string email = registrantInfo.GetEmail( RegistrationTemplate ); if ( registrantInfo.Id > 0 ) { registrant = registration.Registrants.FirstOrDefault( r => r.Id == registrantInfo.Id ); if ( registrant != null ) { person = registrant.Person; if ( person != null && ( ( registrant.Person.FirstName.Equals( firstName, StringComparison.OrdinalIgnoreCase ) || registrant.Person.NickName.Equals( firstName, StringComparison.OrdinalIgnoreCase ) ) && registrant.Person.LastName.Equals( lastName, StringComparison.OrdinalIgnoreCase ) ) ) { // } else { person = null; registrant.PersonAlias = null; registrant.PersonAliasId = null; } } } if ( person == null ) { // Try to find a matching person based on name and email address var personMatches = personService.GetByMatch( firstName, lastName, email ); if ( personMatches.Count() == 1 ) { person = personMatches.First(); } // Try to find a matching person based on name within same family as registrar if ( person == null && registrar != null && registrantInfo.FamilyGuid == RegistrationState.FamilyGuid ) { var familyMembers = registrar.GetFamilyMembers( true, rockContext ) .Where( m => ( m.Person.FirstName == firstName || m.Person.NickName == firstName ) && m.Person.LastName == lastName ) .Select( m => m.Person ) .ToList(); if ( familyMembers.Count() == 1 ) { person = familyMembers.First(); if ( !string.IsNullOrWhiteSpace( email ) ) { person.Email = email; } } if ( familyMembers.Count() > 1 && !string.IsNullOrWhiteSpace( email ) ) { familyMembers = familyMembers .Where( m => m.Email != null && m.Email.Equals( email, StringComparison.OrdinalIgnoreCase ) ) .ToList(); if ( familyMembers.Count() == 1 ) { person = familyMembers.First(); } } } } if ( person == null ) { // If a match was not found, create a new person person = new Person(); person.FirstName = firstName; person.LastName = lastName; person.IsEmailActive = true; person.Email = email; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { person.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { person.RecordStatusValueId = dvcRecordStatus.Id; } } int? campusId = CampusId; Location location = null; // Set any of the template's person fields foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.PersonField ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value.FieldValue ) .FirstOrDefault(); if ( fieldValue != null ) { switch ( field.PersonFieldType ) { case RegistrationPersonFieldType.Campus: { if ( fieldValue != null ) { campusId = fieldValue.ToString().AsIntegerOrNull(); } break; } case RegistrationPersonFieldType.Address: { location = fieldValue as Location; break; } case RegistrationPersonFieldType.Birthdate: { var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; person.SetBirthDate( fieldValue as DateTime? ); History.EvaluateChange( personChanges, "Birth Month", birthMonth, person.BirthMonth ); History.EvaluateChange( personChanges, "Birth Day", birthDay, person.BirthDay ); History.EvaluateChange( personChanges, "Birth Year", birthYear, person.BirthYear ); break; } case RegistrationPersonFieldType.Grade: { var newGraduationYear = fieldValue.ToString().AsIntegerOrNull(); History.EvaluateChange( personChanges, "Graduation Year", person.GraduationYear, newGraduationYear ); person.GraduationYear = newGraduationYear; break; } case RegistrationPersonFieldType.Gender: { var newGender = fieldValue.ToString().ConvertToEnumOrNull<Gender>() ?? Gender.Unknown; History.EvaluateChange( personChanges, "Gender", person.Gender, newGender ); person.Gender = newGender; break; } case RegistrationPersonFieldType.MaritalStatus: { if ( fieldValue != null ) { int? newMaritalStatusId = fieldValue.ToString().AsIntegerOrNull(); History.EvaluateChange( personChanges, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) ); person.MaritalStatusValueId = newMaritalStatusId; } break; } case RegistrationPersonFieldType.MobilePhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), personChanges ); break; } case RegistrationPersonFieldType.HomePhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), personChanges ); break; } case RegistrationPersonFieldType.WorkPhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid(), personChanges ); break; } } } } // Save the person ( and family if needed ) SavePerson( rockContext, person, registrantInfo.FamilyGuid, campusId, location, adultRoleId, childRoleId, multipleFamilyGroupIds, ref singleFamilyId ); // Load the person's attributes person.LoadAttributes(); // Set any of the template's person fields foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.PersonAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value.FieldValue ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { string originalValue = person.GetAttributeValue( attribute.Key ); string newValue = fieldValue.ToString(); person.SetAttributeValue( attribute.Key, fieldValue.ToString() ); // DateTime values must be stored in ISO8601 format as http://www.rockrms.com/Rock/Developer/BookContent/16/16#datetimeformatting if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) || attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE_TIME.AsGuid() ) ) { DateTime aDateTime; if ( DateTime.TryParse( newValue, out aDateTime ) ) { newValue = aDateTime.ToString( "o" ); } } 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 ); } Helper.SaveAttributeValue( person, attribute, newValue, rockContext ); History.EvaluateChange( personChanges, attribute.Name, formattedOriginalValue, formattedNewValue ); } } } } string registrantName = person.FullName + ": "; personChanges.ForEach( c => registrantChanges.Add( c ) ); if ( registrant == null ) { registrant = new RegistrationRegistrant(); registrant.Guid = registrantInfo.Guid; registrantService.Add( registrant ); registrant.RegistrationId = registration.Id; } registrant.PersonAliasId = person.PrimaryAliasId; registrant.Cost = registrantInfo.Cost; // Remove fees // Remove/delete any registrant fees that are no longer in UI with quantity foreach ( var dbFee in registrant.Fees.ToList() ) { if ( !registrantInfo.FeeValues.Keys.Contains( dbFee.RegistrationTemplateFeeId ) || registrantInfo.FeeValues[dbFee.RegistrationTemplateFeeId] == null || !registrantInfo.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 or Update fees foreach ( var uiFee in registrantInfo.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 = RegistrationTemplate.Fees.Where( f => f.Id == uiFee.Key ).FirstOrDefault(); } 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; } } rockContext.SaveChanges(); registrantInfo.Id = registrant.Id; // Set any of the templat's registrant attributes registrant.LoadAttributes(); foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.RegistrationAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value.FieldValue ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { string originalValue = registrant.GetAttributeValue( attribute.Key ); string newValue = fieldValue.ToString(); registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() ); // DateTime values must be stored in ISO8601 format as http://www.rockrms.com/Rock/Developer/BookContent/16/16#datetimeformatting if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) || attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE_TIME.AsGuid() ) ) { DateTime aDateTime; if ( DateTime.TryParse( fieldValue.ToString(), out aDateTime ) ) { newValue = aDateTime.ToString( "o" ); } } 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 ); } Helper.SaveAttributeValue( registrant, attribute, newValue, rockContext ); History.EvaluateChange( registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue ); } } } } Task.Run( () => HistoryService.SaveChanges( new RockContext(), typeof( Registration ), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registration.Id, registrantChanges, "Registrant: " + person.FullName, null, null, true, CurrentPersonAliasId ) ); // Clear this registran't family guid so it's not updated again registrantInfo.FamilyGuid = Guid.Empty; } rockContext.SaveChanges(); } catch ( Exception ex ) { using ( var newRockContext = new RockContext() ) { if ( newRegistration ) { var newRegistrationService = new RegistrationService( newRockContext ); var savedRegistration = new RegistrationService( newRockContext ).Get( registration.Id ); if ( savedRegistration != null ) { HistoryService.DeleteChanges( newRockContext, typeof( Registration ), savedRegistration.Id ); newRegistrationService.Delete( savedRegistration ); newRockContext.SaveChanges(); } } } throw ex; } return registration; }
private void LoadState() { int? registrantId = PageParameter( "RegistrantId" ).AsIntegerOrNull(); int? registrationId = PageParameter( "RegistrationId" ).AsIntegerOrNull(); if ( RegistrantState == null ) { var rockContext = new RockContext(); RegistrationRegistrant registrant = null; if ( registrantId.HasValue && registrantId.Value != 0 ) { registrant = new RegistrationRegistrantService( rockContext ) .Queryable( "Registration.RegistrationInstance.RegistrationTemplate.Forms.Fields,Registration.RegistrationInstance.RegistrationTemplate.Fees,PersonAlias.Person,Fees" ).AsNoTracking() .Where( r => r.Id == registrantId.Value ) .FirstOrDefault(); if ( registrant != null && registrant.Registration != null && registrant.Registration.RegistrationInstance != null && registrant.Registration.RegistrationInstance.RegistrationTemplate != null ) { RegistrantState = new RegistrantInfo( registrant, rockContext ); TemplateState = registrant.Registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registrant.Registration.RegistrationInstanceId; lWizardTemplateName.Text = registrant.Registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registrant.Registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registrant.Registration.ToString(); lWizardRegistrantName.Text = registrant.ToString(); tglWaitList.Checked = !registrant.OnWaitList; } } if ( TemplateState == null && registrationId.HasValue && registrationId.Value != 0 ) { var registration = new RegistrationService( rockContext ) .Queryable( "RegistrationInstance.RegistrationTemplate.Forms.Fields,RegistrationInstance.RegistrationTemplate.Fees" ).AsNoTracking() .Where( r => r.Id == registrationId.Value ) .FirstOrDefault(); if ( registration != null && registration.RegistrationInstance != null && registration.RegistrationInstance.RegistrationTemplate != null ) { TemplateState = registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registration.RegistrationInstanceId; lWizardTemplateName.Text = registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registration.ToString(); lWizardRegistrantName.Text = "New Registrant"; } } if ( TemplateState != null ) { tglWaitList.Visible = TemplateState.WaitListEnabled; } if ( TemplateState != null && RegistrantState == null ) { RegistrantState = new RegistrantInfo(); RegistrantState.RegistrationId = registrationId ?? 0; if ( TemplateState.SetCostOnInstance.HasValue && TemplateState.SetCostOnInstance.Value ) { var instance = new RegistrationInstanceService( rockContext ).Get( RegistrationInstanceId ); if ( instance != null ) { RegistrantState.Cost = instance.Cost ?? 0.0m; } } else { RegistrantState.Cost = TemplateState.Cost; } } if ( registrant != null && registrant.PersonAlias != null && registrant.PersonAlias.Person != null ) { ppPerson.SetValue( registrant.PersonAlias.Person ); if ( TemplateState != null && TemplateState.RequiredSignatureDocumentTemplate != null ) { fuSignedDocument.Label = TemplateState.RequiredSignatureDocumentTemplate.Name; if ( TemplateState.RequiredSignatureDocumentTemplate.BinaryFileType != null ) { fuSignedDocument.BinaryFileTypeGuid = TemplateState.RequiredSignatureDocumentTemplate.BinaryFileType.Guid; } var signatureDocument = new SignatureDocumentService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.SignatureDocumentTemplateId == TemplateState.RequiredSignatureDocumentTemplateId.Value && d.AppliesToPersonAlias != null && d.AppliesToPersonAlias.PersonId == registrant.PersonAlias.PersonId && d.LastStatusDate.HasValue && d.Status == SignatureDocumentStatus.Signed && d.BinaryFile != null ) .OrderByDescending( d => d.LastStatusDate.Value ) .FirstOrDefault(); if ( signatureDocument != null ) { hfSignedDocumentId.Value = signatureDocument.Id.ToString(); fuSignedDocument.BinaryFileId = signatureDocument.BinaryFileId; } fuSignedDocument.Visible = true; } else { fuSignedDocument.Visible = false; } } else { ppPerson.SetValue( null ); } if ( RegistrantState != null ) { cbCost.Text = RegistrantState.Cost.ToString( "N2" ); cbDiscountApplies.Checked = RegistrantState.DiscountApplies; } } }
/// <summary> /// Binds the group placement grid. /// </summary> /// <param name="isExporting">if set to <c>true</c> [is exporting].</param> private void BindGroupPlacementGrid( bool isExporting = false ) { int? groupId = gpGroupPlacementParentGroup.SelectedValueAsInt(); int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { // Start query for registrants var qry = new RegistrationRegistrantService( rockContext ) .Queryable( "PersonAlias.Person.PhoneNumbers.NumberTypeValue,Fees.RegistrationTemplateFee,GroupMember.Group" ).AsNoTracking() .Where( r => r.Registration.RegistrationInstanceId == instanceId.Value && r.PersonAlias != null && r.PersonAlias.Person != null ); if ( groupId.HasValue ) { var validGroupIds = new GroupService( rockContext ).GetAllDescendents( groupId.Value ) .Select( g => g.Id ) .ToList(); var existingPeopleInGroups = new GroupMemberService( rockContext ) .Queryable().AsNoTracking() .Where( m => validGroupIds.Contains( m.GroupId ) ) .Select( m => m.PersonId ) .ToList(); qry = qry.Where( r => !existingPeopleInGroups.Contains( r.PersonAlias.PersonId ) ); } bool preloadCampusValues = false; var registrantAttributeIds = new List<int>(); var personAttributesIds = new List<int>(); var groupMemberAttributesIds = new List<int>(); if ( RegistrantFields != null ) { // Check if campus is used preloadCampusValues = RegistrantFields .Any( f => f.FieldSource == RegistrationFieldSource.PersonField && f.PersonFieldType.HasValue && f.PersonFieldType.Value == RegistrationPersonFieldType.Campus ); // Get all the registrant attributes selected var registrantAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.RegistrationAttribute ) .Select( f => f.Attribute ) .ToList(); registrantAttributeIds = registrantAttributes.Select( a => a.Id ).Distinct().ToList(); // Get all the person attributes selected var personAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.PersonAttribute ) .Select( f => f.Attribute ) .ToList(); personAttributesIds = personAttributes.Select( a => a.Id ).Distinct().ToList(); // Get all the group member attributes selected to be on grid var groupMemberAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.GroupMemberAttribute ) .Select( f => f.Attribute ) .ToList(); groupMemberAttributesIds = groupMemberAttributes.Select( a => a.Id ).Distinct().ToList(); } // Sort the query IOrderedQueryable<RegistrationRegistrant> orderedQry = null; SortProperty sortProperty = gGroupPlacements.SortProperty; if ( sortProperty != null ) { orderedQry = qry.Sort( sortProperty ); } else { orderedQry = qry .OrderBy( r => r.PersonAlias.Person.LastName ) .ThenBy( r => r.PersonAlias.Person.NickName ); } // Set the grids LinqDataSource which will run query and set results for current page gGroupPlacements.SetLinqDataSource<RegistrationRegistrant>( orderedQry ); if ( RegistrantFields != null ) { // Get the query results for the current page var currentPageRegistrants = gGroupPlacements.DataSource as List<RegistrationRegistrant>; if ( currentPageRegistrants != null ) { // Get all the registrant ids in current page of query results var registrantIds = currentPageRegistrants .Select( r => r.Id ) .Distinct() .ToList(); // Get all the person ids in current page of query results var personIds = currentPageRegistrants .Select( r => r.PersonAlias.PersonId ) .Distinct() .ToList(); // Get all the group member ids and the group id in current page of query results var groupMemberIds = new List<int>(); GroupLinks = new Dictionary<int, string>(); foreach ( var groupMember in currentPageRegistrants .Where( m => m.GroupMember != null && m.GroupMember.Group != null ) .Select( m => m.GroupMember ) ) { groupMemberIds.Add( groupMember.Id ); GroupLinks.AddOrIgnore( groupMember.GroupId, isExporting ? groupMember.Group.Name : string.Format( "<a href='{0}'>{1}</a>", LinkedPageUrl( "GroupDetailPage", new Dictionary<string, string> { { "GroupId", groupMember.GroupId.ToString() } } ), groupMember.Group.Name ) ); } // If the campus column was selected to be displayed on grid, preload all the people's // campuses so that the databind does not need to query each row if ( preloadCampusValues ) { PersonCampusIds = new Dictionary<int, List<int>>(); Guid familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); foreach ( var personCampusList in new GroupMemberService( rockContext ) .Queryable().AsNoTracking() .Where( m => m.Group.GroupType.Guid == familyGroupTypeGuid && personIds.Contains( m.PersonId ) ) .GroupBy( m => m.PersonId ) .Select( m => new { PersonId = m.Key, CampusIds = m .Where( g => g.Group.CampusId.HasValue ) .Select( g => g.Group.CampusId.Value ) .ToList() } ) ) { PersonCampusIds.Add( personCampusList.PersonId, personCampusList.CampusIds ); } } // If there are any attributes that were selected to be displayed, we're going // to try and read all attribute values in one query and then put them into a // custom grid ObjectList property so that the AttributeField columns don't need // to do the LoadAttributes and querying of values for each row/column if ( personAttributesIds.Any() || groupMemberAttributesIds.Any() || registrantAttributeIds.Any() ) { // Query the attribute values for all rows and attributes var attributeValues = new AttributeValueService( rockContext ) .Queryable( "Attribute" ).AsNoTracking() .Where( v => v.EntityId.HasValue && ( ( personAttributesIds.Contains( v.AttributeId ) && personIds.Contains( v.EntityId.Value ) ) || ( groupMemberAttributesIds.Contains( v.AttributeId ) && groupMemberIds.Contains( v.EntityId.Value ) ) || ( registrantAttributeIds.Contains( v.AttributeId ) && registrantIds.Contains( v.EntityId.Value ) ) ) ) .ToList(); // Get the attributes to add to each row's object var attributes = new Dictionary<string, AttributeCache>(); RegistrantFields .Where( f => f.Attribute != null ) .Select( f => f.Attribute ) .ToList() .ForEach( a => attributes .Add( a.Id.ToString() + a.Key, a ) ); // Initialize the grid's object list gGroupPlacements.ObjectList = new Dictionary<string, object>(); // Loop through each of the current page's registrants and build an attribute // field object for storing attributes and the values for each of the registrants foreach ( var registrant in currentPageRegistrants ) { // Create a row attribute object var attributeFieldObject = new AttributeFieldObject(); // Add the attributes to the attribute object attributeFieldObject.Attributes = attributes; // Add any person attribute values to object attributeValues .Where( v => personAttributesIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.PersonAlias.PersonId ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, new AttributeValueCache( v ) ) ); // Add any group member attribute values to object if ( registrant.GroupMemberId.HasValue ) { attributeValues .Where( v => groupMemberAttributesIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.GroupMemberId.Value ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, new AttributeValueCache( v ) ) ); } // Add any registrant attribute values to object attributeValues .Where( v => registrantAttributeIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.Id ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, new AttributeValueCache( v ) ) ); // Add row attribute object to grid's object list gGroupPlacements.ObjectList.Add( registrant.Id.ToString(), attributeFieldObject ); } } } } gGroupPlacements.DataBind(); } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="groupMemberId">The group member identifier.</param> /// <param name="groupId">The group id.</param> public void ShowDetail( int groupMemberId, int? groupId ) { // autoexpand the person picker if this is an add var personPickerStartupScript = @"Sys.Application.add_load(function () { // if the person picker is empty then open it for quick entry var personPicker = $('.js-authorizedperson'); var currentPerson = personPicker.find('.picker-selectedperson').html(); if (currentPerson != null && currentPerson.length == 0) { $(personPicker).find('a.picker-label').trigger('click'); } });"; this.Page.ClientScript.RegisterStartupScript( this.GetType(), "StartupScript", personPickerStartupScript, true ); var rockContext = new RockContext(); GroupMember groupMember = null; if ( !groupMemberId.Equals( 0 ) ) { groupMember = new GroupMemberService( rockContext ).Get( groupMemberId ); pdAuditDetails.SetEntity( groupMember, ResolveRockUrl( "~" ) ); } else { // only create a new one if parent was specified if ( groupId.HasValue ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = groupId.Value; groupMember.Group = new GroupService( rockContext ).Get( groupMember.GroupId ); groupMember.GroupRoleId = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0; groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMember.DateTimeAdded = RockDateTime.Now; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } } if ( groupMember == null ) { if ( groupMemberId > 0 ) { nbErrorMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning; nbErrorMessage.Title = "Warning"; nbErrorMessage.Text = "Group Member not found. Group Member may have been moved to another group or deleted."; } else { nbErrorMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Danger; nbErrorMessage.Title = "Invalid Request"; nbErrorMessage.Text = "An incorrect querystring parameter was used. A valid GroupMemberId or GroupId parameter is required."; } pnlEditDetails.Visible = false; return; } pnlEditDetails.Visible = true; hfGroupId.Value = groupMember.GroupId.ToString(); hfGroupMemberId.Value = groupMember.Id.ToString(); if ( IsUserAuthorized( Authorization.ADMINISTRATE ) ) { cbIsNotified.Checked = groupMember.IsNotified; cbIsNotified.Visible = true; cbIsNotified.Help = "If this box is unchecked and a <a href=\"http://www.rockrms.com/Rock/BookContent/7/#servicejobsrelatingtogroups\">group leader notification job</a> is enabled then a notification will be sent to the group's leaders when this group member is saved."; } else { cbIsNotified.Visible = false; } // render UI based on Authorized and IsSystem bool readOnly = false; var group = groupMember.Group; if ( !string.IsNullOrWhiteSpace( group.GroupType.IconCssClass ) ) { lGroupIconHtml.Text = string.Format( "<i class='{0}' ></i>", group.GroupType.IconCssClass ); } else { lGroupIconHtml.Text = "<i class='fa fa-user' ></i>"; } if ( groupMember.Id.Equals( 0 ) ) { lReadOnlyTitle.Text = ActionTitle.Add( groupMember.Group.GroupType.GroupTerm + " " + groupMember.Group.GroupType.GroupMemberTerm ).FormatAsHtmlTitle(); btnSaveThenAdd.Visible = true; } else { lReadOnlyTitle.Text = groupMember.Person.FullName.FormatAsHtmlTitle(); btnSaveThenAdd.Visible = false; } if ( groupMember.DateTimeAdded.HasValue ) { hfDateAdded.Text = string.Format( "Added: {0}", groupMember.DateTimeAdded.Value.ToShortDateString() ); hfDateAdded.Visible = true; } else { hfDateAdded.Text = string.Empty; hfDateAdded.Visible = false; } // user has to have EDIT Auth to the Block OR the group nbEditModeMessage.Text = string.Empty; if ( !IsUserAuthorized( Authorization.EDIT ) && !group.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Group.FriendlyTypeName ); } if ( groupMember.IsSystem ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( Group.FriendlyTypeName ); } btnSave.Visible = !readOnly; if ( readOnly || groupMember.Id == 0) { // hide the ShowMoveDialog if this is readOnly or if this is a new group member (can't move a group member that doesn't exist yet) btnShowMoveDialog.Visible = false; } LoadDropDowns(); ShowRequiredDocumentStatus( rockContext, groupMember, group ); ppGroupMemberPerson.SetValue( groupMember.Person ); ppGroupMemberPerson.Enabled = !readOnly; if ( groupMember.Id != 0 ) { // once a group member record is saved, don't let them change the person ppGroupMemberPerson.Enabled = false; } ddlGroupRole.SetValue( groupMember.GroupRoleId ); ddlGroupRole.Enabled = !readOnly; tbNote.Text = groupMember.Note; tbNote.ReadOnly = readOnly; rblStatus.SetValue( (int)groupMember.GroupMemberStatus ); rblStatus.Enabled = !readOnly; rblStatus.Label = string.Format( "{0} Status", group.GroupType.GroupMemberTerm ); var registrations = new RegistrationRegistrantService( rockContext ) .Queryable().AsNoTracking() .Where( r => r.Registration != null && r.Registration.RegistrationInstance != null && r.GroupMemberId.HasValue && r.GroupMemberId.Value == groupMember.Id ) .Select( r => new { Id = r.Registration.Id, Name = r.Registration.RegistrationInstance.Name } ) .ToList(); if ( registrations.Any() ) { rcwLinkedRegistrations.Visible = true; rptLinkedRegistrations.DataSource = registrations; rptLinkedRegistrations.DataBind(); } else { rcwLinkedRegistrations.Visible = false; } if ( groupMember.Group.RequiredSignatureDocumentTemplate != null ) { fuSignedDocument.Label = groupMember.Group.RequiredSignatureDocumentTemplate.Name; if ( groupMember.Group.RequiredSignatureDocumentTemplate.BinaryFileType != null ) { fuSignedDocument.BinaryFileTypeGuid = groupMember.Group.RequiredSignatureDocumentTemplate.BinaryFileType.Guid; } var signatureDocument = new SignatureDocumentService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.SignatureDocumentTemplateId == groupMember.Group.RequiredSignatureDocumentTemplateId.Value && d.AppliesToPersonAlias != null && d.AppliesToPersonAlias.PersonId == groupMember.PersonId && d.LastStatusDate.HasValue && d.Status == SignatureDocumentStatus.Signed && d.BinaryFile != null ) .OrderByDescending( d => d.LastStatusDate.Value ) .FirstOrDefault(); if ( signatureDocument != null ) { hfSignedDocumentId.Value = signatureDocument.Id.ToString(); fuSignedDocument.BinaryFileId = signatureDocument.BinaryFileId; } fuSignedDocument.Visible = true; } else { fuSignedDocument.Visible = false; } groupMember.LoadAttributes(); phAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls( groupMember, phAttributes, true, string.Empty, true ); if ( readOnly ) { Rock.Attribute.Helper.AddDisplayControls( groupMember, phAttributesReadOnly ); phAttributesReadOnly.Visible = true; phAttributes.Visible = false; } else { phAttributesReadOnly.Visible = false; phAttributes.Visible = true; } var groupHasRequirements = group.GroupRequirements.Any(); pnlRequirements.Visible = groupHasRequirements; btnReCheckRequirements.Visible = groupHasRequirements; ShowGroupRequirementsStatuses(); }
private void LoadState() { int? registrantId = PageParameter( "RegistrantId" ).AsIntegerOrNull(); int? registrationId = PageParameter( "RegistrationId" ).AsIntegerOrNull(); if ( RegistrantState == null ) { var rockContext = new RockContext(); RegistrationRegistrant registrant = null; if ( registrantId.HasValue && registrantId.Value != 0 ) { registrant = new RegistrationRegistrantService( rockContext ) .Queryable( "Registration.RegistrationInstance.RegistrationTemplate.Forms.Fields,Registration.RegistrationInstance.RegistrationTemplate.Fees,PersonAlias.Person,Fees" ).AsNoTracking() .Where( r => r.Id == registrantId.Value ) .FirstOrDefault(); if ( registrant != null && registrant.Registration != null && registrant.Registration.RegistrationInstance != null && registrant.Registration.RegistrationInstance.RegistrationTemplate != null ) { RegistrantState = new RegistrantInfo( registrant, rockContext ); TemplateState = registrant.Registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registrant.Registration.RegistrationInstanceId; lWizardTemplateName.Text = registrant.Registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registrant.Registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registrant.Registration.ToString(); lWizardRegistrantName.Text = registrant.ToString(); } } if ( TemplateState == null && registrationId.HasValue && registrationId.Value != 0 ) { var registration = new RegistrationService( rockContext ) .Queryable( "RegistrationInstance.RegistrationTemplate.Forms.Fields,RegistrationInstance.RegistrationTemplate.Fees" ).AsNoTracking() .Where( r => r.Id == registrationId.Value ) .FirstOrDefault(); if ( registration != null && registration.RegistrationInstance != null && registration.RegistrationInstance.RegistrationTemplate != null ) { TemplateState = registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registration.RegistrationInstanceId; lWizardTemplateName.Text = registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registration.ToString(); lWizardRegistrantName.Text = "New Registrant"; } } if ( TemplateState != null && RegistrantState == null ) { RegistrantState = new RegistrantInfo(); RegistrantState.RegistrationId = registrationId ?? 0; RegistrantState.Cost = TemplateState.Cost; } if ( registrant != null && registrant.PersonAlias != null && registrant.PersonAlias.Person != null ) { ppPerson.SetValue( registrant.PersonAlias.Person ); } else { ppPerson.SetValue( null ); } if ( RegistrantState != null ) { cbCost.Text = RegistrantState.Cost.ToString( "N2" ); } } }
void lbDeleteRegistrant_Click( object sender, EventArgs e ) { var lb = sender as LinkButton; if ( lb != null ) { int? registrantId = lb.ID.Substring( 19 ).AsIntegerOrNull(); if ( registrantId.HasValue ) { var rockContext = new RockContext(); var registrantService = new RegistrationRegistrantService( rockContext ); RegistrationRegistrant registrant = registrantService.Get( registrantId.Value ); if ( registrant != null ) { if ( !UserCanEdit && !registrant.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { mdDeleteWarning.Show( "You are not authorized to delete this registrant.", ModalAlertType.Information ); return; } string errorMessage; if ( !registrantService.CanDelete( registrant, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } var changes = new List<string>(); changes.Add( string.Format( "Deleted Registrant: {0}", registrant.PersonAlias.Person.FullName ) ); rockContext.WrapTransaction( () => { HistoryService.SaveChanges( rockContext, typeof( Registration ), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, changes ); registrantService.Delete( registrant ); rockContext.SaveChanges(); }); } // Reload registration ShowReadonlyDetails( GetRegistration( RegistrationId ) ); } } }
/// <summary> /// Handles the Delete event of the gRegistrants control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gRegistrants_Delete( object sender, RowEventArgs e ) { using ( var rockContext = new RockContext() ) { var registrantService = new RegistrationRegistrantService( rockContext ); var registrant = registrantService.Get( e.RowKeyId ); if ( registrant != null ) { string errorMessage; if ( !registrantService.CanDelete( registrant, out errorMessage ) ) { mdRegistrantsGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } registrantService.Delete( registrant ); rockContext.SaveChanges(); } } BindRegistrantsGrid(); }
private void AddRegistrantToGroup( int registrantId ) { if ( RegistrationTemplateState != null && RegistrationTemplateState.GroupTypeId.HasValue && Registration.GroupId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrant = new RegistrationRegistrantService( rockContext ).Get( registrantId ); if ( registrant != null && registrant.PersonId.HasValue && !registrant.GroupMemberId.HasValue ) { var groupService = new GroupService( rockContext ); var group = groupService.Get( Registration.GroupId.Value ); if ( group != null && group.GroupTypeId == RegistrationTemplateState.GroupTypeId.Value ) { int? groupRoleId = RegistrationTemplateState.GroupMemberRoleId.HasValue ? RegistrationTemplateState.GroupMemberRoleId.Value : group.GroupType.DefaultGroupRoleId; if ( groupRoleId.HasValue ) { var registrantChanges = new List<string>(); var groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService .Queryable().AsNoTracking() .Where( m => m.GroupId == Registration.Group.Id && m.PersonId == registrant.PersonId && m.GroupRoleId == groupRoleId.Value ) .FirstOrDefault(); if ( groupMember == null ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = group.Id; groupMember.PersonId = registrant.PersonId.Value; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = RegistrationTemplateState.GroupMemberStatus; rockContext.SaveChanges(); registrantChanges.Add( string.Format( "Registrant added to {0} group", group.Name ) ); } else { registrantChanges.Add( string.Format( "Registrant group member reference updated to existing person in {0} group", group.Name ) ); } registrant.GroupMemberId = groupMember.Id; rockContext.SaveChanges(); HistoryService.SaveChanges( rockContext, typeof( Registration ), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, registrantChanges, "Registrant: " + CurrentPerson.FullName, null, null ); } } } } } }
/// <summary> /// Saves the registration. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="hasPayment">if set to <c>true</c> [has payment].</param> /// <returns></returns> private Registration SaveRegistration( RockContext rockContext, bool hasPayment ) { var registrationService = new RegistrationService( rockContext ); var registrantService = new RegistrationRegistrantService( rockContext ); var personService = new PersonService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); // variables to keep track of the family that new people should be added to int? singleFamilyId = null; var multipleFamilyGroupIds = new Dictionary<Guid, int>(); var dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); var dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); var familyGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ); var adultRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var childRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var registration = new Registration(); registrationService.Add( registration ); registration.RegistrationInstanceId = RegistrationInstanceState.Id; registration.GroupId = GroupId; registration.FirstName = RegistrationState.FirstName; registration.LastName = RegistrationState.LastName; registration.ConfirmationEmail = RegistrationState.ConfirmationEmail; registration.DiscountCode = RegistrationState.DiscountCode; registration.DiscountAmount = RegistrationState.DiscountAmount; registration.DiscountPercentage = RegistrationState.DiscountPercentage; // If the 'your name' value equals the currently logged in person, use their person alias id if ( CurrentPerson != null && ( CurrentPerson.NickName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) || CurrentPerson.FirstName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ) && CurrentPerson.LastName.Trim().Equals( registration.LastName.Trim(), StringComparison.OrdinalIgnoreCase ) ) { registration.PersonAliasId = CurrentPerson.PrimaryAliasId; } else { // otherwise look for one and one-only match by name/email var personMatches = personService.GetByMatch( registration.FirstName, registration.LastName, registration.ConfirmationEmail ); if ( personMatches.Count() == 1 ) { registration.PersonAliasId = personMatches.First().PrimaryAliasId; } } // If the registration includes a payment, make sure there's an actual person associated to registration if ( hasPayment && !registration.PersonAliasId.HasValue ) { // If a match was not found, create a new person var person = new Person(); person.FirstName = registration.FirstName; person.LastName = registration.LastName; person.IsEmailActive = true; person.Email = registration.ConfirmationEmail; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { person.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { person.RecordStatusValueId = dvcRecordStatus.Id; } registration.PersonAliasId = SavePerson( rockContext, person, Guid.NewGuid(), null, null, adultRoleId, childRoleId, multipleFamilyGroupIds, singleFamilyId ); } // Save the registration ( so we can get an id ) rockContext.SaveChanges(); // If the Registration Instance linkage specified a group, load it now Group group = null; if ( GroupId.HasValue ) { group = new GroupService( rockContext ).Get( GroupId.Value ); } // Get each registrant foreach ( var registrantInfo in RegistrationState.Registrants ) { var changes = new List<string>(); var familyChanges = new List<string>(); Person person = null; // Try to find a matching person based on name and email address string firstName = registrantInfo.GetFirstName( RegistrationTemplate ); string lastName = registrantInfo.GetLastName( RegistrationTemplate ); string email = registrantInfo.GetEmail( RegistrationTemplate ); var personMatches = personService.GetByMatch( firstName, lastName, email ); if ( personMatches.Count() == 1 ) { person = personMatches.First(); } if ( person == null ) { // If a match was not found, create a new person person = new Person(); person.FirstName = firstName; person.LastName = lastName; person.IsEmailActive = true; person.Email = email; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { person.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { person.RecordStatusValueId = dvcRecordStatus.Id; } } int? campusId = null; Location location = null; // Set any of the template's person fields foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.PersonField ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { switch ( field.PersonFieldType ) { case RegistrationPersonFieldType.Campus: { if ( fieldValue != null ) { campusId = fieldValue.ToString().AsIntegerOrNull(); } break; } case RegistrationPersonFieldType.Address: { location = fieldValue.ToString().FromJsonOrNull<Location>(); break; } case RegistrationPersonFieldType.Birthdate: { var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; person.SetBirthDate( fieldValue as DateTime? ); History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth ); History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay ); History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear ); break; } case RegistrationPersonFieldType.Gender: { var newGender = fieldValue.ToString().ConvertToEnumOrNull<Gender>() ?? Gender.Unknown; History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; break; } case RegistrationPersonFieldType.MaritalStatus: { if ( fieldValue != null ) { int? newMaritalStatusId = fieldValue.ToString().AsIntegerOrNull(); History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) ); person.MaritalStatusValueId = newMaritalStatusId; } break; } case RegistrationPersonFieldType.MobilePhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), changes ); break; } case RegistrationPersonFieldType.HomePhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), changes ); break; } case RegistrationPersonFieldType.WorkPhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid(), changes ); break; } } } } // Save the person ( and family if needed ) SavePerson( rockContext, person, registrantInfo.FamilyGuid, campusId, location, adultRoleId, childRoleId, multipleFamilyGroupIds, singleFamilyId ); // Load the person's attributes person.LoadAttributes(); // Set any of the template's person fields foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.PersonAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { string originalValue = person.GetAttributeValue( attribute.Key ); string newValue = fieldValue.ToString(); person.SetAttributeValue( attribute.Key, fieldValue.ToString() ); 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( changes, attribute.Name, formattedOriginalValue, formattedNewValue ); } } } } person.SaveAttributeValues( rockContext ); GroupMember groupMember = null; // If the registration instance linkage specified a group to add registrant to, add them if there not already // part of that group if ( group != null ) { groupMember = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault(); if ( groupMember == null && group.GroupType.DefaultGroupRoleId.HasValue ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = group.Id; groupMember.PersonId = person.Id; if ( RegistrationTemplate.GroupTypeId.HasValue && RegistrationTemplate.GroupTypeId == group.GroupTypeId && RegistrationTemplate.GroupMemberRoleId.HasValue ) { groupMember.GroupRoleId = RegistrationTemplate.GroupMemberRoleId.Value; groupMember.GroupMemberStatus = RegistrationTemplate.GroupMemberStatus; } else { groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value; groupMember.GroupMemberStatus = GroupMemberStatus.Active; } } rockContext.SaveChanges(); // Set any of the template's group member attributes groupMember.LoadAttributes(); foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.GroupMemberAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { groupMember.SetAttributeValue( attribute.Key, fieldValue.ToString() ); } } } groupMember.SaveAttributeValues( rockContext ); } var registrant = new RegistrationRegistrant(); registrantService.Add( registrant ); registrant.RegistrationId = registration.Id; registrant.PersonAliasId = person.PrimaryAliasId; registrant.Cost = registrantInfo.Cost; registrant.GroupMemberId = groupMember != null ? groupMember.Id : (int?)null; // Add or Update fees foreach ( var feeValue in registrantInfo.FeeValues.Where( f => f.Value != null ) ) { foreach ( var uiFee in feeValue.Value ) { var fee = new RegistrationRegistrantFee(); registrant.Fees.Add( fee ); fee.RegistrationTemplateFeeId = feeValue.Key; fee.Option = uiFee.Option; fee.Quantity = uiFee.Quantity; fee.Cost = uiFee.Cost; } } rockContext.SaveChanges(); // Set any of the templat's registrant attributes registrant.LoadAttributes(); foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.RegistrationAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() ); } } registrant.SaveAttributeValues( rockContext ); } } return registration; }
/// <summary> /// Shows the view. /// </summary> /// <param name="groupId">The group identifier.</param> protected void ShowView(int groupId) { pnlView.Visible = true; hfGroupId.Value = groupId.ToString(); var rockContext = new RockContext(); var group = new GroupService(rockContext).Get(groupId); if (group == null) { pnlView.Visible = false; return; } group.LoadAttributes(rockContext); var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid()); if (this.GetAttributeValue("SetPageTitletoOpportunityTitle").AsBoolean()) { RockPage.Title = group.GetAttributeValue("OpportunityTitle"); RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle"); RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle"); } var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("Block", this.BlockCache); mergeFields.Add("Group", group); // Left Sidebar var photoGuid = group.GetAttributeValue("OpportunityPhoto").AsGuidOrNull(); imgOpportunityPhoto.Visible = photoGuid.HasValue; imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid); var groupMembers = group.Members.ToList(); foreach (var gm in groupMembers) { gm.LoadAttributes(rockContext); } // only show the 'Donate to a Participant' button if there are participants that are taking contribution requests btnDonateToParticipant.Visible = groupMembers.Where(a => !a.GetAttributeValue("DisablePublicContributionRequests").AsBoolean()).Any(); if (!string.IsNullOrWhiteSpace(opportunityType.GetAttributeValue("core_DonateButtonText"))) { btnDonateToParticipant.Text = opportunityType.GetAttributeValue("core_DonateButtonText"); } RegistrationInstance registrationInstance = null; var registrationInstanceId = group.GetAttributeValue("RegistrationInstance").AsIntegerOrNull(); if (registrationInstanceId.HasValue) { registrationInstance = new RegistrationInstanceService(rockContext).Get(registrationInstanceId.Value); } mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage")); if (registrationInstance != null) { mergeFields.Add("RegistrationInstance", registrationInstance); mergeFields.Add("RegistrationInstanceLinkages", registrationInstance.Linkages); // populate merge fields for Registration Counts var maxRegistrantCount = 0; var currentRegistrationCount = 0; if (registrationInstance.MaxAttendees != 0) { maxRegistrantCount = registrationInstance.MaxAttendees; } currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking() .Where(r => r.Registration.RegistrationInstanceId == registrationInstance.Id && r.OnWaitList == false) .Count(); mergeFields.Add("CurrentRegistrationCount", currentRegistrationCount); if (maxRegistrantCount != 0) { mergeFields.Add("MaxRegistrantCount", maxRegistrantCount); mergeFields.Add("RegistrationSpotsAvailable", maxRegistrantCount - currentRegistrationCount); } } string sidebarLavaTemplate = this.GetAttributeValue("SidebarLavaTemplate"); lSidebarHtml.Text = sidebarLavaTemplate.ResolveMergeFields(mergeFields); SetActiveTab("Details"); // Top Main string summaryLavaTemplate = this.GetAttributeValue("SummaryLavaTemplate"); lMainTopContentHtml.Text = summaryLavaTemplate.ResolveMergeFields(mergeFields); // only show the leader toolbox link of the currentperson has a leader role in the group btnLeaderToolbox.Visible = group.Members.Any(a => a.PersonId == this.CurrentPersonId && a.GroupRole.IsLeader); //// Participant Actions // only show if the current person is a group member var groupMember = group.Members.FirstOrDefault(a => a.PersonId == this.CurrentPersonId); if (groupMember != null) { hfGroupMemberId.Value = groupMember.Id.ToString(); pnlParticipantActions.Visible = true; } else { hfGroupMemberId.Value = null; pnlParticipantActions.Visible = false; } mergeFields.Add("GroupMember", groupMember); // Progress if (groupMember != null && pnlParticipantActions.Visible) { var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>(); var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable() .Where(d => d.EntityTypeId == entityTypeIdGroupMember && d.EntityId == groupMember.Id) .Sum(a => (decimal?)a.Amount) ?? 0.00M; var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); if (!individualFundraisingGoal.HasValue) { individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); } var amountLeft = individualFundraisingGoal - contributionTotal; var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100; mergeFields.Add("AmountLeft", amountLeft); mergeFields.Add("PercentMet", percentMet); var queryParams = new Dictionary <string, string>(); queryParams.Add("GroupId", hfGroupId.Value); queryParams.Add("GroupMemberId", hfGroupMemberId.Value); mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams)); mergeFields.Add("ParticipantPageUrl", LinkedPageUrl("ParticipantPage", queryParams)); string makeDonationButtonText = null; if (groupMember.PersonId == this.CurrentPersonId) { makeDonationButtonText = "Make Payment"; } else { makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType); } mergeFields.Add("MakeDonationButtonText", makeDonationButtonText); var participantLavaTemplate = this.GetAttributeValue("ParticipantLavaTemplate"); lParticipantActionsHtml.Text = participantLavaTemplate.ResolveMergeFields(mergeFields); } // Tab:Details lDetailsHtml.Text = group.GetAttributeValue("OpportunityDetails"); btnDetailsTab.Text = string.Format("{0} Details", opportunityType); // Tab:Updates liUpdatesTab.Visible = false; var updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull(); if (updatesContentChannelGuid.HasValue) { var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value); if (contentChannel != null) { liUpdatesTab.Visible = true; string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate"); var contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList(); mergeFields.Add("ContentChannelItems", contentChannelItems); lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields); btnUpdatesTab.Text = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count()); } } // Tab:Comments var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid()); if (noteType != null) { notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> { noteType }); } notesCommentsTimeline.NoteOptions.EntityId = groupId; // show the Add button on comments for any logged in person notesCommentsTimeline.AddAllowed = true; var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean(); btnCommentsTab.Text = string.Format("Comments ({0})", notesCommentsTimeline.NoteCount); if (CurrentPerson == null) { notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0); lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0; liCommentsTab.Visible = enableCommenting; btnLoginToComment.Visible = enableCommenting; } else { lNoLoginNoCommentsYet.Visible = false; notesCommentsTimeline.Visible = enableCommenting; liCommentsTab.Visible = enableCommenting; btnLoginToComment.Visible = false; } // if btnDetailsTab is the only visible tab, hide the tab since there is nothing else to tab to if (!liCommentsTab.Visible && !liUpdatesTab.Visible) { tlTabList.Visible = false; } }