示例#1
0
        /// <summary>
        /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
        /// </summary>
        /// <param name="eventArgument">A <see cref="T:System.String" /> that represents an optional event argument to be passed to the event handler.</param>
        public void RaisePostBackEvent(string eventArgument)
        {
            if (eventArgument == "StatusUpdate" &&
                ddlAction != null &&
                ddlAction.SelectedValue != null &&
                !string.IsNullOrWhiteSpace(ddlAction.SelectedValue))
            {
                var batchesSelected = new List <int>();

                gBatchList.SelectedKeys.ToList().ForEach(b => batchesSelected.Add(b.ToString().AsInteger()));

                if (batchesSelected.Any())
                {
                    var newStatus = ddlAction.SelectedValue == "OPEN" ? BatchStatus.Open : BatchStatus.Closed;

                    var rockContext     = new RockContext();
                    var batchService    = new FinancialBatchService(rockContext);
                    var batchesToUpdate = batchService.Queryable()
                                          .Where(b =>
                                                 batchesSelected.Contains(b.Id) &&
                                                 b.Status != newStatus)
                                          .ToList();

                    foreach (var batch in batchesToUpdate)
                    {
                        batch.Status = newStatus;
                    }

                    rockContext.SaveChanges();

                    nbResult.Text = string.Format(
                        "{0} batches were {1}.",
                        batchesToUpdate.Count().ToString("N0"),
                        newStatus == BatchStatus.Open ? "opened" : "closed");

                    nbResult.NotificationBoxType = NotificationBoxType.Success;
                    nbResult.Visible             = true;
                }
                else
                {
                    nbResult.Text = string.Format("There were not any batches selected.");
                    nbResult.NotificationBoxType = NotificationBoxType.Warning;
                    nbResult.Visible             = true;
                }

                ddlAction.SelectedIndex = 0;
                BindGrid();
            }
        }
示例#2
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var batchService = new FinancialBatchService(new RockContext());
            var batches      = batchService.Queryable();

            if (dpBatchDate.SelectedDate.HasValue)
            {
                batches = batches.Where(batch => batch.BatchStartDateTime >= dpBatchDate.SelectedDate);
            }

            string status = gfBatchFilter.GetUserPreference("Status");

            if (!string.IsNullOrWhiteSpace(status))
            {
                var batchStatus = (BatchStatus)Enum.Parse(typeof(BatchStatus), status);
                batches = batches.Where(batch => batch.Status == batchStatus);
            }

            if (!string.IsNullOrEmpty(tbTitle.Text))
            {
                batches = batches.Where(batch => batch.Name == tbTitle.Text);
            }

            if (campCampus.SelectedCampusId.HasValue)
            {
                batches = batches.Where(batch => batch.CampusId == campCampus.SelectedCampusId.Value);
            }

            SortProperty sortProperty = gBatchList.SortProperty;

            if (sortProperty != null)
            {
                gBatchList.DataSource = batches.Sort(sortProperty).ToList();
            }
            else
            {
                gBatchList.DataSource = batches.OrderBy(batch => batch.Name).ToList();
            }

            gBatchList.DataBind();
        }
示例#3
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var          batchService = new FinancialBatchService();
            var          batches      = batchService.Queryable();
            SortProperty sortProperty = rGridBatch.SortProperty;

            if (dtBatchDate.SelectedDate.HasValue)
            {
                batches = batches.Where(batch => batch.BatchStartDateTime >= dtBatchDate.SelectedDate);
            }

            if ((ddlStatus.SelectedValueAsInt() ?? 0) > 0)
            {
                var batchStatus = ddlStatus.SelectedValueAsEnum <BatchStatus>();
                batches = batches.Where(Batch => Batch.Status == batchStatus);
            }

            if (!string.IsNullOrEmpty(txtTitle.Text))
            {
                batches = batches.Where(Batch => Batch.Name == txtTitle.Text);
            }

            if (ddlCampus.SelectedCampusId.HasValue)
            {
                batches = batches.Where(Batch => Batch.CampusId == ddlCampus.SelectedCampusId.Value);
            }

            if (sortProperty != null)
            {
                rGridBatch.DataSource = batches.Sort(sortProperty).ToList();
            }
            else
            {
                rGridBatch.DataSource = batches.OrderBy(b => b.Name).ToList();
            }

            rGridBatch.DataBind();
        }
示例#4
0
        private List <BatchRow> GetData()
        {
            var batchService = new FinancialBatchService(new RockContext());
            var qry          = batchService.Queryable()
                               .Where(b => b.BatchStartDateTime.HasValue);

            // filter by date
            string dateRangeValue = gfBatchFilter.GetUserPreference("Date Range");

            if (!string.IsNullOrWhiteSpace(dateRangeValue))
            {
                var drp = new DateRangePicker();
                drp.DelimitedValues = dateRangeValue;
                if (drp.LowerValue.HasValue)
                {
                    qry = qry.Where(b => b.BatchStartDateTime >= drp.LowerValue);
                }

                if (drp.UpperValue.HasValue)
                {
                    var endOfDay = drp.UpperValue.Value.AddDays(1);
                    qry = qry.Where(b => b.BatchStartDateTime < drp.UpperValue);
                }
            }

            // filter by status
            var status = gfBatchFilter.GetUserPreference("Status").ConvertToEnumOrNull <BatchStatus>();

            if (status.HasValue)
            {
                qry = qry.Where(b => b.Status == status);
            }

            // filter by title
            string title = gfBatchFilter.GetUserPreference("Title");

            if (!string.IsNullOrEmpty(title))
            {
                qry = qry.Where(batch => batch.Name.StartsWith(title));
            }

            // filter by accounting code
            if (tbAccountingCode.Visible)
            {
                string accountingCode = gfBatchFilter.GetUserPreference("Accounting Code");
                if (!string.IsNullOrEmpty(accountingCode))
                {
                    qry = qry.Where(batch => batch.AccountingSystemCode.StartsWith(accountingCode));
                }
            }

            // filter by campus
            var campus = CampusCache.Read(gfBatchFilter.GetUserPreference("Campus").AsInteger());

            if (campus != null)
            {
                qry = qry.Where(b => b.CampusId == campus.Id);
            }

            IOrderedQueryable <FinancialBatch> sortedQry = null;

            SortProperty sortProperty = gBatchList.SortProperty;

            if (sortProperty != null)
            {
                switch (sortProperty.Property)
                {
                case "TransactionCount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Count());
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Count());
                    }

                    break;
                }

                case "TransactionAmount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }

                    break;
                }

                default:
                {
                    sortedQry = qry.Sort(sortProperty);
                    break;
                }
                }
            }
            else
            {
                sortedQry = qry
                            .OrderByDescending(b => b.BatchStartDateTime)
                            .ThenBy(b => b.Name);
            }

            return(sortedQry
                   .Select(b => new BatchRow
            {
                Id = b.Id,
                BatchStartDateTime = b.BatchStartDateTime.Value,
                Name = b.Name,
                AccountingSystemCode = b.AccountingSystemCode,
                TransactionCount = b.Transactions.Count(),
                TransactionAmount = b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M,
                ControlAmount = b.ControlAmount,
                CampusName = b.Campus != null ? b.Campus.Name : "",
                Status = b.Status,
                UnMatchedTxns = b.Transactions.Any(t => !t.AuthorizedPersonAliasId.HasValue)
            })
                   .ToList());
        }
        /// <summary>
        /// Gets the query.  Set the timeout to 90 seconds in case the user
        /// has not set any filters and they've imported N years worth of
        /// batch data into Rock.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private IOrderedQueryable <FinancialBatch> GetQuery(RockContext rockContext)
        {
            var batchService = new FinancialBatchService(rockContext);

            rockContext.Database.CommandTimeout = 90;
            var qry = batchService.Queryable()
                      .Where(b => b.BatchStartDateTime.HasValue);

            // filter by date
            string dateRangeValue = gfBatchFilter.GetUserPreference("Date Range");

            if (!string.IsNullOrWhiteSpace(dateRangeValue))
            {
                var drp = new DateRangePicker();
                drp.DelimitedValues = dateRangeValue;
                if (drp.LowerValue.HasValue)
                {
                    qry = qry.Where(b => b.BatchStartDateTime >= drp.LowerValue.Value);
                }

                if (drp.UpperValue.HasValue)
                {
                    var endOfDay = drp.UpperValue.Value.AddDays(1);
                    qry = qry.Where(b => b.BatchStartDateTime < endOfDay);
                }
            }

            // filter by status
            var status = gfBatchFilter.GetUserPreference("Status").ConvertToEnumOrNull <BatchStatus>();

            if (status.HasValue)
            {
                qry = qry.Where(b => b.Status == status);
            }

            // filter by batches that contain transactions of the specified transaction type
            var transactionTypeValueId = gfBatchFilter.GetUserPreference("Contains Transaction Type").AsIntegerOrNull();

            if (transactionTypeValueId.HasValue)
            {
                qry = qry.Where(a => a.Transactions.Any(t => t.TransactionTypeValueId == transactionTypeValueId.Value));
            }

            // filter by title
            string title = gfBatchFilter.GetUserPreference("Title");

            if (!string.IsNullOrEmpty(title))
            {
                qry = qry.Where(batch => batch.Name.StartsWith(title));
            }

            // filter by accounting code
            if (tbAccountingCode.Visible)
            {
                string accountingCode = gfBatchFilter.GetUserPreference("Accounting Code");
                if (!string.IsNullOrEmpty(accountingCode))
                {
                    qry = qry.Where(batch => batch.AccountingSystemCode.StartsWith(accountingCode));
                }
            }

            // filter by campus
            var campus = CampusCache.Read(gfBatchFilter.GetUserPreference("Campus").AsInteger());

            if (campus != null)
            {
                qry = qry.Where(b => b.CampusId == campus.Id);
            }

            // Filter query by any configured attribute filters
            if (AvailableAttributes != null && AvailableAttributes.Any())
            {
                var attributeValueService = new AttributeValueService(rockContext);
                var parameterExpression   = attributeValueService.ParameterExpression;

                foreach (var attribute in AvailableAttributes)
                {
                    var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());
                    if (filterControl != null)
                    {
                        var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter);
                        var expression   = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression);
                        if (expression != null)
                        {
                            var attributeValues = attributeValueService
                                                  .Queryable()
                                                  .Where(v => v.Attribute.Id == attribute.Id);

                            attributeValues = attributeValues.Where(parameterExpression, expression, null);

                            qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id));
                        }
                    }
                }
            }

            IOrderedQueryable <FinancialBatch> sortedQry = null;

            SortProperty sortProperty = gBatchList.SortProperty;

            if (sortProperty != null)
            {
                switch (sortProperty.Property)
                {
                case "TransactionCount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Count());
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Count());
                    }

                    break;
                }

                case "TransactionAmount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }

                    break;
                }

                default:
                {
                    sortedQry = qry.Sort(sortProperty);
                    break;
                }
                }
            }
            else
            {
                sortedQry = qry
                            .OrderByDescending(b => b.BatchStartDateTime)
                            .ThenBy(b => b.Name);
            }

            return(sortedQry);
        }
        /// <summary>
        /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
        /// </summary>
        /// <param name="eventArgument">A <see cref="T:System.String" /> that represents an optional event argument to be passed to the event handler.</param>
        public void RaisePostBackEvent(string eventArgument)
        {
            if (eventArgument == "StatusUpdate" &&
                ddlAction != null &&
                ddlAction.SelectedValue != null &&
                !string.IsNullOrWhiteSpace(ddlAction.SelectedValue))
            {
                var batchesSelected = new List <int>();

                gBatchList.SelectedKeys.ToList().ForEach(b => batchesSelected.Add(b.ToString().AsInteger()));

                if (batchesSelected.Any())
                {
                    var newStatus = ddlAction.SelectedValue == "OPEN" ? BatchStatus.Open : BatchStatus.Closed;

                    var rockContext     = new RockContext();
                    var batchService    = new FinancialBatchService(rockContext);
                    var batchesToUpdate = batchService.Queryable()
                                          .Where(b =>
                                                 batchesSelected.Contains(b.Id) &&
                                                 b.Status != newStatus)
                                          .ToList();

                    foreach (var batch in batchesToUpdate)
                    {
                        var changes = new List <string>();
                        History.EvaluateChange(changes, "Status", batch.Status, newStatus);

                        string errorMessage;
                        if (!batch.IsValidBatchStatusChange(batch.Status, newStatus, this.CurrentPerson, out errorMessage))
                        {
                            maWarningDialog.Show(errorMessage, ModalAlertType.Warning);
                            return;
                        }

                        if (batch.IsAutomated && batch.Status == BatchStatus.Pending && newStatus != BatchStatus.Pending)
                        {
                            errorMessage = string.Format("{0} is an automated batch and the status can not be modified when the status is pending. The system will automatically set this batch to OPEN when all transactions have been downloaded.", batch.Name);
                            maWarningDialog.Show(errorMessage, ModalAlertType.Warning);
                            return;
                        }

                        batch.Status = newStatus;

                        if (!batch.IsValid)
                        {
                            string message = string.Format("Unable to update status for the selected batches.<br/><br/>{0}", batch.ValidationResults.AsDelimited("<br/>"));
                            maWarningDialog.Show(message, ModalAlertType.Warning);
                            return;
                        }

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

                    rockContext.SaveChanges();

                    nbResult.Text = string.Format(
                        "{0} batches were {1}.",
                        batchesToUpdate.Count().ToString("N0"),
                        newStatus == BatchStatus.Open ? "opened" : "closed");

                    nbResult.NotificationBoxType = NotificationBoxType.Success;
                    nbResult.Visible             = true;
                }
                else
                {
                    nbResult.Text = string.Format("There were not any batches selected.");
                    nbResult.NotificationBoxType = NotificationBoxType.Warning;
                    nbResult.Visible             = true;
                }

                ddlAction.SelectedIndex = 0;
                BindGrid();
            }
        }
示例#7
0
        /// <summary>
        /// Gets the query.
        /// </summary>
        /// <returns></returns>
        private IOrderedQueryable <FinancialBatch> GetQuery()
        {
            var batchService = new FinancialBatchService(new RockContext());
            var qry          = batchService.Queryable()
                               .Where(b => b.BatchStartDateTime.HasValue);

            // filter by date
            string dateRangeValue = gfBatchFilter.GetUserPreference("Date Range");

            if (!string.IsNullOrWhiteSpace(dateRangeValue))
            {
                var drp = new DateRangePicker();
                drp.DelimitedValues = dateRangeValue;
                if (drp.LowerValue.HasValue)
                {
                    qry = qry.Where(b => b.BatchStartDateTime >= drp.LowerValue.Value);
                }

                if (drp.UpperValue.HasValue)
                {
                    var endOfDay = drp.UpperValue.Value.AddDays(1);
                    qry = qry.Where(b => b.BatchStartDateTime < endOfDay);
                }
            }

            // filter by status
            var status = gfBatchFilter.GetUserPreference("Status").ConvertToEnumOrNull <BatchStatus>();

            if (status.HasValue)
            {
                qry = qry.Where(b => b.Status == status);
            }

            // filter by batches that contain transactions of the specified transaction type
            var transactionTypeValueId = gfBatchFilter.GetUserPreference("Contains Transaction Type").AsIntegerOrNull();

            if (transactionTypeValueId.HasValue)
            {
                qry = qry.Where(a => a.Transactions.Any(t => t.TransactionTypeValueId == transactionTypeValueId.Value));
            }

            // filter by title
            string title = gfBatchFilter.GetUserPreference("Title");

            if (!string.IsNullOrEmpty(title))
            {
                qry = qry.Where(batch => batch.Name.StartsWith(title));
            }

            // filter by accounting code
            if (tbAccountingCode.Visible)
            {
                string accountingCode = gfBatchFilter.GetUserPreference("Accounting Code");
                if (!string.IsNullOrEmpty(accountingCode))
                {
                    qry = qry.Where(batch => batch.AccountingSystemCode.StartsWith(accountingCode));
                }
            }

            // filter by campus
            var campus = CampusCache.Read(gfBatchFilter.GetUserPreference("Campus").AsInteger());

            if (campus != null)
            {
                qry = qry.Where(b => b.CampusId == campus.Id);
            }

            IOrderedQueryable <FinancialBatch> sortedQry = null;

            SortProperty sortProperty = gBatchList.SortProperty;

            if (sortProperty != null)
            {
                switch (sortProperty.Property)
                {
                case "TransactionCount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Count());
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Count());
                    }

                    break;
                }

                case "TransactionAmount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }

                    break;
                }

                default:
                {
                    sortedQry = qry.Sort(sortProperty);
                    break;
                }
                }
            }
            else
            {
                sortedQry = qry
                            .OrderByDescending(b => b.BatchStartDateTime)
                            .ThenBy(b => b.Name);
            }

            return(sortedQry);
        }
示例#8
0
        /// <summary>
        /// Handles the Click event of the btnExportToShelbyFinancials 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 btnExportToShelbyFinancials_Click(object sender, EventArgs e)
        {
            Session["JournalType"]      = ddlJournalType.SelectedValue;
            Session["AccountingPeriod"] = tbAccountingPeriod.Text;

            var selectedBatches = new List <int>();

            gBatchesToExport.SelectedKeys.ToList().ForEach(b => selectedBatches.Add(b.ToString().AsInteger()));

            if (selectedBatches.Any())
            {
                var sfJournal = new SFJournal();
                var items     = new List <SFJournal.GLExcelLine>();
                var debugLava = GetAttributeValue("EnableDebug");

                var rockContext     = new RockContext();
                var batchService    = new FinancialBatchService(rockContext);
                var batchesToUpdate = new List <FinancialBatch>();

                var exportedBatches = batchService.Queryable()
                                      .WhereAttributeValue(rockContext, a => a.Attribute.Key == "rocks.kfs.ShelbyFinancials.DateExported" && (a.Value != null && a.Value != ""))
                                      .Select(b => b.Id)
                                      .ToList();

                batchesToUpdate = batchService.Queryable()
                                  .Where(b =>
                                         selectedBatches.Contains(b.Id) &&
                                         !exportedBatches.Contains(b.Id))
                                  .ToList();

                foreach (var batch in batchesToUpdate)
                {
                    var changes = new History.HistoryChangeList();
                    History.EvaluateChange(changes, "Status", batch.Status, BatchStatus.Closed);

                    string errorMessage;

                    if (batch.IsAutomated && batch.Status == BatchStatus.Pending)
                    {
                        errorMessage = string.Format("{0} is an automated batch and the status can not be modified when the status is pending. The system will automatically set this batch to OPEN when all transactions have been downloaded.", batch.Name);
                        maWarningDialog.Show(errorMessage, ModalAlertType.Warning);
                        return;
                    }

                    batch.Status = BatchStatus.Closed;

                    if (!batch.IsValid)
                    {
                        string message = string.Format("Unable to update status for the selected batches.<br/><br/>{0}", batch.ValidationResults.AsDelimited("<br/>"));
                        maWarningDialog.Show(message, ModalAlertType.Warning);
                        return;
                    }

                    batch.LoadAttributes();

                    var newDate = string.Empty;

                    var oldDate = batch.GetAttributeValue("rocks.kfs.ShelbyFinancials.DateExported");
                    newDate = RockDateTime.Now.ToString();
                    History.EvaluateChange(changes, "Date Exported", oldDate, newDate.ToString());

                    var journalCode = ddlJournalType.SelectedValue;
                    var period      = tbAccountingPeriod.Text.AsInteger();

                    items.AddRange(sfJournal.GetGLExcelLines(rockContext, batch, journalCode, period, ref debugLava, GetAttributeValue("JournalDescriptionLava")));

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

                    batch.SetAttributeValue("rocks.kfs.ShelbyFinancials.DateExported", newDate);
                    batch.SaveAttributeValue("rocks.kfs.ShelbyFinancials.DateExported", rockContext);
                }

                rockContext.SaveChanges();

                if (HttpContext.Current.Session["ShelbyFinancialsExcelExport"] != null)
                {
                    HttpContext.Current.Session["ShelbyFinancialsExcelExport"] = null;
                }
                if (HttpContext.Current.Session["ShelbyFinancialsFileId"] != null)
                {
                    HttpContext.Current.Session["ShelbyFinancialsFileId"] = string.Empty;
                }

                var excel = sfJournal.GLExcelExport(items);

                Session["ShelbyFinancialsExcelExport"] = excel;
                Session["ShelbyFinancialsFileId"]      = RockDateTime.Now.ToString("yyyyMMdd_HHmmss");
                Session["ShelbyFinancialsDebugLava"]   = debugLava;

                NavigateToPage(this.RockPage.Guid, new Dictionary <string, string>());
            }
            else
            {
                nbError.Text = string.Format("There were not any batches selected.");
                nbError.NotificationBoxType = NotificationBoxType.Warning;
                nbError.Visible             = true;
            }
        }
示例#9
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            btnExportToShelbyFinancials.Text = GetAttributeValue("ButtonText");
            var monthsBack     = GetAttributeValue("MonthsBack").AsInteger() * -1;
            var firstBatchDate = RockDateTime.Now.AddMonths(monthsBack);

            var batchIdList         = new List <int>();
            var filteredBatchIdList = new List <int>();
            var batchesToExport     = new List <BatchData>();

            using (var rockContextBatches = new RockContext())
            {
                var batchService = new FinancialBatchService(rockContextBatches);
                var qry          = batchService
                                   .Queryable().AsNoTracking()
                                   .Where(b => b.BatchStartDateTime.HasValue)
                                   .Where(b => b.BatchStartDateTime >= firstBatchDate)
                                   .Where(b => b.ControlAmount == b.Transactions.Sum(t => t.TransactionDetails.Sum(d => d.Amount)));

                string dateRangeValue = gfBatchesToExportFilter.GetUserPreference("Date Range");
                if (!string.IsNullOrWhiteSpace(dateRangeValue))
                {
                    var drp = new DateRangePicker();
                    drp.DelimitedValues = dateRangeValue;
                    if (drp.LowerValue.HasValue)
                    {
                        qry = qry.Where(b => b.BatchStartDateTime >= drp.LowerValue.Value);
                    }

                    if (drp.UpperValue.HasValue)
                    {
                        var endOfDay = drp.UpperValue.Value.AddDays(1);
                        qry = qry.Where(b => b.BatchStartDateTime < endOfDay);
                    }
                }

                var status = gfBatchesToExportFilter.GetUserPreference("Status").ConvertToEnumOrNull <BatchStatus>();
                if (status.HasValue)
                {
                    qry = qry.Where(b => b.Status == status);
                }

                SortProperty sortProperty = gBatchesToExport.SortProperty;
                if (sortProperty != null)
                {
                    qry = qry.Sort(sortProperty);
                }
                else
                {
                    qry = qry
                          .OrderByDescending(b => b.BatchStartDateTime)
                          .ThenBy(b => b.Name);
                }

                batchIdList = qry.Select(b => b.Id).ToList();
            }

            using (var rockContextAttributeValues = new RockContext())
            {
                var dateExportedAttributeId = AttributeCache.Get("4B6576DD-82F6-419F-8DF0-467D2636822D".AsGuid()).Id;    //rocks.kfs.ShelbyFinancials.DateExported

                foreach (var batchId in batchIdList)
                {
                    var attributeValue = new AttributeValueService(rockContextAttributeValues).GetByAttributeIdAndEntityId(dateExportedAttributeId, batchId);
                    if (attributeValue == null || attributeValue.ValueAsDateTime == null)
                    {
                        filteredBatchIdList.Add(batchId);
                    }
                }
            }

            using (var rockContextBatchData = new RockContext())
            {
                foreach (var batchId in filteredBatchIdList)
                {
                    var batch = new FinancialBatchService(rockContextBatchData).Get(batchId);

                    batchesToExport.Add(new BatchData
                    {
                        Id = batch.Id,
                        BatchStartDateTime = batch.BatchStartDateTime,
                        Name         = batch.Name,
                        Status       = batch.Status.ToString(),
                        Note         = batch.Note,
                        Transactions = batch.Transactions.Count,
                        Total        = batch.GetTotalTransactionAmount(rockContextBatchData)
                    });
                }
            }

            gBatchesToExport.DataSource   = batchesToExport;
            gBatchesToExport.ObjectList   = ((List <BatchData>)gBatchesToExport.DataSource).ToDictionary(b => b.Id.ToString(), v => v as object);
            gBatchesToExport.EntityTypeId = EntityTypeCache.Get <FinancialBatch>().Id;

            gBatchesToExport.DataBind();
        }
        /// <summary>
        /// Handles the Click event of the btnExportToFinancialEdge 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 btnExportToFinancialEdge_Click(object sender, EventArgs e)
        {
            var selectedBatches = new List <int>();

            gBatchesToExport.SelectedKeys.ToList().ForEach(b => selectedBatches.Add(b.ToString().AsInteger()));

            if (selectedBatches.Any())
            {
                var feJournal = new FEJournal();
                var items     = new List <JournalEntryLine>();

                var rockContext     = new RockContext();
                var batchService    = new FinancialBatchService(rockContext);
                var batchesToUpdate = new List <FinancialBatch>();

                var exportedBatches = batchService.Queryable()
                                      .WhereAttributeValue(rockContext, a => a.Attribute.Key == "rocks.kfs.FinancialEdge.DateExported" && (a.Value != null && a.Value != ""))
                                      .Select(b => b.Id)
                                      .ToList();

                batchesToUpdate = batchService.Queryable()
                                  .Where(b =>
                                         selectedBatches.Contains(b.Id) &&
                                         !exportedBatches.Contains(b.Id))
                                  .ToList();

                foreach (var batch in batchesToUpdate)
                {
                    var changes = new History.HistoryChangeList();
                    History.EvaluateChange(changes, "Status", batch.Status, BatchStatus.Closed);

                    string errorMessage;

                    if (batch.IsAutomated && batch.Status == BatchStatus.Pending)
                    {
                        errorMessage = string.Format("{0} is an automated batch and the status can not be modified when the status is pending. The system will automatically set this batch to OPEN when all transactions have been downloaded.", batch.Name);
                        maWarningDialog.Show(errorMessage, ModalAlertType.Warning);
                        return;
                    }

                    batch.Status = BatchStatus.Closed;

                    if (!batch.IsValid)
                    {
                        string message = string.Format("Unable to update status for the selected batches.<br/><br/>{0}", batch.ValidationResults.AsDelimited("<br/>"));
                        maWarningDialog.Show(message, ModalAlertType.Warning);
                        return;
                    }

                    batch.LoadAttributes();

                    var newDate = string.Empty;

                    var oldDate = batch.GetAttributeValue("rocks.kfs.FinancialEdge.DateExported");
                    newDate = RockDateTime.Now.ToString();
                    History.EvaluateChange(changes, "Date Exported", oldDate, newDate.ToString());

                    items.AddRange(feJournal.GetGlEntries(rockContext, batch, tbJournalType.Text));

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

                    batch.SetAttributeValue("rocks.kfs.FinancialEdge.DateExported", newDate);
                    batch.SaveAttributeValue("rocks.kfs.FinancialEdge.DateExported", rockContext);
                }

                rockContext.SaveChanges();

                feJournal.SetFinancialEdgeSessions(items, RockDateTime.Now.ToString("yyyyMMdd_HHmmss"));

                NavigateToPage(this.RockPage.Guid, new Dictionary <string, string>());
            }
            else
            {
                nbError.Text = string.Format("There were not any batches selected.");
                nbError.NotificationBoxType = NotificationBoxType.Warning;
                nbError.Visible             = true;
            }
        }