public string CalculateSlidingDateRange(Rock.Web.UI.Controls.SlidingDateRangePicker.SlidingDateRangeType slidingDateRangeType, Rock.Web.UI.Controls.SlidingDateRangePicker.TimeUnitType timeUnitType, int number = 1) { var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(string.Format("{0}|{1}|{2}||", slidingDateRangeType, number, timeUnitType)); return(dateRange.ToStringAutomatic()); }
/// <summary> /// Loads the chart. /// </summary> public void LoadChart() { lcAttendance.ShowTooltip = true; if (this.DetailPageGuid.HasValue) { lcAttendance.ChartClick += lcAttendance_ChartClick; } var dataSourceUrl = "~/api/Attendances/GetChartData"; var dataSourceParams = new Dictionary <string, object>(); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(drpSlidingDateRange.DelimitedValues); if (dateRange.Start.HasValue) { dataSourceParams.AddOrReplace("startDate", dateRange.Start.Value.ToString("o")); } if (dateRange.End.HasValue) { dataSourceParams.AddOrReplace("endDate", dateRange.End.Value.ToString("o")); } var groupBy = hfGroupBy.Value.ConvertToEnumOrNull <AttendanceGroupBy>() ?? AttendanceGroupBy.Week; lcAttendance.TooltipFormatter = null; switch (groupBy) { case AttendanceGroupBy.Week: { lcAttendance.Options.xaxis.tickSize = new string[] { "7", "day" }; lcAttendance.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = 'Weekend of <br />' + itemDate.toLocaleDateString(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case AttendanceGroupBy.Month: { lcAttendance.Options.xaxis.tickSize = new string[] { "1", "month" }; lcAttendance.TooltipFormatter = @" function(item) { var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = month_names[itemDate.getMonth()] + ' ' + itemDate.getFullYear(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case AttendanceGroupBy.Year: { lcAttendance.Options.xaxis.tickSize = new string[] { "1", "year" }; lcAttendance.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = itemDate.getFullYear(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; } dataSourceParams.AddOrReplace("groupBy", hfGroupBy.Value.AsInteger()); dataSourceParams.AddOrReplace("graphBy", hfGraphBy.Value.AsInteger()); if (cpCampuses.SelectedCampusIds.Any()) { dataSourceParams.AddOrReplace("campusIds", cpCampuses.SelectedCampusIds.AsDelimited(",")); } dataSourceParams.AddOrReplace("groupIds", GetSelectedGroupIds().AsDelimited(",")); SaveSettingsToUserPreferences(); dataSourceUrl += "?" + dataSourceParams.Select(s => string.Format("{0}={1}", s.Key, s.Value)).ToList().AsDelimited("&"); lcAttendance.DataSourceUrl = this.ResolveUrl(dataSourceUrl); if (pnlGrid.Visible) { BindGrid(); } }
/// <summary> /// Gets a filter expression for an entity property value. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="propertyType">Type of the property.</param> /// <returns></returns> public override Expression PropertyFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, Expression parameterExpression, string propertyName, Type propertyType) { if (filterValues.Count >= 2) { // uses Tab Delimited since slidingDateRangePicker is | delimited var filterValueValues = filterValues[1].Split(new string[] { "\t" }, StringSplitOptions.None); // Parse for RelativeValue of DateTime (if specified) filterValueValues[0] = ParseRelativeValue(filterValueValues[0]); string comparisonValue = filterValues[0]; if (comparisonValue != "0" && comparisonValue.IsNotNullOrWhiteSpace()) { ComparisonType comparisonType = comparisonValue.ConvertToEnum <ComparisonType>(ComparisonType.EqualTo); MemberExpression propertyExpression = Expression.Property(parameterExpression, propertyName); if (comparisonType == ComparisonType.Between && filterValueValues.Length > 1) { var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(filterValueValues[1]); ConstantExpression constantExpressionLower = dateRange.Start.HasValue ? Expression.Constant(dateRange.Start, typeof(DateTime)) : null; ConstantExpression constantExpressionUpper = dateRange.End.HasValue ? Expression.Constant(dateRange.End, typeof(DateTime)) : null; if (constantExpressionLower == null && constantExpressionUpper == null) { return(new NoAttributeFilterExpression()); } else { /* * Convert expressions to int if the property type is an int */ if (propertyType == typeof(int) || propertyType == typeof(int?)) { if (constantExpressionLower != null) { constantExpressionLower = Expression.Constant(Convert.ToDateTime(constantExpressionLower.Value).ToString("yyyyMMdd").AsInteger(), typeof(int)); } if (constantExpressionUpper != null) { constantExpressionUpper = Expression.Constant(Convert.ToDateTime(constantExpressionUpper.Value).ToString("yyyyMMdd").AsInteger(), typeof(int)); } } return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, constantExpressionLower, constantExpressionUpper)); } } else { var dateTime = filterValueValues[0].AsDateTime(); if (dateTime.HasValue) { ConstantExpression constantExpression = Expression.Constant(dateTime, typeof(DateTime)); if (propertyType == typeof(int) || propertyType == typeof(int?)) { constantExpression = Expression.Constant(dateTime?.ToString("yyyyMMdd").AsInteger(), typeof(int)); } return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, constantExpression)); } else { if (comparisonType == ComparisonType.IsBlank || comparisonType == ComparisonType.IsNotBlank) { return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, null)); } else { return(new NoAttributeFilterExpression()); } } } } } return(null); }
/// <summary> /// Sets the selection. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="controls">The controls.</param> /// <param name="selection">The selection.</param> public override void SetSelection(Type entityType, Control[] controls, string selection) { if (controls.Count() < 8) { return; } GroupPicker groupPicker = controls[0] as GroupPicker; RockCheckBox cbChildGroups = controls[1] as RockCheckBox; RockCheckBox cbIncludeSelectedGroup = controls[2] as RockCheckBox; RockCheckBox cbChildGroupsPlusDescendants = controls[3] as RockCheckBox; RockCheckBoxList cblRoles = controls[4] as RockCheckBoxList; RockDropDownList ddlGroupMemberStatus = controls[5] as RockDropDownList; RockCheckBox cbIncludeInactive = controls[6] as RockCheckBox; SlidingDateRangePicker addedOnDateRangePicker = controls[7] as SlidingDateRangePicker; SlidingDateRangePicker firstAttendanceDateRangePicker = controls[9] as SlidingDateRangePicker; SlidingDateRangePicker lastAttendanceDateRangePicker = controls[10] as SlidingDateRangePicker; string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 2) { List <Guid> groupGuids = selectionValues[0].Split(',').AsGuidList(); var groups = new GroupService(new RockContext()).GetByGuids(groupGuids); if (groups != null) { groupPicker.SetValues(groups); } if (selectionValues.Length >= 3) { cbChildGroups.Checked = selectionValues[2].AsBooleanOrNull() ?? false; } if (selectionValues.Length >= 6) { cbIncludeSelectedGroup.Checked = selectionValues[4].AsBooleanOrNull() ?? false; cbChildGroupsPlusDescendants.Checked = selectionValues[5].AsBooleanOrNull() ?? false; } else { cbIncludeSelectedGroup.Checked = true; cbChildGroupsPlusDescendants.Checked = true; } if (selectionValues.Length >= 7) { cbIncludeInactiveGroups.Checked = selectionValues[6].AsBooleanOrNull() ?? false; } else { // if options where saved before this option was added, set to false, even though it would have included inactive before cbIncludeInactiveGroups.Checked = false; } gp_SelectItem(this, new EventArgs()); string[] selectedRoleGuids = selectionValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in cblRoles.Items.OfType <ListItem>()) { item.Selected = selectedRoleGuids.Contains(item.Value); } if (selectionValues.Length >= 4) { ddlGroupMemberStatus.SetValue(selectionValues[3]); } else { ddlGroupMemberStatus.SetValue(string.Empty); } if (selectionValues.Length >= 8) { // convert comma delimited to pipe addedOnDateRangePicker.DelimitedValues = selectionValues[7].Replace(',', '|'); } if (selectionValues.Length >= 10) { // convert comma delimited to pipe firstAttendanceDateRangePicker.DelimitedValues = selectionValues[8].Replace(',', '|'); // convert comma delimited to pipe lastAttendanceDateRangePicker.DelimitedValues = selectionValues[9].Replace(',', '|'); } } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { string[] selectionValues = selection.Split('|'); var rockContext = ( RockContext )serviceInstance.Context; if (selectionValues.Length >= 2) { GroupMemberService groupMemberService = new GroupMemberService(rockContext); List <Guid> groupGuids = selectionValues[0].Split(',').AsGuidList(); var groupService = new GroupService(rockContext); var groupIds = groupService.GetByGuids(groupGuids).Select(a => a.Id).Distinct().ToList(); bool includeChildGroups = false; bool includeChildGroupsIncludeSelected = false; bool includeChildGroupsPlusDescendants = false; bool includeInactiveGroups = false; if (selectionValues.Length >= 3) { includeChildGroups = selectionValues[2].AsBooleanOrNull() ?? false; } if (selectionValues.Length >= 6) { includeChildGroupsIncludeSelected = selectionValues[4].AsBooleanOrNull() ?? false; includeChildGroupsPlusDescendants = selectionValues[5].AsBooleanOrNull() ?? false; } else if (includeChildGroups) { // in case the selection was saved before these options where added includeChildGroupsIncludeSelected = true; includeChildGroupsPlusDescendants = true; } if (selectionValues.Length >= 7) { includeInactiveGroups = selectionValues[6].AsBooleanOrNull() ?? true; } else { // if options where saved before this option was added, set to false, even though it would have included inactive before includeInactiveGroups = false; } GroupMemberStatus?groupMemberStatus = null; if (selectionValues.Length >= 4) { groupMemberStatus = selectionValues[3].ConvertToEnumOrNull <GroupMemberStatus>(); } var groupMemberServiceQry = groupMemberService.Queryable(); List <int> childGroupIds = new List <int>(); if (includeChildGroups) { foreach (var groupId in groupIds) { if (includeChildGroupsPlusDescendants) { // get all children and descendants of the selected group(s) var descendants = groupService.GetAllDescendents(groupId); if (!includeInactiveGroups) { descendants = descendants.Where(a => a.IsActive == true); } childGroupIds.AddRange(descendants.Select(a => a.Id).Distinct().ToList()); } else { // get only immediate children of the selected group(s) var childGroups = groupService.Queryable().Where(a => a.ParentGroupId == groupId); if (!includeInactiveGroups) { childGroups = childGroups.Where(a => a.IsActive == true); } childGroupIds.AddRange(childGroups.Select(a => a.Id)); } } if (includeChildGroupsIncludeSelected) { groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupIds.Contains(xx.GroupId) || childGroupIds.Contains(xx.GroupId)); } else { groupMemberServiceQry = groupMemberServiceQry.Where(xx => childGroupIds.Contains(xx.GroupId)); } } else { groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupIds.Contains(xx.GroupId)); } if (groupMemberStatus.HasValue) { groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.GroupMemberStatus == groupMemberStatus.Value); } var groupRoleGuids = selectionValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => n.AsGuid()).ToList(); if (groupRoleGuids.Count() > 0) { var groupRoleIds = new GroupTypeRoleService(( RockContext )serviceInstance.Context).Queryable().Where(a => groupRoleGuids.Contains(a.Guid)).Select(a => a.Id).ToList(); groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupRoleIds.Contains(xx.GroupRoleId)); } if (selectionValues.Length >= 8) { string addedOnSlidingDelimitedValues = selectionValues[7].Replace(',', '|'); DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(addedOnSlidingDelimitedValues); if (dateRange.Start.HasValue) { groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.DateTimeAdded >= dateRange.Start.Value); } if (dateRange.End.HasValue) { groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.DateTimeAdded < dateRange.End.Value); } } IQueryable <PersonIdFirstAttendance> firstAttendanceDateQry = null; IQueryable <PersonIdLastAttendance> lastAttendanceDateQry = null; if (selectionValues.Length >= 10) { List <int> attendanceGroupIds = null; if (includeChildGroups) { if (includeChildGroupsIncludeSelected) { attendanceGroupIds = new List <int>(); attendanceGroupIds.AddRange(groupIds); attendanceGroupIds.AddRange(childGroupIds); } else { attendanceGroupIds = childGroupIds; } } else { attendanceGroupIds = groupIds; } var groupAttendanceQuery = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend == true && a.GroupId.HasValue && attendanceGroupIds.Contains(a.GroupId.Value)); string firstAttendanceSlidingDelimitedValues = selectionValues[8].Replace(',', '|'); DateRange firstAttendanceDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(firstAttendanceSlidingDelimitedValues); if (firstAttendanceDateRange.Start.HasValue || firstAttendanceDateRange.End.HasValue) { firstAttendanceDateQry = groupAttendanceQuery .GroupBy(xx => xx.PersonAlias.PersonId) .Select(ss => new PersonIdFirstAttendance { PersonId = ss.Key, FirstAttendanceSundayDate = ss.Min(a => a.SundayDate) }); if (firstAttendanceDateRange.Start.HasValue) { firstAttendanceDateQry = firstAttendanceDateQry.Where(xx => xx.FirstAttendanceSundayDate >= firstAttendanceDateRange.Start.Value); } if (firstAttendanceDateRange.End.HasValue) { firstAttendanceDateQry = firstAttendanceDateQry.Where(xx => xx.FirstAttendanceSundayDate < firstAttendanceDateRange.End.Value); } } string lastAttendanceSlidingDelimitedValues = selectionValues[9].Replace(',', '|'); DateRange lastAttendanceDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(lastAttendanceSlidingDelimitedValues); if (lastAttendanceDateRange.Start.HasValue || lastAttendanceDateRange.End.HasValue) { lastAttendanceDateQry = groupAttendanceQuery .GroupBy(xx => xx.PersonAlias.PersonId) .Select(ss => new PersonIdLastAttendance { PersonId = ss.Key, LastAttendanceSundayDate = ss.Max(a => a.SundayDate) }); if (lastAttendanceDateRange.Start.HasValue) { lastAttendanceDateQry = lastAttendanceDateQry.Where(xx => xx.LastAttendanceSundayDate >= lastAttendanceDateRange.Start.Value); } if (lastAttendanceDateRange.End.HasValue) { lastAttendanceDateQry = lastAttendanceDateQry.Where(xx => xx.LastAttendanceSundayDate < lastAttendanceDateRange.End.Value); } } } IQueryable <Rock.Model.Person> qry = null; if (lastAttendanceDateQry == null && firstAttendanceDateQry == null) { qry = new PersonService(( RockContext )serviceInstance.Context).Queryable() .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id)); } else { if (firstAttendanceDateQry != null && lastAttendanceDateQry != null) { qry = new PersonService(( RockContext )serviceInstance.Context).Queryable() .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) && firstAttendanceDateQry.Any(aa => aa.PersonId == p.Id) && lastAttendanceDateQry.Any(bb => bb.PersonId == p.Id)); } else if (firstAttendanceDateQry != null) { qry = new PersonService(( RockContext )serviceInstance.Context).Queryable() .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) && firstAttendanceDateQry.Any(aa => aa.PersonId == p.Id)); } else if (lastAttendanceDateQry != null) { qry = new PersonService(( RockContext )serviceInstance.Context).Queryable() .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) && lastAttendanceDateQry.Any(aa => aa.PersonId == p.Id)); } } Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"); return(extractedFilterExpression); } return(null); }
private void LoadContent() { var eventItemGuid = GetAttributeValue("EventItem").AsGuid(); if (eventItemGuid != Guid.Empty) { lMessages.Text = string.Empty; RockContext rockContext = new RockContext(); // get event occurrences var qry = new EventItemOccurrenceService(rockContext).Queryable() .Where(e => e.EventItem.Guid == eventItemGuid); // filter occurrences for campus if (GetAttributeValue("UseCampusContext").AsBoolean()) { var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus"); var contextCampus = RockPage.GetCurrentContext(campusEntityType) as Campus; if (contextCampus != null) { qry = qry.Where(e => e.CampusId == contextCampus.Id); } } else { if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses"))) { var selectedCampuses = Array.ConvertAll(GetAttributeValue("Campuses").Split(','), s => new Guid(s)).ToList(); qry = qry.Where(e => selectedCampuses.Contains(e.Campus.Guid)); } } // retrieve occurrences var itemOccurrences = qry.ToList(); // filter by date range var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange")); if (dateRange.Start != null && dateRange.End != null) { itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0); } else { // default show all future (max 1 year) itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddDays(365)).Count() == 0); } // limit results int maxItems = GetAttributeValue("MaxOccurrences").AsInteger(); itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList(); // load event item var eventItem = new EventItemService(rockContext).Get(eventItemGuid); // make lava merge fields var mergeFields = new Dictionary <string, object>(); mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage")); mergeFields.Add("EventItem", eventItem); mergeFields.Add("EventItemOccurrences", itemOccurrences); // add context to merge fields var contextEntityTypes = RockPage.GetContextEntityTypes(); var contextObjects = new Dictionary <string, object>(); foreach (var conextEntityType in contextEntityTypes) { var contextObject = RockPage.GetCurrentContext(conextEntityType); contextObjects.Add(conextEntityType.FriendlyName, contextObject); } mergeFields.Add("Context", contextObjects); lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields); } else { lMessages.Text = "<div class='alert alert-warning'>No event item is configured for this block.</div>"; } }
/// <summary> /// Renders the specified writer. /// </summary> /// <param name="badge">The badge.</param> /// <param name="writer">The writer.</param> public override void Render(BadgeCache badge, System.Web.UI.HtmlTextWriter writer) { if (Person == null) { return; } Guid?groupTypeGuid = GetAttributeValue(badge, "GroupType").AsGuidOrNull(); if (groupTypeGuid.HasValue) { var lavaTemplate = this.GetAttributeValue(badge, "LavaTemplate"); var slidingDateRangeDelimitedValues = this.GetAttributeValue(badge, "DateRange"); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDateRangeDelimitedValues); var dateRangeSummary = SlidingDateRangePicker.FormatDelimitedValues(slidingDateRangeDelimitedValues); var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null, null, new Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("Person", this.Person); using (var rockContext = new RockContext()) { var groupType = GroupTypeCache.Get(groupTypeGuid.Value); int groupTypeId = groupType?.Id ?? 0; mergeFields.Add("GroupType", groupType); mergeFields.Add("Badge", badge); mergeFields.Add("DateRange", new { Dates = dateRange, Summary = dateRangeSummary }); var personAliasIds = Person.Aliases.Select(a => a.Id).ToList(); var attendanceQuery = new AttendanceService(rockContext) .Queryable() .Where(a => a.Occurrence.Group != null && a.Occurrence.Group.GroupTypeId == groupTypeId && a.DidAttend == true && personAliasIds.Contains(a.PersonAliasId.Value)); if (dateRange.Start.HasValue) { attendanceQuery = attendanceQuery.Where(a => a.StartDateTime >= dateRange.Start.Value); } if (dateRange.End.HasValue) { attendanceQuery = attendanceQuery.Where(a => a.StartDateTime < dateRange.End.Value); } var attendanceDateTimes = attendanceQuery.Select(a => a.StartDateTime).ToList(); if (attendanceDateTimes.Any()) { var attendanceResult = new { Count = attendanceDateTimes.Count(), LastDateTime = attendanceDateTimes.Max() }; mergeFields.Add("Attendance", attendanceResult); } string output = lavaTemplate.ResolveMergeFields(mergeFields); writer.Write(output); } } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { var rockContext = (RockContext)serviceInstance.Context; string[] selectionValues = selection.Split('|'); if (selectionValues.Length < 3) { return(null); } DateRange dateRange; if (selectionValues.Length >= 4) { string slidingDelimitedValues = selectionValues[3].Replace(',', '|'); dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues); } else { // if converting from a previous version of the selection DateTime?startDate = selectionValues[0].AsDateTime(); DateTime?endDate = selectionValues[1].AsDateTime(); dateRange = new DateRange(startDate, endDate); if (dateRange.End.HasValue) { // the DateRange picker doesn't automatically add a full day to the end date dateRange.End.Value.AddDays(1); } } var accountGuids = selectionValues[2].Split(',').Select(a => a.AsGuid()).ToList(); var accountIdList = new FinancialAccountService((RockContext)serviceInstance.Context).GetByGuids(accountGuids).Select(a => a.Id).ToList(); int transactionTypeContributionId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid()).Id; var financialTransactionsQry = new FinancialTransactionService(rockContext).Queryable() .Where(xx => xx.TransactionTypeValueId == transactionTypeContributionId); if (accountIdList.Any()) { if (accountIdList.Count == 1) { int accountId = accountIdList.First(); financialTransactionsQry = financialTransactionsQry.Where(xx => xx.TransactionDetails.Any(a => a.AccountId == accountId)); } else { financialTransactionsQry = financialTransactionsQry.Where(xx => xx.TransactionDetails.Any(a => accountIdList.Contains(a.AccountId))); } } var firstContributionDateQry = financialTransactionsQry .GroupBy(xx => xx.AuthorizedPersonAlias.PersonId) .Select(ss => new { PersonId = ss.Key, FirstTransactionSundayDate = ss.Min(a => a.SundayDate) }); if (dateRange.Start.HasValue) { firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionSundayDate >= dateRange.Start.Value); } if (dateRange.End.HasValue) { firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionSundayDate < dateRange.End.Value); } var innerQry = firstContributionDateQry.Select(xx => xx.PersonId).AsQueryable(); var qry = new PersonService(rockContext).Queryable() .Where(p => innerQry.Any(xx => xx == p.Id)); Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"); return(extractedFilterExpression); }
/// <summary> /// Loads the content. /// </summary> protected void LoadContent() { RockContext rockContext = new RockContext(); var registrationService = new RegistrationService(rockContext); var qryRegistrations = registrationService.Queryable(); // only show Active registrations qryRegistrations = qryRegistrations .Where(a => a.RegistrationInstance.IsActive == true && !a.IsTemporary); // limit to the current person int currentPersonId = this.CurrentPersonId ?? 0; qryRegistrations = qryRegistrations.Where(a => a.PersonAlias.PersonId == currentPersonId); // bring into a list so we can filter on non-database columns var registrationList = qryRegistrations.ToList(); List <Registration> hasDates = registrationList.Where(a => a.RegistrationInstance.Linkages.Any(x => x.EventItemOccurrenceId.HasValue && x.EventItemOccurrence.NextStartDateTime.HasValue)).ToList(); List <Registration> noDates = registrationList.Where(a => !hasDates.Any(d => d.Id == a.Id)).OrderBy(x => x.RegistrationInstance.Name).ToList(); hasDates = hasDates .OrderBy(a => a.RegistrationInstance.Linkages .Where(x => x.EventItemOccurrenceId.HasValue && x.EventItemOccurrence.NextStartDateTime.HasValue) .OrderBy(b => b.EventItemOccurrence.NextStartDateTime) .FirstOrDefault() .EventItemOccurrence.NextStartDateTime) .ToList(); // filter by date range var requestDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange") ?? "-1||"); if (requestDateRange.Start.HasValue) { hasDates = hasDates .Where(a => a.RegistrationInstance.Linkages .Where(x => x.EventItemOccurrenceId.HasValue && x.EventItemOccurrence.NextStartDateTime.HasValue) .OrderBy(b => b.EventItemOccurrence.NextStartDateTime) .FirstOrDefault() .EventItemOccurrence.NextStartDateTime >= requestDateRange.Start) .ToList(); } if (requestDateRange.End.HasValue) { hasDates = hasDates .Where(a => a.RegistrationInstance.Linkages .Where(x => x.EventItemOccurrenceId.HasValue && x.EventItemOccurrence.NextStartDateTime.HasValue) .OrderBy(b => b.EventItemOccurrence.NextStartDateTime) .FirstOrDefault() .EventItemOccurrence.NextStartDateTime < requestDateRange.End) .ToList(); } registrationList = hasDates; registrationList.AddRange(noDates); if (this.GetAttributeValue("LimitToOwed").AsBooleanOrNull() ?? true) { registrationList = registrationList.Where(a => a.BalanceDue != 0).ToList(); } int?maxResults = GetAttributeValue("MaxResults").AsIntegerOrNull(); if (maxResults.HasValue && maxResults > 0) { registrationList = registrationList.Take(maxResults.Value).ToList(); } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("Registrations", registrationList); string template = GetAttributeValue("LavaTemplate"); lContent.Text = template.ResolveMergeFields(mergeFields); }
/// <summary> /// Creates the child controls. /// </summary> /// <returns></returns> public override Control[] CreateChildControls(Type entityType, FilterField filterControl) { var pGroupPicker = new GroupPicker(); pGroupPicker.AllowMultiSelect = true; pGroupPicker.ID = $"{filterControl.ID}_{nameof( pGroupPicker )}"; pGroupPicker.AddCssClass("js-group-picker"); filterControl.Controls.Add(pGroupPicker); var cbChildGroups = new RockCheckBox(); cbChildGroups.ID = $"{filterControl.ID}_{nameof( cbChildGroups )}"; cbChildGroups.AddCssClass("js-child-groups"); cbChildGroups.Text = "Include Child Groups"; filterControl.Controls.Add(cbChildGroups); var ddlIntegerCompare = ComparisonHelper.ComparisonControl(ComparisonHelper.NumericFilterComparisonTypes); ddlIntegerCompare.Label = "Attendance Count"; ddlIntegerCompare.ID = $"{filterControl.ID}_{nameof( ddlIntegerCompare )}"; ddlIntegerCompare.AddCssClass("js-filter-compare"); filterControl.Controls.Add(ddlIntegerCompare); var tbAttendedCount = new NumberBox(); tbAttendedCount.ID = $"{filterControl.ID}_{nameof( tbAttendedCount )}"; tbAttendedCount.Label = " "; // give it whitespace label so it lines up nicely tbAttendedCount.AddCssClass("js-attended-count"); filterControl.Controls.Add(tbAttendedCount); var slidingDateRangePicker = new SlidingDateRangePicker(); slidingDateRangePicker.Label = "Date Range"; slidingDateRangePicker.ID = $"{filterControl.ID}_{nameof( slidingDateRangePicker )}"; slidingDateRangePicker.AddCssClass("js-sliding-date-range"); filterControl.Controls.Add(slidingDateRangePicker); var schedulePicker = new SchedulePicker(); schedulePicker.Label = "Schedules"; schedulePicker.ID = $"{filterControl.ID}_{nameof( schedulePicker )}"; schedulePicker.AddCssClass("js-schedule-picker"); schedulePicker.AllowMultiSelect = true; filterControl.Controls.Add(schedulePicker); var controls = new Control[6] { pGroupPicker, cbChildGroups, ddlIntegerCompare, tbAttendedCount, slidingDateRangePicker, schedulePicker }; var defaultGroupAttendanceFilterSelection = new GroupAttendanceFilterSelection { IntegerCompare = ComparisonType.GreaterThanOrEqualTo, AttendedCount = 4, SlidingDateRangeDelimitedValues = slidingDateRangePicker.DelimitedValues, IncludeChildGroups = false, }; // set the default values in case this is a newly added filter SetSelection( entityType, controls, defaultGroupAttendanceFilterSelection.ToJson()); return(controls); }
/// <summary> /// Get the data source for the list after applying the specified filter settings. /// </summary> /// <param name="dataContext"></param> /// <param name="filterSettingsKeyValueMap"></param> /// <returns></returns> private void OnPopulateListItems(RockContext dataContext, Grid listControl, Dictionary <string, string> filterSettingsKeyValueMap, SortProperty sortProperty) { if (_exceptionTemplate == null) { return; } string filterDescriptionPrefix = null; filterDescriptionPrefix = _exceptionTemplate.Description; // Construct the query... var exceptionService = new ExceptionLogService(dataContext); // Get the set of exceptions in the filter group. var exceptionQuery = exceptionService.Queryable().AsNoTracking(); exceptionQuery = exceptionService.FilterByOutermost(exceptionQuery); exceptionQuery = exceptionService.FilterByDescriptionPrefix(exceptionQuery, filterDescriptionPrefix); // Filter by: SiteId int siteId = filterSettingsKeyValueMap.GetValueOrDefault(FilterSettingName.Site, string.Empty).AsInteger(); if (siteId != 0) { exceptionQuery = exceptionQuery.Where(e => e.SiteId == siteId); } // Filter by: PageId int pageId = filterSettingsKeyValueMap.GetValueOrDefault(FilterSettingName.Page, string.Empty).AsInteger(); if (pageId != 0) { exceptionQuery = exceptionQuery.Where(e => e.PageId == pageId); } // Filter by: PersonId int userPersonID = filterSettingsKeyValueMap.GetValueOrDefault(FilterSettingName.User, string.Empty).AsInteger(); if (userPersonID != 0) { exceptionQuery = exceptionQuery.Where(e => e.CreatedByPersonAlias != null && e.CreatedByPersonAlias.PersonId == userPersonID); } // Filter by: Date Range var dateRangeSettings = filterSettingsKeyValueMap.GetValueOrDefault(FilterSettingName.DateRange, string.Empty); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dateRangeSettings); if (dateRange.Start.HasValue) { exceptionQuery = exceptionQuery.Where(e => e.CreatedDateTime.HasValue && e.CreatedDateTime.Value >= dateRange.Start.Value); } if (dateRange.End.HasValue) { exceptionQuery = exceptionQuery.Where(e => e.CreatedDateTime.HasValue && e.CreatedDateTime.Value < dateRange.End.Value); } // Materialize the list items. var listQuery = exceptionQuery.Select(e => new { Id = e.Id, CreatedDateTime = e.CreatedDateTime, PageName = e.Page.InternalName ?? e.PageUrl, FullName = (e.CreatedByPersonAlias != null && e.CreatedByPersonAlias.Person != null) ? e.CreatedByPersonAlias.Person.LastName + ", " + e.CreatedByPersonAlias.Person.NickName : "", Description = e.Description, }); // Sort the results. if (sortProperty == null) { listQuery = listQuery.OrderByDescending(e => e.CreatedDateTime); } else { listQuery = listQuery.Sort(sortProperty); } // Populate the grid. gExceptionList.SetLinqDataSource(listQuery); gExceptionList.DataBind(); }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var rockContext = new RockContext(); var jobService = new ServiceJobService(rockContext); GroupService groupService = new GroupService(rockContext); CategoryService categoryService = new CategoryService(rockContext); MetricService metricService = new MetricService(rockContext); var metricCategories = MetricCategoriesFieldAttribute.GetValueAsGuidPairs(dataMap.GetString("Metrics")); DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange")); var systemEmail = dataMap.GetString("Email").AsGuidOrNull(); if (!systemEmail.HasValue) { throw new Exception("System Email is required!"); } // get job type id int jobId = Convert.ToInt16(context.JobDetail.Description); var job = jobService.Get(jobId); DateTime _midnightToday = RockDateTime.Today.AddDays(1); var currentDateTime = RockDateTime.Now; int recipients = 0; Group notificationGroup = groupService.Get(dataMap.GetString("NotificationGroup").AsGuid()); List <MetricCount> metricCounts = CampusCache.All().Select(c => new MetricCount() { Campus = c, TotalEntered = 0, TotalMetrics = 0 }).ToList(); List <Metric> metrics = new List <Metric>(); // If we have some reasonable data, go ahead and run the job if (notificationGroup != null && metricCategories.Count > 0 && dateRange.Start.HasValue && dateRange.End.HasValue) { foreach (MetricCategoryPair metricCategoryPair in metricCategories) { Metric metric = metricService.Get(metricCategoryPair.MetricGuid); metrics.Add(metric); // Split this by campus partition if (metric.MetricPartitions.Any(mp => mp.EntityType.Name.Contains("Campus"))) { foreach (CampusCache campus in CampusCache.All()) { // Check to see if we also have a schedule partition if (metric.MetricPartitions.Any(mp => mp.EntityType.Name.Contains("Schedule"))) { var services = GetServices(campus, dataMap, dateRange); metricCounts.Where(mc => mc.Campus == campus).FirstOrDefault().TotalMetrics += services.Count; foreach (var service in services) { var hasValues = metric.MetricValues.Where(mv => mv.MetricValuePartitions.Any(mvp => mvp.MetricPartition.EntityType.Name.Contains("Campus") && mvp.EntityId == campus.Id) && mv.MetricValuePartitions.Any(mvp => mvp.MetricPartition.EntityType.Name.Contains("Schedule") && mvp.EntityId == service.Id) && mv.MetricValueDateTime >= dateRange.Start.Value && mv.MetricValueDateTime <= dateRange.End.Value).Any(); if (hasValues) { metricCounts.Where(mc => mc.Campus == campus).FirstOrDefault().TotalEntered++; } } } else { // Add totals for metrics and, if values are entered, metrics entered. metricCounts.Where(mc => mc.Campus == campus).FirstOrDefault().TotalMetrics++; var hasValues = metric.MetricValues.Where(mv => mv.MetricValuePartitions.Any(mvp => mvp.MetricPartition.EntityType.Name.Contains("Campus") && mvp.EntityId == campus.Id) && mv.MetricValueDateTime >= dateRange.Start.Value && mv.MetricValueDateTime <= dateRange.End.Value).Any(); if (hasValues) { metricCounts.Where(mc => mc.Campus == campus).FirstOrDefault().TotalEntered++; } } } } } // Create the merge fields var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("MetricCounts", metricCounts); mergeFields.Add("Metrics", metrics); mergeFields.Add("DateRange", dateRange.ToString()); mergeFields.Add("LastRunDate", job.LastSuccessfulRunDateTime); // Setup the email and send it out! RockEmailMessage message = new RockEmailMessage(systemEmail.Value); message.AdditionalMergeFields = mergeFields; foreach (GroupMember member in notificationGroup.Members) { message.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(member.Person.Email, mergeFields)); recipients++; } message.SendSeperatelyToEachRecipient = true; message.Send(); } context.Result = string.Format("Sent " + recipients + " metric entry digest emails."); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { string[] options = selection.Split('|'); if (options.Length < 4) { return(null); } Guid groupTypeGuid = options[0].AsGuid(); var campusGuidList = options[0].Split(',').AsGuidList(); List <int> campusIds = new List <int>(); foreach (var campusGuid in campusGuidList) { var campus = CampusCache.Get(campusGuid); if (campus != null) { campusIds.Add(campus.Id); } } if (!campusIds.Any()) { return(null); } ComparisonType comparisonType = options[1].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo); int? attended = options[2].AsIntegerOrNull(); string slidingDelimitedValues; if (options[3].AsIntegerOrNull().HasValue) { //// selection was from when it just simply a LastXWeeks instead of Sliding Date Range // Last X Weeks was treated as "LastXWeeks * 7" days, so we have to convert it to a SlidingDateRange of Days to keep consistent behavior int lastXWeeks = options[3].AsIntegerOrNull() ?? 1; var fakeSlidingDateRangePicker = new SlidingDateRangePicker(); fakeSlidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.Last; fakeSlidingDateRangePicker.TimeUnit = SlidingDateRangePicker.TimeUnitType.Day; fakeSlidingDateRangePicker.NumberOfTimeUnits = lastXWeeks * 7; slidingDelimitedValues = fakeSlidingDateRangePicker.DelimitedValues; } else { slidingDelimitedValues = options[3].Replace(',', '|'); } var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues); var rockContext = serviceInstance.Context as RockContext; var attendanceQry = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend.HasValue && a.DidAttend.Value); attendanceQry = attendanceQry.Where(a => a.CampusId.HasValue && campusIds.Contains((int)a.CampusId)); if (dateRange.Start.HasValue) { var startDate = dateRange.Start.Value; attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate >= startDate); } if (dateRange.End.HasValue) { var endDate = dateRange.End.Value; attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate < endDate); } var qry = new PersonService(rockContext).Queryable() .Where(p => attendanceQry.Count(xx => xx.PersonAlias.PersonId == p.Id) == attended); var compareEqualExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p") as BinaryExpression; var result = FilterExpressionExtractor.AlterComparisonType(comparisonType, compareEqualExpression, null); return(result); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { string[] options = selection.Split('|'); if (options.Length < 4) { return(null); } Guid groupTypeGuid = options[0].AsGuid(); ComparisonType comparisonType = options[1].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo); int? attended = options[2].AsIntegerOrNull(); string slidingDelimitedValues; if (options[3].AsIntegerOrNull().HasValue) { //// selection was from when it just simply a LastXWeeks instead of Sliding Date Range // Last X Weeks was treated as "LastXWeeks * 7" days, so we have to convert it to a SlidingDateRange of Days to keep consistent behavior int lastXWeeks = options[3].AsIntegerOrNull() ?? 1; var fakeSlidingDateRangePicker = new SlidingDateRangePicker(); fakeSlidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.Last; fakeSlidingDateRangePicker.TimeUnit = SlidingDateRangePicker.TimeUnitType.Day; fakeSlidingDateRangePicker.NumberOfTimeUnits = lastXWeeks * 7; slidingDelimitedValues = fakeSlidingDateRangePicker.DelimitedValues; } else { slidingDelimitedValues = options[3].Replace(',', '|'); } var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues); bool includeChildGroupTypes = options.Length >= 5 ? options[4].AsBooleanOrNull() ?? false : false; var groupTypeService = new GroupTypeService(new RockContext()); var groupType = groupTypeService.Get(groupTypeGuid); List <int> groupTypeIds = new List <int>(); if (groupType != null) { groupTypeIds.Add(groupType.Id); if (includeChildGroupTypes) { var childGroupTypes = groupTypeService.GetAllAssociatedDescendents(groupType.Guid); if (childGroupTypes.Any()) { groupTypeIds.AddRange(childGroupTypes.Select(a => a.Id)); // get rid of any duplicates groupTypeIds = groupTypeIds.Distinct().ToList(); } } } var rockContext = serviceInstance.Context as RockContext; var attendanceQry = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend.HasValue && a.DidAttend.Value); if (dateRange.Start.HasValue) { var startDate = dateRange.Start.Value; attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate >= startDate); } if (dateRange.End.HasValue) { var endDate = dateRange.End.Value; attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate < endDate); } if (groupTypeIds.Count == 1) { int groupTypeId = groupTypeIds[0]; attendanceQry = attendanceQry.Where(a => a.Occurrence.Group.GroupTypeId == groupTypeId); } else if (groupTypeIds.Count > 1) { attendanceQry = attendanceQry.Where(a => groupTypeIds.Contains(a.Occurrence.Group.GroupTypeId)); } else { // no group type selected, so return nothing return(Expression.Constant(false)); } var qry = new PersonService(rockContext).Queryable() .Where(p => attendanceQry.Where(xx => xx.PersonAlias.PersonId == p.Id).Count() == attended); BinaryExpression compareEqualExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p") as BinaryExpression; BinaryExpression result = FilterExpressionExtractor.AlterComparisonType(comparisonType, compareEqualExpression, null); return(result); }
public string GetSlidingDateRangeTextValue(Rock.Web.UI.Controls.SlidingDateRangePicker.SlidingDateRangeType slidingDateRangeType, Rock.Web.UI.Controls.SlidingDateRangePicker.TimeUnitType timeUnitType, int number = 1) { string textValue = SlidingDateRangePicker.FormatDelimitedValues(string.Format("{0}|{1}|{2}||", slidingDateRangeType, number, timeUnitType)); return(textValue); }
/// <summary> /// Formats the selection for the InGroupFilter/NotInGroupFilter based on if we are in "Not" mode /// </summary> /// <param name="selection">The selection.</param> /// <param name="not">if set to <c>true</c> [not].</param> /// <returns></returns> public virtual string GroupFilterFormatSelection(string selection, bool not) { string result = "Group Member"; string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 2) { var rockContext = new RockContext(); var groupGuids = selectionValues[0].Split(',').AsGuidList(); var groups = new GroupService(rockContext).GetByGuids(groupGuids); var groupTypeRoleGuidList = selectionValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.AsGuid()).ToList(); var groupTypeRoles = new GroupTypeRoleService(rockContext).Queryable().Where(a => groupTypeRoleGuidList.Contains(a.Guid)).ToList(); bool includeChildGroups = false; bool includeChildGroupsPlusDescendants = false; bool includeChildGroupsIncludeSelected = false; bool includeInactiveGroups = false; string addedOnDateRangeText = null; string firstAttendanceDateRangeText = null; string lastAttendanceDateRangeText = null; if (selectionValues.Length >= 3) { includeChildGroups = selectionValues[2].AsBooleanOrNull() ?? false; if (selectionValues.Length >= 6) { includeChildGroupsIncludeSelected = selectionValues[4].AsBooleanOrNull() ?? false; includeChildGroupsPlusDescendants = selectionValues[5].AsBooleanOrNull() ?? false; } if (selectionValues.Length >= 7) { includeInactiveGroups = selectionValues[6].AsBooleanOrNull() ?? false; } if (selectionValues.Length >= 8) { // convert comma delimited to pipe then get date range text addedOnDateRangeText = SlidingDateRangePicker.FormatDelimitedValues(selectionValues[7].Replace(',', '|')); } if (selectionValues.Length >= 10) { // convert comma delimited to pipe then get date range text firstAttendanceDateRangeText = SlidingDateRangePicker.FormatDelimitedValues(selectionValues[8].Replace(',', '|')); // convert comma delimited to pipe then get date range text lastAttendanceDateRangeText = SlidingDateRangePicker.FormatDelimitedValues(selectionValues[9].Replace(',', '|')); } } GroupMemberStatus?groupMemberStatus = null; if (selectionValues.Length >= 4) { groupMemberStatus = selectionValues[3].ConvertToEnumOrNull <GroupMemberStatus>(); } if (groups != null) { result = string.Format(not ? "Not in groups: {0}" : "In groups: {0}", groups.Select(a => a.Name).ToList().AsDelimited(", ", " or ")); if (includeChildGroups) { if (includeChildGroupsPlusDescendants) { result += " or descendant groups"; } else { result += " or child groups"; } if (includeInactiveGroups) { result += ", including inactive groups"; } if (!includeChildGroupsIncludeSelected) { result += ", not including selected groups"; } } if (groupTypeRoles.Count() > 0) { result += string.Format(", with role(s): {0}", groupTypeRoles.Select(a => string.Format("{0} ({1})", a.Name, a.GroupType.Name)).ToList().AsDelimited(",")); } if (groupMemberStatus.HasValue) { result += string.Format(", with member status: {0}", groupMemberStatus.ConvertToString()); } if (!string.IsNullOrEmpty(addedOnDateRangeText)) { result += string.Format(", added to group in Date Range: {0}", addedOnDateRangeText); } if (!string.IsNullOrEmpty(firstAttendanceDateRangeText)) { result += string.Format(", first attendance to group in Date Range: {0}", firstAttendanceDateRangeText); } if (!string.IsNullOrEmpty(lastAttendanceDateRangeText)) { result += string.Format(", last attendance to group in Date Range: {0}", lastAttendanceDateRangeText); } } } return(result); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { var rockContext = (RockContext)serviceInstance.Context; string[] selectionValues = selection.Split('|'); if (selectionValues.Length < 4) { return(null); } ComparisonType comparisonType = selectionValues[0].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo); decimal amount = selectionValues[1].AsDecimalOrNull() ?? 0.00M; DateRange dateRange; if (selectionValues.Length >= 7) { string slidingDelimitedValues = selectionValues[6].Replace(',', '|'); dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues); } else { // if converting from a previous version of the selection DateTime?startDate = selectionValues[2].AsDateTime(); DateTime?endDate = selectionValues[3].AsDateTime(); dateRange = new DateRange(startDate, endDate); if (dateRange.End.HasValue) { // the DateRange picker doesn't automatically add a full day to the end date dateRange.End.Value.AddDays(1); } } var accountIdList = new List <int>(); if (selectionValues.Length >= 5) { var accountGuids = selectionValues[4].Split(',').Select(a => a.AsGuid()).ToList(); accountIdList = new FinancialAccountService((RockContext)serviceInstance.Context).GetByGuids(accountGuids).Select(a => a.Id).ToList(); } bool combineGiving = false; if (selectionValues.Length >= 6) { combineGiving = selectionValues[5].AsBooleanOrNull() ?? false; } int transactionTypeContributionId = Rock.Web.Cache.DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid()).Id; var financialTransactionQry = new FinancialTransactionService(rockContext).Queryable() .Where(xx => xx.AuthorizedPersonAliasId.HasValue) .Where(xx => xx.TransactionTypeValueId == transactionTypeContributionId); if (dateRange.Start.HasValue) { financialTransactionQry = financialTransactionQry.Where(xx => xx.TransactionDateTime >= dateRange.Start.Value); } if (dateRange.End.HasValue) { financialTransactionQry = financialTransactionQry.Where(xx => xx.TransactionDateTime < dateRange.End.Value); } bool limitToAccounts = accountIdList.Any(); // Create an explicit join to person alias so that rendered SQL is an INNER Join vs OUTER join var personAliasQry = new PersonAliasService(rockContext).Queryable(); var financialTransactionGivingGroupQry = financialTransactionQry .Join(personAliasQry, t => t.AuthorizedPersonAliasId, p => p.Id, (t, p) => new { Txn = t, GivingGroupId = p.Person.GivingGroupId }); // query transactions for individuals. // If CombineGiving, exclude people that are Giving Group, and we'll get those when we union with CombineGiving var financialTransactionDetailsIndividualQry = financialTransactionGivingGroupQry.Where(a => !combineGiving || !a.GivingGroupId.HasValue).Select(a => a.Txn) .GroupBy(xx => xx.AuthorizedPersonAlias.PersonId ).Select(xx => new { PersonId = xx.Key, TotalAmount = xx.Sum(ss => ss.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Sum(td => td.Amount)) }); if (comparisonType == ComparisonType.LessThan) { financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount < amount); } else if (comparisonType == ComparisonType.EqualTo) { financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount == amount); } else if (comparisonType == ComparisonType.GreaterThanOrEqualTo) { // NOTE: if the amount filter is 'they gave $0.00 or more', there no account filter, and doing a GreaterThanOrEqualTo, then we don't need to calculate and compare against TotalAmount if (amount == 0.00M && !accountIdList.Any()) { // don't query against TotalAmount if we don't care about amount or accounts } else { financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount >= amount); } } var innerQryIndividual = financialTransactionDetailsIndividualQry.Select(xx => xx.PersonId).AsQueryable(); IQueryable <int> qryTransactionPersonIds; if (combineGiving) { // if CombineGiving=true, do another query to total by GivingGroupId for people with GivingGroupId specified var financialTransactionDetailsGivingGroupQry = financialTransactionGivingGroupQry.Where(a => a.GivingGroupId.HasValue) .GroupBy(xx => new { xx.GivingGroupId }).Select(xx => new { GivingGroupId = xx.Key, TotalAmount = xx.Sum(ss => ss.Txn.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Sum(td => td.Amount)) }); if (comparisonType == ComparisonType.LessThan) { financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount < amount); } else if (comparisonType == ComparisonType.EqualTo) { financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount == amount); } else if (comparisonType == ComparisonType.GreaterThanOrEqualTo) { // NOTE: if the amount filter is 'they gave $0.00 or more', there no account filter, and doing a GreaterThanOrEqualTo, then we don't need to calculate and compare against TotalAmount if (amount == 0.00M && !accountIdList.Any()) { // don't query against TotalAmount if we don't care about amount or accounts } else { financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount >= amount); } } var personService = new PersonService(rockContext); IQueryable <int> innerQryGivingGroupPersons = personService.Queryable() .Where(a => financialTransactionDetailsGivingGroupQry.Select(xx => xx.GivingGroupId).AsQueryable().Any(gg => gg.GivingGroupId == a.GivingGroupId)) .Select(s => s.Id); // include people that either give as individuals or are members of a giving group qryTransactionPersonIds = innerQryIndividual.Union(innerQryGivingGroupPersons); } else { // don't factor in GivingGroupId. Only include people that are directly associated with the transaction qryTransactionPersonIds = innerQryIndividual; } var qry = new PersonService(rockContext).Queryable() .Where(p => qryTransactionPersonIds.Any(xx => xx == p.Id)); Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"); return(extractedFilterExpression); }
/// <summary> /// Creates the child controls. /// </summary> /// <returns></returns> public override Control[] CreateChildControls(Type entityType, FilterField filterControl) { gp = new GroupPicker(); gp.ID = filterControl.ID + "_gp"; gp.Label = "Group(s)"; gp.SelectItem += gp_SelectItem; gp.CssClass = "js-group-picker"; gp.AllowMultiSelect = true; filterControl.Controls.Add(gp); cbChildGroups = new RockCheckBox(); cbChildGroups.ID = filterControl.ID + "_cbChildsGroups"; cbChildGroups.Text = "Include Child Group(s)"; cbChildGroups.CssClass = "js-include-child-groups"; cbChildGroups.AutoPostBack = true; cbChildGroups.CheckedChanged += gp_SelectItem; filterControl.Controls.Add(cbChildGroups); cbIncludeSelectedGroup = new RockCheckBox(); cbIncludeSelectedGroup.ID = filterControl.ID + "_cbIncludeSelectedGroup"; cbIncludeSelectedGroup.Text = "Include Selected Group(s)"; cbIncludeSelectedGroup.CssClass = "js-include-selected-groups"; cbIncludeSelectedGroup.AutoPostBack = true; cbIncludeSelectedGroup.CheckedChanged += gp_SelectItem; filterControl.Controls.Add(cbIncludeSelectedGroup); cbChildGroupsPlusDescendants = new RockCheckBox(); cbChildGroupsPlusDescendants.ID = filterControl.ID + "_cbChildGroupsPlusDescendants"; cbChildGroupsPlusDescendants.Text = "Include All Descendants(s)"; cbChildGroupsPlusDescendants.CssClass = "js-include-child-groups-descendants"; cbChildGroupsPlusDescendants.AutoPostBack = true; cbChildGroupsPlusDescendants.CheckedChanged += gp_SelectItem; filterControl.Controls.Add(cbChildGroupsPlusDescendants); cbIncludeInactiveGroups = new RockCheckBox(); cbIncludeInactiveGroups.ID = filterControl.ID + "_cbIncludeInactiveGroups"; cbIncludeInactiveGroups.Text = "Include Inactive Groups"; cbIncludeInactiveGroups.CssClass = "js-include-inactive-groups"; cbIncludeInactiveGroups.AutoPostBack = true; cbIncludeInactiveGroups.CheckedChanged += gp_SelectItem; filterControl.Controls.Add(cbIncludeInactiveGroups); cblRole = new RockCheckBoxList(); cblRole.Label = "with Group Member Role(s) (optional)"; cblRole.ID = filterControl.ID + "_cblRole"; cblRole.CssClass = "js-roles"; cblRole.Visible = false; filterControl.Controls.Add(cblRole); RockDropDownList ddlGroupMemberStatus = new RockDropDownList(); ddlGroupMemberStatus.CssClass = "js-group-member-status"; ddlGroupMemberStatus.ID = filterControl.ID + "_ddlGroupMemberStatus"; ddlGroupMemberStatus.Label = "with Group Member Status"; ddlGroupMemberStatus.Help = "Select a specific group member status to only include group members with that status. Leaving this blank will return all members."; ddlGroupMemberStatus.BindToEnum <GroupMemberStatus>(true); ddlGroupMemberStatus.SetValue(GroupMemberStatus.Active.ConvertToInt()); filterControl.Controls.Add(ddlGroupMemberStatus); PanelWidget pwAdvanced = new PanelWidget(); filterControl.Controls.Add(pwAdvanced); pwAdvanced.ID = filterControl.ID + "_pwAttributes"; pwAdvanced.Title = "Advanced Filters"; pwAdvanced.CssClass = "advanced-panel"; SlidingDateRangePicker addedOnDateRangePicker = new SlidingDateRangePicker(); addedOnDateRangePicker.ID = pwAdvanced.ID + "_addedOnDateRangePicker"; addedOnDateRangePicker.AddCssClass("js-dateadded-sliding-date-range"); addedOnDateRangePicker.Label = "Date Added:"; addedOnDateRangePicker.Help = "Select the date range that the person was added to the group. Leaving this blank will not restrict results to a date range."; pwAdvanced.Controls.Add(addedOnDateRangePicker); SlidingDateRangePicker firstAttendanceDateRangePicker = new SlidingDateRangePicker(); firstAttendanceDateRangePicker.ID = filterControl.ID + "_firstAttendanceDateRangePicker"; firstAttendanceDateRangePicker.AddCssClass("js-firstattendance-sliding-date-range"); firstAttendanceDateRangePicker.Label = "First Attendance"; firstAttendanceDateRangePicker.Help = "The date range of the first attendance using the 'Sunday Date' of each attendance"; pwAdvanced.Controls.Add(firstAttendanceDateRangePicker); SlidingDateRangePicker lastAttendanceDateRangePicker = new SlidingDateRangePicker(); lastAttendanceDateRangePicker.ID = filterControl.ID + "_lastAttendanceDateRangePicker"; lastAttendanceDateRangePicker.AddCssClass("js-lastattendance-sliding-date-range"); lastAttendanceDateRangePicker.Label = "Last Attendance"; lastAttendanceDateRangePicker.Help = "The date range of the last attendance using the 'Sunday Date' of each attendance"; pwAdvanced.Controls.Add(lastAttendanceDateRangePicker); return(new Control[11] { gp, cbChildGroups, cbIncludeSelectedGroup, cbChildGroupsPlusDescendants, cblRole, ddlGroupMemberStatus, cbIncludeInactiveGroups, addedOnDateRangePicker, pwAdvanced, firstAttendanceDateRangePicker, lastAttendanceDateRangePicker }); }
/// <summary> /// Loads the content. /// </summary> private void LoadContent() { var rockContext = new RockContext(); var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid(); var eventCalendar = new EventCalendarService(rockContext).Get(eventCalendarGuid); if (eventCalendar == null) { lMessages.Text = "<div class='alert alert-warning'>No event calendar is configured for this block.</div>"; lContent.Text = string.Empty; return; } else { lMessages.Text = string.Empty; } var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext); // Grab events // NOTE: Do not use AsNoTracking() so that things can be lazy loaded if needed var qry = eventItemOccurrenceService .Queryable("EventItem, EventItem.EventItemAudiences,Schedule") .Where(m => m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) && m.EventItem.IsActive); // Filter by campus (always include the "All Campuses" events) if (GetAttributeValue("UseCampusContext").AsBoolean()) { var campusEntityType = EntityTypeCache.Get <Campus>(); var contextCampus = RockPage.GetCurrentContext(campusEntityType) as Campus; if (contextCampus != null) { qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue); } } else { var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList(); if (campusGuidList.Any()) { qry = qry.Where(e => !e.CampusId.HasValue || campusGuidList.Contains(e.Campus.Guid)); } } // make sure they have a date range var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(this.GetAttributeValue("DateRange")); var today = RockDateTime.Today; dateRange.Start = dateRange.Start ?? today; if (dateRange.End == null) { dateRange.End = dateRange.Start.Value.AddDays(1000); } // Get the occurrences var occurrences = qry.ToList(); var occurrencesWithDates = occurrences .Select(o => new EventOccurrenceDate { EventItemOccurrence = o, Dates = o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).ToList() }) .Where(d => d.Dates.Any()) .ToList(); CalendarEventDates = new List <DateTime>(); var eventOccurrenceSummaries = new List <EventOccurrenceSummary>(); foreach (var occurrenceDates in occurrencesWithDates) { var eventItemOccurrence = occurrenceDates.EventItemOccurrence; foreach (var datetime in occurrenceDates.Dates) { CalendarEventDates.Add(datetime.Date); if (datetime >= dateRange.Start.Value && datetime < dateRange.End.Value) { eventOccurrenceSummaries.Add(new EventOccurrenceSummary { EventItemOccurrence = eventItemOccurrence, EventItem = eventItemOccurrence.EventItem, Name = eventItemOccurrence.EventItem.Name, DateTime = datetime, Date = datetime.ToShortDateString(), Time = datetime.ToShortTimeString(), Location = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses", Description = eventItemOccurrence.EventItem.Description, Summary = eventItemOccurrence.EventItem.Summary, DetailPage = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl }); } } } var eventSummaries = eventOccurrenceSummaries .OrderBy(e => e.DateTime) .GroupBy(e => e.Name) .Select(e => e.ToList()) .ToList(); eventOccurrenceSummaries = eventOccurrenceSummaries .OrderBy(e => e.DateTime) .ThenBy(e => e.Name) .ToList(); // limit results int?maxItems = GetAttributeValue("MaxOccurrences").AsIntegerOrNull(); if (maxItems.HasValue) { eventOccurrenceSummaries = eventOccurrenceSummaries.Take(maxItems.Value).ToList(); } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("DetailsPage", LinkedPageRoute("DetailsPage")); mergeFields.Add("EventItems", eventSummaries); mergeFields.Add("EventOccurrenceSummaries", eventOccurrenceSummaries); lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed) { return(SlidingDateRangePicker.FormatDelimitedValues(value)); }