Esempio n. 1
0
        protected void lbSaveAccounts_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var txn = GetTransaction(rockContext);
                {
                    decimal totalAmount = TransactionDetailsState.Select(d => d.Amount).ToList().Sum();
                    if (txn.TotalAmount != totalAmount)
                    {
                        nbError.Title   = "Incorrect Amount";
                        nbError.Text    = string.Format("<p>When updating account allocations, the total amount needs to remain the same as the original amount ({0}).</p>", txn.TotalAmount.FormatAsCurrency());
                        nbError.Visible = true;
                        return;
                    }

                    var txnDetailService = new FinancialScheduledTransactionDetailService(rockContext);
                    var accountService   = new FinancialAccountService(rockContext);

                    // Delete any transaction details that were removed
                    var txnDetailsInDB = txnDetailService.Queryable().Where(a => a.ScheduledTransactionId.Equals(txn.Id)).ToList();
                    var deletedDetails = from txnDetail in txnDetailsInDB
                                         where !TransactionDetailsState.Select(d => d.Guid).Contains(txnDetail.Guid)
                                         select txnDetail;

                    bool accountChanges = deletedDetails.Any();

                    deletedDetails.ToList().ForEach(txnDetail =>
                    {
                        txnDetailService.Delete(txnDetail);
                    });

                    var changeSummary = new StringBuilder();

                    // Save Transaction Details
                    foreach (var editorTxnDetail in TransactionDetailsState)
                    {
                        editorTxnDetail.Account = accountService.Get(editorTxnDetail.AccountId);

                        // Add or Update the activity type
                        var txnDetail = txn.ScheduledTransactionDetails.FirstOrDefault(d => d.Guid.Equals(editorTxnDetail.Guid));
                        if (txnDetail == null)
                        {
                            accountChanges = true;
                            txnDetail      = new FinancialScheduledTransactionDetail();
                            txnDetail.Guid = editorTxnDetail.Guid;
                            txn.ScheduledTransactionDetails.Add(txnDetail);
                        }
                        else
                        {
                            if (txnDetail.AccountId != editorTxnDetail.AccountId ||
                                txnDetail.Amount != editorTxnDetail.Amount ||
                                txnDetail.Summary != editorTxnDetail.Summary)
                            {
                                accountChanges = true;
                            }
                        }

                        changeSummary.AppendFormat("{0}: {1}", editorTxnDetail.Account != null ? editorTxnDetail.Account.Name : "?", editorTxnDetail.Amount.FormatAsCurrency());
                        changeSummary.AppendLine();

                        txnDetail.AccountId = editorTxnDetail.AccountId;
                        txnDetail.Amount    = editorTxnDetail.Amount;
                        txnDetail.Summary   = editorTxnDetail.Summary;
                    }

                    if (accountChanges)
                    {
                        // save changes
                        rockContext.SaveChanges();

                        // Add a note about the change
                        var noteType = NoteTypeCache.Read(Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid());
                        if (noteType != null)
                        {
                            var noteService = new NoteService(rockContext);
                            var note        = new Note();
                            note.NoteTypeId = noteType.Id;
                            note.EntityId   = txn.Id;
                            note.Caption    = "Updated Transaction";
                            note.Text       = changeSummary.ToString();
                            noteService.Add(note);
                        }
                        rockContext.SaveChanges();
                    }

                    ShowView(txn);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Processes the confirmation.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessConfirmation( out string errorMessage )
        {
            errorMessage = string.Empty;

            if ( string.IsNullOrWhiteSpace( TransactionCode ) )
            {
                if ( Gateway == null )
                {
                    errorMessage = "There was a problem creating the payment gateway information";
                    return false;
                }

                using ( new UnitOfWorkScope() )
                {
                    var personService = new PersonService();
                    var transactionService = new FinancialScheduledTransactionService();
                    var transactionDetailService = new FinancialScheduledTransactionDetailService();

                    FinancialScheduledTransaction scheduledTransaction = null;

                    if ( ScheduledTransactionId.HasValue )
                    {
                        scheduledTransaction = transactionService.Get( ScheduledTransactionId.Value );
                    }

                    if ( scheduledTransaction == null )
                    {
                        errorMessage = "There was a problem getting the transaction information";
                        return false;
                    }

                    if ( scheduledTransaction.AuthorizedPerson == null )
                    {
                        errorMessage = "There was a problem determining the person associated with the transaction";
                        return false;
                    }

                    // Get the payment schedule
                    scheduledTransaction.TransactionFrequencyValueId = btnFrequency.SelectedValueAsId().Value;
                    if ( dtpStartDate.SelectedDate.HasValue && dtpStartDate.SelectedDate > DateTime.Today )
                    {
                        scheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
                    }
                    else
                    {
                        scheduledTransaction.StartDate = DateTime.MinValue;
                    }

                    PaymentInfo paymentInfo = GetPaymentInfo( personService, scheduledTransaction );
                    if ( paymentInfo == null )
                    {
                        errorMessage = "There was a problem creating the payment information";
                        return false;
                    }
                    else
                    {

                    }

                    if ( Gateway.UpdateScheduledPayment( scheduledTransaction, paymentInfo, out errorMessage ) )
                    {
                        var selectedAccountIds = SelectedAccounts
                            .Where( a => a.Amount > 0 )
                            .Select( a => a.Id ).ToList();


                        var deletedAccounts = scheduledTransaction.ScheduledTransactionDetails
                            .Where( a => !selectedAccountIds.Contains( a.AccountId ) ).ToList();
                        foreach ( var deletedAccount in deletedAccounts )
                        {
                            scheduledTransaction.ScheduledTransactionDetails.Remove( deletedAccount );
                            transactionDetailService.Delete( deletedAccount, CurrentPersonId );
                        }

                        foreach ( var account in SelectedAccounts )
                        {
                            var detail = scheduledTransaction.ScheduledTransactionDetails
                                .Where( d => d.AccountId == account.Id ).FirstOrDefault();
                            if ( detail == null )
                            {
                                detail = new FinancialScheduledTransactionDetail();
                                detail.AccountId = account.Id;
                                scheduledTransaction.ScheduledTransactionDetails.Add( detail );
                            }
                            detail.Amount = account.Amount;
                        }

                        transactionService.Save( scheduledTransaction, CurrentPersonId );

                        ScheduleId = scheduledTransaction.GatewayScheduleId;
                        TransactionCode = scheduledTransaction.TransactionCode;
                    }
                    else
                    {
                        return false;
                    }

                    tdTransactionCode.Description = TransactionCode;
                    tdTransactionCode.Visible = !string.IsNullOrWhiteSpace( TransactionCode );

                    tdScheduleId.Description = ScheduleId;
                    tdScheduleId.Visible = !string.IsNullOrWhiteSpace( ScheduleId );

                    return true;
                }
            }
            else
            {
                pnlDupWarning.Visible = true;
                return false;
            }
        }
        /// <summary>
        /// Processes the confirmation.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessConfirmation( out string errorMessage )
        {
            var rockContext = new RockContext();
            errorMessage = string.Empty;

            if ( string.IsNullOrWhiteSpace( TransactionCode ) )
            {
                if ( Gateway == null )
                {
                    errorMessage = "There was a problem creating the payment gateway information";
                    return false;
                }

                var personService = new PersonService( rockContext );
                var transactionService = new FinancialScheduledTransactionService( rockContext );
                var transactionDetailService = new FinancialScheduledTransactionDetailService( rockContext );

                FinancialScheduledTransaction scheduledTransaction = null;

                if ( ScheduledTransactionId.HasValue )
                {
                    scheduledTransaction = transactionService.Get( ScheduledTransactionId.Value );
                }

                if ( scheduledTransaction == null )
                {
                    errorMessage = "There was a problem getting the transaction information";
                    return false;
                }

                if ( scheduledTransaction.AuthorizedPerson == null )
                {
                    errorMessage = "There was a problem determining the person associated with the transaction";
                    return false;
                }

                var changeSummary = new StringBuilder();

                // Get the payment schedule
                scheduledTransaction.TransactionFrequencyValueId = btnFrequency.SelectedValueAsId().Value;
                changeSummary.Append( DefinedValueCache.Read( scheduledTransaction.TransactionFrequencyValueId, rockContext ) );

                if ( dtpStartDate.SelectedDate.HasValue && dtpStartDate.SelectedDate > RockDateTime.Today )
                {
                    scheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
                    changeSummary.AppendFormat( " starting {0}", scheduledTransaction.StartDate.ToShortDateString() );
                }
                else
                {
                    scheduledTransaction.StartDate = DateTime.MinValue;
                }

                changeSummary.AppendLine();

                PaymentInfo paymentInfo = GetPaymentInfo( personService, scheduledTransaction );
                if ( paymentInfo == null )
                {
                    errorMessage = "There was a problem creating the payment information";
                    return false;
                }
                else
                {
                }

                // If transaction is not active, attempt to re-activate it first
                if ( !scheduledTransaction.IsActive )
                {
                    if ( !transactionService.Reactivate( scheduledTransaction, out errorMessage ) )
                    {
                        return false;
                    }
                }

                if ( Gateway.UpdateScheduledPayment( scheduledTransaction, paymentInfo, out errorMessage ) )
                {
                    if ( paymentInfo.CurrencyTypeValue != null )
                    {
                        changeSummary.Append( paymentInfo.CurrencyTypeValue.Value );
                        scheduledTransaction.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;

                        DefinedValueCache creditCardTypeValue = paymentInfo.CreditCardTypeValue;
                        if ( creditCardTypeValue != null )
                        {
                            changeSummary.AppendFormat( " - {0}", creditCardTypeValue.Value );
                            scheduledTransaction.CreditCardTypeValueId = creditCardTypeValue.Id;
                        }
                        else
                        {
                            scheduledTransaction.CreditCardTypeValueId = null;
                        }
                        changeSummary.AppendFormat( " {0}", paymentInfo.MaskedNumber );
                        changeSummary.AppendLine();
                    }

                    var selectedAccountIds = SelectedAccounts
                        .Where( a => a.Amount > 0 )
                        .Select( a => a.Id ).ToList();

                    var deletedAccounts = scheduledTransaction.ScheduledTransactionDetails
                        .Where( a => !selectedAccountIds.Contains( a.AccountId ) ).ToList();

                    foreach ( var deletedAccount in deletedAccounts )
                    {
                        scheduledTransaction.ScheduledTransactionDetails.Remove( deletedAccount );
                        transactionDetailService.Delete( deletedAccount );
                    }

                    foreach ( var account in SelectedAccounts )
                    {
                        var detail = scheduledTransaction.ScheduledTransactionDetails
                            .Where( d => d.AccountId == account.Id ).FirstOrDefault();
                        if ( detail == null )
                        {
                            detail = new FinancialScheduledTransactionDetail();
                            detail.AccountId = account.Id;
                            scheduledTransaction.ScheduledTransactionDetails.Add( detail );
                        }

                        detail.Amount = account.Amount;

                        changeSummary.AppendFormat( "{0}: {1:C2}", account.Name, account.Amount );
                        changeSummary.AppendLine();
                    }

                    rockContext.SaveChanges();

                    // Add a note about the change
                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( scheduledTransaction.TypeId, "Note" );

                    var noteService = new NoteService( rockContext );
                    var note = new Note();
                    note.NoteTypeId = noteType.Id;
                    note.EntityId = scheduledTransaction.Id;
                    note.Caption = "Updated Transaction";
                    note.Text = changeSummary.ToString();
                    noteService.Add( note );

                    rockContext.SaveChanges();

                    ScheduleId = scheduledTransaction.GatewayScheduleId;
                    TransactionCode = scheduledTransaction.TransactionCode;

                    if (transactionService.GetStatus( scheduledTransaction, out errorMessage ))
                    {
                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    return false;
                }

                tdTransactionCode.Description = TransactionCode;
                tdTransactionCode.Visible = !string.IsNullOrWhiteSpace( TransactionCode );

                tdScheduleId.Description = ScheduleId;
                tdScheduleId.Visible = !string.IsNullOrWhiteSpace( ScheduleId );

                return true;
            }
            else
            {
                pnlDupWarning.Visible = true;
                return false;
            }
        }
        /// <summary>
        /// Updates the scheduled payment.
        /// </summary>
        /// <param name="usePaymentToken">if set to <c>true</c> [use payment token].</param>
        /// <param name="paymentToken">The payment token.</param>
        protected void UpdateScheduledPayment(bool usePaymentToken, string paymentToken = null)
        {
            var giftTerm = this.GetAttributeValue(AttributeKey.GiftTerm);

            if (dtpStartDate.SelectedDate <= RockDateTime.Today)
            {
                nbUpdateScheduledPaymentWarning.Visible = true;
                nbUpdateScheduledPaymentWarning.Text    = string.Format("When scheduling a {0}, make sure the starting date is in the future (after today)", giftTerm.ToLower());
                return;
            }

            var rockContext = new RockContext();

            var  financialScheduledTransactionService       = new FinancialScheduledTransactionService(rockContext);
            var  financialScheduledTransactionDetailService = new FinancialScheduledTransactionDetailService(rockContext);
            Guid scheduledTransactionGuid      = hfScheduledTransactionGuid.Value.AsGuid();
            var  financialScheduledTransaction = financialScheduledTransactionService.Get(scheduledTransactionGuid);

            financialScheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
            financialScheduledTransaction.TransactionFrequencyValueId = ddlFrequency.SelectedValue.AsInteger();

            ReferencePaymentInfo referencePaymentInfo;

            var person = financialScheduledTransaction.AuthorizedPersonAlias.Person;

            string errorMessage;

            var financialGateway                      = this.FinancialGateway;
            var financialGatewayComponent             = this.FinancialGatewayComponent;
            var existingPaymentOrPersonSavedAccountId = rblExistingPaymentOrPersonSavedAccount.SelectedValue.AsInteger();

            bool useExistingPaymentMethod = pnlUseExistingPaymentNoSavedAccounts.Visible || existingPaymentOrPersonSavedAccountId == 0;
            bool useSavedAccount          = pnlUseExistingPaymentWithSavedAccounts.Visible && existingPaymentOrPersonSavedAccountId > 0;

            if (usePaymentToken)
            {
                referencePaymentInfo           = new ReferencePaymentInfo();
                referencePaymentInfo.FirstName = person.FirstName;
                referencePaymentInfo.LastName  = person.LastName;

                referencePaymentInfo.UpdateAddressFieldsFromAddressControl(acBillingAddress);

                referencePaymentInfo.ReferenceNumber = paymentToken;

                var customerToken = financialGatewayComponent.CreateCustomerAccount(this.FinancialGateway, referencePaymentInfo, out errorMessage);

                if (errorMessage.IsNotNullOrWhiteSpace() || customerToken.IsNullOrWhiteSpace())
                {
                    nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                    nbMessage.Text    = errorMessage ?? "Unknown Error";
                    nbMessage.Visible = true;
                    return;
                }

                referencePaymentInfo.GatewayPersonIdentifier = customerToken;
            }
            else if (useExistingPaymentMethod)
            {
                // use save payment method as original transaction
                referencePaymentInfo = new ReferencePaymentInfo();
                referencePaymentInfo.GatewayPersonIdentifier       = financialScheduledTransaction.FinancialPaymentDetail.GatewayPersonIdentifier;
                referencePaymentInfo.FinancialPersonSavedAccountId = financialScheduledTransaction.FinancialPaymentDetail.FinancialPersonSavedAccountId;
            }
            else if (useSavedAccount)
            {
                var savedAccount = new FinancialPersonSavedAccountService(rockContext).Get(existingPaymentOrPersonSavedAccountId);
                if (savedAccount != null)
                {
                    referencePaymentInfo = savedAccount.GetReferencePayment();
                }
                else
                {
                    // shouldn't happen
                    throw new Exception("Unable to determine Saved Account");
                }
            }
            else
            {
                // shouldn't happen
                throw new Exception("Unable to determine payment method");
            }

            var selectedAccountAmounts = caapPromptForAccountAmounts.AccountAmounts.Where(a => a.Amount.HasValue && a.Amount.Value != 0).Select(a => new { a.AccountId, Amount = a.Amount.Value }).ToArray();

            referencePaymentInfo.Amount = selectedAccountAmounts.Sum(a => a.Amount);

            var originalGatewayScheduleId = financialScheduledTransaction.GatewayScheduleId;

            try
            {
                financialScheduledTransaction.FinancialPaymentDetail.ClearPaymentInfo();
                var successfullyUpdated = financialGatewayComponent.UpdateScheduledPayment(financialScheduledTransaction, referencePaymentInfo, out errorMessage);

                if (!successfullyUpdated)
                {
                    nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                    nbMessage.Text    = errorMessage ?? "Unknown Error";
                    nbMessage.Visible = true;
                    return;
                }

                financialScheduledTransaction.FinancialPaymentDetail.SetFromPaymentInfo(referencePaymentInfo, financialGatewayComponent as GatewayComponent, rockContext);

                var selectedAccountIds        = selectedAccountAmounts.Select(a => a.AccountId).ToArray();
                var deletedTransactionDetails = financialScheduledTransaction.ScheduledTransactionDetails.ToList().Where(a => !selectedAccountIds.Contains(a.AccountId)).ToList();

                foreach (var deletedTransactionDetail in deletedTransactionDetails)
                {
                    financialScheduledTransaction.ScheduledTransactionDetails.Remove(deletedTransactionDetail);
                    financialScheduledTransactionDetailService.Delete(deletedTransactionDetail);
                }

                foreach (var selectedAccountAmount in selectedAccountAmounts)
                {
                    var scheduledTransactionDetail = financialScheduledTransaction.ScheduledTransactionDetails.FirstOrDefault(a => a.AccountId == selectedAccountAmount.AccountId);
                    if (scheduledTransactionDetail == null)
                    {
                        scheduledTransactionDetail           = new FinancialScheduledTransactionDetail();
                        scheduledTransactionDetail.AccountId = selectedAccountAmount.AccountId;
                        financialScheduledTransaction.ScheduledTransactionDetails.Add(scheduledTransactionDetail);
                    }

                    scheduledTransactionDetail.Amount = selectedAccountAmount.Amount;
                }

                rockContext.SaveChanges();
                Task.Run(() => ScheduledGiftWasModifiedMessage.PublishScheduledTransactionEvent(financialScheduledTransaction.Id, ScheduledGiftEventTypes.ScheduledGiftUpdated));
            }
            catch (Exception)
            {
                // if the GatewayScheduleId was updated, but there was an exception,
                // make sure we save the  financialScheduledTransaction record with the updated GatewayScheduleId so we don't orphan it
                if (financialScheduledTransaction.GatewayScheduleId.IsNotNullOrWhiteSpace() && (originalGatewayScheduleId != financialScheduledTransaction.GatewayScheduleId))
                {
                    rockContext.SaveChanges();
                }

                throw;
            }

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });
            var finishLavaTemplate = this.GetAttributeValue(AttributeKey.FinishLavaTemplate);

            // re-fetch financialScheduledTransaction with a new RockContext from database to ensure that lazy loaded fields will be populated
            using (var rockContextForSummary = new RockContext())
            {
                if (pnlHostedPaymentControl.Visible && hfSaveNewAccount.Value.AsInteger() == 1 && tbSaveAccount.Text.IsNotNullOrWhiteSpace())
                {
                    SaveNewFinancialPersonSavedAccount(financialScheduledTransaction);
                }

                financialScheduledTransaction = new FinancialScheduledTransactionService(rockContextForSummary).Get(scheduledTransactionGuid);

                mergeFields.Add("Transaction", financialScheduledTransaction);
                mergeFields.Add("Person", financialScheduledTransaction.AuthorizedPersonAlias.Person);
                mergeFields.Add("PaymentDetail", financialScheduledTransaction.FinancialPaymentDetail);
                mergeFields.Add("BillingLocation", financialScheduledTransaction.FinancialPaymentDetail.BillingLocation);

                pnlPromptForChanges.Visible   = false;
                pnlTransactionSummary.Visible = true;

                lTransactionSummaryHTML.Text = finishLavaTemplate.ResolveMergeFields(mergeFields);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Handles the Click event of the btnSaveAccounts 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 btnSaveAccounts_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var financialScheduledTransaction = GetTransaction(rockContext);

                decimal totalAmount = TransactionDetailsState.Select(d => d.Amount).ToList().Sum();
                if (financialScheduledTransaction.TotalAmount != totalAmount)
                {
                    nbError.Title   = "Incorrect Amount";
                    nbError.Text    = string.Format("<p>When updating account allocations, the total amount needs to remain the same as the original amount ({0}).</p>", financialScheduledTransaction.TotalAmount.FormatAsCurrency());
                    nbError.Visible = true;
                    return;
                }

                var txnDetailService = new FinancialScheduledTransactionDetailService(rockContext);
                var accountService   = new FinancialAccountService(rockContext);

                // Delete any transaction details that were removed
                var txnDetailsInDB = txnDetailService.Queryable().Where(a => a.ScheduledTransactionId.Equals(financialScheduledTransaction.Id)).ToList();
                var deletedDetails = from txnDetail in txnDetailsInDB
                                     where !TransactionDetailsState.Select(d => d.Guid).Contains(txnDetail.Guid)
                                     select txnDetail;

                bool accountChanges = deletedDetails.Any();

                deletedDetails.ToList().ForEach(txnDetail =>
                {
                    txnDetailService.Delete(txnDetail);
                });

                // Save Transaction Details
                foreach (var editorTxnDetail in TransactionDetailsState)
                {
                    editorTxnDetail.Account = accountService.Get(editorTxnDetail.AccountId);

                    // Add or Update the activity type
                    var financialTransactionDetail = financialScheduledTransaction.ScheduledTransactionDetails.FirstOrDefault(d => d.Guid.Equals(editorTxnDetail.Guid));
                    if (financialTransactionDetail == null)
                    {
                        accountChanges                  = true;
                        financialTransactionDetail      = new FinancialScheduledTransactionDetail();
                        financialTransactionDetail.Guid = editorTxnDetail.Guid;
                        financialScheduledTransaction.ScheduledTransactionDetails.Add(financialTransactionDetail);
                    }
                    else
                    {
                        if (financialTransactionDetail.AccountId != editorTxnDetail.AccountId ||
                            financialTransactionDetail.Amount != editorTxnDetail.Amount ||
                            financialTransactionDetail.Summary != editorTxnDetail.Summary)
                        {
                            accountChanges = true;
                        }
                    }

                    financialTransactionDetail.AccountId = editorTxnDetail.AccountId;
                    financialTransactionDetail.Amount    = editorTxnDetail.Amount;
                    financialTransactionDetail.Summary   = editorTxnDetail.Summary;
                }

                if (accountChanges)
                {
                    // save changes
                    rockContext.SaveChanges();
                }

                ShowView(financialScheduledTransaction);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Updates the scheduled payment.
        /// </summary>
        /// <param name="usePaymentToken">if set to <c>true</c> [use payment token].</param>
        /// <param name="paymentToken">The payment token.</param>
        protected void UpdateScheduledPayment(bool usePaymentToken, string paymentToken = null)
        {
            var giftTerm = this.GetAttributeValue(AttributeKey.GiftTerm);

            if (dtpStartDate.SelectedDate <= RockDateTime.Today)
            {
                nbUpdateScheduledPaymentWarning.Visible = true;
                nbUpdateScheduledPaymentWarning.Text    = string.Format("When scheduling a {0}, make sure the starting date is in the future (after today)", giftTerm.ToLower());
                return;
            }

            var rockContext = new RockContext();

            var financialScheduledTransactionService       = new FinancialScheduledTransactionService(rockContext);
            var financialScheduledTransactionDetailService = new FinancialScheduledTransactionDetailService(rockContext);
            int scheduledTransactionId        = hfScheduledTransactionId.Value.AsInteger();
            var financialScheduledTransaction = financialScheduledTransactionService.Get(scheduledTransactionId);

            financialScheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
            financialScheduledTransaction.TransactionFrequencyValueId = ddlFrequency.SelectedValue.AsInteger();

            ReferencePaymentInfo referencePaymentInfo;

            var person = financialScheduledTransaction.AuthorizedPersonAlias.Person;

            string errorMessage;

            var financialGateway          = this.FinancialGateway;
            var financialGatewayComponent = this.FinancialGatewayComponent;

            if (usePaymentToken)
            {
                referencePaymentInfo           = new ReferencePaymentInfo();
                referencePaymentInfo.FirstName = person.FirstName;
                referencePaymentInfo.LastName  = person.LastName;

                referencePaymentInfo.UpdateAddressFieldsFromAddressControl(acBillingAddress);

                referencePaymentInfo.ReferenceNumber = paymentToken;

                var customerToken = financialGatewayComponent.CreateCustomerAccount(this.FinancialGateway, referencePaymentInfo, out errorMessage);

                if (errorMessage.IsNotNullOrWhiteSpace() || customerToken.IsNullOrWhiteSpace())
                {
                    nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                    nbMessage.Text    = errorMessage ?? "Unknown Error";
                    nbMessage.Visible = true;
                    return;
                }

                referencePaymentInfo.GatewayPersonIdentifier = customerToken;
            }
            else
            {
                var savedAccountId = ddlPersonSavedAccount.SelectedValue.AsInteger();

                var savedAccount = new FinancialPersonSavedAccountService(rockContext).Get(savedAccountId);
                if (savedAccount != null)
                {
                    referencePaymentInfo = savedAccount.GetReferencePayment();
                }
                else
                {
                    throw new Exception("Unable to determine Saved Account");
                }
            }

            var selectedAccountAmounts = caapPromptForAccountAmounts.AccountAmounts.Where(a => a.Amount.HasValue && a.Amount.Value != 0).Select(a => new { a.AccountId, Amount = a.Amount.Value }).ToArray();

            referencePaymentInfo.Amount = selectedAccountAmounts.Sum(a => a.Amount);

            var successfullyUpdated = financialGatewayComponent.UpdateScheduledPayment(financialScheduledTransaction, referencePaymentInfo, out errorMessage);

            if (!successfullyUpdated)
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbMessage.Text    = errorMessage ?? "Unknown Error";
                nbMessage.Visible = true;
                return;
            }

            financialScheduledTransaction.FinancialPaymentDetail.SetFromPaymentInfo(referencePaymentInfo, financialGatewayComponent as GatewayComponent, rockContext);

            var selectedAccountIds        = selectedAccountAmounts.Select(a => a.AccountId).ToArray();
            var deletedTransactionDetails = financialScheduledTransaction.ScheduledTransactionDetails.ToList().Where(a => !selectedAccountIds.Contains(a.AccountId)).ToList();

            foreach (var deletedTransactionDetail in deletedTransactionDetails)
            {
                financialScheduledTransaction.ScheduledTransactionDetails.Remove(deletedTransactionDetail);
                financialScheduledTransactionDetailService.Delete(deletedTransactionDetail);
            }

            foreach (var selectedAccountAmount in selectedAccountAmounts)
            {
                var scheduledTransactionDetail = financialScheduledTransaction.ScheduledTransactionDetails.FirstOrDefault(a => a.AccountId == selectedAccountAmount.AccountId);
                if (scheduledTransactionDetail == null)
                {
                    scheduledTransactionDetail           = new FinancialScheduledTransactionDetail();
                    scheduledTransactionDetail.AccountId = selectedAccountAmount.AccountId;
                    financialScheduledTransaction.ScheduledTransactionDetails.Add(scheduledTransactionDetail);
                }

                scheduledTransactionDetail.Amount = selectedAccountAmount.Amount;
            }

            rockContext.SaveChanges();

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });
            var finishLavaTemplate = this.GetAttributeValue(AttributeKey.FinishLavaTemplate);

            mergeFields.Add("Transaction", financialScheduledTransaction);
            mergeFields.Add("Person", financialScheduledTransaction.AuthorizedPersonAlias.Person);
            mergeFields.Add("PaymentDetail", financialScheduledTransaction.FinancialPaymentDetail);
            mergeFields.Add("BillingLocation", financialScheduledTransaction.FinancialPaymentDetail.BillingLocation);

            pnlPromptForChanges.Visible   = false;
            pnlTransactionSummary.Visible = true;

            lTransactionSummaryHTML.Text = finishLavaTemplate.ResolveMergeFields(mergeFields);
        }