/// <summary>
        /// Gets the specified name prefix.
        /// </summary>
        /// <param name="namePrefix">The name prefix.</param>
        /// <param name="nameSuffix">The name suffix.</param>
        /// <param name="currencyType">Type of the currency.</param>
        /// <param name="creditCardType">Type of the credit card.</param>
        /// <param name="transactionDate">The transaction date.</param>
        /// <param name="batchTimeOffset">The batch time offset.</param>
        /// <param name="batches">The batches.</param>
        /// <returns></returns>
        public FinancialBatch Get( string namePrefix, string nameSuffix, DefinedValueCache currencyType, DefinedValueCache creditCardType,
            DateTime transactionDate, TimeSpan batchTimeOffset, List<FinancialBatch> batches = null )
        {
            // Use the credit card type's batch name suffix, or if that doesn't exist, use the currency type value
            string ccSuffix = string.Empty;

            if (creditCardType != null )
            {
                ccSuffix = creditCardType.GetAttributeValue( "BatchNameSuffix" );
                if ( string.IsNullOrWhiteSpace( ccSuffix ) )
                {
                    ccSuffix = creditCardType.Value;
                }
            }

            if ( string.IsNullOrWhiteSpace( ccSuffix ) && currencyType != null )
            {
                ccSuffix = currencyType.Value;
            }

            string batchName = namePrefix.Trim() + ( string.IsNullOrWhiteSpace( ccSuffix ) ? "" : " " + ccSuffix ) + nameSuffix;

            return GetByNameAndDate( batchName, transactionDate, batchTimeOffset, batches );
        }
Esempio n. 2
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            _groupType = GroupTypeCache.Read( GetAttributeValue( "GroupType" ).AsGuid() );
            if ( _groupType == null )
            {
                _groupType = GroupTypeCache.GetFamilyGroupType();
            }

            _groupTypeName = _groupType.Name;
            _isFamilyGroupType = _groupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() );
            _locationType = _groupType.LocationTypeValues.FirstOrDefault( v => v.Guid.Equals( GetAttributeValue( "LocationType" ).AsGuid() ) );
            if ( _locationType == null )
            {
                _locationType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME );
            }

            if ( _isFamilyGroupType )
            {
                divGroupName.Visible = false;
                var campusi = GetAttributeValue( "ShowInactiveCampuses" ).AsBoolean() ? CampusCache.All() : CampusCache.All().Where( c => c.IsActive == true ).ToList();
                cpCampus.Campuses =  campusi;
                cpCampus.Visible = campusi.Any();
                if ( campusi.Count == 1 )
                {
                    cpCampus.SelectedCampusId = campusi.FirstOrDefault().Id;
                }

                ddlMaritalStatus.Visible = true;
                ddlMaritalStatus.BindToDefinedType( DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid() ), true );
                var AdultMaritalStatus = DefinedValueCache.Read( GetAttributeValue( "AdultMaritalStatus" ).AsGuid() );
                if ( AdultMaritalStatus != null )
                {
                    ddlMaritalStatus.SetValue( AdultMaritalStatus.Id );
                }

                _childRoleId = _groupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
            }
            else
            {
                divGroupName.Visible = true;
                tbGroupName.Label = _groupTypeName + " Name";
                cpCampus.Visible = false;
                ddlMaritalStatus.Visible = false;
            }

            nfmMembers.ShowGrade = _isFamilyGroupType;
            nfmMembers.RequireGender = GetAttributeValue( "Gender" ).AsBoolean();
            nfmMembers.RequireGrade = GetAttributeValue( "Grade" ).AsBoolean();
            _SMSEnabled = GetAttributeValue("SMS").AsBoolean();

            lTitle.Text = string.Format( "Add {0}", _groupType.Name ).FormatAsHtmlTitle();

            _homePhone = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME );
            _cellPhone = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE );

            _confirmMaritalStatus = _isFamilyGroupType && GetAttributeValue( "MaritalStatusConfirmation" ).AsBoolean();
            if ( _confirmMaritalStatus )
            {
                string script = string.Format( @"
            $('a.js-confirm-marital-status').click(function( e ){{

            var anyAdults = false;
            $(""input[id$='_rblRole_0']"").each(function() {{
            if ( $(this).prop('checked') ) {{
                anyAdults = true;
            }}
            }});

            if ( anyAdults ) {{
            if ( $('#{0}').val() == '' ) {{
                e.preventDefault();
                Rock.dialogs.confirm('You have not selected a marital status for the adults in this new family. Are you sure you want to continue?', function (result) {{
                    if (result) {{
                        window.location = e.target.href ? e.target.href : e.target.parentElement.href;
                    }}
                }});
            }}
            }}
            }});
            ", ddlMaritalStatus.ClientID );
                ScriptManager.RegisterStartupScript( btnNext, btnNext.GetType(), "confirm-marital-status", script, true );

            }
        }
Esempio n. 3
0
 private void SetPayPeriod( RecurringInfo recurringInfo, DefinedValueCache transactionFrequencyValue )
 {
     recurringInfo.MaxFailPayments = 0;
     recurringInfo.Term = 0;
     var selectedFrequencyGuid = transactionFrequencyValue.Guid.ToString().ToUpper();
     switch ( selectedFrequencyGuid )
     {
         case Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME:
             recurringInfo.PayPeriod = "YEAR";
             recurringInfo.Term = 1;
             break;
         case Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_WEEKLY:
             recurringInfo.PayPeriod = "WEEK";
             break;
         case Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_BIWEEKLY:
             recurringInfo.PayPeriod = "BIWK";
             break;
         case Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_TWICEMONTHLY:
             recurringInfo.PayPeriod = "SMMO";
             break;
         case Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_MONTHLY:
             recurringInfo.PayPeriod = "MONT";
             break;
     }
 }
        // checks the settings provided
        private bool CheckSettings()
        {
            nbBlockConfigErrors.Title = string.Empty;
            nbBlockConfigErrors.Text = string.Empty;

            // get list of selected accounts filtered by the current campus
            RockContext rockContext = new RockContext();
            FinancialAccountService accountService = new FinancialAccountService( rockContext );

            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "Accounts" ) ) )
            {
                Guid[] selectedAccounts = GetAttributeValue( "Accounts" ).Split( ',' ).Select( s => Guid.Parse( s ) ).ToArray(); ;

                var accounts = accountService.Queryable()
                                .Where( a => selectedAccounts.Contains( a.Guid ) );

                if ( this.CampusId != 0 )
                {
                    accounts = accounts.Where( a => a.CampusId.Value == this.CampusId || a.CampusId == null );
                }

                this.Accounts = new Dictionary<int, string>();

                foreach ( var account in accounts.OrderBy( a => a.Order ).ToList() )
                {
                    this.Accounts.Add( account.Id, account.PublicName );
                }
            }
            else
            {
                nbBlockConfigErrors.Heading = "No Accounts Configured";
                nbBlockConfigErrors.Text = "<p>There are currently no accounts configured.</p>";
                return false;
            }

            // hide cancel buttons if no homepage defined
            if ( string.IsNullOrWhiteSpace( GetAttributeValue( "Homepage" ) ) )
            {
                lbSearchCancel.Visible = false;
                lbGivingUnitSelectCancel.Visible = false;
                lbRegisterCancel.Visible = false;
                lbAccountEntryCancel.Visible = false;
                lbSwipeCancel.Visible = false;
            }

            // get anonymous person
            Person anonymousPerson = null;

            Guid anonymousPersonAliasGuid;

            if ( Guid.TryParse( GetAttributeValue( "AnonymousPerson" ), out anonymousPersonAliasGuid ) )
            {
                anonymousPerson = new PersonAliasService( rockContext ).Get(anonymousPersonAliasGuid ).Person;
            }

            if ( anonymousPerson != null )
            {
                this.AnonymousGiverPersonAliasId = anonymousPerson.PrimaryAliasId;
                lbGiveAnonymously.Visible = true;
            }
            else
            {
                lbGiveAnonymously.Visible = false;
            }

            _dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            if ( _dvcConnectionStatus == null )
            {
                nbBlockConfigErrors.Heading = "Invalid Connection Status";
                nbBlockConfigErrors.Text = "<p>The selected Connection Status setting does not exist.</p>";
                return false;
            }

            _dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );
            if ( _dvcRecordStatus == null )
            {
                nbBlockConfigErrors.Heading = "Invalid Record Status";
                nbBlockConfigErrors.Text = "<p>The selected Record Status setting does not exist.</p>";
                return false;
            }

            return true;
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            ddlMaritalStatus.BindToDefinedType( DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid() ), true );
            var AdultMaritalStatus = DefinedValueCache.Read( GetAttributeValue( "AdultMaritalStatus" ).AsGuid() );
            if ( AdultMaritalStatus != null )
            {
                ddlMaritalStatus.SetValue( AdultMaritalStatus.Id );
            }

            var campusi = CampusCache.All();
            cpCampus.Campuses = campusi;
            cpCampus.Visible = campusi.Any();

            var familyGroupType = GroupTypeCache.GetFamilyGroupType();
            if ( familyGroupType != null )
            {
                _childRoleId = familyGroupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
            }

            nfmMembers.RequireGender = GetAttributeValue( "Gender" ).AsBoolean();
            nfmMembers.RequireGrade = GetAttributeValue( "Grade" ).AsBoolean();

            lTitle.Text = ( "Add Family" ).FormatAsHtmlTitle();

            _homePhone = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME );
            _cellPhone = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE );

            _confirmMaritalStatus = GetAttributeValue( "MaritalStatusConfirmation" ).AsBoolean();
            if ( _confirmMaritalStatus )
            {
                string script = string.Format( @"
            $('a.js-confirm-marital-status').click(function( e ){{

            var anyAdults = false;
            $(""input[id$='_rblRole_0']"").each(function() {{
            if ( $(this).prop('checked') ) {{
                anyAdults = true;
            }}
            }});

            if ( anyAdults ) {{
            if ( $('#{0}').val() == '' ) {{
                e.preventDefault();
                Rock.dialogs.confirm('You have not selected a marital status for the adults in this new family. Are you sure you want to continue?', function (result) {{
                    if (result) {{
                        window.location = e.target.href ? e.target.href : e.target.parentElement.href;
                    }}
                }});
            }}
            }}
            }});
            ", ddlMaritalStatus.ClientID );
                ScriptManager.RegisterStartupScript( btnNext, btnNext.GetType(), "confirm-marital-status", script, true );

            }
        }
Esempio n. 6
0
 /// <summary>
 /// Returnes a boolean value indicating if 'Saved Account' functionality is supported for the given currency type.
 /// </summary>
 /// <param name="currencyType">Type of the currency.</param>
 /// <returns></returns>
 public override bool SupportsSavedAccount( DefinedValueCache currencyType )
 {
     // PayflowPro only supports saved account functionality for credit card transactions
     return currencyType.Guid.Equals( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid() );
 }
Esempio n. 7
0
        /// <summary>
        /// Determines if this gateway supports saved accounts of the type indicated by currencyType
        /// </summary>
        /// <param name="currencyType">The currency type</param>
        /// <returns></returns>
        public override bool SupportsSavedAccount( DefinedValueCache currencyType )
        {
            var ach = Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH.AsGuid();
            var creditCard = Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid();
            var currencyTypeGuid = currencyType.Guid;

            return currencyTypeGuid.Equals( ach ) || currencyTypeGuid.Equals( creditCard );
        }
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid( bool isExporting = false )
        {
            if ( _group != null )
            {
                pnlGroupMembers.Visible = true;

                lHeading.Text = string.Format( "{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize() );

                if ( _group.GroupType.Roles.Any() )
                {
                    nbRoleWarning.Visible = false;
                    rFilter.Visible = true;
                    gGroupMembers.Visible = true;

                    var rockContext = new RockContext();

                    if ( _group != null &&
                        _group.RequiredSignatureDocumentTemplateId.HasValue )
                    {
                        Signers = new SignatureDocumentService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.SignatureDocumentTemplateId == _group.RequiredSignatureDocumentTemplateId.Value &&
                                d.Status == SignatureDocumentStatus.Signed &&
                                d.BinaryFileId.HasValue &&
                                d.AppliesToPersonAlias != null )
                            .OrderByDescending( d => d.LastStatusDate )
                            .Select( d => d.AppliesToPersonAlias.PersonId )
                            .ToList();
                    }

                    GroupMemberService groupMemberService = new GroupMemberService( rockContext );
                    var qry = groupMemberService.Queryable( "Person,GroupRole", true ).AsNoTracking()
                        .Where( m => m.GroupId == _group.Id );

                    // Filter by First Name
                    string firstName = tbFirstName.Text;
                    if ( !string.IsNullOrWhiteSpace( firstName ) )
                    {
                        qry = qry.Where( m =>
                            m.Person.FirstName.StartsWith( firstName ) ||
                            m.Person.NickName.StartsWith( firstName ) );
                    }

                    // Filter by Last Name
                    string lastName = tbLastName.Text;
                    if ( !string.IsNullOrWhiteSpace( lastName ) )
                    {
                        qry = qry.Where( m => m.Person.LastName.StartsWith( lastName ) );
                    }

                    // Filter by role
                    var validGroupTypeRoles = _group.GroupType.Roles.Select( r => r.Id ).ToList();
                    var roles = new List<int>();
                    foreach ( var roleId in cblRole.SelectedValues.AsIntegerList() )
                    {
                        if ( validGroupTypeRoles.Contains( roleId ) )
                        {
                            roles.Add( roleId );
                        }
                    }

                    if ( roles.Any() )
                    {
                        qry = qry.Where( m => roles.Contains( m.GroupRoleId ) );
                    }

                    // Filter by Group Member Status
                    var statuses = new List<GroupMemberStatus>();
                    foreach ( string status in cblGroupMemberStatus.SelectedValues )
                    {
                        if ( !string.IsNullOrWhiteSpace( status ) )
                        {
                            statuses.Add( status.ConvertToEnum<GroupMemberStatus>() );
                        }
                    }

                    if ( statuses.Any() )
                    {
                        qry = qry.Where( m => statuses.Contains( m.GroupMemberStatus ) );
                    }

                    var genders = new List<Gender>();
                    foreach ( var item in cblGenderFilter.SelectedValues )
                    {
                        var gender = item.ConvertToEnum<Gender>();
                        genders.Add( gender );
                    }

                    if ( genders.Any() )
                    {
                        qry = qry.Where( m => genders.Contains( m.Person.Gender ) );
                    }

                    // Filter by Campus
                    if ( cpCampusFilter.SelectedCampusId.HasValue )
                    {
                        Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );
                        int campusId = cpCampusFilter.SelectedCampusId.Value;
                        var qryFamilyMembersForCampus = new GroupMemberService( rockContext ).Queryable().Where( a => a.Group.GroupType.Guid == familyGuid && a.Group.CampusId == campusId );
                        qry = qry.Where( a => qryFamilyMembersForCampus.Any( f => f.PersonId == a.PersonId ) );
                    }

                    // Filter by signed documents
                    if ( Signers != null )
                    {
                        if ( ddlSignedDocument.SelectedValue.AsBooleanOrNull() == true )
                        {
                            qry = qry.Where( m => Signers.Contains( m.PersonId ) );
                        }
                        else if ( ddlSignedDocument.SelectedValue.AsBooleanOrNull() == false )
                        {
                            qry = qry.Where( m => !Signers.Contains( m.PersonId ) );
                        }
                    }

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

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

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

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

                    _inactiveStatus = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE );

                    SortProperty sortProperty = gGroupMembers.SortProperty;

                    bool hasGroupRequirements = new GroupRequirementService( rockContext ).Queryable().Where( a => a.GroupId == _group.Id ).Any();

                    // If there are group requirements that that member doesn't meet, show an icon in the grid
                    bool includeWarnings = false;
                    var groupMemberIdsThatLackGroupRequirements = new GroupService( rockContext ).GroupMembersNotMeetingRequirements( _group.Id, includeWarnings ).Select( a => a.Key.Id );

                    List<GroupMember> groupMembersList = null;
                    if ( sortProperty != null && sortProperty.Property != "FirstAttended" && sortProperty.Property != "LastAttended" )
                    {
                        groupMembersList = qry.Sort( sortProperty ).ToList();
                    }
                    else
                    {
                        groupMembersList = qry.OrderBy( a => a.GroupRole.Order ).ThenBy( a => a.Person.LastName ).ThenBy( a => a.Person.FirstName ).ToList();
                    }

                    // If there is a required signed document that member has not signed, show an icon in the grid
                    var personIdsThatHaventSigned = new List<int>();
                    if ( Signers != null )
                    {
                        var memberPersonIds = groupMembersList.Select( m => m.PersonId ).ToList();
                        personIdsThatHaventSigned = memberPersonIds.Where( i => !Signers.Contains( i ) ).ToList();
                    }

                    // Since we're not binding to actual group member list, but are using AttributeField columns,
                    // we need to save the group members into the grid's object list
                    gGroupMembers.ObjectList = new Dictionary<string, object>();
                    groupMembersList.ForEach( m => gGroupMembers.ObjectList.Add( m.Id.ToString(), m ) );
                    gGroupMembers.EntityTypeId = EntityTypeCache.Read( Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid() ).Id;

                    var homePhoneType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME );
                    var cellPhoneType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE );

                    // If exporting to Excel, the selectAll option will be true, and home location should be calculated
                    var homeLocations = new Dictionary<int, Location>();
                    if ( isExporting )
                    {
                        foreach ( var m in groupMembersList )
                        {
                            homeLocations.Add( m.Id, m.Person.GetHomeLocation( rockContext ) );
                        }
                    }

                    var groupMemberIds = groupMembersList.Select( m => m.Id ).ToList();

                    // Get all the group members with any associated registrations
                    _groupMembersWithRegistrations = new RegistrationRegistrantService( rockContext )
                        .Queryable().AsNoTracking()
                        .Where( r =>
                            r.Registration != null &&
                            r.Registration.RegistrationInstance != null &&
                            r.GroupMemberId.HasValue &&
                            groupMemberIds.Contains( r.GroupMemberId.Value ) )
                        .ToList()
                        .GroupBy( r => r.GroupMemberId.Value )
                        .Select( g => new
                        {
                            GroupMemberId = g.Key,
                            Registrations = g.ToList()
                                .Select( r => new
                                {
                                    Id = r.Registration.Id,
                                    Name = r.Registration.RegistrationInstance.Name
                                } ).Distinct()
                                .ToDictionary( r => r.Id, r => r.Name )
                        } )
                        .ToDictionary( r => r.GroupMemberId, r => r.Registrations );

                    var registrationField = gGroupMembers.ColumnsOfType<RockTemplateFieldUnselected>().FirstOrDefault();
                    if ( registrationField != null )
                    {
                        registrationField.Visible = _groupMembersWithRegistrations.Any();
                    }

                    var connectionStatusField = gGroupMembers.ColumnsOfType<DefinedValueField>().FirstOrDefault( a => a.DataField == "ConnectionStatusValueId" );
                    if ( connectionStatusField != null )
                    {
                        connectionStatusField.Visible = _group.GroupType.ShowConnectionStatus;
                    }

                    string photoFormat = "<div class=\"photo-icon photo-round photo-round-xs pull-left margin-r-sm js-person-popover\" personid=\"{0}\" data-original=\"{1}&w=50\" style=\"background-image: url( '{2}' ); background-size: cover; background-repeat: no-repeat;\"></div>";

                    var attendanceFirstLast = new Dictionary<int, DateRange>();
                    bool showAttendance = GetAttributeValue( "ShowAttendance" ).AsBoolean() && _group.GroupType.TakesAttendance;
                    gGroupMembers.ColumnsOfType<DateField>().First( a => a.DataField == "FirstAttended" ).Visible = showAttendance;
                    gGroupMembers.ColumnsOfType<DateField>().First( a => a.DataField == "LastAttended" ).Visible = showAttendance;
                    if ( showAttendance )
                    {
                        foreach ( var attendance in new AttendanceService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( a =>
                                a.GroupId.HasValue && a.GroupId.Value == _group.Id &&
                                a.DidAttend.HasValue && a.DidAttend.Value )
                            .GroupBy( a => a.PersonAlias.PersonId )
                            .Select( g => new
                            {
                                PersonId = g.Key,
                                FirstAttended = g.Min( a => a.StartDateTime ),
                                LastAttended = g.Max( a => a.StartDateTime )
                            } )
                            .ToList() )
                        {
                            attendanceFirstLast.Add( attendance.PersonId, new DateRange( attendance.FirstAttended, attendance.LastAttended ) );
                        }
                    }

                    var dataSource = groupMembersList.Select( m => new
                    {
                        m.Id,
                        m.Guid,
                        m.PersonId,
                        m.Person.NickName,
                        m.Person.LastName,
                        Name =
                        ( isExporting ? m.Person.LastName + ", " + m.Person.NickName : string.Format( photoFormat, m.PersonId, m.Person.PhotoUrl, ResolveUrl( "~/Assets/Images/person-no-photo-male.svg" ) ) +
                            m.Person.NickName + " " + m.Person.LastName
                            + ( ( hasGroupRequirements && groupMemberIdsThatLackGroupRequirements.Contains( m.Id ) )
                                ? " <i class='fa fa-exclamation-triangle text-warning'></i>"
                                : string.Empty )
                            + ( !string.IsNullOrEmpty( m.Note )
                                ? " <i class='fa fa-file-text-o text-info'></i>"
                                : string.Empty )
                            + ((personIdsThatHaventSigned.Contains( m.PersonId ))
                                ? " <i class='fa fa-pencil-square-o text-danger'></i>"
                                : string.Empty)),
                        m.Person.BirthDate,
                        m.Person.Age,
                        m.Person.ConnectionStatusValueId,
                        m.DateTimeAdded,
                        FirstAttended = attendanceFirstLast.Where( a => a.Key == m.PersonId ).Select( a => a.Value.Start ).FirstOrDefault(),
                        LastAttended = attendanceFirstLast.Where( a => a.Key == m.PersonId ).Select( a => a.Value.End ).FirstOrDefault(),
                        Email = m.Person.Email,
                        HomePhone = isExporting && homePhoneType != null ?
                            m.Person.PhoneNumbers
                                .Where( p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == homePhoneType.Id )
                                .Select( p => p.NumberFormatted )
                                .FirstOrDefault() : string.Empty,
                        CellPhone = isExporting && cellPhoneType != null ?
                            m.Person.PhoneNumbers
                                .Where( p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == cellPhoneType.Id )
                                .Select( p => p.NumberFormatted )
                                .FirstOrDefault() : string.Empty,
                        HomeAddress = homeLocations.ContainsKey( m.Id ) && homeLocations[m.Id] != null ?
                            homeLocations[m.Id].FormattedAddress : string.Empty,
                        Latitude = homeLocations.ContainsKey( m.Id ) && homeLocations[m.Id] != null ?
                            homeLocations[m.Id].Latitude : (double?)null,
                        Longitude = homeLocations.ContainsKey( m.Id ) && homeLocations[m.Id] != null ?
                            homeLocations[m.Id].Longitude : (double?)null,
                        GroupRole = m.GroupRole.Name,
                        m.GroupMemberStatus,
                        RecordStatusValueId = m.Person.RecordStatusValueId,
                        IsDeceased = m.Person.IsDeceased
                    } ).ToList();

                    if ( sortProperty != null )
                    {
                        if ( sortProperty.Property == "FirstAttended" )
                        {
                            if ( sortProperty.Direction == SortDirection.Descending )
                            {
                                dataSource = dataSource.OrderByDescending( a => a.FirstAttended ?? DateTime.MinValue ).ToList();
                            }
                            else
                            {
                                dataSource = dataSource.OrderBy( a => a.FirstAttended ?? DateTime.MinValue ).ToList();
                            }
                        }

                        if ( sortProperty.Property == "LastAttended" )
                        {
                            if ( sortProperty.Direction == SortDirection.Descending )
                            {
                                dataSource = dataSource.OrderByDescending( a => a.LastAttended ?? DateTime.MinValue ).ToList();
                            }
                            else
                            {
                                dataSource = dataSource.OrderBy( a => a.LastAttended ?? DateTime.MinValue ).ToList();
                            }
                        }
                    }

                    gGroupMembers.DataSource = dataSource;
                    gGroupMembers.DataBind();
                }
                else
                {
                    nbRoleWarning.Text = string.Format(
                        "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.",
                        _group.GroupType.GroupMemberTerm.Pluralize(),
                        _group.GroupType.GroupTerm,
                        _group.GroupType.Name );

                    nbRoleWarning.Visible = true;
                    rFilter.Visible = false;
                    gGroupMembers.Visible = false;
                }
            }
            else
            {
                pnlGroupMembers.Visible = false;
            }
        }
 /// <summary>
 /// Gets the specified name prefix.
 /// </summary>
 /// <param name="namePrefix">The name prefix.</param>
 /// <param name="currencyType">Type of the currency.</param>
 /// <param name="creditCardType">Type of the credit card.</param>
 /// <param name="transactionDate">The transaction date.</param>
 /// <param name="batchTimeOffset">The batch time offset.</param>
 /// <param name="batches">The batches.</param>
 /// <returns></returns>
 public FinancialBatch Get( string namePrefix, DefinedValueCache currencyType, DefinedValueCache creditCardType,
     DateTime transactionDate, TimeSpan batchTimeOffset, List<FinancialBatch> batches = null )
 {
     return Get( namePrefix, string.Empty, currencyType, creditCardType, transactionDate, batchTimeOffset, batches );
 }
Esempio n. 10
0
        //
        // Swipe Panel Events
        //

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

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

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

                        var homeLocation = giver.Person.GetHomeLocation();

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

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

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

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

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

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

                        if (transaction != null)
                        {
                            _transactionCode = transaction.TransactionCode;

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

                            transaction.AuthorizedPersonAliasId = this.SelectedGivingUnit.PersonAliasId;
                            transaction.TransactionDateTime     = RockDateTime.Now;
                            transaction.FinancialGatewayId      = financialGateway.Id;

                            var txnType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION));
                            transaction.TransactionTypeValueId = txnType.Id;

                            transaction.Summary = swipeInfo.Comment1;

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

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

                            foreach (var accountAmount in this.Amounts.Where(a => a.Value > 0))
                            {
                                var transactionDetail = new FinancialTransactionDetail();
                                transactionDetail.Amount    = accountAmount.Value;
                                transactionDetail.AccountId = accountAmount.Key;
                                transaction.TransactionDetails.Add(transactionDetail);
                                var account = new FinancialAccountService(rockContext).Get(accountAmount.Key);
                            }

                            var batchService = new FinancialBatchService(rockContext);

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

                            var batchChanges = new History.HistoryChangeList();

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

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

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

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

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

                                SendReceipt();
                            }

                            HidePanels();
                            ShowReceiptPanel();
                        }
                        else
                        {
                            lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", errorMessage);
                        }
                    }
                    else
                    {
                        lSwipeErrors.Text = "<div class='alert alert-danger'>Invalid gateway provided. Please provide a gateway. Transaction not processed.</div>";
                    }
                }
            }
            catch (Exception ex)
            {
                lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", ex.Message);
            }
        }
Esempio n. 11
0
        // checks the settings provided
        private bool CheckSettings()
        {
            nbBlockConfigErrors.Title = string.Empty;
            nbBlockConfigErrors.Text  = string.Empty;

            // get list of selected accounts filtered by the current campus
            RockContext             rockContext    = new RockContext();
            FinancialAccountService accountService = new FinancialAccountService(rockContext);

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("Accounts")))
            {
                Guid[] selectedAccounts = GetAttributeValue("Accounts").Split(',').Select(s => Guid.Parse(s)).ToArray();;

                var accounts = accountService.Queryable()
                               .Where(a => selectedAccounts.Contains(a.Guid));

                if (this.CampusId != 0)
                {
                    accounts = accounts.Where(a => a.CampusId.Value == this.CampusId || a.CampusId == null);
                }

                this.Accounts = new Dictionary <int, string>();

                foreach (var account in accounts.OrderBy(a => a.Order).ToList())
                {
                    this.Accounts.Add(account.Id, account.PublicName);
                }
            }
            else
            {
                nbBlockConfigErrors.Heading = "No Accounts Configured";
                nbBlockConfigErrors.Text    = "<p>There are currently no accounts configured.</p>";
                return(false);
            }

            // hide cancel buttons if no homepage defined
            if (string.IsNullOrWhiteSpace(GetAttributeValue("Homepage")))
            {
                lbSearchCancel.Visible           = false;
                lbGivingUnitSelectCancel.Visible = false;
                lbRegisterCancel.Visible         = false;
                lbAccountEntryCancel.Visible     = false;
                lbSwipeCancel.Visible            = false;
            }

            // get anonymous person
            Person anonymousPerson = null;

            Guid anonymousPersonAliasGuid;

            if (Guid.TryParse(GetAttributeValue("AnonymousPerson"), out anonymousPersonAliasGuid))
            {
                anonymousPerson = new PersonAliasService(rockContext).Get(anonymousPersonAliasGuid).Person;
            }

            if (anonymousPerson != null)
            {
                this.AnonymousGiverPersonAliasId = anonymousPerson.PrimaryAliasId;
                lbGiveAnonymously.Visible        = true;
            }
            else
            {
                lbGiveAnonymously.Visible = false;
            }

            _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
            if (_dvcConnectionStatus == null)
            {
                nbBlockConfigErrors.Heading = "Invalid Connection Status";
                nbBlockConfigErrors.Text    = "<p>The selected Connection Status setting does not exist.</p>";
                return(false);
            }

            _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());
            if (_dvcRecordStatus == null)
            {
                nbBlockConfigErrors.Heading = "Invalid Record Status";
                nbBlockConfigErrors.Text    = "<p>The selected Record Status setting does not exist.</p>";
                return(false);
            }

            return(true);
        }
Esempio n. 12
0
        /// <summary>
        /// Migrates the communication recipient activity data.
        /// </summary>
        /// <param name="context">The context.</param>
        private void MigrateCommunicationRecipientActivityData(IJobExecutionContext context)
        {
            using (var rockContext = new RockContext())
            {
                var componentEntityTypeCommunicationRecipient = EntityTypeCache.Get <Rock.Model.CommunicationRecipient>();
                var channelMediumCommunication = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_COMMUNICATION);

                // InteractionChannel for Communications already exists (in a migration)
                var interactionChannel   = new InteractionChannelService(rockContext).Get(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid());
                var interactionChannelId = interactionChannel.Id;

                // InteractionComponent : Email Subject Line as Name and Communication.Id as EntityId for any communication that has CommunicationRecipientActivity
                var insertCommunicationsAsComponentsSQL = $@"
INSERT INTO [dbo].[InteractionComponent] (
	[Name]
	,[EntityId]
	,[ChannelId]
	,[Guid]
	)
SELECT c.[Subject]
	,c.Id
	,{interactionChannelId}
	,NEWID()
FROM Communication c
WHERE (
		c.Id IN (
			SELECT cr.CommunicationId
			FROM CommunicationRecipient cr
			WHERE cr.Id IN (
					SELECT cra.CommunicationRecipientId
					FROM CommunicationRecipientActivity cra
					)
			)
		)
	AND c.Id NOT IN (
		SELECT EntityId
		FROM InteractionComponent
		WHERE ChannelId = {interactionChannelId}
		)
";

                // InteractionDeviceType: CommunicationRecipientActivity puts IP address, ClientType, OS, etc all smooshed together into ActivityDetail,
                var populateDeviceTypeFromActivityDetail = @"
DECLARE @ipaddressPatternSendGridMandrill NVARCHAR(max) = '%([0-9]%.%[0-9]%.%[0-9]%.%[0-9]%)%'
	DECLARE @ipaddressPatternMailgun NVARCHAR(max) = '%Opened from [0-9]%.%[0-9]%.%[0-9]%.%[0-9]% using %'
	DECLARE @ipaddressPatternMailgun_start NVARCHAR(max) = '%[0-9]%.%[0-9]%.%[0-9]%.%[0-9]%'
	DECLARE @ipaddressPatternMailgun_end NVARCHAR(max) = '% using %'
	DECLARE @ipaddressPatternClickStart NVARCHAR(max) = '% from %[0-9]%.%[0-9]%.%[0-9]%.%[0-9]% using%'
	DECLARE @ipaddressPatternClickEnd NVARCHAR(max) = '% using %'

	INSERT INTO [dbo].[InteractionDeviceType] (
		[Name]
		,[DeviceTypeData]
		,[Guid]
		)
	SELECT CASE 
			WHEN x.DeviceTypeInfo LIKE '%Apple Mail%'
				AND x.DeviceTypeInfo LIKE '%OS X%'
				THEN 'Apple Mail on OS X'
			WHEN x.DeviceTypeInfo LIKE '%Safari%'
				AND x.DeviceTypeInfo LIKE '%iOS%'
				THEN 'Safari on iOS'
			WHEN x.DeviceTypeInfo LIKE '%IE %'
				AND x.DeviceTypeInfo LIKE '%Windows%'
				THEN 'IE on Windows'
			WHEN x.DeviceTypeInfo LIKE '%Firefox browser%'
				AND x.DeviceTypeInfo LIKE '%Windows%'
				THEN 'Firefox browser on Windows'
			WHEN x.DeviceTypeInfo LIKE '%Chrome browser%'
				AND x.DeviceTypeInfo LIKE '%Windows%'
				THEN 'Chrome browser on Windows'
			WHEN x.DeviceTypeInfo LIKE '%Gmail%'
				AND x.DeviceTypeInfo LIKE '%Linux%'
				THEN 'Gmail on Linux'
			WHEN x.DeviceTypeInfo LIKE '%Android%mobile%'
				THEN 'Android Mobile'
			WHEN x.DeviceTypeInfo LIKE '%Android%browser%'
				THEN 'Android Browser'
			WHEN x.DeviceTypeInfo LIKE '%Outlook% on %Windows%'
				THEN 'Outlook on Windows'
			WHEN x.DeviceTypeInfo LIKE '%Outlook%'
				AND x.DeviceTypeInfo LIKE '%Windows%'
				THEN 'Outlook on Windows'
			ELSE 'Other'
			END [Name]
		,DeviceTypeInfo
		,NEWID()
	FROM (
		SELECT rtrim(ltrim(x.DeviceTypeInfo)) [DeviceTypeInfo]
		FROM (
			-- get just the UserAgent, etc stuff  (SendGrid or Mandrill): examples
			--   * Opened from Outlook 2013 on Windows 8 (70.209.106.108)
			--   * Opened from IE Mobile 7.0 on Windows Phone 7 (203.210.7.152)
			SELECT replace(substring([ActivityDetail], 0, PATINDEX(@ipaddressPatternSendGridMandrill, [ActivityDetail])), 'Opened from', '') [DeviceTypeInfo]
			FROM [CommunicationRecipientActivity]
			WHERE ActivityType = 'Opened'
				AND [ActivityDetail] NOT LIKE @ipaddressPatternMailgun
			
			UNION ALL
			
			-- get just the UserAgent, etc stuff  (Mailgun): examples
			--   * Opened from 207.91.187.194 using OS X desktop Apple Mail email client
			--   * Opened from 66.102.7.142 using Windows desktop Firefox browser
			SELECT replace(replace(substring([ActivityDetail], PATINDEX(@ipaddressPatternMailgun_end, [ActivityDetail]), 8000), 'Opened from', ''), ' using ', '') [DeviceTypeInfo]
			FROM [CommunicationRecipientActivity]
			WHERE ActivityType = 'Opened'
				AND [ActivityDetail] LIKE @ipaddressPatternMailgun
			
			UNION ALL
			
			SELECT ltrim(rtrim(replace(substring([Parsed], PATINDEX(@ipaddressPatternClickEnd, [Parsed]), 8000), ' using ', ''))) [DeviceTypeData]
			FROM (
				SELECT substring(ActivityDetail, PATINDEX(@ipaddressPatternClickStart, [ActivityDetail]) + len(' from '), 8000) [Parsed]
				FROM [CommunicationRecipientActivity]
				WHERE ActivityType = 'Click'
				) x
			) x
		GROUP BY rtrim(ltrim(x.DeviceTypeInfo))
		) x
	WHERE x.DeviceTypeInfo NOT IN (
			SELECT DeviceTypeData
			FROM InteractionDeviceType
			WHERE DeviceTypeData IS NOT NULL
			)
";

                // InteractionSession: CommunicationRecipientActivity smooshed the IP address into ActivityDetail
                var insertSessions = @"
DECLARE @ipaddressPatternSendGridMandrill NVARCHAR(max) = '%([0-9]%.%[0-9]%.%[0-9]%.%[0-9]%)%'
	DECLARE @ipaddressPatternMailgun NVARCHAR(max) = '%Opened from [0-9]%.%[0-9]%.%[0-9]%.%[0-9]% using %'
	DECLARE @ipaddressPatternMailgun_start NVARCHAR(max) = '%[0-9]%.%[0-9]%.%[0-9]%.%[0-9]%'
	DECLARE @ipaddressPatternMailgun_end NVARCHAR(max) = '% using %'
	DECLARE @ipaddressPatternClickStart NVARCHAR(max) = '% from %[0-9]%.%[0-9]%.%[0-9]%.%[0-9]% using%'
	DECLARE @ipaddressPatternClickEnd NVARCHAR(max) = '% using %'
    DECLARE @alreadyInsertedCount INT = (select count(*) from InteractionSession where ForeignGuid is not null)

	-- populate InteractionSession
	INSERT INTO [InteractionSession] (
		IPAddress
		,DeviceTypeId
		,ForeignGuid
		,[Guid]
		)
	SELECT rtrim(ltrim(x.IPAddress)) [IPAddress]
		,dt.Id [DeviceType.Id]
		,cra.[Guid]
		,newid()
	FROM (
		-- get the IP Address and DeviceType from Opens (SendGrid or Mandrill)
		SELECT replace(replace(substring([ActivityDetail], PATINDEX(@ipaddressPatternSendGridMandrill, [ActivityDetail]), 8000), '(', ''), ')', '') [IPAddress]
			,replace(substring([ActivityDetail], 0, PATINDEX(@ipaddressPatternSendGridMandrill, [ActivityDetail])), 'Opened from', '') [DeviceTypeData]
			,NULL [InteractionData]
			,[Id]
		FROM [CommunicationRecipientActivity]
		WHERE ActivityType = 'Opened'
			AND [ActivityDetail] NOT LIKE @ipaddressPatternMailgun
		
		UNION ALL
		
		-- get the IP Address and DeviceType from Opens (Mailgun)
		SELECT substring(x.Parsed, 0, PATINDEX(@ipaddressPatternMailgun_end, x.Parsed)) [IPAddress]
			,[DeviceTypeData]
			,NULL [InteractionData]
			,[Id]
		FROM (
			SELECT [Id]
				,replace(replace(substring([ActivityDetail], PATINDEX(@ipaddressPatternMailgun_end, [ActivityDetail]), 8000), 'Opened from', ''), ' using ', '') [DeviceTypeData]
				,substring([ActivityDetail], PATINDEX(@ipaddressPatternMailgun_start, [ActivityDetail]), 8000) [Parsed]
			FROM [CommunicationRecipientActivity]
			WHERE ActivityType = 'Opened'
				AND [ActivityDetail] LIKE @ipaddressPatternMailgun
			) x
		
		UNION ALL
		
		-- get the IP Address and DeviceType from Clicks (all webhooks)
		SELECT ltrim(rtrim(substring([Parsed], 0, PATINDEX(@ipaddressPatternClickEnd, [Parsed])))) [IPAddress]
			,ltrim(rtrim(replace(substring([Parsed], PATINDEX(@ipaddressPatternClickEnd, [Parsed]), 8000), ' using ', ''))) [DeviceTypeData]
			,ltrim(rtrim(replace(replace(replace(ActivityDetail, Parsed, ''), 'Clicked the address', ''), ' from', ''))) [InteractionData]
			,Id
		FROM (
			SELECT substring(ActivityDetail, PATINDEX(@ipaddressPatternClickStart, [ActivityDetail]) + len(' from '), 8000) [Parsed]
				,replace(replace(substring([ActivityDetail], PATINDEX(@ipaddressPatternClickStart, [ActivityDetail]), 8000), '(', ''), ')', '') [IPAddress]
				,replace(substring([ActivityDetail], 0, PATINDEX('% from %', [ActivityDetail])), ' from ', '') [DeviceTypeData]
				,*
			FROM [CommunicationRecipientActivity]
			WHERE ActivityType = 'Click'
			) x
		) x
	INNER JOIN CommunicationRecipientActivity cra ON cra.Id = x.Id
	CROSS APPLY (SELECT TOP 1 Id FROM InteractionDeviceType WHERE DeviceTypeData = rtrim(ltrim(x.DeviceTypeData))) dt
	WHERE (@alreadyInsertedCount = 0 or cra.[Guid] NOT IN (
			SELECT ForeignGuid
			FROM InteractionSession where ForeignGuid is not null
			))
";

                rockContext.Database.CommandTimeout = _commandTimeout;
                context.UpdateLastStatusMessage("Migrating Communication Activity to Interaction Components");

                rockContext.Database.ExecuteSqlCommand(@"
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_EntityId_ChannelId' AND object_id = OBJECT_ID('InteractionComponent'))
BEGIN
CREATE INDEX [IX_EntityId_ChannelId] ON [dbo].[InteractionComponent] ([EntityId],[ChannelId])
END
");

                _componentsInserted = rockContext.Database.ExecuteSqlCommand(insertCommunicationsAsComponentsSQL);

                rockContext.Database.CommandTimeout = _commandTimeout;
                context.UpdateLastStatusMessage("Migrating Communication Activity to Interaction DeviceTypes");
                _deviceTypesInserted = rockContext.Database.ExecuteSqlCommand(populateDeviceTypeFromActivityDetail);


                // Interaction
                // Remove any CommunicationRecipientActivity records that can't be converted into Interactions (because an IP Address couldn't be extracted)
                var unconvertableInteractionsSQL = @"DECLARE @ipaddressPatternSendGridMandrill NVARCHAR(max) = '%([0-9]%.%[0-9]%.%[0-9]%.%[0-9]%)%'
	DECLARE @ipaddressPatternMailgun NVARCHAR(max) = '%Opened from [0-9]%.%[0-9]%.%[0-9]%.%[0-9]% using %'
	DECLARE @ipaddressPatternMailgun_start NVARCHAR(max) = '%[0-9]%.%[0-9]%.%[0-9]%.%[0-9]%'
	DECLARE @ipaddressPatternMailgun_end NVARCHAR(max) = '% using %'
	DECLARE @ipaddressPatternClickStart NVARCHAR(max) = '% from %[0-9]%.%[0-9]%.%[0-9]%.%[0-9]% using%'
	DECLARE @ipaddressPatternClickEnd NVARCHAR(max) = '% using %'

DELETE FROM CommunicationRecipientActivity where Id in (    
SELECT --rtrim(ltrim(x.IPAddress)) [IPAddress]
		x.Id [cra.Id]
	FROM (
		-- get the IP Address and DeviceType from Opens (SendGrid or Mandrill)
		SELECT replace(replace(substring([ActivityDetail], PATINDEX(@ipaddressPatternSendGridMandrill, [ActivityDetail]), 8000), '(', ''), ')', '') [IPAddress]
			,[Id]
		FROM [CommunicationRecipientActivity]
		WHERE ActivityType = 'Opened'
			AND [ActivityDetail] NOT LIKE @ipaddressPatternMailgun
		
		UNION ALL
		
		-- get the IP Address and DeviceType from Opens (Mailgun)
		SELECT substring(x.Parsed, 0, PATINDEX(@ipaddressPatternMailgun_end, x.Parsed)) [IPAddress]
			,[Id]
		FROM (
			SELECT [Id]
				,substring([ActivityDetail], PATINDEX(@ipaddressPatternMailgun_start, [ActivityDetail]), 8000) [Parsed]
			FROM [CommunicationRecipientActivity]
			WHERE ActivityType = 'Opened'
				AND [ActivityDetail] LIKE @ipaddressPatternMailgun
			) x
		
		UNION ALL
		
		-- get the IP Address and DeviceType from Clicks (all webhooks)
		SELECT ltrim(rtrim(substring([Parsed], 0, PATINDEX(@ipaddressPatternClickEnd, [Parsed])))) [IPAddress]
			,Id
		FROM (
			SELECT substring(ActivityDetail, PATINDEX(@ipaddressPatternClickStart, [ActivityDetail]) + len(' from '), 8000) [Parsed]
				,*
			FROM [CommunicationRecipientActivity]
			WHERE ActivityType = 'Click'
			) x
		) x
	WHERE IPAddress LIKE '%[a-z]%'
			or len(IPAddress) > 15)"            ;

                context.UpdateLastStatusMessage("Cleaning up unconvertable Communication Activity to Interaction Sessions");
                rockContext.Database.ExecuteSqlCommand(unconvertableInteractionsSQL);

                rockContext.Database.ExecuteSqlCommand(@"
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_InteractionSessionForeignGuid' AND object_id = OBJECT_ID('InteractionSession'))
BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX [IX_InteractionSessionForeignGuid]
	ON [dbo].[InteractionSession] ([ForeignGuid])
    where ForeignGuid is not null
END
");

                rockContext.Database.CommandTimeout = _commandTimeout;
                context.UpdateLastStatusMessage("Migrating Communication Activity to Interaction Sessions");
                _sessionsInserted = rockContext.Database.ExecuteSqlCommand(insertSessions);

                int chunkSize           = 25000;
                var populateInteraction = $@"
BEGIN
	DECLARE @ipaddressPatternClickStart NVARCHAR(max) = '% from %[0-9]%.%[0-9]%.%[0-9]%.%[0-9]% using%'

	-- populate Interaction
	insert into Interaction (
	[InteractionDateTime]
	,[Operation]
	,InteractionComponentId
	,PersonAliasId
	,EntityId
	,InteractionSessionId
	,InteractionData
	,ForeignGuid
	,[Guid]
	)
	SELECT top {chunkSize} cra.ActivityDateTime [InteractionDateTime]
		,cra.ActivityType [Operation]
		,icmp.Id [ComponentId]
		,cr.PersonAliasId
		,cr.Id [EntityId]
		,iss.Id [SessionId]
		,cra.InteractionData [InteractionData]
		,cra.[Guid]
		,NEWID()
	FROM (
		SELECT ActivityDateTime
			,ActivityType
			,[Guid]
			,[CommunicationRecipientId]
			,NULL [InteractionData]
		FROM CommunicationRecipientActivity
		WHERE ActivityType = 'Opened'
		
		UNION ALL
		
		SELECT ActivityDateTime
			,ActivityType
			,[Guid]
			,[CommunicationRecipientId]
			,ltrim(rtrim(replace(replace(replace(ActivityDetail, Parsed, ''), 'Clicked the address', ''), ' from', ''))) [InteractionData]
		FROM (
			SELECT substring(ActivityDetail, PATINDEX(@ipaddressPatternClickStart, [ActivityDetail]) + len(' from '), 8000) [Parsed]
				,*
			FROM CommunicationRecipientActivity
			WHERE ActivityType = 'Click'
			) cc
		) cra
	INNER JOIN InteractionSession iss ON iss.[ForeignGuid] = cra.[Guid]
	INNER JOIN CommunicationRecipient cr ON cra.CommunicationRecipientId = cr.Id
	INNER JOIN Communication c ON cr.CommunicationId = c.Id
	CROSS APPLY (select top 1 icmp.Id from InteractionComponent icmp WHERE icmp.ChannelId = {interactionChannelId} AND icmp.EntityId = c.Id) icmp
     where cra.[Guid] not in (select ForeignGuid from Interaction where ForeignGuid is not null)
END
";

                bool keepMoving = true;

                while (keepMoving)
                {
                    var dbTransaction = rockContext.Database.BeginTransaction();
                    try
                    {
                        rockContext.Database.CommandTimeout = _commandTimeout;
                        int rowsMoved = rockContext.Database.ExecuteSqlCommand(populateInteraction);
                        keepMoving = rowsMoved > 0;
                        _communicationRecipientActivityMoved += rowsMoved;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }

                    var percentComplete = _communicationRecipientActivityTotal > 0 ? (_communicationRecipientActivityMoved * 100.0) / _communicationRecipientActivityTotal : 100.0;
                    var statusMessage   = $@"Progress: {_communicationRecipientActivityMoved} of {_communicationRecipientActivityTotal} ({Math.Round( percentComplete, 1 )}%) Communication Recipient Activity data migrated to Interactions";
                    context.UpdateLastStatusMessage(statusMessage);
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Migrates the page views data.
        /// </summary>
        /// <param name="context">The context.</param>
        private void MigratePageViewsData(IJobExecutionContext context)
        {
            using (var rockContext = new RockContext())
            {
                var componentEntityTypePage  = EntityTypeCache.Get <Rock.Model.Page>();
                var channelMediumWebsite     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE);
                var sqlInsertSitesToChannels = $@"
-- Insert Websites
INSERT INTO [InteractionChannel] (
    [Name]
    ,[ComponentEntityTypeId]
    ,[ChannelTypeMediumValueId]
    ,[ChannelEntityId]
    ,[Guid]
    )
SELECT s.[Name] [Site.Name]
    ,{componentEntityTypePage.Id}
    ,'{channelMediumWebsite.Id}'
    ,s.[Id] [SiteId]
    ,NEWID() AS NewGuid
FROM [PageView] pv
INNER JOIN [Site] s ON pv.[SiteId] = s.[Id]
WHERE s.Id NOT IN (
        SELECT ChannelEntityId
        FROM InteractionChannel where ChannelEntityId is not null
        )
GROUP BY s.[Id]
    ,s.[Name]";

                var sqlInsertPagesToComponents = @"
INSERT INTO [InteractionComponent] (
    [Name]
    ,[EntityId]
    ,[Guid]
    ,[ChannelId]
    )
SELECT isnull(pv.[PageTitle], '')
    ,pv.[PageId]
    ,NEWID() AS NewGuid
    ,c.[Id]
FROM [PageView] pv 
INNER JOIN [Site] s ON pv.SiteId = s.Id
INNER JOIN [InteractionChannel] c ON s.[Id] = c.[ChannelEntityId]
AND CONCAT (
        pv.[PageTitle]
		,'_'
		,pv.PageId
        ,'_'
        ,c.Id
        ) NOT IN (
        SELECT CONCAT (
				[Name]
				,'_'
                ,EntityId
                ,'_'
                ,ChannelId
                )
        FROM InteractionComponent
        )
GROUP BY pv.[PageId]
    ,isnull(pv.[PageTitle], '')
    ,c.[Id]
";

                var insertUserAgentToDeviceTypes = @"
-- Insert Devices
INSERT INTO [InteractionDeviceType] (
    [Name]
    ,[Application]
    ,[DeviceTypeData]
    ,[ClientType]
    ,[OperatingSystem]
    ,[Guid]
    ,[ForeignId]
    )
SELECT [OperatingSystem] + ' - ' + [Browser]
    ,[Browser]
    ,[UserAgent]
    ,[ClientType]
    ,[OperatingSystem]
    ,NEWID()
    ,[Id]
FROM [PageViewUserAgent]
WHERE Id NOT IN (
        SELECT ForeignId
        FROM InteractionDeviceType where ForeignId is not null
        )
";

                // Clean up unused PageViewSession data in chunks
                // delete the indexes so they don't have to be updated as the rows are deleted
                rockContext.Database.ExecuteSqlCommand(@"
IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_Guid'
			AND object_id = OBJECT_ID('PageViewSession')
		)
BEGIN
	DROP INDEX [IX_Guid] ON [dbo].[PageViewSession]
END

IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_PageViewUserAgentId'
			AND object_id = OBJECT_ID('PageViewSession')
		)
BEGIN
	DROP INDEX [IX_PageViewUserAgentId] ON [dbo].[PageViewSession]
END

IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_SessionId'
			AND object_id = OBJECT_ID('PageViewSession')
		)
BEGIN
	DROP INDEX [IX_SessionId] ON [dbo].[PageViewSession]
END");

                int unUsedSessionsTotal   = rockContext.Database.SqlQuery <int>(@"SELECT COUNT(*) FROM PageViewSession where Id not in ( select distinct PageViewSessionId from PageView )").First();
                int unUsedSessionsDeleted = 0;

                bool keepMoving           = true;
                int  chunkSize            = 25000;
                var  deleteUnusedSessions = $@"delete top ({chunkSize}) from PageViewSession where Id not in (
select distinct PageViewSessionId from PageView)";
                while (keepMoving)
                {
                    int rowsDeleted = rockContext.Database.ExecuteSqlCommand(deleteUnusedSessions);
                    keepMoving             = rowsDeleted > 0;
                    unUsedSessionsDeleted += rowsDeleted;
                    if (unUsedSessionsTotal > 0)
                    {
                        var percentDone = Math.Round(( decimal )unUsedSessionsDeleted * 100 / unUsedSessionsTotal, 2);
                        context.UpdateLastStatusMessage($"Cleaning up unused PageViewSession data ({unUsedSessionsDeleted} of {unUsedSessionsTotal}, {percentDone}%) ");
                    }
                }

                var insertSessions = $@"
INSERT INTO [InteractionSession] (
    [DeviceTypeId]
    ,[IpAddress]
    ,[Guid]
    ,[ForeignId]
    )
SELECT c.[Id]
    ,a.[IpAddress]
    ,a.[Guid]
    ,a.[Id]
FROM [PageViewSession] a
INNER JOIN [PageViewUserAgent] AS b ON a.[PageViewUserAgentId] = b.[Id]
INNER JOIN [InteractionDeviceType] AS c ON c.[ForeignId] = a.[PageViewUserAgentId]
WHERE a.Id NOT IN (
        SELECT ForeignId
        FROM InteractionSession where ForeignId is not null
        );";

                rockContext.Database.CommandTimeout = _commandTimeout;
                _channelsInserted   += rockContext.Database.ExecuteSqlCommand(sqlInsertSitesToChannels);
                _componentsInserted  = rockContext.Database.ExecuteSqlCommand(sqlInsertPagesToComponents);
                _deviceTypesInserted = rockContext.Database.ExecuteSqlCommand(insertUserAgentToDeviceTypes);
                _sessionsInserted    = rockContext.Database.ExecuteSqlCommand(insertSessions);
                var interactionService = new InteractionService(rockContext);

                rockContext.Database.ExecuteSqlCommand(@"
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_InteractionSessionForeignId' AND object_id = OBJECT_ID('InteractionSession'))
BEGIN
    CREATE unique NONCLUSTERED INDEX [IX_InteractionSessionForeignId]
	ON [dbo].[InteractionSession] ([ForeignId])
	INCLUDE ([Id])
	where ForeignId is not null
END
");

                var interactionCommunicationChannel   = new InteractionChannelService(rockContext).Get(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid());
                var interactionCommunicationChannelId = interactionCommunicationChannel.Id;

                // move PageView data in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)

                // delete the indexes so they don't have to be updated as the rows are deleted
                rockContext.Database.ExecuteSqlCommand(@"
IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_DateTimeViewed'
			AND object_id = OBJECT_ID('PageView')
		)
BEGIN
	DROP INDEX [IX_DateTimeViewed] ON [dbo].[PageView]
END

IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_PageId'
			AND object_id = OBJECT_ID('PageView')
		)
BEGIN
	DROP INDEX IX_PageId ON [dbo].[PageView]
END

IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_PageViewSessionId'
			AND object_id = OBJECT_ID('PageView')
		)
BEGIN
	DROP INDEX IX_PageViewSessionId ON [dbo].[PageView]
END

IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_PersonAliasId'
			AND object_id = OBJECT_ID('PageView')
		)
BEGIN
	DROP INDEX IX_PersonAliasId ON [dbo].[PageView]
END

IF EXISTS (
		SELECT *
		FROM sys.indexes
		WHERE NAME = 'IX_SiteId'
			AND object_id = OBJECT_ID('PageView')
		)
BEGIN
	DROP INDEX IX_SiteId ON [dbo].[PageView]
END
");

                keepMoving = true;

                while (keepMoving)
                {
                    var dbTransaction = rockContext.Database.BeginTransaction();
                    try
                    {
                        // keep track of where to start so that SQL doesn't have to scan the whole table when deleting
                        int insertStartId = interactionService.Queryable().Max(a => (int?)a.Id) ?? 1;

                        rockContext.Database.CommandTimeout = _commandTimeout;
                        int rowsMoved = rockContext.Database.ExecuteSqlCommand($@"
                            INSERT INTO [Interaction]  WITH (TABLOCK) (
		                        [InteractionDateTime]
		                        ,[Operation]
		                        ,[InteractionComponentId]
		                        ,[InteractionSessionId]
		                        ,[InteractionData]
		                        ,[PersonAliasId]
		                        ,[Guid]
		                        )
	                        SELECT TOP ({chunkSize}) *
	                        FROM (
		                        SELECT [DateTimeViewed]
			                        ,'View' [Operation]
			                        ,cmp.[Id] [InteractionComponentId]
			                        ,s.[Id] [InteractionSessionId]
			                        ,pv.[Url] [InteractionData]
			                        ,pv.[PersonAliasId]
			                        ,pv.[Guid] [Guid]
		                        FROM [PageView] pv
		                        CROSS APPLY (
			                        SELECT max(id) [Id]
			                        FROM [InteractionComponent] cmp
			                        WHERE ChannelId != {interactionCommunicationChannelId}
                                        AND ISNULL(pv.[PageId], 0) = ISNULL(cmp.[EntityId], 0)
				                        AND isnull(pv.[PageTitle], '') = isnull(cmp.[Name], '')
			                        ) cmp
		                        CROSS APPLY (
			                        SELECT top 1 s.Id [Id]
			                        FROM [InteractionSession] s
			                        WHERE s.[ForeignId] = pv.[PageViewSessionId]
				                        AND s.ForeignId IS NOT NULL
			                        ) s
		                        where cmp.Id is not null
		                        ) x "        );

                        // delete PageViews that have been moved to the Interaction table
                        rockContext.Database.CommandTimeout = _commandTimeout;
                        rockContext.Database.ExecuteSqlCommand($"delete from PageView with (tablock) where [Guid] in (select [Guid] from Interaction WHERE Id >= {insertStartId})");

                        keepMoving       = rowsMoved > 0;
                        _pageViewsMoved += rowsMoved;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }

                    var percentComplete = _pageViewsTotal > 0 ? (_pageViewsMoved * 100.0) / _pageViewsTotal : 100.0;
                    var statusMessage   = $@"Progress: {_pageViewsMoved} of {_pageViewsTotal} ({Math.Round( percentComplete, 1 )}%) PageViews data migrated to Interactions";
                    context.UpdateLastStatusMessage(statusMessage);
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Handles the DisplayFilterValue event of the gfBatchFilter control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs"/> instance containing the event data.</param>
        protected void gfBatchFilter_DisplayFilterValue(object sender, Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs e)
        {
            if (AvailableAttributes != null)
            {
                var attribute = AvailableAttributes.FirstOrDefault(a => "Attribute_" + a.Key == e.Key);
                if (attribute != null)
                {
                    try
                    {
                        var values = JsonConvert.DeserializeObject <List <string> >(e.Value);
                        e.Value = attribute.FieldType.Field.FormatFilterValues(attribute.QualifierValues, values);
                        return;
                    }
                    catch
                    {
                        // intentionally ignore
                    }
                }
            }

            switch (e.Key)
            {
            case "Row Limit":
            {
                // row limit filter was removed, so hide it just in case
                e.Value = null;
                break;
            }

            case "Date Range":
            {
                e.Value = DateRangePicker.FormatDelimitedValues(e.Value);
                break;
            }

            case "Status":
            {
                var status = e.Value.ConvertToEnumOrNull <BatchStatus>();
                if (status.HasValue)
                {
                    e.Value = status.ConvertToString();
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Contains Transaction Type":
            {
                var transactionTypeValueId = e.Value.AsIntegerOrNull();
                if (transactionTypeValueId.HasValue)
                {
                    var transactionTypeValue = DefinedValueCache.Get(transactionTypeValueId.Value);
                    e.Value = transactionTypeValue != null?transactionTypeValue.ToString() : string.Empty;
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Campus":
            {
                var campus = CampusCache.Get(e.Value.AsInteger());
                if (campus != null)
                {
                    e.Value = campus.Name;
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid()
        {
            if ( _group != null )
            {
                pnlGroupMembers.Visible = true;

                lHeading.Text = string.Format( "{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize() );

                if ( _group.GroupType.Roles.Any() )
                {
                    nbRoleWarning.Visible = false;
                    rFilter.Visible = true;
                    gGroupMembers.Visible = true;

                    var rockContext = new RockContext();

                    GroupMemberService groupMemberService = new GroupMemberService( rockContext );
                    var qry = groupMemberService.Queryable( "Person,GroupRole", true ).AsNoTracking()
                        .Where( m => m.GroupId == _group.Id );

                    // Filter by First Name
                    string firstName = tbFirstName.Text;
                    if ( !string.IsNullOrWhiteSpace( firstName ) )
                    {
                        qry = qry.Where( m => m.Person.FirstName.StartsWith( firstName ) );
                    }

                    // Filter by Last Name
                    string lastName = tbLastName.Text;
                    if ( !string.IsNullOrWhiteSpace( lastName ) )
                    {
                        qry = qry.Where( m => m.Person.LastName.StartsWith( lastName ) );
                    }

                    // Filter by role
                    var validGroupTypeRoles = _group.GroupType.Roles.Select( r => r.Id ).ToList();
                    var roles = new List<int>();
                    foreach ( string role in cblRole.SelectedValues )
                    {
                        if ( !string.IsNullOrWhiteSpace( role ) )
                        {
                            int roleId = int.MinValue;
                            if ( int.TryParse( role, out roleId ) && validGroupTypeRoles.Contains( roleId ) )
                            {
                                roles.Add( roleId );
                            }
                        }
                    }

                    if ( roles.Any() )
                    {
                        qry = qry.Where( m => roles.Contains( m.GroupRoleId ) );
                    }

                    // Filter by Status
                    var statuses = new List<GroupMemberStatus>();
                    foreach ( string status in cblStatus.SelectedValues )
                    {
                        if ( !string.IsNullOrWhiteSpace( status ) )
                        {
                            statuses.Add( status.ConvertToEnum<GroupMemberStatus>() );
                        }
                    }

                    if ( statuses.Any() )
                    {
                        qry = qry.Where( m => statuses.Contains( m.GroupMemberStatus ) );
                    }

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

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

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

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

                    _inactiveStatus = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE );

                    SortProperty sortProperty = gGroupMembers.SortProperty;

                    bool hasGroupRequirements = new GroupRequirementService( rockContext ).Queryable().Where( a => a.GroupId == _group.Id ).Any();

                    // If there are group requirements that that member doesn't meet, show an icon in the grid
                    bool includeWarnings = false;
                    var groupMemberIdsThatLackGroupRequirements = new GroupService( rockContext ).GroupMembersNotMeetingRequirements( _group.Id, includeWarnings ).Select( a => a.Key.Id );

                    List<GroupMember> groupMembersList = null;

                    if ( sortProperty != null )
                    {
                        groupMembersList = qry.Sort( sortProperty ).ToList();
                    }
                    else
                    {
                        groupMembersList = qry.OrderBy( a => a.GroupRole.Order ).ThenBy( a => a.Person.LastName ).ThenBy( a => a.Person.FirstName ).ToList();
                    }

                    // Since we're not binding to actual group member list, but are using AttributeField columns,
                    // we need to save the workflows into the grid's object list
                    gGroupMembers.ObjectList = new Dictionary<string, object>();
                    groupMembersList.ForEach( m => gGroupMembers.ObjectList.Add( m.Id.ToString(), m ) );
                    gGroupMembers.EntityTypeId = EntityTypeCache.Read( Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid() ).Id;

                    gGroupMembers.DataSource = groupMembersList.Select( m => new
                    {
                        m.Id,
                        m.Guid,
                        m.PersonId,
                        Name = m.Person.NickName + " " + m.Person.LastName
                            + ( hasGroupRequirements && groupMemberIdsThatLackGroupRequirements.Contains( m.Id )
                                ? " <i class='fa fa-exclamation-triangle text-warning'></i>"
                                : string.Empty )
                            + ( !string.IsNullOrEmpty( m.Note )
                            ? " <i class='fa fa-file-text-o text-info'></i>"
                            : string.Empty ),
                        GroupRole = m.GroupRole.Name,
                        m.GroupMemberStatus,
                        RecordStatusValueId = m.Person.RecordStatusValueId,
                        IsDeceased = m.Person.IsDeceased
                    } ).ToList();

                    gGroupMembers.DataBind();
                }
                else
                {
                    nbRoleWarning.Text = string.Format(
                        "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.",
                        _group.GroupType.GroupMemberTerm.Pluralize(),
                        _group.GroupType.GroupTerm,
                        _group.GroupType.Name );

                    nbRoleWarning.Visible = true;
                    rFilter.Visible = false;
                    gGroupMembers.Visible = false;
                }
            }
            else
            {
                pnlGroupMembers.Visible = false;
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            GroupType groupType = null;

            var rockContext = new RockContext();
            GroupTypeService          groupTypeService          = new GroupTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int?groupTypeId = hfGroupTypeId.ValueAsInt();

            if (groupTypeId.HasValue && groupTypeId.Value > 0)
            {
                groupType = groupTypeService.Get(groupTypeId.Value);
            }

            bool newGroupType = false;

            if (groupType == null)
            {
                groupType = new GroupType();
                groupTypeService.Add(groupType);

                var templatePurpose = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid());
                if (templatePurpose != null)
                {
                    groupType.GroupTypePurposeValueId = templatePurpose.Id;
                }

                newGroupType = true;
            }

            if (groupType != null)
            {
                groupType.Name         = tbName.Text;
                groupType.Description  = tbDescription.Text;
                groupType.IconCssClass = tbIconCssClass.Text;
                groupType.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributeEdits, groupType);

                groupType.SetAttributeValue("core_checkin_AgeRequired", cbAgeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_GradeRequired", cbGradeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_HidePhotos", cbHidePhotos.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventDuplicateCheckin", cbPreventDuplicateCheckin.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventInactivePeople", cbPreventInactivePeople.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_CheckInType", ddlType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_DisplayLocationCount", cbDisplayLocCount.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableManagerOption", cbEnableManager.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableOverride", cbEnableOverride.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_MaximumPhoneSearchLength", nbMaxPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_MaxSearchResults", nbMaxResults.Text);
                groupType.SetAttributeValue("core_checkin_MinimumPhoneSearchLength", nbMinPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_UseSameOptions", cbUseSameOptions.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PhoneSearchType", ddlPhoneSearchType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_RefreshInterval", nbRefreshInterval.Text);
                groupType.SetAttributeValue("core_checkin_RegularExpressionFilter", tbSearchRegex.Text);
                groupType.SetAttributeValue("core_checkin_ReuseSameCode", cbReuseCode.Checked.ToString());

                var searchType = DefinedValueCache.Get(ddlSearchType.SelectedValueAsInt() ?? 0);
                if (searchType != null)
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", searchType.Guid.ToString());
                }
                else
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                }

                groupType.SetAttributeValue("core_checkin_SecurityCodeLength", nbCodeAlphaNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeAlphaLength", nbCodeAlphaLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericLength", nbCodeNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericRandom", cbCodeRandom.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AllowCheckout", cbAllowCheckout.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnablePresence", cbEnablePresence.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AutoSelectDaysBack", nbAutoSelectDaysBack.Text);
                groupType.SetAttributeValue("core_checkin_AutoSelectOptions", ddlAutoSelectOptions.SelectedValueAsInt());

                // Registration Settings

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORADULTS, cbRegistrationDisplayAlternateIdFieldForAdults.Checked.ToTrueFalse());
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORCHILDREN, cbRegistrationDisplayAlternateIdFieldForChildren.Checked.ToTrueFalse());
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYSMSBUTTON, cbRegistrationDisplaySmsEnabled.Checked.ToTrueFalse());
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED, cbRegistrationSmsEnabledByDefault.Checked.ToTrueFalse());

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORADULTS,
                    lbRegistrationRequiredAttributesForAdults.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORADULTS,
                    lbRegistrationOptionalAttributesForAdults.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORCHILDREN,
                    lbRegistrationRequiredAttributesForChildren.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORCHILDREN,
                    lbRegistrationOptionalAttributesForChildren.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORFAMILIES,
                    lbRegistrationRequiredAttributesForFamilies.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORFAMILIES,
                    lbRegistrationOptionalAttributesForFamilies.SelectedValues.AsDelimited(","));

                Guid?defaultPersonConnectionStatusValueGuid = null;
                var  defaultPersonConnectionStatusValueId   = dvpRegistrationDefaultPersonConnectionStatus.SelectedValue.AsIntegerOrNull();
                if (defaultPersonConnectionStatusValueId.HasValue)
                {
                    var defaultPersonConnectionStatusValue = DefinedValueCache.Get(defaultPersonConnectionStatusValueId.Value);
                    if (defaultPersonConnectionStatusValue != null)
                    {
                        defaultPersonConnectionStatusValueGuid = defaultPersonConnectionStatusValue.Guid;
                    }
                }

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTPERSONCONNECTIONSTATUS,
                    defaultPersonConnectionStatusValueGuid.ToString());

                var workflowTypeService = new WorkflowTypeService(rockContext);

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDFAMILYWORKFLOWTYPES,
                    workflowTypeService.GetByIds(wftpRegistrationAddFamilyWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDPERSONWORKFLOWTYPES,
                    workflowTypeService.GetByIds(wftpRegistrationAddPersonWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(","));

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ENABLECHECKINAFTERREGISTRATION, cbEnableCheckInAfterRegistration.Checked.ToTrueFalse());

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_KNOWNRELATIONSHIPTYPES, lbKnownRelationshipTypes.SelectedValues.AsDelimited(","));
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_SAMEFAMILYKNOWNRELATIONSHIPTYPES, lbSameFamilyKnownRelationshipTypes.SelectedValues.AsDelimited(","));
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_CANCHECKINKNOWNRELATIONSHIPTYPES, lbCanCheckInKnownRelationshipTypes.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_START_LAVA_TEMPLATE, ceStartTemplate.Text);
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_FAMILYSELECT_LAVA_TEMPLATE, ceFamilySelectTemplate.Text);
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_SUCCESS_LAVA_TEMPLATE, ceSuccessTemplate.Text);

                // Save group type and attributes
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    groupType.SaveAttributeValues(rockContext);
                });

                if (newGroupType)
                {
                    var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId);
                    pageRef.Parameters.Add("CheckinTypeId", groupType.Id.ToString());
                    NavigateToPage(pageRef);
                }
                else
                {
                    groupType = groupTypeService.Get(groupType.Id);
                    ShowReadonlyDetails(groupType);
                }

                Rock.CheckIn.KioskDevice.Clear();
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            Campus campus;
            var    rockContext         = new RockContext();
            var    campusService       = new CampusService(rockContext);
            var    locationService     = new LocationService(rockContext);
            var    locationCampusValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS.AsGuid());

            int campusId = int.Parse(hfCampusId.Value);

            if (campusId == 0)
            {
                campus = new Campus();
                campusService.Add(campus);
            }
            else
            {
                campus = campusService.Get(campusId);
            }

            campus.Name        = tbCampusName.Text;
            campus.IsActive    = cbIsActive.Checked;
            campus.Description = tbDescription.Text;
            campus.Url         = tbUrl.Text;

            campus.PhoneNumber = tbPhoneNumber.Text;
            if (campus.Location == null)
            {
                var location = locationService.Queryable()
                               .Where(l =>
                                      l.Name.Equals(campus.Name, StringComparison.OrdinalIgnoreCase) &&
                                      l.LocationTypeValueId == locationCampusValue.Id)
                               .FirstOrDefault();
                if (location == null)
                {
                    location = new Location();
                    locationService.Add(location);
                }

                campus.Location = location;
            }

            campus.Location.Name = campus.Name;
            campus.Location.LocationTypeValueId = locationCampusValue.Id;

            string preValue = campus.Location.GetFullStreetAddress();

            acAddress.GetValues(campus.Location);
            string postValue = campus.Location.GetFullStreetAddress();

            campus.ShortCode = tbCampusCode.Text;

            var personService = new PersonService(rockContext);
            var leaderPerson  = personService.Get(ppCampusLeader.SelectedValue ?? 0);

            campus.LeaderPersonAliasId = leaderPerson != null ? leaderPerson.PrimaryAliasId : null;

            campus.ServiceTimes = kvlServiceTimes.Value;

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

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

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

                if (preValue != postValue && !string.IsNullOrWhiteSpace(campus.Location.Street1))
                {
                    locationService.Verify(campus.Location, true);
                }
            });

            Rock.Web.Cache.CampusCache.Flush(campus.Id);

            NavigateToParentPage();
        }
Esempio n. 18
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="groupTypeId">The groupType identifier.</param>
        public void ShowDetail(int groupTypeId)
        {
            pnlDetails.Visible = false;

            bool editAllowed = true;

            GroupType groupType = null;

            if (!groupTypeId.Equals(0))
            {
                groupType = new GroupTypeService(new RockContext()).Get(groupTypeId);
                pdAuditDetails.SetEntity(groupType, ResolveRockUrl("~"));
            }

            if (groupType == null)
            {
                groupType = new GroupType {
                    Id = 0
                };
                var templatePurpose = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid());
                if (templatePurpose != null)
                {
                    groupType.GroupTypePurposeValueId = templatePurpose.Id;
                }

                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            if (groupType != null)
            {
                editAllowed = groupType.IsAuthorized(Authorization.EDIT, CurrentPerson);

                pnlDetails.Visible  = true;
                hfGroupTypeId.Value = groupType.Id.ToString();

                // render UI based on Authorized and IsSystem
                bool readOnly = false;

                nbEditModeMessage.Text = string.Empty;
                if (!editAllowed || !IsUserAuthorized(Authorization.EDIT))
                {
                    readOnly = true;
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(GroupType.FriendlyTypeName);
                }

                if (readOnly)
                {
                    btnEdit.Visible   = false;
                    btnDelete.Visible = false;
                    ShowReadonlyDetails(groupType);
                }
                else
                {
                    btnEdit.Visible   = true;
                    btnDelete.Visible = true;

                    if (groupType.Id > 0)
                    {
                        ShowReadonlyDetails(groupType);
                    }
                    else
                    {
                        ShowEditDetails(groupType);
                    }
                }
            }
        }
 /// <summary>
 /// Returnes a boolean value indicating if 'Saved Account' functionality is supported for the given currency type. 
 /// </summary>
 /// <param name="currencyType">Type of the currency.</param>
 /// <returns></returns>
 public virtual bool SupportsSavedAccount( DefinedValueCache currencyType )
 {
     return true;
 }
Esempio n. 20
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="groupType">The groupType.</param>
        private void ShowEditDetails(GroupType groupType)
        {
            if (groupType != null)
            {
                if (groupType.Id == 0)
                {
                    lReadOnlyTitle.Text = ActionTitle.Add("Check-in Configuration").FormatAsHtmlTitle();
                }
                else
                {
                    lReadOnlyTitle.Text = groupType.ToString().FormatAsHtmlTitle();
                }

                SetEditMode(true);

                tbName.Text         = groupType.Name;
                tbDescription.Text  = groupType.Description;
                tbIconCssClass.Text = groupType.IconCssClass;
                var rockContext = new RockContext();

                groupType.LoadAttributes(rockContext);

                cbAgeRequired.Checked             = groupType.GetAttributeValue("core_checkin_AgeRequired").AsBoolean(true);
                cbGradeRequired.Checked           = groupType.GetAttributeValue("core_checkin_GradeRequired").AsBoolean(true);
                cbHidePhotos.Checked              = groupType.GetAttributeValue("core_checkin_HidePhotos").AsBoolean(true);
                cbPreventDuplicateCheckin.Checked = groupType.GetAttributeValue("core_checkin_PreventDuplicateCheckin").AsBoolean(true);
                cbPreventInactivePeople.Checked   = groupType.GetAttributeValue("core_checkin_PreventInactivePeople").AsBoolean(true);
                ddlType.SetValue(groupType.GetAttributeValue("core_checkin_CheckInType"));
                cbDisplayLocCount.Checked = groupType.GetAttributeValue("core_checkin_DisplayLocationCount").AsBoolean(true);
                cbEnableManager.Checked   = groupType.GetAttributeValue("core_checkin_EnableManagerOption").AsBoolean(true);
                cbEnableOverride.Checked  = groupType.GetAttributeValue("core_checkin_EnableOverride").AsBoolean(true);
                nbMaxPhoneLength.Text     = groupType.GetAttributeValue("core_checkin_MaximumPhoneSearchLength");
                nbMaxResults.Text         = groupType.GetAttributeValue("core_checkin_MaxSearchResults");
                nbMinPhoneLength.Text     = groupType.GetAttributeValue("core_checkin_MinimumPhoneSearchLength");
                cbUseSameOptions.Checked  = groupType.GetAttributeValue("core_checkin_UseSameOptions").AsBoolean(false);
                ddlPhoneSearchType.SetValue(groupType.GetAttributeValue("core_checkin_PhoneSearchType"));
                nbRefreshInterval.Text = groupType.GetAttributeValue("core_checkin_RefreshInterval");
                tbSearchRegex.Text     = groupType.GetAttributeValue("core_checkin_RegularExpressionFilter");
                cbReuseCode.Checked    = groupType.GetAttributeValue("core_checkin_ReuseSameCode").AsBoolean(false);

                var searchType = DefinedValueCache.Get(groupType.GetAttributeValue("core_checkin_SearchType").AsGuid());
                if (searchType != null)
                {
                    ddlSearchType.SetValue(searchType.Id.ToString());
                }

                nbCodeAlphaNumericLength.Text = groupType.GetAttributeValue("core_checkin_SecurityCodeLength");
                nbCodeAlphaLength.Text        = groupType.GetAttributeValue("core_checkin_SecurityCodeAlphaLength");
                nbCodeNumericLength.Text      = groupType.GetAttributeValue("core_checkin_SecurityCodeNumericLength");
                cbCodeRandom.Checked          = groupType.GetAttributeValue("core_checkin_SecurityCodeNumericRandom").AsBoolean(true);
                cbAllowCheckout.Checked       = groupType.GetAttributeValue("core_checkin_AllowCheckout").AsBoolean(true);
                cbEnablePresence.Checked      = groupType.GetAttributeValue("core_checkin_EnablePresence").AsBoolean();
                nbAutoSelectDaysBack.Text     = groupType.GetAttributeValue("core_checkin_AutoSelectDaysBack");
                ddlAutoSelectOptions.SetValue(groupType.GetAttributeValue("core_checkin_AutoSelectOptions"));

                // Registration Settings
                cbRegistrationDisplayAlternateIdFieldForAdults.Checked   = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORADULTS).AsBoolean();
                cbRegistrationDisplayAlternateIdFieldForChildren.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORCHILDREN).AsBoolean();

                cbRegistrationDisplaySmsEnabled.Checked   = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYSMSBUTTON).AsBoolean();
                cbRegistrationSmsEnabledByDefault.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBoolean();

                lbRegistrationRequiredAttributesForAdults.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORADULTS).SplitDelimitedValues());
                lbRegistrationOptionalAttributesForAdults.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORADULTS).SplitDelimitedValues());

                lbRegistrationRequiredAttributesForChildren.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORCHILDREN).SplitDelimitedValues());
                lbRegistrationOptionalAttributesForChildren.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORCHILDREN).SplitDelimitedValues());

                lbRegistrationRequiredAttributesForFamilies.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORFAMILIES).SplitDelimitedValues());
                lbRegistrationOptionalAttributesForFamilies.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORFAMILIES).SplitDelimitedValues());

                int? defaultPersonConnectionStatusValueId   = null;
                Guid?defaultPersonConnectionStatusValueGuid = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTPERSONCONNECTIONSTATUS).AsGuidOrNull();
                if (defaultPersonConnectionStatusValueGuid.HasValue)
                {
                    var defaultPersonRecordStatusValue = DefinedValueCache.Get(defaultPersonConnectionStatusValueGuid.Value);
                    if (defaultPersonRecordStatusValue != null)
                    {
                        defaultPersonConnectionStatusValueId = defaultPersonRecordStatusValue.Id;
                    }
                }

                dvpRegistrationDefaultPersonConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS.AsGuid()).Id;
                dvpRegistrationDefaultPersonConnectionStatus.SetValue(defaultPersonConnectionStatusValueId);

                var workflowTypeService = new WorkflowTypeService(rockContext);
                wftpRegistrationAddFamilyWorkflowTypes.SetValues(workflowTypeService.GetByGuids(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDFAMILYWORKFLOWTYPES).SplitDelimitedValues().AsGuidList()));
                wftpRegistrationAddPersonWorkflowTypes.SetValues(workflowTypeService.GetByGuids(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDPERSONWORKFLOWTYPES).SplitDelimitedValues().AsGuidList()));

                cbEnableCheckInAfterRegistration.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ENABLECHECKINAFTERREGISTRATION).AsBoolean();

                lbKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_KNOWNRELATIONSHIPTYPES).SplitDelimitedValues());
                lbSameFamilyKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_SAMEFAMILYKNOWNRELATIONSHIPTYPES).SplitDelimitedValues());
                lbCanCheckInKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_CANCHECKINKNOWNRELATIONSHIPTYPES).SplitDelimitedValues());

                ceStartTemplate.Text        = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_START_LAVA_TEMPLATE);
                ceFamilySelectTemplate.Text = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_FAMILYSELECT_LAVA_TEMPLATE);
                ceSuccessTemplate.Text      = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_SUCCESS_LAVA_TEMPLATE);

                // Other GroupType Attributes
                BuildAttributeEdits(groupType, true);

                SetFieldVisibility();
            }
        }
        /// <summary>
        /// Gets the specified name prefix.
        /// </summary>
        /// <param name="namePrefix">The name prefix.</param>
        /// <param name="currencyType">Type of the currency.</param>
        /// <param name="creditCardType">Type of the credit card.</param>
        /// <param name="transactionDate">The transaction date.</param>
        /// <param name="batchTimeOffset">The batch time offset.</param>
        /// <param name="batches">The batches.</param>
        /// <returns></returns>
        public FinancialBatch Get( string namePrefix, DefinedValueCache currencyType, DefinedValueCache creditCardType,
            DateTime transactionDate, TimeSpan batchTimeOffset, List<FinancialBatch> batches = null )
        {
            // Use the credit card type's batch name suffix, or if that doesn't exist, use the currency type value
            string ccSuffix = string.Empty;
            
            if (creditCardType != null )
            {
                ccSuffix = creditCardType.GetAttributeValue( "BatchNameSuffix" );
                if ( string.IsNullOrWhiteSpace( ccSuffix ) )
                {
                    ccSuffix = creditCardType.Value;
                }
            }

            if ( string.IsNullOrWhiteSpace( ccSuffix ) && currencyType != null )
            {
                ccSuffix = currencyType.Value;
            }

            string batchName = namePrefix.Trim() + ( string.IsNullOrWhiteSpace( ccSuffix ) ? "" : " " + ccSuffix );

            FinancialBatch batch = null;

            // If a list of batches was passed, search those first
            if ( batches != null )
            {
                batch = batches
                    .Where( b =>
                        b.Status == BatchStatus.Open &&
                        b.BatchStartDateTime <= transactionDate &&
                        b.BatchEndDateTime > transactionDate &&
                        b.Name == batchName )
                    .OrderByDescending( b => b.BatchStartDateTime )
                    .FirstOrDefault();

                if ( batch != null )
                {
                    return batch;
                }
            }

            // If batch was not found in existing list, search database
            batch = Queryable()
                .Where( b =>
                    b.Status == BatchStatus.Open &&
                    b.BatchStartDateTime <= transactionDate &&
                    b.BatchEndDateTime > transactionDate &&
                    b.Name == batchName )
                .OrderByDescending( b => b.BatchStartDateTime )
                .FirstOrDefault();

            // If still no batch, create a new one
            if ( batch == null )
            {
                batch = new FinancialBatch();
                batch.Guid = Guid.NewGuid();
                batch.Name = batchName;
                batch.Status = BatchStatus.Open;
                batch.BatchStartDateTime = transactionDate.Date.Add( batchTimeOffset );
                if ( batch.BatchStartDateTime > transactionDate )
                {
                    batch.BatchStartDateTime.Value.AddDays( -1 );
                }

                batch.BatchEndDateTime = batch.BatchStartDateTime.Value.AddDays( 1 );
                batch.ControlAmount = 0;
                Add( batch );
            }

            // Add the batch to the list
            if ( batches != null )
            {
                batches.Add( batch );
            }

            return batch;
        }
Esempio n. 22
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(EntityState entityState, Rock.Data.DbContext dbContext)
        {
            AttributeCache.UpdateCachedEntity(this.Id, entityState);
            AttributeCache.UpdateCacheEntityAttributes(this, entityState);

            int?   entityTypeId;
            string entityTypeQualifierColumn;
            string entityTypeQualifierValue;

            if (entityState == EntityState.Deleted)
            {
                entityTypeId = originalEntityTypeId;
                entityTypeQualifierColumn = originalEntityTypeQualifierColumn;
                entityTypeQualifierValue  = originalEntityTypeQualifierValue;
            }
            else
            {
                entityTypeId = this.EntityTypeId;
                entityTypeQualifierColumn = this.EntityTypeQualifierColumn;
                entityTypeQualifierValue  = this.EntityTypeQualifierValue;
            }

            if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && string.IsNullOrEmpty(entityTypeQualifierColumn) && string.IsNullOrEmpty(entityTypeQualifierValue))
            {
                GlobalAttributesCache.Remove();
            }

            if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && entityTypeQualifierColumn == Attribute.SYSTEM_SETTING_QUALIFIER && string.IsNullOrEmpty(entityTypeQualifierValue))
            {
                if (entityState != EntityState.Modified)
                {
                    // if a SystemSettings was Added or Removed, flush the SystemSettings cache (if it was only modified, it'll will point to the updated AttributeCache value)
                    Rock.Web.SystemSettings.Remove();
                }
            }

            if (entityTypeId.HasValue)
            {
                if (entityTypeId == EntityTypeCache.GetId <Block>())
                {
                    // Update BlockTypes/Blocks that reference this attribute
                    if (entityTypeQualifierColumn.Equals("BlockTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?blockTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (blockTypeId.HasValue)
                        {
                            BlockTypeCache.FlushItem(blockTypeId.Value);

                            foreach (var blockId in new BlockService(dbContext as RockContext).GetByBlockTypeId(blockTypeId.Value).Select(a => a.Id).ToList())
                            {
                                BlockCache.FlushItem(blockId);
                            }
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <DefinedValue>())
                {
                    // Update DefinedTypes/DefinedValues that reference this attribute
                    if (entityTypeQualifierColumn.Equals("DefinedTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?definedTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (definedTypeId.HasValue)
                        {
                            DefinedTypeCache.FlushItem(definedTypeId.Value);

                            foreach (var definedValueId in new DefinedValueService(dbContext as RockContext).GetByDefinedTypeId(definedTypeId.Value).Select(a => a.Id).ToList())
                            {
                                DefinedValueCache.FlushItem(definedValueId);
                            }
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <WorkflowActivityType>())
                {
                    if (entityTypeQualifierColumn.Equals("ActivityTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?activityTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (activityTypeId.HasValue)
                        {
                            WorkflowActivityTypeCache.FlushItem(activityTypeId.Value);
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <GroupType>())
                {
                    if (entityTypeQualifierColumn.Equals("Id", StringComparison.OrdinalIgnoreCase))
                    {
                        int?groupTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (groupTypeId.HasValue)
                        {
                            GroupTypeCache.FlushItem(groupTypeId.Value);
                        }
                    }
                    else if (entityTypeQualifierColumn.Equals("GroupTypePurposeValueId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?groupTypePurposeValueId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (groupTypePurposeValueId.HasValue)
                        {
                            foreach (var groupTypeId in GroupTypeCache.All().Where(a => a.GroupTypePurposeValueId == groupTypePurposeValueId.Value).Select(a => a.Id).ToList())
                            {
                                GroupTypeCache.FlushItem(groupTypeId);
                            }
                        }
                    }
                }
                else if (entityTypeId.HasValue)
                {
                    // some other EntityType. If it the EntityType has a CacheItem associated with it, clear out all the CachedItems of that type to ensure they have a clean read of the Attributes that were Added, Changed or Removed
                    EntityTypeCache entityType = EntityTypeCache.Get(entityTypeId.Value, dbContext as RockContext);

                    if (entityType?.HasEntityCache() == true)
                    {
                        entityType.ClearCachedItems();
                    }
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Checks the settings.
        /// </summary>
        /// <returns></returns>
        private bool CheckSettings()
        {
            _rockContext = _rockContext ?? new RockContext();

            _mode = GetAttributeValue( "Mode" );

            _autoFill = GetAttributeValue( "AutoFillForm" ).AsBoolean();

            tbEmail.Required = _autoFill;

            string registerButtonText = GetAttributeValue( "RegisterButtonAltText" );
            if ( string.IsNullOrWhiteSpace( registerButtonText ) )
            {
                registerButtonText = "Register";
            }
            btnRegister.Text = registerButtonText;

            var groupService = new GroupService( _rockContext );
            bool groupIsFromQryString = true;

            Guid? groupGuid = GetAttributeValue( "Group" ).AsGuidOrNull();
            if ( groupGuid.HasValue )
            {
                _group = groupService.Get( groupGuid.Value );
                groupIsFromQryString = false;
            }

            if ( _group == null )
            {
                groupGuid = PageParameter( "GroupGuid" ).AsGuidOrNull();
                if ( groupGuid.HasValue )
                {
                    _group = groupService.Get( groupGuid.Value );
                }
            }

            if ( _group == null )
            {
                int? groupId = PageParameter( "GroupId" ).AsIntegerOrNull();
                if ( groupId.HasValue )
                {
                    _group = groupService.Get( groupId.Value );
                }
            }

            if ( _group == null )
            {
                nbNotice.Heading = "Unknown Group";
                nbNotice.Text = "<p>This page requires a valid group id parameter, and there was not one provided.</p>";
                return false;
            }
            else
            {
                if ( groupIsFromQryString && ( _group.IsSecurityRole || _group.GroupType.Guid == Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) )
                {
                    nbNotice.Heading = "Invalid Group";
                    nbNotice.Text = "<p>The selected group is a security group and this block cannot be used to add people to a security group (unless configured for that specific group).</p>";
                    return false;
                }
                else
                {
                    _defaultGroupRole = _group.GroupType.DefaultGroupRole;
                }
            }

            _dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            if ( _dvcConnectionStatus == null )
            {
                nbNotice.Heading = "Invalid Connection Status";
                nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>";
                return false;
            }

            _dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );
            if ( _dvcRecordStatus == null )
            {
                nbNotice.Heading = "Invalid Record Status";
                nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>";
                return false;
            }

            _married = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid() );
            _homeAddressType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() );
            _familyType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() );
            _adultRole = _familyType.Roles.FirstOrDefault( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) );

            if ( _married == null || _homeAddressType == null || _familyType == null || _adultRole == null )
            {
                nbNotice.Heading = "Missing System Value";
                nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>";
                return false;
            }

            return true;
        }
        /// <summary>
        /// Puts the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="phoneNumber">The phone number.</param>
        public override void Put(int id, PhoneNumber phoneNumber)
        {
            SetProxyCreation(true);

            var rockContext   = (RockContext)Service.Context;
            var existingPhone = Service.Get(id);

            if (existingPhone != null)
            {
                var changes = new List <string>();

                History.EvaluateChange(changes, "Phone Type", DefinedValueCache.GetName(existingPhone.NumberTypeValueId), DefinedValueCache.GetName(phoneNumber.NumberTypeValueId));

                string oldPhoneNumber = existingPhone.NumberFormattedWithCountryCode;
                string newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                History.EvaluateChange(
                    changes,
                    string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)),
                    oldPhoneNumber,
                    newPhoneNumber);

                if (changes.Any())
                {
                    System.Web.HttpContext.Current.Items.Add("CurrentPerson", GetPerson());

                    int?modifiedByPersonAliasId = phoneNumber.ModifiedAuditValuesAlreadyUpdated ? phoneNumber.ModifiedByPersonAliasId : (int?)null;

                    HistoryService.SaveChanges(
                        rockContext,
                        typeof(Person),
                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                        phoneNumber.PersonId,
                        changes,
                        true,
                        modifiedByPersonAliasId);
                }
            }

            base.Put(id, phoneNumber);
        }
        protected void lbRegisterNext_Click( object sender, EventArgs e )
        {
            _dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            _dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );

            // create new person / family
            Person person = new Person();
            person.FirstName = tbFirstName.Text.Trim();
            person.LastName = tbLastName.Text.Trim();
            person.Email = tbEmail.Text.Trim();
            person.ConnectionStatusValueId = _dvcConnectionStatus.Id;
            person.RecordStatusValueId = _dvcRecordStatus.Id;
            person.Gender = Gender.Unknown;

            PersonService.SaveNewPerson( person, new RockContext(), this.CampusId, false );

            // set as selected giving unit
            this.SelectedGivingUnit = new GivingUnit( person.PrimaryAliasId.Value, person.LastName, person.FirstName );

            ShowAccountPanel();
        }
Esempio n. 26
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // get person
            int?personId = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            personId = new PersonAliasService(rockContext).Queryable()
                                       .Where(a => a.Guid.Equals(personAliasGuid))
                                       .Select(a => a.PersonId)
                                       .FirstOrDefault();
                            if (personId == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (personId == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // determine the phone type to edit
            DefinedValueCache phoneType = null;
            var phoneTypeAttributeValue = action.GetWorklowAttributeValue(GetAttributeValue(action, "PhoneTypeAttribute").AsGuid());

            if (phoneTypeAttributeValue != null)
            {
                phoneType = DefinedValueCache.Read(phoneTypeAttributeValue.AsGuid());
            }
            if (phoneType == null)
            {
                phoneType = DefinedValueCache.Read(GetAttributeValue(action, "PhoneType").AsGuid());
            }
            if (phoneType == null)
            {
                errorMessages.Add("The phone type to be updated was not selected.");
                return(false);
            }

            // get the ignore blank setting
            var ignoreBlanks = GetActionAttributeValue(action, "IgnoreBlankValues").AsBoolean(true);

            // get the new phone number value
            string phoneNumberValue     = GetAttributeValue(action, "PhoneNumber");
            Guid?  phoneNumberValueGuid = phoneNumberValue.AsGuidOrNull();

            if (phoneNumberValueGuid.HasValue)
            {
                phoneNumberValue = action.GetWorklowAttributeValue(phoneNumberValueGuid.Value);
            }
            else
            {
                phoneNumberValue = phoneNumberValue.ResolveMergeFields(GetMergeFields(action));
            }
            phoneNumberValue = PhoneNumber.CleanNumber(phoneNumberValue);

            // gets value indicating if phone number is unlisted
            string unlistedValue     = GetAttributeValue(action, "Unlisted");
            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();

            if (unlistedValueGuid.HasValue)
            {
                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
            }
            else
            {
                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?unlisted = unlistedValue.AsBooleanOrNull();

            // gets value indicating if messaging should be enabled for phone number
            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();

            if (smsEnabledValueGuid.HasValue)
            {
                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
            }
            else
            {
                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?smsEnabled = smsEnabledValue.AsBooleanOrNull();

            bool updated            = false;
            var  phoneNumberService = new PhoneNumberService(rockContext);
            var  phoneNumber        = phoneNumberService.Queryable()
                                      .Where(n =>
                                             n.PersonId == personId.Value &&
                                             n.NumberTypeValueId == phoneType.Id)
                                      .FirstOrDefault();
            string oldValue = string.Empty;

            if (phoneNumber == null)
            {
                phoneNumber = new PhoneNumber {
                    NumberTypeValueId = phoneType.Id, PersonId = personId.Value
                };
                phoneNumberService.Add(phoneNumber);
                updated = true;
            }
            else
            {
                oldValue = phoneNumber.NumberFormattedWithCountryCode;
            }

            if (!string.IsNullOrWhiteSpace(phoneNumberValue) || !ignoreBlanks)
            {
                updated            = updated || phoneNumber.Number != phoneNumberValue;
                phoneNumber.Number = phoneNumberValue;
            }
            if (unlisted.HasValue)
            {
                updated = updated || phoneNumber.IsUnlisted != unlisted.Value;
                phoneNumber.IsUnlisted = unlisted.Value;
            }
            if (smsEnabled.HasValue)
            {
                updated = updated || phoneNumber.IsMessagingEnabled != smsEnabled.Value;
                phoneNumber.IsMessagingEnabled = smsEnabled.Value;
            }

            if (updated)
            {
                if (oldValue != phoneNumber.NumberFormattedWithCountryCode)
                {
                    var changes = new List <string> {
                        string.Format("<em>(Phone was updated by the '{0}' workflow)</em>", action.ActionTypeCache.ActivityType.WorkflowType.Name)
                    };
                    HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), personId.Value, changes, false);
                }

                rockContext.SaveChanges();

                if (action.Activity != null && action.Activity.Workflow != null)
                {
                    var workflowType = action.Activity.Workflow.WorkflowTypeCache;
                    if (workflowType != null && workflowType.LoggingLevel == WorkflowLoggingLevel.Action)
                    {
                        var person = new PersonService(rockContext).Get(personId.Value);
                        action.AddLogEntry(string.Format("Updated {0} phone for {1} to {2}.", phoneType.Value, person.FullName, phoneNumber.NumberFormattedWithCountryCode));
                    }
                }
            }

            return(true);
        }
Esempio n. 27
0
        /// <summary>
        /// Checks the settings.
        /// </summary>
        /// <returns></returns>
        private bool CheckSettings()
        {
            _rockContext = _rockContext ?? new RockContext();

            _mode = GetAttributeValue( "Mode" );

            _autoFill = GetAttributeValue( "AutoFillForm" ).AsBoolean();

            tbEmail.Required = _autoFill;

            string registerButtonText = GetAttributeValue( "RegisterButtonAltText" );
            if ( string.IsNullOrWhiteSpace( registerButtonText ) )
            {
                registerButtonText = "Register";
            }
            btnRegister.Text = registerButtonText;

            int groupId = PageParameter( "GroupId" ).AsInteger();
            _group = new GroupService( _rockContext )
                .Queryable( "GroupType.DefaultGroupRole" ).AsNoTracking()
                .FirstOrDefault( g => g.Id == groupId );
            if ( _group == null )
            {
                nbNotice.Heading = "Unknown Group";
                nbNotice.Text = "<p>This page requires a valid group id parameter, and there was not one provided.</p>";
                return false;
            }
            else
            {
                _defaultGroupRole = _group.GroupType.DefaultGroupRole;
            }

            _dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            if ( _dvcConnectionStatus == null )
            {
                nbNotice.Heading = "Invalid Connection Status";
                nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>";
                return false;
            }

            _dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );
            if ( _dvcRecordStatus == null )
            {
                nbNotice.Heading = "Invalid Record Status";
                nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>";
                return false;
            }

            _married = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid() );
            _homeAddressType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() );
            _familyType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() );
            _adultRole = _familyType.Roles.FirstOrDefault( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) );

            if ( _married == null || _homeAddressType == null || _familyType == null || _adultRole == null )
            {
                nbNotice.Heading = "Missing System Value";
                nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>";
                return false;
            }

            return true;
        }
        public void ProcessRequest(HttpContext context)
        {
            request  = context.Request;
            response = context.Response;

            RockContext rockContext = new RockContext();

            if (request.HttpMethod != "GET" && request.HttpMethod != "HEAD")
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 405;
                response.Headers.Add("Allow", "GET");
                response.Write("Invalid request method.");
                return;
            }

            if (request.QueryString["ChannelId"] == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("A ChannelId is required.");
                return;
            }

            int?channelId = request.QueryString["ChannelId"].AsIntegerOrNull();

            if (channelId == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid channel id.");
                return;
            }

            ContentChannel channel = new ContentChannelService(rockContext).Queryable("ContentChannelType").FirstOrDefault(c => c.Id == channelId.Value);

            if (channel == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 404;
                response.Write("Channel does not exist.");
                return;
            }

            if (!channel.EnableRss)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 403;
                response.Write("RSS is not enabled for this channel.");
                return;
            }

            DefinedValueCache dvRssTemplate = null;

            if (request.QueryString["TemplateId"] != null)
            {
                int?templateDefinedValueId = request.QueryString["TemplateId"].AsIntegerOrNull();

                if (templateDefinedValueId == null)
                {
                    response.TrySkipIisCustomErrors = true;
                    response.StatusCode             = 400;
                    response.Write("Invalid template id.");
                    return;
                }

                dvRssTemplate = DefinedValueCache.Get(templateDefinedValueId.Value);
            }

            if (dvRssTemplate == null)
            {
                dvRssTemplate = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL);
            }

            if (dvRssTemplate.DefinedType.Guid != new Guid(Rock.SystemGuid.DefinedType.LAVA_TEMPLATES))
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid template id.");
                return;
            }

            string rssTemplate = dvRssTemplate.GetAttributeValue("Template");

            if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType")))
            {
                response.ContentType = "application/rss+xml";
            }
            else
            {
                response.ContentType = dvRssTemplate.GetAttributeValue("MimeType");
            }

            if (request.HttpMethod == "HEAD")
            {
                response.StatusCode = 200;
                return;
            }

            // load merge fields
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeFields.Add("Channel", channel);

            Dictionary <string, object> requestObjects = new Dictionary <string, object>();

            requestObjects.Add("Scheme", request.Url.Scheme);
            requestObjects.Add("Host", WebRequestHelper.GetHostNameFromRequest(context));
            requestObjects.Add("Authority", request.Url.Authority);
            requestObjects.Add("LocalPath", request.Url.LocalPath);
            requestObjects.Add("AbsoluteUri", request.Url.AbsoluteUri);
            requestObjects.Add("AbsolutePath", request.Url.AbsolutePath);
            requestObjects.Add("Port", request.Url.Port);
            requestObjects.Add("Query", request.Url.Query);
            requestObjects.Add("OriginalString", request.Url.OriginalString);

            mergeFields.Add("Request", requestObjects);

            // check for new rss item limit
            if (request.QueryString["Count"] != null)
            {
                int.TryParse(request.QueryString["Count"], out rssItemLimit);
            }

            // get channel items
            ContentChannelItemService contentService = new ContentChannelItemService(rockContext);

            var content = contentService.Queryable("ContentChannelType")
                          .Where(c =>
                                 c.ContentChannelId == channel.Id &&
                                 (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.ContentChannelType.DisableStatus || c.ContentChannel.RequiresApproval == false) &&
                                 c.StartDateTime <= RockDateTime.Now);

            if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
            {
                if (channel.ContentChannelType.IncludeTime)
                {
                    content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime >= RockDateTime.Now);
                }
                else
                {
                    content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime > RockDateTime.Today);
                }
            }

            if (channel.ItemsManuallyOrdered)
            {
                content = content.OrderBy(c => c.Order);
            }
            else
            {
                content = content.OrderByDescending(c => c.StartDateTime);
            }

            content = content.Take(rssItemLimit);

            foreach (var item in content)
            {
                item.Content = item.Content.ResolveMergeFields(mergeFields);

                // resolve any relative links
                var    globalAttributes = GlobalAttributesCache.Get();
                string publicAppRoot    = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                item.Content = item.Content.Replace(@" src=""/", @" src=""" + publicAppRoot);
                item.Content = item.Content.Replace(@" href=""/", @" href=""" + publicAppRoot);

                // get item attributes and add them as elements to the feed
                item.LoadAttributes(rockContext);
                foreach (var attributeValue in item.AttributeValues)
                {
                    attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(mergeFields);
                }
            }

            mergeFields.Add("Items", content);

            mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber());

            response.Write(rssTemplate.ResolveMergeFields(mergeFields));
        }
        private void BindGrid()
        {
            string type = PageParameter( "SearchType" );
            string term = PageParameter( "SearchTerm" );

            if ( !String.IsNullOrWhiteSpace( type ) && !String.IsNullOrWhiteSpace( term ) )
            {
                using ( var rockContext = new RockContext() )
                {
                    var personService = new PersonService( rockContext );
                    IQueryable<Person> people = null;

                    switch ( type.ToLower() )
                    {
                        case ( "name" ):
                            {
                                bool allowFirstNameOnly = false;
                                if ( !bool.TryParse( PageParameter( "allowFirstNameOnly" ), out allowFirstNameOnly ) )
                                {
                                    allowFirstNameOnly = false;
                                }
                                people = personService.GetByFullName( term, allowFirstNameOnly, true );
                                break;
                            }
                        case ( "phone" ):
                            {
                                var phoneService = new PhoneNumberService( rockContext );
                                var personIds = phoneService.GetPersonIdsByNumber( term );
                                people = personService.Queryable().Where( p => personIds.Contains( p.Id ) );
                                break;
                            }
                        case ( "address" ):
                            {
                                var groupMemberService = new GroupMemberService( rockContext );
                                var personIds2 = groupMemberService.GetPersonIdsByHomeAddress( term );
                                people = personService.Queryable().Where( p => personIds2.Contains( p.Id ) );
                                break;
                            }
                        case ( "email" ):
                            {
                                people = personService.Queryable().Where( p => p.Email.Contains( term ) );
                                break;
                            }
                    }

                    SortProperty sortProperty = gPeople.SortProperty;
                    if ( sortProperty != null )
                    {
                        people = people.Sort( sortProperty );
                    }
                    else
                    {
                        people = people.OrderBy( p => p.LastName ).ThenBy( p => p.FirstName );
                    }

                    var personList = people.ToList();

                    if ( personList.Count == 1 )
                    {
                        Response.Redirect( string.Format( "~/Person/{0}", personList[0].Id ), false );
                        Context.ApplicationInstance.CompleteRequest();
                    }
                    else
                    {
                        if ( type.ToLower() == "name" )
                        {
                            var similiarNames = personService.GetSimiliarNames( term,
                                personList.Select( p => p.Id ).ToList(), true );
                            if ( similiarNames.Any() )
                            {
                                var hyperlinks = new List<string>();
                                foreach ( string name in similiarNames.Distinct() )
                                {
                                    var pageRef = CurrentPageReference;
                                    pageRef.Parameters["SearchTerm"] = name;
                                    hyperlinks.Add( string.Format( "<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name ) );
                                }
                                string altNames = string.Join( ", ", hyperlinks );
                                nbNotice.Text = string.Format( "Other Possible Matches: {0}", altNames );
                                nbNotice.Visible = true;
                            }
                        }

                        _inactiveStatus = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE );

                        gPeople.DataSource = personList;
                        gPeople.DataBind();
                    }
                }
            }
        }
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid()
        {
            if ( _group != null )
            {
                pnlGroupMembers.Visible = true;

                lHeading.Text = string.Format( "{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize() );

                if ( _group.GroupType.Roles.Any() )
                {
                    nbRoleWarning.Visible = false;
                    rFilter.Visible = true;
                    gGroupMembers.Visible = true;

                    var rockContext = new RockContext();

                    GroupMemberService groupMemberService = new GroupMemberService( rockContext );
                    var qry = groupMemberService.Queryable( "Person,GroupRole", true )
                        .Where( m => m.GroupId == _group.Id );

                    // Filter by First Name
                    string firstName = tbFirstName.Text;
                    if ( !string.IsNullOrWhiteSpace( firstName ) )
                    {
                        qry = qry.Where( m => m.Person.FirstName.StartsWith( firstName ) );
                    }

                    // Filter by Last Name
                    string lastName = tbLastName.Text;
                    if ( !string.IsNullOrWhiteSpace( lastName ) )
                    {
                        qry = qry.Where( m => m.Person.LastName.StartsWith( lastName ) );
                    }

                    // Filter by role
                    var validGroupTypeRoles = _group.GroupType.Roles.Select( r => r.Id ).ToList();
                    var roles = new List<int>();
                    foreach ( string role in cblRole.SelectedValues )
                    {
                        if ( !string.IsNullOrWhiteSpace( role ) )
                        {
                            int roleId = int.MinValue;
                            if ( int.TryParse( role, out roleId ) && validGroupTypeRoles.Contains( roleId ) )
                            {
                                roles.Add( roleId );
                            }
                        }
                    }
                    if ( roles.Any() )
                    {
                        qry = qry.Where( m => roles.Contains( m.GroupRoleId ) );
                    }

                    // Filter by Status
                    var statuses = new List<GroupMemberStatus>();
                    foreach ( string status in cblStatus.SelectedValues )
                    {
                        if ( !string.IsNullOrWhiteSpace( status ) )
                        {
                            statuses.Add( status.ConvertToEnum<GroupMemberStatus>() );
                        }
                    }
                    if ( statuses.Any() )
                    {
                        qry = qry.Where( m => statuses.Contains( m.GroupMemberStatus ) );
                    }

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

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

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

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

                    _inactiveStatus = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE );

                    SortProperty sortProperty = gGroupMembers.SortProperty;

                    List<GroupMember> groupMembers = null;

                    if ( sortProperty != null )
                    {
                        groupMembers = qry.Sort( sortProperty ).ToList();
                    }
                    else
                    {
                        groupMembers = qry.OrderBy( a => a.GroupRole.Order ).ThenBy( a => a.Person.LastName ).ThenBy( a => a.Person.FirstName ).ToList();
                    }

                    // Since we're not binding to actual group member list, but are using AttributeField columns,
                    // we need to save the workflows into the grid's object list
                    gGroupMembers.ObjectList = new Dictionary<string, object>();
                    groupMembers.ForEach( m => gGroupMembers.ObjectList.Add( m.Id.ToString(), m ) );

                    gGroupMembers.DataSource = groupMembers.Select( m => new
                    {
                        m.Id,
                        m.Guid,
                        m.PersonId,
                        Name = m.Person.NickName + " " + m.Person.LastName,
                        GroupRole = m.GroupRole.Name,
                        m.GroupMemberStatus
                    } ).ToList();

                    gGroupMembers.DataBind();
                }
                else
                {
                    nbRoleWarning.Text = string.Format(
                        "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.",
                        _group.GroupType.GroupMemberTerm.Pluralize(),
                        _group.GroupType.GroupTerm,
                        _group.GroupType.Name );

                    nbRoleWarning.Visible = true;
                    rFilter.Visible = false;
                    gGroupMembers.Visible = false;
                }
            }
            else
            {
                pnlGroupMembers.Visible = false;
            }
        }
Esempio n. 31
0
        private void BindGrid()
        {
            var birthDateCol = gPeople.ColumnsOfType<DateField>().First( c => c.DataField == "BirthDate" );
            birthDateCol.Visible = GetAttributeValue( "ShowBirthdate" ).AsBoolean();

            string type = PageParameter( "SearchType" );
            string term = PageParameter( "SearchTerm" );

            if ( !string.IsNullOrWhiteSpace( type ) && !string.IsNullOrWhiteSpace( term ) )
            {
                term = term.Trim();
                type = type.Trim();
                var rockContext = new RockContext();

                var personService = new PersonService( rockContext );
                IQueryable<Person> people = null;

                switch ( type.ToLower() )
                {
                    case ( "name" ):
                        {
                            bool allowFirstNameOnly = false;
                            if ( !bool.TryParse( PageParameter( "allowFirstNameOnly" ), out allowFirstNameOnly ) )
                            {
                                allowFirstNameOnly = false;
                            }
                            people = personService.GetByFullName( term, allowFirstNameOnly, true );
                            break;
                        }
                    case ( "phone" ):
                        {
                            var phoneService = new PhoneNumberService( rockContext );
                            var personIds = phoneService.GetPersonIdsByNumber( term );
                            people = personService.Queryable().Where( p => personIds.Contains( p.Id ) );
                            break;
                        }
                    case ( "address" ):
                        {
                            var groupMemberService = new GroupMemberService( rockContext );
                            var personIds2 = groupMemberService.GetPersonIdsByHomeAddress( term );
                            people = personService.Queryable().Where( p => personIds2.Contains( p.Id ) );
                            break;
                        }
                    case ( "email" ):
                        {
                            people = personService.Queryable().Where( p => p.Email.Contains( term ) );
                            break;
                        }
                }

                var personIdList = people.Select( p => p.Id ).ToList();

                people = personService.Queryable(true).Where( p => personIdList.Contains( p.Id ) );

                SortProperty sortProperty = gPeople.SortProperty;
                if ( sortProperty != null )
                {
                    people = people.Sort( sortProperty );
                }
                else
                {
                    people = people.OrderBy( p => p.LastName ).ThenBy( p => p.FirstName );
                }

                Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );
                Guid homeAddressTypeGuid = new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME );

                var personList = people.Select( p => new PersonSearchResult
                {
                    Id = p.Id,
                    FirstName = p.FirstName,
                    NickName = p.NickName,
                    LastName = p.LastName,
                    BirthDate = p.BirthDate,
                    BirthYear = p.BirthYear,
                    BirthMonth = p.BirthMonth,
                    BirthDay = p.BirthDay,
                    ConnectionStatusValueId = p.ConnectionStatusValueId,
                    RecordStatusValueId = p.RecordStatusValueId,
                    RecordTypeValueId = p.RecordTypeValueId,
                    SuffixValueId = p.SuffixValueId,
                    IsDeceased = p.IsDeceased,
                    Email = p.Email,
                    Gender = p.Gender,
                    PhotoId = p.PhotoId,
                    CampusIds = p.Members
                        .Where( m =>
                            m.Group.GroupType.Guid.Equals( familyGuid ) &&
                            m.Group.CampusId.HasValue )
                        .Select( m => m.Group.CampusId.Value )
                        .ToList(),
                    HomeAddresses = p.Members
                        .Where( m => m.Group.GroupType.Guid == familyGuid )
                        .SelectMany( m => m.Group.GroupLocations )
                        .Where( gl => gl.GroupLocationTypeValue.Guid.Equals( homeAddressTypeGuid ) )
                        .Select( gl => gl.Location )
                } ).ToList();

                if ( personList.Count == 1 )
                {
                    Response.Redirect( string.Format( "~/Person/{0}", personList[0].Id ), false );
                    Context.ApplicationInstance.CompleteRequest();
                }
                else
                {
                    if ( type.ToLower() == "name" )
                    {
                        var similarNames = personService.GetSimilarNames( term,
                            personList.Select( p => p.Id ).ToList(), true );
                        if ( similarNames.Any() )
                        {
                            var hyperlinks = new List<string>();
                            foreach ( string name in similarNames.Distinct() )
                            {
                                var pageRef = CurrentPageReference;
                                pageRef.Parameters["SearchTerm"] = name;
                                hyperlinks.Add( string.Format( "<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name ) );
                            }
                            string altNames = string.Join( ", ", hyperlinks );
                            nbNotice.Text = string.Format( "Other Possible Matches: {0}", altNames );
                            nbNotice.Visible = true;
                        }
                    }

                    _inactiveStatus = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE );
                    gPeople.EntityTypeId = EntityTypeCache.GetId<Person>();

                    gPeople.DataSource = personList;
                    gPeople.DataBind();
                }
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid()
        {
            if ( _group != null )
            {
                pnlGroupMembers.Visible = true;

                lHeading.Text = string.Format( "{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize() );

                if ( _group.GroupType.Roles.Any() )
                {
                    nbRoleWarning.Visible = false;
                    rFilter.Visible = true;
                    gGroupMembers.Visible = true;

                    GroupMemberService groupMemberService = new GroupMemberService( new RockContext() );
                    var qry = groupMemberService.Queryable( "Person,GroupRole", true )
                        .Where( m => m.GroupId == _group.Id );

                    // Filter by First Name
                    string firstName = rFilter.GetUserPreference( "First Name" );
                    if ( !string.IsNullOrWhiteSpace( firstName ) )
                    {
                        qry = qry.Where( m => m.Person.FirstName.StartsWith( firstName ) );
                    }

                    // Filter by Last Name
                    string lastName = rFilter.GetUserPreference( "Last Name" );
                    if ( !string.IsNullOrWhiteSpace( lastName ) )
                    {
                        qry = qry.Where( m => m.Person.LastName.StartsWith( lastName ) );
                    }

                    // Filter by role
                    var roles = new List<int>();
                    foreach ( string role in rFilter.GetUserPreference( "Role" ).Split( ';' ) )
                    {
                        if ( !string.IsNullOrWhiteSpace( role ) )
                        {
                            int roleId = int.MinValue;
                            if ( int.TryParse( role, out roleId ) )
                            {
                                roles.Add( roleId );
                            }
                        }
                    }

                    if ( roles.Any() )
                    {
                        qry = qry.Where( m => roles.Contains( m.GroupRoleId ) );
                    }

                    // Filter by Sttus
                    var statuses = new List<GroupMemberStatus>();
                    foreach ( string status in rFilter.GetUserPreference( "Status" ).Split( ';' ) )
                    {
                        if ( !string.IsNullOrWhiteSpace( status ) )
                        {
                            statuses.Add( status.ConvertToEnum<GroupMemberStatus>() );
                        }
                    }

                    if ( statuses.Any() )
                    {
                        qry = qry.Where( m => statuses.Contains( m.GroupMemberStatus ) );
                    }

                    _inactiveStatus = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE );

                    SortProperty sortProperty = gGroupMembers.SortProperty;

                    if ( sortProperty != null )
                    {
                        gGroupMembers.DataSource = qry.Sort( sortProperty ).ToList();
                    }
                    else
                    {
                        gGroupMembers.DataSource = qry.OrderBy( a => a.GroupRole.Order ).ThenBy( a => a.Person.LastName ).ThenBy( a => a.Person.FirstName ).ToList();
                    }

                    gGroupMembers.DataBind();
                }
                else
                {
                    nbRoleWarning.Text = string.Format(
                        "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.",
                        _group.GroupType.GroupMemberTerm.Pluralize(),
                        _group.GroupType.GroupTerm,
                        _group.GroupType.Name );

                    nbRoleWarning.Visible = true;
                    rFilter.Visible = false;
                    gGroupMembers.Visible = false;
                }
            }
            else
            {
                pnlGroupMembers.Visible = false;
            }
        }
        // TODO: Add support for scanner
        private void SomeScannerSearch( DefinedValueCache searchType, string searchValue )
        {
            CurrentCheckInState.CheckIn.UserEnteredSearch = false;
            CurrentCheckInState.CheckIn.ConfirmSingleFamily = false;
            CurrentCheckInState.CheckIn.SearchType = searchType;
            CurrentCheckInState.CheckIn.SearchValue = searchValue;

            var errors = new List<string>();
            if ( ProcessActivity( "Family Search", out errors ) )
            {
                SaveState();
                NavigateToLinkedPage( "FamilySelectPage" );
            }
            else
            {
                string errorMsg = "<ul><li>" + errors.AsDelimited( "</li><li>" ) + "</li></ul>";
                maWarning.Show( errorMsg, Rock.Web.UI.Controls.ModalAlertType.Warning );
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            var homePhoneValueId   = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME).Id;
            var mobilePhoneValueId = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;
            var workPhoneValueId   = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK).Id;

            // get requester
            var requestPerson = new PersonAliasService(rockContext).Get(GetAttributeValue(action, "Person", true).AsGuid()).Person;

            if (requestPerson == null)
            {
                var errorMessage = "Could not determine the person for the request.";
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            // get case worker
            var caseWorker = new PersonAliasService(rockContext).Get(GetAttributeValue(action, "CaseWorker", true).AsGuid())?.Person;

            // get request status
            var statusValue = DefinedValueCache.Read(GetAttributeValue(action, "RequestStatus"));

            if (statusValue == null)
            {
                var errorMessage = "Invalid request status provided.";
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            // get request description
            var requestDescription = GetAttributeValue(action, "RequestDescription", true).ResolveMergeFields(mergeFields);

            if (string.IsNullOrWhiteSpace(requestDescription))
            {
                var errorMessage = "Request description is requried.";
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            // get government id
            var governmentId = GetAttributeValue(action, "GovernmentId", true).ResolveMergeFields(mergeFields);

            // get campus
            int?campusId = CampusCache.Read(GetAttributeValue(action, "Campus").AsGuid())?.Id;

            // create benevolence request
            BenevolenceRequestService benevolenceRequestService = new BenevolenceRequestService(rockContext);

            BenevolenceRequest request = new BenevolenceRequest();

            benevolenceRequestService.Add(request);

            request.RequestDateTime          = RockDateTime.Now;
            request.RequestText              = requestDescription;
            request.RequestedByPersonAliasId = requestPerson.PrimaryAliasId;
            request.FirstName    = requestPerson.NickName;
            request.LastName     = requestPerson.LastName;
            request.Email        = requestPerson.Email;
            request.LocationId   = requestPerson.GetHomeLocation()?.Id;
            request.GovernmentId = governmentId;

            if (campusId.HasValue)
            {
                request.CampusId = campusId.Value;
            }
            else
            {
                request.CampusId = requestPerson.GetCampus()?.Id;
            }

            var requestorPhoneNumbers = requestPerson.PhoneNumbers;

            if (requestorPhoneNumbers != null)
            {
                request.HomePhoneNumber = requestorPhoneNumbers.Where(p => p.NumberTypeValueId == homePhoneValueId).FirstOrDefault()?.NumberFormatted;
                request.CellPhoneNumber = requestorPhoneNumbers.Where(p => p.NumberTypeValueId == mobilePhoneValueId).FirstOrDefault()?.NumberFormatted;
                request.WorkPhoneNumber = requestorPhoneNumbers.Where(p => p.NumberTypeValueId == workPhoneValueId).FirstOrDefault()?.NumberFormatted;
            }

            if (caseWorker != null)
            {
                request.CaseWorkerPersonAliasId = caseWorker.PrimaryAliasId;
            }

            request.ConnectionStatusValueId = requestPerson.ConnectionStatusValueId;
            request.RequestStatusValueId    = statusValue.Id;

            rockContext.SaveChanges();

            SetWorkflowAttributeValue(action, "BenevolenceRequest", request.Guid);

            action.AddLogEntry($"Set 'Benevolence Request' attribute to '{request.Guid}'.");
            return(true);
        }