Ejemplo n.º 1
0
        /// <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 System.Linq.Expressions.Expression GetExpression(Type entityType, Data.IService serviceInstance, System.Linq.Expressions.ParameterExpression parameterExpression, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                var accountGuids = selectionValues[0].Split(',').Select(a => a.AsGuid()).ToList();
                var accountIds   = new FinancialAccountService((RockContext)serviceInstance.Context).GetByGuids(accountGuids).Select(a => a.Id).ToList();

                var qry = new FinancialScheduledTransactionDetailService((RockContext)serviceInstance.Context).Queryable()
                          .Where(p => accountIds.Contains(p.AccountId));

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.FinancialScheduledTransactionDetail>(qry, parameterExpression, "p");

                return(extractedFilterExpression);
            }

            return(null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext   = new RockContext();
            var pledgeService = new FinancialPledgeService(rockContext);
            var sortProperty  = gPledges.SortProperty;
            var pledges       = pledgeService.Queryable();

            Person person = null;

            if (TargetPerson != null)
            {
                person = TargetPerson;
            }
            else
            {
                int?personId = gfPledges.GetUserPreference("Person").AsIntegerOrNull();
                if (personId.HasValue)
                {
                    person = new PersonService(rockContext).Get(personId.Value);
                }
            }

            if (person != null)
            {
                // if a person is specified, get pledges for that person ( and also anybody in their GivingUnit )
                pledges = pledges.Where(p => p.PersonAlias.Person.GivingId == person.GivingId);
            }

            // get the accounts and make sure they still exist by checking the database
            var accountIds = gfPledges.GetUserPreference("Accounts").Split(',').AsIntegerList();

            accountIds = new FinancialAccountService(rockContext).GetByIds(accountIds).Select(a => a.Id).ToList();

            if (accountIds.Any())
            {
                pledges = pledges.Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value));
            }

            // Date Range
            var drp = new DateRangePicker();

            drp.DelimitedValues = gfPledges.GetUserPreference("Date Range");
            var filterStartDate = drp.LowerValue ?? DateTime.MinValue;
            var filterEndDate   = drp.UpperValue ?? DateTime.MaxValue;

            /****
             * Include any pledges whose Start/EndDates overlap with the Filtered Date Range
             *
             * * Pledge1 Range 1/1/2011 - 12/31/2011
             * * Pledge2 Range 1/1/0000 - 1/1/9999
             * * Pledge3 Range 6/1/2011 - 6/1/2012
             *
             * Filter1 Range 1/1/2010 - 1/1/2013
             * * * All Pledges should show
             * Filter1 Range 1/1/2012 - 1/1/2013
             * * * Pledge2 and Pledge3 should show
             * Filter2 Range 5/1/2012 - 5/2/2012
             * * * Pledge2 and Pledge3 should show
             * Filter3 Range 5/1/2012 - 1/1/9999
             * * * Pledge2 and Pledge3 should show
             * Filter4 Range 5/1/2010 - 5/1/2010
             * * * Pledge2 should show
             ***/

            // exclude pledges that start after the filter's end date or end before the filter's start date
            pledges = pledges.Where(p => !(p.StartDate > filterEndDate) && !(p.EndDate < filterStartDate));

            gPledges.DataSource = sortProperty != null?pledges.Sort(sortProperty).ToList() : pledges.OrderBy(p => p.AccountId).ToList();

            gPledges.DataBind();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();
            var pledgeService = new FinancialPledgeService( rockContext );
            var sortProperty = gPledges.SortProperty;
            var pledges = pledgeService.Queryable();

            Person person = null;
            if ( TargetPerson != null )
            {
                person = TargetPerson;
            }
            else
            {
                int? personId = gfPledges.GetUserPreference( "Person" ).AsIntegerOrNull();
                if ( personId.HasValue && ppFilterPerson.Visible )
                {
                    person = new PersonService( rockContext ).Get( personId.Value );
                }
            }

            if ( person != null )
            {
                // if a person is specified, get pledges for that person ( and also anybody in their GivingUnit )
                pledges = pledges.Where( p => p.PersonAlias.Person.GivingId == person.GivingId );
            }

            // get the accounts and make sure they still exist by checking the database
            var accountIds = gfPledges.GetUserPreference( "Accounts" ).Split( ',' ).AsIntegerList();
            accountIds = new FinancialAccountService( rockContext ).GetByIds( accountIds ).Select( a => a.Id ).ToList();

            if ( accountIds.Any() && apFilterAccount.Visible )
            {
                pledges = pledges.Where( p => p.AccountId.HasValue && accountIds.Contains( p.AccountId.Value ) );
            }

            // Date Range
            var drp = new DateRangePicker();
            drp.DelimitedValues = gfPledges.GetUserPreference( "Date Range" );
            var filterStartDate = drp.LowerValue ?? DateTime.MinValue;
            var filterEndDate = drp.UpperValue ?? DateTime.MaxValue;

            if (filterEndDate != DateTime.MaxValue)
            {
                filterEndDate = filterEndDate.AddDays( 1 );
            }

            /****
             * Include any pledges whose Start/EndDates overlap with the Filtered Date Range
             *
             * * Pledge1 Range 1/1/2011 - 12/31/2011
             * * Pledge2 Range 1/1/0000 - 1/1/9999
             * * Pledge3 Range 6/1/2011 - 6/1/2012
             *
             * Filter1 Range 1/1/2010 - 1/1/2013
             * * * All Pledges should show
             * Filter1 Range 1/1/2012 - 1/1/2013
             * * * Pledge2 and Pledge3 should show
             * Filter2 Range 5/1/2012 - 5/2/2012
             * * * Pledge2 and Pledge3 should show
             * Filter3 Range 5/1/2012 - 1/1/9999
             * * * Pledge2 and Pledge3 should show
             * Filter4 Range 5/1/2010 - 5/1/2010
             * * * Pledge2 should show
             ***/

            // exclude pledges that start after the filter's end date or end before the filter's start date
            if ( drpDates.Visible )
            {
                pledges = pledges.Where( p => !(p.StartDate > filterEndDate) && !(p.EndDate < filterStartDate) );
            }

            // Last Modified
            drp.DelimitedValues = gfPledges.GetUserPreference( "Last Modified" );
            filterStartDate = drp.LowerValue ?? DateTime.MinValue;
            filterEndDate = drp.UpperValue ?? DateTime.MaxValue;

            if (filterEndDate != DateTime.MaxValue)
            {
                filterEndDate = filterEndDate.AddDays( 1 );
            }

            if ( drpLastModifiedDates.Visible )
            {
                pledges = pledges.Where( p => !(p.ModifiedDateTime >= filterEndDate) && !(p.ModifiedDateTime <= filterStartDate) );
            }

            gPledges.DataSource = sortProperty != null ? pledges.Sort( sortProperty ).ToList() : pledges.OrderBy( p => p.AccountId ).ToList();
            gPledges.DataBind();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext   = new RockContext();
            var pledgeService = new FinancialPledgeService(rockContext);
            var sortProperty  = gPledges.SortProperty;
            var pledges       = pledgeService.Queryable();

            Person person = null;

            if (TargetPerson != null)
            {
                person = TargetPerson;
            }
            else
            {
                int?personId = gfPledges.GetUserPreference("Person").AsIntegerOrNull();
                if (personId.HasValue && ppFilterPerson.Visible)
                {
                    person = new PersonService(rockContext).Get(personId.Value);
                }
            }

            if (person != null)
            {
                // if a person is specified, get pledges for that person ( and also anybody in their GivingUnit )
                pledges = pledges.Where(p => p.PersonAlias.Person.GivingId == person.GivingId);
            }

            // Filter by configured limit accounts if specified.
            var accountGuids = GetAttributeValue("Accounts").SplitDelimitedValues().AsGuidList();

            if (accountGuids.Any())
            {
                pledges = pledges.Where(p => accountGuids.Contains(p.Account.Guid));
            }

            // get the accounts and make sure they still exist by checking the database
            var accountIds = gfPledges.GetUserPreference("Accounts").Split(',').AsIntegerList();

            accountIds = new FinancialAccountService(rockContext).GetByIds(accountIds).Select(a => a.Id).ToList();

            if (accountIds.Any() && apFilterAccount.Visible)
            {
                pledges = pledges.Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value));
            }

            // Date Range
            DateRange filterDateRange = DateRangePicker.CalculateDateRangeFromDelimitedValues(gfPledges.GetUserPreference("Date Range"));
            var       filterStartDate = filterDateRange.Start ?? DateTime.MinValue;
            var       filterEndDate   = filterDateRange.End ?? DateTime.MaxValue;

            /****
             * Include any pledges whose Start/EndDates overlap with the Filtered Date Range
             *
             * * Pledge1 Range 1/1/2011 - 12/31/2011
             * * Pledge2 Range 1/1/0000 - 1/1/9999
             * * Pledge3 Range 6/1/2011 - 6/1/2012
             *
             * Filter1 Range 1/1/2010 - 1/1/2013
             * * * All Pledges should show
             * Filter1 Range 1/1/2012 - 1/1/2013
             * * * Pledge2 and Pledge3 should show
             * Filter2 Range 5/1/2012 - 5/2/2012
             * * * Pledge2 and Pledge3 should show
             * Filter3 Range 5/1/2012 - 1/1/9999
             * * * Pledge2 and Pledge3 should show
             * Filter4 Range 5/1/2010 - 5/1/2010
             * * * Pledge2 should show
             ***/

            // exclude pledges that start after the filter's end date or end before the filter's start date
            if (drpDates.Visible && (filterDateRange.Start.HasValue || filterDateRange.End.HasValue))
            {
                pledges = pledges.Where(p => !(p.StartDate > filterEndDate) && !(p.EndDate < filterStartDate));
            }

            // Last Modified
            DateRange filterModifiedDateRange = DateRangePicker.CalculateDateRangeFromDelimitedValues(gfPledges.GetUserPreference("Last Modified"));
            var       filterModifiedStartDate = filterModifiedDateRange.Start ?? DateTime.MinValue;
            var       filterModifiedEndDate   = filterModifiedDateRange.End ?? DateTime.MaxValue;

            if (drpLastModifiedDates.Visible && (filterModifiedDateRange.Start.HasValue || filterModifiedDateRange.End.HasValue))
            {
                pledges = pledges.Where(p => !(p.ModifiedDateTime >= filterModifiedEndDate) && !(p.ModifiedDateTime <= filterModifiedStartDate));
            }

            gPledges.DataSource = sortProperty != null?pledges.Sort(sortProperty).ToList() : pledges.OrderBy(p => p.AccountId).ToList();

            gPledges.DataBind();

            var showAccountSummary = this.GetAttributeValue("ShowAccountSummary").AsBoolean();

            if (showAccountSummary || TargetPerson == null)
            {
                pnlSummary.Visible = true;

                var summaryList = pledges
                                  .GroupBy(a => a.AccountId)
                                  .Select(a => new AccountSummaryRow
                {
                    AccountId   = a.Key.Value,
                    TotalAmount = a.Sum(x => x.TotalAmount),
                    Name        = a.Select(p => p.Account.Name).FirstOrDefault(),
                    Order       = a.Select(p => p.Account.Order).FirstOrDefault()
                }).ToList();

                var grandTotalAmount = (summaryList.Count > 0) ? summaryList.Sum(a => a.TotalAmount) : 0;
                lGrandTotal.Text             = grandTotalAmount.FormatAsCurrency();
                rptAccountSummary.DataSource = summaryList.Select(a => new { a.Name, TotalAmount = a.TotalAmount.FormatAsCurrency() }).ToList();
                rptAccountSummary.DataBind();
            }
            else
            {
                pnlSummary.Visible = false;
            }
        }
        /// <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;
            }

            DateTime? startDate = selectionValues[0].AsDateTime();
            DateTime? endDate = selectionValues[1].AsDateTime();
            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 = Rock.Web.Cache.DefinedValueCache.Read( 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,
                    FirstTransactionDateTime = ss.Min( a => a.TransactionDateTime )
                } );

            if ( startDate.HasValue )
            {
                firstContributionDateQry = firstContributionDateQry.Where( xx => xx.FirstTransactionDateTime >= startDate.Value );
            }

            if ( endDate.HasValue )
            {
                firstContributionDateQry = firstContributionDateQry.Where( xx => xx.FirstTransactionDateTime < endDate );
            }

            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>
        /// 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 = Rock.Web.Cache.DefinedValueCache.Read(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>
        /// 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);
            }

            DateTime?startDate     = selectionValues[0].AsDateTime();
            DateTime?endDate       = selectionValues[1].AsDateTime();
            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 = Rock.Web.Cache.DefinedValueCache.Read(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 (startDate.HasValue)
            {
                firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionSundayDate >= startDate.Value);
            }

            if (endDate.HasValue)
            {
                firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionSundayDate < endDate);
            }

            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);
        }
Ejemplo n.º 8
0
        /// <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;

            var selectionConfig = SelectionConfig.Parse(selection) ?? new SelectionConfig();

            ComparisonType comparisonType = selectionConfig.ComparisonType;
            decimal        amount         = selectionConfig.Amount ?? 0.00M;
            DateRange      dateRange      = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(selectionConfig.SlidingDateRangePickerDelimitedValues);

            var        accountGuids = selectionConfig.AccountGuids;
            List <int> accountIdList;

            if (accountGuids != null && accountGuids.Any())
            {
                var financialAccountService = new FinancialAccountService(( RockContext )serviceInstance.Context);
                accountIdList = financialAccountService.GetByGuids(accountGuids).Select(a => a.Id).ToList();
                if (selectionConfig.IncludeChildAccounts)
                {
                    var parentAccountIds = accountIdList.ToList();
                    foreach (var parentAccountId in parentAccountIds)
                    {
                        var descendantChildAccountIds = financialAccountService.GetAllDescendentIds(parentAccountId);
                        accountIdList.AddRange(descendantChildAccountIds);
                    }
                }
            }
            else
            {
                accountIdList = new List <int>();
            }

            bool combineGiving = selectionConfig.CombineGiving;

            int  transactionTypeContributionId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid()).Id;
            bool useAnalyticsModels            = selectionConfig.UseAnalyticsModels;

            IQueryable <TransactionDetailData> financialTransactionDetailBaseQry;

            if (useAnalyticsModels)
            {
                financialTransactionDetailBaseQry = new AnalyticsSourceFinancialTransactionService(rockContext).Queryable()
                                                    .Where(xx => xx.AuthorizedPersonAliasId.HasValue)
                                                    .Where(xx => xx.TransactionTypeValueId == transactionTypeContributionId)
                                                    .Select(ss => new TransactionDetailData
                {
                    AuthorizedPersonAliasId = ss.AuthorizedPersonAliasId.Value,
                    TransactionDateTime     = ss.TransactionDateTime,
                    Amount    = ss.Amount,
                    AccountId = ss.AccountId ?? 0
                });
            }
            else
            {
                financialTransactionDetailBaseQry = new FinancialTransactionDetailService(rockContext).Queryable()
                                                    .Where(xx => xx.Transaction.AuthorizedPersonAliasId.HasValue)
                                                    .Where(xx => xx.Transaction.TransactionDateTime.HasValue)
                                                    .Where(xx => xx.Transaction.TransactionTypeValueId == transactionTypeContributionId)
                                                    .Select(ss => new TransactionDetailData
                {
                    AuthorizedPersonAliasId = ss.Transaction.AuthorizedPersonAliasId.Value,
                    TransactionDateTime     = ss.Transaction.TransactionDateTime.Value,
                    Amount    = ss.Amount,
                    AccountId = ss.AccountId
                });
            }

            if (dateRange.Start.HasValue)
            {
                financialTransactionDetailBaseQry = financialTransactionDetailBaseQry.Where(xx => xx.TransactionDateTime >= dateRange.Start.Value);
            }

            if (dateRange.End.HasValue)
            {
                financialTransactionDetailBaseQry = financialTransactionDetailBaseQry.Where(xx => xx.TransactionDateTime < dateRange.End.Value);
            }

            if (accountIdList.Any())
            {
                if (accountIdList.Count() == 1)
                {
                    var accountId = accountIdList[0];
                    financialTransactionDetailBaseQry = financialTransactionDetailBaseQry.Where(x => accountId == x.AccountId);
                }
                else
                {
                    financialTransactionDetailBaseQry = financialTransactionDetailBaseQry.Where(x => accountIdList.Contains(x.AccountId));
                }
            }

            if (selectionConfig.IgnoreInactiveAccounts)
            {
                var inactiveAccountIdQuery = new FinancialAccountService(rockContext).Queryable().Where(a => !a.IsActive).Select(a => a.Id);
                financialTransactionDetailBaseQry = financialTransactionDetailBaseQry.Where(a => !inactiveAccountIdQuery.Contains(a.AccountId));
            }

            bool excludePersonsWithTransactions = false;

            // Create explicit joins to person alias and person tables so that rendered SQL has an INNER Joins vs OUTER joins on Person and PersonAlias
            var personAliasQry   = new PersonAliasService(rockContext).Queryable();
            var personQryForJoin = new PersonService(rockContext).Queryable(true);
            var financialTransactionDetailAmountQry = financialTransactionDetailBaseQry
                                                      .Join(
                personAliasQry,
                t => t.AuthorizedPersonAliasId,
                pa => pa.Id,
                (t, pa) => new { TransactionDetailData = t, PersonId = pa.PersonId })
                                                      .Join(
                personQryForJoin,
                j1 => j1.PersonId,
                p => p.Id,
                (j1, p) => new { Amount = j1.TransactionDetailData.Amount, Person = p });

            IQueryable <GiverAmountInfo> financialTransactionGivingAmountQry;

            if (combineGiving)
            {
                var financialTransactionGroupByQuery = financialTransactionDetailAmountQry.GroupBy(xx => xx.Person.GivingId);

                financialTransactionGivingAmountQry = financialTransactionGroupByQuery
                                                      .Select(xx => new GiverAmountInfo {
                    GivingId = xx.Key, TotalAmount = xx.Sum(ss => ss.Amount)
                });
            }
            else
            {
                var financialTransactionGroupByQuery = financialTransactionDetailAmountQry.GroupBy(xx => xx.Person.Id);

                financialTransactionGivingAmountQry = financialTransactionGroupByQuery
                                                      .Select(xx => new GiverAmountInfo {
                    PersonId = xx.Key, TotalAmount = xx.Sum(ss => ss.Amount)
                });
            }

            if (comparisonType == ComparisonType.LessThan)
            {
                // NOTE: Since we want people that have less than the specified, but also want to include people to didn't give anything at all (no transactions)
                // make this query the same as the GreaterThan, but use it to EXCLUDE people that gave MORE than the specified amount. That
                // way the filter will include people that had no transactions for the specified date/range and account
                financialTransactionGivingAmountQry = financialTransactionGivingAmountQry.Where(xx => xx.TotalAmount >= amount);
                excludePersonsWithTransactions      = true;
            }
            else if (comparisonType == ComparisonType.EqualTo)
            {
                if (amount == 0.00M)
                {
                    // NOTE: If we want to list people that gave $0.00 (they didn't giving anything)
                    // EXCLUDE people that gave any amount
                    excludePersonsWithTransactions = true;
                }
                else
                {
                    financialTransactionGivingAmountQry = financialTransactionGivingAmountQry.Where(xx => xx.TotalAmount == amount);
                }
            }
            else if (comparisonType == ComparisonType.GreaterThanOrEqualTo)
            {
                // NOTE: if the amount filter is 'they gave $0.00 or more', and doing a GreaterThanOrEqualTo, then we don't need to calculate and compare against TotalAmount
                if (amount == 0.00M)
                {
                    // no need to filter by amount if greater than or equal to $0.00
                }
                else
                {
                    financialTransactionGivingAmountQry = financialTransactionGivingAmountQry.Where(xx => xx.TotalAmount >= amount);
                }
            }

            IQueryable <Model.Person> qry;

            if (combineGiving)
            {
                if (excludePersonsWithTransactions)
                {
                    // the filter is for people that gave LESS than the specified amount, so return people that didn't give MORE than the specified amount
                    qry = new PersonService(rockContext).Queryable().Where(p => !financialTransactionGivingAmountQry.Any(xx => xx.GivingId == p.GivingId));
                }
                else
                {
                    qry = new PersonService(rockContext).Queryable().Where(p => financialTransactionGivingAmountQry.Any(xx => xx.GivingId == p.GivingId));
                }
            }
            else
            {
                if (excludePersonsWithTransactions)
                {
                    // the filter is for people that gave LESS than the specified amount, so return people that didn't give MORE than the specified amount
                    qry = new PersonService(rockContext).Queryable().Where(p => !financialTransactionGivingAmountQry.Any(xx => xx.PersonId == p.Id));
                }
                else
                {
                    qry = new PersonService(rockContext).Queryable().Where(p => financialTransactionGivingAmountQry.Any(xx => xx.PersonId == p.Id));
                }
            }

            Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p");

            return(extractedFilterExpression);
        }
Ejemplo n.º 9
0
        /// <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;

            SelectionConfig selectionConfig = SelectionConfig.Parse(selection);

            if (selectionConfig == null)
            {
                return(null);
            }

            DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(selectionConfig.DelimitedValues);

            int transactionTypeContributionId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid()).Id;
            var financialTransactionBaseQry   = new FinancialTransactionService(rockContext)
                                                .Queryable()
                                                .Where(xx => xx.TransactionTypeValueId == transactionTypeContributionId);

            var accountIdList = new FinancialAccountService(( RockContext )serviceInstance.Context).GetByGuids(selectionConfig.AccountGuids).Select(a => a.Id).ToList();

            if (accountIdList.Any())
            {
                if (accountIdList.Count == 1)
                {
                    int accountId = accountIdList.First();
                    financialTransactionBaseQry = financialTransactionBaseQry.Where(xx => xx.TransactionDetails.Any(a => a.AccountId == accountId));
                }
                else
                {
                    financialTransactionBaseQry = financialTransactionBaseQry.Where(xx => xx.TransactionDetails.Any(a => accountIdList.Contains(a.AccountId)));
                }
            }

            var personAliasQry   = new PersonAliasService(rockContext).Queryable();
            var personQryForJoin = new PersonService(rockContext).Queryable();

            // Create explicit joins to person alias and person tables so that rendered SQL has an INNER Joins vs OUTER joins on PersonAlias
            var financialTransactionsQry = financialTransactionBaseQry
                                           .Join(personAliasQry, t => t.AuthorizedPersonAliasId, pa => pa.Id, (t, pa) => new
            {
                txn      = t,
                PersonId = pa.PersonId
            });

            var firstContributionDateQry = financialTransactionsQry
                                           .GroupBy(xx => xx.PersonId)
                                           .Select(ss => new
            {
                PersonId             = ss.Key,
                FirstTransactionDate = ss.Min(a => selectionConfig.UseSundayDate == true ? a.txn.SundayDate : a.txn.TransactionDateTime)
            });

            if (dateRange.Start.HasValue)
            {
                firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionDate >= dateRange.Start.Value);
            }

            if (dateRange.End.HasValue)
            {
                firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionDate < 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));

            return(FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"));
        }
Ejemplo n.º 10
0
        /// <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 = Rock.Web.Cache.DefinedValueCache.Read( 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;
        }