示例#1
0
        /// <summary>
        /// Maps the activity ministry.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapActivityMinistry( IQueryable<Row> tableData )
        {
            int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
            var attributeService = new AttributeService();

            // Add an Attribute for the unique F1 Ministry Id
            var ministryAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == groupEntityTypeId
                && a.Key == "F1MinistryId" ).Select( a => a.Id ).FirstOrDefault();
            if ( ministryAttributeId == 0 )
            {
                var newMinistryAttribute = new Rock.Model.Attribute();
                newMinistryAttribute.Key = "F1MinistryId";
                newMinistryAttribute.Name = "F1 Ministry Id";
                newMinistryAttribute.FieldTypeId = IntegerFieldTypeId;
                newMinistryAttribute.EntityTypeId = groupEntityTypeId;
                newMinistryAttribute.EntityTypeQualifierValue = string.Empty;
                newMinistryAttribute.EntityTypeQualifierColumn = string.Empty;
                newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported";
                newMinistryAttribute.DefaultValue = string.Empty;
                newMinistryAttribute.IsMultiValue = false;
                newMinistryAttribute.IsRequired = false;
                newMinistryAttribute.Order = 0;

                attributeService.Add( newMinistryAttribute, ImportPersonAlias );
                attributeService.Save( newMinistryAttribute, ImportPersonAlias );
                ministryAttributeId = newMinistryAttribute.Id;
            }

            // Get previously imported Ministries
            var importedMinistries = new AttributeValueService().GetByAttributeId( ministryAttributeId )
                .Select( av => new { RLCId = av.Value.AsType<int?>(), LocationId = av.EntityId } )
                .ToDictionary( t => t.RLCId, t => t.LocationId );

            foreach ( var row in tableData )
            {
                int? ministryId = row["Ministry_ID"] as int?;
                if ( ministryId != null && !importedMinistries.ContainsKey( ministryId ) )
                {
                    // Activity_ID
                    // Ministry_Name
                    // Activity_Name
                    // Ministry_Active
                    // Activity_Active
                }
            }
        }
示例#2
0
        /// <summary>
        /// Gets the root matrix attribute value that ties the matrix values to a person or other entity.
        /// </summary>
        /// <returns></returns>
        private AttributeValue GetRootMatrixAttributeValue()
        {
            var rockContext            = new RockContext();
            var attributeMatrixService = new AttributeMatrixService(rockContext);
            var attributeService       = new AttributeService(rockContext);
            var attributeValueService  = new AttributeValueService(rockContext);

            var matrixGuidQuery = attributeMatrixService.Queryable().AsNoTracking().Where(am =>
                                                                                          am.AttributeMatrixItems.Any(ami => ami.Id == EntityId))
                                  .Select(am => am.Guid.ToString());

            var matrixFieldType  = FieldTypeCache.Get(SystemGuid.FieldType.MATRIX);
            var attributeIdQuery = attributeService.Queryable().AsNoTracking().Where(a =>
                                                                                     a.FieldTypeId == matrixFieldType.Id)
                                   .Select(a => a.Id);

            var attributeValue = attributeValueService.Queryable().AsNoTracking().FirstOrDefault(av =>
                                                                                                 attributeIdQuery.Contains(av.AttributeId) && matrixGuidQuery.Contains(av.Value));

            return(attributeValue);
        }
        /// <summary>
        /// Gets the Attributes for a Group Member of a specific Group Type.
        /// </summary>
        /// <returns></returns>
        private List<EntityField> GetGroupMemberAttributes()
        {
            var entityAttributeFields = new Dictionary<string, EntityField>();
            var context = new RockContext();

            var attributeService = new AttributeService( context );
            var groupTypeService = new GroupTypeService( context );

            var groupMemberEntityTypeId = EntityTypeCache.GetId( typeof(Model.GroupMember) );

            var groupMemberAttributes = attributeService.Queryable()
                                                        .AsNoTracking()
                                                        .Where( a => a.EntityTypeId == groupMemberEntityTypeId )
                                                        .Join( groupTypeService.Queryable(), a => a.EntityTypeQualifierValue, gt => gt.Id.ToString(),
                                                               ( a, gt ) =>
                                                               new
                                                               {
                                                                   Attribute = a,
                                                                   AttributeKey = a.Key,
                                                                   FieldTypeName = a.FieldType.Name,
                                                                   a.FieldTypeId,
                                                                   AttributeName = a.Name,
                                                                   GroupTypeName = gt.Name
                                                               } )
                                                        .GroupBy( x => x.AttributeName )
                                                        .ToList();

            foreach (var attributesByName in groupMemberAttributes)
            {
                var attributeNameAndTypeGroups = attributesByName.GroupBy( x => x.FieldTypeId ).ToList();

                bool requiresTypeQualifier = ( attributeNameAndTypeGroups.Count > 1 );

                foreach (var attributeNameAndTypeGroup in attributeNameAndTypeGroups)
                {
                    foreach (var attribute in attributeNameAndTypeGroup)
                    {
                        string fieldKey;
                        string fieldName;

                        if (requiresTypeQualifier)
                        {
                            fieldKey = attribute.AttributeName + "_" + attribute.FieldTypeId;

                            fieldName = string.Format( "{0} [{1}]", attribute.AttributeName, attribute.FieldTypeName );
                        }
                        else
                        {
                            fieldName = attribute.AttributeName;
                            fieldKey = attribute.AttributeName;
                        }

                        if (entityAttributeFields.ContainsKey( fieldKey ))
                        {
                            continue;
                        }

                        var attributeCache = AttributeCache.Read( attribute.Attribute );

                        var entityField = EntityHelper.GetEntityFieldForAttribute( attributeCache );

                        entityField.Title = fieldName;
                        entityField.AttributeGuid = null;

                        entityAttributeFields.Add( fieldKey, entityField );
                    }
                }
            }

            int index = 0;
            var sortedFields = new List<EntityField>();
            foreach (var entityProperty in entityAttributeFields.Values.OrderBy( p => p.Title ).ThenBy( p => p.Name ))
            {
                entityProperty.Index = index;
                index++;
                sortedFields.Add( entityProperty );
            }

            return sortedFields;
        }
示例#4
0
        /// <summary>
        /// Saves any attribute edits made using an Attribute Editor control
        /// </summary>
        /// <param name="edtAttribute">The edt attribute.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param>
        /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static Rock.Model.Attribute SaveAttributeEdits( AttributeEditor edtAttribute, int? entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null )
        {
            // Create and update a new attribute object with new values
            var newAttribute = new Rock.Model.Attribute();
            edtAttribute.GetAttributeProperties( newAttribute );

            rockContext = rockContext ?? new RockContext();
            var internalAttributeService = new AttributeService( rockContext );
            Rock.Model.Attribute attribute = null;

            if ( newAttribute.Id > 0 )
            {
                attribute = internalAttributeService.Get( newAttribute.Id );
            }

            if ( attribute == null )
            {
                newAttribute.Order = internalAttributeService.Queryable().Max( a => a.Order ) + 1;
            }
            else
            {
                newAttribute.Order = attribute.Order;
            } 
            
            return SaveAttributeEdits( newAttribute, entityTypeId, entityTypeQualifierColumn, entityTypeQualifierValue, rockContext );
        }
示例#5
0
        /// <summary>
        /// Loads the <see cref="P:IHasAttributes.Attributes" /> and <see cref="P:IHasAttributes.AttributeValues" /> of any <see cref="IHasAttributes" /> object
        /// </summary>
        /// <param name="entity">The item.</param>
        /// <param name="rockContext">The rock context.</param>
        public static void LoadAttributes( Rock.Attribute.IHasAttributes entity, RockContext rockContext )
        {
            if ( entity != null )
            {
                Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();

                Type entityType = entity.GetType();
                if ( entityType.Namespace == "System.Data.Entity.DynamicProxies" )
                    entityType = entityType.BaseType;

                rockContext = rockContext ?? new RockContext();

                // Check for group type attributes
                var groupTypeIds = new List<int>();
                if ( entity is GroupMember || entity is Group || entity is GroupType )
                {
                    // Can't use GroupTypeCache here since it loads attributes and would result in a recursive stack overflow situation
                    var groupTypeService = new GroupTypeService( rockContext );
                    GroupType groupType = null;

                    if ( entity is GroupMember )
                    {
                        var group = ( (GroupMember)entity ).Group ?? new GroupService( rockContext )
                            .Queryable().AsNoTracking().FirstOrDefault(g => g.Id == ( (GroupMember)entity ).GroupId );
                        if ( group != null )
                        {
                            groupType = group.GroupType ?? groupTypeService
                                .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == group.GroupTypeId );
                        }
                    }
                    else if ( entity is Group )
                    {
                        groupType = ( (Group)entity ).GroupType ?? groupTypeService
                            .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == ( (Group)entity ).GroupTypeId );
                    }
                    else
                    {
                        groupType = ( (GroupType)entity );
                    }

                    while ( groupType != null )
                    {
                        groupTypeIds.Insert( 0, groupType.Id );

                        // Check for inherited group type id's
                        if ( groupType.InheritedGroupTypeId.HasValue )
                        {
                            groupType = groupType.InheritedGroupType ?? groupTypeService
                                .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == ( groupType.InheritedGroupTypeId ?? 0 ) );
                        }
                        else
                        {
                            groupType = null;
                        }
                    }

                }

                foreach ( PropertyInfo propertyInfo in entityType.GetProperties() )
                    properties.Add( propertyInfo.Name.ToLower(), propertyInfo );

                Rock.Model.AttributeService attributeService = new Rock.Model.AttributeService( rockContext );
                Rock.Model.AttributeValueService attributeValueService = new Rock.Model.AttributeValueService( rockContext );

                var inheritedAttributes = new Dictionary<int, List<Rock.Web.Cache.AttributeCache>>();
                if ( groupTypeIds.Any() )
                {
                    groupTypeIds.ForEach( g => inheritedAttributes.Add( g, new List<Rock.Web.Cache.AttributeCache>() ) );
                }
                else
                {
                    inheritedAttributes.Add( 0, new List<Rock.Web.Cache.AttributeCache>() );
                }

                var attributes = new List<Rock.Web.Cache.AttributeCache>();

                // Get all the attributes that apply to this entity type and this entity's properties match any attribute qualifiers
                var entityTypeCache = Rock.Web.Cache.EntityTypeCache.Read( entityType);
                if ( entityTypeCache != null )
                {
                    int entityTypeId = entityTypeCache.Id;
                    foreach ( var attribute in attributeService.Queryable()
                        .AsNoTracking()
                        .Where( a => a.EntityTypeId == entityTypeCache.Id )
                        .Select( a => new
                        {
                            a.Id,
                            a.EntityTypeQualifierColumn,
                            a.EntityTypeQualifierValue
                        }
                        ) )
                    {
                        // group type ids exist (entity is either GroupMember, Group, or GroupType) and qualifier is for a group type id
                        if ( groupTypeIds.Any() && (
                                ( entity is GroupMember && string.Compare( attribute.EntityTypeQualifierColumn, "GroupTypeId", true ) == 0 ) ||
                                ( entity is Group && string.Compare( attribute.EntityTypeQualifierColumn, "GroupTypeId", true ) == 0 ) ||
                                ( entity is GroupType && string.Compare( attribute.EntityTypeQualifierColumn, "Id", true ) == 0 ) ) )
                        {
                            int groupTypeIdValue = int.MinValue;
                            if ( int.TryParse( attribute.EntityTypeQualifierValue, out groupTypeIdValue ) && groupTypeIds.Contains( groupTypeIdValue ) )
                            {
                                inheritedAttributes[groupTypeIdValue].Add( Rock.Web.Cache.AttributeCache.Read( attribute.Id ) );
                            }
                        }

                        else if ( string.IsNullOrEmpty( attribute.EntityTypeQualifierColumn ) ||
                            ( properties.ContainsKey( attribute.EntityTypeQualifierColumn.ToLower() ) &&
                            ( string.IsNullOrEmpty( attribute.EntityTypeQualifierValue ) ||
                            ( properties[attribute.EntityTypeQualifierColumn.ToLower()].GetValue( entity, null ) ?? "" ).ToString() == attribute.EntityTypeQualifierValue ) ) )
                        {
                            attributes.Add( Rock.Web.Cache.AttributeCache.Read( attribute.Id ) );
                        }
                    }
                }

                var allAttributes = new List<Rock.Web.Cache.AttributeCache>();

                foreach ( var attributeGroup in inheritedAttributes )
                {
                    foreach ( var attribute in attributeGroup.Value )
                    {
                        allAttributes.Add( attribute );
                    }
                }
                foreach ( var attribute in attributes )
                {
                    allAttributes.Add( attribute );
                }

                var attributeValues = new Dictionary<string, Rock.Model.AttributeValue>();

                if ( allAttributes.Any() )
                {
                    foreach ( var attribute in allAttributes )
                    {
                        // Add a placeholder for this item's value for each attribute
                        attributeValues.Add( attribute.Key, null );
                    }

                    // If loading attributes for a saved item, read the item's value(s) for each attribute 
                    if ( !entityTypeCache.IsEntity || entity.Id != 0 )
                    {
                        List<int> attributeIds = allAttributes.Select( a => a.Id ).ToList();
                        foreach ( var attributeValue in attributeValueService.Queryable().AsNoTracking()
                            .Where( v => v.EntityId == entity.Id && attributeIds.Contains( v.AttributeId ) ) )
                        {
                            var attributeKey = AttributeCache.Read( attributeValue.AttributeId ).Key;
                            attributeValues[attributeKey] = attributeValue.Clone( false ) as Rock.Model.AttributeValue;
                        }
                    }

                    // Look for any attributes that don't have a value and create a default value entry
                    foreach ( var attribute in allAttributes )
                    {
                        if ( attributeValues[attribute.Key] == null )
                        {
                            var attributeValue = new Rock.Model.AttributeValue();
                            attributeValue.AttributeId = attribute.Id;
                            if ( entity.AttributeValueDefaults != null && entity.AttributeValueDefaults.ContainsKey( attribute.Name ) )
                            {
                                attributeValue.Value = entity.AttributeValueDefaults[attribute.Name];
                            }
                            else
                            {
                                attributeValue.Value = attribute.DefaultValue;
                            }
                            attributeValues[attribute.Key] = attributeValue;
                        }
                        else
                        {
                            if ( !String.IsNullOrWhiteSpace( attribute.DefaultValue ) &&
                                String.IsNullOrWhiteSpace( attributeValues[attribute.Key].Value ) )
                            {
                                attributeValues[attribute.Key].Value = attribute.DefaultValue;
                            }
                        }
                    }
                }

                entity.Attributes = new Dictionary<string, Web.Cache.AttributeCache>();
                allAttributes.ForEach( a => entity.Attributes.Add( a.Key, a ) );

                entity.AttributeValues = attributeValues;
            }
        }
示例#6
0
        private IQueryable<Rock.Model.Attribute> GetData( RockContext rockContext )
        {
            IQueryable<Rock.Model.Attribute> query = null;

            AttributeService attributeService = new AttributeService( rockContext );
            if ( _configuredType )
            {
                query = attributeService.Get( _entityTypeId, _entityQualifierColumn, _entityQualifierValue );
            }
            else
            {
                int? entityTypeId = rFilter.GetUserPreference( "Entity Type" ).AsIntegerOrNull();
                if ( entityTypeId.HasValue )
                {
                    if ( entityTypeId.Value == 0 )
                    {
                        // Global Attributes
                        query = attributeService.GetByEntityTypeId( null );
                    }
                    else
                    {
                        query = attributeService.GetByEntityTypeId( entityTypeId );
                    }
                }
                else
                {
                    // All entity attribute
                    query = attributeService.Queryable()
                        .Where( a =>
                            ( a.EntityType != null && a.EntityType.IsEntity ) ||    // Entity Attributes
                            ( a.EntityType == null && a.EntityTypeQualifierColumn == "" && a.EntityTypeQualifierValue == "" ) // Global Attributes
                        );
                }
            }

            // if filtering by block setting of categories
            if (!string.IsNullOrWhiteSpace( GetAttributeValue( "CategoryFilter" ) ) )
            {
                try {
                    var categoryGuids = GetAttributeValue( "CategoryFilter" ).Split( ',' ).Select( Guid.Parse ).ToList();

                    query = query.Where( a => a.Categories.Any( c => categoryGuids.Contains( c.Guid ) ) );
                }
                catch { }
            }

            var selectedCategoryIds = new List<int>();
            rFilter.GetUserPreference( "Categories" ).SplitDelimitedValues().ToList().ForEach( s => selectedCategoryIds.Add( int.Parse( s ) ) );
            if ( selectedCategoryIds.Any() )
            {
                query = query.Where( a => a.Categories.Any( c => selectedCategoryIds.Contains( c.Id ) ) );
            }

            if ( _enableOrdering )
            {
                query = query.OrderBy( a => a.Order );
            }
            else
            {
                SortProperty sortProperty = rGrid.SortProperty;
                if ( sortProperty != null )
                {
                    query = query.Sort( sortProperty );
                }
                else
                {
                    query = query.OrderBy( a => a.Key );
                }
            }

            return query;
        }
示例#7
0
        /// <summary>
        /// Maps the RLC data to rooms, locations & classes
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapRLC( IQueryable<Row> tableData )
        {
            int locationEntityTypeId = EntityTypeCache.Read( "Rock.Model.Location" ).Id;
            int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
            var attributeService = new AttributeService();

            // Add an Attribute for the unique F1 RLC Id
            var rlcAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == locationEntityTypeId
                && a.Key == "F1RLCId" ).Select( a => a.Id ).FirstOrDefault();
            if ( rlcAttributeId == 0 )
            {
                var newRLCAttribute = new Rock.Model.Attribute();
                newRLCAttribute.Key = "F1RLCId";
                newRLCAttribute.Name = "F1 RLC Id";
                newRLCAttribute.FieldTypeId = IntegerFieldTypeId;
                newRLCAttribute.EntityTypeId = locationEntityTypeId;
                newRLCAttribute.EntityTypeQualifierValue = string.Empty;
                newRLCAttribute.EntityTypeQualifierColumn = string.Empty;
                newRLCAttribute.Description = "The FellowshipOne identifier for the RLC (Room/Location/Class) that was imported";
                newRLCAttribute.DefaultValue = string.Empty;
                newRLCAttribute.IsMultiValue = false;
                newRLCAttribute.IsRequired = false;
                newRLCAttribute.Order = 0;

                attributeService.Add( newRLCAttribute, ImportPersonAlias );
                attributeService.Save( newRLCAttribute, ImportPersonAlias );
                rlcAttributeId = newRLCAttribute.Id;
            }

            // Add an Attribute for the unique F1 Activity Id
            var activityAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == locationEntityTypeId
                && a.Key == "F1ActivityId" ).Select( a => a.Id ).FirstOrDefault();
            if ( rlcAttributeId == 0 )
            {
                var newActivityAttribute = new Rock.Model.Attribute();
                newActivityAttribute.Key = "F1ActivityId";
                newActivityAttribute.Name = "F1 Activity Id";
                newActivityAttribute.FieldTypeId = IntegerFieldTypeId;
                newActivityAttribute.EntityTypeId = locationEntityTypeId;
                newActivityAttribute.EntityTypeQualifierValue = string.Empty;
                newActivityAttribute.EntityTypeQualifierColumn = string.Empty;
                newActivityAttribute.Description = "The FellowshipOne identifier for the activity that was imported";
                newActivityAttribute.DefaultValue = string.Empty;
                newActivityAttribute.IsMultiValue = false;
                newActivityAttribute.IsRequired = false;
                newActivityAttribute.Order = 0;

                attributeService.Add( newActivityAttribute, ImportPersonAlias );
                attributeService.Save( newActivityAttribute, ImportPersonAlias );
                activityAttributeId = newActivityAttribute.Id;
            }

            var rlcAttribute = AttributeCache.Read( rlcAttributeId );
            var activityAttribute = AttributeCache.Read( activityAttributeId );

            // Get any previously imported RLCs
            var importedRLC = new AttributeValueService().GetByAttributeId( rlcAttributeId )
                .Select( av => new { RLCId = av.Value.AsType<int?>(), LocationId = av.EntityId } )
                .ToDictionary( t => t.RLCId, t => t.LocationId );

            ImportedActivities = new AttributeValueService().GetByAttributeId( activityAttributeId )
                .Select( av => new { ActivityId = av.Value.AsType<int?>(), GroupId = av.EntityId } )
                .ToDictionary( t => t.ActivityId, t => t.GroupId );

            foreach ( var row in tableData )
            {
                int? rlcId = row["RLC_ID"] as int?;
                if ( rlcId != null && !importedRLC.ContainsKey( rlcId ) )
                {
                    // Activity_ID
                    // RLC_Name
                    // Activity_Group_ID
                    // Start_Age_Date
                    // End_Age_Date
                    // Is_Active
                    // Room_Code
                    // Room_Desc
                    // Room_Name
                    // Max_Capacity
                    // Building_Name
                }
            }
        }
示例#8
0
        /// <summary>
        /// Loads the <see cref="P:IHasAttributes.Attributes" /> and <see cref="P:IHasAttributes.AttributeValues" /> of any <see cref="IHasAttributes" /> object
        /// </summary>
        /// <param name="entity">The item.</param>
        /// <param name="rockContext">The rock context.</param>
        public static void LoadAttributes(Rock.Attribute.IHasAttributes entity, RockContext rockContext)
        {
            if (entity != null)
            {
                Dictionary <string, PropertyInfo> properties = new Dictionary <string, PropertyInfo>();

                Type entityType = entity.GetType();
                if (entityType.Namespace == "System.Data.Entity.DynamicProxies")
                {
                    entityType = entityType.BaseType;
                }

                rockContext = rockContext ?? new RockContext();

                // Check for group type attributes
                var groupTypeIds = new List <int>();
                if (entity is GroupMember || entity is Group || entity is GroupType)
                {
                    // Can't use GroupTypeCache here since it loads attributes and would result in a recursive stack overflow situation
                    var       groupTypeService = new GroupTypeService(rockContext);
                    GroupType groupType        = null;

                    if (entity is GroupMember)
                    {
                        var group = ((GroupMember)entity).Group ?? new GroupService(rockContext)
                                    .Queryable().AsNoTracking().FirstOrDefault(g => g.Id == ((GroupMember)entity).GroupId);
                        if (group != null)
                        {
                            groupType = group.GroupType ?? groupTypeService
                                        .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == group.GroupTypeId);
                        }
                    }
                    else if (entity is Group)
                    {
                        groupType = ((Group)entity).GroupType ?? groupTypeService
                                    .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == ((Group)entity).GroupTypeId);
                    }
                    else
                    {
                        groupType = ((GroupType)entity);
                    }

                    while (groupType != null)
                    {
                        groupTypeIds.Insert(0, groupType.Id);

                        // Check for inherited group type id's
                        if (groupType.InheritedGroupTypeId.HasValue)
                        {
                            groupType = groupType.InheritedGroupType ?? groupTypeService
                                        .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == (groupType.InheritedGroupTypeId ?? 0));
                        }
                        else
                        {
                            groupType = null;
                        }
                    }
                }

                foreach (PropertyInfo propertyInfo in entityType.GetProperties())
                {
                    properties.Add(propertyInfo.Name.ToLower(), propertyInfo);
                }

                Rock.Model.AttributeService      attributeService      = new Rock.Model.AttributeService(rockContext);
                Rock.Model.AttributeValueService attributeValueService = new Rock.Model.AttributeValueService(rockContext);

                var inheritedAttributes = new Dictionary <int, List <Rock.Web.Cache.AttributeCache> >();
                if (groupTypeIds.Any())
                {
                    groupTypeIds.ForEach(g => inheritedAttributes.Add(g, new List <Rock.Web.Cache.AttributeCache>()));
                }
                else
                {
                    inheritedAttributes.Add(0, new List <Rock.Web.Cache.AttributeCache>());
                }

                var attributes = new List <Rock.Web.Cache.AttributeCache>();

                // Get all the attributes that apply to this entity type and this entity's properties match any attribute qualifiers
                var entityTypeCache = Rock.Web.Cache.EntityTypeCache.Read(entityType);
                if (entityTypeCache != null)
                {
                    int entityTypeId = entityTypeCache.Id;
                    foreach (var attribute in attributeService.Queryable()
                             .AsNoTracking()
                             .Where(a => a.EntityTypeId == entityTypeCache.Id)
                             .Select(a => new
                    {
                        a.Id,
                        a.EntityTypeQualifierColumn,
                        a.EntityTypeQualifierValue
                    }
                                     ))
                    {
                        // group type ids exist (entity is either GroupMember, Group, or GroupType) and qualifier is for a group type id
                        if (groupTypeIds.Any() && (
                                (entity is GroupMember && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) ||
                                (entity is Group && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) ||
                                (entity is GroupType && string.Compare(attribute.EntityTypeQualifierColumn, "Id", true) == 0)))
                        {
                            int groupTypeIdValue = int.MinValue;
                            if (int.TryParse(attribute.EntityTypeQualifierValue, out groupTypeIdValue) && groupTypeIds.Contains(groupTypeIdValue))
                            {
                                inheritedAttributes[groupTypeIdValue].Add(Rock.Web.Cache.AttributeCache.Read(attribute.Id));
                            }
                        }

                        else if (string.IsNullOrEmpty(attribute.EntityTypeQualifierColumn) ||
                                 (properties.ContainsKey(attribute.EntityTypeQualifierColumn.ToLower()) &&
                                  (string.IsNullOrEmpty(attribute.EntityTypeQualifierValue) ||
                                   (properties[attribute.EntityTypeQualifierColumn.ToLower()].GetValue(entity, null) ?? "").ToString() == attribute.EntityTypeQualifierValue)))
                        {
                            attributes.Add(Rock.Web.Cache.AttributeCache.Read(attribute.Id));
                        }
                    }
                }

                var allAttributes = new List <Rock.Web.Cache.AttributeCache>();

                foreach (var attributeGroup in inheritedAttributes)
                {
                    foreach (var attribute in attributeGroup.Value)
                    {
                        allAttributes.Add(attribute);
                    }
                }
                foreach (var attribute in attributes)
                {
                    allAttributes.Add(attribute);
                }

                var attributeValues = new Dictionary <string, Rock.Model.AttributeValue>();

                if (allAttributes.Any())
                {
                    foreach (var attribute in allAttributes)
                    {
                        // Add a placeholder for this item's value for each attribute
                        attributeValues.Add(attribute.Key, null);
                    }

                    // If loading attributes for a saved item, read the item's value(s) for each attribute
                    if (!entityTypeCache.IsEntity || entity.Id != 0)
                    {
                        List <int> attributeIds = allAttributes.Select(a => a.Id).ToList();
                        foreach (var attributeValue in attributeValueService.Queryable().AsNoTracking()
                                 .Where(v => v.EntityId == entity.Id && attributeIds.Contains(v.AttributeId)))
                        {
                            var attributeKey = AttributeCache.Read(attributeValue.AttributeId).Key;
                            attributeValues[attributeKey] = attributeValue.Clone(false) as Rock.Model.AttributeValue;
                        }
                    }

                    // Look for any attributes that don't have a value and create a default value entry
                    foreach (var attribute in allAttributes)
                    {
                        if (attributeValues[attribute.Key] == null)
                        {
                            var attributeValue = new Rock.Model.AttributeValue();
                            attributeValue.AttributeId = attribute.Id;
                            if (entity.AttributeValueDefaults != null && entity.AttributeValueDefaults.ContainsKey(attribute.Name))
                            {
                                attributeValue.Value = entity.AttributeValueDefaults[attribute.Name];
                            }
                            else
                            {
                                attributeValue.Value = attribute.DefaultValue;
                            }
                            attributeValues[attribute.Key] = attributeValue;
                        }
                        else
                        {
                            if (!String.IsNullOrWhiteSpace(attribute.DefaultValue) &&
                                String.IsNullOrWhiteSpace(attributeValues[attribute.Key].Value))
                            {
                                attributeValues[attribute.Key].Value = attribute.DefaultValue;
                            }
                        }
                    }
                }

                entity.Attributes = new Dictionary <string, Web.Cache.AttributeCache>();
                allAttributes.ForEach(a => entity.Attributes.Add(a.Key, a));

                entity.AttributeValues = attributeValues;
            }
        }
示例#9
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var attributeValueService = new AttributeValueService();
            var attributeService = new AttributeService();

            IntegerFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.INTEGER ) ).Id;
            TextFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ) ).Id;
            PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            BatchEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialBatch" ).Id;

            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList();

            var householdAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1HouseholdId" );
            if ( householdAttribute == null )
            {
                householdAttribute = new Rock.Model.Attribute();
                householdAttribute.Key = "F1HouseholdId";
                householdAttribute.Name = "F1 Household Id";
                householdAttribute.FieldTypeId = IntegerFieldTypeId;
                householdAttribute.EntityTypeId = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue = string.Empty;
                householdAttribute.IsMultiValue = false;
                householdAttribute.IsRequired = false;
                householdAttribute.Order = 0;

                attributeService.Add( householdAttribute, ImportPersonAlias );
                attributeService.Save( householdAttribute, ImportPersonAlias );
                personAttributes.Add( householdAttribute );
            }

            var individualAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1IndividualId" );
            if ( individualAttribute == null )
            {
                individualAttribute = new Rock.Model.Attribute();
                individualAttribute.Key = "F1IndividualId";
                individualAttribute.Name = "F1 Individual Id";
                individualAttribute.FieldTypeId = IntegerFieldTypeId;
                individualAttribute.EntityTypeId = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue = string.Empty;
                individualAttribute.IsMultiValue = false;
                individualAttribute.IsRequired = false;
                individualAttribute.Order = 0;

                attributeService.Add( individualAttribute, ImportPersonAlias );
                attributeService.Save( individualAttribute, ImportPersonAlias );
                personAttributes.Add( individualAttribute );
            }

            IndividualAttributeId = individualAttribute.Id;
            HouseholdAttributeId = householdAttribute.Id;

            ReportProgress( 0, "Checking for existing people..." );
            var listHouseholdId = attributeValueService.GetByAttributeId( householdAttribute.Id ).Select( av => new { PersonId = av.EntityId, HouseholdId = av.Value } ).ToList();
            var listIndividualId = attributeValueService.GetByAttributeId( individualAttribute.Id ).Select( av => new { PersonId = av.EntityId, IndividualId = av.Value } ).ToList();

            ImportedPeople = listHouseholdId.GroupJoin( listIndividualId, household => household.PersonId,
                individual => individual.PersonId, ( household, individual ) => new ImportedPerson
                {
                    PersonId = household.PersonId,
                    HouseholdId = household.HouseholdId.AsType<int?>(),
                    IndividualId = individual.Select( i => i.IndividualId.AsType<int?>() ).FirstOrDefault()
                } ).ToList();

            var batchAttribute = attributeService.Queryable().FirstOrDefault( a => a.EntityTypeId == BatchEntityTypeId
                && a.Key == "F1BatchId" );
            if ( batchAttribute == null )
            {
                batchAttribute = new Rock.Model.Attribute();
                batchAttribute.Key = "F1BatchId";
                batchAttribute.Name = "F1 Batch Id";
                batchAttribute.FieldTypeId = IntegerFieldTypeId;
                batchAttribute.EntityTypeId = BatchEntityTypeId;
                batchAttribute.EntityTypeQualifierValue = string.Empty;
                batchAttribute.EntityTypeQualifierColumn = string.Empty;
                batchAttribute.Description = "The FellowshipOne identifier for the batch that was imported";
                batchAttribute.DefaultValue = string.Empty;
                batchAttribute.IsMultiValue = false;
                batchAttribute.IsRequired = false;
                batchAttribute.Order = 0;

                attributeService.Add( batchAttribute, ImportPersonAlias );
                attributeService.Save( batchAttribute, ImportPersonAlias );
            }

            BatchAttributeId = batchAttribute.Id;

            ReportProgress( 0, "Checking for existing contributions..." );
            ImportedBatches = new AttributeValueService().GetByAttributeId( batchAttribute.Id )
                .Select( av => new { F1BatchId = av.Value.AsType<int?>(), RockBatchId = av.EntityId } )
                .ToDictionary( t => t.F1BatchId, t => t.RockBatchId );

            CampusList = new CampusService().Queryable().ToList();
        }
示例#10
0
        /// <summary>
        /// Maps the contribution.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="selectedColumns">The selected columns.</param>
        private void MapContribution( IQueryable<Row> tableData, List<string> selectedColumns = null )
        {
            int transactionEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialTransaction" ).Id;
            var accountService = new FinancialAccountService();
            var attributeService = new AttributeService();

            var transactionTypeContributionId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ).Id;

            int currencyTypeACH = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH ) ).Id;
            int currencyTypeCash = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH ) ).Id;
            int currencyTypeCheck = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK ) ).Id;
            int currencyTypeCreditCard = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ).Id;

            List<DefinedValue> refundReasons = new DefinedValueService().Queryable().Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON ) ).ToList();

            List<FinancialPledge> pledgeList = new FinancialPledgeService().Queryable().ToList();

            List<FinancialAccount> accountList = accountService.Queryable().ToList();

            // Add an Attribute for the unique F1 Contribution Id
            int contributionAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == transactionEntityTypeId
                && a.Key == "F1ContributionId" ).Select( a => a.Id ).FirstOrDefault();
            if ( contributionAttributeId == 0 )
            {
                var newContributionAttribute = new Rock.Model.Attribute();
                newContributionAttribute.Key = "F1ContributionId";
                newContributionAttribute.Name = "F1 Contribution Id";
                newContributionAttribute.FieldTypeId = IntegerFieldTypeId;
                newContributionAttribute.EntityTypeId = transactionEntityTypeId;
                newContributionAttribute.EntityTypeQualifierValue = string.Empty;
                newContributionAttribute.EntityTypeQualifierColumn = string.Empty;
                newContributionAttribute.Description = "The FellowshipOne identifier for the contribution that was imported";
                newContributionAttribute.DefaultValue = string.Empty;
                newContributionAttribute.IsMultiValue = false;
                newContributionAttribute.IsRequired = false;
                newContributionAttribute.Order = 0;

                attributeService.Add( newContributionAttribute, ImportPersonAlias );
                attributeService.Save( newContributionAttribute, ImportPersonAlias );
                contributionAttributeId = newContributionAttribute.Id;
            }

            var contributionAttribute = AttributeCache.Read( contributionAttributeId );

            // Get all imported contributions
            var importedContributions = new AttributeValueService().GetByAttributeId( contributionAttributeId )
               .Select( av => new { ContributionId = av.Value.AsType<int?>(), TransactionId = av.EntityId } )
               .ToDictionary( t => t.ContributionId, t => t.TransactionId );

            // List for batching new contributions
            var newTransactions = new List<FinancialTransaction>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Checking contribution import ({0:N0} found, {1:N0} already exist).", totalRows, importedContributions.Count() ) );
            foreach ( var row in tableData )
            {
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                int? contributionId = row["ContributionID"] as int?;

                if ( contributionId != null && !importedContributions.ContainsKey( contributionId ) )
                {
                    var transaction = new FinancialTransaction();
                    transaction.TransactionTypeValueId = transactionTypeContributionId;
                    transaction.AuthorizedPersonId = GetPersonId( individualId, householdId );
                    transaction.CreatedByPersonAliasId = ImportPersonAlias.Id;
                    transaction.AuthorizedPersonId = GetPersonId( individualId, householdId );

                    string summary = row["Memo"] as string;
                    if ( summary != null )
                    {
                        transaction.Summary = summary;
                    }

                    int? batchId = row["BatchID"] as int?;
                    if ( batchId != null && ImportedBatches.Any( b => b.Key == batchId ) )
                    {
                        transaction.BatchId = ImportedBatches.FirstOrDefault( b => b.Key == batchId ).Value;
                    }

                    DateTime? receivedDate = row["Received_Date"] as DateTime?;
                    if ( receivedDate != null )
                    {
                        transaction.TransactionDateTime = receivedDate;
                        transaction.CreatedDateTime = receivedDate;
                    }

                    bool isTypeNonCash = false;
                    string contributionType = row["Contribution_Type_Name"] as string;
                    if ( contributionType != null )
                    {
                        if ( contributionType == "ACH" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeACH;
                        }
                        else if ( contributionType == "Cash" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeCash;
                        }
                        else if ( contributionType == "Check" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeCheck;
                        }
                        else if ( contributionType == "Credit Card" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeCreditCard;
                        }
                        else
                        {
                            isTypeNonCash = true;
                        }
                    }

                    string checkNumber = row["Check_Number"] as string;
                    if ( checkNumber != null && checkNumber.AsType<int?>() != null )
                    {
                        // routing & account set to zero
                        transaction.CheckMicrEncrypted = Encryption.EncryptString( string.Format( "{0}_{1}_{2}", 0, 0, checkNumber ) );
                    }

                    string fundName = row["Fund_Name"] as string;
                    string subFund = row["Sub_Fund_Name"] as string;
                    decimal? amount = row["Amount"] as decimal?;
                    if ( fundName != null & amount != null )
                    {
                        FinancialAccount matchingAccount = null;
                        fundName = fundName.Trim();

                        int? fundCampusId = null;
                        if ( subFund != null )
                        {
                            subFund = subFund.Trim();
                            fundCampusId = CampusList.Where( c => c.Name.StartsWith( subFund ) || c.ShortCode == subFund )
                                .Select( c => (int?)c.Id ).FirstOrDefault();

                            if ( fundCampusId != null )
                            {
                                matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName )
                                    && a.CampusId != null && a.CampusId.Equals( fundCampusId ) );
                            }
                            else
                            {
                                matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.Name.StartsWith( subFund ) );
                            }
                        }
                        else
                        {
                            matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.CampusId == null );
                        }

                        if ( matchingAccount == null )
                        {
                            matchingAccount = new FinancialAccount();
                            matchingAccount.Name = fundName;
                            matchingAccount.PublicName = fundName;
                            matchingAccount.IsTaxDeductible = true;
                            matchingAccount.IsActive = true;
                            matchingAccount.CampusId = fundCampusId;
                            matchingAccount.CreatedByPersonAliasId = ImportPersonAlias.Id;

                            accountService.Add( matchingAccount );
                            accountService.Save( matchingAccount );
                            accountList.Add( matchingAccount );
                        }

                        var transactionDetail = new FinancialTransactionDetail();
                        transactionDetail.Amount = (decimal)amount;
                        transactionDetail.CreatedDateTime = receivedDate;
                        transactionDetail.AccountId = matchingAccount.Id;
                        transactionDetail.IsNonCash = isTypeNonCash;
                        transaction.TransactionDetails.Add( transactionDetail );

                        if ( amount < 0 )
                        {
                            var transactionRefund = new FinancialTransactionRefund();
                            transactionRefund.CreatedDateTime = receivedDate;
                            transactionRefund.RefundReasonSummary = summary;
                            transactionRefund.RefundReasonValueId = refundReasons.Where( dv => summary != null && dv.Name.Contains( summary ) )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();
                            transaction.Refund = transactionRefund;
                        }
                    }

                    // Other Attributes to create:
                    // Pledge_Drive_Name
                    // Stated_Value
                    // True_Value
                    // Liquidation_cost

                    transaction.Attributes = new Dictionary<string, AttributeCache>();
                    transaction.AttributeValues = new Dictionary<string, List<AttributeValue>>();
                    transaction.Attributes.Add( contributionAttribute.Key, contributionAttribute );
                    transaction.AttributeValues.Add( contributionAttribute.Key, new List<AttributeValue>() );
                    transaction.AttributeValues[contributionAttribute.Key].Add( new AttributeValue()
                    {
                        AttributeId = contributionAttribute.Id,
                        Value = contributionId.ToString(),
                        Order = 0
                    } );

                    newTransactions.Add( transaction );
                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} contributions imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        RockTransactionScope.WrapTransaction( () =>
                        {
                            var transactionService = new FinancialTransactionService();
                            transactionService.RockContext.FinancialTransactions.AddRange( newTransactions );
                            transactionService.RockContext.SaveChanges();

                            var attributeValueService = new AttributeValueService();
                            foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) )
                            {
                                var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault();
                                if ( attributeValue != null )
                                {
                                    attributeValue.EntityId = contribution.Id;
                                    attributeValueService.RockContext.AttributeValues.Add( attributeValue );
                                }
                            }

                            attributeValueService.RockContext.SaveChanges();
                        } );

                        newTransactions.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if ( newTransactions.Any() )
            {
                RockTransactionScope.WrapTransaction( () =>
                {
                    var transactionService = new FinancialTransactionService();
                    transactionService.RockContext.FinancialTransactions.AddRange( newTransactions );
                    transactionService.RockContext.SaveChanges();

                    var attributeValueService = new AttributeValueService();
                    foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) )
                    {
                        var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault();
                        if ( attributeValue != null )
                        {
                            attributeValue.EntityId = contribution.Id;
                            attributeValueService.RockContext.AttributeValues.Add( attributeValue );
                        }
                    }

                    attributeValueService.RockContext.SaveChanges();
                } );
            }

            ReportProgress( 100, string.Format( "Finished contribution import: {0:N0} contributions imported.", completed ) );
        }
示例#11
0
        /// <summary>
        /// Processes the confirmation.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessConfirmation( out string errorMessage )
        {
            var rockContext = new RockContext();
            if ( string.IsNullOrWhiteSpace( TransactionCode ) )
            {
                GatewayComponent gateway = null;
                var financialGateway = hfPaymentTab.Value == "ACH" ? _achGateway : _ccGateway;
                if ( financialGateway != null )
                {
                    gateway = financialGateway.GetGatewayComponent();
                }

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

                Person person = GetPerson( true );
                if ( person == null )
                {
                    errorMessage = "There was a problem creating the person information";
                    return false;
                }

                if ( !person.PrimaryAliasId.HasValue )
                {
                    errorMessage = "There was a problem creating the person's primary alias";
                    return false;
                }

                PaymentInfo paymentInfo = GetPaymentInfo();
                if ( paymentInfo == null )
                {
                    errorMessage = "There was a problem creating the payment information";
                    return false;
                }
                else
                {
                    paymentInfo.FirstName = person.FirstName;
                    paymentInfo.LastName = person.LastName;
                }

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

                if ( _showCommmentEntry )
                {
                    paymentInfo.Comment1 = !string.IsNullOrWhiteSpace( GetAttributeValue( "PaymentComment" ) ) ? string.Format( "{0}: {1}", GetAttributeValue( "PaymentComment" ), txtCommentEntry.Text ) : txtCommentEntry.Text;
                }
                else
                {
                    paymentInfo.Comment1 = GetAttributeValue( "PaymentComment" );
                }

                PaymentSchedule schedule = GetSchedule();
                if ( schedule != null )
                {
                    schedule.PersonId = person.Id;

                    var scheduledTransaction = gateway.AddScheduledPayment( financialGateway, schedule, paymentInfo, out errorMessage );
                    if ( scheduledTransaction != null )
                    {
                        scheduledTransaction.TransactionFrequencyValueId = schedule.TransactionFrequencyValue.Id;
                        scheduledTransaction.AuthorizedPersonAliasId = person.PrimaryAliasId.Value;
                        scheduledTransaction.FinancialGatewayId = financialGateway.Id;

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

                        var changeSummary = new StringBuilder();
                        changeSummary.AppendFormat( "{0} starting {1}", schedule.TransactionFrequencyValue.Value, schedule.StartDate.ToShortDateString() );
                        changeSummary.AppendLine();
                        changeSummary.Append( paymentInfo.CurrencyTypeValue.Value );
                        if ( paymentInfo.CreditCardTypeValue != null )
                        {
                            changeSummary.AppendFormat( " - {0}", paymentInfo.CreditCardTypeValue.Value );
                        }
                        changeSummary.AppendFormat( " {0}", paymentInfo.MaskedNumber );
                        changeSummary.AppendLine();

                        foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) )
                        {
                            var transactionDetail = new FinancialScheduledTransactionDetail();
                            transactionDetail.Amount = account.Amount;
                            transactionDetail.AccountId = account.Id;
                            scheduledTransaction.ScheduledTransactionDetails.Add( transactionDetail );
                            changeSummary.AppendFormat( "{0}: {1}", account.Name, account.Amount.FormatAsCurrency() );
                            changeSummary.AppendLine();
                        }

                        var transactionService = new FinancialScheduledTransactionService( rockContext );
                        transactionService.Add( scheduledTransaction );
                        rockContext.SaveChanges();

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

                        ScheduleId = scheduledTransaction.GatewayScheduleId;
                        TransactionCode = scheduledTransaction.TransactionCode;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    var transaction = gateway.Charge( financialGateway, paymentInfo, out errorMessage );
                    if ( transaction != null )
                    {
                        var txnChanges = new List<string>();
                        txnChanges.Add( "Created Transaction" );

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

                        transaction.AuthorizedPersonAliasId = person.PrimaryAliasId;
                        History.EvaluateChange( txnChanges, "Person", string.Empty, person.FullName );

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

                        if ( transaction.FinancialPaymentDetail == null )
                        {
                            transaction.FinancialPaymentDetail = new FinancialPaymentDetail();
                        }
                        transaction.FinancialPaymentDetail.SetFromPaymentInfo( paymentInfo, 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 account in SelectedAccounts.Where( a => a.Amount > 0 ) )
                        {
                            var transactionDetail = new FinancialTransactionDetail();
                            transactionDetail.Amount = account.Amount;
                            transactionDetail.AccountId = account.Id;
                            transaction.TransactionDetails.Add( transactionDetail );
                            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" ),
                            paymentInfo.CurrencyTypeValue,
                            paymentInfo.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.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,
                            person.FullName,
                            typeof( FinancialTransaction ),
                            transaction.Id
                        );

                        SendReceipt( transaction.Id );

                        TransactionCode = transaction.TransactionCode;
                    }
                    else
                    {
                        return false;
                    }
                }

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

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

                tdNameReceipt.Description = paymentInfo.FullName;
                tdPhoneReceipt.Description = paymentInfo.Phone;
                tdEmailReceipt.Description = paymentInfo.Email;
                tdAddressReceipt.Description = string.Format( "{0} {1}, {2} {3}", paymentInfo.Street1, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode );

                rptAccountListReceipt.DataSource = SelectedAccounts.Where( a => a.Amount != 0 );
                rptAccountListReceipt.DataBind();

                tdTotalReceipt.Description = paymentInfo.Amount.ToString( "C" );

                tdPaymentMethodReceipt.Description = paymentInfo.CurrencyTypeValue.Description;
                tdAccountNumberReceipt.Description = paymentInfo.MaskedNumber;
                tdWhenReceipt.Description = schedule != null ? schedule.ToString() : "Today";

                // If there was a transaction code returned and this was not already created from a previous saved account,
                // show the option to save the account.
                if ( !( paymentInfo is ReferencePaymentInfo ) && !string.IsNullOrWhiteSpace( TransactionCode ) && gateway.SupportsSavedAccount( paymentInfo.CurrencyTypeValue ) )
                {
                    cbSaveAccount.Visible = true;
                    pnlSaveAccount.Visible = true;
                    txtSaveAccount.Visible = true;

                    // If current person does not have a login, have them create a username and password
                    phCreateLogin.Visible = !new UserLoginService( rockContext ).GetByPersonId( person.Id ).Any();
                }
                else if ( !new UserLoginService( rockContext ).GetByPersonId( person.Id ).Any() )
                {
                    pnlSaveAccount.Visible = true;
                    phCreateLogin.Visible = true;
                    cbSaveAccount.Visible = false;
                    txtSaveAccount.Visible = false;
                }
                else
                {
                    pnlSaveAccount.Visible = false;
                }

                if ( PageParameter( "argsd" ) == "1" )
                {
                    var rc = new RockContext();
                    var ats = new AttributeService( rc );
                    var argsd = ats.Queryable().Where( x => x.Key == "AutomatedRecurringGiftSetupDate" ).FirstOrDefault();
                    if ( argsd == null )
                    {
                        argsd = new Rock.Model.Attribute();
                        argsd.FieldTypeId = 85;
                        argsd.EntityTypeId = 15;
                        argsd.Key = "AutomatedRecurringGiftSetupDate";
                        argsd.Name = "Automated Recurring Gift Setup Date";
                        argsd.Guid = Guid.NewGuid();
                        argsd.CreatedDateTime = argsd.ModifiedDateTime = DateTime.Now;
                        ats.Add( argsd );
                        rc.SaveChanges();
                        rc = new RockContext();
                        ats = new AttributeService( rc );
                        argsd = ats.Queryable().Where( x => x.Key == "AutomatedRecurringGiftSetupDate" ).FirstOrDefault();
                    }
                    if ( argsd != null )
                    {
                        var atvs = new AttributeValueService( rc );
                        var argsdVal = atvs.Queryable().Where( x => x.AttributeId == argsd.Id && x.EntityId == person.Id ).FirstOrDefault();
                        if ( argsdVal == null )
                        {
                            argsdVal = new Rock.Model.AttributeValue();
                            argsdVal.AttributeId = argsd.Id;
                            argsdVal.EntityId = person.Id;
                            argsdVal.Value = DateTime.Now.ToString( "o" );
                            argsdVal.Guid = Guid.NewGuid();
                            argsdVal.CreatedDateTime = argsdVal.ModifiedDateTime = DateTime.Now;

                            atvs.Add( argsdVal );
                            rc.SaveChanges();
                        }
                        else
                        {
                            argsdVal.Value = DateTime.Now.ToString( "o" );
                            rc.SaveChanges();
                        }
                    }
                }
                return true;
            }
            else
            {
                pnlDupWarning.Visible = true;
                divActions.Visible = false;
                errorMessage = string.Empty;
                return false;
            }
        }
示例#12
0
        /// <summary>
        /// Maps the Individual Giftedness.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapIndividualGiftedness( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var attributeService = new AttributeService( lookupContext );

            int rank1Id = attributeService.Queryable().Where( a => a.Key == "Rank1" ).FirstOrDefault().Id;
            int rank2Id = attributeService.Queryable().Where( a => a.Key == "Rank2" ).FirstOrDefault().Id;
            int rank3Id = attributeService.Queryable().Where( a => a.Key == "Rank3" ).FirstOrDefault().Id;
            int rank4Id = attributeService.Queryable().Where( a => a.Key == "Rank4" ).FirstOrDefault().Id;

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying Giftedness Program import ({0:N0} found).", totalRows ) );

            var newAttributeValueList = new List<AttributeValue>();

            foreach ( var row in tableData )
            {
                int? individualId = row["Individual_ID"] as int?;
                int personId = (int)GetPersonAliasId( individualId );
                var newAttributeValue = new AttributeValue();
                int? rank = row["Rank"] as int?;
                int rankId = 0;

                //not everyone has all 4 ranks, some are missing the fourth and that was causing it to run in the below if condition and try to create a duplicate record.
                if ( rank == 1 ) { rankId = rank1Id; }
                if ( rank == 2 ) { rankId = rank2Id; }
                if ( rank == 3 ) { rankId = rank3Id; }
                if ( rank == 4 ) { rankId = rank4Id; }

                if ( personId != 0 && rankId != 0 )
                {
                    var attributeValueService = new AttributeValueService( lookupContext );

                    //checks if they are in the database already or if there is a record currently in the newAttributeValueList
                    if ( attributeValueService.Queryable().Where( a => a.AttributeId == rankId && a.EntityId == personId ).FirstOrDefault() == null && newAttributeValueList.Find(a => a.AttributeId == rankId && a.EntityId == personId) == null )
                    {

                        DateTime? assessmentDate = row["AssessmentDate"] as DateTime?;
                        int? giftAttributeId = row["GiftAttributeID"] as int?;
                        string giftAttributeIdString = Convert.ToString( giftAttributeId );

                        var definedValueService = new DefinedValueService( lookupContext );

                        newAttributeValue.IsSystem = false;
                        newAttributeValue.EntityId = personId;

                        if ( rank == 1 ) { newAttributeValue.AttributeId = rank1Id; }
                        if ( rank == 2 ) { newAttributeValue.AttributeId = rank2Id; }
                        if ( rank == 3 ) { newAttributeValue.AttributeId = rank3Id; }
                        if ( rank == 4 ) { newAttributeValue.AttributeId = rank4Id; }

                        newAttributeValue.Value = Convert.ToString( definedValueService.Queryable().Where( a => a.ForeignId == giftAttributeIdString ).FirstOrDefault().Guid );
                        newAttributeValue.CreatedDateTime = assessmentDate;

                        newAttributeValueList.Add( newAttributeValue );
                        completed++;
                    }
                }
                if ( newAttributeValueList.Any() )
                {
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} spiritual gifts imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        var rockContext = new RockContext();
                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.AttributeValues.AddRange( newAttributeValueList );
                            rockContext.SaveChanges( DisableAudit );
                            newAttributeValueList.Clear();
                        } );
                        ReportPartialProgress();
                    }
                }
            }

            if ( newAttributeValueList.Any() )
            {
                var rockContext = new RockContext();
                rockContext.WrapTransaction( () =>
                {
                    rockContext.Configuration.AutoDetectChangesEnabled = false;
                    rockContext.AttributeValues.AddRange( newAttributeValueList );
                    rockContext.SaveChanges( DisableAudit );
                } );
            }

            ReportProgress( 100, string.Format( "Finished individual gifts import: {0:N0} spiritual gifts imported.", completed ) );
        }