Ejemplo n.º 1
0
        /// <summary>
        /// Deletes all related notes.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void DeleteAllRelatedNotes(PrayerRequest prayerRequest, RockContext rockContext)
        {
            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());
            var noteService     = new NoteService(rockContext);
            var prayerComments  = noteService.Get(noteType.Id, prayerRequest.Id);

            foreach (Note prayerComment in prayerComments)
            {
                noteService.Delete(prayerComment);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 modalDetails_SaveClick(object sender, EventArgs e)
        {
            int noteTypeId = 0;

            if (hfIdValue.Value != string.Empty && !int.TryParse(hfIdValue.Value, out noteTypeId))
            {
                noteTypeId = 0;
            }

            var      rockContext = new RockContext();
            var      service     = new NoteTypeService(rockContext);
            NoteType noteType    = null;

            if (noteTypeId != 0)
            {
                noteType = service.Get(noteTypeId);
            }

            if (noteType == null)
            {
                var orders = service.Queryable()
                             .Where(t => t.EntityTypeId == (entityTypePicker.SelectedEntityTypeId ?? 0))
                             .Select(t => t.Order)
                             .ToList();

                noteType       = new NoteType();
                noteType.Order = orders.Any() ? orders.Max(t => t) + 1 : 0;
                service.Add(noteType);
            }

            noteType.Name         = tbName.Text;
            noteType.EntityTypeId = entityTypePicker.SelectedEntityTypeId ?? 0;
            noteType.EntityTypeQualifierColumn = "";
            noteType.EntityTypeQualifierValue  = "";
            noteType.UserSelectable            = cbUserSelectable.Checked;
            noteType.CssClass     = tbCssClass.Text;
            noteType.IconCssClass = tbIconCssClass.Text;

            if (noteType.IsValid)
            {
                rockContext.SaveChanges();

                NoteTypeCache.Flush(noteType.Id);
                NoteTypeCache.FlushEntityNoteTypes();

                hfIdValue.Value = string.Empty;
                modalDetails.Hide();

                BindFilter();
                BindGrid();
            }
        }
Ejemplo n.º 3
0
        private void DeleteAllRelatedNotes(PrayerRequest prayerRequest)
        {
            var noteTypeService = new NoteTypeService();
            var noteType        = noteTypeService.Get((int)_prayerRequestEntityTypeId, "Prayer Comment");
            var noteService     = new NoteService();
            var prayerComments  = noteService.Get(noteType.Id, prayerRequest.Id);

            foreach (Note prayerComment in prayerComments)
            {
                noteService.Delete(prayerComment, CurrentPersonId);
                noteService.Save(prayerComment, CurrentPersonId);
            }
        }
Ejemplo n.º 4
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)
        {
            int noteTypeId = hfNoteTypeId.Value.AsInteger();

            var      rockContext = new RockContext();
            var      service     = new NoteTypeService(rockContext);
            NoteType noteType    = null;

            if (noteTypeId != 0)
            {
                noteType = service.Get(noteTypeId);
            }

            int entityTypeId = epEntityType.SelectedEntityTypeId ?? 0;

            if (noteType == null)
            {
                int?maxNoteTypeOrderForEntity = service.Queryable().Where(t => t.EntityTypeId == entityTypeId).Max(a => ( int? )a.Order);

                noteType       = new NoteType();
                noteType.Order = (maxNoteTypeOrderForEntity ?? 0) + 1;
                service.Add(noteType);
            }

            noteType.Name         = tbName.Text;
            noteType.EntityTypeId = entityTypeId;
            noteType.EntityTypeQualifierColumn = string.Empty;
            noteType.EntityTypeQualifierValue  = string.Empty;

            noteType.IconCssClass    = tbIconCssClass.Text;
            noteType.BackgroundColor = cpBackgroundColor.Text;
            noteType.FontColor       = cpFontColor.Text;
            noteType.BorderColor     = cpBorderColor.Text;

            noteType.UserSelectable            = cbUserSelectable.Checked;
            noteType.RequiresApprovals         = cbRequiresApprovals.Checked;
            noteType.SendApprovalNotifications = cbSendApprovalNotifications.Checked;
            noteType.AllowsWatching            = cbAllowsWatching.Checked;
            noteType.AutoWatchAuthors          = cbAutoWatchAuthors.Checked;

            noteType.AllowsReplies       = cbAllowsReplies.Checked;
            noteType.MaxReplyDepth       = nbMaxReplyDepth.Text.AsIntegerOrNull();
            noteType.ApprovalUrlTemplate = ceApprovalUrlTemplate.Text;

            if (noteType.IsValid)
            {
                rockContext.SaveChanges();
            }

            NavigateToParentPage();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 modalDetails_SaveClick( object sender, EventArgs e )
        {
            int noteTypeId = 0;
            if ( hfIdValue.Value != string.Empty && !int.TryParse( hfIdValue.Value, out noteTypeId ) )
            {
                noteTypeId = 0;
            }

            var rockContext = new RockContext();
            var service = new NoteTypeService( rockContext );
            NoteType noteType = null;

            if ( noteTypeId != 0 )
            {
                noteType = service.Get( noteTypeId );
            }

            if ( noteType == null )
            {
                var orders = service.Queryable()
                    .Where( t => t.EntityTypeId == ( entityTypePicker.SelectedEntityTypeId ?? 0 ) )
                    .Select( t => t.Order )
                    .ToList();

                noteType = new NoteType();
                noteType.Order = orders.Any() ? orders.Max( t => t ) + 1 : 0;
                service.Add( noteType );
            }

            noteType.Name = tbName.Text;
            noteType.EntityTypeId = entityTypePicker.SelectedEntityTypeId ?? 0;
            noteType.EntityTypeQualifierColumn = "";
            noteType.EntityTypeQualifierValue = "";
            noteType.UserSelectable = cbUserSelectable.Checked;
            noteType.CssClass = tbCssClass.Text;
            noteType.IconCssClass = tbIconCssClass.Text;

            if ( noteType.IsValid )
            {
                rockContext.SaveChanges();

                NoteTypeCache.Flush( noteType.Id );
                NoteTypeCache.FlushEntityNoteTypes();

                hfIdValue.Value = string.Empty;
                modalDetails.Hide();

                BindFilter();
                BindGrid();
            }
        }
        /// <summary>
        /// Deletes all related notes.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void DeleteAllRelatedNotes(PrayerRequest prayerRequest)
        {
            var rockContext     = new RockContext();
            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get(_prayerRequestEntityTypeId.Value, "Prayer Comment");
            var noteService     = new NoteService(rockContext);
            var prayerComments  = noteService.Get(noteType.Id, prayerRequest.Id);

            foreach (Note prayerComment in prayerComments)
            {
                noteService.Delete(prayerComment);
                rockContext.SaveChanges();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var noteTypeService = new NoteTypeService();
            var noteType        = noteTypeService.Get((int)_prayerRequestEntityTypeId, "Prayer Comment");
            // TODO log exception if noteType is null

            var noteService    = new NoteService();
            var prayerComments = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // TODO: filter out comments that do not belong to the configured "category" grouping.
            //if ( _blockInstanceGroupCategoryId != All.Id )
            //{
            //    prayerComments = prayerComments.Where( c => c.CategoryId == _blockInstanceGroupCategoryId );
            //}

            // TODO: Filter by approved/unapproved
            //if ( rblApprovedFilter.SelectedValue == "unapproved" )
            //{
            //    prayerComments = prayerComments.Where( a => a.IsApproved == false || !a.IsApproved.HasValue );
            //}
            //else if ( rblApprovedFilter.SelectedValue == "approved" )
            //{
            //    prayerComments = prayerComments.Where( a => a.IsApproved == true );
            //}

            // Filter by EnteredDate
            if (dtDateRangeStartDate.SelectedDate != null)
            {
                prayerComments = prayerComments.Where(a => a.CreationDateTime >= dtDateRangeStartDate.SelectedDate);
            }
            if (dtDateRangeEndDate.SelectedDate != null)
            {
                prayerComments = prayerComments.Where(a => a.CreationDateTime <= dtDateRangeEndDate.SelectedDate);
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if (sortProperty != null)
            {
                gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy(n => n.CreationDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
Ejemplo n.º 8
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);

            var contextEntity = this.ContextEntity();

            if (contextEntity != null)
            {
                string noteTypeName = GetAttributeValue("NoteType");

                var rockContext = new RockContext();
                var service     = new NoteTypeService(rockContext);
                var noteType    = service.Get(contextEntity.TypeId, noteTypeName);

                // If a note type with the specified name does not exist for the context entity type, create one
                if (noteType == null)
                {
                    noteType              = new NoteType();
                    noteType.IsSystem     = false;
                    noteType.EntityTypeId = contextEntity.TypeId;
                    noteType.EntityTypeQualifierColumn = string.Empty;
                    noteType.EntityTypeQualifierValue  = string.Empty;
                    noteType.Name = noteTypeName;
                    service.Add(noteType);
                    rockContext.SaveChanges();
                }

                notesTimeline.NoteTypeId = noteType.Id;
                notesTimeline.EntityId   = contextEntity.Id;
                notesTimeline.Title      = GetAttributeValue("Heading");
                if (string.IsNullOrWhiteSpace(notesTimeline.Title))
                {
                    notesTimeline.Title = noteType.Name;
                }
                notesTimeline.TitleIconCssClass = GetAttributeValue("HeadingIcon");
                notesTimeline.Term                = GetAttributeValue("NoteTerm");
                notesTimeline.DisplayType         = GetAttributeValue("DisplayType") == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                notesTimeline.UsePersonIcon       = GetAttributeValue("UsePersonIcon").AsBoolean();
                notesTimeline.ShowAlertCheckBox   = GetAttributeValue("ShowAlertCheckbox").AsBoolean();
                notesTimeline.ShowPrivateCheckBox = GetAttributeValue("ShowPrivateCheckbox").AsBoolean();
                notesTimeline.ShowSecurityButton  = GetAttributeValue("ShowSecurityButton").AsBoolean();
                notesTimeline.AllowAnonymousEntry = GetAttributeValue("Allow Anonymous").AsBoolean();
                notesTimeline.AddAlwaysVisible    = GetAttributeValue("AddAlwaysVisible").AsBoolean();
                notesTimeline.SortDirection       = GetAttributeValue("DisplayOrder") == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get((int)_prayerRequestEntityTypeId, "Prayer Comment");
            // TODO log exception if noteType is null

            var noteService    = new NoteService(rockContext);
            var prayerComments = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // TODO: filter out comments that do not belong to the configured "category" grouping.
            //if ( _blockInstanceGroupCategoryId != All.Id )
            //{
            //    prayerComments = prayerComments.Where( c => c.CategoryId == _blockInstanceGroupCategoryId );
            //}

            // Filter by Date Range
            if (drpDateRange.LowerValue.HasValue)
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate);
            }

            if (drpDateRange.UpperValue.HasValue)
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays(1);
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate);
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if (sortProperty != null)
            {
                gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy(n => n.CreatedDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
Ejemplo n.º 10
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 );

            var contextEntity = this.ContextEntity();
            if ( contextEntity != null )
            {
                string noteTypeName = GetAttributeValue( "NoteType" );

                var rockContext = new RockContext();
                var service = new NoteTypeService( rockContext );
                var noteType = service.Get( contextEntity.TypeId, noteTypeName );

                // If a note type with the specified name does not exist for the context entity type, create one
                if ( noteType == null )
                {
                    noteType = new NoteType();
                    noteType.IsSystem = false;
                    noteType.EntityTypeId = contextEntity.TypeId;
                    noteType.EntityTypeQualifierColumn = string.Empty;
                    noteType.EntityTypeQualifierValue = string.Empty;
                    noteType.Name = noteTypeName;
                    service.Add( noteType );
                    rockContext.SaveChanges();
                }

                notesTimeline.NoteTypeId = noteType.Id;
                notesTimeline.EntityId = contextEntity.Id;
                notesTimeline.Title = GetAttributeValue( "Heading" );
                if ( string.IsNullOrWhiteSpace( notesTimeline.Title ) )
                {
                    notesTimeline.Title = noteType.Name;
                }
                notesTimeline.TitleIconCssClass = GetAttributeValue( "HeadingIcon" );
                notesTimeline.Term = GetAttributeValue( "NoteTerm" );
                notesTimeline.DisplayType = GetAttributeValue( "DisplayType" ) == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                notesTimeline.UsePersonIcon = GetAttributeValue( "UsePersonIcon" ).AsBoolean();
                notesTimeline.ShowAlertCheckBox = GetAttributeValue( "ShowAlertCheckbox" ).AsBoolean();
                notesTimeline.ShowPrivateCheckBox = GetAttributeValue( "ShowPrivateCheckbox" ).AsBoolean();
                notesTimeline.ShowSecurityButton = GetAttributeValue( "ShowSecurityButton" ).AsBoolean();
                notesTimeline.AllowAnonymousEntry = GetAttributeValue( "Allow Anonymous" ).AsBoolean();
                notesTimeline.AddAlwaysVisible = GetAttributeValue( "AddAlwaysVisible" ).AsBoolean();
                notesTimeline.SortDirection = GetAttributeValue( "DisplayOrder" ) == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
            }
        }
Ejemplo n.º 11
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);

            var contextEntity = this.ContextEntity();

            if (contextEntity != null)
            {
                upNotes.Visible = true;

                string noteTypeName = GetAttributeValue("NoteType");

                using (var rockContext = new RockContext())
                {
                    var service  = new NoteTypeService(rockContext);
                    var noteType = service.Get(contextEntity.TypeId, noteTypeName);

                    notesTimeline.NoteTypeId = noteType.Id;
                    notesTimeline.EntityId   = contextEntity.Id;
                    notesTimeline.Title      = GetAttributeValue("Heading");
                    if (string.IsNullOrWhiteSpace(notesTimeline.Title))
                    {
                        notesTimeline.Title = noteType.Name;
                    }
                    notesTimeline.TitleIconCssClass = GetAttributeValue("HeadingIcon");
                    notesTimeline.Term                = GetAttributeValue("NoteTerm");
                    notesTimeline.DisplayType         = GetAttributeValue("DisplayType") == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                    notesTimeline.UsePersonIcon       = GetAttributeValue("UsePersonIcon").AsBoolean();
                    notesTimeline.ShowAlertCheckBox   = GetAttributeValue("ShowAlertCheckbox").AsBoolean();
                    notesTimeline.ShowPrivateCheckBox = GetAttributeValue("ShowPrivateCheckbox").AsBoolean();
                    notesTimeline.ShowSecurityButton  = GetAttributeValue("ShowSecurityButton").AsBoolean();
                    notesTimeline.AllowAnonymousEntry = GetAttributeValue("Allow Anonymous").AsBoolean();
                    notesTimeline.AddAlwaysVisible    = GetAttributeValue("AddAlwaysVisible").AsBoolean();
                    notesTimeline.SortDirection       = GetAttributeValue("DisplayOrder") == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
                }
            }
            else
            {
                upNotes.Visible = false;
            }
        }
Ejemplo n.º 12
0
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue("NoteType");

            var service = new NoteTypeService();

            noteType = service.Get(contextEntity.TypeId, noteTypeName);

            // If a note type with the specified name does not exist for the context entity type, create one
            if (noteType == null)
            {
                noteType              = new NoteType();
                noteType.IsSystem     = false;
                noteType.EntityTypeId = contextEntity.TypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue  = string.Empty;
                noteType.Name = noteTypeName;
                service.Add(noteType, CurrentPersonId);
                service.Save(noteType, CurrentPersonId);
            }
        }
        /// <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 );

            var contextEntity = this.ContextEntity();
            if ( contextEntity != null )
            {
                upNotes.Visible = true;

                string noteTypeName = GetAttributeValue( "NoteType" );

                using ( var rockContext = new RockContext() )
                {
                    var service = new NoteTypeService( rockContext );
                    var noteType = service.Get( contextEntity.TypeId, noteTypeName );

                    notesTimeline.NoteTypeId = noteType.Id;
                    notesTimeline.EntityId = contextEntity.Id;
                    notesTimeline.Title = GetAttributeValue( "Heading" );
                    if ( string.IsNullOrWhiteSpace( notesTimeline.Title ) )
                    {
                        notesTimeline.Title = noteType.Name;
                    }
                    notesTimeline.TitleIconCssClass = GetAttributeValue( "HeadingIcon" );
                    notesTimeline.Term = GetAttributeValue( "NoteTerm" );
                    notesTimeline.DisplayType = GetAttributeValue( "DisplayType" ) == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                    notesTimeline.UsePersonIcon = GetAttributeValue( "UsePersonIcon" ).AsBoolean();
                    notesTimeline.ShowAlertCheckBox = GetAttributeValue( "ShowAlertCheckbox" ).AsBoolean();
                    notesTimeline.ShowPrivateCheckBox = GetAttributeValue( "ShowPrivateCheckbox" ).AsBoolean();
                    notesTimeline.ShowSecurityButton = GetAttributeValue( "ShowSecurityButton" ).AsBoolean();
                    notesTimeline.AllowAnonymousEntry = GetAttributeValue( "Allow Anonymous" ).AsBoolean();
                    notesTimeline.AddAlwaysVisible = GetAttributeValue( "AddAlwaysVisible" ).AsBoolean();
                    notesTimeline.SortDirection = GetAttributeValue( "DisplayOrder" ) == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
                }
            }
            else
            {
                upNotes.Visible = false;
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Sets the type of the note.
        /// </summary>
        private void SetNoteType()
        {
            var    entityTypeId = EntityTypeCache.Read(typeof(PrayerRequest)).Id;
            string noteTypeName = GetAttributeValue("NoteType");

            var rockContext = new RockContext();
            var service     = new NoteTypeService(rockContext);
            var noteType    = service.Get(entityTypeId, noteTypeName);

            // If a note type with the specified name does not exist, create one
            if (noteType == null)
            {
                noteType              = new NoteType();
                noteType.IsSystem     = false;
                noteType.EntityTypeId = entityTypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue  = string.Empty;
                noteType.Name = noteTypeName;
                service.Add(noteType);
                rockContext.SaveChanges();
            }

            NoteTypeId = noteType.Id;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Add a note on the given person's record.
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="noteTypeName"></param>
        /// <param name="noteText"></param>
        /// <param name="noteDate">(optional) The date the note was created</param>
        /// <param name="byPersonGuid">(optional) The guid of the person who created the note</param>
        /// <param name="rockContext"></param>
        private void AddNote( int personId, string noteTypeName, string noteText, string noteDate, string byPersonGuid, string isPrivate, RockContext rockContext )
        {
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( _personEntityTypeId, noteTypeName );
            // if the note type does not exist, create it
            if ( noteType == null )
            {
                noteType = new NoteType();
                noteType.IsSystem = false;
                noteType.EntityTypeId = _personEntityTypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue = string.Empty;
                noteType.Name = noteTypeName;
                service.Add( noteType );
                rockContext.SaveChanges();
            }

            // Find the person's alias
            int? createdByPersonAliasId = null;
            if ( byPersonGuid != null )
            {
                createdByPersonAliasId = _personCache[byPersonGuid.AsGuid()].PrimaryAliasId;
            }

            var noteService = new NoteService( rockContext );
            var note = new Note()
            {
                IsSystem = false,
                NoteTypeId = noteType.Id,
                EntityId = personId,
                Caption = string.Empty,
                CreatedByPersonAliasId = createdByPersonAliasId,
                Text = noteText,
                CreatedDateTime = DateTime.Parse( noteDate ?? RockDateTime.Now.ToString() )
            };

            noteService.Add( note );

            if ( isPrivate.AsBoolean() )
            {
                rockContext.SaveChanges( disablePrePostProcessing: true );
                note.MakePrivate( Rock.Security.Authorization.VIEW, _personCache[byPersonGuid.AsGuid()] );
            }
        }
        /// <summary>
        /// Deletes all related notes.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void DeleteAllRelatedNotes( PrayerRequest prayerRequest, RockContext rockContext )
        {
            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
            foreach ( Note prayerComment in prayerComments )
            {
                noteService.Delete( prayerComment );
            }

            rockContext.SaveChanges();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Handles the Delete event of the rGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGrid_Delete( object sender, RowEventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                var service = new NoteTypeService( rockContext );
                var noteType = service.Get( e.RowKeyId );
                if ( noteType != null )
                {
                    string errorMessage = string.Empty;
                    if ( service.CanDelete( noteType, out errorMessage ) )
                    {
                        int id = noteType.Id;

                        service.Delete( noteType );
                        rockContext.SaveChanges();

                        NoteTypeCache.Flush( id );
                        NoteTypeCache.FlushEntityNoteTypes();
                    }
                    else
                    {
                        nbMessage.Text = errorMessage;
                        nbMessage.Visible = true;
                    }
                }
            }

            BindFilter();
            BindGrid();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Add a note on the given person's record.
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="noteTypeName"></param>
        /// <param name="noteText"></param>
        /// <param name="noteDate">(optional) The date the note was created</param>
        /// <param name="byPersonGuid">(optional) The guid of the person who created the note</param>
        /// <param name="rockContext"></param>
        private void AddNote( int personId, string noteTypeName, string noteText, string noteDate, string byPersonGuid, string isPrivate, string isAlert, RockContext rockContext )
        {
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( _personEntityTypeId, noteTypeName );

            if ( noteType != null )
            {
                // Find the person's alias
                int? createdByPersonAliasId = null;
                if ( byPersonGuid != null )
                {
                    createdByPersonAliasId = _personCache[byPersonGuid.AsGuid()].PrimaryAliasId;
                }

                var noteService = new NoteService( rockContext );
                var note = new Note()
                {
                    IsSystem = false,
                    NoteTypeId = noteType.Id,
                    EntityId = personId,
                    Caption = string.Empty,
                    CreatedByPersonAliasId = createdByPersonAliasId,
                    Text = noteText,
                    IsAlert = isAlert.AsBoolean(),
                    IsPrivateNote = isPrivate.AsBoolean(),
                    CreatedDateTime = string.IsNullOrWhiteSpace( noteDate ) ? RockDateTime.Now : DateTime.Parse( noteDate, new CultureInfo( "en-US" ) )
                };

                noteService.Add( note );
            }
        }
        /// <summary>
        /// Add a note on the given person's record.
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="noteTypeName"></param>
        /// <param name="noteText"></param>
        /// <param name="noteDate">(optional) The date the note was created</param>
        /// <param name="byPersonGuid">(optional) The guid of the person who created the note</param>
        /// <param name="rockContext"></param>
        private void AddNote( int personId, string noteTypeName, string noteText, string noteDate, string byPersonGuid, string isPrivate, RockContext rockContext )
        {
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( _personEntityTypeId, noteTypeName );

            // Find the person's alias
            int? createdByPersonAliasId = null;
            if ( byPersonGuid != null )
            {
                createdByPersonAliasId = _personCache[byPersonGuid.AsGuid()].PrimaryAliasId;
            }

            var noteService = new NoteService( rockContext );
            var note = new Note()
            {
                IsSystem = false,
                NoteTypeId = noteType.Id,
                EntityId = personId,
                Caption = string.Empty,
                CreatedByPersonAliasId = createdByPersonAliasId,
                Text = noteText,
                CreatedDateTime = string.IsNullOrWhiteSpace( noteDate ) ? RockDateTime.Now : DateTime.Parse( noteDate, new CultureInfo( "en-US" ) )
            };

            noteService.Add( note );

            if ( isPrivate.AsBoolean() )
            {
                rockContext.SaveChanges( disablePrePostProcessing: true );
                note.MakePrivate( Rock.Security.Authorization.VIEW, _personCache[byPersonGuid.AsGuid()], rockContext );
            }
        }
        /// <summary>
        /// Cancels the specified scheduled transaction.
        /// </summary>
        /// <param name="scheduledTransaction">The scheduled transaction.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool Cancel( FinancialScheduledTransaction scheduledTransaction, out string errorMessages )
        {
            if ( scheduledTransaction.GatewayEntityType != null )
            {
                var gateway = Rock.Financial.GatewayContainer.GetComponent( scheduledTransaction.GatewayEntityType.Guid.ToString() );
                if ( gateway != null && gateway.IsActive )
                {
                    if ( gateway.CancelScheduledPayment( scheduledTransaction, out errorMessages ) )
                    {
                        var noteTypeService = new NoteTypeService( (RockContext)this.Context );
                        var noteType = noteTypeService.Get( scheduledTransaction.TypeId, "Note" );

                        var noteService = new NoteService( (RockContext)this.Context );
                        var note = new Note();
                        note.NoteTypeId = noteType.Id;
                        note.EntityId = scheduledTransaction.Id;
                        note.Caption = "Cancelled Transaction";
                        noteService.Add( note );

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            errorMessages = "Gateway is invalid or not active";
            return false;
        }
Ejemplo n.º 21
0
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue( "NoteType" );

            var service = new NoteTypeService();
            noteType = service.Get( contextEntity.TypeId, noteTypeName );

            // If a note type with the specified name does not exist for the context entity type, create one
            if ( noteType == null )
            {
                noteType = new NoteType();
                noteType.IsSystem = false;
                noteType.EntityTypeId = contextEntity.TypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue = string.Empty;
                noteType.Name = noteTypeName;
                service.Add( noteType, CurrentPersonId );
                service.Save( noteType, CurrentPersonId );
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Deletes all related notes.
 /// </summary>
 /// <param name="prayerRequest">The prayer request.</param>
 private void DeleteAllRelatedNotes( PrayerRequest prayerRequest )
 {
     var rockContext = new RockContext();
     var noteTypeService = new NoteTypeService( rockContext );
     var noteType = noteTypeService.Get( _prayerRequestEntityTypeId.Value, "Prayer Comment" );
     var noteService = new NoteService( rockContext );
     var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
     foreach ( Note prayerComment in prayerComments )
     {
         noteService.Delete( prayerComment );
         rockContext.SaveChanges();
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Handles the Click event of the btnComplete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnComplete_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var ids = Individuals.Select( i => i.PersonId ).ToList();

                var personEntityType = EntityTypeCache.Read( "Rock.Model.Person" );
                if ( personEntityType != null )
                {
                    int personEntityTypeId = personEntityType.Id;

                    var people = personService.Queryable().Where( p => ids.Contains( p.Id ) ).ToList();

                    #region Individual Details Updates

                    int? newTitleId = ddlTitle.SelectedValueAsInt();
                    int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                    int? newConnectionStatusId = ddlStatus.SelectedValueAsInt();
                    int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                    int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt();
                    string newInactiveReasonNote = tbInactiveReasonNote.Text;
                    Gender? newGender = ddlGender.SelectedValue.ConvertToEnumOrNull<Gender>();

                    int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();

                    DateTime? newGraduationDate = null;
                    if ( ypGraduation.SelectedYear.HasValue )
                    {
                        newGraduationDate = new DateTime( ypGraduation.SelectedYear.Value, _gradeTransitionDate.Month, _gradeTransitionDate.Day );
                    }

                    int? newCampusId = cpCampus.SelectedCampusId;
                    bool? newEmailActive = null;
                    if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) )
                    {
                        newEmailActive = ddlIsEmailActive.SelectedValue == "Active";
                    }
                    EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>();
                    string newEmailNote = tbEmailNote.Text;
                    bool? newFollow = null;
                    if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) )
                    {
                        newFollow = ddlFollow.SelectedValue == "Add";
                    }
                    int? newReviewReason = ddlReviewReason.SelectedValueAsInt();
                    string newSystemNote = tbSystemNote.Text;
                    string newReviewReasonNote = tbReviewReasonNote.Text;

                    var allChanges = new Dictionary<int, List<string>>();

                    foreach ( var person in people )
                    {
                        var changes = new List<string>();
                        allChanges.Add( person.Id, changes );

                        if ( newTitleId.HasValue )
                        {
                            History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                            person.TitleValueId = newTitleId;
                        }

                        if ( newSuffixId.HasValue )
                        {
                            History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                            person.SuffixValueId = newSuffixId;
                        }

                        if ( newConnectionStatusId.HasValue )
                        {
                            History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) );
                            person.ConnectionStatusValueId = newConnectionStatusId;
                        }

                        if ( newRecordStatusId.HasValue )
                        {
                            History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                            person.RecordStatusValueId = newRecordStatusId;
                        }

                        if ( newInactiveReasonId.HasValue )
                        {
                            History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newInactiveReasonId ) );
                            person.RecordStatusReasonValueId = newInactiveReasonId;
                        }

                        if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) )
                        {
                            History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, newInactiveReasonNote );
                            person.InactiveReasonNote = newInactiveReasonNote;
                        }

                        if ( newGender.HasValue )
                        {
                            History.EvaluateChange( changes, "Gender", person.Gender, newGender.Value );
                            person.Gender = newGender.Value;
                        }

                        if ( newMaritalStatusId.HasValue )
                        {
                            History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                            person.MaritalStatusValueId = newMaritalStatusId;
                        }

                        if ( newGraduationDate.HasValue )
                        {
                            History.EvaluateChange( changes, "Graduation Date", person.GraduationDate, newGraduationDate );
                            person.GraduationDate = newGraduationDate;
                        }

                        if ( newEmailActive.HasValue )
                        {
                            History.EvaluateChange( changes, "Email Is Active", person.IsEmailActive ?? true, newEmailActive.Value );
                            person.IsEmailActive = newEmailActive;
                        }

                        if ( newEmailPreference.HasValue )
                        {
                            History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                            person.EmailPreference = newEmailPreference.Value;
                        }

                        if ( !string.IsNullOrWhiteSpace( newEmailNote ) )
                        {
                            History.EvaluateChange( changes, "Email Note", person.EmailNote, newEmailNote );
                            person.EmailNote = newEmailNote;
                        }

                        if ( !string.IsNullOrWhiteSpace( newSystemNote ) )
                        {
                            History.EvaluateChange( changes, "System Note", person.SystemNote, newSystemNote );
                            person.SystemNote = newSystemNote;
                        }

                        if ( newReviewReason.HasValue )
                        {
                            History.EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( person.ReviewReasonValueId ), DefinedValueCache.GetName( newReviewReason ) );
                            person.ReviewReasonValueId = newReviewReason;
                        }

                        if ( !string.IsNullOrWhiteSpace( newReviewReasonNote ) )
                        {
                            History.EvaluateChange( changes, "Review Reason Note", person.ReviewReasonNote, newReviewReasonNote );
                            person.ReviewReasonNote = newReviewReasonNote;
                        }
                    }

                    // Update following
                    if ( newFollow.HasValue && CurrentPersonAlias != null )
                    {
                        var followingService = new FollowingService( rockContext );
                        if ( newFollow.Value )
                        {
                            var alreadyFollingIds = followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personEntityTypeId &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id )
                                .Select( f => f.EntityId )
                                .Distinct()
                                .ToList();
                            foreach ( int id in ids.Where( id => !alreadyFollingIds.Contains( id ) ) )
                            {
                                var following = new Following
                                {
                                    EntityTypeId = personEntityTypeId,
                                    EntityId = id,
                                    PersonAliasId = CurrentPersonAlias.Id
                                };
                                followingService.Add( following );
                            }
                        }
                        else
                        {
                            foreach ( var following in followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personEntityTypeId &&
                                    ids.Contains( f.EntityId ) &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id ) )
                            {
                                followingService.Delete( following );
                            }
                        }
                    }

                    rockContext.SaveChanges();

                    #endregion

                    #region Attributes

                    var selectedCategories = new List<CategoryCache>();
                    foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
                    {
                        var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                        if ( category != null )
                        {
                            selectedCategories.Add( category );
                        }
                    }

                    var attributes = new List<AttributeCache>();
                    var attributeValues = new Dictionary<int, string>();

                    int categoryIndex = 0;
                    foreach ( var category in selectedCategories.OrderBy( c => c.Name ) )
                    {
                        PanelWidget pw = null;
                        string controlId = "pwAttributes_" + category.Id.ToString();
                        if ( categoryIndex % 2 == 0 )
                        {
                            pw = phAttributesCol1.FindControl( controlId ) as PanelWidget;
                        }
                        else
                        {
                            pw = phAttributesCol2.FindControl( controlId) as PanelWidget;
                        }
                        categoryIndex++;

                        if ( pw != null )
                        {
                            var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                                .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                            foreach ( var attribute in orderedAttributeList )
                            {
                                if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                                {
                                    var attributeCache = AttributeCache.Read( attribute.Id );

                                    Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) );
                                    if ( attributeControl != null )
                                    {
                                        string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                        if (!string.IsNullOrWhiteSpace(newValue))
                                        {
                                            attributes.Add( attributeCache);
                                            attributeValues.Add( attributeCache.Id, newValue );
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (attributes.Any())
                    {
                        foreach ( var person in people )
                        {
                            person.LoadAttributes();
                            foreach ( var attribute in attributes )
                            {
                                string originalValue = person.GetAttributeValue( attribute.Key );
                                string newValue = attributeValues[attribute.Id];
                                if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                                {
                                    Rock.Attribute.Helper.SaveAttributeValue( person, attribute, newValue, rockContext );

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

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

                                    History.EvaluateChange( allChanges[person.Id], attribute.Name, formattedOriginalValue, formattedNewValue );
                                }
                            }
                        }
                    }

                    // Create the history records
                    foreach ( var changes in allChanges )
                    {
                        if ( changes.Value.Any() )
                        {
                            HistoryService.AddChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                changes.Key, changes.Value );
                        }
                    }
                    rockContext.SaveChanges();

                    #endregion

                    #region Add Note

                    if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null )
                    {
                        string text = tbNote.Text;
                        bool isAlert = cbIsAlert.Checked;
                        bool isPrivate = cbIsPrivate.Checked;

                        var noteTypeService = new NoteTypeService( rockContext );
                        var noteService = new NoteService( rockContext );

                        string noteTypeName = GetAttributeValue( "NoteType" );
                        var noteType = noteTypeService.Get( personEntityTypeId, noteTypeName );

                        if ( noteType != null )
                        {
                            var notes = new List<Note>();

                            foreach ( int id in ids )
                            {
                                var note = new Note();
                                note.IsSystem = false;
                                note.EntityId = id;
                                note.Caption = isPrivate ? "You - Personal Note" : string.Empty;
                                note.Text = tbNote.Text;
                                note.IsAlert = cbIsAlert.Checked;
                                note.NoteType = noteType;

                                notes.Add( note );
                                noteService.Add( note );
                            }

                            rockContext.WrapTransaction( () =>
                            {
                                rockContext.SaveChanges();
                                foreach( var note in notes)
                                {
                                    note.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                                    if ( isPrivate)
                                    {
                                        note.MakePrivate( Authorization.VIEW, CurrentPerson, rockContext );
                                    }
                                }
                            } );

                        }
                    }

                    #endregion

                }

                string message = string.Format("{0} {1} succesfully updated!",
                    ids.Count().ToString("N0"), (ids.Count() > 1 ? "people were" : "person was") );
                ShowResult( message );
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());
            var noteService     = new NoteService(rockContext);
            var prayerComments  = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // Filter by Category.  First see if there is a Block Setting, otherwise use the Grid Filter
            CategoryCache categoryFilter    = null;
            var           blockCategoryGuid = GetAttributeValue("PrayerRequestCategory").AsGuidOrNull();

            if (blockCategoryGuid.HasValue)
            {
                categoryFilter = CategoryCache.Read(blockCategoryGuid.Value);
            }

            if (categoryFilter == null && catpPrayerCategoryFilter.Visible)
            {
                int?filterCategoryId = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull();
                if (filterCategoryId.HasValue)
                {
                    categoryFilter = CategoryCache.Read(filterCategoryId.Value);
                }
            }

            if (categoryFilter != null)
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService(rockContext);
                var categories      = new CategoryService(rockContext).GetAllDescendents(categoryFilter.Guid).Select(a => a.Id).ToList();

                var prayerRequestQry = new PrayerRequestService(rockContext).Queryable().Where(a => a.CategoryId.HasValue &&
                                                                                               (a.Category.Guid == categoryFilter.Guid || categories.Contains(a.CategoryId.Value)))
                                       .Select(a => a.Id);

                prayerComments = prayerComments.Where(a => a.EntityId.HasValue && prayerRequestQry.Contains(a.EntityId.Value));
            }

            // Filter by Date Range
            if (drpDateRange.LowerValue.HasValue)
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate);
            }

            if (drpDateRange.UpperValue.HasValue)
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays(1);
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate);
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if (sortProperty != null)
            {
                gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderByDescending(n => n.CreatedDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
        /// <summary>
        /// Processes the confirmation.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessConfirmation( out string errorMessage )
        {
            var rockContext = new RockContext();
            if ( string.IsNullOrWhiteSpace( TransactionCode ) )
            {
                GatewayComponent gateway = hfPaymentTab.Value == "ACH" ? _achGateway : _ccGateway;
                if ( gateway == null )
                {
                    errorMessage = "There was a problem creating the payment gateway information";
                    return false;
                }

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

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

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

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

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

                    var scheduledTransaction = gateway.AddScheduledPayment( schedule, paymentInfo, out errorMessage );
                    if ( scheduledTransaction != null  )
                    {
                        scheduledTransaction.TransactionFrequencyValueId = schedule.TransactionFrequencyValue.Id;
                        scheduledTransaction.AuthorizedPersonAliasId = person.PrimaryAliasId.Value;
                        scheduledTransaction.GatewayEntityTypeId = EntityTypeCache.Read( gateway.TypeGuid ).Id;
                        scheduledTransaction.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
                        scheduledTransaction.CreditCardTypeValueId = CreditCardTypeValueId;

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

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

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

                        // Add a note about the change
                        var noteTypeService = new NoteTypeService( rockContext );
                        var noteType = noteTypeService.Get( scheduledTransaction.TypeId, "Note" );

                        var noteService = new NoteService( rockContext );
                        var note = new Note();
                        note.NoteTypeId = noteType.Id;
                        note.EntityId = scheduledTransaction.Id;
                        note.Caption = "Created Transaction";
                        note.Text = changeSummary.ToString();
                        noteService.Add( note );

                        rockContext.SaveChanges();

                        ScheduleId = scheduledTransaction.GatewayScheduleId;
                        TransactionCode = scheduledTransaction.TransactionCode;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    var transaction = gateway.Charge( paymentInfo, out errorMessage );
                    if ( transaction != null )
                    {
                        transaction.TransactionDateTime = RockDateTime.Now;
                        transaction.AuthorizedPersonAliasId = person.PrimaryAliasId;
                        transaction.GatewayEntityTypeId = gateway.TypeId;
                        transaction.TransactionTypeValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ).Id;
                        transaction.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
                        transaction.CreditCardTypeValueId = CreditCardTypeValueId;

                        Guid sourceGuid = Guid.Empty;
                        if ( Guid.TryParse( GetAttributeValue( "Source" ), out sourceGuid ) )
                        {
                            transaction.SourceTypeValueId = DefinedValueCache.Read( sourceGuid ).Id;
                        }

                        foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) )
                        {
                            var transactionDetail = new FinancialTransactionDetail();
                            transactionDetail.Amount = account.Amount;
                            transactionDetail.AccountId = account.Id;
                            transaction.TransactionDetails.Add( transactionDetail );
                        }

                        var batchService = new FinancialBatchService( rockContext );

                        // Get the batch
                        var batch = batchService.Get(
                            GetAttributeValue( "BatchNamePrefix" ),
                            paymentInfo.CurrencyTypeValue,
                            paymentInfo.CreditCardTypeValue,
                            transaction.TransactionDateTime.Value,
                            gateway.BatchTimeOffset );

                        batch.ControlAmount += transaction.TotalAmount;

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

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

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

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

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

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

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

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

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

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

                return true;
            }
            else
            {
                pnlDupWarning.Visible = true;
                divActions.Visible = false;
                errorMessage = string.Empty;
                return false;
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Sets the type of the note.
 /// </summary>
 private void SetNoteType()
 {
     var rockContext = new RockContext();
     var service = new NoteTypeService( rockContext );
     var noteType = service.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
     NoteTypeId = noteType.Id;
 }
Ejemplo n.º 27
0
 private void DeleteAllRelatedNotes( PrayerRequest prayerRequest )
 {
     var noteTypeService = new NoteTypeService();
     var noteType = noteTypeService.Get( (int)_prayerRequestEntityTypeId, "Prayer Comment" );
     var noteService = new NoteService();
     var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
     foreach ( Note prayerComment in prayerComments )
     {
         noteService.Delete( prayerComment, CurrentPersonId );
         noteService.Save( prayerComment, CurrentPersonId );
     }
 }
        /// <summary>
        /// Sets the type of the note.
        /// </summary>
        private void SetNoteType()
        {
            var entityTypeId = EntityTypeCache.Read( typeof( PrayerRequest ) ).Id;
            string noteTypeName = GetAttributeValue( "NoteType" );

            var rockContext = new RockContext();
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( entityTypeId, noteTypeName );

            // If a note type with the specified name does not exist, create one
            if ( noteType == null )
            {
                noteType = new NoteType();
                noteType.IsSystem = false;
                noteType.EntityTypeId = entityTypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue = string.Empty;
                noteType.Name = noteTypeName;
                service.Add( noteType );
                rockContext.SaveChanges();
            }

            NoteTypeId = noteType.Id;
        }
        /// <summary>
        /// Handles the Click event of the btnConfirm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnConfirm_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var ids = Individuals.Select( i => i.PersonId ).ToList();

                #region Individual Details Updates

                int? newTitleId = ddlTitle.SelectedValueAsInt();
                int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                int? newConnectionStatusId = ddlStatus.SelectedValueAsInt();
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt();
                string newInactiveReasonNote = tbInactiveReasonNote.Text;
                Gender newGender = ddlGender.SelectedValue.ConvertToEnum<Gender>();
                int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();

                int? newGraduationYear = null;
                if ( ypGraduation.SelectedYear.HasValue )
                {
                    newGraduationYear = ypGraduation.SelectedYear.Value;
                }

                int? newCampusId = cpCampus.SelectedCampusId;

                bool? newEmailActive = null;
                if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) )
                {
                    newEmailActive = ddlIsEmailActive.SelectedValue == "Active";
                }

                EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>();

                string newEmailNote = tbEmailNote.Text;

                int? newReviewReason = ddlReviewReason.SelectedValueAsInt();
                string newSystemNote = tbSystemNote.Text;
                string newReviewReasonNote = tbReviewReasonNote.Text;

                int inactiveStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id;

                var allChanges = new Dictionary<int, List<string>>();

                var people = personService.Queryable().Where( p => ids.Contains( p.Id ) ).ToList();
                foreach ( var person in people )
                {
                    var changes = new List<string>();
                    allChanges.Add( person.Id, changes );

                    if ( SelectedFields.Contains( ddlTitle.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                        person.TitleValueId = newTitleId;
                    }

                    if ( SelectedFields.Contains( ddlSuffix.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                        person.SuffixValueId = newSuffixId;
                    }

                    if ( SelectedFields.Contains( ddlStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) );
                        person.ConnectionStatusValueId = newConnectionStatusId;
                    }

                    if ( SelectedFields.Contains( ddlRecordStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                        person.RecordStatusValueId = newRecordStatusId;

                        if ( newRecordStatusId.HasValue && newRecordStatusId.Value == inactiveStatusId )
                        {
                            History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newInactiveReasonId ) );
                            person.RecordStatusReasonValueId = newInactiveReasonId;

                            if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) )
                            {
                                History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, newInactiveReasonNote );
                                person.InactiveReasonNote = newInactiveReasonNote;
                            }
                        }
                    }

                    if ( SelectedFields.Contains( ddlGender.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                        person.Gender = newGender;
                    }

                    if ( SelectedFields.Contains( ddlMaritalStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                        person.MaritalStatusValueId = newMaritalStatusId;
                    }

                    if ( SelectedFields.Contains( ddlGradePicker.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Graduation Year", person.GraduationYear, newGraduationYear );
                        person.GraduationYear = newGraduationYear;
                    }

                    if ( SelectedFields.Contains( ddlIsEmailActive.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Is Active", person.IsEmailActive ?? true, newEmailActive.Value );
                        person.IsEmailActive = newEmailActive;
                    }

                    if ( SelectedFields.Contains( ddlEmailPreference.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                        person.EmailPreference = newEmailPreference.Value;
                    }

                    if ( SelectedFields.Contains( tbEmailNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Note", person.EmailNote, newEmailNote );
                        person.EmailNote = newEmailNote;
                    }

                    if ( SelectedFields.Contains( tbSystemNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "System Note", person.SystemNote, newSystemNote );
                        person.SystemNote = newSystemNote;
                    }

                    if ( SelectedFields.Contains( ddlReviewReason.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( person.ReviewReasonValueId ), DefinedValueCache.GetName( newReviewReason ) );
                        person.ReviewReasonValueId = newReviewReason;
                    }

                    if ( SelectedFields.Contains( tbReviewReasonNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason Note", person.ReviewReasonNote, newReviewReasonNote );
                        person.ReviewReasonNote = newReviewReasonNote;
                    }
                }

                if ( SelectedFields.Contains( cpCampus.ClientID ) && cpCampus.SelectedCampusId.HasValue )
                {
                    int campusId = cpCampus.SelectedCampusId.Value;

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

                    var familyMembers = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => new { m.PersonId, m.GroupId } )
                        .Distinct()
                        .ToList();

                    var families = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => m.Group )
                        .Distinct()
                        .ToList();

                    foreach ( int personId in ids )
                    {
                        var familyIds = familyMembers.Where( m => m.PersonId == personId ).Select( m => m.GroupId ).ToList();
                        if ( familyIds.Count == 1 )
                        {
                            int familyId = familyIds.FirstOrDefault();
                            var family = families.Where( g => g.Id == familyId ).FirstOrDefault();
                            {
                                if ( family != null )
                                {
                                    family.CampusId = campusId;
                                }
                                familyMembers.RemoveAll( m => m.GroupId == familyId );
                            }
                        }
                    }

                    rockContext.SaveChanges();
                }

                // Update following
                if ( SelectedFields.Contains( ddlFollow.ClientID ) )
                {
                    var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" );
                    if ( personAliasEntityType != null )
                    {
                        int personAliasEntityTypeId = personAliasEntityType.Id;

                        bool follow = true;
                        if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) )
                        {
                            follow = ddlFollow.SelectedValue == "Add";
                        }

                        var personAliasService = new PersonAliasService( rockContext );
                        var followingService = new FollowingService( rockContext );
                        if ( follow )
                        {
                            var paQry = personAliasService.Queryable();

                            var alreadyFollowingIds = followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id )
                                .Join( paQry, f => f.EntityId, p => p.Id, ( f, p ) => new { PersonAlias = p } )
                                .Select( p => p.PersonAlias.PersonId )
                                .Distinct()
                                .ToList();

                            foreach ( int id in ids.Where( id => !alreadyFollowingIds.Contains( id ) ) )
                            {
                                var following = new Following
                                {
                                    EntityTypeId = personAliasEntityTypeId,
                                    EntityId = ( people.FirstOrDefault( p => p.Id == id ).PrimaryAliasId ) ?? 0,
                                    PersonAliasId = CurrentPersonAlias.Id
                                };
                                followingService.Add( following );
                            }
                        }
                        else
                        {
                            var paQry = personAliasService.Queryable()
                                .Where( p => ids.Contains( p.PersonId ) )
                                .Select( p => p.Id );

                            foreach ( var following in followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    paQry.Contains( f.EntityId ) &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id ) )
                            {
                                followingService.Delete( following );
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                #endregion

                #region Attributes

                var selectedCategories = new List<CategoryCache>();
                foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
                {
                    var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                    if ( category != null )
                    {
                        selectedCategories.Add( category );
                    }
                }

                var attributes = new List<AttributeCache>();
                var attributeValues = new Dictionary<int, string>();

                int categoryIndex = 0;
                foreach ( var category in selectedCategories.OrderBy( c => c.Name ) )
                {
                    PanelWidget pw = null;
                    string controlId = "pwAttributes_" + category.Id.ToString();
                    if ( categoryIndex % 2 == 0 )
                    {
                        pw = phAttributesCol1.FindControl( controlId ) as PanelWidget;
                    }
                    else
                    {
                        pw = phAttributesCol2.FindControl( controlId ) as PanelWidget;
                    }
                    categoryIndex++;

                    if ( pw != null )
                    {
                        var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                            .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                        foreach ( var attribute in orderedAttributeList )
                        {
                            if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                var attributeCache = AttributeCache.Read( attribute.Id );

                                Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) );

                                if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    attributes.Add( attributeCache );
                                    attributeValues.Add( attributeCache.Id, newValue );
                                }
                            }
                        }
                    }
                }

                if ( attributes.Any() )
                {
                    foreach ( var person in people )
                    {
                        person.LoadAttributes();
                        foreach ( var attribute in attributes )
                        {
                            string originalValue = person.GetAttributeValue( attribute.Key );
                            string newValue = attributeValues[attribute.Id];
                            if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                            {
                                Rock.Attribute.Helper.SaveAttributeValue( person, attribute, newValue, rockContext );

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

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

                                History.EvaluateChange( allChanges[person.Id], attribute.Name, formattedOriginalValue, formattedNewValue );
                            }
                        }
                    }
                }

                // Create the history records
                foreach ( var changes in allChanges )
                {
                    if ( changes.Value.Any() )
                    {
                        HistoryService.AddChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            changes.Key, changes.Value );
                    }
                }
                rockContext.SaveChanges();

                #endregion

                #region Add Note

                if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null )
                {
                    string text = tbNote.Text;
                    bool isAlert = cbIsAlert.Checked;
                    bool isPrivate = cbIsPrivate.Checked;

                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                    if ( noteType != null )
                    {
                        var notes = new List<Note>();
                        var noteService = new NoteService( rockContext );

                        foreach ( int id in ids )
                        {
                            var note = new Note();
                            note.IsSystem = false;
                            note.EntityId = id;
                            note.Caption = isPrivate ? "You - Personal Note" : string.Empty;
                            note.Text = tbNote.Text;
                            note.IsAlert = cbIsAlert.Checked;
                            note.NoteType = noteType;
                            notes.Add( note );
                            noteService.Add( note );
                        }

                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.SaveChanges();
                            foreach ( var note in notes )
                            {
                                note.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                                if ( isPrivate )
                                {
                                    note.MakePrivate( Authorization.VIEW, CurrentPerson, rockContext );
                                }
                            }
                        } );

                    }
                }

                #endregion

                #region Group

                int? groupId = gpGroup.SelectedValue.AsIntegerOrNull();
                if ( groupId.HasValue )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        var groupMemberService = new GroupMemberService( rockContext );

                        var existingMembers = groupMemberService.Queryable( "Group" )
                            .Where( m =>
                                m.GroupId == group.Id &&
                                ids.Contains( m.PersonId ) )
                            .ToList();

                        string action = ddlGroupAction.SelectedValue;
                        if ( action == "Remove" )
                        {
                            groupMemberService.DeleteRange( existingMembers );
                            rockContext.SaveChanges();
                        }
                        else
                        {
                            var roleId = ddlGroupRole.SelectedValueAsInt();
                            var status = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();

                            // Get the attribute values updated
                            var gm = new GroupMember();
                            gm.Group = group;
                            gm.GroupId = group.Id;
                            gm.LoadAttributes( rockContext );
                            var selectedGroupAttributes = new List<AttributeCache>();
                            var selectedGroupAttributeValues = new Dictionary<string, string>();
                            foreach ( var attributeCache in gm.Attributes.Select( a => a.Value ) )
                            {
                                Control attributeControl = phAttributes.FindControl( string.Format( "attribute_field_{0}", attributeCache.Id ) );
                                if ( attributeControl != null && ( action == "Add" || SelectedFields.Contains( attributeControl.ClientID ) ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    selectedGroupAttributes.Add( attributeCache );
                                    selectedGroupAttributeValues.Add( attributeCache.Key, newValue );
                                }
                            }

                            if ( action == "Add" )
                            {
                                if ( roleId.HasValue )
                                {
                                    var newGroupMembers = new List<GroupMember>();

                                    var existingIds = existingMembers.Select( m => m.PersonId ).Distinct().ToList();
                                    foreach ( int id in ids.Where( id => !existingIds.Contains( id ) ) )
                                    {
                                        var groupMember = new GroupMember();
                                        groupMember.GroupId = group.Id;
                                        groupMember.GroupRoleId = roleId.Value;
                                        groupMember.GroupMemberStatus = status;
                                        groupMember.PersonId = id;
                                        groupMemberService.Add( groupMember );
                                        newGroupMembers.Add( groupMember );
                                    }

                                    rockContext.SaveChanges();

                                    if ( selectedGroupAttributes.Any() )
                                    {
                                        foreach ( var groupMember in newGroupMembers )
                                        {
                                            foreach ( var attribute in selectedGroupAttributes )
                                            {
                                                Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                            }
                                        }
                                    }
                                }
                            }
                            else // Update
                            {
                                if ( SelectedFields.Contains( ddlGroupRole.ClientID ) && roleId.HasValue )
                                {
                                    foreach ( var member in existingMembers.Where( m => m.GroupRoleId != roleId.Value ) )
                                    {
                                        if ( !existingMembers.Where( m => m.PersonId == member.PersonId && m.GroupRoleId == roleId.Value ).Any() )
                                        {
                                            member.GroupRoleId = roleId.Value;
                                        }
                                    }
                                }

                                if ( SelectedFields.Contains( ddlGroupMemberStatus.ClientID ) )
                                {
                                    foreach ( var member in existingMembers )
                                    {
                                        member.GroupMemberStatus = status;
                                    }
                                }

                                rockContext.SaveChanges();

                                if ( selectedGroupAttributes.Any() )
                                {
                                    foreach ( var groupMember in existingMembers )
                                    {
                                        foreach ( var attribute in selectedGroupAttributes )
                                        {
                                            Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                pnlEntry.Visible = false;
                pnlConfirm.Visible = false;

                nbResult.Text = string.Format( "{0} {1} succesfully updated.",
                    ids.Count().ToString( "N0" ), ( ids.Count() > 1 ? "people were" : "person was" ) ); ;
                pnlResult.Visible = true;
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Sets the type of the note.
        /// </summary>
        private void SetNoteType()
        {
            var entityTypeId = EntityTypeCache.Read( typeof( PrayerRequest ) ).Id;
            string noteTypeName = GetAttributeValue( "NoteType" );

            var rockContext = new RockContext();
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( entityTypeId, noteTypeName );
            NoteTypeId = noteType.Id;
        }
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );

            // TODO log exception if noteType is null

            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            if ( _blockInstancePrayerRequestCategoryGuid.HasValue )
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService( rockContext );

                if ( _blockInstancePrayerRequestCategoryGuid.HasValue )
                {
                    var categories = new CategoryService( rockContext ).GetAllDescendents( _blockInstancePrayerRequestCategoryGuid.Value ).Select( a => a.Id ).ToList();

                    var prayerRequestQry = new PrayerRequestService( rockContext ).Queryable().Where( a => a.CategoryId.HasValue &&
                        ( a.Category.Guid == _blockInstancePrayerRequestCategoryGuid.Value || categories.Contains( a.CategoryId.Value ) ) )
                        .Select( a => a.Id );

                    prayerComments = prayerComments.Where( a => a.EntityId.HasValue && prayerRequestQry.Contains( a.EntityId.Value ) );
                }
            }

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Gets the type of the note.
        /// </summary>
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue( "NoteType" );

            var rockContext = new RockContext();
            var service = new NoteTypeService( rockContext );
            noteType = service.Get( contextEntity.TypeId, noteTypeName );
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // Filter by Category.  First see if there is a Block Setting, otherwise use the Grid Filter
            CategoryCache categoryFilter = null;
            var blockCategoryGuid = GetAttributeValue( "PrayerRequestCategory" ).AsGuidOrNull();
            if ( blockCategoryGuid.HasValue )
            {
                categoryFilter = CategoryCache.Read( blockCategoryGuid.Value );
            }

            if ( categoryFilter == null && catpPrayerCategoryFilter.Visible )
            {
                int? filterCategoryId = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull();
                if ( filterCategoryId.HasValue )
                {
                    categoryFilter = CategoryCache.Read( filterCategoryId.Value );
                }
            }

            if ( categoryFilter != null )
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService( rockContext );
                var categories = new CategoryService( rockContext ).GetAllDescendents( categoryFilter.Guid ).Select( a => a.Id ).ToList();

                var prayerRequestQry = new PrayerRequestService( rockContext ).Queryable().Where( a => a.CategoryId.HasValue &&
                    ( a.Category.Guid == categoryFilter.Guid || categories.Contains( a.CategoryId.Value ) ) )
                    .Select( a => a.Id );

                prayerComments = prayerComments.Where( a => a.EntityId.HasValue && prayerRequestQry.Contains( a.EntityId.Value ) );
            }

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderByDescending( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Processes the confirmation.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessConfirmation( out string errorMessage )
        {
            var rockContext = new RockContext();
            errorMessage = string.Empty;

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

                var personService = new PersonService( rockContext );
                var transactionService = new FinancialScheduledTransactionService( rockContext );
                var transactionDetailService = new FinancialScheduledTransactionDetailService( rockContext );

                FinancialScheduledTransaction scheduledTransaction = null;

                if ( ScheduledTransactionId.HasValue )
                {
                    scheduledTransaction = transactionService.Get( ScheduledTransactionId.Value );
                }

                if ( scheduledTransaction == null )
                {
                    errorMessage = "There was a problem getting the transaction information";
                    return false;
                }

                if ( scheduledTransaction.AuthorizedPerson == null )
                {
                    errorMessage = "There was a problem determining the person associated with the transaction";
                    return false;
                }

                var changeSummary = new StringBuilder();

                // Get the payment schedule
                scheduledTransaction.TransactionFrequencyValueId = btnFrequency.SelectedValueAsId().Value;
                changeSummary.Append( DefinedValueCache.Read( scheduledTransaction.TransactionFrequencyValueId, rockContext ) );

                if ( dtpStartDate.SelectedDate.HasValue && dtpStartDate.SelectedDate > RockDateTime.Today )
                {
                    scheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
                    changeSummary.AppendFormat( " starting {0}", scheduledTransaction.StartDate.ToShortDateString() );
                }
                else
                {
                    scheduledTransaction.StartDate = DateTime.MinValue;
                }

                changeSummary.AppendLine();

                PaymentInfo paymentInfo = GetPaymentInfo( personService, scheduledTransaction );
                if ( paymentInfo == null )
                {
                    errorMessage = "There was a problem creating the payment information";
                    return false;
                }
                else
                {
                }

                // If transaction is not active, attempt to re-activate it first
                if ( !scheduledTransaction.IsActive )
                {
                    if ( !transactionService.Reactivate( scheduledTransaction, out errorMessage ) )
                    {
                        return false;
                    }
                }

                if ( Gateway.UpdateScheduledPayment( scheduledTransaction, paymentInfo, out errorMessage ) )
                {
                    if ( paymentInfo.CurrencyTypeValue != null )
                    {
                        changeSummary.Append( paymentInfo.CurrencyTypeValue.Value );
                        scheduledTransaction.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;

                        DefinedValueCache creditCardTypeValue = paymentInfo.CreditCardTypeValue;
                        if ( creditCardTypeValue != null )
                        {
                            changeSummary.AppendFormat( " - {0}", creditCardTypeValue.Value );
                            scheduledTransaction.CreditCardTypeValueId = creditCardTypeValue.Id;
                        }
                        else
                        {
                            scheduledTransaction.CreditCardTypeValueId = null;
                        }
                        changeSummary.AppendFormat( " {0}", paymentInfo.MaskedNumber );
                        changeSummary.AppendLine();
                    }

                    var selectedAccountIds = SelectedAccounts
                        .Where( a => a.Amount > 0 )
                        .Select( a => a.Id ).ToList();

                    var deletedAccounts = scheduledTransaction.ScheduledTransactionDetails
                        .Where( a => !selectedAccountIds.Contains( a.AccountId ) ).ToList();

                    foreach ( var deletedAccount in deletedAccounts )
                    {
                        scheduledTransaction.ScheduledTransactionDetails.Remove( deletedAccount );
                        transactionDetailService.Delete( deletedAccount );
                    }

                    foreach ( var account in SelectedAccounts )
                    {
                        var detail = scheduledTransaction.ScheduledTransactionDetails
                            .Where( d => d.AccountId == account.Id ).FirstOrDefault();
                        if ( detail == null )
                        {
                            detail = new FinancialScheduledTransactionDetail();
                            detail.AccountId = account.Id;
                            scheduledTransaction.ScheduledTransactionDetails.Add( detail );
                        }

                        detail.Amount = account.Amount;

                        changeSummary.AppendFormat( "{0}: {1:C2}", account.Name, account.Amount );
                        changeSummary.AppendLine();
                    }

                    rockContext.SaveChanges();

                    // Add a note about the change
                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( scheduledTransaction.TypeId, "Note" );

                    var noteService = new NoteService( rockContext );
                    var note = new Note();
                    note.NoteTypeId = noteType.Id;
                    note.EntityId = scheduledTransaction.Id;
                    note.Caption = "Updated Transaction";
                    note.Text = changeSummary.ToString();
                    noteService.Add( note );

                    rockContext.SaveChanges();

                    ScheduleId = scheduledTransaction.GatewayScheduleId;
                    TransactionCode = scheduledTransaction.TransactionCode;

                    if (transactionService.GetStatus( scheduledTransaction, out errorMessage ))
                    {
                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    return false;
                }

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

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

                return true;
            }
            else
            {
                pnlDupWarning.Visible = true;
                return false;
            }
        }
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( (int)_prayerRequestEntityTypeId, "Prayer Comment" );
            // TODO log exception if noteType is null

            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // TODO: filter out comments that do not belong to the configured "category" grouping.
            //if ( _blockInstanceGroupCategoryId != All.Id )
            //{
            //    prayerComments = prayerComments.Where( c => c.CategoryId == _blockInstanceGroupCategoryId );
            //}

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Gets the configured NoteType for the PrayerRequest entity.
        /// </summary>
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue( "NoteType" );

            var _prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( new PrayerRequest().GetType().FullName );
            var noteTypeService = new NoteTypeService();
            var noteType = noteTypeService.Get( (int)_prayerRequestEntityTypeId, noteTypeName );
            
            // all that work to get this... for use later.
            PrayerCommentNoteTypeId = noteType.Id;
        }
        /// <summary>
        /// Reactivates the specified scheduled transaction.
        /// </summary>
        /// <param name="scheduledTransaction">The scheduled transaction.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool Reactivate( FinancialScheduledTransaction scheduledTransaction, out string errorMessages )
        {
            if ( scheduledTransaction != null &&
                scheduledTransaction.FinancialGateway != null &&
                scheduledTransaction.FinancialGateway.IsActive )
            {
                if ( scheduledTransaction.FinancialGateway.Attributes == null )
                {
                    scheduledTransaction.FinancialGateway.LoadAttributes( (RockContext)this.Context );
                }

                var gateway = scheduledTransaction.FinancialGateway.GetGatewayComponent();
                if ( gateway != null )
                {
                    if ( gateway.ReactivateScheduledPayment( scheduledTransaction, out errorMessages ) )
                    {
                        var noteTypeService = new NoteTypeService( (RockContext)this.Context );
                        var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid() );
                        if ( noteType != null )
                        {
                            var noteService = new NoteService( (RockContext)this.Context );
                            var note = new Note();
                            note.NoteTypeId = noteType.Id;
                            note.EntityId = scheduledTransaction.Id;
                            note.Caption = "Reactivated Transaction";
                            noteService.Add( note );
                        }

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            errorMessages = "Gateway is invalid or not active";
            return false;
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );

            var userLogin = userLoginService.Queryable().Where( a => a.ApiKey == tbKey.Text ).FirstOrDefault();
            if ( userLogin != null && userLogin.PersonId != int.Parse( hfRestUserId.Value ) )
            {
                // this key already exists in the database. Show the error and get out of here.
                nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. ";
                nbWarningMessage.Visible = true;
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                var restUser = new Person();
                if ( int.Parse( hfRestUserId.Value ) != 0 )
                {
                    restUser = personService.Get( int.Parse( hfRestUserId.Value ) );
                }
                else
                {
                    personService.Add( restUser );
                }

                // the rest user name gets saved as the last name on a person
                History.EvaluateChange( changes, "Last Name", restUser.LastName, tbName.Text );
                restUser.LastName = tbName.Text;
                restUser.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid() ).Id;
                if ( cbActive.Checked )
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;
                }
                else
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid() ).Id;
                }

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

                // the description gets saved as a system note for the person
                var entityTypeService = new EntityTypeService( rockContext );
                var entityType = entityTypeService.Get( "Rock.Model.Person" );
                var noteTypeService = new NoteTypeService( rockContext );
                var noteType = noteTypeService.Get( entityType.Id, "Timeline" );
                var noteService = new NoteService( rockContext );
                var note = noteService.Get( noteType.Id, restUser.Id ).FirstOrDefault();
                if ( note == null )
                {
                    note = new Note();
                    noteService.Add( note );
                }

                note.NoteTypeId = noteType.Id;
                note.EntityId = restUser.Id;
                note.Text = tbDescription.Text;
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                entityType = entityTypeService.Get( "Rock.Security.Authentication.Database" );
                userLogin = userLoginService.GetByPersonId( restUser.Id ).FirstOrDefault();
                if ( userLogin == null )
                {
                    userLogin = new UserLogin();
                    userLoginService.Add( userLogin );
                }

                if ( string.IsNullOrWhiteSpace( userLogin.UserName ) )
                {
                    userLogin.UserName = Guid.NewGuid().ToString();
                }

                userLogin.ApiKey = tbKey.Text;
                userLogin.PersonId = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();
            } );
            NavigateToParentPage();
        }