예제 #1
0
        public void RemoveLavaComments_CommentInRawTag_IsNotRemoved()
        {
            var input = @"
//- Line Comment: A comment that is confined to a single line.
/- Block Comment: A comment that can span...
   ... multiple lines. -/
Example Start<br>
Valid Lava Comment Styles are:
{% raw %}//- Line Comment: A comment that is confined to a single line.
or
/- Block Comment: A comment that can span...
   ... multiple lines. -/{% endraw %}
Example End<br>
";

            var expectedOutput = @"


Example Start<br>
Valid Lava Comment Styles are:
{% raw %}//- Line Comment: A comment that is confined to a single line.
or
/- Block Comment: A comment that can span...
   ... multiple lines. -/{% endraw %}
Example End<br>
";

            var templateUncommented = LavaHelper.RemoveLavaComments(input);

            Assert.That.AreEqual(expectedOutput, templateUncommented);
        }
예제 #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>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void OnRender(ILavaRenderContext context, TextWriter result)
        {
            try
            {
                var dataSource = new EventOccurrencesLavaDataSource();

                _settings.ParseFromMarkup(_attributesMarkup, context);

                var events = dataSource.GetEventOccurrencesForCalendar(_settings, LavaHelper.GetRockContextFromLavaContext(context));

                AddLavaMergeFieldsToContext(context, events);

                base.OnRender(context, result);
            }
            catch (Exception ex)
            {
                var message = "Calendar Events not available. " + ex.Message;

                if (_renderErrors)
                {
                    result.Write(message);
                }
                else
                {
                    ExceptionLogService.LogException(ex);
                }
            }
        }
예제 #4
0
        public void RemoveLavaComments_CommentInStringLiteral_IsNotRemoved()
        {
            var input = @"
-- Begin Example --
Lava Comments can be added as follows:
For a single line comment, use ""//- Single Line Comment 1"" or '//- Single Line Comment 2'.
For a block comment, use ""/- Block Comment 1...
... like this! -/""
or '/- Block Comment 2...
... like this! -/'
-- End Example --
";

            var expectedOutput = @"
-- Begin Example --
Lava Comments can be added as follows:
For a single line comment, use ""//- Single Line Comment 1"" or '//- Single Line Comment 2'.
For a block comment, use ""/- Block Comment 1...
... like this! -/""
or '/- Block Comment 2...
... like this! -/'
-- End Example --
";

            var templateUncommented = LavaHelper.RemoveLavaComments(input);

            Assert.That.AreEqual(expectedOutput, templateUncommented);
        }
예제 #5
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 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();
            }
        }
예제 #7
0
        private Template GetTemplate()
        {
            var cacheTemplate = LavaTemplateCache.Get(CacheKey(), GetAttributeValue(AttributeKey.Template));

            LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue(AttributeKey.Template));

            return(cacheTemplate != null ? cacheTemplate.Template as Template : null);
        }
        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);
        }
예제 #9
0
        public void IsLavaTemplate_CommentContainingQuotedText_ReturnsTrue()
        {
            var input = @"
Line 1<br>
Line 2<br> /- I said ""This comment contains some quoted text"" -/<br>
Line 3<br>
";

            var isTemplate = LavaHelper.IsLavaTemplate(input);

            Assert.That.AreEqual(true, isTemplate);
        }
예제 #10
0
        public void IsLavaTemplate_HtmlWithComment_RendersTrue()
        {
            var input = @"
Line 1<br>
Line 2 Start<br>/- This is an inline block comment -/Line 2 End<br>
Line 3<br>
";

            var isTemplate = LavaHelper.IsLavaTemplate(input);

            Assert.That.AreEqual(true, isTemplate);
        }
예제 #11
0
        public void IsLavaTemplate_TextWithDoubleQuotedComment_ReturnsFalse()
        {
            // In Liquid, a string must be surrounded by a pair of double quotes or single quotes: "the 'quoted' text" or 'the "quoted" text'.
            var input = @"
Line 1<br>
Line 2<br>Here is a sample comment: ""/- This is a double-quoted inline comment with an internal 'quote' -/""<br>
Line 3<br>
";

            var isTemplate = LavaHelper.IsLavaTemplate(input);

            Assert.That.AreEqual(false, isTemplate);
        }
        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);
            }
        }
예제 #13
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;
                }
            }
        }
예제 #14
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);
        }
예제 #15
0
        public void RemoveLavaComments_BlockCommentInline_RendersCorrectLineContent()
        {
            var input = @"
Line 1<br>
Line 2 Start<br>/- This is an inline block comment -/Line 2 End<br>
Line 3<br>
";

            var expectedOutput = @"
Line 1<br>
Line 2 Start<br>Line 2 End<br>
Line 3<br>
";

            var templateUncommented = LavaHelper.RemoveLavaComments(input);

            Assert.That.AreEqual(expectedOutput, templateUncommented);
        }
예제 #16
0
        public void RemoveLavaComments_LineCommentAfterContent_ReturnsContent()
        {
            var input = @"
Line 1<br>
Line 2<br>//- This is a single line comment.
Line 3<br>
";

            var expectedOutput = @"
Line 1<br>
Line 2<br>
Line 3<br>
";

            var templateUncommented = LavaHelper.RemoveLavaComments(input);

            Assert.That.AreEqual(expectedOutput, templateUncommented);
        }
예제 #17
0
        public void RemoveLavaComments_LineCommentContainingQuotedString_IsRemoved()
        {
            var input = @"
Line 1<br>
Line 2<br>//-Please enter the following: ""//- This is a single line comment."" and '//- This is also a single line comment'.
Line 3<br>
";

            var expectedOutput = @"
Line 1<br>
Line 2<br>
Line 3<br>
";

            var templateUncommented = LavaHelper.RemoveLavaComments(input);

            Assert.That.AreEqual(expectedOutput, templateUncommented);
        }
예제 #18
0
        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);
        }
예제 #20
0
        public void RemoveLavaComments_BlockCommentSpanningMultipleLines_RemovesNewLinesContainedInComment()
        {
            var input = @"
Line 1<br>
Line 2 Start<br>/- This is a block comment...


   ... spanning multiple lines. -/Line 2 End<br>
Line 3<br>
";

            var expectedOutput = @"
Line 1<br>
Line 2 Start<br>Line 2 End<br>
Line 3<br>
";

            var templateUncommented = LavaHelper.RemoveLavaComments(input);

            Assert.That.AreEqual(expectedOutput, templateUncommented);
        }
예제 #21
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));
        }
예제 #22
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));
        }
예제 #23
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;
        }
예제 #24
0
        private static LavaTemplateCache Load(string content)
        {
            // Strip out Lava comments before parsing the template because they are not recognized by standard Liquid syntax.
            content = LavaHelper.RemoveLavaComments(content);

            var template = Template.Parse(content);

            /*
             * 2/19/2020 - JPH
             * The DotLiquid library's Template object was not originally designed to be thread safe, but a PR has since
             * been merged into that repository to add this functionality (https://github.com/dotliquid/dotliquid/pull/220).
             * We have cherry-picked the PR's changes into our DotLiquid project, allowing the Template to operate safely
             * in a multithreaded context, which can happen often with our cached Template instances.
             *
             * Reason: Rock Issue #4084, Weird Behavior with Lava Includes
             */
            template.MakeThreadSafe();

            var lavaTemplate = new LavaTemplateCache {
                Template = template
            };

            return(lavaTemplate);
        }
예제 #25
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);
        }
예제 #26
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;
            }
        }
        /// <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);
        }
예제 #28
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;
        }
        /// <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);
            }
        }
예제 #30
0
        private void Map()
        {
            string mapStylingFormat = @"
                        <style>
                            #map_wrapper {{
                                height: {0}px;
                            }}

                            #map_canvas {{
                                width: 100%;
                                height: 100%;
                                border-radius: var(--border-radius-base);
                            }}
                        </style>";

            lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight"));

            string settingGroupTypeId     = GetAttributeValue("GroupType");
            string queryStringGroupTypeId = PageParameter("GroupTypeId");

            if ((string.IsNullOrWhiteSpace(settingGroupTypeId) && string.IsNullOrWhiteSpace(queryStringGroupTypeId)))
            {
                pnlMap.Visible = false;
                lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display as a block setting or pass a GroupTypeId as a query parameter.</div>";
            }
            else
            {
                var rockContext = new RockContext();

                pnlMap.Visible = true;

                int groupsMapped    = 0;
                int groupsWithNoGeo = 0;

                StringBuilder sbGroupJson       = new StringBuilder();
                StringBuilder sbGroupsWithNoGeo = new StringBuilder();

                Guid?groupType   = null;
                int  groupTypeId = -1;

                if (!string.IsNullOrWhiteSpace(settingGroupTypeId))
                {
                    groupType = new Guid(settingGroupTypeId);
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(queryStringGroupTypeId) && Int32.TryParse(queryStringGroupTypeId, out groupTypeId))
                    {
                        groupType = new GroupTypeService(rockContext).Get(groupTypeId).Guid;
                    }
                }

                if (groupType != null)
                {
                    Template      template     = null;
                    ILavaTemplate lavaTemplate = null;

                    if (LavaService.RockLiquidIsEnabled)
                    {
                        if (GetAttributeValue("ShowMapInfoWindow").AsBoolean())
                        {
                            template = Template.Parse(GetAttributeValue("InfoWindowContents").Trim());

                            LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue("InfoWindowContents").Trim());
                        }
                        else
                        {
                            template = Template.Parse(string.Empty);
                        }
                    }
                    else
                    {
                        string templateContent;

                        if (GetAttributeValue("ShowMapInfoWindow").AsBoolean())
                        {
                            templateContent = GetAttributeValue("InfoWindowContents").Trim();
                        }
                        else
                        {
                            templateContent = string.Empty;
                        }

                        var parseResult = LavaService.ParseTemplate(templateContent);

                        lavaTemplate = parseResult.Template;
                    }

                    var groupPageRef = new PageReference(GetAttributeValue("GroupDetailPage"));

                    // create group detail link for use in map's info window
                    var personPageParams = new Dictionary <string, string>();
                    personPageParams.Add("PersonId", string.Empty);
                    var personProfilePage = LinkedPageUrl("PersonProfilePage", personPageParams);

                    var groupEntityType = EntityTypeCache.Get(typeof(Group));
                    var dynamicGroups   = new List <dynamic>();


                    // Create query to get attribute values for selected attribute keys.
                    var attributeKeys   = GetAttributeValue("Attributes").SplitDelimitedValues().ToList();
                    var attributeValues = new AttributeValueService(rockContext).Queryable("Attribute")
                                          .Where(v =>
                                                 v.Attribute.EntityTypeId == groupEntityType.Id &&
                                                 attributeKeys.Contains(v.Attribute.Key));

                    GroupService groupService = new GroupService(rockContext);
                    var          groups       = groupService.Queryable()
                                                .Where(g => g.GroupType.Guid == groupType)
                                                .Select(g => new
                    {
                        Group           = g,
                        GroupId         = g.Id,
                        GroupName       = g.Name,
                        GroupGuid       = g.Guid,
                        GroupMemberTerm = g.GroupType.GroupMemberTerm,
                        GroupCampus     = g.Campus.Name,
                        IsActive        = g.IsActive,
                        GroupLocation   = g.GroupLocations
                                          .Where(l => l.Location.GeoPoint != null)
                                          .Select(l => new
                        {
                            l.Location.Street1,
                            l.Location.Street2,
                            l.Location.City,
                            l.Location.State,
                            PostalCode = l.Location.PostalCode,
                            Latitude   = l.Location.GeoPoint.Latitude,
                            Longitude  = l.Location.GeoPoint.Longitude,
                            Name       = l.GroupLocationTypeValue.Value
                        }).FirstOrDefault(),
                        GroupMembers    = g.Members,
                        AttributeValues = attributeValues
                                          .Where(v => v.EntityId == g.Id)
                    });


                    if (GetAttributeValue("IncludeInactiveGroups").AsBoolean() == false)
                    {
                        groups = groups.Where(g => g.IsActive == true);
                    }

                    // Create dynamic object to include attribute values
                    foreach (var group in groups)
                    {
                        dynamic dynGroup = new ExpandoObject();
                        dynGroup.GroupId   = group.GroupId;
                        dynGroup.GroupName = group.GroupName;

                        // create group detail link for use in map's info window
                        if (groupPageRef.PageId > 0)
                        {
                            var groupPageParams = new Dictionary <string, string>();
                            groupPageParams.Add("GroupId", group.GroupId.ToString());
                            groupPageRef.Parameters  = groupPageParams;
                            dynGroup.GroupDetailPage = groupPageRef.BuildUrl();
                        }
                        else
                        {
                            dynGroup.GroupDetailPage = string.Empty;
                        }

                        dynGroup.PersonProfilePage = personProfilePage;
                        dynGroup.GroupMemberTerm   = group.GroupMemberTerm;
                        dynGroup.GroupCampus       = group.GroupCampus;
                        dynGroup.GroupLocation     = group.GroupLocation;

                        var groupAttributes = new List <dynamic>();
                        foreach (AttributeValue value in group.AttributeValues)
                        {
                            var attrCache     = AttributeCache.Get(value.AttributeId);
                            var dictAttribute = new Dictionary <string, object>();
                            dictAttribute.Add("Key", attrCache.Key);
                            dictAttribute.Add("Name", attrCache.Name);

                            if (attrCache != null)
                            {
                                dictAttribute.Add("Value", attrCache.FieldType.Field.FormatValueAsHtml(null, attrCache.EntityTypeId, group.GroupId, value.Value, attrCache.QualifierValues, false));
                            }
                            else
                            {
                                dictAttribute.Add("Value", value.Value);
                            }

                            groupAttributes.Add(dictAttribute);
                        }

                        dynGroup.Attributes = groupAttributes;

                        var groupMembers = new List <dynamic>();
                        foreach (GroupMember member in group.GroupMembers)
                        {
                            var dictMember = new Dictionary <string, object>();
                            dictMember.Add("Id", member.Person.Id);
                            dictMember.Add("GuidP", member.Person.Guid);
                            dictMember.Add("NickName", member.Person.NickName);
                            dictMember.Add("LastName", member.Person.LastName);
                            dictMember.Add("RoleName", member.GroupRole.Name);
                            dictMember.Add("Email", member.Person.Email);
                            dictMember.Add("PhotoGuid", member.Person.Photo != null ? member.Person.Photo.Guid : Guid.Empty);

                            var phoneTypes = new List <dynamic>();
                            foreach (PhoneNumber p in member.Person.PhoneNumbers)
                            {
                                var dictPhoneNumber = new Dictionary <string, object>();
                                dictPhoneNumber.Add("Name", p.NumberTypeValue.Value);
                                dictPhoneNumber.Add("Number", p.ToString());
                                phoneTypes.Add(dictPhoneNumber);
                            }

                            dictMember.Add("PhoneTypes", phoneTypes);

                            groupMembers.Add(dictMember);
                        }

                        dynGroup.GroupMembers = groupMembers;

                        dynamicGroups.Add(dynGroup);
                    }

                    foreach (var group in dynamicGroups)
                    {
                        if (group.GroupLocation != null && group.GroupLocation.Latitude != null)
                        {
                            groupsMapped++;
                            var groupDict = group as IDictionary <string, object>;

                            string infoWindow;

                            if (LavaService.RockLiquidIsEnabled)
                            {
                                infoWindow = template.Render(Hash.FromDictionary(groupDict)).Replace("\n", string.Empty);
                            }
                            else
                            {
                                var result = LavaService.RenderTemplate(lavaTemplate, groupDict);

                                infoWindow = result.Text;

                                if (!result.HasErrors)
                                {
                                    infoWindow = infoWindow.Replace("\n", string.Empty);
                                }
                            }

                            sbGroupJson.Append(string.Format(
                                                   @"{{ ""name"":""{0}"" , ""latitude"":""{1}"", ""longitude"":""{2}"", ""infowindow"":""{3}"" }},",
                                                   HttpUtility.HtmlEncode(group.GroupName),
                                                   group.GroupLocation.Latitude,
                                                   group.GroupLocation.Longitude,
                                                   HttpUtility.HtmlEncode(infoWindow)));
                        }
                        else
                        {
                            groupsWithNoGeo++;

                            if (!string.IsNullOrWhiteSpace(group.GroupDetailPage))
                            {
                                sbGroupsWithNoGeo.Append(string.Format(@"<li><a href='{0}'>{1}</a></li>", group.GroupDetailPage, group.GroupName));
                            }
                            else
                            {
                                sbGroupsWithNoGeo.Append(string.Format(@"<li>{0}</li>", group.GroupName));
                            }
                        }
                    }

                    string groupJson = sbGroupJson.ToString();

                    // remove last comma
                    if (groupJson.Length > 0)
                    {
                        groupJson = groupJson.Substring(0, groupJson.Length - 1);
                    }

                    // add styling to map
                    string styleCode   = "null";
                    string markerColor = "FE7569";

                    DefinedValueCache dvcMapStyle = DefinedValueCache.Get(GetAttributeValue("MapStyle").AsGuid());
                    if (dvcMapStyle != null)
                    {
                        styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle");
                        var colors = dvcMapStyle.GetAttributeValue("Colors").Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        if (colors.Any())
                        {
                            markerColor = colors.First().Replace("#", "");
                        }
                    }

                    // write script to page
                    string mapScriptFormat = @" <script>
                                                Sys.Application.add_load(function () {{
                                                    var groupData = JSON.parse('{{ ""groups"" : [ {0} ]}}');
                                                    var showInfoWindow = {1};
                                                    var mapStyle = {2};
                                                    var pinColor = '{3}';

                                                    var pinImage = {{
                                                        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
                                                        fillColor: '#' + pinColor,
                                                        fillOpacity: 1,
                                                        strokeColor: '#000',
                                                        strokeWeight: 1,
                                                        scale: 1,
                                                        labelOrigin: new google.maps.Point(0,-28)
                                                    }};

                                                    initializeMap();

                                                    function initializeMap() {{
                                                        console.log(mapStyle);
                                                        var map;
                                                        var bounds = new google.maps.LatLngBounds();
                                                        var mapOptions = {{
                                                            mapTypeId: 'roadmap',
                                                            styles: mapStyle
                                                        }};

                                                        // Display a map on the page
                                                        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
                                                        map.setTilt(45);

                                                        // Display multiple markers on a map
                                                        if (showInfoWindow) {{
                                                            var infoWindow = new google.maps.InfoWindow(), marker, i;
                                                        }}

                                                        // Loop through our array of markers & place each one on the map
                                                        $.each(groupData.groups, function (i, group) {{

                                                            var position = new google.maps.LatLng(group.latitude, group.longitude);
                                                            bounds.extend(position);

                                                            marker = new google.maps.Marker({{
                                                                position: position,
                                                                map: map,
                                                                title: htmlDecode(group.name),
                                                                icon: pinImage,
                                                                label: String.fromCharCode(9679)
                                                            }});

                                                            // Allow each marker to have an info window
                                                            if (showInfoWindow) {{
                                                                google.maps.event.addListener(marker, 'click', (function (marker, i) {{
                                                                    return function () {{
                                                                        infoWindow.setContent(htmlDecode(groupData.groups[i].infowindow));
                                                                        infoWindow.open(map, marker);
                                                                    }}
                                                                }})(marker, i));
                                                            }}

                                                            map.fitBounds(bounds);

                                                        }});

                                                        // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
                                                        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {{
                                                            google.maps.event.removeListener(boundsListener);
                                                        }});
                                                    }}

                                                    function htmlDecode(input) {{
                                                        var e = document.createElement('div');
                                                        e.innerHTML = input;
                                                        return e.childNodes.length === 0 ? """" : e.childNodes[0].nodeValue;
                                                    }}
                                                }});
                                            </script>";

                    string mapScript = string.Format(
                        mapScriptFormat,
                        groupJson,
                        GetAttributeValue("ShowMapInfoWindow").AsBoolean().ToString().ToLower(),
                        styleCode,
                        markerColor);

                    ScriptManager.RegisterStartupScript(pnlMap, pnlMap.GetType(), "group-mapper-script", mapScript, false);

                    if (groupsMapped == 0)
                    {
                        pnlMap.Visible = false;
                        lMessages.Text = @" <p>
                                                <div class='alert alert-warning fade in'>No groups were able to be mapped. You may want to check your configuration.</div>
                                        </p>";
                    }
                    else
                    {
                        // output any warnings
                        if (groupsWithNoGeo > 0)
                        {
                            string messagesFormat = @" <p>
                                                <div class='alert alert-warning fade in'>Some groups could not be mapped.
                                                    <button type='button' class='close' data-dismiss='alert' aria-hidden='true'><i class='fa fa-times'></i></button>
                                                    <small><a data-toggle='collapse' data-parent='#accordion' href='#map-error-details'>Show Details</a></small>
                                                    <div id='map-error-details' class='collapse'>
                                                        <p class='margin-t-sm'>
                                                            <strong>Groups That Could Not Be Mapped</strong>
                                                            <ul>
                                                                {0}
                                                            </ul>
                                                        </p>
                                                    </div>
                                                </div>
                                            </p>";
                            lMessages.Text = string.Format(messagesFormat, sbGroupsWithNoGeo.ToString());
                        }
                    }
                }
                else
                {
                    pnlMap.Visible = false;
                    lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display and a location type to use.</div>";
                }
            }
        }