private void rptFamilies_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int familyId = (int)e.Item.DataItem;

            if (_familyMembers == null || !_familyMembers.ContainsKey(familyId))
            {
                return;
            }

            var lFamilyLava     = e.Item.FindControl("lFamilyLava") as Literal;
            var rptFamilyPeople = e.Item.FindControl("rptFamilyPeople") as Repeater;

            if (lFamilyLava != null)
            {
                var family      = _families.FirstOrDefault(g => g.Id == familyId);
                var mergeFields = LavaHelper.GetCommonMergeFields(null);
                mergeFields.Add("Family", family);
                var contents = _familyLava.ResolveMergeFields(mergeFields, _enabledLavaCommands);
                lFamilyLava.Text = contents;
            }

            if (rptFamilyPeople != null)
            {
                rptFamilyPeople.ItemDataBound += rptPeople_ItemDataBound;
                rptFamilyPeople.DataSource     = _familyMembers[familyId].Select(p => new PersonFamilyItem {
                    FamilyId = familyId, PersonId = p.Id
                });
                rptFamilyPeople.DataBind();
            }
        }
예제 #2
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                RockContext      rockContext      = new RockContext();
                JiraTopicService jiraTopicService = new JiraTopicService(rockContext);
                var topics = jiraTopicService
                             .Queryable("JiraTickets")
                             .AsNoTracking()
                             .OrderBy(t => t.Order)
                             .ToList();

                topics.ForEach(t => t.JiraTickets = t.JiraTickets.OrderBy(t2 => t.CreatedDateTime).ToList());

                var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson);
                mergeFields.Add("JiraTopics", topics);
                var output = GetAttributeValue(AttributeKey.LavaTemplate)
                             .ResolveMergeFields(
                    mergeFields,
                    CurrentPerson,
                    GetAttributeValue(AttributeKey.EnabledCommands)
                    );

                ltLava.Text = output;
            }
        }
예제 #3
0
        /// <summary>
        /// Runs the <see cref="BuildScript" /> and sets <see cref="ResultData"/>
        /// </summary>
        public void UpdateResultData()
        {
            var timeToBuildStopwatch = System.Diagnostics.Stopwatch.StartNew();

            switch (this.BuildScriptType)
            {
            case PersistedDatasetScriptType.Lava:
            {
                var mergeFields = LavaHelper.GetCommonMergeFields(null, null, CommonMergeFieldsOptions.CommonMergeFieldsOptionsEmpty);

                if (this.EnabledLavaCommands.IsNotNullOrWhiteSpace())
                {
                    this.ResultData = this.BuildScript.ResolveMergeFields(mergeFields, null, this.EnabledLavaCommands);
                }
                else
                {
                    this.ResultData = this.BuildScript.ResolveMergeFields(mergeFields);
                }
                break;
            }

            default:
            {
                throw new UnsupportedBuildScriptTypeException(this.BuildScriptType);
            }
            }

            timeToBuildStopwatch.Stop();
            this.TimeToBuildMS = timeToBuildStopwatch.Elapsed.TotalMilliseconds;

            this.LastRefreshDateTime = RockDateTime.Now;
        }
        private void ApplyBlockSettings()
        {
            var mergeFields = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);

            litTitle.Text = GetAttributeValue(AttributeKey.Title);
            litInitialInstructions.Text             = GetAttributeValue(AttributeKey.InitialInstructions).ResolveMergeFields(mergeFields);
            litIndividualSelectionInstructions.Text = GetAttributeValue(AttributeKey.IndividualSelectionInstructions).ResolveMergeFields(mergeFields);
            litNotFoundInstructions.Text            = GetAttributeValue(AttributeKey.PhoneNumberNotFoundMessage).ResolveMergeFields(mergeFields);
            litVerificationInstructions.Text        = GetAttributeValue(AttributeKey.VerificationInstructions).ResolveMergeFields(mergeFields);
        }
        protected void btnLookup_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            var ipLimit         = GetAttributeValue(AttributeKey.IpThrottleLimit).AsInteger();
            var messageTemplate = GetAttributeValue(AttributeKey.TextMessageTemplate);
            var fromNumber      = GetAttributeValue(AttributeKey.SmsNumber);
            var phoneNumber     = pbPhoneNumberLookup.Number;

            try
            {
                using (var rockContext = new RockContext())
                {
                    var identityVerificationService = new IdentityVerificationService(rockContext);

                    var identityVerification = identityVerificationService.CreateIdentityVerificationRecord(Request.UserHostAddress, ipLimit, phoneNumber);

                    var smsMessage = new RockSMSMessage
                    {
                        FromNumber = DefinedValueCache.Get(fromNumber),
                        Message    = messageTemplate,
                    };
                    var mergeObjects = LavaHelper.GetCommonMergeFields(this.RockPage);
                    mergeObjects.Add("ConfirmationCode", identityVerification.IdentityVerificationCode.Code);

                    smsMessage.SetRecipients(new List <RockSMSMessageRecipient> {
                        RockSMSMessageRecipient.CreateAnonymous(phoneNumber, mergeObjects)
                    });

                    var errorList = new List <string>();
                    if (smsMessage.Send(out errorList))
                    {
                        IdentityVerificationId = identityVerification.Id;
                        ShowVerificationPage();
                    }
                    else
                    {
                        ShowWarningMessage("Verification text message failed to send.");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowWarningMessage(ex.Message);
                RockLogger.Log.Error(RockLogDomains.Core, ex);
                ExceptionLogService.LogException(ex);
            }
        }
예제 #6
0
        /// <summary>
        /// Handles the RowDataBound event of the gDonations control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void gDonations_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var item        = e.Row.DataItem;
                var isExporting = ( bool )item.GetPropertyValue("IsExporting");

                //
                // Get the merge fields to be available.
                //
                var options = new CommonMergeFieldsOptions();
                options.GetLegacyGlobalMergeFields = false;
                var mergeFields = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson, options);
                mergeFields.AddOrReplace("Group", item.GetPropertyValue("Group"));
                mergeFields.AddOrReplace("Donor", item.GetPropertyValue("Donor"));
                mergeFields.AddOrReplace("Participant", item.GetPropertyValue("Participant"));

                //
                // Set the Donor column value.
                //
                var column = gDonations.ColumnsOfType <RockLiteralField>().First(c => c.HeaderText == "Donor");
                if (column.Visible)
                {
                    var literal   = ( Literal )e.Row.Cells[gDonations.Columns.IndexOf(column)].Controls[0];
                    var donorText = GetAttributeValue("DonorColumn").ResolveMergeFields(mergeFields);
                    if (isExporting)
                    {
                        donorText = donorText.ScrubHtmlAndConvertCrLfToBr();
                    }
                    literal.Text = donorText;
                }

                //
                // Set the Participant column value.
                //
                column = gDonations.ColumnsOfType <RockLiteralField>().First(c => c.HeaderText == "Participant");
                if (column.Visible)
                {
                    var literal   = ( Literal )e.Row.Cells[gDonations.Columns.IndexOf(column)].Controls[0];
                    var donorText = GetAttributeValue("ParticipantColumn").ResolveMergeFields(mergeFields);
                    if (isExporting)
                    {
                        donorText = donorText.SanitizeHtml().Trim();
                    }
                    literal.Text = donorText;
                }
            }
        }
예제 #7
0
        protected void ShowGroups()
        {
            RockContext rockContext        = new RockContext();
            var         groupTypeGuid      = GetAttributeValue("GroupType").AsGuid();
            var         groupTypeId        = new GroupTypeService(rockContext).Get(groupTypeGuid).Id;
            var         groupTypeIdString  = groupTypeId.ToString();
            var         groupEntityTypeId  = EntityTypeCache.Get(typeof(Group)).Id;
            var         groupAttributesQry = new AttributeService(rockContext).Queryable()
                                             .Where(a => a.EntityTypeId == groupEntityTypeId)
                                             .Where(a => a.EntityTypeQualifierValue == groupTypeIdString)
                                             .Where(a => a.EntityTypeQualifierColumn == "GroupTypeId");
            var groupAttributesValueQry = new AttributeValueService(rockContext).Queryable()
                                          .Join(groupAttributesQry,
                                                av => av.AttributeId,
                                                a => a.Id,
                                                (av, a) => av);

            var items = new GroupService(rockContext)
                        .Queryable()
                        .Where(g => g.GroupTypeId == groupTypeId)
                        .Where(g => g.IsActive && g.IsPublic && !g.IsArchived)
                        .Where(g =>
                               g.GroupCapacity == null ||
                               g.GroupCapacity == 0 ||
                               g.Members.Where(m => m.GroupMemberStatus == GroupMemberStatus.Active).Count() < g.GroupCapacity)
                        .GroupJoin(groupAttributesValueQry,
                                   g => g.Id,
                                   av => av.EntityId,
                                   (g, av) => new { g, av }
                                   )
                        .ToList();

            var groups = new List <Group>();

            foreach (var item in items)
            {
                item.g.AttributeValues = item.av.ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));
                item.g.Attributes      = item.av.ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));
                groups.Add(item.g);
            }

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("Groups", groups);

            lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
        private void rptPeople_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Person person           = null;
            var    personIdentifier = e.Item.DataItem as int?;

            if (personIdentifier != null)
            {
                person = _people.FirstOrDefault(p => p.Id == personIdentifier);
            }
            else
            {
                if (e.Item.DataItem != null)
                {
                    var personFamilyItem = e.Item.DataItem as PersonFamilyItem;
                    if (personFamilyItem != null)
                    {
                        person = _familyMembers[personFamilyItem.FamilyId].FirstOrDefault(p => p.Id == personFamilyItem.PersonId);
                    }
                }
                else
                {
                    return;
                }
            }

            if (person == null)
            {
                return;
            }

            var mergeFields = LavaHelper.GetCommonMergeFields(null);

            mergeFields.Add("Person", person);
            var contents = _personLava.ResolveMergeFields(mergeFields, _enabledLavaCommands);

            var lLava = e.Item.FindControl("lPersonLava") as Literal;

            if (lLava != null)
            {
                lLava.Text = contents;
            }
        }
        /// <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;
            }

            // only show if the current person is a Leader in the Group
            if (!group.Members.Any(a => a.PersonId == this.CurrentPersonId && a.GroupRole.IsLeader))
            {
                pnlView.Visible = false;
                return;
            }

            group.LoadAttributes(rockContext);
            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("Group", group);

            // Left Top Sidebar
            var photoGuid = group.GetAttributeValue("OpportunityPhoto");

            imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid);

            // Top Main
            string summaryLavaTemplate = this.GetAttributeValue("SummaryLavaTemplate");

            BindGroupMembersGrid();

            mergeFields.Add("GroupTotals", _groupTotals);
            lMainTopContentHtml.Text = summaryLavaTemplate.ResolveMergeFields(mergeFields);
        }
예제 #10
0
        /// <summary>
        /// Gets the message text.
        /// </summary>
        /// <param name="messageLavaTemplateAttributeKey">The message lava template attribute key.</param>
        /// <returns></returns>
        private string GetMessageText(string messageLavaTemplateAttributeKey)
        {
            var mobilePerson = this.GetMobilePerson();
            var mergeFields  = LavaHelper.GetCommonMergeFields(this.RockPage, mobilePerson);

            string messageLavaTemplate = this.GetAttributeValue(messageLavaTemplateAttributeKey);

            if (CurrentCheckInState != null && CurrentCheckInState.Kiosk != null)
            {
                mergeFields.Add("Kiosk", CurrentCheckInState.Kiosk);
                DateTime nextActiveTime     = DateTime.MaxValue;
                var      filteredGroupTypes = CurrentCheckInState.Kiosk.FilteredGroupTypes(CurrentCheckInState.ConfiguredGroupTypes);
                if (filteredGroupTypes.Any())
                {
                    nextActiveTime = filteredGroupTypes.Select(g => g.NextActiveTime).Min();
                }
                mergeFields.Add("NextActiveTime", nextActiveTime);
            }

            return(messageLavaTemplate.ResolveMergeFields(mergeFields));
        }
예제 #11
0
        private void ShowDetails()
        {
            var courseGuids = GetAttributeValues(AttributeKeys.Categories);
            var categories  = new List <CategoryCache>();

            foreach (var guid in courseGuids)
            {
                var category = CategoryCache.Get(guid);
                if (category != null)
                {
                    categories.Add(category);
                }
            }

            List <EnrollmentHelper.CourseResult> courses = EnrollmentHelper.GetPersonCourses(CurrentPerson, categories);

            var mergeFields = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);

            mergeFields.Add("Courses", courses);

            ltContent.Text = GetAttributeValue(AttributeKeys.Lava)
                             .ResolveMergeFields(mergeFields, CurrentPerson, GetAttributeValue(AttributeKeys.EnabledCommands));
        }
예제 #12
0
        /// <summary>
        /// Runs the <see cref="BuildScript" /> and sets <see cref="ResultData"/> if it is valid.
        /// </summary>
        /// <exception cref="System.Runtime.Serialization.InvalidDataContractException">Is thrown if the resulting data deserialized.</exception>
        /// <exception cref="Rock.Model.PersistedDataset.UnsupportedBuildScriptTypeException">Is thrown if the BuildScriptType is not known/supported.</exception>
        public void UpdateResultData()
        {
            var timeToBuildStopwatch = System.Diagnostics.Stopwatch.StartNew();

            switch (this.BuildScriptType)
            {
            case PersistedDatasetScriptType.Lava:
            {
                var mergeFields = LavaHelper.GetCommonMergeFields(null, null, CommonMergeFieldsOptions.CommonMergeFieldsOptionsEmpty);
                var output      = this.BuildScript.ResolveMergeFields(mergeFields, null, this.EnabledLavaCommands);

                // Ensure resulting output is valid for its defined format,
                // otherwise log the problem and throw an exception.
                if (this.ResultFormat == PersistedDatasetDataFormat.JSON)
                {
                    if (output.FromJsonDynamicOrNull() == null)
                    {
                        throw new InvalidDataContractException($"PersistedDataset (Id: {this.Id}) build script created invalid result data: {output}");
                    }
                }

                this.ResultData = output;
                break;
            }

            default:
            {
                throw new UnsupportedBuildScriptTypeException(this.BuildScriptType);
            }
            }

            timeToBuildStopwatch.Stop();
            this.TimeToBuildMS = timeToBuildStopwatch.Elapsed.TotalMilliseconds;

            this.LastRefreshDateTime = RockDateTime.Now;
        }
예제 #13
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            var         errors      = new List <string>();
            RockContext rockContext = new RockContext();
            var         workflows   = GetWorkflows(rockContext);

            //Get the new attribute values from the repeater
            Dictionary <string, string> attributeUpdates = GetNewAttributeValues();

            if (attributeUpdates.Any())
            {
                var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                foreach (var workflow in workflows)
                {
                    //Reuse the mergefields with new workflow
                    mergeFields["Workflow"] = workflow;

                    //We will store the attribute value changes and apply them all at once
                    Dictionary <string, string> toUpdate = new Dictionary <string, string>();
                    foreach (var update in attributeUpdates)
                    {
                        toUpdate[update.Key] = update.Value.ResolveMergeFields(mergeFields);
                        //if (toUpdate[update.Key])
                        //{

                        //}
                    }

                    foreach (var update in toUpdate)
                    {
                        workflow.SetAttributeValue(update.Key, update.Value);
                    }

                    workflow.SaveAttributeValues();
                }
            }

            //Workflow settings

            //Activate the workflows if requested or if a new activity is activated
            if (ddlState.SelectedValue == "NotComplete" || ddlActivities.SelectedValue.IsNotNullOrWhiteSpace())
            {
                foreach (var workflow in workflows)
                {
                    workflow.CompletedDateTime = null;
                }
            }
            else if (ddlState.SelectedValue == "Complete")
            {
                foreach (var workflow in workflows)
                {
                    workflow.MarkComplete();
                }
            }

            //Update Status message
            if (tbStatus.Text.IsNotNullOrWhiteSpace())
            {
                var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                foreach (var workflow in workflows)
                {
                    mergeFields["Workflow"] = workflow;
                    workflow.Status         = tbStatus.Text.ResolveMergeFields(mergeFields);
                }
            }

            //Activate New Activity

            int?activityTypeId = ddlActivities.SelectedValueAsId();

            if (activityTypeId.HasValue)
            {
                var activityType = WorkflowActivityTypeCache.Get(activityTypeId.Value);
                if (activityType != null)
                {
                    foreach (var workflow in workflows)
                    {
                        var activity = WorkflowActivity.Activate(activityType, workflow, rockContext);
                        activity.Guid = Guid.NewGuid();

                        foreach (var action in activity.Actions)
                        {
                            action.Guid = Guid.NewGuid();
                        }
                    }
                }
            }
            rockContext.SaveChanges();

            //Process workflows
            List <string> errorMessages = new List <string>();

            if (workflows.Where(w => w.IsActive).Any())
            {
                foreach (var workflow in workflows)
                {
                    WorkflowService workflowService = new WorkflowService(new RockContext());
                    workflowService.Process(workflow, out errorMessages);
                }
            }

            pnlConfirmation.Visible = false;
            pnlDisplay.Visible      = false;
            pnlDone.Visible         = true;
        }
예제 #14
0
        /// <summary>
        /// Raises 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)
            {
                var categoryGuids = GetAttributeValue(AttributeKeys.Categories)
                                    .SplitDelimitedValues()
                                    .Select(i => i.AsGuid())
                                    .ToList();

                RockContext rockContext = new RockContext();


                CategoryService categoryService = new CategoryService(rockContext);
                var             categoryIds     = categoryService.Queryable()
                                                  .Where(c => categoryGuids.Contains(c.Guid))
                                                  .Select(c => c.Id)
                                                  .ToList();

                CourseRequirementStatusService courseRequirementStatusService = new CourseRequirementStatusService(rockContext);
                var statusQry = courseRequirementStatusService.Queryable()
                                .Where(s => s.PersonAlias.PersonId == CurrentPersonId);

                CourseRecordService courseRecordService = new CourseRecordService(rockContext);
                var recordQueryable = courseRecordService.Queryable()
                                      .GroupJoin(statusQry,
                                                 r => r.CourseId,
                                                 s => s.CourseRequirement.CourseId,
                                                 (r, s) => new { Record = r, Statuses = s }
                                                 )
                                      .Where(r => r.Record.PersonAlias.PersonId == CurrentPersonId)
                                      .OrderByDescending(r => r.Record.CompletionDateTime);

                CourseService courseService = new CourseService(rockContext);

                var courses = courseService.Queryable()
                              .Where(c => c.IsActive)
                              .Where(c => categoryIds.Contains(c.CategoryId ?? 0))
                              .GroupJoin(recordQueryable,
                                         c => c.Id,
                                         r => r.Record.CourseId,
                                         (c, r) => new
                {
                    Course   = c,
                    Records  = r,
                    Category = c.Category
                })
                              .ToList();

                var courseItems = new List <PersonCourseInfo>();

                foreach (var course in courses)
                {
                    if (!course.Course.PersonCanView(CurrentPerson))
                    {
                        continue;
                    }

                    var courseItem = new PersonCourseInfo()
                    {
                        Course     = course.Course,
                        Category   = course.Category,
                        IsComplete = false
                    };

                    var completedRecords = course.Records.Where(r => r.Record.Passed).ToList();
                    if (completedRecords.Any())
                    {
                        var completedCourse = completedRecords.First();
                        courseItem.IsComplete        = true;
                        courseItem.CompletedDateTime = completedCourse.Record.CompletionDateTime;
                        var expired = completedCourse.Statuses
                                      .Where(s => s.State == CourseRequirementState.Expired).Any();
                        if (expired)
                        {
                            courseItem.IsExpired = true;
                        }
                    }
                    courseItems.Add(courseItem);
                }


                var mergeFields = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);
                mergeFields.Add("CourseItems", courseItems);
                ltOutput.Text = GetAttributeValue(AttributeKeys.LavaTemplate).ResolveMergeFields(mergeFields);
            }
        }
예제 #15
0
        /// <summary>
        /// Writes the <see cref="T:System.Web.UI.WebControls.CompositeControl" /> content to the specified <see cref="T:System.Web.UI.HtmlTextWriter" /> object, for display on the client.
        /// </summary>
        /// <param name="writer">An <see cref="T:System.Web.UI.HtmlTextWriter" /> that represents the output stream to render HTML content on the client.</param>
        public override void RenderControl(HtmlTextWriter writer)
        {
            if (this.Visible)
            {
                var  currentPerson     = (this.Page as RockPage)?.CurrentPerson;
                var  editableNoteTypes = NoteOptions.GetEditableNoteTypes(currentPerson);
                bool canAdd            = AddAllowed &&
                                         editableNoteTypes.Any() &&
                                         (AllowAnonymousEntry || currentPerson != null);

                string cssClass = "panel panel-note js-notecontainer" +
                                  (this.NoteOptions.DisplayType == NoteDisplayType.Light ? " panel-note-light" : string.Empty);

                writer.AddAttribute(HtmlTextWriterAttribute.Class, cssClass);
                writer.AddAttribute("data-sortdirection", this.SortDirection.ConvertToString(false));
                writer.RenderBeginTag("section");

                // Heading
                if (ShowHeading)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "panel-heading clearfix");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);

                    if (!string.IsNullOrWhiteSpace(TitleIconCssClass) ||
                        !string.IsNullOrWhiteSpace(Title))
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "panel-title");
                        writer.RenderBeginTag(HtmlTextWriterTag.H3);

                        if (!string.IsNullOrWhiteSpace(TitleIconCssClass))
                        {
                            writer.AddAttribute(HtmlTextWriterAttribute.Class, TitleIconCssClass);
                            writer.RenderBeginTag(HtmlTextWriterTag.I);
                            writer.RenderEndTag();      // I
                        }

                        if (!string.IsNullOrWhiteSpace(Title))
                        {
                            writer.Write(" ");
                            writer.Write(Title);
                        }

                        writer.RenderEndTag();
                    }

                    if (!NoteOptions.AddAlwaysVisible && canAdd && SortDirection == ListSortDirection.Descending)
                    {
                        RenderAddButton(writer);
                    }

                    writer.RenderEndTag();
                }

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

                _noteEditor.ShowEditMode = NoteOptions.AddAlwaysVisible;

                if (canAdd && SortDirection == ListSortDirection.Descending)
                {
                    if (!ShowHeading && !NoteOptions.AddAlwaysVisible)
                    {
                        RenderAddButton(writer);
                    }

                    _noteEditor.RenderControl(writer);
                }

                _hfCurrentNoteId.RenderControl(writer);
                _hfExpandedNoteIds.RenderControl(writer);
                _lbDeleteNote.RenderControl(writer);
                _mdDeleteWarning.RenderControl(writer);
                using (var rockContext = new RockContext())
                {
                    List <Note> viewableNoteList = GetViewableNoteList(rockContext, currentPerson);

                    this.ShowMoreOption = (SortDirection == ListSortDirection.Descending) && (viewableNoteList.Count > this.DisplayCount);
                    if (this.ShowMoreOption)
                    {
                        viewableNoteList = viewableNoteList.Take(this.DisplayCount).ToList();
                    }

                    var rockBlock       = this.RockBlock();
                    var noteMergeFields = LavaHelper.GetCommonMergeFields(rockBlock?.RockPage, currentPerson, new CommonMergeFieldsOptions {
                        GetLegacyGlobalMergeFields = false
                    });
                    noteMergeFields.Add("NoteOptions", this.NoteOptions);
                    noteMergeFields.Add("NoteList", viewableNoteList);
                    List <int> expandedNoteIdList = _hfExpandedNoteIds.Value.SplitDelimitedValues().AsIntegerList();
                    noteMergeFields.Add("ExpandedNoteIds", expandedNoteIdList);

                    var noteTreeHtml = this.NoteOptions.NoteViewLavaTemplate.ResolveMergeFields(noteMergeFields).ResolveClientIds(this.ParentUpdatePanel()?.ClientID);
                    writer.Write(noteTreeHtml);
                }

                if (canAdd && SortDirection == ListSortDirection.Ascending)
                {
                    if (!NoteOptions.AddAlwaysVisible)
                    {
                        RenderAddButton(writer);
                    }

                    _noteEditor.RenderControl(writer);
                }
                else
                {
                    if (ShowMoreOption)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "load-more-container");
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        _lbShowMore.RenderControl(writer);
                        writer.RenderEndTag();
                    }
                }

                writer.RenderEndTag();

                writer.RenderEndTag();
            }
        }
        ////
        //// Group Methods

        /// <summary>
        /// Displays the view group  using a lava template
        /// </summary>
        private void DisplayViewGroup()
        {
            if (_groupId > 0)
            {
                RockContext  rockContext  = new RockContext();
                GroupService groupService = new GroupService(rockContext);

                bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean();

                var qry = groupService
                          .Queryable("GroupLocations,Members,Members.Person,Members.Person.PhoneNumbers,GroupType")
                          .Where(g => g.Id == _groupId);

                if (!enableDebug)
                {
                    qry = qry.AsNoTracking();
                }

                var group = qry.FirstOrDefault();

                // order group members by name
                if (group != null)
                {
                    group.Members = group.Members.OrderBy(m => m.Person.LastName).ThenBy(m => m.Person.FirstName).ToList();
                }

                var mergeFields = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);
                mergeFields.Add("Group", group);

                // add linked pages
                Dictionary <string, object> linkedPages = new Dictionary <string, object>();
                linkedPages.Add("PersonDetailPage", LinkedPageRoute("PersonDetailPage"));
                linkedPages.Add("RosterPage", LinkedPageRoute("RosterPage"));
                linkedPages.Add("AttendancePage", LinkedPageRoute("AttendancePage"));
                linkedPages.Add("CommunicationPage", LinkedPageRoute("CommunicationPage"));
                mergeFields.Add("LinkedPages", linkedPages);

                // add collection of allowed security actions
                Dictionary <string, object> securityActions = new Dictionary <string, object>();
                securityActions.Add("View", group != null && group.IsAuthorized(Authorization.VIEW, CurrentPerson));
                securityActions.Add("Edit", group != null && (group.IsAuthorized(Authorization.EDIT, CurrentPerson) || LineQuery.IsGroupInPersonsLine(group, CurrentPerson)));
                securityActions.Add("Administrate", group != null && group.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson));
                mergeFields.Add("AllowedActions", securityActions);
                mergeFields.Add("Groups", string.Join(",", LineQuery.GetCellGroupsInLine(CurrentPerson, new RockContext(), false).Select(g => g.Name).ToList()));

                mergeFields.Add("LinePermission", LineQuery.IsGroupInPersonsLine(group, CurrentPerson));

                Dictionary <string, object> currentPageProperties = new Dictionary <string, object>();
                currentPageProperties.Add("Id", RockPage.PageId);
                currentPageProperties.Add("Path", Request.Path);
                mergeFields.Add("CurrentPage", currentPageProperties);

                string template = GetAttributeValue("LavaTemplate");

                // show debug info
                if (enableDebug && IsUserAuthorized(Authorization.EDIT))
                {
                    string postbackCommands = @"<h5>Available Postback Commands</h5>
                                                <ul>
                                                    <li><strong>EditGroup:</strong> Shows a panel for modifing group info. Expects a group id. <code>{{ Group.Id | Postback:'EditGroup' }}</code></li>
                                                    <li><strong>AddGroupMember:</strong> Shows a panel for adding group info. Does not require input. <code>{{ '' | Postback:'AddGroupMember' }}</code></li>
                                                    <li><strong>EditGroupMember:</strong> Shows a panel for modifing group info. Expects a group member id. <code>{{ member.Id | Postback:'EditGroupMember' }}</code></li>
                                                    <li><strong>DeleteGroupMember:</strong> Deletes a group member. Expects a group member id. <code>{{ member.Id | Postback:'DeleteGroupMember' }}</code></li>
                                                    <li><strong>SendCommunication:</strong> Sends a communication to all group members on behalf of the Current User. This will redirect them to the communication page where they can author their email. <code>{{ '' | Postback:'SendCommunication' }}</code></li>
                                                </ul>";

                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo(null, string.Empty, postbackCommands);
                }

                lContent.Text = template.ResolveMergeFields(mergeFields).ResolveClientIds(upnlContent.ClientID);
            }
            else
            {
                lContent.Text = "<div class='alert alert-warning'>No group was available from the querystring.</div>";
            }
        }
예제 #17
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="groupId">The group identifier.</param>
        protected void ShowView(int groupId)
        {
            pnlView.Visible = true;
            hfGroupId.Value = groupId.ToString();
            var rockContext = new RockContext();

            var group = new GroupService(rockContext).Get(groupId);

            if (group == null)
            {
                pnlView.Visible = false;
                return;
            }

            group.LoadAttributes(rockContext);
            var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid());

            if (this.GetAttributeValue("SetPageTitletoOpportunityTitle").AsBoolean())
            {
                RockPage.Title        = group.GetAttributeValue("OpportunityTitle");
                RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle");
                RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle");
            }

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("Block", this.BlockCache);
            mergeFields.Add("Group", group);

            // Left Sidebar
            var photoGuid = group.GetAttributeValue("OpportunityPhoto").AsGuidOrNull();

            imgOpportunityPhoto.Visible  = photoGuid.HasValue;
            imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid);

            var groupMembers = group.Members.ToList();

            foreach (var gm in groupMembers)
            {
                gm.LoadAttributes(rockContext);
            }

            // only show the 'Donate to a Participant' button if there are participants that are taking contribution requests
            btnDonateToParticipant.Visible = groupMembers.Where(a => !a.GetAttributeValue("DisablePublicContributionRequests").AsBoolean()).Any();
            if (!string.IsNullOrWhiteSpace(opportunityType.GetAttributeValue("core_DonateButtonText")))
            {
                btnDonateToParticipant.Text = opportunityType.GetAttributeValue("core_DonateButtonText");
            }

            RegistrationInstance registrationInstance = null;
            var registrationInstanceId = group.GetAttributeValue("RegistrationInstance").AsIntegerOrNull();

            if (registrationInstanceId.HasValue)
            {
                registrationInstance = new RegistrationInstanceService(rockContext).Get(registrationInstanceId.Value);
            }

            mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));

            if (registrationInstance != null)
            {
                mergeFields.Add("RegistrationInstance", registrationInstance);
                mergeFields.Add("RegistrationInstanceLinkages", registrationInstance.Linkages);

                // populate merge fields for Registration Counts
                var maxRegistrantCount       = 0;
                var currentRegistrationCount = 0;

                if (registrationInstance.MaxAttendees != 0)
                {
                    maxRegistrantCount = registrationInstance.MaxAttendees;
                }

                currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking()
                                           .Where(r =>
                                                  r.Registration.RegistrationInstanceId == registrationInstance.Id &&
                                                  r.OnWaitList == false)
                                           .Count();

                mergeFields.Add("CurrentRegistrationCount", currentRegistrationCount);
                if (maxRegistrantCount != 0)
                {
                    mergeFields.Add("MaxRegistrantCount", maxRegistrantCount);
                    mergeFields.Add("RegistrationSpotsAvailable", maxRegistrantCount - currentRegistrationCount);
                }
            }

            string sidebarLavaTemplate = this.GetAttributeValue("SidebarLavaTemplate");

            lSidebarHtml.Text = sidebarLavaTemplate.ResolveMergeFields(mergeFields);

            SetActiveTab("Details");

            // Top Main
            string summaryLavaTemplate = this.GetAttributeValue("SummaryLavaTemplate");

            lMainTopContentHtml.Text = summaryLavaTemplate.ResolveMergeFields(mergeFields);

            // only show the leader toolbox link of the currentperson has a leader role in the group
            btnLeaderToolbox.Visible = group.Members.Any(a => a.PersonId == this.CurrentPersonId && a.GroupRole.IsLeader);

            //// Participant Actions
            // only show if the current person is a group member
            var groupMember = group.Members.FirstOrDefault(a => a.PersonId == this.CurrentPersonId);

            if (groupMember != null)
            {
                hfGroupMemberId.Value         = groupMember.Id.ToString();
                pnlParticipantActions.Visible = true;
            }
            else
            {
                hfGroupMemberId.Value         = null;
                pnlParticipantActions.Visible = false;
            }

            mergeFields.Add("GroupMember", groupMember);

            // Progress
            if (groupMember != null && pnlParticipantActions.Visible)
            {
                var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>();

                var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable()
                                        .Where(d => d.EntityTypeId == entityTypeIdGroupMember &&
                                               d.EntityId == groupMember.Id)
                                        .Sum(a => (decimal?)a.Amount) ?? 0.00M;

                var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                if (!individualFundraisingGoal.HasValue)
                {
                    individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                }

                var amountLeft = individualFundraisingGoal - contributionTotal;
                var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100;

                mergeFields.Add("AmountLeft", amountLeft);
                mergeFields.Add("PercentMet", percentMet);

                var queryParams = new Dictionary <string, string>();
                queryParams.Add("GroupId", hfGroupId.Value);
                queryParams.Add("GroupMemberId", hfGroupMemberId.Value);
                mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams));
                mergeFields.Add("ParticipantPageUrl", LinkedPageUrl("ParticipantPage", queryParams));

                string makeDonationButtonText = null;
                if (groupMember.PersonId == this.CurrentPersonId)
                {
                    makeDonationButtonText = "Make Payment";
                }
                else
                {
                    makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType);
                }

                mergeFields.Add("MakeDonationButtonText", makeDonationButtonText);

                var participantLavaTemplate = this.GetAttributeValue("ParticipantLavaTemplate");
                lParticipantActionsHtml.Text = participantLavaTemplate.ResolveMergeFields(mergeFields);
            }

            // Tab:Details
            lDetailsHtml.Text  = group.GetAttributeValue("OpportunityDetails");
            btnDetailsTab.Text = string.Format("{0} Details", opportunityType);

            // Tab:Updates
            liUpdatesTab.Visible = false;
            var updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull();

            if (updatesContentChannelGuid.HasValue)
            {
                var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value);
                if (contentChannel != null)
                {
                    liUpdatesTab.Visible = true;
                    string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate");
                    var    contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList();

                    mergeFields.Add("ContentChannelItems", contentChannelItems);
                    lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields);

                    btnUpdatesTab.Text = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count());
                }
            }

            // Tab:Comments
            var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid());

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

            notesCommentsTimeline.NoteOptions.EntityId = groupId;

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

            var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean();

            btnCommentsTab.Text = string.Format("Comments ({0})", notesCommentsTimeline.NoteCount);

            if (CurrentPerson == null)
            {
                notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0);
                lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0;
                liCommentsTab.Visible         = enableCommenting;
                btnLoginToComment.Visible     = enableCommenting;
            }
            else
            {
                lNoLoginNoCommentsYet.Visible = false;
                notesCommentsTimeline.Visible = enableCommenting;
                liCommentsTab.Visible         = enableCommenting;
                btnLoginToComment.Visible     = false;
            }

            // if btnDetailsTab is the only visible tab, hide the tab since there is nothing else to tab to
            if (!liCommentsTab.Visible && !liUpdatesTab.Visible)
            {
                tlTabList.Visible = false;
            }
        }
예제 #18
0
        /// <summary>
        /// Gets the locked out markup.
        /// </summary>
        /// <returns></returns>
        private string GetUnconfirmedMarkup()
        {
            var mergeFields = LavaHelper.GetCommonMergeFields(null, GetCurrentPerson());

            return(GetAttributeValue(AttributeKey.ConfirmCaption).ResolveMergeFields(mergeFields));
        }
예제 #19
0
        /// <summary>
        /// Populates the roster.
        /// In cases where there won't be a postback, we can disable view state. The only time we need viewstate is when the Configuration Dialog
        /// is showing.
        /// </summary>
        private void PopulateRoster(ViewStateMode viewStateMode = ViewStateMode.Disabled)
        {
            RosterConfiguration rosterConfiguration = this.GetBlockUserPreference(UserPreferenceKey.RosterConfigurationJSON)
                                                      .FromJsonOrNull <RosterConfiguration>() ?? new RosterConfiguration();

            if (!rosterConfiguration.IsConfigured())
            {
                return;
            }

            int[]      scheduleIds    = rosterConfiguration.ScheduleIds;
            int[]      locationIds    = rosterConfiguration.LocationIds;
            List <int> pickedGroupIds = rosterConfiguration.PickedGroupIds.ToList();

            var allGroupIds = new List <int>();

            allGroupIds.AddRange(pickedGroupIds);

            var rockContext = new RockContext();

            // Only use teh ShowChildGroups option when there is 1 group selected
            if (rosterConfiguration.IncludeChildGroups && pickedGroupIds.Count == 1)
            {
                // if there is exactly one groupId we can avoid a 'Contains' (Contains has a small performance impact)
                var parentGroupId = pickedGroupIds[0];
                var groupService  = new GroupService(rockContext);

                // just the first level of child groups, not all decendants
                var childGroupIds = groupService.Queryable().Where(a => a.ParentGroupId == parentGroupId).Select(a => a.Id).ToList();
                allGroupIds.AddRange(childGroupIds);
            }

            allGroupIds = allGroupIds.Distinct().ToList();

            var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);

            // An OccurrenceDate probably won't be included in the URL, but just in case
            DateTime?occurrenceDate = this.PageParameter(PageParameterKey.OccurrenceDate).AsDateTime();

            if (!occurrenceDate.HasValue)
            {
                occurrenceDate = RockDateTime.Today;
            }

            // only show occurrences for the current day
            var attendanceOccurrenceQuery = attendanceOccurrenceService
                                            .Queryable()
                                            .Where(a => a.ScheduleId.HasValue && a.LocationId.HasValue && a.GroupId.HasValue)
                                            .WhereDeducedIsActive()
                                            .Where(a =>
                                                   allGroupIds.Contains(a.GroupId.Value) &&
                                                   a.OccurrenceDate == occurrenceDate &&
                                                   scheduleIds.Contains(a.ScheduleId.Value));

            // if specific locations are specified, use those, otherwise just show all
            if (locationIds.Any())
            {
                attendanceOccurrenceQuery = attendanceOccurrenceQuery.Where(a => locationIds.Contains(a.LocationId.Value));
            }

            // limit attendees to ones that schedules (or are checked-in regardless of being scheduled)
            var confirmedAttendancesForOccurrenceQuery = attendanceOccurrenceQuery
                                                         .SelectMany(a => a.Attendees)
                                                         .Include(a => a.PersonAlias.Person)
                                                         .Include(a => a.Occurrence.Group.Members)
                                                         .WhereScheduledOrCheckedIn();

            var confirmedScheduledIndividualsForOccurrenceId = confirmedAttendancesForOccurrenceQuery
                                                               .AsNoTracking()
                                                               .ToList()
                                                               .GroupBy(a => a.OccurrenceId)
                                                               .ToDictionary(
                k => k.Key,
                v => v.Select(a => new ScheduledIndividual
            {
                ScheduledAttendanceItemStatus = Attendance.GetScheduledAttendanceItemStatus(a.RSVP, a.ScheduledToAttend),
                Person             = a.PersonAlias.Person,
                GroupMember        = a.Occurrence.Group.Members.FirstOrDefault(gm => gm.PersonId == a.PersonAlias.PersonId),
                CurrentlyCheckedIn = a.DidAttend == true
            })
                .ToList());

            List <AttendanceOccurrence> attendanceOccurrenceList = attendanceOccurrenceQuery
                                                                   .Include(a => a.Schedule)
                                                                   .Include(a => a.Attendees)
                                                                   .Include(a => a.Group)
                                                                   .Include(a => a.Location)
                                                                   .AsNoTracking()
                                                                   .ToList()
                                                                   .OrderBy(a => a.OccurrenceDate)
                                                                   .ThenBy(a => a.Schedule.Order)
                                                                   .ThenBy(a => a.Schedule.GetNextStartDateTime(a.OccurrenceDate))
                                                                   .ThenBy(a => a.Location.Name)
                                                                   .ToList();

            var occurrenceRosterInfoList = new List <OccurrenceRosterInfo>();

            foreach (var attendanceOccurrence in attendanceOccurrenceList)
            {
                var scheduleDate         = attendanceOccurrence.Schedule.GetNextStartDateTime(attendanceOccurrence.OccurrenceDate);
                var scheduledIndividuals = confirmedScheduledIndividualsForOccurrenceId.GetValueOrNull(attendanceOccurrence.Id);

                if ((scheduleDate == null) || (scheduleDate.Value.Date != attendanceOccurrence.OccurrenceDate))
                {
                    // scheduleDate can be later than the OccurrenceDate (or null) if there are exclusions that cause the schedule
                    // to not occur on the occurrence date. In this case, don't show the roster unless there are somehow individuals
                    // scheduled for this occurrence.
                    if (scheduledIndividuals == null || !scheduledIndividuals.Any())
                    {
                        // no scheduleDate and no scheduled individuals, so continue on to the next attendanceOccurrence
                        continue;
                    }
                }

                var occurrenceRosterInfo = new OccurrenceRosterInfo
                {
                    Group                = attendanceOccurrence.Group,
                    Location             = attendanceOccurrence.Location,
                    Schedule             = attendanceOccurrence.Schedule,
                    ScheduleDate         = scheduleDate,
                    ScheduledIndividuals = scheduledIndividuals
                };

                occurrenceRosterInfoList.Add(occurrenceRosterInfo);
            }

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage);

            mergeFields.Add("OccurrenceList", occurrenceRosterInfoList);
            mergeFields.Add("DisplayRole", rosterConfiguration.DisplayRole);
            mergeFields.Add("OccurrenceDate", occurrenceDate);
            var rosterLavaTemplate = this.GetAttributeValue(AttributeKey.RosterLavaTemplate);

            var rosterHtml = rosterLavaTemplate.ResolveMergeFields(mergeFields);

            // by default, let's disable viewstate (except for when the configuration dialog is showing)
            lOccurrenceRosterHTML.ViewStateMode = viewStateMode;
            lOccurrenceRosterHTML.Text          = rosterHtml;
        }
        /// <summary>
        /// Updates the scheduled payment.
        /// </summary>
        /// <param name="usePaymentToken">if set to <c>true</c> [use payment token].</param>
        /// <param name="paymentToken">The payment token.</param>
        protected void UpdateScheduledPayment(bool usePaymentToken, string paymentToken = null)
        {
            var giftTerm = this.GetAttributeValue(AttributeKey.GiftTerm);

            if (dtpStartDate.SelectedDate <= RockDateTime.Today)
            {
                nbUpdateScheduledPaymentWarning.Visible = true;
                nbUpdateScheduledPaymentWarning.Text    = string.Format("When scheduling a {0}, make sure the starting date is in the future (after today)", giftTerm.ToLower());
                return;
            }

            var rockContext = new RockContext();

            var  financialScheduledTransactionService       = new FinancialScheduledTransactionService(rockContext);
            var  financialScheduledTransactionDetailService = new FinancialScheduledTransactionDetailService(rockContext);
            Guid scheduledTransactionGuid      = hfScheduledTransactionGuid.Value.AsGuid();
            var  financialScheduledTransaction = financialScheduledTransactionService.Get(scheduledTransactionGuid);

            financialScheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
            financialScheduledTransaction.TransactionFrequencyValueId = ddlFrequency.SelectedValue.AsInteger();

            ReferencePaymentInfo referencePaymentInfo;

            var person = financialScheduledTransaction.AuthorizedPersonAlias.Person;

            string errorMessage;

            var financialGateway                      = this.FinancialGateway;
            var financialGatewayComponent             = this.FinancialGatewayComponent;
            var existingPaymentOrPersonSavedAccountId = rblExistingPaymentOrPersonSavedAccount.SelectedValue.AsInteger();

            bool useExistingPaymentMethod = pnlUseExistingPaymentNoSavedAccounts.Visible || existingPaymentOrPersonSavedAccountId == 0;
            bool useSavedAccount          = pnlUseExistingPaymentWithSavedAccounts.Visible && existingPaymentOrPersonSavedAccountId > 0;

            if (usePaymentToken)
            {
                referencePaymentInfo           = new ReferencePaymentInfo();
                referencePaymentInfo.FirstName = person.FirstName;
                referencePaymentInfo.LastName  = person.LastName;

                referencePaymentInfo.UpdateAddressFieldsFromAddressControl(acBillingAddress);

                referencePaymentInfo.ReferenceNumber = paymentToken;

                var customerToken = financialGatewayComponent.CreateCustomerAccount(this.FinancialGateway, referencePaymentInfo, out errorMessage);

                if (errorMessage.IsNotNullOrWhiteSpace() || customerToken.IsNullOrWhiteSpace())
                {
                    nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                    nbMessage.Text    = errorMessage ?? "Unknown Error";
                    nbMessage.Visible = true;
                    return;
                }

                referencePaymentInfo.GatewayPersonIdentifier = customerToken;
            }
            else if (useExistingPaymentMethod)
            {
                // use save payment method as original transaction
                referencePaymentInfo = new ReferencePaymentInfo();
                referencePaymentInfo.GatewayPersonIdentifier       = financialScheduledTransaction.FinancialPaymentDetail.GatewayPersonIdentifier;
                referencePaymentInfo.FinancialPersonSavedAccountId = financialScheduledTransaction.FinancialPaymentDetail.FinancialPersonSavedAccountId;
            }
            else if (useSavedAccount)
            {
                var savedAccount = new FinancialPersonSavedAccountService(rockContext).Get(existingPaymentOrPersonSavedAccountId);
                if (savedAccount != null)
                {
                    referencePaymentInfo = savedAccount.GetReferencePayment();
                }
                else
                {
                    // shouldn't happen
                    throw new Exception("Unable to determine Saved Account");
                }
            }
            else
            {
                // shouldn't happen
                throw new Exception("Unable to determine payment method");
            }

            var selectedAccountAmounts = caapPromptForAccountAmounts.AccountAmounts.Where(a => a.Amount.HasValue && a.Amount.Value != 0).Select(a => new { a.AccountId, Amount = a.Amount.Value }).ToArray();

            referencePaymentInfo.Amount = selectedAccountAmounts.Sum(a => a.Amount);

            var originalGatewayScheduleId = financialScheduledTransaction.GatewayScheduleId;

            try
            {
                financialScheduledTransaction.FinancialPaymentDetail.ClearPaymentInfo();
                var successfullyUpdated = financialGatewayComponent.UpdateScheduledPayment(financialScheduledTransaction, referencePaymentInfo, out errorMessage);

                if (!successfullyUpdated)
                {
                    nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                    nbMessage.Text    = errorMessage ?? "Unknown Error";
                    nbMessage.Visible = true;
                    return;
                }

                financialScheduledTransaction.FinancialPaymentDetail.SetFromPaymentInfo(referencePaymentInfo, financialGatewayComponent as GatewayComponent, rockContext);

                var selectedAccountIds        = selectedAccountAmounts.Select(a => a.AccountId).ToArray();
                var deletedTransactionDetails = financialScheduledTransaction.ScheduledTransactionDetails.ToList().Where(a => !selectedAccountIds.Contains(a.AccountId)).ToList();

                foreach (var deletedTransactionDetail in deletedTransactionDetails)
                {
                    financialScheduledTransaction.ScheduledTransactionDetails.Remove(deletedTransactionDetail);
                    financialScheduledTransactionDetailService.Delete(deletedTransactionDetail);
                }

                foreach (var selectedAccountAmount in selectedAccountAmounts)
                {
                    var scheduledTransactionDetail = financialScheduledTransaction.ScheduledTransactionDetails.FirstOrDefault(a => a.AccountId == selectedAccountAmount.AccountId);
                    if (scheduledTransactionDetail == null)
                    {
                        scheduledTransactionDetail           = new FinancialScheduledTransactionDetail();
                        scheduledTransactionDetail.AccountId = selectedAccountAmount.AccountId;
                        financialScheduledTransaction.ScheduledTransactionDetails.Add(scheduledTransactionDetail);
                    }

                    scheduledTransactionDetail.Amount = selectedAccountAmount.Amount;
                }

                rockContext.SaveChanges();
                Task.Run(() => ScheduledGiftWasModifiedMessage.PublishScheduledTransactionEvent(financialScheduledTransaction.Id, ScheduledGiftEventTypes.ScheduledGiftUpdated));
            }
            catch (Exception)
            {
                // if the GatewayScheduleId was updated, but there was an exception,
                // make sure we save the  financialScheduledTransaction record with the updated GatewayScheduleId so we don't orphan it
                if (financialScheduledTransaction.GatewayScheduleId.IsNotNullOrWhiteSpace() && (originalGatewayScheduleId != financialScheduledTransaction.GatewayScheduleId))
                {
                    rockContext.SaveChanges();
                }

                throw;
            }

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });
            var finishLavaTemplate = this.GetAttributeValue(AttributeKey.FinishLavaTemplate);

            // re-fetch financialScheduledTransaction with a new RockContext from database to ensure that lazy loaded fields will be populated
            using (var rockContextForSummary = new RockContext())
            {
                if (pnlHostedPaymentControl.Visible && hfSaveNewAccount.Value.AsInteger() == 1 && tbSaveAccount.Text.IsNotNullOrWhiteSpace())
                {
                    SaveNewFinancialPersonSavedAccount(financialScheduledTransaction);
                }

                financialScheduledTransaction = new FinancialScheduledTransactionService(rockContextForSummary).Get(scheduledTransactionGuid);

                mergeFields.Add("Transaction", financialScheduledTransaction);
                mergeFields.Add("Person", financialScheduledTransaction.AuthorizedPersonAlias.Person);
                mergeFields.Add("PaymentDetail", financialScheduledTransaction.FinancialPaymentDetail);
                mergeFields.Add("BillingLocation", financialScheduledTransaction.FinancialPaymentDetail.BillingLocation);

                pnlPromptForChanges.Visible   = false;
                pnlTransactionSummary.Visible = true;

                lTransactionSummaryHTML.Text = finishLavaTemplate.ResolveMergeFields(mergeFields);
            }
        }
예제 #21
0
        private string GetTwitter()
        {
            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            try
            {
                // You need to set your own keys and screen name
                var oAuthConsumerKey    = GetAttributeValue(AttributeKeys.OAuthConsumerKey);
                var oAuthConsumerSecret = GetAttributeValue(AttributeKeys.OAuthConsumerSecret);
                var oAuthUrl            = "https://api.twitter.com/oauth2/token";
                var screenname          = GetAttributeValue(AttributeKeys.ScreenName);

                if (oAuthConsumerKey.IsNullOrWhiteSpace() ||
                    oAuthConsumerSecret.IsNullOrWhiteSpace() ||
                    screenname.IsNullOrWhiteSpace())
                {
                    return("");
                }

                // Do the Authenticate
                var authHeaderFormat = "Basic {0}";

                var authHeader = string.Format(authHeaderFormat,
                                               Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
                                                                                             Uri.EscapeDataString((oAuthConsumerSecret)))
                                                                      ));

                var postBody = "grant_type=client_credentials";

                HttpWebRequest authRequest = ( HttpWebRequest )WebRequest.Create(oAuthUrl);
                authRequest.Headers.Add("Authorization", authHeader);
                authRequest.Method                 = "POST";
                authRequest.ContentType            = "application/x-www-form-urlencoded;charset=UTF-8";
                authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                using (Stream stream = authRequest.GetRequestStream())
                {
                    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
                    stream.Write(content, 0, content.Length);
                }

                authRequest.Headers.Add("Accept-Encoding", "gzip");

                WebResponse authResponse = authRequest.GetResponse();
                // deserialize into an object
                TwitAuthenticateResponse twitAuthResponse;
                using ( authResponse )
                {
                    using (var reader = new StreamReader(authResponse.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var objectText          = reader.ReadToEnd();
                        twitAuthResponse = JsonConvert.DeserializeObject <TwitAuthenticateResponse>(objectText);
                    }
                }

                var            timelineFormat       = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count={1}";
                var            timelineUrl          = string.Format(timelineFormat, screenname, GetAttributeValue(AttributeKeys.TweetCount));
                HttpWebRequest timeLineRequest      = ( HttpWebRequest )WebRequest.Create(timelineUrl);
                var            timelineHeaderFormat = "{0} {1}";
                timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
                timeLineRequest.Method = "Get";
                WebResponse timeLineResponse = timeLineRequest.GetResponse();
                var         timeLineJson     = string.Empty;
                using ( timeLineResponse )
                {
                    using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
                    {
                        timeLineJson = reader.ReadToEnd();
                    }
                }
                dynamic parsedJson = JsonConvert.DeserializeObject(timeLineJson);

                var    urlRegex            = new Regex("https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)");
                var    usernameRegex       = new Regex("(^|[^@\\w])@(\\w{1,15})\\b");
                var    hashtagRegex        = new Regex("(^|\\B)#(?![0-9_]+\\b)([a-zA-Z0-9_]{1,30})(\\b|\\r)");
                string twitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";

                var tweets = new List <Tweet>();
                foreach (var item in parsedJson)
                {
                    string text = item["text"];

                    text = urlRegex.Replace(text, "<a href='$0'>$0</a>");
                    text = usernameRegex.Replace(text, "<a href='http://twitter.com/$2'>$0</a>");
                    text = hashtagRegex.Replace(text, "<a href='http://twitter.com/hashtag/$2'>$0</a>");

                    DateTime createdAt = DateTime.ParseExact(( string )item["created_at"], twitterDateTemplate, new System.Globalization.CultureInfo("en-US"));

                    var tweet = new Tweet
                    {
                        Text    = text,
                        Id      = item["id"],
                        Created = createdAt
                    };
                    tweets.Add(tweet);
                }

                mergeFields.Add("Tweets", tweets);
            }
            catch (Exception e)
            {
                LogException(e);
            }
            return(GetAttributeValue(AttributeKeys.LavaTemplate).ResolveMergeFields(mergeFields));
        }
예제 #22
0
        /// <summary>
        /// Shows the wall.
        /// </summary>
        private void ShowWall()
        {
            var pageRef = CurrentPageReference;

            pageRef.Parameters.AddOrReplace("Page", "PageNum");

            var prayerRequests = new List <PrayerRequest>();

            var qry = new PrayerRequestService(new RockContext())
                      .Queryable()
                      .AsNoTracking()
                      .Where(r => r.ExpirationDate >= RockDateTime.Now &&
                             r.IsApproved == true &&
                             r.IsPublic == true);

            var categoryGuids = (GetAttributeValue("CategoryFilter") ?? string.Empty).SplitDelimitedValues().AsGuidList();

            if (categoryGuids.Any())
            {
                qry = qry.Where(a => a.CategoryId.HasValue && (categoryGuids.Contains(a.Category.Guid) || (a.Category.ParentCategoryId.HasValue && categoryGuids.Contains(a.Category.ParentCategory.Guid))));
            }

            var campusEntity = RockPage.GetCurrentContext(EntityTypeCache.Get(typeof(Campus)));

            if (campusEntity != null)
            {
                var campusId = campusEntity.Id;
                qry = qry.Where(r => r.CampusId.HasValue && r.CampusId == campusId);
            }

            var sortOrder = GetAttributeValue("SortOrder").AsInteger();

            switch (sortOrder)
            {
            case 0:
                qry = qry.OrderByDescending(a => a.EnteredDateTime);
                break;

            case 1:
                qry = qry.OrderBy(a => a.EnteredDateTime);
                break;
            }

            prayerRequests = qry.ToList();

            var pagination = new Pagination();

            pagination.ItemCount   = prayerRequests.Count();
            pagination.PageSize    = GetAttributeValue("PageSize").AsInteger();
            pagination.CurrentPage = PageParameter("Page").AsIntegerOrNull() ?? 1;
            pagination.UrlTemplate = pageRef.BuildUrl();

            var currentPrayerRequests = pagination.GetCurrentPageItems(prayerRequests);

            var commonMergeFields = LavaHelper.GetCommonMergeFields(RockPage);

            var mergeFields = new Dictionary <string, object>(commonMergeFields);

            mergeFields.Add("Pagination", pagination);
            mergeFields.Add("PrayerRequests", currentPrayerRequests);

            Template template = null;
            var      error    = string.Empty;

            try
            {
                template = Template.Parse(GetAttributeValue("LavaTemplate"));
            }
            catch (Exception ex)
            {
                error = string.Format("Lava error: {0}", ex.Message);
            }
            finally
            {
                if (error.IsNotNullOrWhiteSpace())
                {
                    nbError.Text    = error;
                    nbError.Visible = true;
                }

                if (template != null)
                {
                    template.Registers["EnabledCommands"] = GetAttributeValue("EnabledLavaCommands");
                    lContent.Text = template.Render(Hash.FromDictionary(mergeFields)).ResolveClientIds(upnlContent.ClientID);
                }
            }
        }
        /// <summary>
        /// Handles the ItemDataBound event of the rptScheduledTransactions control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void rptScheduledTransactions_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var transactionSchedule = e.Item.DataItem as FinancialScheduledTransaction;

                HiddenField hfScheduledTransactionId = ( HiddenField )e.Item.FindControl("hfScheduledTransactionId");
                hfScheduledTransactionId.Value = transactionSchedule.Id.ToString();

                // create dictionary for liquid
                Dictionary <string, object> scheduleSummary = new Dictionary <string, object>();
                scheduleSummary.Add("Id", transactionSchedule.Id);
                scheduleSummary.Add("Guid", transactionSchedule.Guid);
                scheduleSummary.Add("StartDate", transactionSchedule.StartDate);
                scheduleSummary.Add("EndDate", transactionSchedule.EndDate);
                scheduleSummary.Add("NextPaymentDate", transactionSchedule.NextPaymentDate);

                Button btnEdit = ( Button )e.Item.FindControl("btnEdit");

                // If a Transfer-To gateway was set and this transaction is not using that gateway, change the Edit button to a Transfer button
                if (_transferToGatewayGuid != null && transactionSchedule.FinancialGateway.Guid != _transferToGatewayGuid)
                {
                    btnEdit.Text = GetAttributeValue(AttributeKey.TransferButtonText);

                    HiddenField hfTransfer = ( HiddenField )e.Item.FindControl("hfTransfer");
                    hfTransfer.Value = TRANSFER;
                }

                // if there isn't an Edit page defined for the transaction, don't show th button
                bool showEditButton;
                var  hostedGatewayComponent   = transactionSchedule.FinancialGateway.GetGatewayComponent() as IHostedGatewayComponent;
                bool useHostedGatewayEditPage = false;
                if (hostedGatewayComponent != null)
                {
                    useHostedGatewayEditPage = hostedGatewayComponent.GetSupportedHostedGatewayModes(transactionSchedule.FinancialGateway).Contains(HostedGatewayMode.Hosted);
                }

                if (useHostedGatewayEditPage)
                {
                    showEditButton = this.GetAttributeValue(AttributeKey.ScheduledTransactionEditPageHosted).IsNotNullOrWhiteSpace();
                }
                else
                {
                    showEditButton = this.GetAttributeValue(AttributeKey.ScheduledTransactionEditPage).IsNotNullOrWhiteSpace();
                }

                btnEdit.Visible = showEditButton;


                if (transactionSchedule.NextPaymentDate.HasValue)
                {
                    scheduleSummary.Add("DaysTillNextPayment", (transactionSchedule.NextPaymentDate.Value - RockDateTime.Now).Days);
                }
                else
                {
                    scheduleSummary.Add("DaysTillNextPayment", null);
                }

                DateTime?lastPaymentDate = transactionSchedule.Transactions.Max(t => t.TransactionDateTime);
                scheduleSummary.Add("LastPaymentDate", lastPaymentDate);

                if (lastPaymentDate.HasValue)
                {
                    scheduleSummary.Add("DaysSinceLastPayment", (RockDateTime.Now - lastPaymentDate.Value).Days);
                }
                else
                {
                    scheduleSummary.Add("DaysSinceLastPayment", null);
                }

                scheduleSummary.Add("PersonName", transactionSchedule.AuthorizedPersonAlias != null && transactionSchedule.AuthorizedPersonAlias.Person != null ? transactionSchedule.AuthorizedPersonAlias.Person.FullName : string.Empty);
                scheduleSummary.Add("CurrencyType", (transactionSchedule.FinancialPaymentDetail != null && transactionSchedule.FinancialPaymentDetail.CurrencyTypeValue != null) ? transactionSchedule.FinancialPaymentDetail.CurrencyTypeValue.Value : string.Empty);
                scheduleSummary.Add("CreditCardType", (transactionSchedule.FinancialPaymentDetail != null && transactionSchedule.FinancialPaymentDetail.CreditCardTypeValue != null) ? transactionSchedule.FinancialPaymentDetail.CreditCardTypeValue.Value : string.Empty);
                scheduleSummary.Add("AccountNumberMasked", (transactionSchedule.FinancialPaymentDetail != null) ? transactionSchedule.FinancialPaymentDetail.AccountNumberMasked ?? string.Empty : string.Empty);
                scheduleSummary.Add("UrlEncryptedKey", transactionSchedule.UrlEncodedKey);
                scheduleSummary.Add("Frequency", transactionSchedule.TransactionFrequencyValue.Value);
                scheduleSummary.Add("FrequencyDescription", transactionSchedule.TransactionFrequencyValue.Description);
                scheduleSummary.Add("Status", transactionSchedule.Status);
                scheduleSummary.Add("CardExpirationDate", transactionSchedule.FinancialPaymentDetail.ExpirationDate);
                scheduleSummary.Add("CardIsExpired", transactionSchedule.FinancialPaymentDetail.CardExpirationDate < RockDateTime.Now);

                List <Dictionary <string, object> > summaryDetails = new List <Dictionary <string, object> >();
                decimal totalAmount = 0;

                foreach (FinancialScheduledTransactionDetail detail in transactionSchedule.ScheduledTransactionDetails)
                {
                    Dictionary <string, object> detailSummary = new Dictionary <string, object>();
                    detailSummary.Add("AccountId", detail.Account.Id);
                    detailSummary.Add("AccountName", detail.Account.Name);
                    detailSummary.Add("Amount", detail.Amount);
                    detailSummary.Add("Summary", detail.Summary);

                    summaryDetails.Add(detailSummary);

                    totalAmount += detail.Amount;
                }

                scheduleSummary.Add("ScheduledAmount", totalAmount);
                scheduleSummary.Add("TransactionDetails", summaryDetails);
                scheduleSummary.Add("IsHostedGateway", useHostedGatewayEditPage);
                if (useHostedGatewayEditPage)
                {
                    scheduleSummary.Add("EditPage", LinkedPageRoute(AttributeKey.ScheduledTransactionEditPageHosted));
                }
                else
                {
                    scheduleSummary.Add("EditPage", LinkedPageRoute(AttributeKey.ScheduledTransactionEditPage));
                }

                Dictionary <string, object> schedule = LavaHelper.GetCommonMergeFields(this.RockPage);
                schedule.Add("ScheduledTransaction", scheduleSummary);

                // merge into content
                Literal lLavaContent = ( Literal )e.Item.FindControl("lLavaContent");
                lLavaContent.Text = GetAttributeValue(AttributeKey.Template).ResolveMergeFields(schedule);
            }
        }
        /// <summary>
        /// Updates the scheduled payment.
        /// </summary>
        /// <param name="usePaymentToken">if set to <c>true</c> [use payment token].</param>
        /// <param name="paymentToken">The payment token.</param>
        protected void UpdateScheduledPayment(bool usePaymentToken, string paymentToken = null)
        {
            var giftTerm = this.GetAttributeValue(AttributeKey.GiftTerm);

            if (dtpStartDate.SelectedDate <= RockDateTime.Today)
            {
                nbUpdateScheduledPaymentWarning.Visible = true;
                nbUpdateScheduledPaymentWarning.Text    = string.Format("When scheduling a {0}, make sure the starting date is in the future (after today)", giftTerm.ToLower());
                return;
            }

            var rockContext = new RockContext();

            var financialScheduledTransactionService = new FinancialScheduledTransactionService(rockContext);
            int scheduledTransactionId        = hfScheduledTransactionId.Value.AsInteger();
            var financialScheduledTransaction = financialScheduledTransactionService.Get(scheduledTransactionId);

            financialScheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
            financialScheduledTransaction.TransactionFrequencyValueId = ddlFrequency.SelectedValue.AsInteger();

            ReferencePaymentInfo referencePaymentInfo;

            var person = financialScheduledTransaction.AuthorizedPersonAlias.Person;

            string errorMessage;

            var financialGateway          = this.FinancialGateway;
            var financialGatewayComponent = this.FinancialGatewayComponent;

            if (usePaymentToken)
            {
                referencePaymentInfo           = new ReferencePaymentInfo();
                referencePaymentInfo.FirstName = person.FirstName;
                referencePaymentInfo.LastName  = person.LastName;

                referencePaymentInfo.UpdateAddressFieldsFromAddressControl(acBillingAddress);

                referencePaymentInfo.ReferenceNumber = paymentToken;

                var customerToken = financialGatewayComponent.CreateCustomerAccount(this.FinancialGateway, referencePaymentInfo, out errorMessage);

                if (errorMessage.IsNotNullOrWhiteSpace() || customerToken.IsNullOrWhiteSpace())
                {
                    nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                    nbMessage.Text    = errorMessage ?? "Unknown Error";
                    nbMessage.Visible = true;
                    return;
                }

                referencePaymentInfo.GatewayPersonIdentifier = customerToken;
            }
            else
            {
                var savedAccountId = ddlPersonSavedAccount.SelectedValue.AsInteger();

                var savedAccount = new FinancialPersonSavedAccountService(rockContext).Get(savedAccountId);
                if (savedAccount != null)
                {
                    referencePaymentInfo = savedAccount.GetReferencePayment();
                }
                else
                {
                    throw new Exception("Unable to determine Saved Account");
                }
            }

            var selectedAccountAmounts = caapPromptForAccountAmounts.AccountAmounts.Where(a => a.Amount.HasValue && a.Amount.Value != 0).Select(a => new { a.AccountId, Amount = a.Amount.Value }).ToArray();

            referencePaymentInfo.Amount = selectedAccountAmounts.Sum(a => a.Amount);

            var successfullyUpdated = financialGatewayComponent.UpdateScheduledPayment(financialScheduledTransaction, referencePaymentInfo, out errorMessage);

            if (!successfullyUpdated)
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbMessage.Text    = errorMessage ?? "Unknown Error";
                nbMessage.Visible = true;
                return;
            }

            financialScheduledTransaction.FinancialPaymentDetail.SetFromPaymentInfo(referencePaymentInfo, financialGatewayComponent as GatewayComponent, rockContext);

            var selectedAccountIds        = selectedAccountAmounts.Select(a => a.AccountId).ToArray();
            var deletedTransactionDetails = financialScheduledTransaction.ScheduledTransactionDetails.ToList().Where(a => selectedAccountIds.Contains(a.AccountId)).ToList();

            foreach (var deletedTransactionDetail in deletedTransactionDetails)
            {
                financialScheduledTransaction.ScheduledTransactionDetails.Remove(deletedTransactionDetail);
            }

            foreach (var selectedAccountAmount in selectedAccountAmounts)
            {
                var scheduledTransactionDetail = financialScheduledTransaction.ScheduledTransactionDetails.FirstOrDefault(a => a.AccountId == selectedAccountAmount.AccountId);
                if (scheduledTransactionDetail == null)
                {
                    scheduledTransactionDetail           = new FinancialScheduledTransactionDetail();
                    scheduledTransactionDetail.AccountId = selectedAccountAmount.AccountId;
                    financialScheduledTransaction.ScheduledTransactionDetails.Add(scheduledTransactionDetail);
                }

                scheduledTransactionDetail.Amount = selectedAccountAmount.Amount;
            }

            rockContext.SaveChanges();

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });
            var finishLavaTemplate = this.GetAttributeValue(AttributeKey.FinishLavaTemplate);

            mergeFields.Add("Transaction", financialScheduledTransaction);
            mergeFields.Add("Person", financialScheduledTransaction.AuthorizedPersonAlias.Person);
            mergeFields.Add("PaymentDetail", financialScheduledTransaction.FinancialPaymentDetail);
            mergeFields.Add("BillingLocation", financialScheduledTransaction.FinancialPaymentDetail.BillingLocation);

            pnlPromptForChanges.Visible   = false;
            pnlTransactionSummary.Visible = true;

            lTransactionSummaryHTML.Text = finishLavaTemplate.ResolveMergeFields(mergeFields);
        }
예제 #25
0
        /// <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;
            }
        }
예제 #26
0
        protected void BindData()
        {
            List <int> campusIds  = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            // Initialize services
            var rockContext           = new RockContext();
            var publishGroupService   = new PublishGroupService(rockContext);
            var attributeService      = new AttributeService(rockContext);
            var attributeValueService = new AttributeValueService(rockContext);

            //Get the entity types
            var publishGroupEntityTypeId = EntityTypeCache.Get(typeof(PublishGroup)).Id;
            var groupEntityTypeId        = EntityTypeCache.Get(typeof(Group)).Id;

            //Attribute Queryables
            var publishGroupAttributeQry = attributeService.Queryable()
                                           .Where(a => a.EntityTypeId == publishGroupEntityTypeId)
                                           .Select(a => a.Id);

            var groupAttributeQry = attributeService.Queryable()
                                    .Where(a => a.EntityTypeId == groupEntityTypeId)
                                    .Select(a => a.Id);

            //Attribute Value Queryables
            var publishGroupAttributeValueQry = attributeValueService.Queryable()
                                                .Where(av => publishGroupAttributeQry.Contains(av.AttributeId));

            var groupAttributeValueQry = attributeValueService.Queryable()
                                         .Where(av => groupAttributeQry.Contains(av.AttributeId));


            var qry = publishGroupService
                      .Queryable("Group")
                      .Where(pg => !pg.IsHidden)                                                                             //Is not hidden from list
                      .Where(pg => pg.PublishGroupStatus == PublishGroupStatus.Approved)                                     //Approved
                      .Where(pg => pg.StartDateTime <= Rock.RockDateTime.Today && pg.EndDateTime >= Rock.RockDateTime.Today) //Active
                      .Where(pg => pg.Group.GroupType.GroupCapacityRule == GroupCapacityRule.None ||
                             pg.Group.GroupCapacity == null || pg.Group.GroupCapacity == 0 ||
                             pg.Group.Members.Count() < pg.Group.GroupCapacity);      // Not full


            // Filter by campus
            if (campusIds.Any())
            {
                qry = qry
                      .Where(pg =>
                             !pg.Group.CampusId.HasValue || // All
                             campusIds.Contains(pg.Group.CampusId.Value));
            }

            // Filter by Category
            if (categories.Any())
            {
                qry = qry
                      .Where(pg => pg.AudienceValues
                             .Any(dv => categories.Contains(dv.Id)));
            }

            //Group join in attributes
            var mixedQry = qry
                           .GroupJoin(publishGroupAttributeValueQry,
                                      pg => pg.Id,
                                      av => av.EntityId,
                                      (pg, av) => new { pg, av })
                           .GroupJoin(groupAttributeValueQry,
                                      pg => pg.pg.GroupId,
                                      av => av.EntityId,
                                      (pg, av) => new { PublishGroup = pg.pg, PublishGroupAttributes = pg.av, GroupAttributes = av });

            //Add in the attributes in the proper format
            var publishGroups = new List <PublishGroup>();

            foreach (var item in mixedQry.ToList())
            {
                var publishGroup = item.PublishGroup;
                publishGroup.AttributeValues = item.PublishGroupAttributes.ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));
                publishGroup.Attributes      = item.PublishGroupAttributes.ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));
                if (publishGroup.Group == null)
                {
                    continue;
                }
                publishGroup.Group.AttributeValues = item.GroupAttributes.ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));
                publishGroup.Group.Attributes      = item.GroupAttributes.ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));
                publishGroups.Add(publishGroup);
            }

            // Output mergefields.
            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("PublishGroups", publishGroups);

            lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
예제 #27
0
        /// <summary>
        /// Bind the grid to the donations that should be visible for the proper context.
        /// </summary>
        protected void BindGrid(bool isExporting = false)
        {
            var   rockContext        = new RockContext();
            var   groupMemberService = new GroupMemberService(rockContext);
            var   financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);
            var   entityTypeIdGroupMember           = EntityTypeCache.GetId <GroupMember>();
            var   hideGridColumns = GetAttributeValue("HideGridColumns").Split(',');
            var   hideGridActions = GetAttributeValue("HideGridActions").Split(',');
            var   mergeFields     = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);
            Group group           = null;
            Dictionary <int, GroupMember> groupMembers;

            //
            // Get the donations for the entire opportunity group or for just the
            // one individual being viewed.
            //
            if (ContextEntity <Group>() != null)
            {
                group = ContextEntity <Group>();

                groupMembers = groupMemberService.Queryable()
                               .Where(m => m.GroupId == group.Id)
                               .ToDictionary(m => m.Id);
            }
            else
            {
                var groupMember = ContextEntity <GroupMember>();
                group = groupMember.Group;

                groupMembers = new Dictionary <int, GroupMember> {
                    { groupMember.Id, groupMember }
                };
            }

            //
            // Get the list of donation entries for the grid that match the list of members.
            //
            var groupMemberIds = groupMembers.Keys.ToList();
            var donations      = financialTransactionDetailService.Queryable()
                                 .Where(d => d.EntityTypeId == entityTypeIdGroupMember && groupMemberIds.Contains(d.EntityId.Value))
                                 .ToList()
                                 .Select(d => new
            {
                IsExporting = isExporting,
                DonorId     = d.Transaction.AuthorizedPersonAlias.PersonId,
                Donor       = d.Transaction.AuthorizedPersonAlias.Person,
                Group       = group,
                Participant = groupMembers[d.EntityId.Value],
                Amount      = d.Amount,
                Address     = d.Transaction.AuthorizedPersonAlias.Person.GetHomeLocation(rockContext).ToStringSafe().ConvertCrLfToHtmlBr(),
                Date        = d.Transaction.TransactionDateTime
            }).AsQueryable();

            //
            // Apply user sorting or default to donor name.
            //
            if (gDonations.SortProperty != null)
            {
                donations = donations.Sort(gDonations.SortProperty);
            }
            else
            {
                donations = donations.Sort(new SortProperty {
                    Property = "Donor.LastName, Donor.NickName"
                });
            }

            gDonations.ObjectList = donations.Select(d => d.Donor)
                                    .DistinctBy(p => p.Id)
                                    .Cast <object>()
                                    .ToDictionary(p => (( Person )p).Id.ToString());

            //
            // Hide any columns they don't want visible to the user.
            //
            gDonations.ColumnsOfType <CurrencyField>()
            .First(c => c.DataField == "Amount")
            .Visible = !hideGridColumns.Contains("Amount");
            gDonations.ColumnsOfType <RockBoundField>()
            .First(c => c.DataField == "Address")
            .Visible = !hideGridColumns.Contains("Donor Address");
            gDonations.ColumnsOfType <RockBoundField>()
            .First(c => c.DataField == "Donor.Email")
            .Visible = !hideGridColumns.Contains("Donor Email");
            gDonations.ColumnsOfType <RockLiteralField>()
            .First(c => c.HeaderText == "Participant")
            .Visible = !hideGridColumns.Contains("Participant") && ContextEntity <GroupMember>() == null;

            //
            // Hide any grid actions they don't want visible to the user.
            //
            gDonations.Actions.ShowCommunicate   = !hideGridActions.Contains("Communicate");
            gDonations.Actions.ShowMergePerson   = !hideGridActions.Contains("Merge Person");
            gDonations.Actions.ShowBulkUpdate    = !hideGridActions.Contains("Bulk Update");
            gDonations.Actions.ShowExcelExport   = !hideGridActions.Contains("Excel Export");
            gDonations.Actions.ShowMergeTemplate = !hideGridActions.Contains("Merge Template");

            //
            // If all the grid actions are hidden, hide the select column too.
            //
            gDonations.ColumnsOfType <SelectField>().First().Visible = gDonations.Actions.ShowCommunicate || gDonations.Actions.ShowMergePerson || gDonations.Actions.ShowBulkUpdate || gDonations.Actions.ShowExcelExport || gDonations.Actions.ShowMergeTemplate;

            gDonations.DataSource = donations.ToList();
            gDonations.DataBind();
        }