/// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed)
        {
            string formattedValue = string.Empty;

            if (!string.IsNullOrWhiteSpace(value))
            {
                var names = new List <string>();

                foreach (string guidString in value.SplitDelimitedValues())
                {
                    Guid?guid = guidString.AsGuidOrNull();
                    if (guid.HasValue)
                    {
                        var noteType = NoteTypeCache.Read(guid.Value);
                        if (noteType != null)
                        {
                            names.Add(noteType.Name);
                        }
                    }
                }

                formattedValue = names.AsDelimited(", ");
            }

            return(base.FormatValue(parentControl, formattedValue, null, condensed));
        }
Beispiel #2
0
        /// <summary>
        /// Sets the edit value from IEntity.Id value
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id">The identifier.</param>
        public void SetEditValueFromEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id)
        {
            var    noteType  = NoteTypeCache.Read(id ?? 0);
            string guidValue = noteType != null?noteType.Guid.ToString() : string.Empty;

            SetEditValue(control, configurationValues, guidValue);
        }
Beispiel #3
0
        /// <summary>
        /// Gets the edit value as the IEntity.Id
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public int?GetEditValueAsEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            Guid guid     = GetEditValue(control, configurationValues).AsGuid();
            var  noteType = NoteTypeCache.Read(guid);

            return(noteType != null ? noteType.Id : (int?)null);
        }
Beispiel #4
0
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection(Type entityType, string selection)
        {
            string result = "Person Note";

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 2)
            {
                int noteTypeId       = selectionValues[0].AsInteger();
                var selectedNoteType = NoteTypeCache.Read(noteTypeId);
                if (selectedNoteType != null)
                {
                    result = $"Has a {selectedNoteType.Name} note";
                }
                else
                {
                    result = "Has a note";
                }

                var containingText = selectionValues[1];
                if (containingText.IsNotNullOrWhitespace())
                {
                    result += $" containing '{containingText}'";
                }
            }

            return(result);
        }
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                DisplayCategories();
                SetNoteType();
                lbStart.Focus();
                lbFlag.Visible = _enableCommunityFlagging;
            }

            if (NoteTypeId.HasValue)
            {
                var noteType = NoteTypeCache.Read(NoteTypeId.Value);
                if (noteType != null)
                {
                    notesComments.NoteTypes = new List <NoteTypeCache> {
                        noteType
                    };
                }
            }

            notesComments.EntityId = CurrentPrayerRequestId;

            if (lbNext.Visible)
            {
                lbNext.Focus();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            if (action != null && action.Activity != null &&
                action.Activity.Workflow != null && action.Activity.Workflow.Id > 0)
            {
                var text = GetAttributeValue(action, "Note").ResolveMergeFields(GetMergeFields(action));

                var note = new Note();
                note.IsSystem      = false;
                note.IsAlert       = GetAttributeValue(action, "IsAlert").AsBoolean();
                note.IsPrivateNote = false;
                note.EntityId      = action.Activity.Workflow.Id;
                note.Caption       = string.Empty;
                note.Text          = text;

                var noteType = NoteTypeCache.Read(GetAttributeValue(action, "NoteType").AsGuid());
                if (noteType != null)
                {
                    note.NoteTypeId = noteType.Id;
                }

                new NoteService(rockContext).Add(note);

                return(true);
            }
            else
            {
                errorMessages.Add("A Note can only be added to a persisted workflow with a valid ID.");
                return(false);
            }
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summarysni>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            var noteTypeString = GetAttributeValue("NoteType");
            var noteType       = NoteTypeCache.Read(noteTypeString.AsGuid());

            if (noteType != null)
            {
                lEntityType.Text = "Note Type: " + noteType.Name;
            }
        }
Beispiel #8
0
        private List <NoteTypeCache> GetNoteTypes(string viewStateKey)
        {
            var noteTypes   = new List <NoteTypeCache>();
            var noteTypeIds = ViewState[viewStateKey] as List <int> ?? new List <int>();

            foreach (var noteTypeId in noteTypeIds)
            {
                var noteType = NoteTypeCache.Read(noteTypeId);
                if (noteType != null)
                {
                    noteTypes.Add(noteType);
                }
            }
            return(noteTypes);
        }
Beispiel #9
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var person = GetPersonAliasFromActionAttribute("Person", rockContext, action, errorMessages);

            if (person != null)
            {
                var mergeFields = GetMergeFields(action);

                NoteService noteService = new NoteService(rockContext);

                Note note = new Note();
                note.EntityId      = person.Id;
                note.Caption       = GetAttributeValue(action, "Caption").ResolveMergeFields(mergeFields);
                note.IsAlert       = GetAttributeValue(action, "Alert").AsBoolean();
                note.IsPrivateNote = false;
                note.Text          = GetAttributeValue(action, "Text").ResolveMergeFields(mergeFields);;

                var noteType = NoteTypeCache.Read(GetAttributeValue(action, "NoteType").AsGuid());
                if (noteType != null)
                {
                    note.NoteTypeId = noteType.Id;
                }

                // get author
                var author = GetPersonAliasFromActionAttribute("Author", rockContext, action, errorMessages);
                if (author != null)
                {
                    note.CreatedByPersonAliasId = author.PrimaryAlias.Id;
                }

                noteService.Add(note);
                rockContext.SaveChanges();

                return(true);
            }
            else
            {
                errorMessages.Add("No person was provided for the note.");
            }

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

            return(true);
        }
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            if ( !string.IsNullOrWhiteSpace( value ) )
            {
                using ( var rockContext = new RockContext() )
                {
                    var noteType = NoteTypeCache.Read( value.AsGuid() );
                    if ( noteType != null )
                    {
                        formattedValue = noteType.Name;
                    }
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
        public override MobileBlockResponse HandleRequest(string request, Dictionary <string, string> Body)
        {
            var         noteTypeString        = GetAttributeValue("NoteType");
            var         noteType              = NoteTypeCache.Read(noteTypeString.AsGuid());
            RockContext rockContext           = new RockContext();
            NoteService noteService           = new NoteService(rockContext);
            var         entityId              = Body["entityId"].AsInteger();
            var         currentPersonAliasIds = CurrentPerson.Aliases.Select(a => a.Id);
            var         note = noteService.Queryable()
                               .Where(n => n.NoteTypeId == noteType.Id && n.EntityId == entityId && currentPersonAliasIds.Contains(n.CreatedByPersonAliasId ?? 0))
                               .FirstOrDefault();

            if (note == null)
            {
                note = new Rock.Model.Note
                {
                    NoteTypeId    = noteType.Id,
                    EntityId      = entityId,
                    Text          = "",
                    IsPrivateNote = true
                };
                noteService.Add(note);
            }

            note.Text = Body["note"];
            rockContext.SaveChanges();

            var response = new FormResponse
            {
                Success          = true,
                FormElementItems = GetForm(noteType, entityId),
                Message          = "Note Saved"
            };

            return(new MobileBlockResponse()
            {
                Request = "save",
                Response = JsonConvert.SerializeObject(response),
                TTL = 0
            });
        }
        public override MobileBlock GetMobile(string parameter)
        {
            var noteTypeString = GetAttributeValue("NoteType");
            var noteType       = NoteTypeCache.Read(noteTypeString.AsGuid());

            if (CurrentPerson == null || noteType == null)
            {
                return(new MobileBlock()
                {
                    BlockType = "Avalanche.Blocks.Null",
                    Attributes = CustomAttributes
                });
            }

            var form = GetForm(noteType, parameter.AsInteger());

            CustomAttributes.Add("FormElementItems", JsonConvert.SerializeObject(form));

            return(new MobileBlock()
            {
                BlockType = "Avalanche.Blocks.FormBlock",
                Attributes = CustomAttributes
            });
        }
 /// <summary>
 /// Gets the type of the note.
 /// </summary>
 private void GetNoteType()
 {
     noteType = NoteTypeCache.Read(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());
 }
        /// <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.Read(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.Read(this.GetAttributeValue("NoteType").AsGuid());

            if (noteType != null)
            {
                notesCommentsTimeline.NoteTypes = new List <NoteTypeCache> {
                    noteType
                };
            }

            notesCommentsTimeline.EntityId = groupMember.Id;

            // show the Add button on comments for any logged in person
            notesCommentsTimeline.AddAllowed = true;

            notesCommentsTimeline.RebuildNotes(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;
            }
        }
Beispiel #15
0
        /// <summary>
        /// Rebuilds the notes.
        /// </summary>
        /// <param name="setSelection">if set to <c>true</c> [set selection].</param>
        public void RebuildNotes(bool setSelection)
        {
            ClearNotes();
            ShowMoreOption = false;

            int?currentPersonId = null;
            var currentPerson   = GetCurrentPerson();

            if (currentPerson != null)
            {
                currentPersonId           = currentPerson.Id;
                _noteNew.CreatedByPhotoId = currentPerson.PhotoId;
                _noteNew.CreatedByGender  = currentPerson.Gender;
                _noteNew.CreatedByName    = currentPerson.FullName;
            }
            else
            {
                _noteNew.CreatedByPhotoId = null;
                _noteNew.CreatedByGender  = Gender.Male;
                _noteNew.CreatedByName    = string.Empty;
            }

            _noteNew.EntityId = EntityId;

            if (ViewableNoteTypes != null && ViewableNoteTypes.Any() && EntityId.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var viewableNoteTypeIds = ViewableNoteTypes.Select(t => t.Id).ToList();
                    var qry = new NoteService(rockContext).Queryable("CreatedByPersonAlias.Person")
                              .Where(n =>
                                     viewableNoteTypeIds.Contains(n.NoteTypeId) &&
                                     n.EntityId == EntityId.Value);

                    if (SortDirection == ListSortDirection.Descending)
                    {
                        qry = qry.OrderByDescending(n => n.IsAlert)
                              .ThenByDescending(n => n.CreatedDateTime);
                    }
                    else
                    {
                        qry = qry.OrderByDescending(n => n.IsAlert)
                              .ThenBy(n => n.CreatedDateTime);
                    }

                    var notes = qry.ToList();

                    NoteCount = notes.Count();

                    int i = 0;
                    foreach (var note in notes)
                    {
                        if (SortDirection == ListSortDirection.Descending && i >= DisplayCount)
                        {
                            ShowMoreOption = true;
                            break;
                        }

                        if (note.IsAuthorized(Authorization.VIEW, currentPerson))
                        {
                            var noteEditor = new NoteControl();
                            noteEditor.NoteTypes          = EditableNoteTypes;
                            noteEditor.ID                 = string.Format("note_{0}", note.Guid.ToString().Replace("-", "_"));
                            noteEditor.Note               = note;
                            noteEditor.IsPrivate          = note.IsPrivateNote;
                            noteEditor.CanEdit            = NoteTypeCache.Read(note.NoteTypeId).UserSelectable&& note.IsAuthorized(Authorization.ADMINISTRATE, currentPerson);
                            noteEditor.SaveButtonClick   += note_Updated;
                            noteEditor.DeleteButtonClick += note_Updated;
                            Controls.Add(noteEditor);

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

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

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

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

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

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

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

            Guid guid = personAttribute.AsGuid();

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

            return(true);
        }
Beispiel #17
0
        protected void lbSaveAccounts_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var txn = GetTransaction(rockContext);
                {
                    decimal totalAmount = TransactionDetailsState.Select(d => d.Amount).ToList().Sum();
                    if (txn.TotalAmount != totalAmount)
                    {
                        nbError.Title   = "Incorrect Amount";
                        nbError.Text    = string.Format("<p>When updating account allocations, the total amount needs to remain the same as the original amount ({0}).</p>", txn.TotalAmount.FormatAsCurrency());
                        nbError.Visible = true;
                        return;
                    }

                    var txnDetailService = new FinancialScheduledTransactionDetailService(rockContext);
                    var accountService   = new FinancialAccountService(rockContext);

                    // Delete any transaction details that were removed
                    var txnDetailsInDB = txnDetailService.Queryable().Where(a => a.ScheduledTransactionId.Equals(txn.Id)).ToList();
                    var deletedDetails = from txnDetail in txnDetailsInDB
                                         where !TransactionDetailsState.Select(d => d.Guid).Contains(txnDetail.Guid)
                                         select txnDetail;

                    bool accountChanges = deletedDetails.Any();

                    deletedDetails.ToList().ForEach(txnDetail =>
                    {
                        txnDetailService.Delete(txnDetail);
                    });

                    var changeSummary = new StringBuilder();

                    // Save Transaction Details
                    foreach (var editorTxnDetail in TransactionDetailsState)
                    {
                        editorTxnDetail.Account = accountService.Get(editorTxnDetail.AccountId);

                        // Add or Update the activity type
                        var txnDetail = txn.ScheduledTransactionDetails.FirstOrDefault(d => d.Guid.Equals(editorTxnDetail.Guid));
                        if (txnDetail == null)
                        {
                            accountChanges = true;
                            txnDetail      = new FinancialScheduledTransactionDetail();
                            txnDetail.Guid = editorTxnDetail.Guid;
                            txn.ScheduledTransactionDetails.Add(txnDetail);
                        }
                        else
                        {
                            if (txnDetail.AccountId != editorTxnDetail.AccountId ||
                                txnDetail.Amount != editorTxnDetail.Amount ||
                                txnDetail.Summary != editorTxnDetail.Summary)
                            {
                                accountChanges = true;
                            }
                        }

                        changeSummary.AppendFormat("{0}: {1}", editorTxnDetail.Account != null ? editorTxnDetail.Account.Name : "?", editorTxnDetail.Amount.FormatAsCurrency());
                        changeSummary.AppendLine();

                        txnDetail.AccountId = editorTxnDetail.AccountId;
                        txnDetail.Amount    = editorTxnDetail.Amount;
                        txnDetail.Summary   = editorTxnDetail.Summary;
                    }

                    if (accountChanges)
                    {
                        // save changes
                        rockContext.SaveChanges();

                        // Add a note about the change
                        var noteType = NoteTypeCache.Read(Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid());
                        if (noteType != null)
                        {
                            var noteService = new NoteService(rockContext);
                            var note        = new Note();
                            note.NoteTypeId = noteType.Id;
                            note.EntityId   = txn.Id;
                            note.Caption    = "Updated Transaction";
                            note.Text       = changeSummary.ToString();
                            noteService.Add(note);
                        }
                        rockContext.SaveChanges();
                    }

                    ShowView(txn);
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            var rockContext      = new RockContext();
            var userLoginService = new UserLoginService(rockContext);

            var userLogin = userLoginService.Queryable().Where(a => a.ApiKey == tbKey.Text).FirstOrDefault();

            if (userLogin != null && userLogin.PersonId != int.Parse(hfRestUserId.Value))
            {
                // this key already exists in the database. Show the error and get out of here.
                nbWarningMessage.Text    = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. ";
                nbWarningMessage.Visible = true;
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var changes       = new List <string>();
                var restUser      = new Person();
                if (int.Parse(hfRestUserId.Value) != 0)
                {
                    restUser = personService.Get(int.Parse(hfRestUserId.Value));
                }
                else
                {
                    personService.Add(restUser);
                    rockContext.SaveChanges();
                }

                // the rest user name gets saved as the last name on a person
                History.EvaluateChange(changes, "Last Name", restUser.LastName, tbName.Text);
                restUser.LastName          = tbName.Text;
                restUser.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid()).Id;
                if (cbActive.Checked)
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                }
                else
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()).Id;
                }

                if (restUser.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                restUser.Id,
                                changes);
                        }
                    }
                }

                // the description gets saved as a system note for the person
                var noteType = NoteTypeCache.Read(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE.AsGuid());
                if (noteType != null)
                {
                    var noteService = new NoteService(rockContext);
                    var note        = noteService.Get(noteType.Id, restUser.Id).FirstOrDefault();
                    if (note == null)
                    {
                        note = new Note();
                        noteService.Add(note);
                    }
                    note.NoteTypeId = noteType.Id;
                    note.EntityId   = restUser.Id;
                    note.Text       = tbDescription.Text;
                }
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                var entityType = new EntityTypeService(rockContext)
                                 .Get("Rock.Security.Authentication.Database");
                userLogin = userLoginService.GetByPersonId(restUser.Id).FirstOrDefault();
                if (userLogin == null)
                {
                    userLogin = new UserLogin();
                    userLoginService.Add(userLogin);
                }

                if (string.IsNullOrWhiteSpace(userLogin.UserName))
                {
                    userLogin.UserName = Guid.NewGuid().ToString();
                }

                userLogin.IsConfirmed  = true;
                userLogin.ApiKey       = tbKey.Text;
                userLogin.PersonId     = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();
            });
            NavigateToParentPage();
        }
Beispiel #19
0
        /// <summary>
        /// Outputs server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter" /> object and stores tracing information about the control if tracing is enabled.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter" /> object that receives the control content.</param>
        public override void RenderControl(HtmlTextWriter writer)
        {
            if (CSSClass != string.Empty)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "note " + CSSClass);
            }
            else
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "note");
            }

            if (this.NoteId.HasValue)
            {
                writer.AddAttribute("rel", this.NoteId.Value.ToStringSafe());
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            // Edit Mode HTML...
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "panel panel-noteentry");
            if (NoteId.HasValue || !AddAlwaysVisible)
            {
                writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "panel-body");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            if (DisplayType == NoteDisplayType.Full && UsePersonIcon)
            {
                writer.Write(Person.GetPersonPhotoImageTag(CreatedByPersonId, CreatedByPhotoId, null, CreatedByGender, null, 50, 50));
            }

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "noteentry-control");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            _ddlNoteType.RenderControl(writer);
            _tbNote.RenderControl(writer);
            writer.RenderEndTag();

            // The optional create date text box, but only for new notes...
            if (ShowCreateDateInput && !NoteId.HasValue)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "createDate clearfix");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                _dtCreateDate.RenderControl(writer);
                writer.RenderEndTag();  // createDate div
            }

            if (DisplayType == NoteDisplayType.Full)
            {
                // Options
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "settings clearfix");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "options pull-left");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                if (ShowAlertCheckBox)
                {
                    _cbAlert.RenderControl(writer);
                }

                if (ShowPrivateCheckBox)
                {
                    _cbPrivate.RenderControl(writer);
                }

                writer.RenderEndTag();

                if (ShowSecurityButton && this.NoteId.HasValue)
                {
                    _sbSecurity.EntityId = this.NoteId.Value;
                    _sbSecurity.Title    = this.Label;
                    _sbSecurity.RenderControl(writer);
                }

                writer.RenderEndTag();  // settings div
            }

            writer.RenderEndTag();  // panel body

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "panel-footer");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            _lbSaveNote.Text = "Save " + Label;
            _lbSaveNote.RenderControl(writer);

            if (NoteId.HasValue || !AddAlwaysVisible)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "edit-note-cancel btn btn-link btn-xs");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write("Cancel");
                writer.RenderEndTag();
            }

            writer.RenderEndTag();  // panel-footer div

            writer.RenderEndTag();  // note-entry div

            if (NoteId.HasValue)
            {
                // View Mode HTML...
                writer.AddAttribute(HtmlTextWriterAttribute.Class, ArticleClass);
                writer.RenderBeginTag("article");

                if (DisplayType == NoteDisplayType.Full)
                {
                    if (UsePersonIcon)
                    {
                        writer.Write(Person.GetPersonPhotoImageTag(CreatedByPersonId, CreatedByPhotoId, CreatedByAge, CreatedByGender, null, 50, 50));
                    }
                    else
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, IconClass);
                        writer.RenderBeginTag(HtmlTextWriterTag.I);
                        writer.RenderEndTag();
                    }
                }

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "details");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                // first, encode the text to ensure html tags get encoded
                string renderedText = Text.EncodeHtml();

                // convert any http, etc text into clickable links (do this before applying Markdown)
                renderedText = renderedText.Linkify();

                // convert any markdown into HTML, and convert into crlf into <br />
                renderedText = renderedText.ConvertMarkdownToHtml(true);

                if (DisplayType == NoteDisplayType.Full)
                {
                    // Heading
                    writer.RenderBeginTag(HtmlTextWriterTag.H5);

                    if (DisplayNoteTypeHeading & this.NoteTypeId.HasValue)
                    {
                        var noteType = NoteTypeCache.Read(this.NoteTypeId.Value);
                        if (noteType != null)
                        {
                            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
                            writer.Write(noteType.Name + " &nbsp; ");
                            writer.RenderEndTag();
                        }
                    }

                    string heading = Caption;
                    if (string.IsNullOrWhiteSpace(Caption))
                    {
                        heading = CreatedByName;
                    }
                    writer.Write(heading.EncodeHtml());
                    if (CreatedDateTime.HasValue)
                    {
                        writer.Write(" ");
                        writer.AddAttribute("class", "date");
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.Write(CreatedDateTime.Value.ToRelativeDateString(6));
                        writer.RenderEndTag();
                    }
                    writer.RenderEndTag();

                    writer.Write(renderedText);
                }
                else
                {
                    writer.Write(renderedText);
                    writer.Write(" - ");
                    if (!string.IsNullOrWhiteSpace(CreatedByName))
                    {
                        writer.AddAttribute("class", "note-author");
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.Write(CreatedByName);
                        writer.RenderEndTag();
                        writer.Write(" ");
                    }
                    if (CreatedDateTime.HasValue)
                    {
                        writer.AddAttribute("class", "note-created");
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.Write(CreatedDateTime.Value.ToRelativeDateString(6));
                        writer.RenderEndTag();
                    }
                }

                writer.RenderEndTag();  // Details Div

                if (CanEdit)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "actions rollover-item");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);

                    _lbDeleteNote.RenderControl(writer);

                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "edit-note");
                    writer.AddAttribute(HtmlTextWriterAttribute.Href, "#");
                    writer.RenderBeginTag(HtmlTextWriterTag.A);
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "fa fa-pencil");
                    writer.RenderBeginTag(HtmlTextWriterTag.I);
                    writer.RenderEndTag();
                    writer.RenderEndTag();  // A

                    writer.RenderEndTag();  // actions
                }

                writer.RenderEndTag();  // article
            }

            writer.RenderEndTag();
        }
Beispiel #20
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="txn">The TXN.</param>
        private void ShowView(FinancialScheduledTransaction txn)
        {
            if (txn != null)
            {
                hlStatus.Text      = txn.IsActive ? "Active" : "Inactive";
                hlStatus.LabelType = txn.IsActive ? LabelType.Success : LabelType.Danger;

                string rockUrlRoot = ResolveRockUrl("/");

                var detailsLeft = new DescriptionList()
                                  .Add("Person", (txn.AuthorizedPersonAlias != null && txn.AuthorizedPersonAlias.Person != null) ?
                                       txn.AuthorizedPersonAlias.Person.GetAnchorTag(rockUrlRoot) : string.Empty);

                var detailsRight = new DescriptionList()
                                   .Add("Amount", (txn.ScheduledTransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M).FormatAsCurrency())
                                   .Add("Frequency", txn.TransactionFrequencyValue != null ? txn.TransactionFrequencyValue.Value : string.Empty)
                                   .Add("Start Date", txn.StartDate.ToShortDateString())
                                   .Add("End Date", txn.EndDate.HasValue ? txn.EndDate.Value.ToShortDateString() : string.Empty)
                                   .Add("Next Payment Date", txn.NextPaymentDate.HasValue ? txn.NextPaymentDate.Value.ToShortDateString() : string.Empty)
                                   .Add("Last Status Refresh", txn.LastStatusUpdateDateTime.HasValue ? txn.LastStatusUpdateDateTime.Value.ToString("g") : string.Empty);

                detailsLeft.Add("Source", txn.SourceTypeValue != null ? txn.SourceTypeValue.Value : string.Empty);

                if (txn.FinancialPaymentDetail != null && txn.FinancialPaymentDetail.CurrencyTypeValue != null)
                {
                    var paymentMethodDetails = new DescriptionList();

                    var currencyType = txn.FinancialPaymentDetail.CurrencyTypeValue;
                    if (currencyType.Guid.Equals(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid()))
                    {
                        // Credit Card
                        paymentMethodDetails.Add("Type", currencyType.Value + (txn.FinancialPaymentDetail.CreditCardTypeValue != null ? (" - " + txn.FinancialPaymentDetail.CreditCardTypeValue.Value) : string.Empty));
                        paymentMethodDetails.Add("Name on Card", txn.FinancialPaymentDetail.NameOnCard.Trim());
                        paymentMethodDetails.Add("Account Number", txn.FinancialPaymentDetail.AccountNumberMasked);
                        paymentMethodDetails.Add("Expires", txn.FinancialPaymentDetail.ExpirationDate);
                    }
                    else
                    {
                        // ACH
                        paymentMethodDetails.Add("Type", currencyType.Value);
                        paymentMethodDetails.Add("Account Number", txn.FinancialPaymentDetail.AccountNumberMasked);
                    }

                    detailsLeft.Add("Payment Method", paymentMethodDetails.GetFormattedList("{0}: {1}").AsDelimited("<br/>"));
                }

                GatewayComponent gateway = null;
                if (txn.FinancialGateway != null)
                {
                    gateway = txn.FinancialGateway.GetGatewayComponent();
                    if (gateway != null)
                    {
                        detailsLeft.Add("Payment Gateway", GatewayContainer.GetComponentName(gateway.TypeName));
                    }
                }

                detailsLeft
                .Add("Transaction Code", txn.TransactionCode)
                .Add("Schedule Id", txn.GatewayScheduleId);

                lDetailsLeft.Text  = detailsLeft.Html;
                lDetailsRight.Text = detailsRight.Html;

                gAccountsView.DataSource = txn.ScheduledTransactionDetails.ToList();
                gAccountsView.DataBind();

                var noteType = NoteTypeCache.Read(Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid());
                if (noteType != null)
                {
                    var rockContext = new RockContext();
                    rptrNotes.DataSource = new NoteService(rockContext).Get(noteType.Id, txn.Id)
                                           .Where(n => n.CreatedDateTime.HasValue)
                                           .OrderBy(n => n.CreatedDateTime)
                                           .ToList()
                                           .Select(n => new
                    {
                        n.Caption,
                        Text   = n.Text.ConvertCrLfToHtmlBr(),
                        Person = (n.CreatedByPersonAlias != null && n.CreatedByPersonAlias.Person != null) ? n.CreatedByPersonAlias.Person.FullName : "",
                        Date   = n.CreatedDateTime.HasValue ? n.CreatedDateTime.Value.ToShortDateString() : "",
                        Time   = n.CreatedDateTime.HasValue ? n.CreatedDateTime.Value.ToShortTimeString() : ""
                    })
                                           .ToList();
                    rptrNotes.DataBind();
                }

                lbRefresh.Visible            = gateway != null && gateway.GetScheduledPaymentStatusSupported;
                lbUpdate.Visible             = gateway != null && gateway.UpdateScheduledPaymentSupported;
                lbCancelSchedule.Visible     = txn.IsActive;
                lbReactivateSchedule.Visible = !txn.IsActive && gateway != null && gateway.ReactivateScheduledPaymentSupported;
            }
        }
        /// <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);

            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 Partipant' button if there are participants that are taking contribution requests
            btnDonateToParticipant.Visible = groupMembers.Where(a => !a.GetAttributeValue("DisablePublicContributionRequests").AsBoolean()).Any();

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

            var opportunityType = DefinedValueCache.Read(group.GetAttributeValue("OpportunityType").AsGuid());

            // 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.Read(this.GetAttributeValue("NoteType").AsGuid());

            if (noteType != null)
            {
                notesCommentsTimeline.NoteTypes = new List <NoteTypeCache> {
                    noteType
                };
            }

            notesCommentsTimeline.EntityId = groupId;

            // show the Add button on comments for any logged in person
            notesCommentsTimeline.AddAllowed = true;

            notesCommentsTimeline.RebuildNotes(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;
            }
        }