Esempio n. 1
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());
        }
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns()
        {
            var rockContext        = new RockContext();
            var financialBatchList = new FinancialBatchService(rockContext).Queryable()
                                     .Where(a => a.Status == BatchStatus.Open).OrderBy(a => a.Name).Select(a => new
            {
                a.Id,
                a.Name,
                a.BatchStartDateTime
            }).ToList();

            ddlBatch.Items.Clear();
            ddlBatch.Items.Add(new ListItem());
            foreach (var batch in financialBatchList)
            {
                ddlBatch.Items.Add(new ListItem(string.Format("#{0} {1} ({2})", batch.Id, batch.Name, batch.BatchStartDateTime.Value.ToString("d")), batch.Id.ToString()));
            }
        }
Esempio n. 3
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();
        }
Esempio n. 4
0
        /// <summary>
        /// Create a new payment processor to handle a single automated payment.
        /// </summary>
        /// <param name="currentPersonAliasId">The current user's person alias ID. Possibly the REST user.</param>
        /// <param name="automatedPaymentArgs">The arguments describing how to charge the payment and store the resulting transaction</param>
        /// <param name="rockContext">The context to use for loading and saving entities</param>
        /// <param name="enableDuplicateChecking">If false, the payment will be charged even if there is a similar transaction for the same person
        /// within a short time period.</param>
        /// <param name="enableScheduleAdherenceProtection">If false and a schedule is indicated in the args, the payment will be charged even if
        /// the schedule has already been processed according to it's frequency.</param>
        public AutomatedPaymentProcessor(int?currentPersonAliasId, AutomatedPaymentArgs automatedPaymentArgs, RockContext rockContext, bool enableDuplicateChecking = true, bool enableScheduleAdherenceProtection = true)
        {
            _rockContext                       = rockContext;
            _automatedPaymentArgs              = automatedPaymentArgs;
            _currentPersonAliasId              = currentPersonAliasId;
            _enableDuplicateChecking           = enableDuplicateChecking;
            _enableScheduleAdherenceProtection = enableScheduleAdherenceProtection;
            _futureTransaction                 = null;

            _personAliasService                   = new PersonAliasService(_rockContext);
            _financialGatewayService              = new FinancialGatewayService(_rockContext);
            _financialAccountService              = new FinancialAccountService(_rockContext);
            _financialPersonSavedAccountService   = new FinancialPersonSavedAccountService(_rockContext);
            _financialBatchService                = new FinancialBatchService(_rockContext);
            _financialTransactionService          = new FinancialTransactionService(_rockContext);
            _financialScheduledTransactionService = new FinancialScheduledTransactionService(_rockContext);

            _payment = null;
        }
Esempio n. 5
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();
        }
        /// <summary>
        /// Handles the Click event of the btnDone 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 lbFinish_Click(object sender, EventArgs e)
        {
            int?batchId = hfBatchId.Value.AsIntegerOrNull();

            if (batchId.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var batch = new FinancialBatchService(rockContext).Get(batchId.Value);
                    if (batch != null && batch.Status == BatchStatus.Pending)
                    {
                        batch.Status = BatchStatus.Open;
                        rockContext.SaveChanges();
                    }
                }

                NavigateToLinkedPage("BatchDetailPage", new Dictionary <string, string> {
                    { "BatchId", batchId.Value.ToString() }
                });
            }
        }
Esempio n. 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();
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            nbMessage.Visible = false;

            if (!Page.IsPostBack)
            {
                using (var rockContext = new RockContext())
                {
                    // Load dropdown list with all of the open batches
                    var batches = new FinancialBatchService(rockContext)
                                  .Queryable().AsNoTracking()
                                  .Where(b =>
                                         b.Status != BatchStatus.Closed &&
                                         b.BatchStartDateTime.HasValue)
                                  .OrderByDescending(b => b.BatchStartDateTime)
                                  .ThenBy(b => b.Name)
                                  .Select(b => new
                    {
                        b.Id,
                        b.Name,
                        b.BatchStartDateTime
                    })
                                  .ToList()
                                  .Select(b => new
                    {
                        b.Id,
                        Name = string.Format("{0} ({1})", b.Name, b.BatchStartDateTime.Value.ToShortDateString())
                    })
                                  .ToList();

                    ddlBatch.DataSource = batches;
                    ddlBatch.DataBind();
                    ddlBatch.Items.Insert(0, new ListItem("", ""));
                }

                ShowEntry();
            }
        }
        protected void lbExport_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var           batchId    = tbBatchId.Text.AsInteger();
                var           batches    = new FinancialBatchService(rockContext).Queryable().Where(b => b.Id == batchId).ToList();
                var           fileFormat = new ImageCashLetterFileFormatService(rockContext).Get(ddlFileFormat.SelectedValue.AsInteger());
                var           component  = FileFormatTypeContainer.GetComponent(fileFormat.EntityType.Name);
                List <string> errorMessages;

                fileFormat.LoadAttributes(rockContext);

                var mergeFields = new Dictionary <string, object>
                {
                    { "FileFormat", fileFormat }
                };
                var filename = fileFormat.FileNameTemplate.ResolveMergeFields(mergeFields);

                var stream = component.ExportBatches(fileFormat, batches, out errorMessages);

                var binaryFileService     = new BinaryFileService(rockContext);
                var binaryFileTypeService = new BinaryFileTypeService(rockContext);
                var binaryFile            = new BinaryFile
                {
                    BinaryFileTypeId = binaryFileTypeService.Get(Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid()).Id,
                    IsTemporary      = true,
                    FileName         = filename,
                    MimeType         = "octet/stream",
                    ContentStream    = stream
                };

                binaryFileService.Add(binaryFile);
                rockContext.SaveChanges();

                pnlSuccess.Visible     = true;
                hlDownload.NavigateUrl = ResolveUrl(string.Format("~/GetFile.ashx?Id={0}&attachment=True", binaryFile.Id));
            }
        }
Esempio n. 10
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();
        }
        public IEnumerable <ControlTotalResult> GetControlTotals(System.Web.Http.OData.Query.ODataQueryOptions <FinancialBatch> queryOptions = null)
        {
            var financialBatchQuery = new FinancialBatchService(this.Service.Context as Rock.Data.RockContext).Queryable();

            financialBatchQuery = queryOptions.ApplyTo(financialBatchQuery) as IOrderedQueryable <FinancialBatch>;

            var batchControlTotalsQuery = financialBatchQuery.SelectMany(a => a.Transactions).Where(a => a.BatchId.HasValue).GroupBy(a => a.BatchId.Value).Select(a => new
            {
                BatchId = a.Key,
                TransactionTotalAmounts = a.Select(x => x.TransactionDetails.Sum(d => (decimal?)d.Amount))
            });

            var batchControlTotalsList = batchControlTotalsQuery.ToList();

            var controlTotalsList = batchControlTotalsList.Select(a => new ControlTotalResult
            {
                FinancialBatchId   = a.BatchId,
                ControlTotalCount  = a.TransactionTotalAmounts.Count(),
                ControlTotalAmount = a.TransactionTotalAmounts.Sum(x => (decimal?)x) ?? 0
            }).ToList();

            return(controlTotalsList);
        }
Esempio n. 12
0
        /// <summary>
        /// Handles the Click event of the lbDownload 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 lbDownload_Click(object sender, EventArgs e)
        {
            var parameters = RockPage.PageParameters();

            var records = GLRecordsForBatch(_batch, dpDate.SelectedDate.Value, tbAccountingPeriod.Text.Trim(), tbJournalType.Text.Trim());

            if (!UserCanEdit)
            {
                return;
            }

            //
            // Update the batch to reflect that it has been exported.
            //
            using (var rockContext = new RockContext())
            {
                FinancialBatch batch = new FinancialBatchService(rockContext).Get(_batch.Id);

                batch.LoadAttributes();
                batch.SetAttributeValue("GLExported", "true");
                batch.SaveAttributeValues(rockContext);
                IsExported = 1;

                rockContext.SaveChanges();
            }

            //
            // Send the results as a CSV file for download.
            //
            Page.EnableViewState = false;
            Page.Response.Clear();
            Page.Response.ContentType = "text/plain";
            Page.Response.AppendHeader("Content-Disposition", "attachment; filename=GLTRN2000.txt");
            Page.Response.Write(string.Join("\r\n", records.Select(r => r.ToString()).ToArray()));
            Page.Response.Flush();
            Page.Response.End();
        }
Esempio n. 13
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();
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var batchId = PageParameter("batchId").AsInteger();

            if (!Page.IsPostBack)
            {
                ShowDetail(batchId);
            }

            // Add any attribute controls.
            // This must be done here regardless of whether it is a postback so that the attribute values will get saved.
            var financialBatch = new FinancialBatchService(new RockContext()).Get(batchId);

            if (financialBatch == null)
            {
                financialBatch = new FinancialBatch();
            }

            financialBatch.LoadAttributes();
            phAttributes.Controls.Clear();
            Helper.AddEditControls(financialBatch, phAttributes, true, BlockValidationGroup);
        }
Esempio n. 15
0
        /// <summary>
        /// Create a new payment processor to handle a single automated payment from a future transaction (probably generated from text-to-give).
        /// </summary>
        /// <param name="futureTransaction">The transaction with a FutureProcessingDateTime</param>
        /// <param name="rockContext">The context to use for loading and saving entities</param>
        public AutomatedPaymentProcessor(FinancialTransaction futureTransaction, RockContext rockContext)
        {
            _rockContext          = rockContext;
            _automatedPaymentArgs = null;
            _currentPersonAliasId = futureTransaction.CreatedByPersonAliasId;
            _futureTransaction    = futureTransaction;

            // The job charging these future transactions could have a variable run frequency and be charging a days worth at a time, so the duplicate
            // checking could very easily provide false positives. Therefore, we rely on the "dry-run" to have previously validated
            _enableDuplicateChecking           = false; // These future transactions should have already had a "dry-run" and been validated.
            _enableScheduleAdherenceProtection = false; // These future transactions should have already had a "dry-run" and been validated

            _personAliasService                   = new PersonAliasService(_rockContext);
            _financialGatewayService              = new FinancialGatewayService(_rockContext);
            _financialAccountService              = new FinancialAccountService(_rockContext);
            _financialPersonSavedAccountService   = new FinancialPersonSavedAccountService(_rockContext);
            _financialBatchService                = new FinancialBatchService(rockContext);
            _financialTransactionService          = new FinancialTransactionService(_rockContext);
            _financialScheduledTransactionService = new FinancialScheduledTransactionService(_rockContext);

            _payment = null;

            CopyFutureTransactionToArgs();
        }
Esempio n. 16
0
        /// <summary>
        /// Maps the batch data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private void MapBatch(IQueryable <Row> tableData, long totalRows = 0)
        {
            var newBatches = new List <FinancialBatch>();

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var earliestBatchDate = ImportDateTime;
            var completedItems    = 0;
            var percentage        = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying batch import ({totalRows:N0} found, {ImportedBatches.Count:N0} already exist).");
            foreach (var row in tableData.Where(r => r != null))
            {
                var batchId = row["BatchID"] as int?;
                if (batchId.HasValue && !ImportedBatches.ContainsKey(( int )batchId))
                {
                    var batch = new FinancialBatch
                    {
                        CreatedByPersonAliasId = ImportPersonAliasId,
                        ForeignKey             = batchId.ToString(),
                        ForeignId            = batchId,
                        Note                 = string.Empty,
                        Status               = BatchStatus.Closed,
                        AccountingSystemCode = string.Empty
                    };

                    var name = row["BatchName"] as string;
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        name           = name.Trim();
                        batch.Name     = name.Truncate(50);
                        batch.CampusId = GetCampusId(name);
                    }

                    var batchDate = row["BatchDate"] as DateTime?;
                    if (batchDate.HasValue)
                    {
                        batch.BatchStartDateTime = batchDate;
                        batch.BatchEndDateTime   = batchDate;

                        if (batchDate < earliestBatchDate)
                        {
                            earliestBatchDate = ( DateTime )batchDate;
                        }
                    }

                    var amount = row["BatchAmount"] as decimal?;
                    if (amount.HasValue)
                    {
                        batch.ControlAmount = amount.Value;
                    }

                    newBatches.Add(batch);
                    completedItems++;
                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems:N0} batches imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveFinancialBatches(newBatches);
                        newBatches.ForEach(b => ImportedBatches.Add(( int )b.ForeignId, ( int? )b.Id));
                        newBatches.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            // add a default batch to use with contributions
            if (!ImportedBatches.ContainsKey(0))
            {
                var defaultBatch = new FinancialBatch
                {
                    CreatedDateTime        = ImportDateTime,
                    CreatedByPersonAliasId = ImportPersonAliasId,
                    BatchStartDateTime     = earliestBatchDate,
                    Status        = BatchStatus.Closed,
                    Name          = $"Default Batch (Imported {ImportDateTime})",
                    ControlAmount = 0.0m,
                    ForeignKey    = "0",
                    ForeignId     = 0
                };

                newBatches.Add(defaultBatch);
            }

            if (newBatches.Any())
            {
                SaveFinancialBatches(newBatches);
                newBatches.ForEach(b => ImportedBatches.Add(( int )b.ForeignId, ( int? )b.Id));
            }

            ImportedBatches = new FinancialBatchService(new RockContext()).Queryable().AsNoTracking()
                              .Where(b => b.ForeignId.HasValue)
                              .ToDictionary(t => ( int )t.ForeignId, t => ( int? )t.Id);

            ReportProgress(100, $"Finished batch import: {completedItems:N0} batches imported.");
        }
Esempio n. 17
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());
        }
Esempio n. 18
0
        /// <summary>Process all transactions (payments) from Service Reef.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext                 dbContext                   = new RockContext();
            FinancialBatchService       financialBatchService       = new FinancialBatchService(dbContext);
            PersonService               personService               = new PersonService(dbContext);
            PersonAliasService          personAliasService          = new PersonAliasService(dbContext);
            FinancialAccountService     financialAccountService     = new FinancialAccountService(dbContext);
            FinancialAccountService     accountService              = new FinancialAccountService(dbContext);
            FinancialTransactionService financialTransactionService = new FinancialTransactionService(dbContext);
            FinancialGatewayService     financialGatewayService     = new FinancialGatewayService(dbContext);
            DefinedValueService         definedValueService         = new DefinedValueService(dbContext);
            DefinedTypeService          definedTypeService          = new DefinedTypeService(dbContext);
            TransactionService          transactionService          = new TransactionService(new PayPalReporting.Data.PayPalReportingContext());

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            String warnings = string.Empty;

            FinancialBatch batch       = null;
            Double         totalAmount = 0;
            var            total       = 1;
            var            processed   = 0;

            try
            {
                DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||");

                String            SRApiKey          = Encryption.DecryptString(dataMap.GetString("ServiceReefAPIKey"));
                String            SRApiSecret       = Encryption.DecryptString(dataMap.GetString("ServiceReefAPISecret"));
                String            SRApiUrl          = dataMap.GetString("ServiceReefAPIURL");
                DefinedValueCache transactionSource = DefinedValueCache.Read(dataMap.GetString("TransactionSource").AsGuid(), dbContext);
                DefinedValueCache connectionStatus  = DefinedValueCache.Read(dataMap.GetString("ConnectionStatus").AsGuid(), dbContext);
                DefinedValueCache contribution      = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION);

                // Setup some lookups
                DefinedTypeCache        creditCards = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE.AsGuid(), dbContext);
                DefinedTypeCache        tenderType  = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE.AsGuid(), dbContext);
                FinancialAccount        specialFund = accountService.Get(dataMap.GetString("Account").AsGuid());
                FinancialGateway        gateway     = financialGatewayService.Get(dataMap.GetString("FinancialGateway").AsGuid());
                List <FinancialAccount> trips       = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList();

                // Get the trips
                DefinedValueCache serviceReefAccountType = DefinedValueCache.Get(dataMap.Get("ServiceReefAccountType").ToString().AsGuid());

                // Setup the ServiceReef API Client
                var client = new RestClient(SRApiUrl);
                client.Authenticator = new HMACAuthenticator(SRApiKey, SRApiSecret);

                // Get all payments from ServiceReef
                var request = new RestRequest("v1/payments", Method.GET);
                request.AddParameter("pageSize", 100);
                if (dateRange.Start.HasValue)
                {
                    request.AddParameter("startDate", dateRange.Start.Value.ToString("o"));
                }
                if (dateRange.End.HasValue)
                {
                    request.AddParameter("endDate", dateRange.End.Value.ToString("o"));
                }
                request.AddParameter("page", 1);

                while (total > processed)
                {
                    var response = client.Execute <Contracts.Payments>(request);
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        throw new Exception("ServiceReef API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength);
                    }
                    if (response.Data != null && response.Data.PageInfo != null)
                    {
                        total = response.Data.PageInfo.TotalRecords;
                        foreach (Contracts.Payments.Result result in response.Data.Results)
                        {
                            // Process the transaction
                            if (result.PaymentProcessorTransactionId != null)
                            {
                                if (result.FirstName == null || result.LastName == null)
                                {
                                    warnings += "Missing Firstname/Lastname for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine;
                                    processed++;
                                    continue;
                                }
                                FinancialAccount trip = null;
                                // Make sure we have a sub-account to go with this transaction
                                if (result.EventId > 0)
                                {
                                    trip = trips.Where(t => t.GlCode == result.EventCode && t.Url == result.EventUrl).FirstOrDefault();
                                }
                                if (trip == null)
                                {
                                    if (result.EventCode == null)
                                    {
                                        warnings += "Event Code is missing on the Service Reef Trip for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine;
                                        processed++;
                                        continue;
                                    }

                                    // Create the trip subaccount
                                    FinancialAccount tripFA = new FinancialAccount();
                                    tripFA.Name = result.EventName;
                                    // Name is limited to 50
                                    if (tripFA.Name.Length > 50)
                                    {
                                        tripFA.Name = tripFA.Name.Substring(0, 50);
                                    }
                                    tripFA.Description = "Service Reef Event.  Name: " + result.EventName + " ID: " + result.EventId;
                                    tripFA.GlCode      = result.EventCode;
                                    tripFA.Url         = result.EventUrl;
                                    tripFA.PublicName  = result.EventName;
                                    // Public Name is limited to 50
                                    if (tripFA.PublicName.Length > 50)
                                    {
                                        tripFA.PublicName = tripFA.PublicName.Substring(0, 50);
                                    }
                                    tripFA.IsTaxDeductible    = true;
                                    tripFA.IsPublic           = false;
                                    tripFA.ParentAccountId    = specialFund.Id;
                                    tripFA.Order              = specialFund.Order + 1;
                                    tripFA.AccountTypeValueId = serviceReefAccountType.Id;
                                    // Figure out what order it should be;
                                    foreach (FinancialAccount tmpTrip in trips)
                                    {
                                        if (tmpTrip.Name.CompareTo(tripFA.Name) < 0)
                                        {
                                            tripFA.Order++;
                                        }
                                    }

                                    financialAccountService.Add(tripFA);

                                    // Now save the trip
                                    dbContext.SaveChanges();
                                    // Increment all the rest of the Orders
                                    financialAccountService.Queryable().Where(fa => fa.Order >= tripFA.Order && fa.Id != tripFA.Id).ToList().ForEach(c => c.Order++);
                                    dbContext.SaveChanges();
                                    trips = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList();
                                    trip  = tripFA;
                                }

                                FinancialTransaction tran = financialTransactionService.Queryable().Where(tx => tx.TransactionCode == result.PaymentProcessorTransactionId).FirstOrDefault();

                                // We haven't processed this before so get busy!
                                if (tran == null)
                                {
                                    tran = new FinancialTransaction();
                                    tran.FinancialPaymentDetail = new FinancialPaymentDetail();
                                    if (result.Type == "CreditCard")
                                    {
                                        tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id;
                                    }
                                    else
                                    {
                                        tran.TransactionTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id;
                                    }

                                    Person person = null;
                                    // Find the person this transaction belongs to
                                    // 1. First start by determining whether this was a person
                                    //    paying their application fee or contributing to themselves
                                    //    because then we can just use their member info
                                    if (result.UserId > 0 &&
                                        result.DonatedToUserId == result.UserId &&
                                        result.DonatedToFirstName == result.FirstName &&
                                        result.DonatedToLastName == result.LastName)
                                    {
                                        var memberRequest = new RestRequest("v1/members/{userId}", Method.GET);
                                        memberRequest.AddUrlSegment("userId", result.UserId.ToString());
                                        var memberResult = client.Execute <Contracts.Member>(memberRequest);
                                        if (memberResult.Data != null && memberResult.Data.ArenaId > 0)
                                        {
                                            try
                                            {
                                                Person personMatch = personAliasService.Queryable().Where(pa => pa.AliasPersonId == memberResult.Data.ArenaId).Select(pa => pa.Person).FirstOrDefault();
                                                if (personMatch == null)
                                                {
                                                    throw new Exception("Person not found: " + memberResult.Data.ArenaId);
                                                }
                                                person = personMatch;
                                            } catch (Exception e)
                                            {
                                                warnings += "Loading the person failed transaction id " + result.TransactionId + " for " + result.FirstName + " " + result.LastName + " with the following error: " + e.Message + Environment.NewLine;
                                                processed++;
                                                continue;
                                            }
                                        }
                                    }
                                    // 2. If we didn't get a person match via their Alias Id
                                    //    then just use the standard person match logic
                                    if (person == null)
                                    {
                                        String street1    = null;
                                        String postalCode = null;
                                        if (result.Address != null)
                                        {
                                            street1    = result.Address.Address1;
                                            postalCode = result.Address.Zip;
                                        }
                                        List <Person> matches = personService.GetByMatch(result.FirstName.Trim(), result.LastName.Trim(), null, result.Email, null, street1, postalCode).ToList();

                                        if (matches.Count > 1)
                                        {
                                            // Find the oldest member record in the list
                                            person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault();
                                            if (person == null)
                                            {
                                                // Find the oldest attendee record in the list
                                                person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault();
                                                if (person == null)
                                                {
                                                    person = matches.OrderBy(p => p.Id).First();
                                                }
                                            }
                                        }
                                        else if (matches.Count == 1)
                                        {
                                            person = matches.First();
                                        }
                                        else
                                        {
                                            // Create the person
                                            person           = new Person();
                                            person.FirstName = result.FirstName.Trim();
                                            person.LastName  = result.LastName.Trim();
                                            if (result.Email.IsValidEmail())
                                            {
                                                person.Email = result.Email.Trim();
                                            }
                                            person.RecordTypeValueId       = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                                            person.ConnectionStatusValueId = connectionStatus.Id;
                                            person.RecordStatusValueId     = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                                            Group         family   = PersonService.SaveNewPerson(person, dbContext);
                                            GroupLocation location = new GroupLocation();
                                            location.GroupLocationTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                            location.Location = new Location()
                                            {
                                                Street1    = result.Address.Address1,
                                                Street2    = result.Address.Address2,
                                                City       = result.Address.City,
                                                State      = result.Address.State,
                                                PostalCode = result.Address.Zip,
                                                Country    = result.Address.Country
                                            };
                                            family.CampusId = CampusCache.All().FirstOrDefault().Id;
                                            family.GroupLocations.Add(location);
                                            dbContext.SaveChanges();
                                        }
                                    }

                                    // Get details about the transaction from our PayPal report table
                                    Transaction tx = transactionService.Get(result.PaymentProcessorTransactionId);
                                    if (tx != null)
                                    {
                                        if (tx.TenderType.Contains("ACH"))
                                        {
                                            result.Type   = "ACH";
                                            result.Method = null;
                                        }
                                        else
                                        {
                                            result.Type   = "Credit Card";
                                            result.Method = tx.TenderType;
                                        }
                                    }
                                    else
                                    {
                                        // Defaults
                                        result.Type   = "Credit Card";
                                        result.Method = "Visa";

                                        warnings += "Unable to find transaction in _org_secc_PaypalReporting_Transaction table: " + result.TransactionId + Environment.NewLine;
                                    }

                                    // If we don't have a batch, create one
                                    if (batch == null)
                                    {
                                        batch = new FinancialBatch();
                                        batch.BatchStartDateTime = result.Date;
                                        batch.BatchEndDateTime   = DateTime.Now;
                                        batch.Name   = "Service Reef Payments";
                                        batch.Status = BatchStatus.Open;
                                        financialBatchService.Add(batch);
                                        dbContext.SaveChanges();
                                    }

                                    // Complete the FinancialTransaction
                                    tran.AuthorizedPersonAliasId = person.PrimaryAliasId;
                                    tran.BatchId             = batch.Id;
                                    tran.Summary             = "F" + specialFund.Id + ":$" + result.Amount.ToString();
                                    tran.TransactionDateTime = result.Date;
                                    tran.FinancialGatewayId  = gateway.Id;

                                    FinancialTransactionDetail financialTransactionDetail = new FinancialTransactionDetail();
                                    financialTransactionDetail.AccountId = trip.Id;
                                    financialTransactionDetail.Amount    = result.Amount.ToString().AsDecimal();
                                    tran.TransactionDetails.Add(financialTransactionDetail);
                                    tran.TransactionTypeValueId = contribution.Id;

                                    tran.FinancialPaymentDetail = new FinancialPaymentDetail();
                                    tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(type => type.Value.ToLower() == result.Type.ToLower()).FirstOrDefault().Id;
                                    if (result.Method != null)
                                    {
                                        tran.FinancialPaymentDetail.CreditCardTypeValueId = creditCards.DefinedValues.Where(card => card.Value.ToLower() == result.Method.ToLower()).FirstOrDefault().Id;
                                    }
                                    tran.TransactionCode   = result.PaymentProcessorTransactionId;
                                    tran.SourceTypeValueId = transactionSource.Id;

                                    financialTransactionService.Add(tran);
                                    dbContext.SaveChanges();

                                    totalAmount += result.Amount;
                                }
                            }
                            processed++;
                        }
                    }
                    else
                    {
                        total = 0;
                    }
                    // Update the page number for the next request
                    var pageParam = request.Parameters.Where(p => p.Name == "page").FirstOrDefault();
                    pageParam.Value = (int)pageParam.Value + 1;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ServiceReef Job Failed", ex);
            } finally
            {
                if (batch != null && totalAmount > 0)
                {
                    batch.ControlAmount = (Decimal)totalAmount;
                }
                dbContext.SaveChanges();
            }
            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " transactions.";
        }
Esempio n. 19
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)
                    {
                        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();
            }
        }
Esempio n. 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;

            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);
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Handles the Click event of the btnCancelFinancialBatch 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 btnCancelFinancialBatch_Click(object sender, EventArgs e)
        {
            var savedFinancialBatch = new FinancialBatchService().Get(hfBatchId.ValueAsInt());

            ShowReadOnly(savedFinancialBatch);
        }
        /// <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);
        }
        protected void btnExportToIntacct_Click(object sender, EventArgs e)
        {
            if (_financialBatch != null)
            {
                if (GetAttributeValue(AttributeKey.ExportMode) == "OtherReceipt")
                {
                    //
                    // Capture ddl values as user preferences
                    //

                    SetBlockUserPreference("ReceiptAccountType", ddlReceiptAccountType.SelectedValue ?? "");
                    SetBlockUserPreference("PaymentMethod", ddlPaymentMethods.SelectedValue ?? "");
                }

                if (_intacctAuth == null)
                {
                    _intacctAuth = GetIntactAuth();
                }

                //
                // Create Intacct Journal XML and Post to Intacct
                //

                var endpoint  = new IntacctEndpoint();
                var debugLava = GetAttributeValue(AttributeKey.EnableDebug);
                var postXml   = new System.Xml.XmlDocument();

                if (GetAttributeValue(AttributeKey.ExportMode) == "JournalEntry")
                {
                    var journal = new IntacctJournal();
                    postXml = journal.CreateJournalEntryXML(_intacctAuth, _financialBatch.Id, GetAttributeValue(AttributeKey.JournalId), ref debugLava, GetAttributeValue(AttributeKey.JournalMemoLava));
                }
                else   // Export Mode is Other Receipt
                {
                    var    otherReceipt     = new IntacctOtherReceipt();
                    string bankAccountId    = null;
                    string undepFundAccount = null;
                    if (ddlReceiptAccountType.SelectedValue == "BankAccount")
                    {
                        SetBlockUserPreference("BankAccountId", ddlBankAccounts.SelectedValue ?? "");
                        bankAccountId = ddlBankAccounts.SelectedValue;
                    }
                    else
                    {
                        undepFundAccount = GetAttributeValue(AttributeKey.UndepositedFundsAccount);
                    }
                    postXml = otherReceipt.CreateOtherReceiptXML(_intacctAuth, _financialBatch.Id, ref debugLava, ( PaymentMethod )ddlPaymentMethods.SelectedValue.AsInteger(), bankAccountId, undepFundAccount, GetAttributeValue(AttributeKey.JournalMemoLava));
                }

                var resultXml = endpoint.PostToIntacct(postXml);
                var success   = endpoint.ParseEndpointResponse(resultXml, _financialBatch.Id, GetAttributeValue(AttributeKey.LogResponse).AsBoolean());

                if (success)
                {
                    var rockContext    = new RockContext();
                    var financialBatch = new FinancialBatchService(rockContext).Get(_batchId);
                    var changes        = new History.HistoryChangeList();

                    Session["IntacctDebugLava"] = debugLava;

                    //
                    // Close Batch if we're supposed to
                    //
                    if (GetAttributeValue(AttributeKey.CloseBatch).AsBoolean())
                    {
                        History.EvaluateChange(changes, "Status", financialBatch.Status, BatchStatus.Closed);
                        financialBatch.Status = BatchStatus.Closed;
                    }

                    //
                    // Set Date Exported
                    //
                    financialBatch.LoadAttributes();
                    var oldDate = financialBatch.GetAttributeValue("rocks.kfs.Intacct.DateExported");
                    var newDate = RockDateTime.Now;
                    History.EvaluateChange(changes, "Date Exported", oldDate, newDate.ToString());

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

                    financialBatch.SetAttributeValue("rocks.kfs.Intacct.DateExported", newDate);
                    financialBatch.SaveAttributeValue("rocks.kfs.Intacct.DateExported", rockContext);
                }
            }

            Response.Redirect(Request.RawUrl);
        }
        protected void btnExportToIntacct_Click(object sender, EventArgs e)
        {
            if (_financialBatch != null)
            {
                //
                // Get Intacct Auth
                //

                var intacctAuth = new IntacctAuth()
                {
                    SenderId       = Encryption.DecryptString(GetAttributeValue("SenderId")),
                    SenderPassword = Encryption.DecryptString(GetAttributeValue("SenderPassword")),
                    CompanyId      = Encryption.DecryptString(GetAttributeValue("CompanyId")),
                    UserId         = Encryption.DecryptString(GetAttributeValue("UserId")),
                    UserPassword   = Encryption.DecryptString(GetAttributeValue("UserPassword")),
                    LocationId     = Encryption.DecryptString(GetAttributeValue("LocationId"))
                };

                //
                // Create Intacct Journal XML and Post to Intacct
                //

                var journal   = new IntacctJournal();
                var endpoint  = new IntacctEndpoint();
                var debugLava = GetAttributeValue("EnableDebug");

                var postXml   = journal.CreateJournalEntryXML(intacctAuth, _financialBatch.Id, GetAttributeValue("JournalId"), ref debugLava, GetAttributeValue("JournalMemoLava"));
                var resultXml = endpoint.PostToIntacct(postXml);
                var success   = endpoint.ParseEndpointResponse(resultXml, _financialBatch.Id, GetAttributeValue("LogResponse").AsBoolean());

                if (success)
                {
                    var rockContext    = new RockContext();
                    var financialBatch = new FinancialBatchService(rockContext).Get(_batchId);
                    var changes        = new History.HistoryChangeList();

                    Session["IntacctDebugLava"] = debugLava;

                    //
                    // Close Batch if we're supposed to
                    //
                    if (GetAttributeValue("CloseBatch").AsBoolean())
                    {
                        History.EvaluateChange(changes, "Status", financialBatch.Status, BatchStatus.Closed);
                        financialBatch.Status = BatchStatus.Closed;
                    }

                    //
                    // Set Date Exported
                    //
                    financialBatch.LoadAttributes();
                    var oldDate = financialBatch.GetAttributeValue("rocks.kfs.Intacct.DateExported");
                    var newDate = RockDateTime.Now;
                    History.EvaluateChange(changes, "Date Exported", oldDate, newDate.ToString());

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

                    financialBatch.SetAttributeValue("rocks.kfs.Intacct.DateExported", newDate);
                    financialBatch.SaveAttributeValue("rocks.kfs.Intacct.DateExported", rockContext);
                }
            }

            Response.Redirect(Request.RawUrl);
        }
Esempio n. 25
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);
        }
Esempio n. 26
0
        /// <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);
        }
        //
        // Swipe Panel Events
        //

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

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

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

                        var homeLocation = giver.Person.GetHomeLocation();

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

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

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

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

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

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

                        if (transaction != null)
                        {
                            var txnChanges = new List <string>();
                            txnChanges.Add("Created Transaction (from kiosk)");

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

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

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

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

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

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

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

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

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

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

                            var batchService = new FinancialBatchService(rockContext);

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

                            var batchChanges = new List <string>();

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

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

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

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

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

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

                                SendReceipt();
                            }

                            HidePanels();
                            ShowReceiptPanel();
                        }
                        else
                        {
                            lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", errorMessage);
                        }
                    }
                    else
                    {
                        lSwipeErrors.Text = "<div class='alert alert-danger'>Invalid gateway provided. Please provide a gateway. Transaction not processed.</div>";
                    }
                }
            }
            catch (Exception ex)
            {
                lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", ex.Message);
            }
        }
        /// <summary>
        /// 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");
                }
            }
        }
        protected void btnExportToShelbyFinancials_Click(object sender, EventArgs e)
        {
            Session["JournalType"]      = ddlJournalType.SelectedValue;
            Session["AccountingPeriod"] = tbAccountingPeriod.Text;

            if (_financialBatch != null)
            {
                var rockContext = new RockContext();

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

                var debugLava = GetAttributeValue("EnableDebug");

                var items = sfJournal.GetGLExcelLines(rockContext, _financialBatch, journalCode, period, ref debugLava, GetAttributeValue("JournalDescriptionLava"));

                if (items.Count > 0)
                {
                    var excel = sfJournal.GLExcelExport(items);

                    Session["ShelbyFinancialsExcelExport"] = excel;
                    Session["ShelbyFinancialsFileId"]      = _financialBatch.Id.ToString();
                    Session["ShelbyFinancialsDebugLava"]   = debugLava;
                    //
                    // vars we need to know
                    //
                    var financialBatch = new FinancialBatchService(rockContext).Get(_batchId);
                    var changes        = new History.HistoryChangeList();

                    //
                    // Close Batch if we're supposed to
                    //
                    if (GetAttributeValue("CloseBatch").AsBoolean())
                    {
                        History.EvaluateChange(changes, "Status", financialBatch.Status, BatchStatus.Closed);
                        financialBatch.Status = BatchStatus.Closed;
                    }

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

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

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

            Response.Redirect(Request.RawUrl);
        }
        /// <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();
        }