Example #1
0
        /// <summary>
        /// Gets the financial transactions query.
        /// </summary>
        /// <param name="achievementTypeCache">The achievement type cache.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private IQueryable <FinancialTransaction> GetFinancialTransactionQuery(AchievementTypeCache achievementTypeCache, RockContext rockContext = null)
        {
            if (null == rockContext)
            {
                rockContext = new RockContext();
            }

            var includeChildAccounts = GetAttributeValue(achievementTypeCache, AttributeKey.IncludeChildFinancialAccounts).AsBoolean();
            var attributeMinDate     = GetAttributeValue(achievementTypeCache, AttributeKey.StartDateTime).AsDateTime();
            var attributeMaxDate     = GetAttributeValue(achievementTypeCache, AttributeKey.EndDateTime).AsDateTime();

            // Get the account identifier for this achievement type
            var accountId = GetFinancialAccountId(achievementTypeCache, rockContext);

            if (!accountId.HasValue)
            {
                return(null);
            }

            // For the include child accounts option to work we need to get the descendents for this Type
            var accountService       = new FinancialAccountService(rockContext);
            var accountDescendentIds = includeChildAccounts ? accountService.GetAllDescendentIds(accountId.Value).ToList() : new List <int>();

            var transactionService = new FinancialTransactionService(rockContext);

            var query = transactionService.Queryable()
                        .AsNoTracking()
                        .Where(t =>
                               t.AuthorizedPersonAliasId.HasValue &&
                               t.RefundDetails == null &&
                               t.TransactionDetails.Any(a =>
                                                        a.Amount > 0 &&
                                                        (a.AccountId == accountId ||
                                                         accountDescendentIds.Contains(a.AccountId))));

            if (attributeMinDate.HasValue)
            {
                query = query.Where(t => t.TransactionDateTime >= attributeMinDate.Value);
            }

            if (attributeMaxDate.HasValue)
            {
                var dayAfterMaxDate = attributeMaxDate.Value.AddDays(1);
                query = query.Where(t => t.TransactionDateTime < dayAfterMaxDate);
            }

            return(query);
        }
Example #2
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);
        }