/// <summary>
        /// Handles the Delete event of the gConnectionType 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 gConnectionType_Delete(object sender, RowEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService(rockContext);
                ConnectionTypeService     connectionTypeService     = new ConnectionTypeService(rockContext);
                AuthService    authService    = new AuthService(rockContext);
                ConnectionType connectionType = connectionTypeService.Get(e.RowKeyId);

                if (connectionType != null)
                {
                    if (!connectionType.IsAuthorized(Authorization.ADMINISTRATE, this.CurrentPerson))
                    {
                        mdGridWarning.Show("You are not authorized to delete this connection type.", ModalAlertType.Information);
                        return;
                    }

                    // var connectionOppotunityies = new Service<ConnectionOpportunity>( rockContext ).Queryable().All( a => a.ConnectionTypeId == connectionType.Id );
                    var connectionOpportunities = connectionType.ConnectionOpportunities.ToList();
                    ConnectionOpportunityService     connectionOpportunityService     = new ConnectionOpportunityService(rockContext);
                    ConnectionRequestActivityService connectionRequestActivityService = new ConnectionRequestActivityService(rockContext);
                    foreach (var connectionOpportunity in connectionOpportunities)
                    {
                        var connectionRequestActivities = new Service <ConnectionRequestActivity>(rockContext).Queryable().Where(a => a.ConnectionOpportunityId == connectionOpportunity.Id).ToList();
                        foreach (var connectionRequestActivity in connectionRequestActivities)
                        {
                            connectionRequestActivityService.Delete(connectionRequestActivity);
                        }

                        rockContext.SaveChanges();
                        string errorMessageConnectionOpportunity;
                        if (!connectionOpportunityService.CanDelete(connectionOpportunity, out errorMessageConnectionOpportunity))
                        {
                            mdGridWarning.Show(errorMessageConnectionOpportunity, ModalAlertType.Information);
                            return;
                        }

                        connectionOpportunityService.Delete(connectionOpportunity);
                    }

                    rockContext.SaveChanges();
                    string errorMessage;
                    if (!connectionTypeService.CanDelete(connectionType, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    connectionTypeService.Delete(connectionType);
                    rockContext.SaveChanges();

                    ConnectionWorkflowService.RemoveCachedTriggers();
                }
            }

            BindGrid();
        }
        /// <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 )
        {
            ConnectionType connectionType;
            using ( var rockContext = new RockContext() )
            {
                if ( StatusesState.Any( s => s.IsDefault ) && ActivityTypesState.Any() )
                {
                    ConnectionTypeService connectionTypeService = new ConnectionTypeService( rockContext );
                    ConnectionActivityTypeService connectionActivityTypeService = new ConnectionActivityTypeService( rockContext );
                    ConnectionStatusService connectionStatusService = new ConnectionStatusService( rockContext );
                    ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext );
                    AttributeService attributeService = new AttributeService( rockContext );
                    AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext );

                    int connectionTypeId = int.Parse( hfConnectionTypeId.Value );

                    if ( connectionTypeId == 0 )
                    {
                        connectionType = new ConnectionType();
                        connectionTypeService.Add( connectionType );
                    }
                    else
                    {
                        connectionType = connectionTypeService.Queryable( "ConnectionActivityTypes, ConnectionWorkflows" ).Where( c => c.Id == connectionTypeId ).FirstOrDefault();

                        var uiWorkflows = WorkflowsState.Select( l => l.Guid );
                        foreach ( var connectionWorkflow in connectionType.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() )
                        {
                            connectionType.ConnectionWorkflows.Remove( connectionWorkflow );
                            connectionWorkflowService.Delete( connectionWorkflow );
                        }

                        var uiActivityTypes = ActivityTypesState.Select( r => r.Guid );
                        foreach ( var connectionActivityType in connectionType.ConnectionActivityTypes.Where( r => !uiActivityTypes.Contains( r.Guid ) ).ToList() )
                        {
                            connectionType.ConnectionActivityTypes.Remove( connectionActivityType );
                            connectionActivityTypeService.Delete( connectionActivityType );
                        }

                        var uiStatuses = StatusesState.Select( r => r.Guid );
                        foreach ( var connectionStatus in connectionType.ConnectionStatuses.Where( r => !uiStatuses.Contains( r.Guid ) ).ToList() )
                        {
                            connectionType.ConnectionStatuses.Remove( connectionStatus );
                            connectionStatusService.Delete( connectionStatus );
                        }
                    }

                    connectionType.Name = tbName.Text;
                    connectionType.Description = tbDescription.Text;
                    connectionType.IconCssClass = tbIconCssClass.Text;
                    connectionType.DaysUntilRequestIdle = nbDaysUntilRequestIdle.Text.AsInteger();
                    connectionType.EnableFutureFollowup = cbFutureFollowUp.Checked;
                    connectionType.EnableFullActivityList = cbFullActivityList.Checked;
                    connectionType.RequiresPlacementGroupToConnect = cbRequiresPlacementGroup.Checked;

                    foreach ( var connectionActivityTypeState in ActivityTypesState )
                    {
                        ConnectionActivityType connectionActivityType = connectionType.ConnectionActivityTypes.Where( a => a.Guid == connectionActivityTypeState.Guid ).FirstOrDefault();
                        if ( connectionActivityType == null )
                        {
                            connectionActivityType = new ConnectionActivityType();
                            connectionType.ConnectionActivityTypes.Add( connectionActivityType );
                        }

                        connectionActivityType.CopyPropertiesFrom( connectionActivityTypeState );
                    }

                    foreach ( var connectionStatusState in StatusesState )
                    {
                        ConnectionStatus connectionStatus = connectionType.ConnectionStatuses.Where( a => a.Guid == connectionStatusState.Guid ).FirstOrDefault();
                        if ( connectionStatus == null )
                        {
                            connectionStatus = new ConnectionStatus();
                            connectionType.ConnectionStatuses.Add( connectionStatus );
                        }

                        connectionStatus.CopyPropertiesFrom( connectionStatusState );
                        connectionStatus.ConnectionTypeId = connectionType.Id;
                    }

                    foreach ( ConnectionWorkflow connectionWorkflowState in WorkflowsState )
                    {
                        ConnectionWorkflow connectionWorkflow = connectionType.ConnectionWorkflows.Where( a => a.Guid == connectionWorkflowState.Guid ).FirstOrDefault();
                        if ( connectionWorkflow == null )
                        {
                            connectionWorkflow = new ConnectionWorkflow();
                            connectionType.ConnectionWorkflows.Add( connectionWorkflow );
                        }
                        else
                        {
                            connectionWorkflowState.Id = connectionWorkflow.Id;
                            connectionWorkflowState.Guid = connectionWorkflow.Guid;
                        }

                        connectionWorkflow.CopyPropertiesFrom( connectionWorkflowState );
                        connectionWorkflow.ConnectionTypeId = connectionTypeId;
                    }

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

                    // need WrapTransaction due to Attribute saves
                    rockContext.WrapTransaction( () =>
                    {
                        rockContext.SaveChanges();

                        /* Save Attributes */
                        string qualifierValue = connectionType.Id.ToString();
                        SaveAttributes( new ConnectionOpportunity().TypeId, "ConnectionTypeId", qualifierValue, AttributesState, rockContext );

                        connectionType = connectionTypeService.Get( connectionType.Id );
                        if ( connectionType != null )
                        {
                            if ( !connectionType.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                            {
                                connectionType.AllowPerson( Authorization.VIEW, CurrentPerson, rockContext );
                            }

                            if ( !connectionType.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                connectionType.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                            }

                            if ( !connectionType.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ) )
                            {
                                connectionType.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext );
                            }
                        }
                    } );

                    ConnectionWorkflowService.FlushCachedTriggers();

                    var qryParams = new Dictionary<string, string>();
                    qryParams["ConnectionTypeId"] = connectionType.Id.ToString();

                    NavigateToPage( RockPage.Guid, qryParams );
                }
                else
                {
                    nbRequired.Visible = true;
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDeleteConfirm_Click( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext );
                ConnectionTypeService connectionTypeService = new ConnectionTypeService( rockContext );
                AuthService authService = new AuthService( rockContext );
                ConnectionType connectionType = connectionTypeService.Get( int.Parse( hfConnectionTypeId.Value ) );

                if ( connectionType != null )
                {
                    if ( !connectionType.IsAuthorized( Authorization.ADMINISTRATE, this.CurrentPerson ) )
                    {
                        mdDeleteWarning.Show( "You are not authorized to delete this connection type.", ModalAlertType.Information );
                        return;
                    }

                    string errorMessage;
                    if ( !connectionTypeService.CanDelete( connectionType, out errorMessage ) )
                    {
                        mdDeleteWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    connectionTypeService.Delete( connectionType );
                    rockContext.SaveChanges();

                    ConnectionWorkflowService.FlushCachedTriggers();
                }
            }

            NavigateToParentPage();
        }
示例#4
0
        /// <summary>
        /// Maps the contact form data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        public void MapContactFormData(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext = new RockContext();

            var importedCommunicationCount = new CommunicationService(lookupContext).Queryable().Count(c => c.ForeignKey != null);
            var importedNoteCount          = new NoteService(lookupContext).Queryable().Count(n => n.ForeignKey != null);

            // Involvement Connection Type
            var connectionTypeService = new ConnectionTypeService(lookupContext);
            var defaultConnectionType = connectionTypeService.Get("DD565087-A4BE-4943-B123-BF22777E8426".AsGuid());
            var connectCardType       = connectionTypeService.Queryable().Where(t => t.Name.Equals("Connect Card", StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var opportunities         = new ConnectionOpportunityService(lookupContext).Queryable().ToList();
            var statuses        = new ConnectionStatusService(lookupContext).Queryable().ToList();
            var noContactStatus = statuses.FirstOrDefault(s => s.Name.Equals("No Contact", StringComparison.InvariantCultureIgnoreCase));

            var prayerRequestors  = new Dictionary <int, Person>();
            var communicationList = new List <Communication>();
            var connectionList    = new List <ConnectionRequest>();
            var prayerList        = new List <PrayerRequest>();
            var noteList          = new List <Note>();

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

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

            ReportProgress(0, $"Verifying contact items ({totalRows:N0} found, {importedNoteCount + importedCommunicationCount:N0} already exist).");

            foreach (var row in tableData.Where(r => r != null))
            {
                // ContactFormData joins to IndividualContactNotes on ContactInstItemID
                var itemForeignKey       = row["ContactInstItemID"] as int?;
                var householdId          = row["HouseholdID"] as int?;
                var itemIndividualId     = row["ContactItemIndividualID"] as int?;
                var individualId         = row["ContactIndividualID"] as int?;
                var createdDate          = row["ContactActivityDate"] as DateTime?;
                var modifiedDate         = row["ContactDatetime"] as DateTime?;
                var approvalDate         = row["ContactFormLastUpdatedDate"] as DateTime?;
                var itemType             = row["ContactFormName"] as string;
                var itemStatus           = row["ContactStatus"] as string;
                var itemCaption          = row["ContactItemName"] as string;
                var noteText1            = row["ContactNote"] as string;
                var noteText2            = row["ContactItemNote"] as string;
                var itemUserId           = row["ContactItemAssignedUserID"] as int?;
                var contactUserId        = row["ContactAssignedUserID"] as int?;
                var initialContactUserId = row["InitialContactCreatedByUserID"] as int?;
                var isConfidential       = row["IsContactItemConfidential"] as int?;
                var itemText             = !string.IsNullOrWhiteSpace(noteText1) ? $"{noteText1}<br>{noteText2}" : noteText2 ?? string.Empty;

                // look up the person this contact form is for
                var hasCaption = !string.IsNullOrWhiteSpace(itemCaption);
                var personKeys = GetPersonKeys(itemIndividualId ?? individualId, householdId);
                if (personKeys != null && (hasCaption || !string.IsNullOrWhiteSpace(itemText)))
                {
                    var assignedUserId    = itemUserId ?? contactUserId ?? initialContactUserId ?? 0;
                    var userPersonAliasId = PortalUsers.ContainsKey(assignedUserId) ? ( int? )PortalUsers[assignedUserId] : null;
                    // 99% of the Email types have no other info
                    if (itemType.Equals("Email", StringComparison.CurrentCultureIgnoreCase))
                    {
                        // create the recipient list for this contact
                        var recipients = new List <CommunicationRecipient> {
                            new CommunicationRecipient {
                                SendDateTime            = createdDate ?? modifiedDate,
                                Status                  = CommunicationRecipientStatus.Delivered,
                                PersonAliasId           = personKeys.PersonAliasId,
                                CreatedDateTime         = createdDate ?? modifiedDate,
                                CreatedByPersonAliasId  = userPersonAliasId,
                                ModifiedByPersonAliasId = userPersonAliasId,
                                ForeignKey              = personKeys.PersonForeignId.ToString(),
                                ForeignId               = personKeys.PersonForeignId
                            }
                        };

                        // create an email record for this contact form
                        var emailSubject  = !string.IsNullOrWhiteSpace(itemCaption) ? itemCaption.Left(100) : itemText.Left(100);
                        var communication = AddCommunication(lookupContext, EmailCommunicationMediumTypeId, emailSubject, itemText, false,
                                                             CommunicationStatus.Approved, recipients, false, createdDate ?? modifiedDate, itemForeignKey.ToString(), userPersonAliasId);

                        communicationList.Add(communication);
                    }
                    else if (itemType.EndsWith("Connection Card", StringComparison.CurrentCultureIgnoreCase) || itemType.Contains("Connect Card"))
                    {
                        // lookup connection opportunity
                        var opportunity = opportunities.FirstOrDefault(o => o.Name.Equals(itemType, StringComparison.InvariantCultureIgnoreCase) || (o.ForeignKey != null && o.ForeignKey.Equals(itemType, StringComparison.InvariantCultureIgnoreCase)));

                        if (opportunity == null)
                        {
                            var connectionType = connectCardType ?? defaultConnectionType;
                            opportunity = AddConnectionOpportunity(lookupContext, connectionType.Id, createdDate, itemType, string.Empty, true, itemForeignKey.ToString());
                            opportunities.Add(opportunity);
                        }

                        // create a connection request
                        var requestStatus = statuses.FirstOrDefault(s => s.Name.Equals(itemStatus, StringComparison.InvariantCultureIgnoreCase)) ?? noContactStatus;
                        var requestState  = itemStatus.Equals("Closed", StringComparison.InvariantCultureIgnoreCase) ? ConnectionState.Connected : ConnectionState.Active;

                        var request = AddConnectionRequest(opportunity, itemForeignKey.ToString(), createdDate, modifiedDate, requestStatus.Id, requestState, !string.IsNullOrWhiteSpace(itemText) ? $"{itemCaption} - {itemText}" : itemCaption ?? string.Empty, approvalDate, personKeys.PersonAliasId, userPersonAliasId);

                        connectionList.Add(request);
                    }
                    else if (hasCaption && itemCaption.EndsWith("Prayer Request", StringComparison.CurrentCultureIgnoreCase))
                    {
                        // create a prayer request
                        Person requestor = null;
                        prayerRequestors.TryGetValue(personKeys.PersonId, out requestor);
                        if (requestor == null)
                        {
                            requestor = lookupContext.People.FirstOrDefault(p => p.Id.Equals(personKeys.PersonId));
                            prayerRequestors.Add(personKeys.PersonId, requestor);
                        }

                        var request = AddPrayerRequest(lookupContext, null, personKeys.PersonAliasId, requestor.FirstName, requestor.LastName, requestor.Email, itemText ?? itemCaption, string.Empty,
                                                       !itemStatus.Equals("Closed", StringComparison.CurrentCultureIgnoreCase), false, createdDate ?? modifiedDate, approvalDate, itemForeignKey.ToString(), userPersonAliasId);
                        if (request != null)
                        {
                            prayerList.Add(request);
                        }
                    }
                    else
                    {
                        //strip campus from type
                        var campusId = GetCampusId(itemType);
                        if (campusId.HasValue)
                        {
                            itemType = StripPrefix(itemType, campusId);
                        }

                        // create a note for this contact form
                        var note = AddEntityNote(lookupContext, PersonEntityTypeId, personKeys.PersonId, itemCaption, itemText, false, false, itemType,
                                                 null, false, createdDate ?? modifiedDate, itemForeignKey.ToString(), userPersonAliasId);

                        noteList.Add(note);
                    }

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

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveCommunications(communicationList);
                        SaveConnectionRequests(connectionList);
                        SavePrayerRequests(prayerList);
                        SaveNotes(noteList);
                        ReportPartialProgress();

                        communicationList.Clear();
                        connectionList.Clear();
                        prayerList.Clear();
                        noteList.Clear();
                    }
                }
            }

            if (communicationList.Any() || connectionList.Any() || noteList.Any())
            {
                SaveCommunications(communicationList);
                SaveConnectionRequests(connectionList);
                SavePrayerRequests(prayerList);
                SaveNotes(noteList);
            }

            ReportProgress(100, $"Finished contact item import: {completedItems:N0} items imported.");
        }