Exemple #1
0
 /// <summary>
 /// Saves the changes.
 /// </summary>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="modelType">Type of the model.</param>
 /// <param name="categoryGuid">The category unique identifier.</param>
 /// <param name="entityId">The entity identifier.</param>
 /// <param name="changes">The changes.</param>
 /// <param name="caption">The caption.</param>
 /// <param name="relatedModelType">Type of the related model.</param>
 /// <param name="relatedEntityId">The related entity identifier.</param>
 /// <param name="commitSave">if set to <c>true</c> [commit save].</param>
 /// <param name="modifiedByPersonAliasId">The modified by person alias identifier.</param>
 /// <param name="sourceOfChange">The source of change to be recorded on the history record. If this is not provided the RockContext source of change will be used instead.</param>
 public static void SaveChanges(RockContext rockContext, Type modelType, Guid categoryGuid, int entityId, History.HistoryChangeList changes, string caption, Type relatedModelType, int?relatedEntityId, bool commitSave = true, int?modifiedByPersonAliasId = null, string sourceOfChange = null)
 {
     if (changes.Any())
     {
         changes.ForEach(a => a.SourceOfChange = sourceOfChange ?? rockContext.SourceOfChange);
         AddChanges(rockContext, modelType, categoryGuid, entityId, changes, caption, relatedModelType, relatedEntityId, modifiedByPersonAliasId);
         if (commitSave)
         {
             rockContext.SaveChanges();
         }
     }
 }
Exemple #2
0
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="modelType">Type of the model.</param>
        /// <param name="categoryGuid">The category unique identifier.</param>
        /// <param name="entityId">The entity identifier.</param>
        /// <param name="changes">The changes.</param>
        /// <param name="caption">The caption.</param>
        /// <param name="relatedModelType">Type of the related model.</param>
        /// <param name="relatedEntityId">The related entity identifier.</param>
        /// <param name="commitSave">if set to <c>true</c> [commit save].</param>
        /// <param name="modifiedByPersonAliasId">The modified by person alias identifier.</param>
        /// <param name="sourceOfChange">The source of change to be recorded on the history record. If this is not provided the RockContext source of change will be used instead.</param>
        public static void SaveChanges(RockContext rockContext, Type modelType, Guid categoryGuid, int entityId, History.HistoryChangeList changes, string caption, Type relatedModelType, int?relatedEntityId, bool commitSave = true, int?modifiedByPersonAliasId = null, string sourceOfChange = null)
        {
            if (changes.Any())
            {
                // Set the change source for any entries that do not have one, or for all entries if a source has been supplied as a parameter.
                SetHistoryEntriesSourceOfChange(changes, sourceOfChange ?? rockContext.SourceOfChange, sourceOfChange != null);

                AddChanges(rockContext, modelType, categoryGuid, entityId, changes, caption, relatedModelType, relatedEntityId, modifiedByPersonAliasId);
                if (commitSave)
                {
                    rockContext.SaveChanges();
                }
            }
        }
Exemple #3
0
        public bool ParseEndpointResponse(XmlDocument xmlDocument, int BatchId, bool Log = false)
        {
            var resultX = XDocument.Load(new XmlNodeReader(xmlDocument));

            if (Log)
            {
                var financialBatch = new FinancialBatchService(new RockContext()).Get(BatchId);
                var changes        = new History.HistoryChangeList();
                var oldValue       = string.Empty;
                var newValue       = resultX.ToString();

                History.EvaluateChange(changes, "Intacct Response", oldValue, newValue);

                var rockContext = new RockContext();
                rockContext.WrapTransaction(() =>
                {
                    if (changes.Any())
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(FinancialBatch),
                            Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                            BatchId,
                            changes);
                    }
                });
            }

            var xResponseXml = resultX.Elements("response").FirstOrDefault();

            if (xResponseXml != null)
            {
                var xOperationXml = xResponseXml.Elements("operation").FirstOrDefault();
                if (xOperationXml != null)
                {
                    var xResultXml = xOperationXml.Elements("result").FirstOrDefault();
                    if (xResultXml != null)
                    {
                        var xStatusXml = xResultXml.Elements("status").FirstOrDefault();
                        if (xStatusXml != null && xStatusXml.Value == "success")
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
        protected void btnRemoveDateExported_Click(object sender, EventArgs e)
        {
            if (_financialBatch != null)
            {
                var rockContext    = new RockContext();
                var financialBatch = new FinancialBatchService(rockContext).Get(_batchId);
                var changes        = new History.HistoryChangeList();

                //
                // Open Batch is we Closed it
                //
                if (GetAttributeValue("CloseBatch").AsBoolean())
                {
                    History.EvaluateChange(changes, "Status", financialBatch.Status, BatchStatus.Open);
                    financialBatch.Status = BatchStatus.Open;
                }

                //
                // Remove Date Exported
                //
                financialBatch.LoadAttributes();
                var oldDate = financialBatch.GetAttributeValue("rocks.kfs.ShelbyFinancials.DateExported").AsDateTime().ToString();
                var newDate = string.Empty;
                History.EvaluateChange(changes, "Date Exported", oldDate, newDate);

                //
                // 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);
        }
Exemple #5
0
        /// <summary>
        /// Method that will be called on an entity immediately after the item is saved
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        public override void PostSaveChanges(Data.DbContext dbContext)
        {
            if (HistoryChangeList.Any())
            {
                HistoryService.SaveChanges(( RockContext )dbContext, typeof(FinancialTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), this.TransactionId, HistoryChangeList, true, this.ModifiedByPersonAliasId);

                var txn = new FinancialTransactionService(( RockContext )dbContext).GetSelect(this.TransactionId, s => new { s.Id, s.BatchId });
                if (txn != null && txn.BatchId != null)
                {
                    var batchHistory = new History.HistoryChangeList();
                    batchHistory.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, $"Transaction ID:{txn.Id}");
                    HistoryService.SaveChanges(( RockContext )dbContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), txn.BatchId.Value, batchHistory, string.Empty, typeof(FinancialTransaction), this.TransactionId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange);
                }
            }

            base.PostSaveChanges(dbContext);
        }
Exemple #6
0
        /// <summary>
        /// This method is called in the
        /// <see cref="M:Rock.Data.Model`1.PreSaveChanges(Rock.Data.DbContext,System.Data.Entity.Infrastructure.DbEntityEntry,System.Data.Entity.EntityState)" />
        /// method. Use it to populate <see cref="P:Rock.Data.Model`1.HistoryItems" /> if needed.
        /// These history items are queued to be written into the database post save (so that they
        /// are only written if the save actually occurs).
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="entry">The entry.</param>
        /// <param name="state">The state.</param>
        protected override void BuildHistoryItems(Data.DbContext dbContext, DbEntityEntry entry, EntityState state)
        {
            var attributeCache = AttributeCache.Get(AttributeId);

            if (attributeCache?.EntityTypeId == null)
            {
                return;
            }

            var entityTypeId = attributeCache.EntityTypeId.Value;
            var entityId     = EntityId;

            if (!entityId.HasValue && (entry.State == EntityState.Modified || entry.State == EntityState.Deleted))
            {
                entityId = entry.OriginalValues["EntityId"].ToStringSafe().AsIntegerOrNull();
            }

            var caption = attributeCache.Name;

            // Check to see if this attribute is for a person or group, and if so, save to history table
            var personEntityTypeId = EntityTypeCache.Get(typeof(Person)).Id;

            var entityTypesToSaveToHistoryTable = new List <int> {
                personEntityTypeId,
                EntityTypeCache.Get(typeof(Group)).Id
            };

            var saveToHistoryTable = entityTypesToSaveToHistoryTable.Contains(entityTypeId);

            // If the value is not directly linked to a person or group, it still may be linked through an attribute matrix.
            // Matrix attribute changes are only logged here for modify. Add and delete are handled in the AttributeMatrixItem.
            if (!saveToHistoryTable && state == EntityState.Modified && IsLikelyWithinMatrix())
            {
                var rootMatrixAttributeValue = GetRootMatrixAttributeValue();

                if (rootMatrixAttributeValue == null)
                {
                    return;
                }

                var rootMatrixAttributeCache = AttributeCache.Get(rootMatrixAttributeValue.AttributeId);

                if (rootMatrixAttributeCache == null || !rootMatrixAttributeCache.EntityTypeId.HasValue)
                {
                    return;
                }

                saveToHistoryTable = entityTypesToSaveToHistoryTable.Contains(rootMatrixAttributeCache.EntityTypeId.Value);

                if (saveToHistoryTable)
                {
                    // Use the values from the root matrix attribute since this is the attribute that ties the
                    // values to a person or group and are thus more meaningful
                    entityTypeId = rootMatrixAttributeCache.EntityTypeId.Value;
                    entityId     = rootMatrixAttributeValue.EntityId;
                    caption      = rootMatrixAttributeCache.Name;
                }
            }

            if (!saveToHistoryTable || !entityId.HasValue)
            {
                return;
            }

            // We have determined to write to the History table. Now determine what changed.
            var oldValue = GetHistoryOldValue(entry);
            var newValue = GetHistoryNewValue(state);

            if (oldValue == newValue)
            {
                return;
            }

            // Evaluate the history change
            var formattedOldValue = GetHistoryFormattedValue(oldValue, attributeCache);
            var formattedNewValue = GetHistoryFormattedValue(newValue, attributeCache);
            var historyChangeList = new History.HistoryChangeList();

            History.EvaluateChange(historyChangeList, attributeCache.Name, formattedOldValue, formattedNewValue, attributeCache.FieldType.Field.IsSensitive());

            if (!historyChangeList.Any())
            {
                return;
            }

            var categoryGuid = entityTypeId == personEntityTypeId?
                               SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid() :
                                   SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid();

            HistoryItems = HistoryService.GetChanges(
                entityTypeId == personEntityTypeId ? typeof(Person) : typeof(Group),
                categoryGuid,
                entityId.Value,
                historyChangeList,
                caption,
                typeof(Attribute),
                AttributeId,
                dbContext.GetCurrentPersonAlias()?.Id,
                dbContext.SourceOfChange);
        }
Exemple #7
0
        /// <summary>
        /// Processes the NCOA results: Mark all individual move addresses as previous, add the new address as current; and processed.
        /// If minMoveDistance is specified, mark the individual as inactive if the individual moved further than the specified distance.
        /// </summary>
        /// <param name="inactiveReason">The inactive reason.</param>
        /// <param name="minMoveDistance">The minimum move distance.</param>
        /// <param name="homeValueId">The home value identifier.</param>
        /// <param name="previousValueId">The previous value identifier.</param>
        private void ProcessNcoaResultsIndividualMove(DefinedValueCache inactiveReason, decimal?minMoveDistance, int?homeValueId, int?previousValueId)
        {
            List <int> ncoaIds = null;

            // Process 'Move' NCOA Types (For the remaining Individual move types that weren't updated with the family move)
            using (var rockContext = new RockContext())
            {
                ncoaIds = new NcoaHistoryService(rockContext)
                          .Queryable().AsNoTracking()
                          .Where(n =>
                                 n.Processed == Processed.NotProcessed &&
                                 n.NcoaType == NcoaType.Move &&
                                 n.MoveType == MoveType.Individual)
                          .Select(n => n.Id)
                          .ToList();
            }

            foreach (int id in ncoaIds)
            {
                using (var rockContext = new RockContext())
                {
                    // Get the NCOA record and make sure it still hasn't been processed
                    var ncoaHistory = new NcoaHistoryService(rockContext).Get(id);
                    if (ncoaHistory != null && ncoaHistory.Processed == Processed.NotProcessed)
                    {
                        var ncoaHistoryService   = new NcoaHistoryService(rockContext);
                        var groupMemberService   = new GroupMemberService(rockContext);
                        var personAliasService   = new PersonAliasService(rockContext);
                        var groupService         = new GroupService(rockContext);
                        var groupLocationService = new GroupLocationService(rockContext);
                        var locationService      = new LocationService(rockContext);
                        var personService        = new PersonService(rockContext);

                        var changes = new History.HistoryChangeList();

                        // Default the status to requiring a manual update (we might change this though)
                        ncoaHistory.Processed = Processed.ManualUpdateRequired;

                        // Find the existing family
                        var family = groupService.Get(ncoaHistory.FamilyId);

                        // If there's only one person in the family
                        if (family.Members.Count == 1)
                        {
                            // And that person is the same as the move record's person then we can process it.
                            var personAlias  = personAliasService.Get(ncoaHistory.PersonAliasId);
                            var familyMember = family.Members.First();
                            if (personAlias != null && familyMember.PersonId == personAlias.PersonId)
                            {
                                // If were able to mark their existing address as previous and add a new updated Home address,
                                // then set the status to complete (otherwise leave it as needing a manual update).
                                var previousGroupLocation = MarkAsPreviousLocation(ncoaHistory, groupLocationService, previousValueId, changes);
                                if (previousGroupLocation != null)
                                {
                                    if (AddNewHomeLocation(ncoaHistory, locationService, groupLocationService, homeValueId, changes, previousGroupLocation.IsMailingLocation, previousGroupLocation.IsMappedLocation))
                                    {
                                        ncoaHistory.Processed = Processed.Complete;

                                        // Look for any other moves for the same person to same address, and set their process to complete also
                                        foreach (var ncoaIndividual in ncoaHistoryService
                                                 .Queryable().Where(n =>
                                                                    n.Processed == Processed.NotProcessed &&
                                                                    n.NcoaType == NcoaType.Move &&
                                                                    n.MoveType == MoveType.Individual &&
                                                                    n.PersonAliasId == ncoaHistory.PersonAliasId &&
                                                                    n.Id != ncoaHistory.Id &&
                                                                    n.UpdatedStreet1 == ncoaHistory.UpdatedStreet1))
                                        {
                                            ncoaIndividual.Processed = Processed.Complete;
                                        }

                                        // If there were any changes, write to history and check to see if person should be inactivated
                                        if (changes.Any())
                                        {
                                            if (ncoaHistory.MoveDistance.HasValue && minMoveDistance.HasValue &&
                                                ncoaHistory.MoveDistance.Value >= minMoveDistance.Value)
                                            {
                                                History.HistoryChangeList personChanges;

                                                personService.InactivatePerson(familyMember.Person, inactiveReason,
                                                                               $"Received a Change of Address (NCOA) notice that was for more than {minMoveDistance} miles away.", out personChanges);

                                                if (personChanges.Any())
                                                {
                                                    HistoryService.SaveChanges(
                                                        rockContext,
                                                        typeof(Person),
                                                        SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                                        familyMember.PersonId,
                                                        personChanges,
                                                        false);
                                                }
                                            }

                                            HistoryService.SaveChanges(
                                                rockContext,
                                                typeof(Person),
                                                SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                                familyMember.PersonId,
                                                changes,
                                                family.Name,
                                                typeof(Group),
                                                family.Id,
                                                false);
                                        }
                                    }
                                }
                            }
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
        }
        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);
        }
        /// <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);
        }
        /// <summary>
        /// Handles the Click event of the btnEdit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnConnect_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var opportunityService       = new ConnectionOpportunityService(rockContext);
                var connectionRequestService = new ConnectionRequestService(rockContext);
                var personService            = new PersonService(rockContext);

                // Get the opportunity and default status
                int opportunityId = PageParameter("OpportunityId").AsInteger();
                var opportunity   = opportunityService
                                    .Queryable()
                                    .Where(o => o.Id == opportunityId)
                                    .FirstOrDefault();

                int defaultStatusId = opportunity.ConnectionType.ConnectionStatuses
                                      .Where(s => s.IsDefault)
                                      .Select(s => s.Id)
                                      .FirstOrDefault();

                // If opportunity is valid and has a default status
                if (opportunity != null && defaultStatusId > 0)
                {
                    Person person = null;

                    string   firstName = tbFirstName.Text.Trim();
                    string   lastName  = tbLastName.Text.Trim();
                    DateTime?birthdate = bpBirthdate.SelectedDate;
                    string   email     = tbEmail.Text.Trim();
                    int?     campusId  = cpCampus.SelectedCampusId;

                    // if a person guid was passed in from the query string use that
                    if (RockPage.PageParameter("PersonGuid") != null && !string.IsNullOrWhiteSpace(RockPage.PageParameter("PersonGuid")))
                    {
                        Guid?personGuid = RockPage.PageParameter("PersonGuid").AsGuidOrNull();

                        if (personGuid.HasValue)
                        {
                            person = personService.Get(personGuid.Value);
                        }
                    }
                    else if (CurrentPerson != null &&
                             CurrentPerson.LastName.Equals(lastName, StringComparison.OrdinalIgnoreCase) &&
                             (CurrentPerson.NickName.Equals(firstName, StringComparison.OrdinalIgnoreCase) || CurrentPerson.FirstName.Equals(firstName, StringComparison.OrdinalIgnoreCase)) &&
                             CurrentPerson.Email.Equals(email, StringComparison.OrdinalIgnoreCase))
                    {
                        // If the name and email entered are the same as current person (wasn't changed), use the current person
                        person = personService.Get(CurrentPerson.Id);
                    }

                    else
                    {
                        List <Person> personMatches = new List <Person>();
                        if (Assembly.GetExecutingAssembly().GetReferencedAssemblies()
                            .FirstOrDefault(c => c.FullName == "org.secc.PersonMatch") != null)
                        {
                            var assembly = Assembly.Load("org.secc.PersonMatch");
                            if (assembly != null)
                            {
                                Type type = assembly.GetExportedTypes().Where(et => et.FullName == "org.secc.PersonMatch.Extension").FirstOrDefault();
                                if (type != null)
                                {
                                    var matchMethod = type.GetMethod("GetByMatch");
                                    personMatches = ((IEnumerable <Person>)matchMethod.Invoke(null, new object[] { personService, firstName, lastName, birthdate, email, null, null, null })).ToList();
                                }
                            }
                        }
                        else
                        {
                            personMatches = personService.FindPersons(firstName, lastName, email).ToList();
                            if (bpBirthdate.Visible)
                            {
                                personMatches = personMatches.Where(p => p.BirthDate == birthdate).ToList();
                            }
                        }

                        if (personMatches.Count() == 1 &&
                            personMatches.First().Email != null &&
                            email.ToLower().Trim() == personMatches.First().Email.ToLower().Trim())
                        {
                            // If one person with same name and email address exists, use that person
                            person = personMatches.First();
                        }
                    }

                    // If person was not found, create a new one
                    if (person == null)
                    {
                        // If a match was not found, create a new person
                        var dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
                        var dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());

                        person               = new Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.SetBirthDate(birthdate);
                        person.Email             = email;
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        if (dvcConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                        }
                        if (dvcRecordStatus != null)
                        {
                            person.RecordStatusValueId = dvcRecordStatus.Id;
                        }

                        PersonService.SaveNewPerson(person, rockContext, campusId, false);
                        person = personService.Get(person.Id);
                    }

                    // If there is a valid person with a primary alias, continue
                    if (person != null && person.PrimaryAliasId.HasValue)
                    {
                        var changes = new History.HistoryChangeList();

                        if (pnHome.Visible)
                        {
                            SavePhone(pnHome, person, _homePhone.Guid, changes);
                        }

                        if (pnMobile.Visible)
                        {
                            SavePhone(pnMobile, person, _cellPhone.Guid, changes);
                        }

                        // Save the DOB
                        if (bpBirthdate.Visible && bpBirthdate.SelectedDate.HasValue && bpBirthdate.SelectedDate != person.BirthDate)
                        {
                            person.BirthDay   = bpBirthdate.SelectedDate.Value.Day;
                            person.BirthMonth = bpBirthdate.SelectedDate.Value.Month;
                            person.BirthYear  = bpBirthdate.SelectedDate.Value.Year;
                        }

                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                person.Id,
                                changes);
                        }

                        // Now that we have a person, we can create the connection requests
                        int RepeaterIndex = 0;
                        foreach (ConnectionRoleRequest roleRequest in RoleRequests)
                        {
                            var connectionRequest = new ConnectionRequest();
                            connectionRequest.PersonAliasId           = person.PrimaryAliasId.Value;
                            connectionRequest.Comments                = tbComments.Text.Trim();
                            connectionRequest.ConnectionOpportunityId = opportunity.Id;
                            connectionRequest.ConnectionState         = ConnectionState.Active;
                            connectionRequest.ConnectionStatusId      = defaultStatusId;
                            connectionRequest.CampusId                = campusId;
                            connectionRequest.ConnectorPersonAliasId  = opportunity.GetDefaultConnectorPersonAliasId(campusId);
                            if (campusId.HasValue &&
                                opportunity != null &&
                                opportunity.ConnectionOpportunityCampuses != null)
                            {
                                var campus = opportunity.ConnectionOpportunityCampuses
                                             .Where(c => c.CampusId == campusId.Value)
                                             .FirstOrDefault();
                                if (campus != null)
                                {
                                    connectionRequest.ConnectorPersonAliasId = campus.DefaultConnectorPersonAliasId;
                                }
                            }

                            var hdnGroupId         = (( HiddenField )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("hdnGroupId")));
                            var hdnGroupRoleTypeId = (( HiddenField )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("hdnGroupRoleTypeId")));


                            if (hdnGroupId.Value.AsInteger() > 0 && hdnGroupRoleTypeId.Value.AsInteger() > 0)
                            {
                                connectionRequest.AssignedGroupId           = hdnGroupId.Value.AsInteger();
                                connectionRequest.AssignedGroupMemberRoleId = hdnGroupRoleTypeId.Value.AsInteger();
                                var groupConfig = opportunity.ConnectionOpportunityGroupConfigs.Where(gc => gc.GroupMemberRoleId == hdnGroupRoleTypeId.Value.AsInteger()).FirstOrDefault();
                                connectionRequest.AssignedGroupMemberStatus = groupConfig.GroupMemberStatus;
                            }

                            var connectionAttributes = GetGroupMemberAttributes(rockContext, RepeaterIndex);

                            if (connectionAttributes != null && connectionAttributes.Keys.Any())
                            {
                                var connectionDictionary = new Dictionary <string, string>();
                                foreach (var kvp in connectionAttributes)
                                {
                                    connectionDictionary.Add(kvp.Key, kvp.Value.Value);
                                }

                                connectionRequest.AssignedGroupMemberAttributeValues = connectionDictionary.ToJson();
                            }

                            if (!connectionRequest.IsValid)
                            {
                                // Controls will show warnings
                                return;
                            }

                            connectionRequestService.Add(connectionRequest);

                            RepeaterIndex++;
                        }

                        rockContext.SaveChanges();

                        var mergeFields = new Dictionary <string, object>();
                        mergeFields.Add("Opportunity", new ConnectionOpportunityService(rockContext).Get(PageParameter("OpportunityId").AsInteger()));
                        mergeFields.Add("CurrentPerson", CurrentPerson);
                        mergeFields.Add("Person", person);

                        lResponseMessage.Text    = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
                        lResponseMessage.Visible = true;

                        if ((( LinkButton )sender).Text == "Connect and Add Another")
                        {
                            ShowDetail(opportunityId, true);
                            AddGroupMemberAttributes(rockContext);
                            pnlSignup.Visible = true;
                        }
                        else
                        {
                            pnlSignup.Visible = false;
                        }
                    }
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// This method is called in the
        /// <see cref="M:Rock.Data.Model`1.PreSaveChanges(Rock.Data.DbContext,System.Data.Entity.Infrastructure.DbEntityEntry,System.Data.Entity.EntityState)" />
        /// method. Use it to populate <see cref="P:Rock.Data.Model`1.HistoryItems" /> if needed.
        /// These history items are queued to be written into the database post save (so that they
        /// are only written if the save actually occurs).
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="entry">The entry.</param>
        /// <param name="state">The state.</param>
        protected override void BuildHistoryItems(Data.DbContext dbContext, DbEntityEntry entry, EntityState state)
        {
            /*
             * 12/18/2019 BJW
             *
             * We want to log the history of attribute values within a person matrix. Most of this logging occurs from
             * the attribute value model. However, when a matrix item (row in the table) is deleted, the pre-save event
             * of the attribute values is not called. Therefore, the delete event needs to be logged here. Additionally,
             * when the matrix item is added, the history is much cleaner when added here so that all the values of the
             * row are consolidated to one history item.  Modified state is not possible to log here because the
             * matrix item is not actually modified when its attributes change.
             *
             * Task: https://app.asana.com/0/1120115219297347/1136643182208595/f
             */

            if (state != EntityState.Deleted && state != EntityState.Added)
            {
                return;
            }

            var rockContext = new RockContext();
            var matrixId    = AttributeMatrixId != default ?
                              AttributeMatrixId :
                              entry.OriginalValues["AttributeMatrixId"].ToStringSafe().AsIntegerOrNull();

            var matrix = AttributeMatrix;

            if (matrix == null && matrixId.HasValue)
            {
                var matrixService = new AttributeMatrixService(rockContext);
                matrix = matrixService.Queryable().AsNoTracking().FirstOrDefault(am => am.Id == matrixId);
            }

            if (matrix == null)
            {
                return;
            }

            // The root attribute matrix attribute value is linked to the matrix by the guid as the attribute value
            var matrixGuidString      = matrix.Guid.ToString();
            var personEntityTypeId    = EntityTypeCache.Get(typeof(Person)).Id;
            var attributeValueService = new AttributeValueService(rockContext);
            var rootAttributeValue    = attributeValueService.Queryable().AsNoTracking().FirstOrDefault(av =>
                                                                                                        av.Value.Equals(matrixGuidString, System.StringComparison.OrdinalIgnoreCase) &&
                                                                                                        av.Attribute.EntityTypeId == personEntityTypeId
                                                                                                        );

            if (rootAttributeValue?.EntityId == null)
            {
                return;
            }

            var rootAttributeCache = AttributeCache.Get(rootAttributeValue.AttributeId);

            if (rootAttributeCache == null)
            {
                return;
            }

            // Evaluate the history changes
            var historyChangeList = new History.HistoryChangeList();

            if (AttributeValues == null || !AttributeValues.Any())
            {
                this.LoadAttributes();
            }

            var isDelete = state == EntityState.Deleted;

            foreach (var attributeValue in AttributeValues.Values)
            {
                var attributeCache    = AttributeCache.Get(attributeValue.AttributeId);
                var formattedOldValue = isDelete ? GetHistoryFormattedValue(attributeValue.Value, attributeCache) : string.Empty;
                var formattedNewValue = isDelete ? string.Empty : GetHistoryFormattedValue(attributeValue.Value, attributeCache);
                History.EvaluateChange(historyChangeList, attributeCache.Name, formattedOldValue, formattedNewValue, attributeCache.FieldType.Field.IsSensitive());
            }

            if (!historyChangeList.Any())
            {
                historyChangeList.AddChange(
                    isDelete ? History.HistoryVerb.Delete : History.HistoryVerb.Add,
                    History.HistoryChangeType.Record,
                    $"{rootAttributeCache.Name} Item");
            }

            HistoryItems = HistoryService.GetChanges(
                typeof(Person),
                SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                rootAttributeValue.EntityId.Value,
                historyChangeList,
                rootAttributeCache.Name,
                typeof(Attribute),
                rootAttributeCache.Id,
                dbContext.GetCurrentPersonAlias()?.Id,
                dbContext.SourceOfChange);
        }
Exemple #13
0
        /// <summary>
        /// Processes the NCOA results: Mark all family move addresses as previous, add the new address as current; and processed.
        /// If minMoveDistance is specified, mark the family as inactive if the family moved further than the specified distance.
        /// </summary>
        /// <param name="inactiveReason">The inactive reason.</param>
        /// <param name="minMoveDistance">The minimum move distance.</param>
        /// <param name="homeValueId">The home value identifier.</param>
        /// <param name="previousValueId">The previous value identifier.</param>
        private void ProcessNcoaResultsFamilyMove(DefinedValueCache inactiveReason, decimal?minMoveDistance, int?homeValueId, int?previousValueId)
        {
            List <int> ncoaIds = null;

            // Process 'Move' NCOA Types (The 'Family' move types will be processed first)
            using (var rockContext = new RockContext())
            {
                ncoaIds = new NcoaHistoryService(rockContext)
                          .Queryable().AsNoTracking()
                          .Where(n =>
                                 n.Processed == Processed.NotProcessed &&
                                 n.NcoaType == NcoaType.Move &&
                                 n.MoveType == MoveType.Family)
                          .Select(n => n.Id)
                          .ToList();
            }

            foreach (int id in ncoaIds)
            {
                using (var rockContext = new RockContext())
                {
                    // Get the NCOA record and make sure it still hasn't been processed
                    var ncoaHistory = new NcoaHistoryService(rockContext).Get(id);
                    if (ncoaHistory != null && ncoaHistory.Processed == Processed.NotProcessed)
                    {
                        var ncoaHistoryService   = new NcoaHistoryService(rockContext);
                        var groupService         = new GroupService(rockContext);
                        var groupLocationService = new GroupLocationService(rockContext);
                        var locationService      = new LocationService(rockContext);
                        var personService        = new PersonService(rockContext);

                        var familyChanges = new History.HistoryChangeList();

                        ncoaHistory.Processed = Processed.ManualUpdateRequired;

                        // If we're able to mark the existing address as previous and successfully create a new home address..
                        var previousGroupLocation = MarkAsPreviousLocation(ncoaHistory, groupLocationService, previousValueId, familyChanges);
                        if (previousGroupLocation != null)
                        {
                            if (AddNewHomeLocation(ncoaHistory, locationService, groupLocationService, homeValueId, familyChanges, previousGroupLocation.IsMailingLocation, previousGroupLocation.IsMappedLocation))
                            {
                                // set the status to 'Complete'
                                ncoaHistory.Processed = Processed.Complete;

                                // Look for any other moves for the same family and to same address, and set their status to complete as well
                                foreach (var ncoaIndividual in ncoaHistoryService
                                         .Queryable().Where(n =>
                                                            n.Processed == Processed.NotProcessed &&
                                                            n.NcoaType == NcoaType.Move &&
                                                            n.FamilyId == ncoaHistory.FamilyId &&
                                                            n.Id != ncoaHistory.Id &&
                                                            n.UpdatedStreet1 == ncoaHistory.UpdatedStreet1))
                                {
                                    ncoaIndividual.Processed = Processed.Complete;
                                }

                                // If there were any changes, write to history and check to see if person should be inactivated
                                if (familyChanges.Any())
                                {
                                    var family = groupService.Get(ncoaHistory.FamilyId);
                                    if (family != null)
                                    {
                                        foreach (var fm in family.Members)
                                        {
                                            if (ncoaHistory.MoveDistance.HasValue && minMoveDistance.HasValue &&
                                                ncoaHistory.MoveDistance.Value >= minMoveDistance.Value)
                                            {
                                                History.HistoryChangeList personChanges;

                                                personService.InactivatePerson(fm.Person, inactiveReason,
                                                                               $"Received a Change of Address (NCOA) notice that was for more than {minMoveDistance} miles away.", out personChanges);

                                                if (personChanges.Any())
                                                {
                                                    HistoryService.SaveChanges(
                                                        rockContext,
                                                        typeof(Person),
                                                        SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                                        fm.PersonId,
                                                        personChanges,
                                                        false);
                                                }
                                            }

                                            HistoryService.SaveChanges(
                                                rockContext,
                                                typeof(Person),
                                                SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                                fm.PersonId,
                                                familyChanges,
                                                family.Name,
                                                typeof(Group),
                                                family.Id,
                                                false);
                                        }
                                    }
                                }
                            }
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
        }
        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);
        }
Exemple #15
0
        /// <summary>
        /// Handles the ItemCommand event of the rptNcoaResults control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void rptNcoaResults_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            var ncoaHistoryId = e.CommandArgument.ToStringSafe().AsIntegerOrNull();

            if (!ncoaHistoryId.HasValue)
            {
                return;
            }

            if (e.CommandName == "MarkAddressAsPrevious")
            {
                using (var rockContext = new RockContext())
                {
                    var ncoaHistory = new NcoaHistoryService(rockContext).Get(ncoaHistoryId.Value);
                    if (ncoaHistory != null)
                    {
                        var groupService         = new GroupService(rockContext);
                        var groupLocationService = new GroupLocationService(rockContext);

                        var changes = new History.HistoryChangeList();

                        Ncoa ncoa                  = new Ncoa();
                        var  previousValue         = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                        int? previousValueId       = previousValue == null ? ( int? )null : previousValue.Id;
                        var  previousGroupLocation = ncoa.MarkAsPreviousLocation(ncoaHistory, groupLocationService, previousValueId, changes);
                        if (previousGroupLocation != null)
                        {
                            ncoaHistory.Processed = Processed.Complete;

                            // If there were any changes, write to history
                            if (changes.Any())
                            {
                                var family = groupService.Get(ncoaHistory.FamilyId);
                                if (family != null)
                                {
                                    foreach (var fm in family.Members)
                                    {
                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof(Person),
                                            Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                            fm.PersonId,
                                            changes,
                                            family.Name,
                                            typeof(Group),
                                            family.Id,
                                            false);
                                    }
                                }
                            }
                        }
                    }

                    rockContext.SaveChanges();
                }
            }
            else if (e.CommandName == "MarkProcessed")
            {
                using (RockContext rockContext = new RockContext())
                {
                    var ncoa = (new NcoaHistoryService(rockContext)).Get(ncoaHistoryId.Value);
                    ncoa.Processed = Processed.Complete;
                    rockContext.SaveChanges();
                }
            }

            NcoaResults_BlockUpdated(null, null);
        }
        protected void SaveDetails()
        {
            var      checkValue = false;
            CheckBox check      = ( CheckBox )fsAttributes.FindControl("SimpleCheckBox");

            if (check != null && check.Checked)
            {
                checkValue = true;
            }

            IHasAttributes entity = ContextEntity() as IHasAttributes;

            var rockContext          = new RockContext();
            var sourceAttributeKey   = GetAttributeValue("SourceEntityAttributeKey");
            var sourceAttributeValue = entity.GetAttributeValue(sourceAttributeKey);
            var attributeService     = new AttributeService(rockContext);
            var targetAttribute      = attributeService.GetByGuids(new List <Guid>()
            {
                sourceAttributeValue.AsGuid()
            }).ToList().FirstOrDefault();

            int personEntityTypeId = EntityTypeCache.Get(typeof(Person)).Id;

            var changes = new History.HistoryChangeList();

            var attribute = AttributeCache.Get(targetAttribute);

            if (CurrentPerson != null)
            {
                Control attributeControl = fsAttributes.FindControl(string.Format("attribute_field_{0}", attribute.Id));
                if (GetAttributeValue("CheckboxMode").AsBoolean(false) || attributeControl != null)
                {
                    string originalValue = CurrentPerson.GetAttributeValue(attribute.Key);
                    string newValue      = string.Empty;

                    if (GetAttributeValue("CheckboxMode").AsBoolean(false))
                    {
                        var valueMode = GetAttributeValue("CheckboxAttributeValueMode");
                        if (valueMode == "Date")
                        {
                            if (checkValue)
                            {
                                newValue = RockDateTime.Now.ToString();
                            }
                            else
                            {
                                newValue = string.Empty;
                            }
                        }
                        else if (valueMode == "Boolean")
                        {
                            if (checkValue)
                            {
                                newValue = "True";
                            }
                            else
                            {
                                newValue = "False";
                            }
                        }
                    }
                    else
                    {
                        newValue = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues);
                    }

                    Rock.Attribute.Helper.SaveAttributeValue(CurrentPerson, attribute, newValue, rockContext);

                    // Check for changes to write to history
                    if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                    {
                        string formattedOriginalValue = string.Empty;
                        if (!string.IsNullOrWhiteSpace(originalValue))
                        {
                            formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                        }

                        string formattedNewValue = string.Empty;
                        if (!string.IsNullOrWhiteSpace(newValue))
                        {
                            formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                        }

                        History.EvaluateChange(changes, attribute.Name, formattedOriginalValue, formattedNewValue, attribute.FieldType.Field.IsSensitive());
                    }
                }
            }

            if (changes.Any())
            {
                HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                           CurrentPerson.Id, changes);
            }

            string linkedPage = GetAttributeValue("RedirectPage");

            if (string.IsNullOrWhiteSpace(linkedPage))
            {
                ShowDetails();
            }
            else
            {
                var pageParams = new Dictionary <string, string>();
                pageParams.Add("av", "updated");
                var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                Response.Redirect(pageReference.BuildUrl(), false);
            }
        }
        protected void btnExportToFinancialEdge_Click(object sender, EventArgs e)
        {
            if (_financialBatch != null)
            {
                var rockContext = new RockContext();
                var feJournal   = new FEJournal();

                var items = feJournal.GetGlEntries(rockContext, _financialBatch, GetAttributeValue("JournalType"));

                if (items.Count > 0)
                {
                    //
                    // Set session for export file
                    //
                    feJournal.SetFinancialEdgeSessions(items, _financialBatch.Id.ToString());

                    //
                    // vars we need now
                    //
                    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.FinancialEdge.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.FinancialEdge.DateExported", newDate);
                    financialBatch.SaveAttributeValue("rocks.kfs.FinancialEdge.DateExported", rockContext);
                }
            }

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

            int batchId = hfBatchId.Value.AsInteger();

            if (batchId == 0)
            {
                batch = new FinancialBatch();
                batchService.Add(batch);
                changes.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Batch");
            }
            else
            {
                batch = batchService.Get(batchId);
            }

            if (batch != null)
            {
                if (dvpBatchName.Visible)
                {
                    History.EvaluateChange(changes, "Batch Name", batch.Name, dvpBatchName.SelectedItem.Text);
                    batch.Name = dvpBatchName.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.Get(batch.CampusId.Value);
                }

                CampusCache newCampus = null;
                if (campCampus.SelectedCampusId.HasValue)
                {
                    newCampus = CampusCache.Get(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;

                int?controlItemCount = nbControlItemCount.Text.AsIntegerOrNull();
                History.EvaluateChange(changes, "Control Item Count", batch.ControlItemCount.FormatAsCurrency(), controlItemCount.FormatAsCurrency());
                batch.ControlItemCount = controlItemCount;

                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");
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// Processes the NCOA results: Mark all 48 month move addresses as previous and processed if enabled, otherwise mark as manual update required.
        /// </summary>
        /// <param name="mark48MonthAsPrevious">if a 48 month move should be marked as previous, set to <c>true</c>.</param>
        /// <param name="previousValueId">The previous value identifier.</param>
        private void ProcessNcoaResults48MonthMove(bool mark48MonthAsPrevious, int?previousValueId)
        {
            List <int> ncoaIds = null;

            // Process the '48 Month Move' NCOA Types
            using (var rockContext = new RockContext())
            {
                ncoaIds = new NcoaHistoryService(rockContext)
                          .Queryable().AsNoTracking()
                          .Where(n =>
                                 n.Processed == Processed.NotProcessed &&
                                 n.NcoaType == NcoaType.Month48Move)
                          .Select(n => n.Id)
                          .ToList();
            }

            foreach (int id in ncoaIds)
            {
                using (var rockContext = new RockContext())
                {
                    var ncoaHistory = new NcoaHistoryService(rockContext).Get(id);
                    if (ncoaHistory != null)
                    {
                        var groupService         = new GroupService(rockContext);
                        var groupLocationService = new GroupLocationService(rockContext);

                        var changes = new History.HistoryChangeList();

                        // If configured to mark these as previous, and we're able to mark it as previous set the status to 'Complete'
                        // otherwise set it to require a manual update
                        if (mark48MonthAsPrevious && MarkAsPreviousLocation(ncoaHistory, groupLocationService, previousValueId, changes) != null)
                        {
                            ncoaHistory.Processed = Processed.Complete;

                            // If there were any changes, write to history
                            if (changes.Any())
                            {
                                var family = groupService.Get(ncoaHistory.FamilyId);
                                if (family != null)
                                {
                                    foreach (var fm in family.Members)
                                    {
                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof(Person),
                                            SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                            fm.PersonId,
                                            changes,
                                            family.Name,
                                            typeof(Group),
                                            family.Id,
                                            false);
                                    }
                                }
                            }
                        }
                        else
                        {
                            ncoaHistory.Processed = Processed.ManualUpdateRequired;
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
        }