/// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            //DateTime fromDate;
            //if ( !DateTime.TryParse( rFilter.GetUserPreference( "From Date" ), out fromDate ) )
            //{
            //    fromDate = DateTime.Today;
            //}
            //dtStartDate.Text = fromDate.ToShortDateString();
            dtStartDate.Text        = rFilter.GetUserPreference("From Date");
            dtEndDate.Text          = rFilter.GetUserPreference("To Date");
            txtFromAmount.Text      = rFilter.GetUserPreference("From Amount");
            txtToAmount.Text        = rFilter.GetUserPreference("To Amount");
            txtTransactionCode.Text = rFilter.GetUserPreference("Transaction Code");

            var accountService = new FinancialAccountService();

            foreach (FinancialAccount account in accountService.Queryable())
            {
                ListItem li = new ListItem(account.Name, account.Id.ToString());
                li.Selected = account.Id.ToString() == rFilter.GetUserPreference("Account");
                ddlAccount.Items.Add(li);
            }
            ddlAccount.Items.Insert(0, Rock.Constants.All.ListItem);

            BindDefinedTypeDropdown(ddlTransactionType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_TYPE), "Transaction Type");
            BindDefinedTypeDropdown(ddlCurrencyType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE), "Currency Type");
            BindDefinedTypeDropdown(ddlCreditCardType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE), "Credit Card Type");
            BindDefinedTypeDropdown(ddlSourceType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_SOURCE_TYPE), "Source");
        }
Exemple #2
0
        /// <summary>
        /// Handles the Changed event of the caapExample control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void caapExample_Changed(object sender, EventArgs e)
        {
            var financialAccountService = new FinancialAccountService(new RockContext());

            lCaapExampleSingleAccountResultAccount.Text = financialAccountService.GetByIds(caapExampleSingleAccount.SelectedAccountIds.ToList()).Select(a => a.PublicName).ToList().AsDelimited(", ");
            lCaapExampleMultiAccountResultAccount.Text  = financialAccountService.GetByIds(caapExampleMultiAccount.SelectedAccountIds.ToList()).Select(a => a.PublicName).ToList().AsDelimited(", ");
        }
Exemple #3
0
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection(System.Web.UI.Control[] controls)
        {
            string delimitedAccountGuids = string.Empty;
            string useSundayDate         = string.Empty;

            if (controls.Count() > 0)
            {
                AccountPicker accountPicker = controls[0] as AccountPicker;
                if (accountPicker != null)
                {
                    var accountIds   = accountPicker.SelectedValues.AsIntegerList();
                    var accountGuids = new FinancialAccountService(new RockContext()).GetByIds(accountIds).Select(a => a.Guid);
                    delimitedAccountGuids = accountGuids.Select(a => a.ToString()).ToList().AsDelimited(",");
                }

                if (controls.Count() > 1)
                {
                    RockCheckBox cbUseSundayDate = controls[1] as RockCheckBox;
                    if (cbUseSundayDate != null)
                    {
                        useSundayDate = cbUseSundayDate.Checked.ToString();
                    }
                }

                if (delimitedAccountGuids != string.Empty || useSundayDate != string.Empty)
                {
                    return($"{delimitedAccountGuids}|{useSundayDate}");
                }
            }

            return(null);
        }
Exemple #4
0
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(System.Web.UI.Control[] controls, string selection)
        {
            string[] selections = selection.Split('|');

            if (controls.Count() > 0)
            {
                AccountPicker accountPicker = controls[0] as AccountPicker;
                if (accountPicker != null)
                {
                    string[] selectionAccountGuidValues = selections[0].Split(',');
                    var      accountList = new List <FinancialAccount>();
                    foreach (string accountGuid in selectionAccountGuidValues)
                    {
                        var account = new FinancialAccountService(new RockContext()).Get(accountGuid.AsGuid());
                        if (account != null)
                        {
                            accountList.Add(account);
                        }
                    }

                    accountPicker.SetValues(accountList);
                }
            }

            if (controls.Count() > 1)
            {
                RockCheckBox cbUseSundayDate = controls[1] as RockCheckBox;
                if (cbUseSundayDate != null && selections.Count() > 1)
                {
                    cbUseSundayDate.Checked = selections[1].AsBooleanOrNull() ?? false;
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (hfAccountId.Value.Equals("0"))
            {
                int?parentAccountId = PageParameter("ParentAccountId").AsIntegerOrNull();
                if (parentAccountId.HasValue)
                {
                    // Cancelling on Add, and we know the parentGroupID, so we are probably in treeview mode, so navigate to the current page
                    var qryParams = new Dictionary <string, string>();
                    if (parentAccountId != 0)
                    {
                        qryParams["AccountId"] = parentAccountId.ToString();
                    }

                    qryParams["ExpandedIds"] = PageParameter("ExpandedIds");
                    NavigateToPage(RockPage.Guid, qryParams);
                }
                else
                {
                    // Cancelling on Add.  Return to Grid
                    NavigateToPage(RockPage.Guid, null);
                }
            }
            else
            {
                // Cancelling on Edit.  Return to Details
                FinancialAccountService service = new FinancialAccountService(new RockContext());
                FinancialAccount        account = service.Get(hfAccountId.ValueAsInt());
                ShowReadonlyDetails(account);
            }
        }
Exemple #6
0
        /// <summary>
        /// Sets the edit value from IEntity.Id value
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id">The identifier.</param>
        public void SetEditValueFromEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id)
        {
            var    item      = new FinancialAccountService(new RockContext()).Get(id ?? 0);
            string guidValue = item != null?item.Guid.ToString() : string.Empty;

            SetEditValue(control, configurationValues, guidValue);
        }
        /// <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);
        }
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Control[] controls, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 4)
            {
                var comparisonControl = controls[0] as DropDownList;
                var numberBox         = controls[1] as CurrencyBox;
                var accountPicker     = controls[2] as AccountPicker;
                SlidingDateRangePicker slidingDateRangePicker = controls[3] as SlidingDateRangePicker;
                var cbCombineGiving = controls[4] as RockCheckBox;
                var cbUseAnalytics  = controls[5] as RockCheckBox;

                comparisonControl.SetValue(selectionValues[0]);
                decimal?amount = selectionValues[1].AsDecimal();
                if (amount.HasValue)
                {
                    numberBox.Text = amount.Value.ToString("F2");
                }
                else
                {
                    numberBox.Text = string.Empty;
                }


                if (selectionValues.Length >= 7)
                {
                    // convert comma delimited to pipe
                    slidingDateRangePicker.DelimitedValues = selectionValues[6].Replace(',', '|');
                }
                else
                {
                    // if converting from a previous version of the selection
                    var lowerValue = selectionValues[2].AsDateTime();
                    var upperValue = selectionValues[3].AsDateTime();

                    slidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.DateRange;
                    slidingDateRangePicker.SetDateRangeModeValue(new DateRange(lowerValue, upperValue));
                }

                if (selectionValues.Length >= 5)
                {
                    var accountGuids = selectionValues[4].Split(',').Select(a => a.AsGuid()).ToList();
                    var accounts     = new FinancialAccountService(new RockContext()).GetByGuids(accountGuids);
                    if (accounts != null && accounts.Any())
                    {
                        accountPicker.SetValues(accounts);
                    }
                }

                if (selectionValues.Length >= 6)
                {
                    cbCombineGiving.Checked = selectionValues[5].AsBooleanOrNull() ?? false;
                }

                if (selectionValues.Length >= 8)
                {
                    cbUseAnalytics.Checked = selectionValues[7].AsBooleanOrNull() ?? false;
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Gets the edit value as the IEntity.Id
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public int?GetEditValueAsEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            Guid guid = GetEditValue(control, configurationValues).AsGuid();
            var  item = new FinancialAccountService(new RockContext()).Get(guid);

            return(item != null ? item.Id : ( int? )null);
        }
Exemple #10
0
        private IQueryable <FinancialAccount> GetAccounts()
        {
            var          accountService = new FinancialAccountService();
            SortProperty sortProperty   = rGridAccount.SortProperty;
            var          accountQuery   = accountService.Queryable();

            string accountNameFilter = rAccountFilter.GetUserPreference("Account Name");

            if (!string.IsNullOrEmpty(accountNameFilter))
            {
                accountQuery = accountQuery.Where(account => account.Name.Contains(accountNameFilter));
            }

            string activeFilter = rAccountFilter.GetUserPreference("Active");

            if (!string.IsNullOrWhiteSpace(activeFilter))
            {
                accountQuery = accountQuery.Where(account => account.IsActive == (activeFilter == "Yes"));
            }

            string taxDeductibleFilter = rAccountFilter.GetUserPreference("Tax Deductible");

            if (!string.IsNullOrWhiteSpace(taxDeductibleFilter))
            {
                accountQuery = accountQuery.Where(account => account.IsTaxDeductible == (taxDeductibleFilter == "Yes"));
            }

            accountQuery = accountQuery.OrderBy(a => a.Order);

            return(accountQuery);
        }
        /// <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)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 3)
            {
                var accountPicker          = controls[0] as AccountPicker;
                var slidingDateRangePicker = controls[1] as SlidingDateRangePicker;

                if (selectionValues.Length >= 4)
                {
                    // convert comma delimited to pipe
                    slidingDateRangePicker.DelimitedValues = selectionValues[3].Replace(',', '|');
                }
                else
                {
                    // if converting from a previous version of the selection
                    var lowerValue = selectionValues[0].AsDateTime();
                    var upperValue = selectionValues[1].AsDateTime();

                    slidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.DateRange;
                    slidingDateRangePicker.SetDateRangeModeValue(new DateRange(lowerValue, upperValue));
                }

                var accountGuids = selectionValues[2].Split(',').Select(a => a.AsGuid()).ToList();
                var accounts     = new FinancialAccountService(new RockContext()).GetByGuids(accountGuids);
                if (accounts != null && accounts.Any())
                {
                    accountPicker.SetValues(accounts);
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Gets the transaction details.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        protected List <FinancialTransactionDetail> GetTransactionDetails(RockContext rockContext)
        {
            var details = new List <FinancialTransactionDetail>();
            var financialAccountService = new FinancialAccountService(rockContext);
            int defaultAccountId        = financialAccountService.Get(GetAttributeValue("DefaultAccount").AsGuid()).Id;

            foreach (var item in Cart.Items)
            {
                int financialAccountId = item.AccountId ?? defaultAccountId;

                var transactionDetail = details.FirstOrDefault(d => d.AccountId == financialAccountId);

                if (transactionDetail == null)
                {
                    transactionDetail = new FinancialTransactionDetail
                    {
                        Amount    = 0,
                        AccountId = financialAccountId
                    };
                    details.Add(transactionDetail);
                }

                transactionDetail.Amount += item.ExtendedPrice;
            }

            return(details);
        }
Exemple #13
0
        /// <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)
        {
            string formattedValue = string.Empty;

            if (!string.IsNullOrWhiteSpace(value))
            {
                bool displayPublicName = true;

                if (configurationValues != null &&
                    configurationValues.ContainsKey(DISPLAY_PUBLIC_NAME))
                {
                    displayPublicName = configurationValues[DISPLAY_PUBLIC_NAME].Value.AsBoolean();
                }

                var guids = value.SplitDelimitedValues();

                using (var rockContext = new RockContext())
                {
                    var accounts = new FinancialAccountService(rockContext).Queryable().AsNoTracking().Where(a => guids.Contains(a.Guid.ToString()));
                    if (accounts.Any())
                    {
                        formattedValue = string.Join(", ", (from account in accounts select displayPublicName && account.PublicName != null && account.PublicName != string.Empty ? account.PublicName : account.Name).ToArray());
                    }
                }
            }

            return(base.FormatValue(parentControl, formattedValue, null, condensed));
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection(Type entityType, Control[] controls)
        {
            SelectionConfig selectionConfig = new SelectionConfig();

            var    accountIdList = (controls[0] as AccountPicker).SelectedValuesAsInt().ToList();
            string accountGuids  = string.Empty;
            var    accounts      = new FinancialAccountService(new RockContext()).GetByIds(accountIdList);

            if (accounts != null && accounts.Any())
            {
                selectionConfig.AccountGuids = accounts.Select(a => a.Guid).ToList();
            }

            SlidingDateRangePicker slidingDateRangePicker = controls[1] as SlidingDateRangePicker;

            selectionConfig.StartDate         = slidingDateRangePicker.DateRangeModeStart;
            selectionConfig.EndDate           = slidingDateRangePicker.DateRangeModeEnd;
            selectionConfig.DateRangeMode     = slidingDateRangePicker.SlidingDateRangeMode;
            selectionConfig.TimeUnit          = slidingDateRangePicker.TimeUnit;
            selectionConfig.NumberOfTimeUnits = slidingDateRangePicker.NumberOfTimeUnits;

            selectionConfig.UseSundayDate = (controls[2] as RockCheckBox).Checked;

            return(selectionConfig.ToJson());
        }
Exemple #15
0
        /// <summary>
        /// Sets the values on select.
        /// </summary>
        /// <exception cref="System.NotImplementedException"></exception>
        protected override void SetValuesOnSelect()
        {
            var itemIds = ItemIds.Select(int.Parse);
            var items   = new FinancialAccountService(new RockContext()).Queryable().Where(i => itemIds.Contains(i.Id));

            this.SetValues(items);
        }
Exemple #16
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="accountId">The account identifier.</param>
        public void ShowDetail( int accountId )
        {
            FinancialAccount account = null;

            bool editAllowed = UserCanEdit;

            if ( !accountId.Equals( 0 ) )
            {
                account = new FinancialAccountService( new RockContext() ).Get( accountId );
                editAllowed = editAllowed || account.IsAuthorized( Authorization.EDIT, CurrentPerson );
                pdAuditDetails.SetEntity( account, ResolveRockUrl( "~" ) );
            }

            if ( account == null )
            {
                account = new FinancialAccount { Id = 0, IsActive = true };
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            hfAccountId.Value = account.Id.ToString();

            nbEditModeMessage.Text = string.Empty;
            if (editAllowed)
            {
                ShowEditDetails(account);
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialAccount.FriendlyTypeName);
                ShowReadonlyDetails(account);
            }
        }
Exemple #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShoppingCartItem"/> class.
        /// </summary>
        /// <param name="item">The content channel item to build from.</param>
        public ShoppingCartItem(ContentChannelItem item)
            : this()
        {
            if (item.Attributes == null)
            {
                item.LoadAttributes();
            }

            ItemId    = item.Id;
            Name      = item.Title;
            Quantity  = 1;
            Price     = item.GetAttributeValue("CubeDown.Price").AsDecimal();
            IsTaxable = item.GetAttributeValue("CubeDown.Taxable").AsBoolean(false);

            //
            // If an Account Guid was provided, convert it to an Id number.
            //
            var accountGuid = item.GetAttributeValue("CubeDown.Account").AsGuidOrNull();

            if (accountGuid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var account = new FinancialAccountService(rockContext).Get(accountGuid.Value);

                    AccountId = account?.Id;
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// Handles the Command event of the lnkAccount control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="CommandEventArgs"/> instance containing the event data.</param>
        protected void lnkAccount_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == LinkCommand.AccountClick)
            {
                var accountService = new FinancialAccountService(new RockContext());

                var queryParams = new Dictionary <string, string>();

                var accountId = e.CommandArgument.ToString();

                if (accountId.IsNotNullOrWhiteSpace())
                {
                    var accountIdNum = accountId.AsInteger();
                    var parentIds    = accountService.GetAllAncestorIds(accountIdNum).Reverse()?.ToList();
                    if (parentIds == null)
                    {
                        parentIds = new List <int>();
                    }

                    queryParams.Add("AccountId", accountId);
                    queryParams.Add("ExpandedIds", parentIds.Select(v => v.ToString()).JoinStrings(","));
                    NavigateToPage(Rock.SystemGuid.Page.ACCOUNTS.AsGuid(), queryParams);
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            if (value != null)
            {
                var picker = control as AccountPicker;
                var guids  = new List <Guid>();

                if (picker != null)
                {
                    var ids = value.Split(new[] { ',' });

                    foreach (var id in ids)
                    {
                        Guid guid;

                        if (Guid.TryParse(id, out guid))
                        {
                            guids.Add(guid);
                        }
                    }

                    var accounts = new FinancialAccountService().Queryable().Where(a => guids.Contains(a.Guid));
                    picker.SetValues(accounts);
                }
            }
        }
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            nreAmount.DelimitedValues = gfSettings.GetUserPreference("Amount");

            ddlFrequency.BindToDefinedType(DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY.AsGuid()));
            ddlFrequency.Items.Insert(0, new ListItem(string.Empty, string.Empty));
            string freqPreference = gfSettings.GetUserPreference("Frequency");

            if (!string.IsNullOrWhiteSpace(freqPreference))
            {
                ddlFrequency.SetValue(freqPreference);
            }

            drpDates.DelimitedValues = gfSettings.GetUserPreference("Created");

            var accountService = new FinancialAccountService(new RockContext());
            var accounts       = accountService
                                 .Queryable().AsNoTracking()
                                 .Where(a => a.IsActive);

            ddlAccount.Visible = string.IsNullOrWhiteSpace(GetAttributeValue("Accounts"));
            ddlAccount.Items.Add(new ListItem(string.Empty, string.Empty));
            foreach (FinancialAccount account in accounts.OrderBy(a => a.Order))
            {
                ListItem li = new ListItem(account.Name, account.Id.ToString());
                li.Selected = account.Id.ToString() == gfSettings.GetUserPreference("Account");
                ddlAccount.Items.Add(li);
            }

            cbIncludeInactive.Checked = !string.IsNullOrWhiteSpace(gfSettings.GetUserPreference("Include Inactive"));
        }
Exemple #21
0
        /// <summary>
        /// Handles the Click event of the btnEdit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            FinancialAccountService service = new FinancialAccountService(new RockContext());
            FinancialAccount        account = service.Get(hfAccountId.ValueAsInt());

            ShowEditDetails(account);
        }
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        public void LoadDropDowns()
        {
            // get accounts that are both allowed by the BlockSettings and also in the personal AccountList setting
            var rockContext = new RockContext();
            var accountGuidList = GetAttributeValue( "Accounts" ).SplitDelimitedValues().Select( a => a.AsGuid() );

            string keyPrefix = string.Format( "transaction-matching-{0}-", this.BlockId );
            var personalAccountGuidList = ( this.GetUserPreference( keyPrefix + "account-list" ) ?? string.Empty ).SplitDelimitedValues().Select( a => a.AsGuid() ).ToList();

            var accountQry = new FinancialAccountService( rockContext ).Queryable();

            // no accounts specified means "all"
            if ( accountGuidList.Any() )
            {
                accountQry = accountQry.Where( a => accountGuidList.Contains( a.Guid ) );
            }

            // no personal accounts specified means "all(that are allowed in block settings)"
            if ( personalAccountGuidList.Any() )
            {
                accountQry = accountQry.Where( a => personalAccountGuidList.Contains( a.Guid ) );
            }

            rptAccounts.DataSource = accountQry.OrderBy( a => a.Order ).ThenBy( a => a.Name ).ToList();
            rptAccounts.DataBind();
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="accountId">The account identifier.</param>
        public void ShowDetail(int accountId)
        {
            FinancialAccount account = null;

            bool editAllowed = UserCanEdit;

            if (!accountId.Equals(0))
            {
                account     = new FinancialAccountService(new RockContext()).Get(accountId);
                editAllowed = editAllowed || account.IsAuthorized(Authorization.EDIT, CurrentPerson);
                pdAuditDetails.SetEntity(account, ResolveRockUrl("~"));
            }

            if (account == null)
            {
                account = new FinancialAccount {
                    Id = 0, IsActive = true
                };
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            hfAccountId.Value = account.Id.ToString();

            nbEditModeMessage.Text = string.Empty;
            if (editAllowed)
            {
                ShowEditDetails(account);
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialAccount.FriendlyTypeName);
                ShowReadonlyDetails(account);
            }
        }
Exemple #24
0
        /// <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)
        {
            string formattedValue = string.Empty;

            Guid?guid = value.AsGuidOrNull();

            if (guid.HasValue)
            {
                bool displayPublicName = true;

                if (configurationValues != null &&
                    configurationValues.ContainsKey(DISPLAY_PUBLIC_NAME))
                {
                    displayPublicName = configurationValues[DISPLAY_PUBLIC_NAME].Value.AsBoolean();
                }

                using (var rockContext = new RockContext())
                {
                    var service = new FinancialAccountService(rockContext);
                    var account = service.GetNoTracking(guid.Value);

                    if (account != null)
                    {
                        formattedValue = displayPublicName ? account.PublicName : account.Name;
                    }
                }
            }

            return(base.FormatValue(parentControl, formattedValue, null, condensed));
        }
Exemple #25
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        public void LoadDropDowns()
        {
            // get accounts that are both allowed by the BlockSettings and also in the personal AccountList setting
            var rockContext     = new RockContext();
            var accountGuidList = GetAttributeValue("Accounts").SplitDelimitedValues().Select(a => a.AsGuid());

            string keyPrefix = string.Format("transaction-matching-{0}-", this.BlockId);
            var    personalAccountGuidList = (this.GetUserPreference(keyPrefix + "account-list") ?? string.Empty).SplitDelimitedValues().Select(a => a.AsGuid()).ToList();

            var accountQry = new FinancialAccountService(rockContext)
                             .Queryable()
                             .Where(a => a.IsActive);

            // no accounts specified means "all Active"
            if (accountGuidList.Any())
            {
                accountQry = accountQry.Where(a => accountGuidList.Contains(a.Guid));
            }

            // no personal accounts specified means "all(that are allowed in block settings)"
            if (personalAccountGuidList.Any())
            {
                accountQry = accountQry.Where(a => personalAccountGuidList.Contains(a.Guid));
            }

            rptAccounts.DataSource = accountQry.OrderBy(a => a.Order).ThenBy(a => a.Name).ToList();
            rptAccounts.DataBind();
        }
Exemple #26
0
        /// <summary>
        /// Reads new values entered by the user for the field
        /// returns Account.Guid
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public override string GetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            var picker = control as AccountPicker;

            if (picker != null)
            {
                int?id = picker.ItemId.AsIntegerOrNull();
                if (id.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        var account = new FinancialAccountService(rockContext).GetNoTracking(id.Value);

                        if (account != null)
                        {
                            return(account.Guid.ToString());
                        }
                    }
                }
                else
                {
                    return(string.Empty);
                }
            }

            return(null);
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection(Control[] controls)
        {
            string  comparisonType = (( DropDownList )controls[0]).SelectedValue;
            decimal?amount         = (controls[1] as CurrencyBox).Text.AsDecimal();

            var    accountIdList = (controls[2] as AccountPicker).SelectedValuesAsInt().ToList();
            string accountGuids  = string.Empty;
            var    accounts      = new FinancialAccountService(new RockContext()).GetByIds(accountIdList);

            if (accounts != null && accounts.Any())
            {
                accountGuids = accounts.Select(a => a.Guid).ToList().AsDelimited(",");
            }

            SlidingDateRangePicker slidingDateRangePicker = controls[3] as SlidingDateRangePicker;

            // convert pipe to comma delimited
            var delimitedValues = slidingDateRangePicker.DelimitedValues.Replace("|", ",");

            RockCheckBox cbCombineGiving = controls[4] as RockCheckBox;
            RockCheckBox cbUseAnalytics  = controls[5] as RockCheckBox;

            // {2} and {3} used to store the DateRange before, but now we using the SlidingDateRangePicker
            return($"{comparisonType}|{amount}|||{accountGuids}|{cbCombineGiving.Checked}|{delimitedValues}|{cbUseAnalytics.Checked}");
        }
Exemple #28
0
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            drpDates.DelimitedValues  = gfTransactions.GetUserPreference("Date Range");
            nreAmount.DelimitedValues = gfTransactions.GetUserPreference("Amount Range");
            tbTransactionCode.Text    = gfTransactions.GetUserPreference("Transaction Code");

            apAccount.DisplayActiveOnly = GetAttributeValue("ActiveAccountsOnlyFilter").AsBoolean();

            var accountIds = (gfTransactions.GetUserPreference("Account") ?? "").SplitDelimitedValues().AsIntegerList().Where(a => a > 0).ToList();

            if (accountIds.Any())
            {
                var service  = new FinancialAccountService(new RockContext());
                var accounts = service.GetByIds(accountIds).OrderBy(a => a.Order).OrderBy(a => a.Name).ToList();
                apAccount.SetValues(accounts);
            }
            else
            {
                apAccount.SetValue(0);
            }


            BindDefinedTypeDropdown(ddlTransactionType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_TYPE), "Transaction Type");
            BindDefinedTypeDropdown(ddlCurrencyType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE), "Currency Type");
            BindDefinedTypeDropdown(ddlCreditCardType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE), "Credit Card Type");
            BindDefinedTypeDropdown(ddlSourceType, new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_SOURCE_TYPE), "Source Type");
        }
Exemple #29
0
        private List <JournalEntryLine> GetGlEntries(FinancialBatch financialBatch, ref string debugLava, string DescriptionLava = "")
        {
            if (string.IsNullOrWhiteSpace(DescriptionLava))
            {
                DescriptionLava = "{{ Batch.Id }}: {{ Batch.Name }}";
            }

            var rockContext = new RockContext();

            //
            // Group/Sum Transactions by Account and Project since Project can come from Account or Transaction Details
            //
            List <RegistrationInstance> registrationLinks;
            List <GroupMember>          groupMemberLinks;
            var batchTransactionsSummary = TransactionHelpers.GetTransactionSummary(financialBatch, rockContext, out registrationLinks, out groupMemberLinks);

            //
            // Get the Dimensions from the Account since the Transaction Details have been Grouped already
            //
            var customDimensions = TransactionHelpers.GetCustomDimensions();
            var batchSummary     = new List <GLBatchTotals>();

            foreach (var summary in batchTransactionsSummary)
            {
                var account = new FinancialAccountService(rockContext).Get(summary.FinancialAccountId);
                var customDimensionValues = new Dictionary <string, dynamic>();
                account.LoadAttributes();
                var mergeFieldObjects = new MergeFieldObjects
                {
                    Account          = account,
                    Batch            = financialBatch,
                    Registrations    = registrationLinks,
                    GroupMembers     = groupMemberLinks,
                    Summary          = summary,
                    CustomDimensions = customDimensions
                };
                Dictionary <string, object> mergeFields = TransactionHelpers.GetMergeFieldsAndDimensions(ref debugLava, customDimensionValues, mergeFieldObjects);

                var batchSummaryItem = new GLBatchTotals()
                {
                    Amount                = summary.Amount,
                    CreditAccount         = account.GetAttributeValue("rocks.kfs.Intacct.ACCOUNTNO"),
                    DebitAccount          = account.GetAttributeValue("rocks.kfs.Intacct.DEBITACCOUNTNO"),
                    TransactionFeeAmount  = summary.TransactionFeeAmount,
                    TransactionFeeAccount = summary.TransactionFeeAccount,
                    Class                  = account.GetAttributeValue("rocks.kfs.Intacct.CLASSID"),
                    Department             = account.GetAttributeValue("rocks.kfs.Intacct.DEPARTMENT"),
                    Location               = account.GetAttributeValue("rocks.kfs.Intacct.LOCATION"),
                    Project                = summary.Project,
                    Description            = DescriptionLava.ResolveMergeFields(mergeFields),
                    CustomDimensions       = customDimensionValues,
                    ProcessTransactionFees = summary.ProcessTransactionFees
                };

                batchSummary.Add(batchSummaryItem);
            }

            return(GenerateLineItems(batchSummary));
        }
        /// <summary>
        /// Binds the yearly summary.
        /// </summary>
        private void BindYearlySummary()
        {
            var givingId = Person.GivingId;

            using (var rockContext = new RockContext())
            {
                DateTime?startDate;
                if (!IsYearlySummaryExpanded)
                {
                    // Only show this current year and last year
                    startDate = RockDateTime.Now.StartOfYear().AddYears(-1);
                }
                else
                {
                    startDate = null;
                }

                var monthlyAccountGivingHistoryList = new FinancialTransactionService(rockContext).GetGivingAutomationMonthlyAccountGivingHistory(givingId, startDate);

                var financialAccounts = new FinancialAccountService(rockContext).Queryable()
                                        .AsNoTracking()
                                        .ToDictionary(k => k.Id, v => v.Name);

                var summaryList = monthlyAccountGivingHistoryList
                                  .GroupBy(a => new { a.Year, a.AccountId })
                                  .Select(t => new SummaryRecord
                {
                    Year        = t.Key.Year,
                    AccountId   = t.Key.AccountId,
                    TotalAmount = t.Sum(d => d.Amount)
                })
                                  .OrderByDescending(a => a.Year)
                                  .ToList();

                var contributionSummaries = new List <ContributionSummary>();
                foreach (var item in summaryList.GroupBy(a => a.Year))
                {
                    var contributionSummary = new ContributionSummary();
                    contributionSummary.Year           = item.Key;
                    contributionSummary.SummaryRecords = new List <SummaryRecord>();
                    foreach (var a in item)
                    {
                        a.AccountName = financialAccounts.ContainsKey(a.AccountId) ? financialAccounts[a.AccountId] : string.Empty;
                        contributionSummary.SummaryRecords.Add(a);
                    }

                    contributionSummary.TotalAmount = item.Sum(a => a.TotalAmount);
                    contributionSummaries.Add(contributionSummary);
                }

                rptYearSummary.DataSource = contributionSummaries;
                rptYearSummary.DataBind();

                // Show the correct button to expand or collapse
                lbShowLessYearlySummary.Visible = IsYearlySummaryExpanded;
                lbShowMoreYearlySummary.Visible = !IsYearlySummaryExpanded;
            }
        }
        /// <inheritdoc/>
        public override IOrderedQueryable <object> SearchQuery(string searchTerm)
        {
            var rockContext             = new RockContext();
            var financialAccountService = new FinancialAccountService(rockContext);
            var qry = financialAccountService.GetAccountsBySearchTerm(searchTerm);

            return(qry
                   .OrderBy(p => p.PublicName.IsNullOrWhiteSpace() ? p.Name : p.PublicName));
        }
        /// <summary>
        /// Shows the view.
        /// </summary>
        private void ShowForm()
        {
            lReceipt.Visible     = false;
            pnlAddPledge.Visible = true;

            if (CurrentPerson != null)
            {
                tbFirstName.Text = CurrentPerson.FirstName;
                tbLastName.Text  = CurrentPerson.LastName;
                tbEmail.Text     = CurrentPerson.Email;
            }

            // Warn if Financial Account is not specified (must be set up by administrator)
            var financialAccount = new FinancialAccountService(new RockContext()).Get(GetAttributeValue("Account").AsGuid());

            if (financialAccount == null)
            {
                nbWarningMessage.Text    = "Warning: No Account is specified for this pledge.  Please contact the administrator.";
                nbWarningMessage.Visible = true;
            }
            else
            {
                nbWarningMessage.Visible = false;
            }

            drpDateRange.DelimitedValues = GetAttributeValue("PledgeDateRange");

            // only show the date range picker if the block setting for date range isn't fully specified
            drpDateRange.Visible = drpDateRange.LowerValue == null || drpDateRange.UpperValue == null;

            bddlFrequency.Items.Clear();
            var frequencies = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY.AsGuid()).DefinedValues.OrderBy(a => a.Order).ThenBy(a => a.Value);

            foreach (var frequency in frequencies)
            {
                bddlFrequency.Items.Add(new ListItem(frequency.Value, frequency.Id.ToString()));
            }

            bddlFrequency.Visible       = GetAttributeValue("ShowPledgeFrequency").AsBooleanOrNull() ?? false;
            bddlFrequency.SelectedValue = null;

            // if Frequency is Visible, require it if RequirePledgeFrequency
            bddlFrequency.Required = bddlFrequency.Visible && (GetAttributeValue("RequirePledgeFrequency").AsBooleanOrNull() ?? false);

            string saveButtonText = GetAttributeValue("SaveButtonText");

            if (!string.IsNullOrWhiteSpace(saveButtonText))
            {
                btnSave.Text = saveButtonText;
            }
            else
            {
                btnSave.Text = "Save";
            }

            lNote.Text = GetAttributeValue("NoteMessage");
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail( string itemKey, int itemKeyValue )
        {
            pnlDetails.Visible = false;

            if ( !itemKey.Equals( "accountId" ) )
            {
                return;
            }

            bool editAllowed = true;

            FinancialAccount account = null;

            if ( !itemKeyValue.Equals( 0 ) )
            {
                account = new FinancialAccountService( new RockContext() ).Get( itemKeyValue );
                editAllowed = account.IsAuthorized( Authorization.EDIT, CurrentPerson );
            }
            else
            {
                account = new FinancialAccount { Id = 0, IsActive = true };
            }

            if ( account == null )
            {
                return;
            }

            pnlDetails.Visible = true;
            hfAccountId.Value = account.Id.ToString();

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( FinancialAccount.FriendlyTypeName );
            }

            if ( readOnly )
            {
                ShowReadonlyDetails( account );
            }
            else
            {
                ShowEditDetails( account );
            }
        }
Exemple #34
0
        /// <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 )
        {
            string formattedValue = string.Empty;

            if ( !string.IsNullOrWhiteSpace( value ) )
            {
                var guids = value.SplitDelimitedValues();
                var accounts = new FinancialAccountService().Queryable().Where( a => guids.Contains( a.Guid.ToString() ) );
                if ( accounts.Any() )
                {
                    formattedValue = string.Join( ", ", ( from account in accounts select account.PublicName ).ToArray() );
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
Exemple #35
0
        /// <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 )
        {
            string formattedValue = string.Empty;

            if ( !string.IsNullOrWhiteSpace( value ) )
            {
                var service = new FinancialAccountService( new RockContext() );
                var account = service.Get( new Guid( value ) );

                if ( account != null )
                {
                    formattedValue = account.PublicName;
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
        /// <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 )
        {
            string formattedValue = string.Empty;

            Guid? guid = value.AsGuidOrNull();
            if ( guid.HasValue )
            {
                var service = new FinancialAccountService( new RockContext() );
                var account = service.Get( guid.Value );

                if ( account != null )
                {
                    formattedValue = account.PublicName;
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
Exemple #37
0
        /// <summary>
        /// Reads new values entered by the user for the field
        /// returns Account.Guid
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public override string GetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues )
        {
            var picker = control as AccountPicker;
            string result = null;

            if ( picker != null )
            {
                var guid = Guid.Empty;
                var id = picker.ItemId.AsIntegerOrNull();
                var account = new FinancialAccountService( new RockContext() ).Get( id ?? 0 );

                if ( account != null )
                {
                    guid = account.Guid;
                }

                result = guid.ToString();
            }

            return result;
        }
Exemple #38
0
        /// <summary>
        /// Reads new values entered by the user for the field
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public override string GetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues )
        {
            var picker = control as AccountPicker;
            string result = null;

            if ( picker != null )
            {
                var guids = new List<Guid>();
                var ids = picker.SelectedValuesAsInt();
                var accounts = new FinancialAccountService().Queryable().Where( a => ids.Contains( a.Id ) );

                if ( accounts.Any() )
                {
                    guids = accounts.Select( a => a.Guid ).ToList();
                }

                result = string.Join( ",", guids );
            }

            return result;
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="accountId">The account identifier.</param>
        public void ShowDetail( int accountId )
        {
            FinancialAccount account = null;

            bool editAllowed = UserCanEdit;

            if ( !accountId.Equals( 0 ) )
            {
                account = new FinancialAccountService( new RockContext() ).Get( accountId );
                editAllowed = editAllowed || account.IsAuthorized( Authorization.EDIT, CurrentPerson );
            }

            if ( account == null )
            {
                account = new FinancialAccount { Id = 0, IsActive = true };
            }

            hfAccountId.Value = account.Id.ToString();

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !editAllowed || !editAllowed )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( FinancialAccount.FriendlyTypeName );
            }

            if ( readOnly )
            {
                ShowReadonlyDetails( account );
            }
            else
            {
                ShowEditDetails( account );
            }
        }
Exemple #40
0
        /// <summary>
        /// Gfs the pledges_ display filter value.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void gfPledges_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e )
        {
            switch ( e.Key )
            {
                case "Date Range":
                    if ( drpDates.Visible )
                    {
                        e.Value = DateRangePicker.FormatDelimitedValues( e.Value );
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }
                    break;

                case "Last Modified":
                    if ( drpLastModifiedDates.Visible )
                    {
                        e.Value = DateRangePicker.FormatDelimitedValues( e.Value );
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }
                    break;

                case "Person":
                    int? personId = e.Value.AsIntegerOrNull();
                    if ( personId != null && ppFilterPerson.Visible )
                    {
                        var person = new PersonService( new RockContext() ).Get( personId.Value );
                        if ( person != null )
                        {
                            e.Value = person.ToString();
                        }
                        else
                        {
                            e.Value = string.Empty;
                        }
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }
                    break;

                case "Accounts":

                    var accountIdList = e.Value.Split( ',' ).AsIntegerList();
                    if ( accountIdList.Any() && apFilterAccount.Visible )
                    {
                        var service = new FinancialAccountService( new RockContext() );
                        var accounts = service.GetByIds( accountIdList );
                        if ( accounts != null && accounts.Any() )
                        {
                            e.Value = accounts.Select( a => a.Name ).ToList().AsDelimited( "," );
                        }
                        else
                        {
                            e.Value = string.Empty;
                        }
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }

                    break;

                default:
                    e.Value = string.Empty;
                    break;
            }
        }
Exemple #41
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();
        }
        private void LoadAccounts()
        {
            var rockContext = new RockContext();
            FinancialAccountService accountService = new FinancialAccountService(rockContext);

            List<Guid> selectedAccounts = new List<Guid>(); ;

            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "Accounts" ) ) )
            {
                selectedAccounts = GetAttributeValue( "Accounts" ).Split( ',' ).Select( Guid.Parse ).ToList();
            }

            var accounts = accountService.Queryable()
                                .Where( a => selectedAccounts.Contains( a.Guid ) )
                                .OrderBy( a => a.Order );

            foreach ( var account in accounts.ToList() )
            {
                ListItem checkbox = new ListItem(account.Name, account.Id.ToString(), true);
                checkbox.Selected = true;

                cblAccounts.Items.Add( checkbox );
            }
        }
        // checks the settings provided
        private bool CheckSettings()
        {
            nbBlockConfigErrors.Title = string.Empty;
            nbBlockConfigErrors.Text = string.Empty;

            // get list of selected accounts filtered by the current campus
            RockContext rockContext = new RockContext();
            FinancialAccountService accountService = new FinancialAccountService( rockContext );

            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "Accounts" ) ) )
            {
                Guid[] selectedAccounts = GetAttributeValue( "Accounts" ).Split( ',' ).Select( s => Guid.Parse( s ) ).ToArray(); ;

                var accounts = accountService.Queryable()
                                .Where( a => selectedAccounts.Contains( a.Guid ) );

                if ( this.CampusId != 0 )
                {
                    accounts = accounts.Where( a => a.CampusId.Value == this.CampusId || a.CampusId == null );
                }

                this.Accounts = new Dictionary<int, string>();

                foreach ( var account in accounts.OrderBy( a => a.Order ).ToList() )
                {
                    this.Accounts.Add( account.Id, account.PublicName );
                }
            }
            else
            {
                nbBlockConfigErrors.Heading = "No Accounts Configured";
                nbBlockConfigErrors.Text = "<p>There are currently no accounts configured.</p>";
                return false;
            }

            // hide cancel buttons if no homepage defined
            if ( string.IsNullOrWhiteSpace( GetAttributeValue( "Homepage" ) ) )
            {
                lbSearchCancel.Visible = false;
                lbGivingUnitSelectCancel.Visible = false;
                lbRegisterCancel.Visible = false;
                lbAccountEntryCancel.Visible = false;
                lbSwipeCancel.Visible = false;
            }

            // get anonymous person
            Person anonymousPerson = null;

            Guid anonymousPersonAliasGuid;

            if ( Guid.TryParse( GetAttributeValue( "AnonymousPerson" ), out anonymousPersonAliasGuid ) )
            {
                anonymousPerson = new PersonAliasService( rockContext ).Get(anonymousPersonAliasGuid ).Person;
            }

            if ( anonymousPerson != null )
            {
                this.AnonymousGiverPersonAliasId = anonymousPerson.PrimaryAliasId;
                lbGiveAnonymously.Visible = true;
            }
            else
            {
                lbGiveAnonymously.Visible = false;
            }

            _dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            if ( _dvcConnectionStatus == null )
            {
                nbBlockConfigErrors.Heading = "Invalid Connection Status";
                nbBlockConfigErrors.Text = "<p>The selected Connection Status setting does not exist.</p>";
                return false;
            }

            _dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );
            if ( _dvcRecordStatus == null )
            {
                nbBlockConfigErrors.Heading = "Invalid Record Status";
                nbBlockConfigErrors.Text = "<p>The selected Record Status setting does not exist.</p>";
                return false;
            }

            return true;
        }
        //
        // Swipe Panel Events
        //
        private void ProcessSwipe( string swipeData )
        {
            try
            {
                using ( var rockContext = new RockContext() )
                {
                    // create swipe object
                    SwipePaymentInfo swipeInfo = new SwipePaymentInfo( swipeData );
                    swipeInfo.Amount = this.Amounts.Sum( a => a.Value );

                    // if not anonymous then add contact info to the gateway transaction
                    if ( this.AnonymousGiverPersonAliasId != this.SelectedGivingUnit.PersonAliasId )
                    {
                        var giver = new PersonAliasService( rockContext ).Queryable( "Person, Person.PhoneNumbers" ).Where( p => p.Id == this.SelectedGivingUnit.PersonAliasId ).FirstOrDefault();
                        swipeInfo.FirstName = giver.Person.NickName;
                        swipeInfo.LastName = giver.Person.LastName;

                        if ( giver.Person.PhoneNumbers != null )
                        {
                            Guid homePhoneValueGuid = new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME );
                            var homephone = giver.Person.PhoneNumbers.Where( p => p.NumberTypeValue.Guid == homePhoneValueGuid ).FirstOrDefault();
                            if ( homephone != null )
                            {
                                swipeInfo.Phone = homephone.NumberFormatted;
                            }
                        }

                        var homeLocation = giver.Person.GetHomeLocation();

                        if ( homeLocation != null )
                        {
                            swipeInfo.Street1 = homeLocation.Street1;

                            if ( !string.IsNullOrWhiteSpace( homeLocation.Street2 ) )
                            {
                                swipeInfo.Street2 = homeLocation.Street2;
                            }

                            swipeInfo.City = homeLocation.City;
                            swipeInfo.State = homeLocation.State;
                            swipeInfo.PostalCode = homeLocation.PostalCode;
                        }

                    }

                    // add comment to the transation
                    swipeInfo.Comment1 = GetAttributeValue( "PaymentComment" );

                    // get gateway
                    FinancialGateway financialGateway = null;
                    GatewayComponent gateway = null;
                    Guid? gatewayGuid = GetAttributeValue( "CreditCardGateway" ).AsGuidOrNull();
                    if ( gatewayGuid.HasValue )
                    {
                        financialGateway = new FinancialGatewayService( rockContext ).Get( gatewayGuid.Value );
                        if ( financialGateway != null )
                        {
                            financialGateway.LoadAttributes( rockContext );
                        }
                        gateway = financialGateway.GetGatewayComponent();
                    }

                    if ( gateway != null )
                    {

                        string errorMessage = string.Empty;
                        var transaction = gateway.Charge( financialGateway, swipeInfo, out errorMessage );

                        if ( transaction != null )
                        {

                            var txnChanges = new List<string>();
                            txnChanges.Add( "Created Transaction (from kiosk)" );

                            _transactionCode = transaction.TransactionCode;
                            History.EvaluateChange( txnChanges, "Transaction Code", string.Empty, transaction.TransactionCode );

                            var personName = new PersonAliasService( rockContext )
                                .Queryable().AsNoTracking()
                                .Where( a => a.Id == this.SelectedGivingUnit.PersonAliasId )
                                .Select( a => a.Person.NickName + " " + a.Person.LastName )
                                .FirstOrDefault();

                            transaction.AuthorizedPersonAliasId = this.SelectedGivingUnit.PersonAliasId;
                            History.EvaluateChange( txnChanges, "Person", string.Empty, personName );

                            transaction.TransactionDateTime = RockDateTime.Now;
                            History.EvaluateChange( txnChanges, "Date/Time", null, transaction.TransactionDateTime );

                            transaction.FinancialGatewayId = financialGateway.Id;
                            History.EvaluateChange( txnChanges, "Gateway", string.Empty, financialGateway.Name );

                            var txnType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) );
                            transaction.TransactionTypeValueId = txnType.Id;
                            History.EvaluateChange( txnChanges, "Type", string.Empty, txnType.Value );

                            transaction.Summary = swipeInfo.Comment1;
                            History.EvaluateChange( txnChanges, "Transaction Code", string.Empty, transaction.Summary );

                            if ( transaction.FinancialPaymentDetail == null )
                            {
                                transaction.FinancialPaymentDetail = new FinancialPaymentDetail();
                            }
                            transaction.FinancialPaymentDetail.SetFromPaymentInfo( swipeInfo, gateway, rockContext, txnChanges );

                            Guid sourceGuid = Guid.Empty;
                            if ( Guid.TryParse( GetAttributeValue( "Source" ), out sourceGuid ) )
                            {
                                var source = DefinedValueCache.Read( sourceGuid );
                                if ( source != null )
                                {
                                    transaction.SourceTypeValueId = source.Id;
                                    History.EvaluateChange( txnChanges, "Source", string.Empty, source.Value );
                                }
                            }

                            foreach ( var accountAmount in this.Amounts.Where( a => a.Value > 0 ) )
                            {
                                var transactionDetail = new FinancialTransactionDetail();
                                transactionDetail.Amount = accountAmount.Value;
                                transactionDetail.AccountId = accountAmount.Key;
                                transaction.TransactionDetails.Add( transactionDetail );
                                var account = new FinancialAccountService( rockContext ).Get( accountAmount.Key );
                                if ( account != null )
                                {
                                    History.EvaluateChange( txnChanges, account.Name, 0.0M.FormatAsCurrency(), transactionDetail.Amount.FormatAsCurrency() );
                                }
                            }

                            var batchService = new FinancialBatchService( rockContext );

                            // Get the batch
                            var batch = batchService.Get(
                                GetAttributeValue( "BatchNamePrefix" ),
                                swipeInfo.CurrencyTypeValue,
                                swipeInfo.CreditCardTypeValue,
                                transaction.TransactionDateTime.Value,
                                financialGateway.GetBatchTimeOffset() );

                            var batchChanges = new List<string>();

                            if ( batch.Id == 0 )
                            {
                                batchChanges.Add( "Generated the batch" );
                                History.EvaluateChange( batchChanges, "Batch Name", string.Empty, batch.Name );
                                History.EvaluateChange( batchChanges, "Status", null, batch.Status );
                                History.EvaluateChange( batchChanges, "Start Date/Time", null, batch.BatchStartDateTime );
                                History.EvaluateChange( batchChanges, "End Date/Time", null, batch.BatchEndDateTime );
                            }

                            decimal newControlAmount = batch.ControlAmount + transaction.TotalAmount;
                            History.EvaluateChange( batchChanges, "Control Amount", batch.ControlAmount.FormatAsCurrency(), newControlAmount.FormatAsCurrency() );
                            batch.ControlAmount = newControlAmount;

                            transaction.BatchId = batch.Id;
                            batch.Transactions.Add( transaction );

                            rockContext.WrapTransaction( () =>
                            {

                                rockContext.SaveChanges();
                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof( FinancialBatch ),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                    batch.Id,
                                    batchChanges
                                );

                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof( FinancialBatch ),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    batch.Id,
                                    txnChanges,
                                    personName,
                                    typeof( FinancialTransaction ),
                                    transaction.Id
                                );
                            } );

                            // send receipt in one is configured and not giving anonymously
                            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "ReceiptEmail" ) ) && ( this.AnonymousGiverPersonAliasId != this.SelectedGivingUnit.PersonAliasId ) )
                            {
                                _receiptSent = true;

                                SendReceipt();
                            }

                            HidePanels();
                            ShowReceiptPanel();
                        }
                        else
                        {
                            lSwipeErrors.Text = String.Format( "<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", errorMessage );
                        }

                    }
                    else
                    {
                        lSwipeErrors.Text = "<div class='alert alert-danger'>Invalid gateway provided. Please provide a gateway. Transaction not processed.</div>";
                    }
                }
            }
            catch ( Exception ex )
            {
                lSwipeErrors.Text = String.Format( "<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", ex.Message );
            }
        }
        /// <summary>
        /// Processes the payments.
        /// </summary>
        /// <param name="gateway">The gateway.</param>
        /// <param name="batchNamePrefix">The batch name prefix.</param>
        /// <param name="payments">The payments.</param>
        /// <param name="batchUrlFormat">The batch URL format.</param>
        /// <returns></returns>
        public static string ProcessPayments( FinancialGateway gateway, string batchNamePrefix, List<Payment> payments, string batchUrlFormat = "" )
        {
            int totalPayments = 0;
            int totalAlreadyDownloaded = 0;
            int totalNoScheduledTransaction = 0;
            int totalAdded = 0;

            var batches = new List<FinancialBatch>();
            var batchSummary = new Dictionary<Guid, List<Payment>>();
            var initialControlAmounts = new Dictionary<Guid, decimal>();

            var allBatchChanges = new Dictionary<Guid, List<string>>();
            var allTxnChanges = new Dictionary<Guid, List<string>>();
            var txnPersonNames = new Dictionary<Guid, string>();

            using ( var rockContext = new RockContext() )
            {
                var accountService = new FinancialAccountService( rockContext );
                var txnService = new FinancialTransactionService( rockContext );
                var batchService = new FinancialBatchService( rockContext );
                var scheduledTxnService = new FinancialScheduledTransactionService( rockContext );

                var contributionTxnType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid() );

                var defaultAccount = accountService.Queryable()
                    .Where( a =>
                        a.IsActive &&
                        !a.ParentAccountId.HasValue &&
                        ( !a.StartDate.HasValue || a.StartDate.Value <= RockDateTime.Now ) &&
                        ( !a.EndDate.HasValue || a.EndDate.Value >= RockDateTime.Now )
                        )
                    .OrderBy( a => a.Order )
                    .FirstOrDefault();

                var batchTxnChanges = new Dictionary<Guid, List<string>>();
                var batchBatchChanges = new Dictionary<Guid, List<string>>();

                foreach ( var payment in payments.Where( p => p.Amount > 0.0M ) )
                {
                    totalPayments++;

                    // Only consider transactions that have not already been added
                    if ( txnService.GetByTransactionCode( payment.TransactionCode ) == null )
                    {
                        var scheduledTransaction = scheduledTxnService.GetByScheduleId( payment.GatewayScheduleId );
                        if ( scheduledTransaction != null )
                        {
                            scheduledTransaction.IsActive = payment.ScheduleActive;

                            var txnChanges = new List<string>();

                            var transaction = new FinancialTransaction();
                            transaction.FinancialPaymentDetail = new FinancialPaymentDetail();

                            transaction.Guid = Guid.NewGuid();
                            allTxnChanges.Add( transaction.Guid, txnChanges );
                            txnChanges.Add( "Created Transaction (Downloaded from Gateway)" );

                            transaction.TransactionCode = payment.TransactionCode;
                            History.EvaluateChange( txnChanges, "Transaction Code", string.Empty, transaction.TransactionCode );

                            transaction.TransactionDateTime = payment.TransactionDateTime;
                            History.EvaluateChange( txnChanges, "Date/Time", null, transaction.TransactionDateTime );

                            transaction.ScheduledTransactionId = scheduledTransaction.Id;

                            transaction.AuthorizedPersonAliasId = scheduledTransaction.AuthorizedPersonAliasId;
                            History.EvaluateChange( txnChanges, "Person", string.Empty, scheduledTransaction.AuthorizedPersonAlias.Person.FullName );
                            txnPersonNames.Add( transaction.Guid, scheduledTransaction.AuthorizedPersonAlias.Person.FullName );

                            transaction.FinancialGatewayId = gateway.Id;
                            History.EvaluateChange( txnChanges, "Gateway", string.Empty, gateway.Name );

                            transaction.TransactionTypeValueId = contributionTxnType.Id;
                            History.EvaluateChange( txnChanges, "Type", string.Empty, contributionTxnType.Value );

                            var currencyTypeValue = payment.CurrencyTypeValue;
                            var creditCardTypevalue = payment.CreditCardTypeValue;

                            if ( scheduledTransaction.FinancialPaymentDetail != null )
                            {
                                if ( currencyTypeValue == null && scheduledTransaction.FinancialPaymentDetail.CurrencyTypeValueId.HasValue )
                                {
                                    currencyTypeValue = DefinedValueCache.Read( scheduledTransaction.FinancialPaymentDetail.CurrencyTypeValueId.Value );
                                }

                                if ( creditCardTypevalue == null && scheduledTransaction.FinancialPaymentDetail.CreditCardTypeValueId.HasValue )
                                {
                                    creditCardTypevalue = DefinedValueCache.Read( scheduledTransaction.FinancialPaymentDetail.CreditCardTypeValueId.Value );
                                }

                                transaction.FinancialPaymentDetail.AccountNumberMasked = scheduledTransaction.FinancialPaymentDetail.AccountNumberMasked;
                                transaction.FinancialPaymentDetail.NameOnCardEncrypted = scheduledTransaction.FinancialPaymentDetail.NameOnCardEncrypted;
                                transaction.FinancialPaymentDetail.ExpirationMonthEncrypted = scheduledTransaction.FinancialPaymentDetail.ExpirationMonthEncrypted;
                                transaction.FinancialPaymentDetail.ExpirationYearEncrypted = scheduledTransaction.FinancialPaymentDetail.ExpirationYearEncrypted;
                            }

                            if ( currencyTypeValue != null )
                            {
                                transaction.FinancialPaymentDetail.CurrencyTypeValueId = currencyTypeValue.Id;
                                History.EvaluateChange( txnChanges, "Currency Type", string.Empty, currencyTypeValue.Value );
                            }
                            if ( creditCardTypevalue != null )
                            {
                                transaction.FinancialPaymentDetail.CreditCardTypeValueId = creditCardTypevalue.Id;
                                History.EvaluateChange( txnChanges, "Credit Card Type", string.Empty, creditCardTypevalue.Value );
                            }

                            //transaction.SourceTypeValueId = DefinedValueCache.Read( sourceGuid ).Id;

                            // Try to allocate the amount of the transaction based on the current scheduled transaction accounts
                            decimal remainingAmount = payment.Amount;
                            foreach ( var detail in scheduledTransaction.ScheduledTransactionDetails.Where( d => d.Amount != 0.0M ) )
                            {
                                var transactionDetail = new FinancialTransactionDetail();
                                transactionDetail.AccountId = detail.AccountId;

                                if ( detail.Amount <= remainingAmount )
                                {
                                    // If the configured amount for this account is less than or equal to the remaining
                                    // amount, allocate the configured amount
                                    transactionDetail.Amount = detail.Amount;
                                    remainingAmount -= detail.Amount;
                                }
                                else
                                {
                                    // If the configured amount is greater than the remaining amount, only allocate
                                    // the remaining amount
                                    transaction.Summary = "Note: Downloaded transaction amount was less than the configured allocation amounts for the Scheduled Transaction.";
                                    detail.Amount = remainingAmount;
                                    detail.Summary = "Note: The downloaded amount was not enough to apply the configured amount to this account.";
                                    remainingAmount = 0.0M;
                                }

                                transaction.TransactionDetails.Add( transactionDetail );

                                History.EvaluateChange( txnChanges, detail.Account.Name, 0.0M.ToString( "C2" ), transactionDetail.Amount.ToString( "C2" ) );
                                History.EvaluateChange( txnChanges, "Summary", string.Empty, transactionDetail.Summary );

                                if ( remainingAmount <= 0.0M )
                                {
                                    // If there's no amount left, break out of details
                                    break;
                                }
                            }

                            // If there's still amount left after allocating based on current config, add the remainder
                            // to the account that was configured for the most amount
                            if ( remainingAmount > 0.0M )
                            {
                                transaction.Summary = "Note: Downloaded transaction amount was greater than the configured allocation amounts for the Scheduled Transaction.";
                                var transactionDetail = transaction.TransactionDetails
                                    .OrderByDescending( d => d.Amount )
                                    .First();
                                if ( transactionDetail == null && defaultAccount != null )
                                {
                                    transactionDetail = new FinancialTransactionDetail();
                                    transactionDetail.AccountId = defaultAccount.Id;
                                }
                                if ( transactionDetail != null )
                                {
                                    transactionDetail.Amount += remainingAmount;
                                    transactionDetail.Summary = "Note: Extra amount was applied to this account.";
                                }

                                History.EvaluateChange( txnChanges, defaultAccount.Name, 0.0M.ToString( "C2" ), transactionDetail.Amount.ToString( "C2" ) );
                                History.EvaluateChange( txnChanges, "Summary", string.Empty, transactionDetail.Summary );
                            }

                            // Get the batch
                            var batch = batchService.Get(
                                batchNamePrefix,
                                currencyTypeValue,
                                creditCardTypevalue,
                                transaction.TransactionDateTime.Value,
                                gateway.GetBatchTimeOffset(),
                                batches );

                            var batchChanges = new List<string>();
                            if ( batch.Id != 0 )
                            {
                                initialControlAmounts.AddOrIgnore( batch.Guid, batch.ControlAmount );
                            }
                            batch.ControlAmount += transaction.TotalAmount;

                            batch.Transactions.Add( transaction );

                            // Add summary
                            if ( !batchSummary.ContainsKey( batch.Guid ) )
                            {
                                batchSummary.Add( batch.Guid, new List<Payment>() );
                            }
                            batchSummary[batch.Guid].Add( payment );

                            totalAdded++;
                        }
                        else
                        {
                            totalNoScheduledTransaction++;
                        }
                    }
                    else
                    {
                        totalAlreadyDownloaded++;
                    }
                }

                foreach ( var batch in batches )
                {
                    var batchChanges = new List<string>();
                    allBatchChanges.Add( batch.Guid, batchChanges );

                    if ( batch.Id == 0 )
                    {
                        batchChanges.Add( "Generated the batch" );
                        History.EvaluateChange( batchChanges, "Batch Name", string.Empty, batch.Name );
                        History.EvaluateChange( batchChanges, "Status", null, batch.Status );
                        History.EvaluateChange( batchChanges, "Start Date/Time", null, batch.BatchStartDateTime );
                        History.EvaluateChange( batchChanges, "End Date/Time", null, batch.BatchEndDateTime );
                    }

                    if ( initialControlAmounts.ContainsKey( batch.Guid ) )
                    {
                        History.EvaluateChange( batchChanges, "Control Amount", initialControlAmounts[batch.Guid].ToString( "C2" ), batch.ControlAmount.ToString( "C2" ) );
                    }
                }

                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();

                    foreach ( var batch in batches )
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof( FinancialBatch ),
                            Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                            batch.Id,
                            allBatchChanges[batch.Guid]
                        );

                        foreach ( var transaction in batch.Transactions )
                        {
                            if ( allTxnChanges.ContainsKey( transaction.Guid ) )
                            {
                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof( FinancialBatch ),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    batch.Id,
                                    allTxnChanges[transaction.Guid],
                                    txnPersonNames[transaction.Guid],
                                    typeof( FinancialTransaction ),
                                    transaction.Id
                                );
                            }
                        }
                    }

                    rockContext.SaveChanges();
                } );
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat( "<li>{0} {1} downloaded.</li>", totalPayments.ToString( "N0" ),
                ( totalPayments == 1 ? "payment" : "payments" ) );

            if ( totalAlreadyDownloaded > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} previously downloaded and {2} already been added.</li>", totalAlreadyDownloaded.ToString( "N0" ),
                    ( totalAlreadyDownloaded == 1 ? "payment was" : "payments were" ),
                    ( totalAlreadyDownloaded == 1 ? "has" : "have" ) );
            }

            if ( totalNoScheduledTransaction > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} could not be matched to an existing scheduled payment profile.</li>", totalNoScheduledTransaction.ToString( "N0" ),
                    ( totalNoScheduledTransaction == 1 ? "payment" : "payments" ) );
            }

            sb.AppendFormat( "<li>{0} {1} successfully added.</li>", totalAdded.ToString( "N0" ),
                ( totalAdded == 1 ? "payment was" : "payments were" ) );

            foreach ( var batchItem in batchSummary )
            {
                int items = batchItem.Value.Count;
                if (items > 0)
                {
                    var batch = batches
                        .Where( b => b.Guid.Equals( batchItem.Key ) )
                        .FirstOrDefault();

                    string batchName = string.Format("'{0} ({1})'", batch.Name, batch.BatchStartDateTime.Value.ToString("d"));
                    if ( !string.IsNullOrWhiteSpace( batchUrlFormat ) )
                    {
                        batchName = string.Format( "<a href='{0}'>{1}</a>", string.Format( batchUrlFormat, batch.Id ), batchName );
                    }

                    decimal sum = batchItem.Value.Select( p => p.Amount ).Sum();

                    string summaryformat = items == 1 ?
                        "<li>{0} transaction of {1} was added to the {2} batch.</li>" :
                        "<li>{0} transactions totaling {1} were added to the {2} batch</li>";

                    sb.AppendFormat( summaryformat, items.ToString( "N0" ), sum.ToString( "C2" ), batchName );
                }
            }

            return sb.ToString();
        }
Exemple #46
0
        /// <summary>
        /// Gets the accounts.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private IQueryable<FinancialAccount> GetAccounts( RockContext rockContext )
        {
            var accountService = new FinancialAccountService( rockContext );
            SortProperty sortProperty = rGridAccount.SortProperty;
            var accountQuery = accountService.Queryable();

            string accountNameFilter = rAccountFilter.GetUserPreference( "Account Name" );
            if ( !string.IsNullOrEmpty( accountNameFilter ) )
            {
                accountQuery = accountQuery.Where( account => account.Name.Contains( accountNameFilter ) );
            }

            int campusId = int.MinValue;
            if ( int.TryParse( rAccountFilter.GetUserPreference( "Campus" ), out campusId ) )
            {
                accountQuery = accountQuery.Where( account => account.Campus.Id == campusId );
            }

            string publicFilter = rAccountFilter.GetUserPreference( "Public" );
            if ( !string.IsNullOrWhiteSpace( publicFilter ) )
            {
                accountQuery = accountQuery.Where( account => ( account.IsPublic ?? false ) == ( publicFilter == "Yes" ) );
            }

            string activeFilter = rAccountFilter.GetUserPreference( "Active" );
            if ( !string.IsNullOrWhiteSpace( activeFilter ) )
            {
                accountQuery = accountQuery.Where( account => account.IsActive == ( activeFilter == "Yes" ) );
            }

            string taxDeductibleFilter = rAccountFilter.GetUserPreference( "Tax Deductible" );
            if ( !string.IsNullOrWhiteSpace( taxDeductibleFilter ) )
            {
                accountQuery = accountQuery.Where( account => account.IsTaxDeductible == ( taxDeductibleFilter == "Yes" ) );
            }

            accountQuery = accountQuery.OrderBy( a => a.Order );

            return accountQuery;
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid( bool isExporting = false )
        {
            _currencyTypes = new Dictionary<int,string>();
            _creditCardTypes = new Dictionary<int,string>();

            // If configured for a registration and registration is null, return
            int registrationEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Registration ) ).Id;
            if ( ContextTypesRequired.Any( e => e.Id == registrationEntityTypeId ) && _registration == null )
            {
                return;
            }

            // If configured for a person and person is null, return
            int personEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            if ( ContextTypesRequired.Any( e => e.Id == personEntityTypeId ) && _person == null )
            {
                return;
            }

            // If configured for a batch and batch is null, return
            int batchEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialBatch" ).Id;
            if ( ContextTypesRequired.Any( e => e.Id == batchEntityTypeId ) && _batch == null )
            {
                return;
            }

            // If configured for a batch and batch is null, return
            int scheduledTxnEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialScheduledTransaction" ).Id;
            if ( ContextTypesRequired.Any( e => e.Id == scheduledTxnEntityTypeId ) && _scheduledTxn == null )
            {
                return;
            }

            // Qry
            var rockContext = new RockContext();
            var qry = new FinancialTransactionService( rockContext ).Queryable();

            // Transaction Types
            var transactionTypeValueIdList = GetAttributeValue( "TransactionTypes" ).SplitDelimitedValues().AsGuidList().Select( a => DefinedValueCache.Read( a ) ).Where( a => a != null ).Select( a => a.Id ).ToList();

            if ( transactionTypeValueIdList.Any() )
            {
                qry = qry.Where( t => transactionTypeValueIdList.Contains( t.TransactionTypeValueId ) );
            }

            // Set up the selection filter
            if ( _batch != null )
            {
                // If transactions are for a batch, the filter is hidden so only check the batch id
                qry = qry.Where( t => t.BatchId.HasValue && t.BatchId.Value == _batch.Id );

                // If the batch is closed, do not allow any editing of the transactions
                if ( _batch.Status != BatchStatus.Closed && _canEdit )
                {
                    gTransactions.IsDeleteEnabled = _canEdit;
                }
                else
                {
                    gTransactions.IsDeleteEnabled = false;
                }
            }
            else if ( _scheduledTxn != null )
            {
                // If transactions are for a batch, the filter is hidden so only check the batch id
                qry = qry.Where( t => t.ScheduledTransactionId.HasValue && t.ScheduledTransactionId.Value == _scheduledTxn.Id );

                gTransactions.IsDeleteEnabled = false;
            }
            else if ( _registration != null )
            {
                qry = qry
                    .Where( t => t.TransactionDetails
                        .Any( d =>
                            d.EntityTypeId.HasValue &&
                            d.EntityTypeId.Value == registrationEntityTypeId &&
                            d.EntityId.HasValue &&
                            d.EntityId.Value == _registration.Id ) );

                gTransactions.IsDeleteEnabled = false;
            }
            else    // Person
            {
                // otherwise set the selection based on filter settings
                if ( _person != null )
                {
                    // get the transactions for the person or all the members in the person's giving group (Family)
                    qry = qry.Where( t => t.AuthorizedPersonAlias.Person.GivingId == _person.GivingId );
                }

                // Date Range
                var drp = new DateRangePicker();
                drp.DelimitedValues = gfTransactions.GetUserPreference( "Date Range" );
                if ( drp.LowerValue.HasValue )
                {
                    qry = qry.Where( t => t.TransactionDateTime >= drp.LowerValue.Value );
                }

                if ( drp.UpperValue.HasValue )
                {
                    DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                    qry = qry.Where( t => t.TransactionDateTime < upperDate );
                }

                // Amount Range
                var nre = new NumberRangeEditor();
                nre.DelimitedValues = gfTransactions.GetUserPreference( "Amount Range" );
                if ( nre.LowerValue.HasValue )
                {
                    qry = qry.Where( t => t.TransactionDetails.Sum( d => d.Amount ) >= nre.LowerValue.Value );
                }

                if ( nre.UpperValue.HasValue )
                {
                    qry = qry.Where( t => t.TransactionDetails.Sum( d => d.Amount ) <= nre.UpperValue.Value );
                }

                // Transaction Code
                string transactionCode = gfTransactions.GetUserPreference( "Transaction Code" );
                if ( !string.IsNullOrWhiteSpace( transactionCode ) )
                {
                    qry = qry.Where( t => t.TransactionCode == transactionCode.Trim() );
                }

                // Account Id
                var accountIds = (gfTransactions.GetUserPreference( "Account" ) ?? "").SplitDelimitedValues().AsIntegerList().Where( a => a > 0 ).ToList();
                {
                    if ( accountIds.Any() )
                    {
                        qry = qry.Where( t => t.TransactionDetails.Any( d => accountIds.Contains( d.AccountId ) || (d.Account.ParentAccountId.HasValue && accountIds.Contains(d.Account.ParentAccountId.Value) ) ) );
                    }
                }

                // Transaction Type
                int transactionTypeId = int.MinValue;
                if ( int.TryParse( gfTransactions.GetUserPreference( "Transaction Type" ), out transactionTypeId ) )
                {
                    qry = qry.Where( t => t.TransactionTypeValueId == transactionTypeId );
                }

                // Currency Type
                int currencyTypeId = int.MinValue;
                if ( int.TryParse( gfTransactions.GetUserPreference( "Currency Type" ), out currencyTypeId ) )
                {
                    qry = qry.Where( t => t.FinancialPaymentDetail != null && t.FinancialPaymentDetail.CurrencyTypeValueId == currencyTypeId );
                }

                // Credit Card Type
                int creditCardTypeId = int.MinValue;
                if ( int.TryParse( gfTransactions.GetUserPreference( "Credit Card Type" ), out creditCardTypeId ) )
                {
                    qry = qry.Where( t => t.FinancialPaymentDetail != null && t.FinancialPaymentDetail.CreditCardTypeValueId == creditCardTypeId );
                }

                // Source Type
                int sourceTypeId = int.MinValue;
                if ( int.TryParse( gfTransactions.GetUserPreference( "Source Type" ), out sourceTypeId ) )
                {
                    qry = qry.Where( t => t.SourceTypeValueId == sourceTypeId );
                }

                // Campus
                if ( this.ContextEntity() == null )
                {
                    var campus = CampusCache.Read( gfTransactions.GetUserPreference( "Campus" ).AsInteger() );
                    if ( campus != null )
                    {
                        qry = qry.Where( b => b.Batch != null && b.Batch.CampusId == campus.Id );
                    }
                }
            }

            SortProperty sortProperty = gTransactions.SortProperty;
            if ( sortProperty != null )
            {
                if ( sortProperty.Property == "TotalAmount" )
                {
                    if ( sortProperty.Direction == SortDirection.Ascending )
                    {
                        qry = qry.OrderBy( t => t.TransactionDetails.Sum( d => (decimal?)d.Amount ) ?? 0.00M );
                    }
                    else
                    {
                        qry = qry.OrderByDescending( t => t.TransactionDetails.Sum( d => (decimal?)d.Amount ) ?? 0.0M );
                    }
                }
                else
                {
                    qry = qry.Sort( sortProperty );
                }
            }
            else
            {
                // Default sort by Id if the transations are seen via the batch,
                // otherwise sort by descending date time.
                if ( ContextTypesRequired.Any( e => e.Id == batchEntityTypeId ) )
                {
                    qry = qry.OrderBy( t => t.Id );
                }
                else
                {
                    qry = qry.OrderByDescending( t => t.TransactionDateTime ).ThenByDescending( t => t.Id );
                }
            }

            var lTransactionImageField = gTransactions.ColumnsOfType<RockLiteralField>().FirstOrDefault( a => a.ID == "lTransactionImage" );
            var summaryField = gTransactions.ColumnsOfType<RockBoundField>().FirstOrDefault( a => a.DataField == "Summary" );
            var showImages = bddlOptions.SelectedValue.AsIntegerOrNull() == 1;
            if ( lTransactionImageField != null)
            {
                lTransactionImageField.Visible = showImages;
            }

            if ( summaryField != null )
            {
                summaryField.Visible = !showImages;
            }

            if ( showImages )
            {
                qry = qry.Include( a => a.Images );
            }

            _isExporting = isExporting;

            gTransactions.SetLinqDataSource( qry.AsNoTracking() );
            gTransactions.DataBind();

            _isExporting = false;

            if ( _batch == null &&
                _scheduledTxn == null &&
                _registration == null &&
                _person == null )
            {
                pnlSummary.Visible = true;

                // No context - show account summary
                var qryTransactionDetails = qry.SelectMany( a => a.TransactionDetails );
                var qryFinancialAccount = new FinancialAccountService( rockContext ).Queryable();
                var accountSummaryQry = qryTransactionDetails.GroupBy( a => a.AccountId ).Select( a => new
                {
                    AccountId = a.Key,
                    TotalAmount = (decimal?)a.Sum( d => d.Amount )
                } ).Join( qryFinancialAccount, k1 => k1.AccountId, k2 => k2.Id, ( td, fa ) => new { td.TotalAmount, fa.Name, fa.Order } )
                .OrderBy( a => a.Order );

                var summaryList = accountSummaryQry.ToList();
                var grandTotalAmount = ( summaryList.Count > 0 ) ? summaryList.Sum( a => a.TotalAmount ?? 0 ) : 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>
        /// Handles the filter display for each saved user value
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void gfTransactions_DisplayFilterValue( object sender, Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs e )
        {
            switch ( e.Key )
            {
                case "Row Limit":
                    // row limit filter was removed, so hide it just in case
                    e.Value = null;
                    break;

                case "Date Range":
                    e.Value = DateRangePicker.FormatDelimitedValues( e.Value );
                    break;

                case "Amount Range":
                    e.Value = NumberRangeEditor.FormatDelimitedValues( e.Value, "N2" );
                    break;

                case "Account":

                    var accountIds = e.Value.SplitDelimitedValues().AsIntegerList().Where(a => a > 0 ).ToList();
                    if ( accountIds.Any())
                    {
                        var service = new FinancialAccountService( new RockContext() );
                        var accountNames = service.GetByIds( accountIds ).OrderBy( a => a.Order ).OrderBy( a => a.Name ).Select( a => a.Name ).ToList().AsDelimited( ", ", " or " );
                        e.Value = accountNames;
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }

                    break;

                case "Transaction Type":
                case "Currency Type":
                case "Credit Card Type":
                case "Source Type":

                    int definedValueId = 0;
                    if ( int.TryParse( e.Value, out definedValueId ) )
                    {
                        var definedValue = DefinedValueCache.Read( definedValueId );
                        if ( definedValue != null )
                        {
                            e.Value = definedValue.Value;
                        }
                    }

                    break;

                case "Campus":
                    var campus = CampusCache.Read( e.Value.AsInteger() );
                    if ( campus != null )
                    {
                        e.Value = campus.Name;
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }

                    break;
            }
        }
        /// <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 )
        {
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 3 )
            {
                var accountPicker = controls[0] as AccountPicker;
                var dateRangePicker = controls[1] as DateRangePicker;

                dateRangePicker.LowerValue = selectionValues[0].AsDateTime();
                dateRangePicker.UpperValue = selectionValues[1].AsDateTime();

                var accountGuids = selectionValues[2].Split( ',' ).Select( a => a.AsGuid() ).ToList();
                var accounts = new FinancialAccountService( new RockContext() ).GetByGuids( accountGuids );
                if ( accounts != null && accounts.Any() )
                {
                    accountPicker.SetValues( accounts );
                }
            }
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection( Type entityType, Control[] controls )
        {
            var accountIdList = ( controls[0] as AccountPicker ).SelectedValuesAsInt().ToList();
            string accountGuids = string.Empty;
            var accounts = new FinancialAccountService( new RockContext() ).GetByIds( accountIdList );
            if ( accounts != null && accounts.Any() )
            {
                accountGuids = accounts.Select( a => a.Guid ).ToList().AsDelimited( "," );
            }

            DateRangePicker dateRangePicker = controls[1] as DateRangePicker;
            return string.Format( "{0}|{1}|{2}", dateRangePicker.LowerValue, dateRangePicker.UpperValue, accountGuids );
        }
        /// <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>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection( Type entityType, string selection )
        {
            string result = "First Contribution Date";
            string[] selectionValues = selection.Split( '|' );

            if ( selectionValues.Length >= 3 )
            {
                DateTime startDate = selectionValues[0].AsDateTime() ?? DateTime.MinValue;
                DateTime endDate = selectionValues[1].AsDateTime() ?? DateTime.MaxValue;
                string accountNames = string.Empty;
                var accountGuids = selectionValues[1].Split( ',' ).Select( a => a.AsGuid() ).ToList();
                accountNames = new FinancialAccountService( new RockContext() ).GetByGuids( accountGuids ).Select( a => a.Name ).ToList().AsDelimited( "," );

                result = string.Format(
                    "First contribution date {0} between {1} and {2}",
                    !string.IsNullOrWhiteSpace( accountNames ) ? " to accounts:" + accountNames : string.Empty,
                    startDate.ToShortDateString(),
                    endDate.ToShortDateString() );
            }

            return result;
        }
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            drpDates.DelimitedValues = gfTransactions.GetUserPreference( "Date Range" );
            nreAmount.DelimitedValues = gfTransactions.GetUserPreference( "Amount Range" );
            tbTransactionCode.Text = gfTransactions.GetUserPreference( "Transaction Code" );

            apAccount.DisplayActiveOnly = GetAttributeValue( "ActiveAccountsOnlyFilter" ).AsBoolean();

            var accountIds = ( gfTransactions.GetUserPreference( "Account" ) ?? "" ).SplitDelimitedValues().AsIntegerList().Where( a => a > 0 ).ToList();
            if ( accountIds.Any() )
            {
                var service = new FinancialAccountService( new RockContext() );
                var accounts = service.GetByIds( accountIds ).OrderBy( a => a.Order ).OrderBy( a => a.Name ).ToList();
                apAccount.SetValues(accounts);
            }
            else
            {
                apAccount.SetValue( 0 );
            }

            BindDefinedTypeDropdown( ddlTransactionType, new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_TYPE ), "Transaction Type" );
            BindDefinedTypeDropdown( ddlCurrencyType, new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE ), "Currency Type" );
            BindDefinedTypeDropdown( ddlCreditCardType, new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE ), "Credit Card Type" );
            BindDefinedTypeDropdown( ddlSourceType, new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_SOURCE_TYPE ), "Source Type" );

            if ( this.ContextEntity() == null )
            {
                var campusi = CampusCache.All();
                campCampus.Campuses = campusi;
                campCampus.Visible = campusi.Any();
                campCampus.SetValue( gfTransactions.GetUserPreference( "Campus" ) );
            }
            else
            {
                campCampus.Visible = false;
            }
        }
Exemple #54
0
        /// <summary>
        /// Handles the SaveClick event of the mdAccountsPersonalFilter control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void mdAccountsPersonalFilter_SaveClick( object sender, EventArgs e )
        {
            var selectedAccountIdList = apPersonalAccounts.SelectedValuesAsInt().ToList();
            var selectedAccountGuidList = new FinancialAccountService( new RockContext() ).GetByIds( selectedAccountIdList ).Select( a => a.Guid ).ToList();

            string keyPrefix = string.Format( "transaction-matching-{0}-", this.BlockId );
            this.SetUserPreference( keyPrefix + "account-list", selectedAccountGuidList.AsDelimited( "," ) );

            mdAccountsPersonalFilter.Hide();
            LoadDropDowns();
        }
        /// <summary>
        /// Loads the accounts.
        /// </summary>
        private void LoadAccounts()
        {
            var rockContext = new RockContext();
            FinancialAccountService accountService = new FinancialAccountService( rockContext );

            List<Guid> selectedAccounts = new List<Guid>();

            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "Accounts" ) ) )
            {
                selectedAccounts = GetAttributeValue( "Accounts" ).Split( ',' ).AsGuidList();
            }

            var accountList = accountService.Queryable()
                                .Where( a => selectedAccounts.Contains( a.Guid ) )
                                .OrderBy( a => a.Order )
                                .Select( a => new
                                {
                                    a.Id,
                                    a.PublicName
                                } ).ToList();

            if ( accountList.Any() )
            {
                foreach ( var account in accountList )
                {
                    ListItem checkbox = new ListItem( account.PublicName, account.Id.ToString(), true );
                    checkbox.Selected = true;

                    cblAccounts.Items.Add( checkbox );
                }
            }
            else
            {
                cblAccounts.Items.Clear();
            }

            // only show Account Checkbox list if there are accounts are configured for the block
            cblAccounts.Visible = accountList.Any();
        }
Exemple #56
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        private void ShowDetail()
        {
            int? RegistrationInstanceId = PageParameter( "RegistrationInstanceId" ).AsIntegerOrNull();
            int? parentTemplateId = PageParameter( "RegistrationTemplateId" ).AsIntegerOrNull();

            if ( !RegistrationInstanceId.HasValue )
            {
                pnlDetails.Visible = false;
                return;
            }

            using ( var rockContext = new RockContext() )
            {
                RegistrationInstance registrationInstance = null;
                if ( RegistrationInstanceId.HasValue )
                {
                    registrationInstance = GetRegistrationInstance( RegistrationInstanceId.Value, rockContext );
                }

                if ( registrationInstance == null )
                {
                    registrationInstance = new RegistrationInstance();
                    registrationInstance.Id = 0;
                    registrationInstance.IsActive = true;
                    registrationInstance.RegistrationTemplateId = parentTemplateId ?? 0;

                    Guid? accountGuid = GetAttributeValue( "DefaultAccount").AsGuidOrNull();
                    if ( accountGuid.HasValue )
                    {
                        var account = new FinancialAccountService( rockContext ).Get( accountGuid.Value );
                        registrationInstance.AccountId = account != null ? account.Id : 0;
                    }
                }

                if ( registrationInstance.RegistrationTemplate == null && registrationInstance.RegistrationTemplateId > 0 )
                {
                    registrationInstance.RegistrationTemplate = new RegistrationTemplateService( rockContext )
                        .Get( registrationInstance.RegistrationTemplateId );
                }

                hlType.Visible = registrationInstance.RegistrationTemplate != null;
                hlType.Text = registrationInstance.RegistrationTemplate != null ? registrationInstance.RegistrationTemplate.Name : string.Empty;

                lWizardTemplateName.Text = hlType.Text;

                pnlDetails.Visible = true;
                hfRegistrationInstanceId.Value = registrationInstance.Id.ToString();
                SetHasPayments( registrationInstance.Id, rockContext );

                // render UI based on Authorized
                bool readOnly = false;

                nbEditModeMessage.Text = string.Empty;

                // User must have 'Edit' rights to block, or 'Administrate' rights to instance
                if ( !UserCanEdit && !registrationInstance.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ) )
                {
                    readOnly = true;
                    nbEditModeMessage.Heading = "Information";
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( RegistrationInstance.FriendlyTypeName );
                }

                if ( readOnly )
                {
                    btnEdit.Visible = false;
                    ShowReadonlyDetails( registrationInstance );
                }
                else
                {
                    btnEdit.Visible = true;

                    if ( registrationInstance.Id > 0 )
                    {
                        ShowReadonlyDetails( registrationInstance );
                    }
                    else
                    {
                        ShowEditDetails( registrationInstance, rockContext );
                    }
                }

                LoadRegistrantFormFields( registrationInstance );
                BindRegistrationsFilter();
                BindRegistrantsFilter();
                BindLinkagesFilter();
                AddDynamicRegistrantControls();
            }
        }
Exemple #57
0
        /// <summary>
        /// Handles the Click event of the btnFilter control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnFilter_Click( object sender, EventArgs e )
        {
            string keyPrefix = string.Format( "transaction-matching-{0}-", this.BlockId );
            var personalAccountGuidList = ( this.GetUserPreference( keyPrefix + "account-list" ) ?? string.Empty ).SplitDelimitedValues().Select( a => a.AsGuid() ).ToList();
            var personalAccountList = new FinancialAccountService( new RockContext() ).GetByGuids( personalAccountGuidList ).ToList();

            apPersonalAccounts.SetValues( personalAccountList );

            mdAccountsPersonalFilter.Show();
        }
Exemple #58
0
        /// <summary>
        /// Handles the Delete event of the rGridAccount control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void rGridAccount_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var accountService = new FinancialAccountService( rockContext );
            var account = accountService.Get( e.RowKeyId );
            if ( account != null )
            {
                string errorMessage;
                if ( !accountService.CanDelete( account, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                accountService.Delete( account );
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <summary>
        /// Processes the payments.
        /// </summary>
        /// <param name="gateway">The gateway.</param>
        /// <param name="batchNamePrefix">The batch name prefix.</param>
        /// <param name="payments">The payments.</param>
        /// <param name="batchUrlFormat">The batch URL format.</param>
        /// <param name="receiptEmail">The receipt email.</param>
        /// <returns></returns>
        public static string ProcessPayments( FinancialGateway gateway, string batchNamePrefix, List<Payment> payments, string batchUrlFormat = "", Guid? receiptEmail = null )
        {
            int totalPayments = 0;
            int totalAlreadyDownloaded = 0;
            int totalNoScheduledTransaction = 0;
            int totalAdded = 0;
            int totalReversals = 0;
            int totalStatusChanges = 0;

            var batches = new List<FinancialBatch>();
            var batchSummary = new Dictionary<Guid, List<Decimal>>();
            var initialControlAmounts = new Dictionary<Guid, decimal>();

            var txnPersonNames = new Dictionary<Guid, string>();

            var gatewayComponent = gateway.GetGatewayComponent();

            var newTransactions = new List<FinancialTransaction>();

            using ( var rockContext = new RockContext() )
            {
                var accountService = new FinancialAccountService( rockContext );
                var txnService = new FinancialTransactionService( rockContext );
                var batchService = new FinancialBatchService( rockContext );
                var scheduledTxnService = new FinancialScheduledTransactionService( rockContext );

                var contributionTxnType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid() );

                var defaultAccount = accountService.Queryable()
                    .Where( a =>
                        a.IsActive &&
                        !a.ParentAccountId.HasValue &&
                        ( !a.StartDate.HasValue || a.StartDate.Value <= RockDateTime.Now ) &&
                        ( !a.EndDate.HasValue || a.EndDate.Value >= RockDateTime.Now )
                        )
                    .OrderBy( a => a.Order )
                    .FirstOrDefault();

                var batchTxnChanges = new Dictionary<Guid, List<string>>();
                var batchBatchChanges = new Dictionary<Guid, List<string>>();
                var scheduledTransactionIds = new List<int>();

                foreach ( var payment in payments.Where( p => p.Amount > 0.0M ) )
                {
                    totalPayments++;

                    var scheduledTransaction = scheduledTxnService.GetByScheduleId( payment.GatewayScheduleId );
                    if ( scheduledTransaction != null )
                    {
                        // Find existing payments with same transaction code
                        var txns = txnService
                            .Queryable( "TransactionDetails" )
                            .Where( t => t.TransactionCode == payment.TransactionCode )
                            .ToList();

                        // Calculate whether a transaction needs to be added
                        var txnAmount = CalculateTransactionAmount( payment, txns );
                        if ( txnAmount != 0.0M )
                        {
                            scheduledTransactionIds.Add( scheduledTransaction.Id );
                            if ( payment.ScheduleActive.HasValue )
                            {
                                scheduledTransaction.IsActive = payment.ScheduleActive.Value;
                            }

                            var transaction = new FinancialTransaction();
                            transaction.FinancialPaymentDetail = new FinancialPaymentDetail();

                            transaction.Guid = Guid.NewGuid();
                            transaction.TransactionCode = payment.TransactionCode;
                            transaction.TransactionDateTime = payment.TransactionDateTime;
                            transaction.Status = payment.Status;
                            transaction.StatusMessage = payment.StatusMessage;
                            transaction.ScheduledTransactionId = scheduledTransaction.Id;
                            transaction.AuthorizedPersonAliasId = scheduledTransaction.AuthorizedPersonAliasId;
                            transaction.SourceTypeValueId = scheduledTransaction.SourceTypeValueId;
                            txnPersonNames.Add( transaction.Guid, scheduledTransaction.AuthorizedPersonAlias.Person.FullName );
                            transaction.FinancialGatewayId = gateway.Id;
                            transaction.TransactionTypeValueId = contributionTxnType.Id;

                            if ( txnAmount < 0.0M )
                            {
                                transaction.Summary = "Reversal for previous transaction that failed during processing." + Environment.NewLine;
                            }

                            var currencyTypeValue = payment.CurrencyTypeValue;
                            var creditCardTypevalue = payment.CreditCardTypeValue;

                            if ( scheduledTransaction.FinancialPaymentDetail != null )
                            {
                                if ( currencyTypeValue == null && scheduledTransaction.FinancialPaymentDetail.CurrencyTypeValueId.HasValue )
                                {
                                    currencyTypeValue = DefinedValueCache.Read( scheduledTransaction.FinancialPaymentDetail.CurrencyTypeValueId.Value );
                                }

                                if ( creditCardTypevalue == null && scheduledTransaction.FinancialPaymentDetail.CreditCardTypeValueId.HasValue )
                                {
                                    creditCardTypevalue = DefinedValueCache.Read( scheduledTransaction.FinancialPaymentDetail.CreditCardTypeValueId.Value );
                                }

                                transaction.FinancialPaymentDetail.AccountNumberMasked = scheduledTransaction.FinancialPaymentDetail.AccountNumberMasked;
                                transaction.FinancialPaymentDetail.NameOnCardEncrypted = scheduledTransaction.FinancialPaymentDetail.NameOnCardEncrypted;
                                transaction.FinancialPaymentDetail.ExpirationMonthEncrypted = scheduledTransaction.FinancialPaymentDetail.ExpirationMonthEncrypted;
                                transaction.FinancialPaymentDetail.ExpirationYearEncrypted = scheduledTransaction.FinancialPaymentDetail.ExpirationYearEncrypted;
                                transaction.FinancialPaymentDetail.BillingLocationId = scheduledTransaction.FinancialPaymentDetail.BillingLocationId;
                            }

                            if ( currencyTypeValue != null )
                            {
                                transaction.FinancialPaymentDetail.CurrencyTypeValueId = currencyTypeValue.Id;
                            }
                            if ( creditCardTypevalue != null )
                            {
                                transaction.FinancialPaymentDetail.CreditCardTypeValueId = creditCardTypevalue.Id;
                            }

                            // Try to allocate the amount of the transaction based on the current scheduled transaction accounts
                            decimal remainingAmount = Math.Abs( txnAmount );
                            foreach ( var detail in scheduledTransaction.ScheduledTransactionDetails.Where( d => d.Amount != 0.0M ) )
                            {
                                var transactionDetail = new FinancialTransactionDetail();
                                transactionDetail.AccountId = detail.AccountId;

                                if ( detail.Amount <= remainingAmount )
                                {
                                    // If the configured amount for this account is less than or equal to the remaining
                                    // amount, allocate the configured amount
                                    transactionDetail.Amount = detail.Amount;
                                    remainingAmount -= detail.Amount;
                                }
                                else
                                {
                                    // If the configured amount is greater than the remaining amount, only allocate
                                    // the remaining amount
                                    transaction.Summary += "Note: Downloaded transaction amount was less than the configured allocation amounts for the Scheduled Transaction.";
                                    transactionDetail.Amount = remainingAmount;
                                    transactionDetail.Summary = "Note: The downloaded amount was not enough to apply the configured amount to this account.";
                                    remainingAmount = 0.0M;
                                }

                                transaction.TransactionDetails.Add( transactionDetail );

                                if ( remainingAmount <= 0.0M )
                                {
                                    // If there's no amount left, break out of details
                                    break;
                                }
                            }

                            // If there's still amount left after allocating based on current config, add the remainder
                            // to the account that was configured for the most amount
                            if ( remainingAmount > 0.0M )
                            {
                                transaction.Summary += "Note: Downloaded transaction amount was greater than the configured allocation amounts for the Scheduled Transaction.";
                                var transactionDetail = transaction.TransactionDetails
                                    .OrderByDescending( d => d.Amount )
                                    .FirstOrDefault();
                                if ( transactionDetail == null && defaultAccount != null )
                                {
                                    transactionDetail = new FinancialTransactionDetail();
                                    transactionDetail.AccountId = defaultAccount.Id;
                                    transaction.TransactionDetails.Add( transactionDetail );
                                }
                                if ( transactionDetail != null )
                                {
                                    transactionDetail.Amount += remainingAmount;
                                    transactionDetail.Summary = "Note: Extra amount was applied to this account.";
                                }
                            }

                            // If the amount to apply was negative, update all details to be negative (absolute value was used when allocating to accounts)
                            if ( txnAmount < 0.0M )
                            {
                                foreach ( var txnDetail in transaction.TransactionDetails )
                                {
                                    txnDetail.Amount = 0 - txnDetail.Amount;
                                }
                            }

                            // Get the batch
                            var batch = batchService.Get(
                                batchNamePrefix,
                                currencyTypeValue,
                                creditCardTypevalue,
                                transaction.TransactionDateTime.Value,
                                gateway.GetBatchTimeOffset(),
                                batches );

                            var batchChanges = new List<string>();
                            if ( batch.Id != 0 )
                            {
                                initialControlAmounts.AddOrIgnore( batch.Guid, batch.ControlAmount );
                            }
                            batch.ControlAmount += transaction.TotalAmount;

                            batch.Transactions.Add( transaction );

                            if ( txnAmount > 0.0M && receiptEmail.HasValue )
                            {
                                newTransactions.Add( transaction );
                            }

                            // Add summary
                            if ( !batchSummary.ContainsKey( batch.Guid ) )
                            {
                                batchSummary.Add( batch.Guid, new List<Decimal>() );
                            }
                            batchSummary[batch.Guid].Add( txnAmount );

                            if ( txnAmount > 0.0M )
                            {
                                totalAdded++;
                            }
                            else
                            {
                                totalReversals++;
                            }
                        }
                        else
                        {
                            totalAlreadyDownloaded++;

                            foreach ( var txn in txns.Where( t => t.Status != payment.Status || t.StatusMessage != payment.StatusMessage ) )
                            {
                                txn.Status = payment.Status;
                                txn.StatusMessage = payment.StatusMessage;
                                totalStatusChanges++;
                            }
                        }
                    }
                    else
                    {
                        totalNoScheduledTransaction++;
                    }
                }

                rockContext.SaveChanges();

                // Queue a transaction to update the status of all affected scheduled transactions
                var updatePaymentStatusTxn = new Rock.Transactions.UpdatePaymentStatusTransaction( gateway.Id, scheduledTransactionIds );
                Rock.Transactions.RockQueue.TransactionQueue.Enqueue( updatePaymentStatusTxn );

                if ( receiptEmail.HasValue )
                {
                    // Queue a transaction to send receipts
                    var newTransactionIds = newTransactions.Select( t => t.Id ).ToList();
                    var sendPaymentReceiptsTxn = new Rock.Transactions.SendPaymentReceipts( receiptEmail.Value, newTransactionIds );
                    Rock.Transactions.RockQueue.TransactionQueue.Enqueue( sendPaymentReceiptsTxn );
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat( "<li>{0} {1} downloaded.</li>", totalPayments.ToString( "N0" ),
                ( totalPayments == 1 ? "payment" : "payments" ) );

            if ( totalAlreadyDownloaded > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} previously downloaded and {2} already been added.</li>", totalAlreadyDownloaded.ToString( "N0" ),
                    ( totalAlreadyDownloaded == 1 ? "payment was" : "payments were" ),
                    ( totalAlreadyDownloaded == 1 ? "has" : "have" ) );
            }

            if ( totalStatusChanges > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} previously downloaded but had a change of status.</li>", totalStatusChanges.ToString( "N0" ),
                ( totalStatusChanges == 1 ? "payment was" : "payments were" ) );
            }

            if ( totalNoScheduledTransaction > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} could not be matched to an existing scheduled payment profile.</li>", totalNoScheduledTransaction.ToString( "N0" ),
                    ( totalNoScheduledTransaction == 1 ? "payment" : "payments" ) );
            }

            sb.AppendFormat( "<li>{0} {1} successfully added.</li>", totalAdded.ToString( "N0" ),
                ( totalAdded == 1 ? "payment was" : "payments were" ) );

            if ( totalReversals > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} added as a reversal to a previous transaction.</li>", totalReversals.ToString( "N0" ),
                    ( totalReversals == 1 ? "payment was" : "payments were" ) );
            }

            if ( totalStatusChanges > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} previously downloaded but had a change of status.</li>", totalStatusChanges.ToString( "N0" ),
                    ( totalStatusChanges == 1 ? "payment was" : "payments were" ) );
            }

            foreach ( var batchItem in batchSummary )
            {
                int items = batchItem.Value.Count;
                if ( items > 0 )
                {
                    var batch = batches
                        .Where( b => b.Guid.Equals( batchItem.Key ) )
                        .FirstOrDefault();

                    string batchName = string.Format( "'{0} ({1})'", batch.Name, batch.BatchStartDateTime.Value.ToString( "d" ) );
                    if ( !string.IsNullOrWhiteSpace( batchUrlFormat ) )
                    {
                        batchName = string.Format( "<a href='{0}'>{1}</a>", string.Format( batchUrlFormat, batch.Id ), batchName );
                    }

                    decimal sum = batchItem.Value.Sum();

                    string summaryformat = items == 1 ?
                        "<li>{0} transaction of {1} was added to the {2} batch.</li>" :
                        "<li>{0} transactions totaling {1} were added to the {2} batch</li>";

                    sb.AppendFormat( summaryformat, items.ToString( "N0" ), sum.FormatAsCurrency(), batchName );
                }
            }

            return sb.ToString();
        }
Exemple #60
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var financialPledgeService = new FinancialPledgeService( rockContext );
            var financialAccountService = new FinancialAccountService( rockContext );
            var definedValueService = new DefinedValueService( rockContext );
            var person = FindPerson( rockContext );

            FinancialPledge financialPledge = new FinancialPledge();

            financialPledge.PersonAliasId = person.PrimaryAliasId;
            var financialAccount = financialAccountService.Get( GetAttributeValue( "Account" ).AsGuid() );
            if ( financialAccount != null )
            {
                financialPledge.AccountId = financialAccount.Id;
            }

            financialPledge.TotalAmount = tbTotalAmount.Text.AsDecimal();

            var pledgeFrequencySelection = DefinedValueCache.Read( bddlFrequency.SelectedValue.AsInteger() );
            if ( pledgeFrequencySelection != null )
            {
                financialPledge.PledgeFrequencyValueId = pledgeFrequencySelection.Id;
            }

            financialPledge.StartDate = drpDateRange.LowerValue ?? DateTime.MinValue;
            financialPledge.EndDate = drpDateRange.UpperValue ?? DateTime.MaxValue;

            if ( sender != btnConfirm )
            {
                var duplicatePledges = financialPledgeService.Queryable()
                    .Where( a => a.PersonAlias.PersonId == person.Id )
                    .Where( a => a.AccountId == financialPledge.AccountId )
                    .Where( a => a.StartDate == financialPledge.StartDate )
                    .Where( a => a.EndDate == financialPledge.EndDate ).ToList();

                if ( duplicatePledges.Any() )
                {
                    pnlAddPledge.Visible = false;
                    pnlConfirm.Visible = true;
                    nbDuplicatePledgeWarning.Text = "The following pledges have already been entered for you:";
                    nbDuplicatePledgeWarning.Text += "<ul>";
                    foreach ( var pledge in duplicatePledges.OrderBy( a => a.StartDate ).ThenBy( a => a.Account.Name ) )
                    {
                        nbDuplicatePledgeWarning.Text += string.Format( "<li>{0} {1} {2}</li>", pledge.Account, pledge.PledgeFrequencyValue, pledge.TotalAmount );
                    }

                    nbDuplicatePledgeWarning.Text += "</ul>";

                    return;
                }
            }

            financialPledgeService.Add( financialPledge );

            rockContext.SaveChanges();

            // populate account so that Liquid can access it
            financialPledge.Account = financialAccount;

            // populate PledgeFrequencyValue so that Liquid can access it
            financialPledge.PledgeFrequencyValue = definedValueService.Get( financialPledge.PledgeFrequencyValueId ?? 0 );

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
            mergeFields.Add( "Person", person );
            mergeFields.Add( "FinancialPledge", financialPledge );
            mergeFields.Add( "PledgeFrequency", pledgeFrequencySelection );
            mergeFields.Add( "Account", financialAccount );
            lReceipt.Text = GetAttributeValue( "ReceiptText" ).ResolveMergeFields( mergeFields );

            // Resolve any dynamic url references
            string appRoot = ResolveRockUrl( "~/" );
            string themeRoot = ResolveRockUrl( "~~/" );
            lReceipt.Text = lReceipt.Text.Replace( "~~/", themeRoot ).Replace( "~/", appRoot );

            // show liquid help for debug
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lReceipt.Text += mergeFields.lavaDebugInfo();
            }

            lReceipt.Visible = true;
            pnlAddPledge.Visible = false;
            pnlConfirm.Visible = false;

            // if a ConfirmationEmailTemplate is configured, send an email
            var confirmationEmailTemplateGuid = GetAttributeValue( "ConfirmationEmailTemplate" ).AsGuidOrNull();
            if ( confirmationEmailTemplateGuid.HasValue )
            {
                var recipients = new List<Rock.Communication.RecipientData>();

                // add person and the mergeObjects (same mergeobjects as receipt)
                recipients.Add( new Rock.Communication.RecipientData( person.Email, mergeFields ) );

                Rock.Communication.Email.Send( confirmationEmailTemplateGuid.Value, recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) );
            }
        }