Пример #1
0
        /// <summary>
        /// Handles the Click event of the lbEdit 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 lbEdit_Click(object sender, EventArgs e)
        {
            var financialBatchService = new FinancialBatchService(new RockContext());
            var financialBatch        = financialBatchService.Get(hfBatchId.ValueAsInt());

            ShowEdit(financialBatch);
        }
Пример #2
0
        /// <summary>
        /// Handles the Click event of the lbSaveFinancialBatch 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 lbSaveFinancialBatch_Click(object sender, EventArgs e)
        {
            var            rockContext           = new RockContext();
            var            financialBatchService = new FinancialBatchService(rockContext);
            FinancialBatch financialBatch        = null;

            int financialBatchId = 0;

            if (!string.IsNullOrEmpty(hfBatchId.Value))
            {
                financialBatchId = int.Parse(hfBatchId.Value);
            }

            if (financialBatchId == 0)
            {
                financialBatch = new Rock.Model.FinancialBatch();
                financialBatchService.Add(financialBatch);
            }
            else
            {
                financialBatch = financialBatchService.Get(financialBatchId);
            }

            financialBatch.Name = tbName.Text;
            financialBatch.BatchStartDateTime = drpBatchDate.LowerValue;
            financialBatch.BatchEndDateTime   = drpBatchDate.UpperValue;
            financialBatch.CampusId           = campCampus.SelectedCampusId;
            financialBatch.Status             = (BatchStatus)ddlStatus.SelectedIndex;
            decimal fcontrolamt = 0;

            decimal.TryParse(tbControlAmount.Text, out fcontrolamt);
            financialBatch.ControlAmount = fcontrolamt;

            if (!financialBatch.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.SaveChanges();
            hfBatchId.SetValue(financialBatch.Id);

            foreach (var block in RockPage.RockBlocks.OfType <RockWeb.Blocks.Finance.TransactionList>())
            {
                ((RockWeb.Blocks.Finance.TransactionList)block).RefreshList();
            }

            var savedFinancialBatch = new FinancialBatchService(rockContext).Get(hfBatchId.ValueAsInt());

            ShowSummary(savedFinancialBatch);
        }
Пример #3
0
        /// <summary>
        /// Handles the Click event of the btnSaveFinancialBatch 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 btnSaveFinancialBatch_Click(object sender, EventArgs e)
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                var            financialBatchService = new FinancialBatchService();
                FinancialBatch financialBatch        = null;

                int financialBatchId = 0;
                if (!string.IsNullOrEmpty(hfBatchId.Value))
                {
                    financialBatchId = int.Parse(hfBatchId.Value);
                }

                if (financialBatchId == 0)
                {
                    financialBatch = new Rock.Model.FinancialBatch();
                    financialBatch.CreatedByPersonId = CurrentPersonId.Value;
                    financialBatchService.Add(financialBatch, CurrentPersonId);
                }
                else
                {
                    financialBatch = financialBatchService.Get(financialBatchId);
                }

                financialBatch.Name = tbName.Text;
                financialBatch.BatchStartDateTime = dtBatchDate.LowerValue;
                financialBatch.BatchEndDateTime   = dtBatchDate.UpperValue;
                financialBatch.CampusId           = cpCampus.SelectedCampusId;
                financialBatch.Status             = (BatchStatus)ddlStatus.SelectedIndex;
                decimal fcontrolamt = 0;
                decimal.TryParse(tbControlAmount.Text, out fcontrolamt);
                financialBatch.ControlAmount = fcontrolamt;

                if (!financialBatch.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                RockTransactionScope.WrapTransaction(() =>
                {
                    financialBatchService.Save(financialBatch, CurrentPersonId);
                    hfBatchId.SetValue(financialBatch.Id);
                });
            }

            var savedFinancialBatch = new FinancialBatchService().Get(hfBatchId.ValueAsInt());

            ShowReadOnly(savedFinancialBatch);
        }
Пример #4
0
        /// <summary>
        /// Handles the Delete event of the gBatchList 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 gBatchList_Delete(object sender, RowEventArgs e)
        {
            var rockContext        = new RockContext();
            var batchService       = new FinancialBatchService(rockContext);
            var transactionService = new FinancialTransactionService(rockContext);
            var batch = batchService.Get(e.RowKeyId);

            if (batch != null)
            {
                if (batch.IsAuthorized(Rock.Security.Authorization.DELETE, CurrentPerson))
                {
                    string errorMessage;
                    if (!batchService.CanDelete(batch, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    rockContext.WrapTransaction(() =>
                    {
                        foreach (var txn in transactionService.Queryable()
                                 .Where(t => t.BatchId == batch.Id))
                        {
                            transactionService.Delete(txn);
                        }

                        var changes = new History.HistoryChangeList();
                        changes.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Batch");
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(FinancialBatch),
                            Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                            batch.Id,
                            changes);

                        batchService.Delete(batch);

                        rockContext.SaveChanges();
                    });
                }
                else
                {
                    mdGridWarning.Show("You are not authorized to delete the selected batch.", ModalAlertType.Warning);
                }
            }

            BindGrid();
        }
Пример #5
0
        /// <summary>
        /// Shows the edit value.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        /// <param name="setValues">if set to <c>true</c> [set values].</param>
        protected void ShowEditValue(int batchId)
        {
            var batchService = new FinancialBatchService();
            var batch        = batchService.Get(batchId);

            hfIdValue.Value = batch.Id.ToString();

            lValue.Text = "Edit";
            tbName.Text = batch.Name;
            dtBatchDate.SelectedDate = batch.BatchDate;
            if (batch.CampusId.HasValue)
            {
                cpCampus.SelectedCampusId = batch.CampusId;
            }
            ddlStatus.BindToEnum(typeof(BatchStatus));
            tbControlAmount.Text = batch.ControlAmount.ToString();
            setTransactionDataSource(batch.Transactions.ToList());
        }
Пример #6
0
        /// <summary>
        /// Handles the Delete event of the gBatchList 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 gBatchList_Delete(object sender, RowEventArgs e)
        {
            var rockContext        = new RockContext();
            var batchService       = new FinancialBatchService(rockContext);
            var transactionService = new FinancialTransactionService(rockContext);
            var batch = batchService.Get(e.RowKeyId);

            if (batch != null)
            {
                if (UserCanEdit || batch.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson))
                {
                    string errorMessage;
                    if (!batchService.CanDelete(batch, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    rockContext.WrapTransaction(() =>
                    {
                        foreach (var txn in transactionService.Queryable()
                                 .Where(t => t.BatchId == batch.Id))
                        {
                            transactionService.Delete(txn);
                        }
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(FinancialBatch),
                            Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                            batch.Id,
                            new List <string> {
                            "Deleted the batch"
                        });

                        batchService.Delete(batch);

                        rockContext.SaveChanges();
                    });
                }
            }

            BindGrid();
        }
Пример #7
0
        /// <summary>
        /// Handles the Delete event of the gBatchList 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 gBatchList_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();
            FinancialBatchService financialBatchService = new FinancialBatchService(rockContext);
            FinancialBatch        financialBatch        = financialBatchService.Get(e.RowKeyId);

            if (financialBatch != null)
            {
                string errorMessage;
                if (!financialBatchService.CanDelete(financialBatch, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                financialBatchService.Delete(financialBatch);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Пример #8
0
        /// <summary>
        /// Handles the Delete event of the gBatchList 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 gBatchList_Delete(object sender, RowEventArgs e)
        {
            var rockContext  = new RockContext();
            var batchService = new FinancialBatchService(rockContext);
            var batch        = batchService.Get(e.RowKeyId);

            if (batch != null)
            {
                if (UserCanEdit || batch.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson))
                {
                    string errorMessage;
                    if (!batchService.CanDelete(batch, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    batchService.Delete(batch);
                    rockContext.SaveChanges();
                }
            }

            BindGrid();
        }
Пример #9
0
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            var            rockContext  = new RockContext();
            var            batchService = new FinancialBatchService(rockContext);
            FinancialBatch batch        = null;

            int batchId = hfBatchId.Value.AsInteger();

            if (batchId == 0)
            {
                batch = new FinancialBatch();
                batchService.Add(batch);
            }
            else
            {
                batch = batchService.Get(batchId);
            }

            if (batch != null)
            {
                batch.Name               = tbName.Text;
                batch.Status             = (BatchStatus)ddlStatus.SelectedIndex;
                batch.CampusId           = campCampus.SelectedCampusId;
                batch.BatchStartDateTime = dtpStart.SelectedDateTimeIsBlank ? null : dtpStart.SelectedDateTime;
                if (dtpEnd.SelectedDateTimeIsBlank && batch.BatchStartDateTime.HasValue)
                {
                    batch.BatchEndDateTime = batch.BatchStartDateTime.Value.AddDays(1);
                }
                else
                {
                    batch.BatchEndDateTime = dtpEnd.SelectedDateTimeIsBlank ? null : dtpEnd.SelectedDateTime;
                }
                batch.ControlAmount        = tbControlAmount.Text.AsDecimal();
                batch.AccountingSystemCode = tbAccountingCode.Text;

                if (!Page.IsValid || !batch.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                rockContext.SaveChanges();

                if (batchId == 0)
                {
                    // If created a new batch, navigate to same page so that transaction list displays correctly
                    var pageReference = CurrentPageReference;
                    pageReference.Parameters.AddOrReplace("batchId", batch.Id.ToString());
                    NavigateToPage(pageReference);
                }
                else
                {
                    hfBatchId.SetValue(batch.Id);

                    // Requery the batch to support EF navigation properties
                    var savedBatch = GetBatch(batch.Id);

                    ShowReadonlyDetails(savedBatch);
                }
            }
        }
Пример #10
0
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                if (contextEntity is Person)
                {
                    var personService = new PersonService(rockContext);
                    var changes       = new History.HistoryChangeList();
                    var _person       = personService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _person.ForeignKey, tbForeignKey.Text);
                    _person.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _person.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _person.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _person.ForeignId.ToString(), tbForeignId.Text);
                    _person.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                _person.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is FinancialAccount)
                {
                    var accountService = new FinancialAccountService(rockContext);
                    var _account       = accountService.Get(contextEntity.Id);

                    _account.ForeignKey  = tbForeignKey.Text;
                    _account.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _account.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is FinancialBatch)
                {
                    var batchService = new FinancialBatchService(rockContext);
                    var changes      = new History.HistoryChangeList();
                    var _batch       = batchService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _batch.ForeignKey, tbForeignKey.Text);
                    _batch.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _batch.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _batch.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _batch.ForeignId.ToString(), tbForeignId.Text);
                    _batch.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                _batch.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is FinancialPledge)
                {
                    var pledgeService = new FinancialPledgeService(rockContext);
                    var _pledge       = pledgeService.Get(contextEntity.Id);

                    _pledge.ForeignKey  = tbForeignKey.Text;
                    _pledge.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _pledge.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is FinancialTransaction)
                {
                    var transactionService = new FinancialTransactionService(rockContext);
                    var changes            = new History.HistoryChangeList();
                    var _transaction       = transactionService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _transaction.ForeignKey, tbForeignKey.Text);
                    _transaction.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _transaction.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _transaction.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _transaction.ForeignId.ToString(), tbForeignId.Text);
                    _transaction.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialTransaction),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                _transaction.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is FinancialScheduledTransaction)
                {
                    var transactionScheduledService = new FinancialScheduledTransactionService(rockContext);
                    var _scheduledTransaction       = transactionScheduledService.Get(contextEntity.Id);

                    _scheduledTransaction.ForeignKey  = tbForeignKey.Text;
                    _scheduledTransaction.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _scheduledTransaction.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is Group)
                {
                    var groupService = new GroupService(rockContext);
                    var _group       = groupService.Get(contextEntity.Id);

                    _group.ForeignKey  = tbForeignKey.Text;
                    _group.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _group.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is GroupMember)
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var changes            = new History.HistoryChangeList();
                    var _groupMember       = groupMemberService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _groupMember.ForeignKey, tbForeignKey.Text);
                    _groupMember.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _groupMember.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _groupMember.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _groupMember.ForeignId.ToString(), tbForeignId.Text);
                    _groupMember.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(GroupMember),
                                Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(),
                                _groupMember.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is Metric)
                {
                    var metricService = new MetricService(rockContext);
                    var _metric       = metricService.Get(contextEntity.Id);

                    _metric.ForeignKey  = tbForeignKey.Text;
                    _metric.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _metric.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is Location)
                {
                    var locationService = new LocationService(rockContext);
                    var _location       = locationService.Get(contextEntity.Id);

                    _location.ForeignKey  = tbForeignKey.Text;
                    _location.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _location.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is PrayerRequest)
                {
                    var prayerRequestService = new PrayerRequestService(rockContext);
                    var _request             = prayerRequestService.Get(contextEntity.Id);

                    _request.ForeignKey  = tbForeignKey.Text;
                    _request.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _request.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is ContentChannel)
                {
                    var contentChannelService = new ContentChannelService(rockContext);
                    var _channel = contentChannelService.Get(contextEntity.Id);

                    _channel.ForeignKey  = tbForeignKey.Text;
                    _channel.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _channel.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is ContentChannelItem)
                {
                    var contentChannelItemService = new ContentChannelItemService(rockContext);
                    var _item = contentChannelItemService.Get(contextEntity.Id);

                    _item.ForeignKey  = tbForeignKey.Text;
                    _item.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _item.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
            });

            Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }
Пример #11
0
        public void RaisePostBackEvent(string eventArgument)
        {
            if (_batch != null)
            {
                if (eventArgument == "MoveTransactions" &&
                    _ddlMove != null &&
                    _ddlMove.SelectedValue != null &&
                    !String.IsNullOrWhiteSpace(_ddlMove.SelectedValue))
                {
                    var txnsSelected = new List <int>();

                    gTransactions.SelectedKeys.ToList().ForEach(b => txnsSelected.Add(b.ToString().AsInteger()));

                    if (txnsSelected.Any())
                    {
                        var rockContext  = new RockContext();
                        var batchService = new FinancialBatchService(rockContext);

                        var newBatch = batchService.Get(_ddlMove.SelectedValue.AsInteger());
                        var oldBatch = batchService.Get(_batch.Id);

                        if (newBatch != null && newBatch.Status == BatchStatus.Open)
                        {
                            var txnService   = new FinancialTransactionService(rockContext);
                            var txnsToUpdate = txnService.Queryable()
                                               .Where(t => txnsSelected.Contains(t.Id))
                                               .ToList();

                            foreach (var txn in txnsToUpdate)
                            {
                                txn.BatchId             = newBatch.Id;
                                oldBatch.ControlAmount -= txn.TotalAmount;
                                newBatch.ControlAmount += txn.TotalAmount;
                            }

                            rockContext.SaveChanges();

                            var pageRef = new Rock.Web.PageReference(RockPage.PageId);
                            pageRef.Parameters = new Dictionary <string, string>();
                            pageRef.Parameters.Add("batchid", newBatch.Id.ToString());
                            string newBatchLink = string.Format("<a href='{0}'>{1}</a>",
                                                                pageRef.BuildUrl(), newBatch.Name);

                            RockPage.UpdateBlocks("~/Blocks/Finance/BatchDetail.ascx");

                            nbResult.Text = string.Format("{0} transactions were moved to the '{1}' batch.",
                                                          txnsToUpdate.Count().ToString("N0"), newBatchLink);
                            nbResult.NotificationBoxType = NotificationBoxType.Success;
                            nbResult.Visible             = true;
                        }
                        else
                        {
                            nbResult.Text = string.Format("The selected batch does not exist, or is no longer open.");
                            nbResult.NotificationBoxType = NotificationBoxType.Danger;
                            nbResult.Visible             = true;
                        }
                    }
                    else
                    {
                        nbResult.Text = string.Format("There were not any transactions selected.");
                        nbResult.NotificationBoxType = NotificationBoxType.Warning;
                        nbResult.Visible             = true;
                    }
                }

                _ddlMove.SelectedIndex = 0;
            }

            BindGrid();
        }
Пример #12
0
        /// <summary>
        /// Handles the Swipe event of the csPayWithCard control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="SwipeEventArgs"/> instance containing the event data.</param>
        protected void csPayWithCard_Swipe(object sender, SwipeEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                try
                {
                    var swipeInfo = e.PaymentInfo;
                    var person    = Customer;

                    if (person == null)
                    {
                        person = new PersonAliasService(rockContext).GetPerson(GetAttributeValue("GuestCustomer").AsGuid());

                        if (person == null)
                        {
                            nbSwipeErrors.Text = "No guest customer configured. Transaction not processed.";
                            return;
                        }
                    }

                    //
                    // Get the gateway to use.
                    //
                    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)
                    {
                        nbSwipeErrors.Text = "Invalid gateway provided. Please provide a gateway. Transaction not processed.";
                        return;
                    }

                    swipeInfo.Amount = Cart.Total;

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

                    if (transaction == null)
                    {
                        nbSwipeErrors.Text = String.Format("An error occurred while process this transaction. Message: {0}", errorMessage);
                        return;
                    }

                    //
                    // Set some common information about the transaction.
                    //
                    transaction.AuthorizedPersonAliasId = person.PrimaryAliasId;
                    transaction.TransactionDateTime     = RockDateTime.Now;
                    transaction.FinancialGatewayId      = financialGateway.Id;
                    transaction.TransactionTypeValueId  = DefinedValueCache.Get(GetAttributeValue("TransactionType")).Id;
                    transaction.SourceTypeValueId       = DefinedValueCache.Get(GetAttributeValue("Source")).Id;
                    transaction.Summary = swipeInfo.Comment1;

                    //
                    // Ensure we have payment details.
                    //
                    if (transaction.FinancialPaymentDetail == null)
                    {
                        transaction.FinancialPaymentDetail = new FinancialPaymentDetail();
                    }
                    transaction.FinancialPaymentDetail.SetFromPaymentInfo(swipeInfo, gateway, rockContext);

                    //
                    // Setup the transaction details to credit the correct account.
                    //
                    GetTransactionDetails(rockContext).ForEach(d => transaction.TransactionDetails.Add(d));

                    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 History.HistoryChangeList();

                    if (batch.Id == 0)
                    {
                        batchChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "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);
                    }

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

                    //
                    // Add the transaction to the batch.
                    //
                    transaction.BatchId = batch.Id;
                    batch.Transactions.Add(transaction);

                    //
                    // Generate the receipt.
                    //
                    int receiptId;
                    using (var rockContext2 = new RockContext())
                    {
                        var receipt = GenerateReceipt(rockContext2);
                        receiptId = receipt.Id;
                    }

                    //
                    // Update each transaction detail to reference the receipt.
                    //
                    foreach (var transactionDetail in transaction.TransactionDetails)
                    {
                        transactionDetail.EntityTypeId = EntityTypeCache.Get(typeof(InteractionComponent)).Id;
                        transactionDetail.EntityId     = receiptId;
                    }

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

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

                    ShowReceiptPanel();
                }
                catch (Exception ex)
                {
                    nbSwipeErrors.Text = String.Format("An error occurred while process this transaction. Message: {0}", ex.Message);
                }
            }
        }
Пример #13
0
        private void SaveTransaction(FinancialGateway financialGateway, GatewayComponent gateway, Person person, PaymentInfo paymentInfo, FinancialTransaction transaction, RockContext rockContext)
        {
            transaction.AuthorizedPersonAliasId = person.PrimaryAliasId;
            if (RockTransactionEntry != null)
            {
                RockCheckBox cbGiveAnonymouslyControl = (( RockCheckBox )(RockTransactionEntry.FindControl("cbGiveAnonymously")));
                if (cbGiveAnonymouslyControl != null)
                {
                    transaction.ShowAsAnonymous = cbGiveAnonymouslyControl.Checked;
                }
            }
            transaction.TransactionDateTime = RockDateTime.Now;
            transaction.FinancialGatewayId  = financialGateway.Id;

            var txnType = DefinedValueCache.Get(this.GetAttributeValue("TransactionType").AsGuidOrNull() ?? Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid());

            transaction.TransactionTypeValueId = txnType.Id;

            transaction.Summary = paymentInfo.Comment1;

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

            Guid sourceGuid = Guid.Empty;

            if (Guid.TryParse(GetAttributeValue("Source"), out sourceGuid))
            {
                var source = DefinedValueCache.Get(sourceGuid);
                if (source != null)
                {
                    transaction.SourceTypeValueId = source.Id;
                }
            }

            var transactionEntity = this.GetTransactionEntity();

            foreach (var account in GetSelectedAccounts().Where(a => a.Amount > 0))
            {
                var transactionDetail = new FinancialTransactionDetail();
                transactionDetail.Amount    = account.Amount;
                transactionDetail.AccountId = account.Id;
                if (transactionEntity != null)
                {
                    transactionDetail.EntityTypeId = transactionEntity.TypeId;
                    transactionDetail.EntityId     = transactionEntity.Id;
                }

                transaction.TransactionDetails.Add(transactionDetail);
            }

            var batchService = new FinancialBatchService(rockContext);

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

            var batchChanges = new History.HistoryChangeList();

            if (batch.Id == 0)
            {
                batchChanges.AddCustom("Add", "Record", "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;
            transaction.LoadAttributes(rockContext);

            var allowedTransactionAttributes = GetAttributeValue("AllowedTransactionAttributesFromURL").Split(',').AsGuidList().Select(x => AttributeCache.Get(x).Key);

            foreach (KeyValuePair <string, AttributeValueCache> attr in transaction.AttributeValues)
            {
                if (PageParameters().ContainsKey("Attribute_" + attr.Key) && allowedTransactionAttributes.Contains(attr.Key))
                {
                    attr.Value.Value = Server.UrlDecode(PageParameter("Attribute_" + attr.Key));
                }
            }

            batch.Transactions.Add(transaction);

            rockContext.SaveChanges();
            transaction.SaveAttributeValues();

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

            SendReceipt(transaction.Id);

            TransactionCode = transaction.TransactionCode;
        }
Пример #14
0
        /// <summary>
        /// Process the data read from the card reader and generate the transaction.
        /// </summary>
        /// <param name="swipeData">The data read from the card.</param>
        private void ProcessSwipe(string swipeData)
        {
            try
            {
                using (var rockContext = new RockContext())
                {
                    // create swipe object
                    SwipePaymentInfo swipeInfo = new SwipePaymentInfo(swipeData);
                    swipeInfo.Amount = tbAmount.Text.AsDecimal();

                    // add comment to the transation
                    swipeInfo.Comment1 = PageParameter("Memo");

                    // 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)
                    {
                        lSwipeErrors.Text = "<div class='alert alert-danger'>Invalid gateway provided. Please provide a gateway. Transaction not processed.</div>";
                        return;
                    }

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

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

                    _transactionCode = transaction.TransactionCode;

                    //
                    // Set some common information about the transaction.
                    //
                    transaction.AuthorizedPersonAliasId = new PersonService(rockContext).Get(SelectedPersonGuid).PrimaryAliasId;
                    transaction.TransactionDateTime     = RockDateTime.Now;
                    transaction.FinancialGatewayId      = financialGateway.Id;
                    transaction.TransactionTypeValueId  = DefinedValueCache.Read(GetAttributeValue("TransactionType")).Id;
                    transaction.SourceTypeValueId       = DefinedValueCache.Read(GetAttributeValue("Source")).Id;
                    transaction.Summary = swipeInfo.Comment1;

                    //
                    // Ensure we have payment details.
                    //
                    if (transaction.FinancialPaymentDetail == null)
                    {
                        transaction.FinancialPaymentDetail = new FinancialPaymentDetail();
                    }
                    transaction.FinancialPaymentDetail.SetFromPaymentInfo(swipeInfo, gateway, rockContext);

                    var transactionDetail = new FinancialTransactionDetail();
                    transactionDetail.Amount    = swipeInfo.Amount;
                    transactionDetail.AccountId = new FinancialAccountService(rockContext).Get(GetAttributeValue("Account").AsGuid()).Id;
                    transaction.TransactionDetails.Add(transactionDetail);

                    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
                            );
                    });

                    ShowReceiptPanel();
                }
            }
            catch (Exception ex)
            {
                lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", ex.Message);
            }
        }
Пример #15
0
        public void RaisePostBackEvent(string eventArgument)
        {
            if (_batch != null)
            {
                if (eventArgument == "MoveTransactions" &&
                    _ddlMove != null &&
                    _ddlMove.SelectedValue != null &&
                    !String.IsNullOrWhiteSpace(_ddlMove.SelectedValue))
                {
                    var txnsSelected = new List <int>();

                    gTransactions.SelectedKeys.ToList().ForEach(b => txnsSelected.Add(b.ToString().AsInteger()));

                    if (txnsSelected.Any())
                    {
                        var rockContext  = new RockContext();
                        var batchService = new FinancialBatchService(rockContext);

                        var newBatch = batchService.Get(_ddlMove.SelectedValue.AsInteger());
                        var oldBatch = batchService.Get(_batch.Id);

                        if (oldBatch != null && newBatch != null && newBatch.Status == BatchStatus.Open)
                        {
                            var txnService   = new FinancialTransactionService(rockContext);
                            var txnsToUpdate = txnService.Queryable("AuthorizedPersonAlias.Person")
                                               .Where(t => txnsSelected.Contains(t.Id))
                                               .ToList();

                            decimal oldBatchControlAmount = oldBatch.ControlAmount;
                            decimal newBatchControlAmount = newBatch.ControlAmount;

                            foreach (var txn in txnsToUpdate)
                            {
                                string caption = (txn.AuthorizedPersonAlias != null && txn.AuthorizedPersonAlias.Person != null) ?
                                                 txn.AuthorizedPersonAlias.Person.FullName :
                                                 string.Format("Transaction: {0}", txn.Id);

                                var changes = new List <string>();
                                History.EvaluateChange(changes, "Batch",
                                                       string.Format("{0} (Id:{1})", oldBatch.Name, oldBatch.Id),
                                                       string.Format("{0} (Id:{1})", newBatch.Name, newBatch.Id));

                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof(FinancialBatch),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    oldBatch.Id,
                                    changes,
                                    caption,
                                    typeof(FinancialTransaction),
                                    txn.Id,
                                    false
                                    );

                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof(FinancialBatch),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    newBatch.Id,
                                    changes,
                                    caption,
                                    typeof(FinancialTransaction),
                                    txn.Id, false
                                    );

                                txn.BatchId            = newBatch.Id;
                                oldBatchControlAmount -= txn.TotalAmount;
                                newBatchControlAmount += txn.TotalAmount;
                            }

                            var oldBatchChanges = new List <string>();
                            History.EvaluateChange(oldBatchChanges, "Control Amount", oldBatch.ControlAmount.FormatAsCurrency(), oldBatchControlAmount.FormatAsCurrency());
                            oldBatch.ControlAmount = oldBatchControlAmount;

                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                oldBatch.Id,
                                oldBatchChanges,
                                false
                                );

                            var newBatchChanges = new List <string>();
                            History.EvaluateChange(newBatchChanges, "Control Amount", newBatch.ControlAmount.FormatAsCurrency(), newBatchControlAmount.FormatAsCurrency());
                            newBatch.ControlAmount = newBatchControlAmount;

                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                newBatch.Id,
                                newBatchChanges,
                                false
                                );

                            rockContext.SaveChanges();

                            var pageRef = new Rock.Web.PageReference(RockPage.PageId);
                            pageRef.Parameters = new Dictionary <string, string>();
                            pageRef.Parameters.Add("batchid", newBatch.Id.ToString());
                            string newBatchLink = string.Format("<a href='{0}'>{1}</a>",
                                                                pageRef.BuildUrl(), newBatch.Name);

                            RockPage.UpdateBlocks("~/Blocks/Finance/BatchDetail.ascx");

                            nbResult.Text = string.Format("{0} transactions were moved to the '{1}' batch.",
                                                          txnsToUpdate.Count().ToString("N0"), newBatchLink);
                            nbResult.NotificationBoxType = NotificationBoxType.Success;
                            nbResult.Visible             = true;
                        }
                        else
                        {
                            nbResult.Text = string.Format("The selected batch does not exist, or is no longer open.");
                            nbResult.NotificationBoxType = NotificationBoxType.Danger;
                            nbResult.Visible             = true;
                        }
                    }
                    else
                    {
                        nbResult.Text = string.Format("There were not any transactions selected.");
                        nbResult.NotificationBoxType = NotificationBoxType.Warning;
                        nbResult.Visible             = true;
                    }
                }

                _ddlMove.SelectedIndex = 0;
            }

            BindGrid();
        }
Пример #16
0
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            var            rockContext  = new RockContext();
            var            batchService = new FinancialBatchService(rockContext);
            FinancialBatch batch        = null;

            var changes = new List <string>();

            int batchId = hfBatchId.Value.AsInteger();

            if (batchId == 0)
            {
                batch = new FinancialBatch();
                batchService.Add(batch);
                changes.Add("Created the batch");
            }
            else
            {
                batch = batchService.Get(batchId);
            }

            if (batch != null)
            {
                if (ddlBatchName.Visible)
                {
                    History.EvaluateChange(changes, "Batch Name", batch.Name, ddlBatchName.SelectedItem.Text);
                    batch.Name = ddlBatchName.SelectedItem.Text;
                }
                else
                {
                    History.EvaluateChange(changes, "Batch Name", batch.Name, tbName.Text);
                    batch.Name = tbName.Text;
                }

                BatchStatus batchStatus = (BatchStatus)ddlStatus.SelectedIndex;

                string errorMessage;
                if (!batch.IsValidBatchStatusChange(batch.Status, batchStatus, this.CurrentPerson, out errorMessage))
                {
                    cvBatch.IsValid      = false;
                    cvBatch.ErrorMessage = errorMessage;
                    return;
                }

                History.EvaluateChange(changes, "Status", batch.Status, batchStatus);
                batch.Status = batchStatus;

                CampusCache oldCampus = null;
                if (batch.CampusId.HasValue)
                {
                    oldCampus = CampusCache.Read(batch.CampusId.Value);
                }

                CampusCache newCampus = null;
                if (campCampus.SelectedCampusId.HasValue)
                {
                    newCampus = CampusCache.Read(campCampus.SelectedCampusId.Value);
                }

                History.EvaluateChange(changes, "Campus", oldCampus != null ? oldCampus.Name : "None", newCampus != null ? newCampus.Name : "None");
                batch.CampusId = campCampus.SelectedCampusId;

                DateTime?startDateTime = dtpStart.SelectedDateTimeIsBlank ? null : dtpStart.SelectedDateTime;
                History.EvaluateChange(changes, "Start Date/Time", batch.BatchStartDateTime, startDateTime);
                batch.BatchStartDateTime = startDateTime;

                DateTime?endDateTime;
                if (dtpEnd.SelectedDateTimeIsBlank && batch.BatchStartDateTime.HasValue)
                {
                    endDateTime = batch.BatchStartDateTime.Value.AddDays(1);
                }
                else
                {
                    endDateTime = dtpEnd.SelectedDateTimeIsBlank ? null : dtpEnd.SelectedDateTime;
                }

                History.EvaluateChange(changes, "End Date/Time", batch.BatchEndDateTime, endDateTime);
                batch.BatchEndDateTime = endDateTime;

                decimal controlAmount = tbControlAmount.Text.AsDecimal();
                History.EvaluateChange(changes, "Control Amount", batch.ControlAmount.FormatAsCurrency(), controlAmount.FormatAsCurrency());
                batch.ControlAmount = controlAmount;

                History.EvaluateChange(changes, "Accounting System Code", batch.AccountingSystemCode, tbAccountingCode.Text);
                batch.AccountingSystemCode = tbAccountingCode.Text;

                History.EvaluateChange(changes, "Notes", batch.Note, tbNote.Text);
                batch.Note = tbNote.Text;

                cvBatch.IsValid = batch.IsValid;
                if (!Page.IsValid || !batch.IsValid)
                {
                    cvBatch.ErrorMessage = batch.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                    return;
                }

                batch.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, batch);

                rockContext.WrapTransaction(() =>
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            pdAuditDetails.SetEntity(batch, ResolveRockUrl("~"));
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                batch.Id,
                                changes);
                        }
                    }
                });

                batch.SaveAttributeValues(rockContext);

                if (batchId == 0)
                {
                    // If created a new batch, navigate to same page so that transaction list displays correctly
                    var pageReference = CurrentPageReference;
                    pageReference.Parameters.AddOrReplace("batchId", batch.Id.ToString());
                    NavigateToPage(pageReference);
                }
                else
                {
                    hfBatchId.SetValue(batch.Id);

                    // Requery the batch to support EF navigation properties
                    var savedBatch = GetBatch(batch.Id);
                    ShowReadonlyDetails(savedBatch);

                    // If there is a batch context item, update the context's properties with new values
                    var contextObjects = new Dictionary <string, object>();
                    foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                    {
                        var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                        if (contextEntity is FinancialBatch)
                        {
                            var contextBatch = contextEntity as FinancialBatch;
                            contextBatch.CopyPropertiesFrom(batch);
                        }
                    }

                    // Then refresh transaction list
                    RockPage.UpdateBlocks("~/Blocks/Finance/TransactionList.ascx");
                }
            }
        }
Пример #17
0
        /// <summary>
        /// This method stores the transaction in the database along with the appropriate details and batch information.
        /// </summary>
        private FinancialTransaction SaveTransaction(Guid transactionGuid)
        {
            // if this is a future transaction, the payment hasn't been charged yet
            if (_payment == null && _automatedPaymentArgs.FutureProcessingDateTime.HasValue)
            {
                _payment = new Payment
                {
                    Status          = "PreProcessing",
                    StatusMessage   = "This transaction is scheduled to be processed in the future",
                    TransactionCode = _financialPersonSavedAccount.Id.ToStringSafe()
                };
            }

            // Create a new transaction or update the future transaction now that it has been charged
            var financialTransaction = _futureTransaction ?? new FinancialTransaction();

            financialTransaction.TransactionCode          = _payment.TransactionCode;
            financialTransaction.Guid                     = transactionGuid;
            financialTransaction.CreatedByPersonAliasId   = _currentPersonAliasId;
            financialTransaction.ScheduledTransactionId   = _automatedPaymentArgs.ScheduledTransactionId;
            financialTransaction.AuthorizedPersonAliasId  = _automatedPaymentArgs.AuthorizedPersonAliasId;
            financialTransaction.ShowAsAnonymous          = _automatedPaymentArgs.ShowAsAnonymous;
            financialTransaction.TransactionDateTime      = _automatedPaymentArgs.FutureProcessingDateTime.HasValue ? ( DateTime? )null : RockDateTime.Now;
            financialTransaction.FinancialGatewayId       = _financialGateway.Id;
            financialTransaction.TransactionTypeValueId   = _transactionType.Id;
            financialTransaction.Summary                  = string.Format("{0} {1}", financialTransaction.Summary, _referencePaymentInfo.Comment1).Trim();
            financialTransaction.SourceTypeValueId        = _financialSource.Id;
            financialTransaction.IsSettled                = _payment.IsSettled;
            financialTransaction.Status                   = _payment.Status;
            financialTransaction.StatusMessage            = _payment.StatusMessage;
            financialTransaction.SettledDate              = _payment.SettledDate;
            financialTransaction.ForeignKey               = _payment.ForeignKey;
            financialTransaction.FutureProcessingDateTime = _automatedPaymentArgs.FutureProcessingDateTime;


            financialTransaction.ForeignCurrencyCodeValueId = GetCurrencyCodeDefinedValueCache(_automatedPaymentArgs.AmountCurrencyCode)?.Id;

            // Create a new payment detail or update the future transaction's payment detail now that it has been charged
            var financialPaymentDetail = financialTransaction.FinancialPaymentDetail ?? new FinancialPaymentDetail();

            financialPaymentDetail.AccountNumberMasked           = _payment.AccountNumberMasked;
            financialPaymentDetail.NameOnCard                    = _payment.NameOnCard;
            financialPaymentDetail.ExpirationMonth               = _payment.ExpirationMonth;
            financialPaymentDetail.ExpirationYear                = _payment.ExpirationYear;
            financialPaymentDetail.CreatedByPersonAliasId        = _currentPersonAliasId;
            financialPaymentDetail.ForeignKey                    = _payment.ForeignKey;
            financialPaymentDetail.GatewayPersonIdentifier       = _financialPersonSavedAccount?.GatewayPersonIdentifier;
            financialPaymentDetail.FinancialPersonSavedAccountId = _financialPersonSavedAccount?.Id;

            if (_payment.CurrencyTypeValue != null)
            {
                financialPaymentDetail.CurrencyTypeValueId = _payment.CurrencyTypeValue.Id;
            }

            if (_payment.CreditCardTypeValue != null)
            {
                financialPaymentDetail.CreditCardTypeValueId = _payment.CreditCardTypeValue.Id;
            }

            financialPaymentDetail.SetFromPaymentInfo(_referencePaymentInfo, _automatedGatewayComponent, _rockContext);
            financialTransaction.FinancialPaymentDetail   = financialPaymentDetail;
            financialTransaction.FinancialPaymentDetailId = financialPaymentDetail.Id == 0 ? ( int? )null : financialPaymentDetail.Id;

            // Future transactions already have the appropriate FinancialTransactionDetail models
            if (_futureTransaction == null)
            {
                var doesHaveForeignCurrency = financialTransaction.ForeignCurrencyCodeValueId != null;

                foreach (var detailArgs in _automatedPaymentArgs.AutomatedPaymentDetails)
                {
                    var transactionDetail = new FinancialTransactionDetail
                    {
                        Amount    = detailArgs.Amount,
                        AccountId = detailArgs.AccountId
                    };

                    if (doesHaveForeignCurrency)
                    {
                        transactionDetail.ForeignCurrencyAmount = detailArgs.Amount;
                    }

                    financialTransaction.TransactionDetails.Add(transactionDetail);
                }

                if (doesHaveForeignCurrency)
                {
                    /*
                     * The amount coming from the gateway is always in the Organization's currency.
                     * As such the Amount value could be different than the original amount passed in if the
                     * specified currency code is different then the Organization's currency code.
                     */
                    financialTransaction.SetApportionedDetailAmounts(_payment.Amount);
                }
            }

            // New transactions and future transactions need fee info
            financialTransaction.SetApportionedFeesOnDetails(_payment.FeeAmount);

            // Get an existing or new batch according to the name prefix and payment type
            FinancialBatch batch;

            if (!financialTransaction.BatchId.HasValue)
            {
                batch = _financialBatchService.Get(
                    _automatedPaymentArgs.BatchNamePrefix ?? "Online Giving",
                    string.Empty,
                    _referencePaymentInfo.CurrencyTypeValue,
                    _referencePaymentInfo.CreditCardTypeValue,
                    financialTransaction.TransactionDateTime ?? financialTransaction.FutureProcessingDateTime.Value,
                    _financialGateway.GetBatchTimeOffset(),
                    _financialGateway.BatchDayOfWeek);
            }
            else
            {
                batch = _financialBatchService.Get(financialTransaction.BatchId.Value);
            }

            var batchChanges = new History.HistoryChangeList();
            var isNewBatch   = batch.Id == 0;

            // If this is a new Batch, SaveChanges so that we can get the Batch.Id and also
            // add history entries about the batch creation
            if (isNewBatch)
            {
                batchChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "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);

                _rockContext.SaveChanges();
            }

            if (_futureTransaction == null)
            {
                // Use the financialTransactionService to add the transaction instead of batch.Transactions
                // to avoid lazy-loading the transactions already associated with the batch
                financialTransaction.BatchId = batch.Id;
                _financialTransactionService.Add(financialTransaction);
            }

            _rockContext.SaveChanges();

            if (_futureTransaction == null)
            {
                // Update the batch control amount
                _financialBatchService.IncrementControlAmount(batch.Id, financialTransaction.TotalAmount, batchChanges);
                _rockContext.SaveChanges();
            }

            // Save the changes history for the batch
            HistoryService.SaveChanges(
                _rockContext,
                typeof(FinancialBatch),
                SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                batch.Id,
                batchChanges
                );

            return(financialTransaction);
        }
        /// <summary>
        /// Handles the Click event of the btnConfirm 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 btnConfirm_Click(object sender, EventArgs e)
        {
            // send signalR message to start progress indicator
            int progress = 0;

            _hubContext.Clients.All.receiveNotification(signalREventName, "0");

            XDocument xml       = null;
            int?      total     = null;
            int?      batchId   = null;
            string    batchName = string.Empty;

            int?attributeId      = null;
            int?binaryFileTypeId = null;

            using (var rockContext = new RockContext())
            {
                // Get the XML
                var binaryFile = new BinaryFileService(rockContext).Get(_binaryFileId.Value);
                if (binaryFile != null)
                {
                    using (var stream = binaryFile.ContentStream)
                    {
                        xml = XDocument.Load(stream);
                    }
                }

                // Get the number of transactions
                if (xml != null)
                {
                    total = xml.Root.Descendants().Where(n => n.Name == "Gift").Count();
                }

                if (xml != null && total.HasValue && total.Value > 0)
                {
                    var            batchService = new FinancialBatchService(rockContext);
                    FinancialBatch batch        = null;

                    // Load (or create) the batch
                    batchId = ddlBatch.SelectedValueAsInt();
                    if (batchId.HasValue)
                    {
                        batch = batchService.Get(batchId.Value);
                    }

                    if (batch == null)
                    {
                        batch                    = new FinancialBatch();
                        batch.Guid               = Guid.NewGuid();
                        batch.Name               = Path.GetFileNameWithoutExtension(binaryFile.FileName);
                        batch.Status             = BatchStatus.Open;
                        batch.BatchStartDateTime = RockDateTime.Today;
                        batch.BatchEndDateTime   = batch.BatchStartDateTime.Value.AddDays(1);
                        batch.ControlAmount      = 0;
                        batchService.Add(batch);

                        rockContext.SaveChanges();

                        batchId = batch.Id;
                    }

                    batchName = batch.Name;

                    // Get the attribute id for the envelop number attribute
                    int?personEntityTypeId = EntityTypeCache.GetId <Rock.Model.Person>();
                    attributeId = new AttributeService(rockContext)
                                  .Queryable().AsNoTracking()
                                  .Where(a =>
                                         a.EntityTypeId == personEntityTypeId &&
                                         a.Key == "GivingEnvelopeNumber")
                                  .Select(a => a.Id)
                                  .FirstOrDefault();

                    // Get the binary file type for contribution images
                    var binaryFileType = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE.AsGuid());
                    if (binaryFileType != null)
                    {
                        binaryFileTypeId = binaryFileType.Id;
                    }
                }
            }

            // Initialize the status variables
            int matchCount   = 0;
            int unmatchCount = 0;
            int errorCount   = 0;

            var allErrorMessages = new List <string>();

            // Process each transaction
            foreach (var node in xml.Root.Descendants().Where(n => n.Name == "Gift"))
            {
                var errorMessages = new List <string>();

                var status = ProcessTransaction(node, batchId, attributeId, binaryFileTypeId, out errorMessages);

                switch (status)
                {
                case ProcessStatus.Matched: matchCount++; break;

                case ProcessStatus.Unmatched: unmatchCount++; break;

                case ProcessStatus.Error: errorCount++; break;
                }

                allErrorMessages.AddRange(errorMessages);

                // Update progress using signalR
                progress++;
                int percentage = (progress * 100) / total.Value;
                _hubContext.Clients.All.receiveNotification(signalREventName, percentage.ToString("N0"));
            }

            // update success message to indicate the txns that were updated
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<li>{0:N0} {1} processed.</li>", total.Value, "transaction".PluralizeIf(total.Value > 1));
            sb.AppendFormat("<li>{0:N0} {1} matched to an existing person.</li>", matchCount,
                            (matchCount == 1 ? "transaction was" : "transactions were"));
            sb.AppendFormat("<li>{0:N0} {1} NOT matched to an existing person.</li>", unmatchCount,
                            (unmatchCount == 1 ? "transaction was" : "transactions were"));
            if (errorCount > 0)
            {
                sb.AppendFormat("<li>{0:N0} {1} NOT imported due to error during import (see errors below).</li>", errorCount,
                                (errorCount == 1 ? "transaction was" : "transactions were"));
            }

            using (var rockContext = new RockContext())
            {
                var batch = new FinancialBatchService(rockContext).Get(batchId.Value);
                if (batch != null)
                {
                    // update batch control amount
                    batch.ControlAmount += _totalAmount;
                    rockContext.SaveChanges();

                    // Add link to batch
                    var qryParam = new Dictionary <string, string>();
                    qryParam.Add("batchId", batchId.ToString());
                    string batchUrl  = LinkedPageUrl("BatchDetailPage", qryParam);
                    string batchLink = string.Format("<a href='{0}'>{1}</a>", batchUrl, batch.Name);

                    int    totalTransactions = matchCount + unmatchCount;
                    string summaryformat     = totalTransactions == 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, totalTransactions.ToString("N0"), _totalAmount.FormatAsCurrency(), batchLink);
                }
            }

            nbSuccess.Text = string.Format("<ul>{0}</ul>", sb.ToString());

            // Display any errors that occurred
            if (allErrorMessages.Any())
            {
                StringBuilder sbErrors = new StringBuilder();
                foreach (var errorMsg in allErrorMessages)
                {
                    sbErrors.AppendFormat("<li>{0}</li>", errorMsg);
                }

                nbErrors.Text    = string.Format("<ul>{0}</ul>", sbErrors.ToString());
                nbErrors.Visible = true;
            }
            else
            {
                nbErrors.Visible = false;
            }

            ShowResults();
        }
        //
        // 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);
            }
        }
Пример #20
0
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            var            rockContext  = new RockContext();
            var            batchService = new FinancialBatchService(rockContext);
            FinancialBatch batch        = null;

            var changes = new List <string>();

            int batchId = hfBatchId.Value.AsInteger();

            if (batchId == 0)
            {
                batch = new FinancialBatch();
                batchService.Add(batch);
                changes.Add("Created the batch");
            }
            else
            {
                batch = batchService.Get(batchId);
            }

            if (batch != null)
            {
                History.EvaluateChange(changes, "Batch Name", batch.Name, tbName.Text);
                batch.Name = tbName.Text;

                BatchStatus batchStatus = (BatchStatus)ddlStatus.SelectedIndex;
                History.EvaluateChange(changes, "Status", batch.Status, batchStatus);
                batch.Status = batchStatus;

                CampusCache oldCampus = null;
                if (batch.CampusId.HasValue)
                {
                    oldCampus = CampusCache.Read(batch.CampusId.Value);
                }
                CampusCache newCampus = null;
                if (campCampus.SelectedCampusId.HasValue)
                {
                    newCampus = CampusCache.Read(campCampus.SelectedCampusId.Value);
                }
                History.EvaluateChange(changes, "Campus", oldCampus != null ? oldCampus.Name : "None", newCampus != null ? newCampus.Name : "None");
                batch.CampusId = campCampus.SelectedCampusId;

                DateTime?startDateTime = dtpStart.SelectedDateTimeIsBlank ? null : dtpStart.SelectedDateTime;
                History.EvaluateChange(changes, "Start Date/Time", batch.BatchStartDateTime, startDateTime);
                batch.BatchStartDateTime = startDateTime;

                DateTime?endDateTime;
                if (dtpEnd.SelectedDateTimeIsBlank && batch.BatchStartDateTime.HasValue)
                {
                    endDateTime = batch.BatchStartDateTime.Value.AddDays(1);
                }
                else
                {
                    endDateTime = dtpEnd.SelectedDateTimeIsBlank ? null : dtpEnd.SelectedDateTime;
                }
                History.EvaluateChange(changes, "End Date/Time", batch.BatchEndDateTime, endDateTime);
                batch.BatchEndDateTime = endDateTime;

                decimal controlAmount = tbControlAmount.Text.AsDecimal();
                History.EvaluateChange(changes, "Control Amount", batch.ControlAmount.FormatAsCurrency(), controlAmount.FormatAsCurrency());
                batch.ControlAmount = controlAmount;

                History.EvaluateChange(changes, "Accounting System Code", batch.AccountingSystemCode, tbAccountingCode.Text);
                batch.AccountingSystemCode = tbAccountingCode.Text;

                History.EvaluateChange(changes, "Notes", batch.Note, tbNote.Text);
                batch.Note = tbNote.Text;

                cvBatch.IsValid = batch.IsValid;
                if (!Page.IsValid || !batch.IsValid)
                {
                    cvBatch.ErrorMessage = batch.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                    return;
                }

                rockContext.WrapTransaction(() =>
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                batch.Id,
                                changes);
                        }
                    }
                });

                if (batchId == 0)
                {
                    // If created a new batch, navigate to same page so that transaction list displays correctly
                    var pageReference = CurrentPageReference;
                    pageReference.Parameters.AddOrReplace("batchId", batch.Id.ToString());
                    NavigateToPage(pageReference);
                }
                else
                {
                    hfBatchId.SetValue(batch.Id);

                    // Requery the batch to support EF navigation properties
                    var savedBatch = GetBatch(batch.Id);

                    ShowReadonlyDetails(savedBatch);
                }
            }
        }