/// <summary> /// Handles the Click event of the btnEditPreferences 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 btnEditProfile_Click(object sender, EventArgs e) { pnlMain.Visible = false; pnlEditPreferences.Visible = true; var rockContext = new RockContext(); var groupMember = new GroupMemberService(rockContext).Get(hfGroupMemberId.Value.AsInteger()); if (groupMember != null) { var person = groupMember.Person; imgProfilePhoto.BinaryFileId = person.PhotoId; imgProfilePhoto.NoPictureUrl = Person.GetPersonNoPictureUrl(person, 200, 200); groupMember.LoadAttributes(rockContext); groupMember.Group.LoadAttributes(rockContext); var opportunityType = DefinedValueCache.Get(groupMember.Group.GetAttributeValue("OpportunityType").AsGuid()); lProfileTitle.Text = string.Format( "{0} Profile for {1}", RockFilters.Possessive(groupMember.Person.FullName), groupMember.Group.GetAttributeValue("OpportunityTitle")); var dateRange = DateRangePicker.CalculateDateRangeFromDelimitedValues(groupMember.Group.GetAttributeValue("OpportunityDateRange")); lDateRange.Text = dateRange.ToString("MMMM dd, yyyy"); CreateDynamicControls(groupMember); } }
/// <summary> /// Handles the Click event of the btnNext 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 btnNext_Click(object sender, EventArgs e) { var groupMemberId = ddlParticipant.SelectedValue.AsIntegerOrNull(); if (groupMemberId.HasValue) { var rockContext = new RockContext(); var groupMember = new GroupMemberService(rockContext).Get(groupMemberId.Value); if (groupMember != null) { var queryParams = new Dictionary <string, string>(); queryParams.Add("GroupMemberId", groupMemberId.ToString()); groupMember.LoadAttributes(rockContext); groupMember.Group.LoadAttributes(rockContext); var financialAccount = new FinancialAccountService(rockContext).Get(groupMember.Group.GetAttributeValue("FinancialAccount").AsGuid()); if (financialAccount != null) { queryParams.Add("AccountIds", financialAccount.Id.ToString()); } if (groupMember.Group.GetAttributeValue("CapFundraisingAmount").AsBoolean()) { var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>(); var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable() .Where(d => d.EntityTypeId == entityTypeIdGroupMember && d.EntityId == groupMemberId) .Sum(a => (decimal?)a.Amount) ?? 0.00M; var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); if (!individualFundraisingGoal.HasValue) { individualFundraisingGoal = groupMember.Group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); } var amountLeft = individualFundraisingGoal - contributionTotal; queryParams.Add("AmountLimit", amountLeft.ToString()); } NavigateToLinkedPage("TransactionEntryPage", queryParams); } } }
/// <summary> /// Handles the SelectItem event of the gpMoveGroupMember 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 gpMoveGroupMember_SelectItem(object sender, EventArgs e) { var rockContext = new RockContext(); var destGroup = new GroupService(rockContext).Get(gpMoveGroupMember.SelectedValue.AsInteger()); if (destGroup != null) { var destTempGroupMember = new GroupMember { Group = destGroup, GroupId = destGroup.Id }; destTempGroupMember.LoadAttributes(rockContext); var destGroupMemberAttributes = destTempGroupMember.Attributes; var groupMember = new GroupMemberService(rockContext).Get(hfGroupMemberId.Value.AsInteger()); groupMember.LoadAttributes(); var currentGroupMemberAttributes = groupMember.Attributes; var lostAttributes = currentGroupMemberAttributes.Where(a => !destGroupMemberAttributes.Any(d => d.Key == a.Key && d.Value.FieldTypeId == a.Value.FieldTypeId)); nbMoveGroupMemberWarning.Visible = lostAttributes.Any(); nbMoveGroupMemberWarning.Text = "The destination group does not have the same group member attributes as the source. Some loss of data may occur"; if (destGroup.Id == groupMember.GroupId) { grpMoveGroupMember.Visible = false; nbMoveGroupMemberWarning.Visible = true; nbMoveGroupMemberWarning.Text = "The destination group is the same as the current group"; } else { grpMoveGroupMember.Visible = true; grpMoveGroupMember.GroupTypeId = destGroup.GroupTypeId; grpMoveGroupMember.GroupRoleId = destGroup.GroupType.DefaultGroupRoleId; } } else { nbMoveGroupMemberWarning.Visible = false; grpMoveGroupMember.Visible = false; } }
/// <summary> /// Shows the view. /// </summary> /// <param name="groupId">The group identifier.</param> /// <param name="groupMemberId">The group member identifier.</param> protected void ShowView(int groupId, int groupMemberId) { pnlView.Visible = true; pnlMain.Visible = true; pnlEditPreferences.Visible = false; hfGroupId.Value = groupId.ToString(); hfGroupMemberId.Value = groupMemberId.ToString(); var rockContext = new RockContext(); var group = new GroupService(rockContext).Get(groupId); if (group == null) { pnlView.Visible = false; return; } var groupMember = new GroupMemberService(rockContext).Queryable().Where(a => a.GroupId == groupId && a.Id == groupMemberId).FirstOrDefault(); if (groupMember == null) { pnlView.Visible = false; return; } group.LoadAttributes(rockContext); // set page title to the trip name 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("Group", group); groupMember.LoadAttributes(rockContext); mergeFields.Add("GroupMember", groupMember); // Left Top Sidebar var photoGuid = group.GetAttributeValue("OpportunityPhoto"); imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid); // Top Main string profileLavaTemplate = this.GetAttributeValue("ProfileLavaTemplate"); if (groupMember.PersonId == this.CurrentPersonId) { // show a warning about missing Photo or Intro if the current person is viewing their own profile var warningItems = new List <string>(); if (!groupMember.Person.PhotoId.HasValue) { warningItems.Add("photo"); } if (groupMember.GetAttributeValue("PersonalOpportunityIntroduction").IsNullOrWhiteSpace()) { warningItems.Add("personal opportunity introduction"); } nbProfileWarning.Text = "<stong>Tip!</strong> Edit your profile to add a " + warningItems.AsDelimited(", ", " and ") + "."; nbProfileWarning.Visible = warningItems.Any(); } else { nbProfileWarning.Visible = false; } btnEditProfile.Visible = groupMember.PersonId == this.CurrentPersonId; lMainTopContentHtml.Text = profileLavaTemplate.ResolveMergeFields(mergeFields); bool disablePublicContributionRequests = groupMember.GetAttributeValue("DisablePublicContributionRequests").AsBoolean(); // only show Contribution stuff if the current person is the participant and contribution requests haven't been disabled bool showContributions = !disablePublicContributionRequests && (groupMember.PersonId == this.CurrentPersonId); btnContributionsTab.Visible = showContributions; // Progress var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>(); var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable() .Where(d => d.EntityTypeId == entityTypeIdGroupMember && d.EntityId == groupMemberId) .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)); var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid()); 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 progressLavaTemplate = this.GetAttributeValue("ProgressLavaTemplate"); lProgressHtml.Text = progressLavaTemplate.ResolveMergeFields(mergeFields); // set text on the return button btnMainPage.Text = opportunityType.Value + " Page"; // Tab:Updates btnUpdatesTab.Visible = false; bool showContentChannelUpdates = false; var updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull(); if (updatesContentChannelGuid.HasValue) { var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value); if (contentChannel != null) { showContentChannelUpdates = true; // only show the UpdatesTab if there is another Tab option btnUpdatesTab.Visible = btnContributionsTab.Visible; 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()); } } if (showContentChannelUpdates) { SetActiveTab("Updates"); } else if (showContributions) { SetActiveTab("Contributions"); } else { SetActiveTab(""); } // Tab: Contributions BindContributionsGrid(); // Tab:Comments var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid()); if (noteType != null) { notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> { noteType }); } notesCommentsTimeline.NoteOptions.EntityId = groupMember.Id; // show the Add button on comments for any logged in person notesCommentsTimeline.AddAllowed = true; var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean(); if (CurrentPerson == null) { notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0); lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0; pnlComments.Visible = enableCommenting; btnLoginToComment.Visible = enableCommenting; } else { lNoLoginNoCommentsYet.Visible = false; notesCommentsTimeline.Visible = enableCommenting; pnlComments.Visible = enableCommenting; btnLoginToComment.Visible = false; } // if btnContributionsTab is the only visible tab, hide the tab since there is nothing else to tab to if (!btnUpdatesTab.Visible && btnContributionsTab.Visible) { SetActiveTab("Contributions"); btnContributionsTab.Visible = false; } }
/// <summary> /// Handles the Click event of the btnSaveEditPreferences control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSaveEditPreferences_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var groupMember = new GroupMemberService(rockContext).Get(hfGroupMemberId.Value.AsInteger()); var personService = new PersonService(rockContext); var person = personService.Get(groupMember.PersonId); int?orphanedPhotoId = null; if (person.PhotoId != imgProfilePhoto.BinaryFileId) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgProfilePhoto.BinaryFileId; // add or update the Photo Verify group to have this person as Pending since the photo was changed or deleted using (var photoRequestRockContext = new RockContext()) { GroupMemberService groupMemberService = new GroupMemberService(photoRequestRockContext); Group photoRequestGroup = new GroupService(photoRequestRockContext).Get(Rock.SystemGuid.Group.GROUP_PHOTO_REQUEST.AsGuid()); var photoRequestGroupMember = groupMemberService.Queryable().Where(a => a.GroupId == photoRequestGroup.Id && a.PersonId == person.Id).FirstOrDefault(); if (photoRequestGroupMember == null) { photoRequestGroupMember = new GroupMember(); photoRequestGroupMember.GroupId = photoRequestGroup.Id; photoRequestGroupMember.PersonId = person.Id; photoRequestGroupMember.GroupRoleId = photoRequestGroup.GroupType.DefaultGroupRoleId ?? -1; groupMemberService.Add(photoRequestGroupMember); } photoRequestGroupMember.GroupMemberStatus = GroupMemberStatus.Pending; photoRequestRockContext.SaveChanges(); } } // Save the GroupMember Attributes groupMember.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phGroupMemberAttributes, groupMember); // Save selected Person Attributes (The ones picked in Block Settings) var personAttributes = this.GetAttributeValue("PersonAttributes").SplitDelimitedValues().AsGuidList().Select(a => AttributeCache.Get(a)); if (personAttributes.Any()) { person.LoadAttributes(rockContext); foreach (var personAttribute in personAttributes) { Control attributeControl = phPersonAttributes.FindControl(string.Format("attribute_field_{0}", personAttribute.Id)); if (attributeControl != null) { // Save Attribute value to the database string newValue = personAttribute.FieldType.Field.GetEditValue(attributeControl, personAttribute.QualifierValues); Rock.Attribute.Helper.SaveAttributeValue(person, personAttribute, newValue, rockContext); } } } // Save everything else to the database in a db transaction rockContext.WrapTransaction(() => { rockContext.SaveChanges(); groupMember.SaveAttributeValues(rockContext); if (orphanedPhotoId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(orphanedPhotoId.Value); if (binaryFile != null) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if (imgProfilePhoto.CropBinaryFileId.HasValue) { if (imgProfilePhoto.CropBinaryFileId != person.PhotoId) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(imgProfilePhoto.CropBinaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } } }); ShowView(hfGroupId.Value.AsInteger(), hfGroupMemberId.Value.AsInteger()); }
/// <summary> /// Runs the process workflow and generated the dynamic controls /// </summary> private void ShowPersonCheckin() { phClasses.Controls.Clear(); if (CurrentCheckInState == null) { NavigateToPreviousPage(); return; } pnlNotFound.Visible = false; pnlSearch.Visible = false; pnlCheckin.Visible = true; var person = CurrentCheckInState.CheckIn.Families.Where(f => f.Selected).SelectMany(f => f.People).Where(p => p.Selected).FirstOrDefault(); if (person == null) { maError.Show("There was an error processing your request.", ModalAlertType.Warning); return; } ltNickName.Text = person.Person.NickName; var groups = GetMembershipGroups(); if (!groups.Any()) { maError.Show("No group fitness groups found.", ModalAlertType.Warning); return; } List <string> errors = new List <string>(); try { bool test = ProcessActivity(GetAttributeValue("ProcessActivity"), out errors); } catch { NavigateToPreviousPage(); Response.End(); return; } GroupMemberService groupMemberService = new GroupMemberService(_rockContext); int groupCount = 0; int checkinCount = 0; foreach (var group in groups) { var groupMember = new GroupMemberService(_rockContext).GetByGroupIdAndPersonId(group.Id, person.Person.Id).FirstOrDefault(); if (groupMember != null) { Panel pnlWell = new Panel(); pnlWell.CssClass = "well"; phClasses.Controls.Add(pnlWell); groupMember.LoadAttributes(); int sessions = groupMember.GetAttributeValue(_groupSessionsKey).AsInteger(); if (sessions > 0) { var checkinGroups = CurrentCheckInState.CheckIn.CurrentPerson .GroupTypes.SelectMany(gt => gt.Groups) .Where(g => g.Group.GetAttributeValue("Group").AsGuid() == group.Guid) .ToList(); if (checkinGroups.Any()) { Literal sessionCount = new Literal(); sessionCount.Text = string.Format("<h2>You have {0} {1} sessions remaining</h2>", sessions, group.Name); pnlWell.Controls.Add(sessionCount); foreach (var chGroup in checkinGroups) { foreach (var location in chGroup.Locations) { foreach (var schedule in location.Schedules) { Panel pnlClass = new Panel(); pnlClass.Style.Add("margin", "5px"); pnlWell.Controls.Add(pnlClass); BootstrapButton btnSelect = new BootstrapButton(); if (schedule.Selected) { btnSelect.Text = "<i class='fa fa-check-square-o'></i>"; btnSelect.CssClass = "btn btn-success btn-lg"; } else { btnSelect.Text = "<i class='fa fa-square-o'></i>"; btnSelect.CssClass = "btn btn-default btn-lg"; } btnSelect.ID = "s" + chGroup.Group.Id.ToString() + location.Location.Id.ToString() + schedule.Schedule.Id.ToString(); btnSelect.Click += (s, e) => { ToggleClass(chGroup, location, schedule, schedule.Selected); }; pnlWell.Controls.Add(btnSelect); Literal ltClassName = new Literal(); ltClassName.Text = string.Format("<span class='classText'> {0}: {1} in {2}</span>", chGroup.Group.Name, schedule.Schedule.Name, location.Location.Name); pnlWell.Controls.Add(ltClassName); checkinCount++; } } } } else { Literal ltNoActiveSessions = new Literal(); ltNoActiveSessions.Text = string.Format("<h2>You have {0} {1} sessions remaining, but there are no active check-ins.</h2>", sessions, group.Name); pnlWell.Controls.Add(ltNoActiveSessions); } } else { Literal ltNoSessions = new Literal(); ltNoSessions.Text = string.Format("<h2>You have no {0} sessions remaining</h2>", group.Name); pnlWell.Controls.Add(ltNoSessions); } groupCount++; } } //If the person is not a member of any fitness groups don't show a not found if (groupCount == 0) { ShowPersonNotFound(); StartTimeout(); return; } //If the person does not have any groups to check into send them back after a time if (checkinCount == 0) { StartTimeout(); } StartTimeout(); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> /// <param name="groupId">The group id.</param> public void ShowDetail(string itemKey, int itemKeyValue, int?groupId) { pnlDetails.Visible = false; if (!itemKey.Equals("groupMemberId")) { return; } GroupMember groupMember = null; if (!itemKeyValue.Equals(0)) { groupMember = new GroupMemberService().Get(itemKeyValue); groupMember.LoadAttributes(); } else { // only create a new one if parent was specified if (groupId != null) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = groupId.Value; groupMember.Group = new GroupService().Get(groupMember.GroupId); groupMember.GroupRoleId = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0; groupMember.GroupMemberStatus = GroupMemberStatus.Active; } } if (groupMember == null) { return; } pnlDetails.Visible = true; hfGroupId.Value = groupMember.GroupId.ToString(); hfGroupMemberId.Value = groupMember.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; nbEditModeMessage.Text = string.Empty; if (!IsUserAuthorized("Edit")) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Group.FriendlyTypeName); } if (groupMember.IsSystem) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(Group.FriendlyTypeName); } if (readOnly) { btnEdit.Visible = false; ShowReadonlyDetails(groupMember); } else { btnEdit.Visible = true; if (groupMember.Id > 0) { ShowReadonlyDetails(groupMember); } else { ShowEditDetails(groupMember); } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> /// <param name="groupId">The group id.</param> public void ShowDetail(string itemKey, int itemKeyValue, int?groupId) { if (!itemKey.Equals("GroupMemberId")) { return; } var rockContext = new RockContext(); GroupMember groupMember = null; if (!itemKeyValue.Equals(0)) { groupMember = new GroupMemberService(rockContext).Get(itemKeyValue); groupMember.LoadAttributes(); } else { // only create a new one if parent was specified if (groupId.HasValue) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = groupId.Value; groupMember.Group = new GroupService(rockContext).Get(groupMember.GroupId); groupMember.GroupRoleId = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0; groupMember.GroupMemberStatus = GroupMemberStatus.Active; } } if (groupMember == null) { return; } hfGroupId.Value = groupMember.GroupId.ToString(); hfGroupMemberId.Value = groupMember.Id.ToString(); // render UI based on Authorized and IsSystem bool readOnly = false; var group = groupMember.Group; if (!string.IsNullOrWhiteSpace(group.GroupType.IconCssClass)) { lGroupIconHtml.Text = string.Format("<i class='{0}' ></i>", group.GroupType.IconCssClass); } else { lGroupIconHtml.Text = string.Empty; } if (groupMember.Id.Equals(0)) { lReadOnlyTitle.Text = ActionTitle.Add(groupMember.Group.GroupType.GroupTerm + " " + groupMember.Group.GroupType.GroupMemberTerm).FormatAsHtmlTitle(); } else { lReadOnlyTitle.Text = groupMember.Person.FullName.FormatAsHtmlTitle(); } // user has to have EDIT Auth to both the Block and 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; LoadDropDowns(); ppGroupMemberPerson.SetValue(groupMember.Person); ppGroupMemberPerson.Enabled = !readOnly; ddlGroupRole.SetValue(groupMember.GroupRoleId); ddlGroupRole.Enabled = !readOnly; rblStatus.SetValue((int)groupMember.GroupMemberStatus); rblStatus.Enabled = !readOnly; rblStatus.Label = string.Format("{0} Status", group.GroupType.GroupMemberTerm); groupMember.LoadAttributes(); phAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls(groupMember, phAttributes, true, "", true); if (readOnly) { Rock.Attribute.Helper.AddDisplayControls(groupMember, phAttributesReadOnly); phAttributesReadOnly.Visible = true; phAttributes.Visible = false; } else { phAttributesReadOnly.Visible = false; phAttributes.Visible = true; } }
/// <summary> /// Builds the content to send to the client. /// </summary> /// <returns>A string containing XAML content.</returns> private string BuildContent() { using (var rockContext = new RockContext()) { var memberGuid = RequestContext.GetPageParameter(PageParameterKeys.GroupMemberGuid).AsGuid(); var member = new GroupMemberService(rockContext).Get(memberGuid); if (member == null) { return(@"<StackLayout> <Rock:NotificationBox Text=""Group Member not Found."" NotificationType=""Error"" /> </StackLayout>"); } // // Verify the user has access to view the group. // if (!member.Group.IsAuthorized(Authorization.VIEW, RequestContext.CurrentPerson)) { return(@"<StackLayout> <Rock:NotificationBox Text=""You do not have permission to view members of this group."" NotificationType=""Error"" /> </StackLayout>"); } var mergeFields = RequestContext.GetCommonMergeFields(); mergeFields.Add("Member", member); mergeFields.Add("GroupMemberEditPage", GroupMemberEditPage.HasValue ? GroupMemberEditPage.ToString() : string.Empty); // // Add in all attributes/values that the user is allowed to see. // member.LoadAttributes(rockContext); var attributes = member.Attributes .Where(a => a.Value.IsAuthorized(Authorization.VIEW, RequestContext.CurrentPerson)) .Select(a => { var rawValue = member.GetAttributeValue(a.Value.Key); return(new { a.Value.Key, a.Value.Name, Value = rawValue, FormattedValue = a.Value.FieldType.Field.FormatValue(null, a.Value.EntityTypeId, member.Id, rawValue, a.Value.QualifierValues, false) }); }) .OrderBy(a => a.Name) .ToList(); mergeFields.Add("VisibleAttributes", attributes); // // Add collection of allowed security actions. // var securityActions = new Dictionary <string, object> { { "View", member.Group.IsAuthorized(Authorization.VIEW, RequestContext.CurrentPerson) }, { "ManageMembers", member.Group.IsAuthorized(Authorization.MANAGE_MEMBERS, RequestContext.CurrentPerson) }, { "Edit", member.Group.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) }, { "Administrate", member.Group.IsAuthorized(Authorization.ADMINISTRATE, RequestContext.CurrentPerson) } }; mergeFields.Add("AllowedActions", securityActions); return(Template.ResolveMergeFields(mergeFields)); } }
/// <summary> /// Saves the group member. /// </summary> /// <param name="parameters">The parameters.</param> /// <returns>The response to send back to the client.</returns> private CallbackResponse SaveGroupMember(Dictionary <string, object> parameters) { using (var rockContext = new RockContext()) { var groupMemberGuid = RequestContext.GetPageParameter(PageParameterKeys.GroupMemberGuid).AsGuid(); var member = new GroupMemberService(rockContext).Get(groupMemberGuid); if (member == null || (!member.Group.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !member.Group.IsAuthorized(Authorization.MANAGE_MEMBERS, RequestContext.CurrentPerson))) { return(new CallbackResponse { Error = "You are not authorized to edit members of this group." }); } member.LoadAttributes(rockContext); // // Verify and save all the property values. // if (AllowRoleChange) { member.GroupRoleId = (( string )parameters["role"]).AsInteger(); } if (AllowMemberStatusChange) { member.GroupMemberStatus = (( string )parameters["memberstatus"]).ConvertToEnum <GroupMemberStatus>(); } if (AllowNoteEdit) { member.Note = ( string )parameters["note"]; } // // Save all the attribute values. // MobileHelper.UpdateEditAttributeValues(member, parameters, GetEditableAttributes(member)); // // Save all changes to database. // rockContext.WrapTransaction(() => { rockContext.SaveChanges(); member.SaveAttributeValues(rockContext); }); } if (MemberDetailPage.HasValue) { return(new CallbackResponse { Command = "ReplacePage", CommandParameter = $"{MemberDetailPage}?GroupMemberGuid={RequestContext.GetPageParameter( PageParameterKeys.GroupMemberGuid )}" }); } else { return(new CallbackResponse { Command = "PopPage", CommandParameter = "true" }); } }
/// <summary> /// Builds the content to be displayed on the block. /// </summary> /// <returns>A string containing the XAML content to be displayed.</returns> private string BuildContent() { string content = @" <StackLayout> ##HEADER## ##FIELDS## <Rock:Validator x:Name=""vForm""> ##VALIDATORS## </Rock:Validator> <Rock:NotificationBox x:Name=""nbError"" NotificationType=""Error"" /> <Button StyleClass=""btn,btn-primary"" Text=""Save"" Margin=""24 0 0 0"" Command=""{Binding Callback}""> <Button.CommandParameter> <Rock:CallbackParameters Name=""Save"" Validator=""{x:Reference vForm}"" Notification=""{x:Reference nbError}""> ##PARAMETERS## </Rock:CallbackParameters> </Button.CommandParameter> </Button> <Button StyleClass=""btn,btn-link"" Text=""Cancel"" ##CANCEL## /> </StackLayout>"; var groupMemberGuid = RequestContext.GetPageParameter(PageParameterKeys.GroupMemberGuid).AsGuid(); var parameters = new Dictionary <string, string>(); string fieldsContent; using (var rockContext = new RockContext()) { var member = new GroupMemberService(rockContext).Get(groupMemberGuid); if (member == null) { return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"We couldn't find that member.\" NotificationType=\"Error\" />"); } else if (!member.Group.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !member.Group.IsAuthorized(Authorization.MANAGE_MEMBERS, RequestContext.CurrentPerson)) { return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"You are not authorized to edit members of this group.\" NotificationType=\"Error\" />"); } member.LoadAttributes(rockContext); var attributes = GetEditableAttributes(member); fieldsContent = BuildCommonFields(member, parameters); fieldsContent += MobileHelper.GetEditAttributesXaml(member, attributes, parameters); } var validatorsContent = parameters.Keys.Select(a => $"<x:Reference>{a}</x:Reference>"); var parametersContent = parameters.Select(a => $"<Rock:Parameter Name=\"{a.Key}\" Value=\"{{Binding {a.Value}, Source={{x:Reference {a.Key}}}}}\" />"); if (MemberDetailPage.HasValue) { content = content.Replace("##CANCEL##", $"Command=\"{{Binding ReplacePage}}\" CommandParameter=\"{MemberDetailPage}?GroupMemberGuid={groupMemberGuid}\""); } else { content = content.Replace("##CANCEL##", "Command=\"{Binding PopPage}\""); } if (ShowHeader) { content = content.Replace("##HEADER##", @"<Label StyleClass=""h2"" Text=""Group Member Edit"" /> <Rock:Divider />"); } else { content = content.Replace("##HEADER##", string.Empty); } return(content.Replace("##FIELDS##", fieldsContent) .Replace("##VALIDATORS##", string.Join(string.Empty, validatorsContent)) .Replace("##PARAMETERS##", string.Join(string.Empty, parametersContent))); }
public BlockActionResult SaveMember(Guid groupMemberGuid, MemberDataViewModel groupMemberData) { using (var rockContext = new RockContext()) { var member = new GroupMemberService(rockContext).Get(groupMemberGuid); if (member == null || (!member.Group.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !member.Group.IsAuthorized(Authorization.MANAGE_MEMBERS, RequestContext.CurrentPerson))) { return(ActionBadRequest("You are not authorized to edit members of this group.")); } member.LoadAttributes(rockContext); // Verify and save the member role. if (AllowRoleChange) { if (!groupMemberData.RoleGuid.HasValue) { return(ActionBadRequest("Invalid data.")); } var groupRole = GroupTypeCache.Get(member.Group.GroupTypeId) .Roles .FirstOrDefault(r => r.Guid == groupMemberData.RoleGuid.Value); if (groupRole == null) { return(ActionBadRequest("Invalid data.")); } member.GroupRoleId = groupRole.Id; } // Verify and save the member status. if (AllowMemberStatusChange) { if (!groupMemberData.MemberStatus.HasValue) { return(ActionBadRequest("Invalid data.")); } member.GroupMemberStatus = groupMemberData.MemberStatus.Value; } // Verify and save the note. if (AllowNoteEdit) { if (groupMemberData.Note == null) { return(ActionBadRequest("Invalid data.")); } member.Note = groupMemberData.Note; } // Save all the attribute values. if (groupMemberData.FieldValues != null) { member.LoadAttributes(); var attributes = GetEditableAttributes(member); foreach (var attribute in attributes) { if (!groupMemberData.FieldValues.TryGetValue(attribute.Key, out var value)) { continue; } member.SetAttributeValue(attribute.Key, value); } } // Save all changes to database. rockContext.WrapTransaction(() => { rockContext.SaveChanges(); member.SaveAttributeValues(rockContext); }); return(ActionOk()); } }
public BlockActionResult GetMemberData(Guid groupMemberGuid) { using (var rockContext = new RockContext()) { var member = new GroupMemberService(rockContext) .Queryable() .Include(m => m.Group.GroupType) .FirstOrDefault(m => m.Guid == groupMemberGuid); if (member == null) { return(ActionBadRequest("We couldn't find that member.")); } else if (!member.Group.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !member.Group.IsAuthorized(Authorization.MANAGE_MEMBERS, RequestContext.CurrentPerson)) { return(ActionBadRequest("You are not authorized to edit members of this group.")); } // Get the header content to send down. string headerContent = ShowHeader ? "<StackLayout><Label StyleClass=\"h2\" Text=\"Group Member Edit\" /><Rock:Divider /></StackLayout>" : string.Empty; // Get all the attribute fields. member.LoadAttributes(rockContext); var fields = GetEditableAttributes(member) .Select(a => new MobileField { AttributeGuid = a.Guid, Key = a.Key, Title = a.Name, IsRequired = a.IsRequired, ConfigurationValues = a.QualifierValues.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Value), FieldTypeGuid = a.FieldType.Guid, #pragma warning disable CS0618 // Type or member is obsolete: Required for Mobile Shell v2 support RockFieldType = a.FieldType.Class, #pragma warning restore CS0618 // Type or member is obsolete: Required for Mobile Shell v2 support Value = member.GetAttributeValue(a.Key) }) .ToList(); // Get all the roles that can be set for this member. var roles = GroupTypeCache.Get(member.Group.GroupTypeId) .Roles .OrderBy(r => r.Order) .Select(r => new ListItemViewModel { Value = r.Guid.ToString(), Text = r.Name }) .ToList(); // Configure the delete/archive options. bool canDelete = EnableDelete; bool canArchive = false; if (canDelete) { var groupMemberHistoricalService = new GroupMemberHistoricalService(rockContext); var roleIdsWithGroupSync = member.Group.GroupSyncs.Select(a => a.GroupTypeRoleId).ToList(); if (roleIdsWithGroupSync.Contains(member.GroupRoleId)) { canDelete = false; } else if (member.Group.GroupType.EnableGroupHistory == true && groupMemberHistoricalService.Queryable().Any(a => a.GroupMemberId == member.Id)) { canDelete = false; canArchive = true; } } return(ActionOk(new GetMemberDataResult { HeaderContent = headerContent, Roles = roles, Fields = fields, CanDelete = canDelete, CanArchive = canArchive, Name = member.Person.FullName, RoleGuid = member.GroupRole.Guid, MemberStatus = member.GroupMemberStatus, Note = member.Note, })); } }