public void LoadContent()
        {
            // get opportunity id
            int opportunityId = -1;

            if (!string.IsNullOrWhiteSpace(PageParameter("OpportunityId")))
            {
                opportunityId = Convert.ToInt32(PageParameter("OpportunityId"));
            }

            if (opportunityId > 0)
            {
                RockContext rockContext = new RockContext();
                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);

                bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean();

                var qry = connectionOpportunityService
                          .Queryable()
                          .Where(g => g.Id == opportunityId);

                if (!enableDebug)
                {
                    qry = qry.AsNoTracking();
                }
                var opportunity = qry.FirstOrDefault();

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                Dictionary <string, object> linkedPages = new Dictionary <string, object>();
                linkedPages.Add("SignupPage", LinkedPageRoute("SignupPage"));
                mergeFields.Add("LinkedPages", linkedPages);

                mergeFields.Add("CampusContext", RockPage.GetCurrentContext(EntityTypeCache.Read("Rock.Model.Campus")) as Campus);

                // run opportunity summary and details through lava
                opportunity.Summary     = opportunity.Summary.ResolveMergeFields(mergeFields);
                opportunity.Description = opportunity.Description.ResolveMergeFields(mergeFields);

                mergeFields.Add("Opportunity", opportunity);

                // add linked pages

                lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                if (GetAttributeValue("SetPageTitle").AsBoolean())
                {
                    string pageTitle = opportunity.PublicName;
                    RockPage.PageTitle    = pageTitle;
                    RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                }

                // show debug info
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo();
                }
            }
        }
Example #2
0
        /// <summary>
        /// Gets the connector campus ids, if the connectorPerson is not a member of the connecter groups for the opportunity, this wil return an empty lkist
        /// </summary>
        /// <param name="selectedCampaignItem">The selected campaign item.</param>
        /// <param name="connectorPerson">The connector person.</param>
        /// <returns></returns>
        public static List <int?> GetConnectorCampusIds(CampaignItem selectedCampaignItem, Person connectorPerson)
        {
            if (connectorPerson == null)
            {
                // if no connector person is specified, we can return list that just an "All" (null) campus
                var result = new List <int?>();
                result.Add(( int? )null);
                return(result);
            }

            var         rockContext = new RockContext();
            List <int?> connectorCampusIds;
            var         opportunityService = new ConnectionOpportunityService(rockContext);

            IQueryable <ConnectionOpportunityConnectorGroup> opportunityConnecterGroupQuery = opportunityService.Queryable()
                                                                                              .Where(a => a.IsActive && a.Guid == selectedCampaignItem.OpportunityGuid)
                                                                                              .SelectMany(a => a.ConnectionOpportunityConnectorGroups);

            int connectorPersonId = connectorPerson.Id;

            // get the campusid of the connector's connector group) of this opportunity
            // If the person is a member in more than one of opportunity groups, get all the campus ids that the connector can work with
            connectorCampusIds = opportunityConnecterGroupQuery.Where(a => a.ConnectorGroup.Members.Any(m => m.GroupMemberStatus == GroupMemberStatus.Active && m.PersonId == connectorPersonId)).Select(a => a.CampusId).Distinct().ToList();

            // NOTE: if connectorPerson isn't in a ConnectionOpportunityConnectorGroup, there will be no campus ids. The AddCampaignRequests block shouldn't of let them request connections for this campaign
            return(connectorCampusIds);
        }
        /// <summary>
        /// Populates the connection opportunity list.
        /// </summary>
        /// <param name="filterField">The filter field.</param>
        private void PopulateConnectionOpportunityDropdownList(FilterField filterField)
        {
            var connectionTypePicker        = filterField.ControlsOfTypeRecursive <RockDropDownList>().FirstOrDefault(a => a.HasCssClass("js-connectiontype-picker"));
            var connectionOpportunityPicker = filterField.ControlsOfTypeRecursive <RockDropDownList>().FirstOrDefault(a => a.HasCssClass("js-connectionopportunity-picker"));
            var connectionTypeId            = connectionTypePicker.SelectedValueAsId();

            if (connectionTypeId.HasValue)
            {
                connectionOpportunityPicker.Items.Clear();
                var connectionOpportunityList = new ConnectionOpportunityService(new RockContext()).Queryable().Where(a => a.ConnectionTypeId == connectionTypeId.Value && a.IsActive)
                                                .OrderBy(a => a.Order)
                                                .ThenBy(a => a.Name)
                                                .ToList();
                foreach (var connectionOpportunity in connectionOpportunityList)
                {
                    connectionOpportunityPicker.Items.Add(new ListItem(connectionOpportunity.Name, connectionOpportunity.Id.ToString()));
                }

                connectionOpportunityPicker.Visible = connectionOpportunityPicker.Items.Count > 0;
            }
            else
            {
                connectionOpportunityPicker.Visible = false;
            }
        }
        /// <summary>
        /// Sets the edit value from IEntity.Id value
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id">The identifier.</param>
        public void SetEditValueFromEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id)
        {
            var    item      = new ConnectionOpportunityService(new RockContext()).Get(id ?? 0);
            string guidValue = item != null?item.Guid.ToString() : string.Empty;

            SetEditValue(control, configurationValues, guidValue);
        }
        /// <summary>
        /// Gets the edit value as the IEntity.Id
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public int?GetEditValueAsEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            Guid guid = GetEditValue(control, configurationValues).AsGuid();
            var  item = new ConnectionOpportunityService(new RockContext()).Get(guid);

            return(item != null ? item.Id : (int?)null);
        }
        /// <summary>
        /// Binds the event calendar items grid.
        /// </summary>
        protected void BindConnectionOpportunitiesGrid()
        {
            if (_connectionType != null)
            {
                pnlConnectionOpportunities.Visible = true;

                rFilter.Visible = true;
                gConnectionOpportunities.Visible = true;

                var rockContext = new RockContext();

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                var qry = connectionOpportunityService.Queryable()
                          .Where(o => o.ConnectionTypeId == _connectionType.Id);

                // Filter by Active Only
                if (cbActive.Checked)
                {
                    qry = qry.Where(o => o.IsActive);
                }

                // Filter query by any configured attribute filters
                if (AvailableAttributes != null && AvailableAttributes.Any())
                {
                    foreach (var attribute in AvailableAttributes)
                    {
                        var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());
                        qry = attribute.FieldType.Field.ApplyAttributeQueryFilter(qry, filterControl, attribute, connectionOpportunityService, Rock.Reporting.FilterMode.SimpleFilter);
                    }
                }
                SortProperty sortProperty = gConnectionOpportunities.SortProperty;

                List <ConnectionOpportunity> connectionOpportunities = null;
                if (sortProperty != null)
                {
                    connectionOpportunities = qry.Sort(sortProperty).ToList();
                }
                else
                {
                    connectionOpportunities = qry.ToList().OrderBy(a => a.Name).ToList();
                }

                // Only include opportunities that current person is allowed to view
                var authorizedOpportunities = new List <ConnectionOpportunity>();
                foreach (var opportunity in connectionOpportunities)
                {
                    if (opportunity.IsAuthorized(Authorization.VIEW, CurrentPerson))
                    {
                        authorizedOpportunities.Add(opportunity);
                    }
                }

                gConnectionOpportunities.DataSource = authorizedOpportunities;
                gConnectionOpportunities.DataBind();
            }
            else
            {
                pnlConnectionOpportunities.Visible = false;
            }
        }
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            var editControl = new RockDropDownList {
                ID = id
            };

            editControl.Items.Add(new ListItem());

            var opportunities = new ConnectionOpportunityService(new RockContext())
                                .Queryable().AsNoTracking()
                                .OrderBy(o => o.ConnectionType.Name)
                                .ThenBy(o => o.Name)
                                .Select(o => new
            {
                o.Guid,
                o.Name,
                ConnectionTypeName = o.ConnectionType.Name
            })
                                .ToList();

            if (opportunities.Any())
            {
                foreach (var opportunity in opportunities)
                {
                    var listItem = new ListItem(opportunity.Name, opportunity.Guid.ToString().ToUpper());
                    listItem.Attributes.Add("OptionGroup", opportunity.ConnectionTypeName);
                    editControl.Items.Add(listItem);
                }

                return(editControl);
            }

            return(null);
        }
        /// <summary>
        /// Handles the Click event of the DeleteConnectionOpportunity control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param>
        protected void DeleteConnectionOpportunity_Click(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            using (RockContext rockContext = new RockContext())
            {
                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                ConnectionOpportunity        connectionOpportunity        = connectionOpportunityService.Get(e.RowKeyId);
                if (connectionOpportunity != null)
                {
                    if (_canEdit)
                    {
                        string errorMessage;
                        if (!connectionOpportunityService.CanDelete(connectionOpportunity, out errorMessage))
                        {
                            mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                            return;
                        }

                        int connectionTypeId = connectionOpportunity.ConnectionTypeId;
                        connectionOpportunityService.Delete(connectionOpportunity);
                        rockContext.SaveChanges();

                        ConnectionWorkflowService.FlushCachedTriggers();
                    }
                    else
                    {
                        mdGridWarning.Show("You are not authorized to delete this calendar item", ModalAlertType.Warning);
                    }
                }
            }
            BindConnectionOpportunitiesGrid();
        }
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            if (!string.IsNullOrWhiteSpace(selection))
            {
                SelectionConfig selectionConfig = SelectionConfig.Parse(selection);
                if (controls.Length > 0 && selectionConfig.ConnectionOpportunityGuid.HasValue)
                {
                    var connectionTypePicker = controls[0] as RockDropDownList;
                    var connectionType       = new ConnectionTypeService(new RockContext()).Get(selectionConfig.ConnectionTypeGuid.Value);
                    if (connectionType != null)
                    {
                        connectionTypePicker.SetValue(connectionType.Id);
                    }

                    connectionTypePicker_SelectedIndexChanged(connectionTypePicker, new EventArgs());

                    var connectionOpportunityGuid   = selectionConfig.ConnectionOpportunityGuid.Value;
                    var connectionOpportunityPicker = controls[1] as RockDropDownList;
                    var connectionOpportunity       = new ConnectionOpportunityService(new RockContext()).Get(connectionOpportunityGuid);
                    if (connectionOpportunity != null)
                    {
                        connectionOpportunityPicker.SetValue(connectionOpportunity.Id);
                    }
                }
            }
        }
        /// <summary>
        /// Sets the default number of requests.
        /// </summary>
        /// <param name="selectedCampaignConnectionItemGuid">The selected campaign connection item unique identifier.</param>
        private void SetDefaultNumberOfRequests(Guid?selectedCampaignConnectionItemGuid)
        {
            if (!selectedCampaignConnectionItemGuid.HasValue)
            {
                // shouldn't happen
                return;
            }

            var campaignConnectionItems        = Rock.Web.SystemSettings.GetValue(CampaignConnectionKey.CAMPAIGN_CONNECTION_CONFIGURATION).FromJsonOrNull <List <CampaignItem> >() ?? new List <CampaignItem>();
            var selectedCampaignConnectionItem = campaignConnectionItems.Where(a => a.Guid == selectedCampaignConnectionItemGuid.Value).FirstOrDefault();

            var rockContext        = new RockContext();
            var opportunityService = new ConnectionOpportunityService(rockContext);
            IQueryable <ConnectionOpportunityConnectorGroup> opportunityConnecterGroupQuery = opportunityService.Queryable()
                                                                                              .Where(a => a.Guid == selectedCampaignConnectionItem.OpportunityGuid)
                                                                                              .SelectMany(a => a.ConnectionOpportunityConnectorGroups);

            int?defaultDailyLimitAssigned = null;

            // Check to see if the group member has any CampaignDailyLimit values defined.
            var currentPersonConnectorGroupMember = opportunityConnecterGroupQuery
                                                    .Select(s => s.ConnectorGroup).SelectMany(g => g.Members)
                                                    .WhereAttributeValue(rockContext, av => (av.Attribute.Key == "CampaignDailyLimit") && av.ValueAsNumeric > 0)
                                                    .FirstOrDefault(m => m.PersonId == this.CurrentPersonId.Value);

            if (currentPersonConnectorGroupMember != null)
            {
                currentPersonConnectorGroupMember.LoadAttributes();
                defaultDailyLimitAssigned = currentPersonConnectorGroupMember.GetAttributeValue("CampaignDailyLimit").AsIntegerOrNull();
            }

            if (defaultDailyLimitAssigned == null && selectedCampaignConnectionItem.CreateConnectionRequestOption == CreateConnectionRequestOptions.AsNeeded)
            {
                defaultDailyLimitAssigned = selectedCampaignConnectionItem.DailyLimitAssigned;
            }

            var entitySetItemService = new EntitySetItemService(rockContext);
            int pendingCount         = CampaignConnectionHelper.GetPendingConnectionCount(selectedCampaignConnectionItem, CurrentPerson);

            if (pendingCount == 0)
            {
                nbAddConnectionRequestsMessage.Text = "There are no pending requests remaining.";
                nbAddConnectionRequestsMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Info;
                nbAddConnectionRequestsMessage.Visible             = true;
            }
            else if (pendingCount < defaultDailyLimitAssigned)
            {
                nbAddConnectionRequestsMessage.Text = string.Format("There are only {0} pending requests remaining.", pendingCount);
                nbAddConnectionRequestsMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Info;
                nbAddConnectionRequestsMessage.Visible             = true;
                defaultDailyLimitAssigned = pendingCount;
            }
            else
            {
                nbAddConnectionRequestsMessage.Visible = false;
            }

            nbNumberOfRequests.Text = defaultDailyLimitAssigned.ToString();
        }
        public void LoadContent()
        {
            // get opportunity id
            int opportunityId = -1;

            if (!string.IsNullOrWhiteSpace(PageParameter("OpportunityId")))
            {
                opportunityId = Convert.ToInt32(PageParameter("OpportunityId"));
            }

            if (opportunityId > 0)
            {
                RockContext rockContext = new RockContext();
                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);

                bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean();

                var qry = connectionOpportunityService
                          .Queryable()
                          .Where(g => g.Id == opportunityId);

                if (!enableDebug)
                {
                    qry = qry.AsNoTracking();
                }
                var opportunity = qry.FirstOrDefault();

                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("Opportunity", opportunity);

                // add linked pages
                Dictionary <string, object> linkedPages = new Dictionary <string, object>();
                linkedPages.Add("SignupPage", LinkedPageUrl("SignupPage", null));
                mergeFields.Add("LinkedPages", linkedPages);

                mergeFields.Add("CurrentPerson", CurrentPerson);

                var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(CurrentPerson);
                globalAttributeFields.ToList().ForEach(d => mergeFields.Add(d.Key, d.Value));

                lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                if (GetAttributeValue("SetPageTitle").AsBoolean())
                {
                    string pageTitle = opportunity.PublicName;
                    RockPage.PageTitle    = pageTitle;
                    RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                }

                // show debug info
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo();
                }
            }
        }
        /// <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 GridReorder event of the gConnectionOpportunities control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs" /> instance containing the event data.</param>
        protected void gConnectionOpportunities_GridReorder(object sender, GridReorderEventArgs e)
        {
            var rockContext             = new RockContext();
            var service                 = new ConnectionOpportunityService(rockContext);
            var connectionOpportunities = service.Queryable().OrderBy(b => b.Order);

            service.Reorder(connectionOpportunities.ToList(), e.OldIndex, e.NewIndex);
            rockContext.SaveChanges();

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

            // Get the connection request
            ConnectionRequest request     = null;
            Guid connectionRequestGuid    = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionRequestAttribute").AsGuid()).AsGuid();
            var  connectionRequestService = new ConnectionRequestService(rockContext);

            request = connectionRequestService.Get(connectionRequestGuid);
            if (request == null)
            {
                errorMessages.Add("Invalid Connection Request Attribute or Value!");
                return(false);
            }

            // Get the opportunity
            ConnectionOpportunity opportunity = null;
            Guid opportunityTypeGuid          = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionOpportunityAttribute").AsGuid()).AsGuid();

            opportunity = new ConnectionOpportunityService(rockContext).Get(opportunityTypeGuid);
            if (opportunity == null)
            {
                errorMessages.Add("Invalid Connection Opportunity Attribute or Value!");
                return(false);
            }

            // Get the transfer note
            string note = GetAttributeValue(action, "TransferNote", true);

            if (request != null && opportunity != null)
            {
                request.ConnectionOpportunityId = opportunity.Id;

                var guid = Rock.SystemGuid.ConnectionActivityType.TRANSFERRED.AsGuid();
                var transferredActivityId = new ConnectionActivityTypeService(rockContext)
                                            .Queryable()
                                            .Where(t => t.Guid == guid)
                                            .Select(t => t.Id)
                                            .FirstOrDefault();

                ConnectionRequestActivity connectionRequestActivity = new ConnectionRequestActivity();
                connectionRequestActivity.ConnectionRequestId      = request.Id;
                connectionRequestActivity.ConnectionOpportunityId  = opportunity.Id;
                connectionRequestActivity.ConnectionActivityTypeId = transferredActivityId;
                connectionRequestActivity.Note = note;
                new ConnectionRequestActivityService(rockContext).Add(connectionRequestActivity);

                rockContext.SaveChanges();
            }

            return(true);
        }
 /// <summary>
 /// Handles the Edit event of the gConnectionOpportunities 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 gConnectionOpportunities_Edit(object sender, RowEventArgs e)
 {
     using (RockContext rockContext = new RockContext())
     {
         ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
         ConnectionOpportunity        connectionOpportunity        = connectionOpportunityService.Get(e.RowKeyId);
         if (connectionOpportunity != null)
         {
             NavigateToLinkedPage("DetailPage", "ConnectionOpportunityId", connectionOpportunity.Id, "ConnectionTypeId", _connectionType.Id);
         }
     }
 }
Example #16
0
        /// <summary>
        /// Execute method to check for any workflows to launch.
        /// </summary>
        public void Execute()
        {
            // Verify that valid ids were saved
            if (ConnectionRequestId.HasValue)
            {
                // Get all the connectionWorkflows from cache
                var cachedWorkflows = ConnectionWorkflowService.GetCachedTriggers();

                // If any connectionWorkflows exist
                if (cachedWorkflows != null && cachedWorkflows.Any())
                {
                    // Get the connectionWorkflows associated to the connection
                    var workflows = cachedWorkflows
                                    .Where(w =>
                                           w.TriggerType == ConnectionWorkflowTriggerType.ActivityAdded &&
                                           (
                                               (w.ConnectionOpportunityId.HasValue && w.ConnectionOpportunityId.Value == ConnectionOpportunityId.Value) ||
                                               (w.ConnectionTypeId.HasValue)
                                           )
                                           )
                                    .ToList();

                    if (workflows.Any())
                    {
                        using (var rockContext = new RockContext())
                        {
                            // Get the current txn's connection type id
                            var ConnectionTypeId = new ConnectionOpportunityService(rockContext)
                                                   .Queryable().AsNoTracking()
                                                   .Where(o => o.Id == ConnectionOpportunityId.Value)
                                                   .Select(o => o.ConnectionTypeId)
                                                   .FirstOrDefault();

                            // Further filter the connection type connectionWorkflows by the connection type id
                            workflows = workflows
                                        .Where(w =>
                                               (w.ConnectionOpportunityId.HasValue && w.ConnectionOpportunityId.Value == ConnectionOpportunityId.Value) ||
                                               (w.ConnectionTypeId.HasValue && w.ConnectionTypeId.Value == ConnectionTypeId))
                                        .ToList();

                            // Loop through connectionWorkflows and lauch appropriate workflow
                            foreach (var connectionWorkflow in workflows)
                            {
                                if (QualifiersMatch(rockContext, connectionWorkflow, ConnectionActivityTypeId))
                                {
                                    LaunchWorkflow(rockContext, connectionWorkflow, "Activity Added");
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            // Get the connection request
            ConnectionRequest request = null;
            Guid connectionRequestGuid = action.GetWorklowAttributeValue( GetAttributeValue( action, "ConnectionRequestAttribute" ).AsGuid() ).AsGuid();
            var connectionRequestService = new ConnectionRequestService( rockContext );
            request = connectionRequestService.Get( connectionRequestGuid );
            if ( request == null )
            {
                errorMessages.Add( "Invalid Connection Request Attribute or Value!" );
                return false;
            }

            // Get the opportunity
            ConnectionOpportunity opportunity = null;
            Guid opportunityTypeGuid = action.GetWorklowAttributeValue( GetAttributeValue( action, "ConnectionOpportunityAttribute" ).AsGuid() ).AsGuid();
            opportunity = new ConnectionOpportunityService( rockContext ).Get( opportunityTypeGuid );
            if ( opportunity == null )
            {
                errorMessages.Add( "Invalid Connection Opportunity Attribute or Value!" );
                return false;
            }

            // Get the tranfer note
            string note = GetAttributeValue( action, "TransferNote", true );

            if ( request != null && opportunity != null )
            {
                request.ConnectionOpportunityId = opportunity.Id;

                var guid = Rock.SystemGuid.ConnectionActivityType.TRANSFERRED.AsGuid();
                var transferredActivityId = new ConnectionActivityTypeService( rockContext )
                    .Queryable()
                    .Where( t => t.Guid == guid )
                    .Select( t => t.Id )
                    .FirstOrDefault();

                ConnectionRequestActivity connectionRequestActivity = new ConnectionRequestActivity();
                connectionRequestActivity.ConnectionRequestId = request.Id;
                connectionRequestActivity.ConnectionOpportunityId = opportunity.Id;
                connectionRequestActivity.ConnectionActivityTypeId = transferredActivityId;
                connectionRequestActivity.Note = note;
                new ConnectionRequestActivityService( rockContext ).Add( connectionRequestActivity );

                rockContext.SaveChanges();
            }

            return true;
        }
Example #18
0
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            bool includeInactive   = false;
            int? groupTypeFilterId = null;

            if (configurationValues != null)
            {
                includeInactive   = configurationValues.ContainsKey(INCLUDE_INACTIVE_KEY) && configurationValues[INCLUDE_INACTIVE_KEY].Value.AsBoolean();
                groupTypeFilterId = configurationValues.ContainsKey(CONNECTION_TYPE_FILTER) ? configurationValues[CONNECTION_TYPE_FILTER].Value.AsIntegerOrNull() : null;
            }

            var opportunities = new ConnectionOpportunityService(new RockContext())
                                .Queryable().AsNoTracking()
                                .Where(o => o.IsActive || includeInactive)
                                .OrderBy(o => o.ConnectionType.Name)
                                .ThenBy(o => o.Name)
                                .Select(o => new { o.Guid, o.Name, o.ConnectionType })
                                .ToList();

            var editControl = new RockDropDownList {
                ID = id
            };

            editControl.Items.Add(new ListItem());

            if (opportunities.Any())
            {
                foreach (var opportunity in opportunities)
                {
                    if (groupTypeFilterId != null && opportunity.ConnectionType.Id != groupTypeFilterId)
                    {
                        continue;
                    }

                    var listItem = new ListItem(opportunity.Name, opportunity.Guid.ToString().ToUpper());

                    // Don't add an option group if there is a filter since that would be only one group.
                    if (groupTypeFilterId == null)
                    {
                        listItem.Attributes.Add("OptionGroup", opportunity.ConnectionType.Name);
                    }

                    editControl.Items.Add(listItem);
                }

                return(editControl);
            }

            return(null);
        }
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );
            _rockContext = new RockContext();

            conOppServ = new ConnectionOpportunityService( _rockContext );
            conStatServ = new ConnectionStatusService( _rockContext );
            conReqActServ = new ConnectionRequestActivityService( _rockContext );

            dateRange.UpperValue = DateTime.Now;
            dateRange.LowerValue = DateTime.Now.AddYears( -1 );

            lReadOnlyTitle.Text = "Connection Requests".FormatAsHtmlTitle();
            workflowFilters.Show();
        }
Example #20
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _rockContext = new RockContext();

            conOppServ    = new ConnectionOpportunityService(_rockContext);
            conStatServ   = new ConnectionStatusService(_rockContext);
            conReqActServ = new ConnectionRequestActivityService(_rockContext);

            dateRange.UpperValue = DateTime.Now;
            dateRange.LowerValue = DateTime.Now.AddYears(-1);

            lReadOnlyTitle.Text = "Connection Requests".FormatAsHtmlTitle();
            workflowFilters.Show();
        }
        private ConnectionRequest BuildConnectionRequest(RockContext rockContext, DateTime?createdDate)
        {
            var connectionOpportunity = new ConnectionOpportunityService(rockContext).Queryable().First();
            var personAlias           = new PersonAliasService(rockContext).Queryable().First();
            var connectionStatus      = new ConnectionStatusService(rockContext).Queryable().First();

            var connectionRequest = new ConnectionRequest();

            connectionRequest.ConnectionOpportunityId = connectionOpportunity.Id;
            connectionRequest.PersonAliasId           = personAlias.Id;
            connectionRequest.ConnectionStatusId      = connectionStatus.Id;
            connectionRequest.ForeignKey      = connectionRequestForeignKey;
            connectionRequest.CreatedDateTime = createdDate;

            return(connectionRequest);
        }
Example #22
0
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlConnectionType 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 ddlConnectionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedConnectionTypeGuid   = ddlConnectionType.SelectedValueAsGuid();
            var connectionOpportunityService = new ConnectionOpportunityService(new RockContext());

            ddlConnectionOpportunity.Items.Clear();
            ddlConnectionOpportunity.Visible = selectedConnectionTypeGuid.HasValue;
            if (selectedConnectionTypeGuid.HasValue)
            {
                var connectionOpportunities = connectionOpportunityService.Queryable().Where(a => a.ConnectionType.Guid == selectedConnectionTypeGuid.Value);
                ddlConnectionOpportunity.Items.Add(new ListItem());
                ddlConnectionOpportunity.Items.AddRange(connectionOpportunities.Select(x => new ListItem {
                    Text = x.Name, Value = x.Guid.ToString()
                }).ToArray());
            }
        }
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection(Type entityType, string selection)
        {
            string result          = "Connection Opportunity";
            var    selectionConfig = SelectionConfig.Parse(selection);

            if (selectionConfig != null && selectionConfig.ConnectionOpportunityGuid.HasValue)
            {
                var connectionOpportunity = new ConnectionOpportunityService(new RockContext()).Get(selectionConfig.ConnectionOpportunityGuid.Value);
                if (connectionOpportunity != null)
                {
                    result = string.Format("Connection Opportunity: {0} in {1} Connection Type", connectionOpportunity.Name, connectionOpportunity.ConnectionType.Name);
                }
            }

            return(result);
        }
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? opportunityId = PageParameter( pageReference, "OpportunityId" ).AsIntegerOrNull();
            if ( opportunityId != null )
            {
                ConnectionOpportunity connectionOpportunity = new ConnectionOpportunityService( new RockContext() ).Get( opportunityId.Value );
                breadCrumbs.Add( new BreadCrumb( connectionOpportunity.Name, pageReference ) );
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed)
        {
            string formattedValue = string.Empty;

            Guid?guid = value.AsGuidOrNull();

            if (guid.HasValue)
            {
                var opportunity = new ConnectionOpportunityService(new RockContext()).Get(guid.Value);
                if (opportunity != null)
                {
                    formattedValue = opportunity.Name;
                }
            }

            return(base.FormatValue(parentControl, formattedValue, configurationValues, condensed));
        }
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <BreadCrumb> GetBreadCrumbs(PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            int?opportunityId = PageParameter(pageReference, "OpportunityId").AsIntegerOrNull();

            if (opportunityId != null)
            {
                ConnectionOpportunity connectionOpportunity = new ConnectionOpportunityService(new RockContext()).Get(opportunityId.Value);
                breadCrumbs.Add(new BreadCrumb(connectionOpportunity.Name, pageReference));
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return(breadCrumbs);
        }
        /// <summary>
        /// Determines which item to display based on either the configuration or the connectionOpportunityId that was passed in.
        /// </summary>
        /// <returns>An <see cref="System.Int32"/> of the Id for a <see cref="Rock.Model.ConnectionOpportunity"/> or null if it was not found.</returns>
        private int GetConnectionOpportunityId()
        {
            Guid?connectionOpportunityGuid = GetAttributeValue(AttributeKey.ConnectionOpportunity).AsGuidOrNull();
            int  itemId = default(int);

            // A configured defined type takes precedence over any definedTypeId param value that is passed in.
            if (connectionOpportunityGuid.HasValue)
            {
                var opportunity = new ConnectionOpportunityService(new RockContext()).Get(connectionOpportunityGuid.Value);
                itemId = opportunity.Id;
            }
            else
            {
                itemId = PageParameter(PageParameterKey.OpportunityId).AsInteger();
            }

            return(itemId);
        }
            /// <summary>
            /// Get the entity (group or connection) for this signup
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            public virtual IModel Entity(RockContext context = null)
            {
                if (context == null)
                {
                    context = new RockContext();
                }
                if (EntityTypeGuid == Rock.SystemGuid.EntityType.CONNECTION_OPPORTUNITY.AsGuid())
                {
                    ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(context);
                    return(connectionOpportunityService.Get(EntityGuid));
                }

                if (EntityTypeGuid == Rock.SystemGuid.EntityType.GROUP.AsGuid())
                {
                    GroupService groupService = new GroupService(context);
                    return(groupService.Get(EntityGuid));
                }
                return(null);
            }
        /// <summary>
        /// Get's all of the (get connected/ follow up) *requests* for a given person
        /// </summary>
        /// <param name="currentPerson">The leader</param>
        /// <returns></returns>
        public static IQueryable <ConnectionRequest> GetPeopleInLineFollowUpRequests(Person currentPerson)
        {
            if (currentPerson == null)
            {
                return(new List <ConnectionRequest>().AsQueryable());
            }

            var rockContext = new RockContext();

            var connectionRequestService  = new ConnectionRequestService(rockContext);
            int getConnectedOpportunityId =
                new ConnectionOpportunityService(rockContext).Get(
                    SystemGuid.ConnectionOpportunity.GET_CONNECTED.AsGuid()).Id;
            var connectionRequests = connectionRequestService
                                     .Queryable()
                                     .Where(c => c.ConnectionOpportunityId == getConnectedOpportunityId && c.ConnectorPersonAliasId == currentPerson.PrimaryAliasId && c.ConnectionState == ConnectionState.Active);


            return(connectionRequests);
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection(Type entityType, Control[] controls)
        {
            var selectionConfig             = new SelectionConfig();
            var connectionTypePicker        = controls[0] as RockDropDownList;
            var connectionOpportunityPicker = controls[1] as RockDropDownList;

            var connectionOpportunityId = connectionOpportunityPicker.SelectedValueAsId();
            var connectionTypeId        = connectionTypePicker.SelectedValueAsId();

            if (connectionTypeId.HasValue && connectionOpportunityId.HasValue)
            {
                var connectionOpportunity = new ConnectionOpportunityService(new RockContext()).Get(connectionOpportunityId.Value);
                if (connectionOpportunity != null)
                {
                    selectionConfig.ConnectionTypeGuid        = connectionOpportunity.ConnectionType.Guid;
                    selectionConfig.ConnectionOpportunityGuid = connectionOpportunity.Guid;
                }
            }

            return(selectionConfig.ToJson());
        }
        /// <summary>
        /// Gets the type request counts (TotalCount and AssignedToYouCount) for the
        /// given connection types. The Person the service was initialized with is used to calculate
        /// <see cref="ConnectionRequestCountsViewModel.AssignedToYouCount"/>.
        /// </summary>
        /// <remarks>This method does not check security, it is assumed you have already done so.</remarks>
        /// <param name="connectionTypeIds">The connection type identifiers.</param>
        /// <returns>A dictionary of connection request count objects.</returns>
        public Dictionary <int, ConnectionRequestCountsViewModel> GetConnectionTypeCounts(IEnumerable <int> connectionTypeIds)
        {
            var opportunityClientService = new ConnectionOpportunityClientService(RockContext, Person);

            var opportunities = new ConnectionOpportunityService(RockContext)
                                .Queryable()
                                .Where(o => connectionTypeIds.Contains(o.ConnectionTypeId))
                                .Select(o => new
            {
                o.Id,
                o.ConnectionTypeId
            })
                                .ToList();
            var opportunityIds = opportunities.Select(o => o.Id).ToList();

            var requestCounts = opportunityClientService.GetOpportunityRequestCounts(opportunityIds)
                                .Select(c => new
            {
                TypeId = opportunities.Single(o => o.Id == c.Key).ConnectionTypeId,
                Counts = c.Value
            })
                                .GroupBy(c => c.TypeId)
                                .ToDictionary(g => g.Key, g => new ConnectionRequestCountsViewModel
            {
                AssignedToYouCount = g.Sum(c => c.Counts.AssignedToYouCount),
                TotalCount         = g.Sum(c => c.Counts.TotalCount)
            });

            // Fill in any missing types with empty counts.
            foreach (var typeId in connectionTypeIds)
            {
                if (!requestCounts.ContainsKey(typeId))
                {
                    requestCounts.Add(typeId, new ConnectionRequestCountsViewModel());
                }
            }

            return(requestCounts);
        }
        /// <summary>
        /// Gets the opportunity summary HTML.
        /// </summary>
        /// <param name="opportunitySummaryId">The opportunity summary identifier.</param>
        /// <returns></returns>
        public string GetOpportunitySummaryHtml(OpportunitySummary opportunitySummary)
        {
            var template = GetAttributeValue(AttributeKey.OpportunitySummaryTemplate);

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("OpportunitySummary", opportunitySummary);

            string result = null;

            using (var rockContext = new RockContext())
            {
                var connectionOpportunity = new ConnectionOpportunityService(rockContext).Queryable().AsNoTracking().FirstOrDefault(a => a.Id == opportunitySummary.Id);
                mergeFields.Add("ConnectionOpportunity", connectionOpportunity);

                result = template.ResolveMergeFields(mergeFields);
            }

            return(result);
        }
        /// <summary>
        /// Shows the settings.
        /// </summary>
        protected override void ShowSettings()
        {
            if (Settings.Partitions.Count > 0)
            {
                deactivateTabs();
                liCounts.AddCssClass("active");
                pnlCounts.Visible = true;
            }

            var connectionOpportunityService = new ConnectionOpportunityService(new RockContext());
            var connections = connectionOpportunityService.Queryable().Where(co => co.IsActive == true).OrderBy(co => co.ConnectionType.Name).ThenBy(co => co.Name).ToList()
                              .Select(co => new ListItem(co.ConnectionType.Name + ": " + co.Name, co.Guid.ToString())).ToList();

            connections.Insert(0, new ListItem("Select One . . ."));
            rddlConnection.DataSource     = connections;
            rddlConnection.DataTextField  = "Text";
            rddlConnection.DataValueField = "Value";
            rddlConnection.DataBind();

            if (Settings.EntityGuid != Guid.Empty)
            {
                rddlConnection.SelectedValue = Settings.EntityGuid.ToString();
            }

            if (Settings.EntityTypeGuid == Rock.SystemGuid.EntityType.CONNECTION_OPPORTUNITY.AsGuid())
            {
                rddlType.SelectedValue = "Connection";
                rddlConnection.Visible = true;
            }
            else if (Settings.EntityTypeGuid == Rock.SystemGuid.EntityType.GROUP.AsGuid())
            {
                rddlType.SelectedValue = "Group";
                gpGroup.Visible        = true;
            }


            mdEdit.Show();
        }
        public void LoadContent()
        {
            // get opportunity id
            int opportunityId = -1;

            if ( !string.IsNullOrWhiteSpace( PageParameter( "OpportunityId" ) ) )
            {
                opportunityId = Convert.ToInt32( PageParameter( "OpportunityId" ) );
            }

            if ( opportunityId > 0 )
            {
                RockContext rockContext = new RockContext();
                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );

                bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();

                var qry = connectionOpportunityService
                    .Queryable()
                    .Where( g => g.Id == opportunityId );

                if ( !enableDebug )
                {
                    qry = qry.AsNoTracking();
                }
                var opportunity = qry.FirstOrDefault();

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
                Dictionary<string, object> linkedPages = new Dictionary<string, object>();
                linkedPages.Add( "SignupPage", LinkedPageRoute( "SignupPage" ) );
                mergeFields.Add( "LinkedPages", linkedPages );

                mergeFields.Add( "CampusContext", RockPage.GetCurrentContext( EntityTypeCache.Read( "Rock.Model.Campus" ) ) as Campus );

                // run opportunity summary and details through lava
                opportunity.Summary = opportunity.Summary.ResolveMergeFields(mergeFields);
                opportunity.Description = opportunity.Description.ResolveMergeFields( mergeFields );

                mergeFields.Add( "Opportunity", opportunity );

                // add linked pages

                lOutput.Text = GetAttributeValue( "LavaTemplate" ).ResolveMergeFields( mergeFields );

                if ( GetAttributeValue( "SetPageTitle" ).AsBoolean() )
                {
                    string pageTitle = opportunity.PublicName;
                    RockPage.PageTitle = pageTitle;
                    RockPage.BrowserTitle = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                    RockPage.Header.Title = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                }

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
        }
Example #35
0
        /// <summary>
        /// Adds the connections requests to the system from the given XML element.
        /// </summary>
        /// <example>
        ///   &lt;connections&gt;
        ///       &lt;connection type="Involvement" opportunity="Children's" comment="I would love to help teach kids about Jesus." date="2015-10-11T00:00:00" personGuid="1dfff821-e97c-4324-9883-cf59b5c5bdd6" /&gt;
        ///   &lt;/connections&gt;
        /// </example>
        /// <param name="elemConnections">The elem connections.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddConnections( XElement elemConnections, RockContext rockContext )
        {
            if ( elemConnections == null )
            {
                return;
            }

            ConnectionRequestService crService = new ConnectionRequestService( rockContext );
            ConnectionOpportunityService coService = new ConnectionOpportunityService( rockContext );
            ConnectionTypeService typeService = new ConnectionTypeService( rockContext );
            ConnectionStatusService connectionStatusService = new ConnectionStatusService( rockContext );
            ConnectionStatus noContact = connectionStatusService.Get( "901e1a6a-0e91-4f42-880f-47c061c24e0c".AsGuid() );

            // Find the type and it's corresponding opportunity and then add a connection request for the given person.
            foreach ( var element in elemConnections.Elements( "connection" ) )
            {
                string connectionTypeName = element.Attribute( "type" ).Value.Trim();
                string opportunityName = element.Attribute( "opportunity" ).Value.Trim();
                string comment = element.Attribute( "comment" ).Value.Trim();
                DateTime date = DateTime.Parse( element.Attribute( "date" ).Value.Trim(), new CultureInfo( "en-US" ) );
                Guid personGuid = element.Attribute( "personGuid" ).Value.Trim().AsGuid();

                var connectionOpportunity = coService.Queryable( "ConnectionType" ).AsNoTracking().Where( co => co.ConnectionType.Name == connectionTypeName && co.Name == opportunityName ).FirstOrDefault();

                // make sure we found a matching connection opportunity
                if ( connectionOpportunity != null )
                {
                    ConnectionRequest connectionRequest = new ConnectionRequest()
                    {
                        ConnectionOpportunityId = connectionOpportunity.Id,
                        PersonAliasId = _peopleAliasDictionary[personGuid],
                        Comments = comment,
                        ConnectionStatus = noContact,
                        ConnectionState = global::ConnectionState.Active,
                        CreatedDateTime = date
                    };

                    crService.Add( connectionRequest );
                }
            }
        }
Example #36
0
        /// <summary>
        /// Handles the Click event of the btnEdit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnConnect_Click( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                var opportunityService = new ConnectionOpportunityService( rockContext );
                var connectionRequestService = new ConnectionRequestService( rockContext );
                var personService = new PersonService( rockContext );

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

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

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

                    string firstName = tbFirstName.Text.Trim();
                    string lastName = tbLastName.Text.Trim();
                    string email = tbEmail.Text.Trim();
                    int? campudId = cpCampus.SelectedCampusId;

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

                    else
                    {
                        // Try to find matching person
                        var personMatches = personService.GetByMatch( firstName, lastName, email );
                        if ( personMatches.Count() == 1 )
                        {
                            // If one person with same name and email address exists, use that person
                            person = personMatches.First();
                        }
                    }

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

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

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

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

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

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

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

                        // Now that we have a person, we can create the connection request
                        var connectionRequest = new ConnectionRequest();
                        connectionRequest.PersonAliasId = person.PrimaryAliasId.Value;
                        connectionRequest.Comments = tbComments.Text.Trim();
                        connectionRequest.ConnectionOpportunityId = opportunity.Id;
                        connectionRequest.ConnectionState = ConnectionState.Active;
                        connectionRequest.ConnectionStatusId = defaultStatusId;
                        connectionRequest.CampusId = campudId;

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

                        connectionRequestService.Add( connectionRequest );
                        rockContext.SaveChanges();

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

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

                        pnlSignup.Visible = false;
                    }
                }
            }
        }
Example #37
0
        private void LaunchWorkflow( RockContext rockContext, ConnectionWorkflow connectionWorkflow, string name )
        {
            ConnectionRequest connectionRequest = null;
            if ( ConnectionRequestGuid.HasValue )
            {
                connectionRequest = new ConnectionRequestService( rockContext ).Get( ConnectionRequestGuid.Value );
            }

            var workflowTypeService = new WorkflowTypeService( rockContext );
            var workflowType = workflowTypeService.Get( connectionWorkflow.WorkflowTypeId.Value );
            if ( workflowType != null )
            {
                var workflow = Rock.Model.Workflow.Activate( workflowType, name );

                if ( workflow.AttributeValues != null )
                {
                    if ( workflow.AttributeValues.ContainsKey( "ConnectionOpportunity" ) )
                    {
                        var connectionOpportunity = new ConnectionOpportunityService( rockContext ).Get( ConnectionOpportunityId.Value );
                        if ( connectionOpportunity != null )
                        {
                            workflow.AttributeValues["ConnectionOpportunity"].Value = connectionOpportunity.Guid.ToString();
                        }
                    }

                    if ( workflow.AttributeValues.ContainsKey( "ConnectionType" ) )
                    {
                        var connectionType = new ConnectionTypeService( rockContext ).Get( ConnectionTypeId.Value );
                        if ( connectionType != null )
                        {
                            workflow.AttributeValues["ConnectionType"].Value = connectionType.Guid.ToString();
                        }
                    }

                    if ( workflow.AttributeValues.ContainsKey( "ConnectionRequest" ) )
                    {
                        if ( connectionRequest != null )
                        {
                            workflow.AttributeValues["ConnectionRequest"].Value = connectionRequest.Guid.ToString();
                        }
                    }

                    if ( workflow.AttributeValues.ContainsKey( "Person" ) )
                    {
                        var person = new PersonService( rockContext ).Get( PersonId.Value );
                        if ( person != null )
                        {
                            workflow.AttributeValues["Person"].Value = person.PrimaryAlias.Guid.ToString();
                        }
                    }
                }

                List<string> workflowErrors;
                new WorkflowService( rockContext ).Process( workflow, connectionRequest, out workflowErrors );
                if ( workflow.Id != 0 )
                {
                    ConnectionRequestWorkflow connectionRequestWorkflow = new ConnectionRequestWorkflow();
                    connectionRequestWorkflow.ConnectionRequestId = connectionRequest.Id;
                    connectionRequestWorkflow.WorkflowId = workflow.Id;
                    connectionRequestWorkflow.ConnectionWorkflowId = connectionWorkflow.Id;
                    connectionRequestWorkflow.TriggerType = connectionWorkflow.TriggerType;
                    connectionRequestWorkflow.TriggerQualifier = connectionWorkflow.QualifierValue;
                    new ConnectionRequestWorkflowService( rockContext ).Add( connectionRequestWorkflow );
                    rockContext.SaveChanges();
                }
            }
        }
        public void LoadContent()
        {
            // get opportunity id
            int opportunityId = -1;

            if ( !string.IsNullOrWhiteSpace( PageParameter( "OpportunityId" ) ) )
            {
                opportunityId = Convert.ToInt32( PageParameter( "OpportunityId" ) );
            }

            if ( opportunityId > 0 )
            {
                RockContext rockContext = new RockContext();
                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );

                bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();

                var qry = connectionOpportunityService
                    .Queryable()
                    .Where( g => g.Id == opportunityId );

                if ( !enableDebug )
                {
                    qry = qry.AsNoTracking();
                }
                var opportunity = qry.FirstOrDefault();

                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "Opportunity", opportunity );

                // add linked pages
                Dictionary<string, object> linkedPages = new Dictionary<string, object>();
                linkedPages.Add( "SignupPage", LinkedPageUrl( "SignupPage", null ) );
                mergeFields.Add( "LinkedPages", linkedPages );

                mergeFields.Add( "CurrentPerson", CurrentPerson );

                var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( CurrentPerson );
                globalAttributeFields.ToList().ForEach( d => mergeFields.Add( d.Key, d.Value ) );

                lOutput.Text = GetAttributeValue( "LavaTemplate" ).ResolveMergeFields( mergeFields );

                if ( GetAttributeValue( "SetPageTitle" ).AsBoolean() )
                {
                    string pageTitle = opportunity.PublicName;
                    RockPage.PageTitle = pageTitle;
                    RockPage.BrowserTitle = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                    RockPage.Header.Title = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                }

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
        }
 /// <summary>
 /// Handles the Edit event of the gConnectionOpportunities 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 gConnectionOpportunities_Edit( object sender, RowEventArgs e )
 {
     using ( RockContext rockContext = new RockContext() )
     {
         ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
         ConnectionOpportunity connectionOpportunity = connectionOpportunityService.Get( e.RowKeyId );
         if ( connectionOpportunity != null )
         {
             NavigateToLinkedPage( "DetailPage", "ConnectionOpportunityId", connectionOpportunity.Id, "ConnectionTypeId", _connectionType.Id );
         }
     }
 }
Example #40
0
        /// <summary>
        /// Shows the opportunity attributes.
        /// </summary>
        private void ShowOpportunityAttributes()
        {
            wpAttributes.Visible = false;
            phAttributes.Controls.Clear();

            ConnectionOpportunity connectionOpportunity;
            int connectionOpportunityId = PageParameter( "ConnectionOpportunityId" ).AsInteger();
            if ( connectionOpportunityId == 0 )
            {
                connectionOpportunity = new ConnectionOpportunity { ConnectionTypeId = PageParameter( "ConnectionTypeId" ).AsInteger() };
            }
            else
            {
                connectionOpportunity = new ConnectionOpportunityService( new RockContext() ).Get( connectionOpportunityId );
            }

            connectionOpportunity.LoadAttributes();
            if ( connectionOpportunity.Attributes != null && connectionOpportunity.Attributes.Any() )
            {
                wpAttributes.Visible = true;
                if ( !Page.IsPostBack )
                {
                    Rock.Attribute.Helper.AddEditControls( connectionOpportunity, phAttributes, true, BlockValidationGroup );
                }
                else
                {
                    Rock.Attribute.Helper.AddEditControls( connectionOpportunity, phAttributes, false, BlockValidationGroup );
                }
            }
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="connectionRequestId">The connection request identifier.</param>
        /// <param name="connectionOpportunityId">The connectionOpportunity id.</param>
        public void ShowDetail( int connectionRequestId, int? connectionOpportunityId )
        {
            bool editAllowed = UserCanEdit;

            // autoexpand the person picker if this is an add
            this.Page.ClientScript.RegisterStartupScript(
                this.GetType(),
                "StartupScript", @"Sys.Application.add_load(function () {

                // if the person picker is empty then open it for quick entry
                var personPicker = $('.js-authorizedperson');
                var currentPerson = personPicker.find('.picker-selectedperson').html();
                if (currentPerson != null && currentPerson.length == 0) {
                    $(personPicker).find('a.picker-label').trigger('click');
                }

            });", true );

            using ( var rockContext = new RockContext() )
            {
                var connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                var connectionRequestService = new ConnectionRequestService( rockContext );
                var connectionStatusService = new ConnectionStatusService( rockContext );

                ConnectionOpportunity connectionOpportunity = null;
                ConnectionRequest connectionRequest = null;

                if ( connectionRequestId > 0 )
                {
                    connectionRequest = new ConnectionRequestService( rockContext ).Get( connectionRequestId );
                }

                if ( connectionRequest == null )
                {
                    connectionOpportunity = connectionOpportunityService.Get( connectionOpportunityId.Value );
                    if ( connectionOpportunity != null )
                    {
                        var connectionStatus = connectionStatusService
                            .Queryable()
                            .Where( s =>
                                s.ConnectionTypeId == connectionOpportunity.ConnectionTypeId &&
                                s.IsDefault )
                            .FirstOrDefault();

                        if ( connectionStatus != null )
                        {
                            connectionRequest = new ConnectionRequest();
                            connectionRequest.ConnectionOpportunity = connectionOpportunity;
                            connectionRequest.ConnectionOpportunityId = connectionOpportunity.Id;
                            connectionRequest.ConnectionState = ConnectionState.Active;
                            connectionRequest.ConnectionStatus = connectionStatus;
                            connectionRequest.ConnectionStatusId = connectionStatus.Id;

                            int? campusId = GetUserPreference( CAMPUS_SETTING ).AsIntegerOrNull();
                            if ( campusId.HasValue )
                            {
                                connectionRequest.CampusId = campusId.Value;
                            }
                        }
                    }
                }
                else
                {
                    connectionOpportunity = connectionRequest.ConnectionOpportunity;
                }

                if ( connectionOpportunity != null && connectionRequest != null )
                {
                    hfConnectionOpportunityId.Value = connectionRequest.ConnectionOpportunityId.ToString();
                    hfConnectionRequestId.Value = connectionRequest.Id.ToString();
                    lConnectionOpportunityIconHtml.Text = string.Format( "<i class='{0}' ></i>", connectionOpportunity.IconCssClass );

                    pnlReadDetails.Visible = true;

                    if ( connectionRequest.PersonAlias != null && connectionRequest.PersonAlias.Person != null )
                    {
                        lTitle.Text = connectionRequest.PersonAlias.Person.FullName.FormatAsHtmlTitle();
                    }
                    else
                    {
                        lTitle.Text = String.Format( "New {0} Connection Request", connectionOpportunity.Name );
                    }

                    // Only users that have Edit rights to block, or edit rights to the opportunity
                    if ( !editAllowed )
                    {
                        editAllowed = connectionRequest.IsAuthorized( Authorization.EDIT, CurrentPerson );
                    }

                    // Grants edit access to those in the opportunity's connector groups
                    if ( !editAllowed && CurrentPersonId.HasValue )
                    {
                        // Grant edit access to any of those in a non campus-specific connector group
                        editAllowed = connectionOpportunity.ConnectionOpportunityConnectorGroups
                            .Any( g =>
                                !g.CampusId.HasValue &&
                                g.ConnectorGroup != null &&
                                g.ConnectorGroup.Members.Any( m => m.PersonId == CurrentPersonId ) );

                        if ( !editAllowed )
                        {
                            //If this is a new request, grant edit access to any connector group. Otherwise, match the request's campus to the corresponding campus-specific connector group
                            foreach ( var groupCampus in connectionOpportunity
                                .ConnectionOpportunityConnectorGroups
                                .Where( g =>
                                    ( connectionRequest.Id == 0 || ( connectionRequest.CampusId.HasValue && g.CampusId == connectionRequest.CampusId.Value ) ) &&
                                    g.ConnectorGroup != null &&
                                    g.ConnectorGroup.Members.Any( m => m.PersonId == CurrentPersonId ) ) )
                            {
                                editAllowed = true;
                                break;
                            }
                        }
                    }

                    lbConnect.Visible = editAllowed;
                    lbEdit.Visible = editAllowed;
                    lbTransfer.Visible = editAllowed;
                    gConnectionRequestActivities.IsDeleteEnabled = editAllowed;
                    gConnectionRequestActivities.Actions.ShowAdd = editAllowed;

                    if ( !editAllowed )
                    {
                        // User is not authorized
                        nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( ConnectionRequest.FriendlyTypeName );
                        ShowReadonlyDetails( connectionRequest );
                    }
                    else
                    {
                        nbEditModeMessage.Text = string.Empty;
                        if ( connectionRequest.Id > 0 )
                        {
                            ShowReadonlyDetails( connectionRequest );
                        }
                        else
                        {
                            ShowEditDetails( connectionRequest, rockContext );
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            Guid? guid = value.AsGuidOrNull();
            if (guid.HasValue)
            {
                var opportunity = new ConnectionOpportunityService( new RockContext() ).Get( guid.Value );
                if ( opportunity != null )
                {
                    formattedValue = opportunity.Name;
                }
            }

            return base.FormatValue( parentControl, formattedValue, configurationValues, condensed );
        }
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var rockContext = new RockContext();
            var breadCrumbs = new List<BreadCrumb>();

            ConnectionRequest connectionRequest = null;

            int? requestId = PageParameter( "ConnectionRequestId" ).AsIntegerOrNull();
            if ( requestId.HasValue && requestId.Value > 0 )
            {
                connectionRequest = new ConnectionRequestService( rockContext ).Get( requestId.Value );
            }

            if ( connectionRequest != null )
            {
                breadCrumbs.Add( new BreadCrumb( connectionRequest.PersonAlias.Person.FullName, pageReference ) );
            }
            else
            {
                var connectionOpportunity = new ConnectionOpportunityService( rockContext ).Get( PageParameter( "ConnectionOpportunityId" ).AsInteger() );
                if ( connectionOpportunity != null )
                {
                    breadCrumbs.Add( new BreadCrumb( String.Format( "New {0} Connection Request", connectionOpportunity.Name ), pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Connection Request", pageReference ) );
                }
            }

            return breadCrumbs;
        }
Example #44
0
        /// <summary>
        /// Binds the event calendar items grid.
        /// </summary>
        protected void BindConnectionOpportunitiesGrid()
        {
            if ( _connectionType != null )
            {
                pnlConnectionOpportunities.Visible = true;

                rFilter.Visible = true;
                gConnectionOpportunities.Visible = true;

                var rockContext = new RockContext();

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                var qry = connectionOpportunityService.Queryable()
                    .Where( o => o.ConnectionTypeId == _connectionType.Id );

                // Filter by Active Only
                if ( cbActive.Checked )
                {
                    qry = qry.Where( o => o.IsActive );
                }

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

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

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

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

                List<ConnectionOpportunity> connectionOpportunities = null;
                if ( sortProperty != null )
                {
                    connectionOpportunities = qry.Sort( sortProperty ).ToList();
                }
                else
                {
                    connectionOpportunities = qry.ToList().OrderByDescending( a => a.Name ).ToList();
                }

                gConnectionOpportunities.ObjectList = new Dictionary<string, object>();
                connectionOpportunities.ForEach( m => gConnectionOpportunities.ObjectList.Add( m.Id.ToString(), m ) );
                gConnectionOpportunities.EntityTypeId = EntityTypeCache.Read( "Rock.Model.ConnectionOpportunity" ).Id;

                gConnectionOpportunities.DataSource = connectionOpportunities.Select( o => new
                {
                    o.Id,
                    o.Guid,
                    Name = o.Name,
                    GroupType = o.GroupType.Name,
                    Active = o.IsActive ? "<span class='label label-success'>Active</span>" : "<span class='label label-campus'>Inactive</span>"

                } ).ToList();

                gConnectionOpportunities.DataBind();
            }
            else
            {
                pnlConnectionOpportunities.Visible = false;
            }
        }
        /// <summary>
        /// Gets the summary data.
        /// </summary>
        private void GetSummaryData()
        {
            SummaryState = new List<ConnectionTypeSummary>();

            var rockContext = new RockContext();
            var opportunities = new ConnectionOpportunityService( rockContext )
                .Queryable().AsNoTracking();

            var typeFilter = GetAttributeValue( "ConnectionTypes" ).SplitDelimitedValues().AsGuidList();
            if ( typeFilter.Any() )
            {
                opportunities = opportunities.Where( o => typeFilter.Contains( o.ConnectionType.Guid ) );
            }

            // Loop through opportunities
            foreach ( var opportunity in opportunities )
            {
                // Check to see if person can view the opportunity because of admin rights to this block or admin rights to
                // the opportunity
                bool canView = UserCanAdministrate || opportunity.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson );
                bool campusSpecificConnector = false;
                var campusIds = new List<int>();

                if ( CurrentPersonId.HasValue )
                {
                    // Check to see if person belongs to any connector group that is not campus specific
                    if ( !canView )
                    {
                        canView = opportunity
                            .ConnectionOpportunityConnectorGroups
                            .Any( g =>
                                !g.CampusId.HasValue &&
                                g.ConnectorGroup != null &&
                                g.ConnectorGroup.Members.Any( m => m.PersonId == CurrentPersonId.Value ) );
                    }

                    // If user is not yet authorized to view the opportunity, check to see if they are a member of one of the
                    // campus-specific connector groups for the opportunity, and note the campus
                    if ( !canView )
                    {
                        foreach ( var groupCampus in opportunity
                            .ConnectionOpportunityConnectorGroups
                            .Where( g =>
                                g.CampusId.HasValue &&
                                g.ConnectorGroup != null &&
                                g.ConnectorGroup.Members.Any( m => m.PersonId == CurrentPersonId.Value ) ) )
                        {
                            campusSpecificConnector = true;
                            canView = true;
                            campusIds.Add( groupCampus.CampusId.Value );
                        }
                    }
                }

                // Is user is authorized to view this opportunity type...
                if ( canView )
                {
                    // Check if the opportunity's type has been added to summary yet, and if not, add it
                    var connectionTypeSummary = SummaryState.Where( c => c.Id == opportunity.ConnectionTypeId ).FirstOrDefault();
                    if ( connectionTypeSummary == null )
                    {
                        connectionTypeSummary = new ConnectionTypeSummary
                        {
                            Id = opportunity.ConnectionTypeId,
                            Name = opportunity.ConnectionType.Name,
                            Opportunities = new List<OpportunitySummary>()
                        };
                        SummaryState.Add( connectionTypeSummary );
                    }

                    // Count number of idle requests (no activity in past X days)

                    var connectionRequestsQry = new ConnectionRequestService( rockContext ).Queryable().Where( a => a.ConnectionOpportunityId == opportunity.Id );
                    var currentDateTime = RockDateTime.Now;
                    int activeRequestCount = connectionRequestsQry
                        .Where( cr =>
                                cr.ConnectionState == ConnectionState.Active
                                || ( cr.ConnectionState == ConnectionState.FutureFollowUp && cr.FollowupDate.HasValue && cr.FollowupDate.Value < _midnightToday )
                        )
                        .Count();

                    // only show if the oppportunity is active and there are active requests
                    if ( opportunity.IsActive || ( !opportunity.IsActive && activeRequestCount > 0 ) )
                    {
                        // idle count is:
                        //  (the request is active OR future follow-up who's time has come)
                        //  AND
                        //  (where the activity is more than DaysUntilRequestIdle days old OR no activity but created more than DaysUntilRequestIdle days ago)
                        int idleCount = connectionRequestsQry
                                        .Where( cr =>
                                            (
                                                cr.ConnectionState == ConnectionState.Active
                                                || ( cr.ConnectionState == ConnectionState.FutureFollowUp && cr.FollowupDate.HasValue && cr.FollowupDate.Value < _midnightToday )
                                            )
                                            &&
                                            (
                                                ( cr.ConnectionRequestActivities.Any() && cr.ConnectionRequestActivities.Max( ra => ra.CreatedDateTime ) < SqlFunctions.DateAdd( "day", -cr.ConnectionOpportunity.ConnectionType.DaysUntilRequestIdle, currentDateTime ) )
                                                || ( !cr.ConnectionRequestActivities.Any() && cr.CreatedDateTime < SqlFunctions.DateAdd( "day", -cr.ConnectionOpportunity.ConnectionType.DaysUntilRequestIdle, currentDateTime ) )
                                            )
                                        )
                                        .Count();

                        // Count the number requests that have a status that is considered critical.
                        int criticalCount = connectionRequestsQry
                                                .Where( r =>
                                                    r.ConnectionStatus.IsCritical
                                                    && (
                                                            r.ConnectionState == ConnectionState.Active
                                                            || ( r.ConnectionState == ConnectionState.FutureFollowUp && r.FollowupDate.HasValue && r.FollowupDate.Value < _midnightToday )
                                                       )
                                                )
                                                .Count();

                        // Add the opportunity
                        var opportunitySummary = new OpportunitySummary
                        {
                            Id = opportunity.Id,
                            Name = opportunity.Name,
                            IsActive = opportunity.IsActive,
                            IconCssClass = opportunity.IconCssClass,
                            IdleCount = idleCount,
                            CriticalCount = criticalCount
                        };

                        // If the user is limited requests with specific campus(es) set the list, otherwise leave it to be null
                        opportunitySummary.CampusSpecificConnector = campusSpecificConnector;
                        opportunitySummary.ConnectorCampusIds = campusIds.Distinct().ToList();

                        connectionTypeSummary.Opportunities.Add( opportunitySummary );
                    }
                }
            }

            // Get a list of all the authorized opportunity ids
            var allOpportunities = SummaryState.SelectMany( s => s.Opportunities ).Select( o => o.Id ).Distinct().ToList();

            // Get all the active and past-due future followup request ids, and include the campus id and personid of connector
            var midnightToday = RockDateTime.Today.AddDays(1);
            var activeRequests = new ConnectionRequestService( rockContext )
                .Queryable().AsNoTracking()
                .Where( r =>
                    allOpportunities.Contains( r.ConnectionOpportunityId ) &&
                    ( r.ConnectionState == ConnectionState.Active ||
                        ( r.ConnectionState == ConnectionState.FutureFollowUp && r.FollowupDate.HasValue && r.FollowupDate.Value < midnightToday ) ) )
                .Select( r => new
                {
                    r.ConnectionOpportunityId,
                    r.CampusId,
                    ConnectorPersonId = r.ConnectorPersonAlias != null ? r.ConnectorPersonAlias.PersonId : -1
                } )
                .ToList();

            // Based on the active requests, set additional properties for each opportunity
            foreach ( var opportunity in SummaryState.SelectMany( s => s.Opportunities ) )
            {
                // Get the active requests for this opportunity that user is authorized to view (based on campus connector)
                var opportunityRequests = activeRequests
                    .Where( r =>
                        r.ConnectionOpportunityId == opportunity.Id &&
                        (
                            !opportunity.CampusSpecificConnector ||
                            ( r.CampusId.HasValue && opportunity.ConnectorCampusIds.Contains( r.CampusId.Value ) )
                        ) )
                    .ToList();

                // The count of active requests assigned to the current person
                opportunity.AssignedToYou = opportunityRequests.Count( r => r.ConnectorPersonId == CurrentPersonId );

                // The count of active requests that are unassigned
                opportunity.UnassignedCount = opportunityRequests.Count( r => r.ConnectorPersonId == -1 );

                // Flag indicating if current user is connector for any of the active types
                opportunity.HasActiveRequestsForConnector = opportunityRequests.Any( r => r.ConnectorPersonId == CurrentPersonId );
            }

            //Set the Idle tooltip
            var connectionTypes = opportunities.Where( o => allOpportunities.Contains( o.Id ) ).Select( o => o.ConnectionType ).Distinct().ToList();
            StringBuilder sb = new StringBuilder();
            if ( connectionTypes.Select( t => t.DaysUntilRequestIdle ).Distinct().Count() == 1 )
            {
                sb.Append( String.Format( "Idle (no activity in {0} days)", connectionTypes.Select( t => t.DaysUntilRequestIdle ).Distinct().First() ) );
            }
            else
            {
                sb.Append( "Idle (no activity in several days)<br/><ul class='list-unstyled'>" );
                foreach ( var connectionType in connectionTypes )
                {
                    sb.Append( String.Format( "<li>{0}: {1} days</li>", connectionType.Name, connectionType.DaysUntilRequestIdle ) );
                }
                sb.Append( "</ul>" );
            }

            var statusTemplate = this.GetAttributeValue( "StatusTemplate" );
            var statusMergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage);
            statusMergeFields.Add( "ConnectionOpportunities", allOpportunities );
            statusMergeFields.Add( "ConnectionTypes", connectionTypes );
            statusMergeFields.Add( "IdleTooltip", sb.ToString() );
            lStatusBarContent.Text = statusTemplate.ResolveMergeFields( statusMergeFields );
            BindSummaryData();
        }
        /// <summary>
        /// Execute method to check for any workflows to launch.
        /// </summary>
        public void Execute()
        {
            // Verify that valid ids were saved
            if ( ConnectionRequestId.HasValue )
            {
                // Get all the connectionWorkflows from cache
                var cachedWorkflows = ConnectionWorkflowService.GetCachedTriggers();

                // If any connectionWorkflows exist
                if ( cachedWorkflows != null && cachedWorkflows.Any() )
                {
                    // Get the connectionWorkflows associated to the connection
                    var workflows = cachedWorkflows
                        .Where( w =>
                            w.TriggerType == ConnectionWorkflowTriggerType.ActivityAdded &&
                            (
                                ( w.ConnectionOpportunityId.HasValue && w.ConnectionOpportunityId.Value == ConnectionOpportunityId.Value ) ||
                                ( w.ConnectionTypeId.HasValue )
                            )
                        )
                        .ToList();

                    if ( workflows.Any() )
                    {
                        using ( var rockContext = new RockContext() )
                        {
                            // Get the current txn's connection type id
                            var ConnectionTypeId = new ConnectionOpportunityService( rockContext )
                                .Queryable().AsNoTracking()
                                .Where( o => o.Id == ConnectionOpportunityId.Value )
                                .Select( o => o.ConnectionTypeId )
                                .FirstOrDefault();

                            // Further filter the connection type connectionWorkflows by the connection type id
                            workflows = workflows
                                .Where( w =>
                                    ( w.ConnectionOpportunityId.HasValue && w.ConnectionOpportunityId.Value == ConnectionOpportunityId.Value ) ||
                                    ( w.ConnectionTypeId.HasValue && w.ConnectionTypeId.Value == ConnectionTypeId ) )
                                .ToList();

                            // Loop through connectionWorkflows and lauch appropriate workflow
                            foreach ( var connectionWorkflow in workflows )
                            {
                                if ( QualifiersMatch( rockContext, connectionWorkflow, ConnectionActivityTypeId ) )
                                {
                                    LaunchWorkflow( rockContext, connectionWorkflow, "Activity Added" );
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <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 )
        {
            ConnectionOpportunity connectionOpportunity = null;

            using ( RockContext rockContext = new RockContext() )
            {
                if ( !ValidPlacementGroups() )
                {
                    return;
                }

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                EventCalendarItemService eventCalendarItemService = new EventCalendarItemService( rockContext );
                ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext );
                ConnectionRequestWorkflowService connectionRequestWorkflowService = new ConnectionRequestWorkflowService( rockContext );
                ConnectionOpportunityConnectorGroupService connectionOpportunityConnectorGroupsService = new ConnectionOpportunityConnectorGroupService( rockContext );
                ConnectionOpportunityCampusService connectionOpportunityCampusService = new ConnectionOpportunityCampusService( rockContext );
                ConnectionOpportunityGroupConfigService connectionOpportunityGroupConfigService = new ConnectionOpportunityGroupConfigService( rockContext );
                ConnectionOpportunityGroupService connectionOpportunityGroupService = new ConnectionOpportunityGroupService( rockContext );

                int connectionOpportunityId = hfConnectionOpportunityId.ValueAsInt();
                if ( connectionOpportunityId != 0 )
                {
                    connectionOpportunity = connectionOpportunityService
                        .Queryable( "ConnectionOpportunityGroups, ConnectionWorkflows" )
                        .Where( ei => ei.Id == connectionOpportunityId )
                        .FirstOrDefault();
                }

                if ( connectionOpportunity == null )
                {
                    connectionOpportunity = new ConnectionOpportunity();
                    connectionOpportunity.Name = string.Empty;
                    connectionOpportunity.ConnectionTypeId = PageParameter( "ConnectionTypeId" ).AsInteger();
                    connectionOpportunityService.Add( connectionOpportunity );
                }

                connectionOpportunity.Name = tbName.Text;
                connectionOpportunity.Summary = htmlSummary.Text;
                connectionOpportunity.Description = htmlDescription.Text;
                connectionOpportunity.IsActive = cbIsActive.Checked;
                connectionOpportunity.PublicName = tbPublicName.Text;
                connectionOpportunity.IconCssClass = tbIconCssClass.Text;

                int? orphanedPhotoId = null;
                if ( imgupPhoto.BinaryFileId != null )
                {
                    if ( connectionOpportunity.PhotoId != imgupPhoto.BinaryFileId )
                    {
                        orphanedPhotoId = connectionOpportunity.PhotoId;
                    }
                    connectionOpportunity.PhotoId = imgupPhoto.BinaryFileId.Value;
                }

                // remove any workflows that removed in the UI
                var uiWorkflows = WorkflowsState.Where( w => w.ConnectionTypeId == null ).Select( l => l.Guid );
                foreach ( var connectionWorkflow in connectionOpportunity.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() )
                {
                    foreach( var requestWorkflow in connectionRequestWorkflowService.Queryable()
                        .Where( w => w.ConnectionWorkflowId == connectionWorkflow.Id ) )
                    {
                        connectionRequestWorkflowService.Delete( requestWorkflow );
                    }

                    connectionOpportunity.ConnectionWorkflows.Remove( connectionWorkflow );
                    connectionWorkflowService.Delete( connectionWorkflow );
                }

                // Add or Update workflows from the UI
                foreach ( var workflowTypeStateObj in WorkflowsState.Where( w => w.ConnectionTypeId == null ) )
                {
                    ConnectionWorkflow connectionOpportunityWorkflow = connectionOpportunity.ConnectionWorkflows.Where( a => a.Guid == workflowTypeStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityWorkflow == null )
                    {
                        connectionOpportunityWorkflow = new ConnectionWorkflow();
                        connectionOpportunity.ConnectionWorkflows.Add( connectionOpportunityWorkflow );
                    }
                    connectionOpportunityWorkflow.Id = workflowTypeStateObj.Id;
                    connectionOpportunityWorkflow.Guid = workflowTypeStateObj.Guid;
                    connectionOpportunityWorkflow.ConnectionTypeId = workflowTypeStateObj.ConnectionTypeId;
                    connectionOpportunityWorkflow.WorkflowTypeId = workflowTypeStateObj.WorkflowTypeId;
                    connectionOpportunityWorkflow.TriggerType = workflowTypeStateObj.TriggerType;
                    connectionOpportunityWorkflow.QualifierValue = workflowTypeStateObj.QualifierValue;
                    connectionOpportunityWorkflow.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // remove any group campuses that removed in the UI
                var uiConnectorGroups = ConnectorGroupsState.Select( l => l.Guid );
                foreach ( var connectionOpportunityConnectorGroups in connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( l => !uiConnectorGroups.Contains( l.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityConnectorGroups.Remove( connectionOpportunityConnectorGroups );
                    connectionOpportunityConnectorGroupsService.Delete( connectionOpportunityConnectorGroups );
                }

                // Add or Update group campuses from the UI
                foreach ( var groupStateObj in ConnectorGroupsState )
                {
                    ConnectionOpportunityConnectorGroup connectionOpportunityConnectorGroup = connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( a => a.Guid == groupStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityConnectorGroup == null )
                    {
                        connectionOpportunityConnectorGroup = new ConnectionOpportunityConnectorGroup();
                        connectionOpportunity.ConnectionOpportunityConnectorGroups.Add( connectionOpportunityConnectorGroup );
                    }

                    connectionOpportunityConnectorGroup.CampusId = groupStateObj.CampusId;
                    connectionOpportunityConnectorGroup.ConnectorGroupId = groupStateObj.GroupId;
                    connectionOpportunityConnectorGroup.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // remove any campuses that removed in the UI
                var uiCampuses = cblSelectedItemsAsInt( cblCampus );
                foreach ( var connectionOpportunityCampus in connectionOpportunity.ConnectionOpportunityCampuses.Where( c => !uiCampuses.Contains( c.CampusId ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityCampuses.Remove( connectionOpportunityCampus );
                    connectionOpportunityCampusService.Delete( connectionOpportunityCampus );
                }

                // Add or Update campuses from the UI
                foreach ( var campusId in uiCampuses )
                {
                    ConnectionOpportunityCampus connectionOpportunityCampus = connectionOpportunity.ConnectionOpportunityCampuses.Where( c => c.CampusId == campusId ).FirstOrDefault();
                    if ( connectionOpportunityCampus == null )
                    {
                        connectionOpportunityCampus = new ConnectionOpportunityCampus();
                        connectionOpportunity.ConnectionOpportunityCampuses.Add( connectionOpportunityCampus );
                    }

                    connectionOpportunityCampus.CampusId = campusId;
                    connectionOpportunityCampus.DefaultConnectorPersonAliasId = DefaultConnectors.ContainsKey( campusId ) ? DefaultConnectors[campusId] : (int?)null;
                }

                // remove any group configs that were removed in the UI
                var uiGroupConfigs = GroupConfigsState.Select( r => r.Guid );
                foreach ( var connectionOpportunityGroupConfig in connectionOpportunity.ConnectionOpportunityGroupConfigs.Where( r => !uiGroupConfigs.Contains( r.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityGroupConfigs.Remove( connectionOpportunityGroupConfig );
                    connectionOpportunityGroupConfigService.Delete( connectionOpportunityGroupConfig );
                }

                // Add or Update group configs from the UI
                foreach ( var groupConfigStateObj in GroupConfigsState )
                {
                    ConnectionOpportunityGroupConfig connectionOpportunityGroupConfig = connectionOpportunity.ConnectionOpportunityGroupConfigs.Where( a => a.Guid == groupConfigStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityGroupConfig == null )
                    {
                        connectionOpportunityGroupConfig = new ConnectionOpportunityGroupConfig();
                        connectionOpportunity.ConnectionOpportunityGroupConfigs.Add( connectionOpportunityGroupConfig );
                    }

                    connectionOpportunityGroupConfig.GroupTypeId = groupConfigStateObj.GroupTypeId;
                    connectionOpportunityGroupConfig.GroupMemberRoleId = groupConfigStateObj.GroupMemberRoleId;
                    connectionOpportunityGroupConfig.GroupMemberStatus = groupConfigStateObj.GroupMemberStatus;
                    connectionOpportunityGroupConfig.UseAllGroupsOfType = groupConfigStateObj.UseAllGroupsOfType;

                    connectionOpportunityGroupConfig.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // Remove any groups that were removed in the UI
                var uiGroups = GroupsState.Select( r => r.Guid );
                foreach ( var connectionOpportunityGroup in connectionOpportunity.ConnectionOpportunityGroups.Where( r => !uiGroups.Contains( r.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityGroups.Remove( connectionOpportunityGroup );
                    connectionOpportunityGroupService.Delete( connectionOpportunityGroup );
                }

                // Add or Update groups from the UI
                foreach ( var groupStateObj in GroupsState )
                {
                    ConnectionOpportunityGroup connectionOpportunityGroup = connectionOpportunity.ConnectionOpportunityGroups.Where( a => a.Guid == groupStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityGroup == null )
                    {
                        connectionOpportunityGroup = new ConnectionOpportunityGroup();
                        connectionOpportunity.ConnectionOpportunityGroups.Add( connectionOpportunityGroup );
                    }

                    connectionOpportunityGroup.GroupId = groupStateObj.GroupId;
                    connectionOpportunityGroup.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                connectionOpportunity.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues( phAttributes, connectionOpportunity );

                if ( !Page.IsValid )
                {
                    return;
                }

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

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();

                    connectionOpportunity.SaveAttributeValues( rockContext );

                    if ( orphanedPhotoId.HasValue )
                    {
                        BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                        var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                        if ( binaryFile != null )
                        {
                            string errorMessage;
                            if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                            {
                                binaryFileService.Delete( binaryFile );
                                rockContext.SaveChanges();
                            }
                        }
                    }
                } );

                ConnectionWorkflowService.FlushCachedTriggers();

                var qryParams = new Dictionary<string, string>();
                qryParams["ConnectionTypeId"] = PageParameter( "ConnectionTypeId" );
                NavigateToParentPage( qryParams );
            }
        }
        /// <summary>
        /// Binds the event calendar items grid.
        /// </summary>
        protected void BindConnectionOpportunitiesGrid()
        {
            if ( _connectionType != null )
            {
                pnlConnectionOpportunities.Visible = true;

                rFilter.Visible = true;
                gConnectionOpportunities.Visible = true;

                var rockContext = new RockContext();

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                var qry = connectionOpportunityService.Queryable()
                    .Where( o => o.ConnectionTypeId == _connectionType.Id );

                // Filter by Active Only
                if ( cbActive.Checked )
                {
                    qry = qry.Where( o => o.IsActive );
                }

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

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

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

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

                List<ConnectionOpportunity> connectionOpportunities = null;
                if ( sortProperty != null )
                {
                    connectionOpportunities = qry.Sort( sortProperty ).ToList();
                }
                else
                {
                    connectionOpportunities = qry.ToList().OrderBy( a => a.Name ).ToList();
                }

                gConnectionOpportunities.DataSource = connectionOpportunities;
                gConnectionOpportunities.DataBind();
            }
            else
            {
                pnlConnectionOpportunities.Visible = false;
            }
        }
        /// <summary>
        /// Updates the list.
        /// </summary>
        private void UpdateList()
        {
            using ( var rockContext = new RockContext() )
            {
                var searchSelections = new Dictionary<string, string>();

                var connectionTypeId = GetAttributeValue( "ConnectionTypeId" ).AsInteger();
                var connectionType = new ConnectionTypeService( rockContext ).Get( connectionTypeId );
                var connectionOpportunityService = new ConnectionOpportunityService( rockContext );

                var qrySearch = connectionOpportunityService.Queryable().Where( a => a.ConnectionTypeId == connectionTypeId && a.IsActive == true ).ToList();

                if ( GetAttributeValue( "DisplayNameFilter" ).AsBoolean() )
                {
                    if ( !string.IsNullOrWhiteSpace( tbSearchName.Text ) )
                    {
                        searchSelections.Add( "tbSearchName", tbSearchName.Text );
                        var searchTerms = tbSearchName.Text.ToLower().SplitDelimitedValues( true );
                        qrySearch = qrySearch.Where( o => searchTerms.Any( t => t.Contains( o.Name.ToLower() ) || o.Name.ToLower().Contains( t ) ) ).ToList();
                    }
                }

                if ( GetAttributeValue( "DisplayCampusFilter" ).AsBoolean() )
                {
                    var searchCampuses = cblCampus.SelectedValuesAsInt;
                    if ( searchCampuses.Count > 0 )
                    {
                        searchSelections.Add( "cblCampus", searchCampuses.AsDelimited("|") );
                        qrySearch = qrySearch.Where( o => o.ConnectionOpportunityCampuses.Any( c => searchCampuses.Contains( c.CampusId ) ) ).ToList();
                    }
                }

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

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

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

                                    qrySearch = qrySearch.Where( o => attributeValues.Select( v => v.EntityId ).Contains( o.Id ) ).ToList();
                                }
                            }
                        }
                    }
                }

                string sessionKey = string.Format( "ConnectionSearch_{0}", this.BlockId );
                Session[sessionKey] = searchSelections;

                var opportunities = qrySearch.OrderBy( s => s.PublicName ).ToList();

                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "Opportunities", opportunities);
                mergeFields.Add( "CurrentPerson", CurrentPerson );

                var pageReference = new PageReference( GetAttributeValue( "DetailPage" ), null );
                mergeFields.Add( "DetailPage", BuildDetailPageUrl(pageReference.BuildUrl()) );

                lOutput.Text = GetAttributeValue( "LavaTemplate" ).ResolveMergeFields( mergeFields );

                if ( GetAttributeValue( "SetPageTitle" ).AsBoolean() )
                {
                    string pageTitle = "Connection";
                    RockPage.PageTitle = pageTitle;
                    RockPage.BrowserTitle = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                    RockPage.Header.Title = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                }

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
        }
 /// <summary>
 /// Sets the edit value from IEntity.Id value
 /// </summary>
 /// <param name="control">The control.</param>
 /// <param name="configurationValues">The configuration values.</param>
 /// <param name="id">The identifier.</param>
 public void SetEditValueFromEntityId( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues, int? id )
 {
     var item = new ConnectionOpportunityService( new RockContext() ).Get( id ?? 0 );
     string guidValue = item != null ? item.Guid.ToString() : string.Empty;
     SetEditValue( control, configurationValues, guidValue );
 }
        protected void ddlPlacementGroup_SelectedIndexChanged( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                var connectionRequestService = new ConnectionRequestService( rockContext );
                var connectionRequest = connectionRequestService.Get( hfConnectionRequestId.ValueAsInt() );
                if ( connectionRequest == null )
                {
                    connectionRequest = new ConnectionRequest();
                    var connectionOpportunity = new ConnectionOpportunityService( rockContext ).Get( hfConnectionOpportunityId.ValueAsInt() );
                    if ( connectionOpportunity != null )
                    {
                        connectionRequest.ConnectionOpportunity = connectionOpportunity;
                        connectionRequest.ConnectionOpportunityId = connectionOpportunity.Id;
                    }
                }

                RebindGroupRole( connectionRequest, rockContext );

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

            // Get the person
            PersonAlias personAlias = null;
            Guid personAliasGuid = action.GetWorklowAttributeValue(GetAttributeValue( action, "PersonAttribute" ).AsGuid()).AsGuid();
            personAlias = new PersonAliasService( rockContext ).Get( personAliasGuid );
            if ( personAlias == null )
            {
                errorMessages.Add( "Invalid Person Attribute or Value!" );
                return false;
            }

            // Get the opportunity
            ConnectionOpportunity opportunity = null;
            Guid opportunityTypeGuid = action.GetWorklowAttributeValue( GetAttributeValue( action, "ConnectionOpportunityAttribute" ).AsGuid() ).AsGuid();
            opportunity = new ConnectionOpportunityService( rockContext ).Get( opportunityTypeGuid );
            if ( opportunity == null )
            {
                errorMessages.Add( "Invalid Connection Opportunity Attribute or Value!" );
                return false;
            }

            // Get connection status
            ConnectionStatus status = null;
            Guid? connectionStatusGuid = null;
            Guid? connectionStatusAttributeGuid = GetAttributeValue( action, "ConnectionStatusAttribute" ).AsGuidOrNull();
            if ( connectionStatusAttributeGuid.HasValue )
            {
                connectionStatusGuid = action.GetWorklowAttributeValue( connectionStatusAttributeGuid.Value ).AsGuidOrNull();
                if ( connectionStatusGuid.HasValue )
                {
                    status = opportunity.ConnectionType.ConnectionStatuses
                        .Where( s => s.Guid.Equals( connectionStatusGuid.Value ) )
                        .FirstOrDefault();
                }
            }
            if ( status == null )
            {
                connectionStatusGuid = GetAttributeValue( action, "ConnectionStatus" ).AsGuidOrNull();
                if ( connectionStatusGuid.HasValue )
                {
                    status = opportunity.ConnectionType.ConnectionStatuses
                        .Where( s => s.Guid.Equals( connectionStatusGuid.Value ) )
                        .FirstOrDefault();
                }
            }
            if ( status == null )
            {
                status = opportunity.ConnectionType.ConnectionStatuses
                    .Where( s => s.IsDefault )
                    .FirstOrDefault();
            }

            // Get Campus
            int? campusId = null;
            Guid? campusAttributeGuid = GetAttributeValue( action, "CampusAttribute" ).AsGuidOrNull();
            if ( campusAttributeGuid.HasValue )
            {
                Guid? campusGuid = action.GetWorklowAttributeValue( campusAttributeGuid.Value ).AsGuidOrNull();
                if ( campusGuid.HasValue )
                {
                    var campus = CampusCache.Read( campusGuid.Value );
                    if ( campus != null )
                    {
                        campusId = campus.Id;
                    }
                }
            }

            // Get the Comment
            String comment = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionCommentAttribute").AsGuid());

            var connectionRequestService = new ConnectionRequestService( rockContext );

            var connectionRequest = new ConnectionRequest();
            connectionRequest.PersonAliasId = personAlias.Id;
            connectionRequest.ConnectionOpportunityId = opportunity.Id;
            connectionRequest.ConnectionState = ConnectionState.Active;
            connectionRequest.ConnectionStatusId = status.Id;
            connectionRequest.CampusId = campusId;
            connectionRequest.ConnectorPersonAliasId = opportunity.GetDefaultConnectorPersonAliasId( campusId );
            connectionRequest.Comments = comment;

            connectionRequestService.Add( connectionRequest );
            rockContext.SaveChanges();

            // If request attribute was specified, requery the request and set the attribute's value
            Guid? connectionRequestAttributeGuid = GetAttributeValue( action, "ConnectionRequestAttribute" ).AsGuidOrNull();
            if ( connectionRequestAttributeGuid.HasValue )
            {
                connectionRequest = connectionRequestService.Get( connectionRequest.Id );
                if ( connectionRequest != null )
                {
                    SetWorkflowAttributeValue( action, connectionRequestAttributeGuid.Value, connectionRequest.Guid.ToString() );
                }
            }

            return true;
        }
Example #53
0
        /// <summary>
        /// Gets the connectionOpportunity.
        /// </summary>
        /// <param name="connectionOpportunityId">The connectionOpportunity identifier.</param>
        /// <returns></returns>
        private ConnectionOpportunity GetConnectionOpportunity( int connectionOpportunityId, RockContext rockContext = null )
        {
            string key = string.Format( "ConnectionOpportunity:{0}", connectionOpportunityId );
            ConnectionOpportunity connectionOpportunity = RockPage.GetSharedItem( key ) as ConnectionOpportunity;
            if ( connectionOpportunity == null )
            {
                rockContext = rockContext ?? new RockContext();
                connectionOpportunity = new ConnectionOpportunityService( rockContext ).Queryable()
                    .Where( e => e.Id == connectionOpportunityId )
                    .FirstOrDefault();
                RockPage.SaveSharedItem( key, connectionOpportunity );
            }

            return connectionOpportunity;
        }
 /// <summary>
 /// Gets the edit value as the IEntity.Id
 /// </summary>
 /// <param name="control">The control.</param>
 /// <param name="configurationValues">The configuration values.</param>
 /// <returns></returns>
 public int? GetEditValueAsEntityId( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues )
 {
     Guid guid = GetEditValue( control, configurationValues ).AsGuid();
     var item = new ConnectionOpportunityService( new RockContext() ).Get( guid );
     return item != null ? item.Id : (int?)null;
 }
Example #55
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 )
        {
            ConnectionOpportunity connectionOpportunity = null;

            using ( RockContext rockContext = new RockContext() )
            {
                int? groupTypeId = ddlGroupType.SelectedValueAsInt();
                if ( groupTypeId.HasValue && GroupsState.Any( g => g.Group.GroupTypeId != groupTypeId.Value ) )
                {
                    var groupType = new GroupTypeService( rockContext ).Get( groupTypeId.Value );
                    if ( groupType != null )
                    {
                        nbInvalidGroupTypes.Text = string.Format( "<p>One or more of the selected groups is not a <strong>{0}</strong> type. Please select groups that have a group type of <strong>{0}</strong>.", groupType.Name );
                        nbInvalidGroupTypes.Visible = true;
                        return;
                    }
                }

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                EventCalendarItemService eventCalendarItemService = new EventCalendarItemService( rockContext );
                ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext );
                ConnectionOpportunityConnectorGroupService connectionOpportunityConnectorGroupsService = new ConnectionOpportunityConnectorGroupService( rockContext );
                ConnectionOpportunityCampusService connectionOpportunityCampusService = new ConnectionOpportunityCampusService( rockContext );
                ConnectionOpportunityGroupService connectionOpportunityGroupService = new ConnectionOpportunityGroupService( rockContext );

                int connectionOpportunityId = hfConnectionOpportunityId.ValueAsInt();
                if ( connectionOpportunityId != 0 )
                {
                    connectionOpportunity = connectionOpportunityService
                        .Queryable( "ConnectionOpportunityGroups, ConnectionWorkflows" )
                        .Where( ei => ei.Id == connectionOpportunityId )
                        .FirstOrDefault();
                }

                if ( connectionOpportunity == null )
                {
                    connectionOpportunity = new ConnectionOpportunity();
                    connectionOpportunity.Name = string.Empty;
                    connectionOpportunity.ConnectionTypeId = PageParameter( "ConnectionTypeId" ).AsInteger();
                    connectionOpportunityService.Add( connectionOpportunity );

                }

                connectionOpportunity.Name = tbName.Text;
                connectionOpportunity.Description = tbDescription.Text;
                connectionOpportunity.IsActive = cbIsActive.Checked;
                connectionOpportunity.PublicName = tbPublicName.Text;
                connectionOpportunity.IconCssClass = tbIconCssClass.Text;
                connectionOpportunity.GroupTypeId = ddlGroupType.SelectedValue.AsInteger();
                connectionOpportunity.GroupMemberRoleId = ddlGroupRole.SelectedValue.AsInteger();
                connectionOpportunity.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();

                int? orphanedPhotoId = null;
                if ( imgupPhoto.BinaryFileId != null )
                {
                    if ( connectionOpportunity.PhotoId != imgupPhoto.BinaryFileId )
                    {
                        orphanedPhotoId = connectionOpportunity.PhotoId;
                    }
                    connectionOpportunity.PhotoId = imgupPhoto.BinaryFileId.Value;
                }

                // remove any workflows that removed in the UI
                var uiWorkflows = WorkflowsState.Where( w => w.ConnectionTypeId == null ).Select( l => l.Guid );
                foreach ( var connectionOpportunityWorkflow in connectionOpportunity.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionWorkflows.Remove( connectionOpportunityWorkflow );
                    connectionWorkflowService.Delete( connectionOpportunityWorkflow );
                }

                // Add or Update workflows from the UI
                foreach ( ConnectionWorkflow connectionOpportunityWorkflowState in WorkflowsState.Where( w => w.ConnectionTypeId == null ) )
                {
                    ConnectionWorkflow connectionOpportunityWorkflow = connectionOpportunity.ConnectionWorkflows.Where( a => a.Guid == connectionOpportunityWorkflowState.Guid ).FirstOrDefault();
                    if ( connectionOpportunityWorkflow == null )
                    {
                        connectionOpportunityWorkflow = new ConnectionWorkflow();
                        connectionOpportunity.ConnectionWorkflows.Add( connectionOpportunityWorkflow );
                    }
                    connectionOpportunityWorkflow.CopyPropertiesFrom( connectionOpportunityWorkflowState );
                    connectionOpportunityWorkflow.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // remove any group campuses that removed in the UI
                var uiGroupCampuses = GroupCampusesState.Select( l => l.Guid );
                foreach ( var connectionOpportunityConnectorGroups in connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( l => !uiGroupCampuses.Contains( l.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityConnectorGroups.Remove( connectionOpportunityConnectorGroups );
                    connectionOpportunityConnectorGroupsService.Delete( connectionOpportunityConnectorGroups );
                }

                // Add or Update group campuses from the UI
                foreach ( var connectionOpportunityConnectorGroupsState in GroupCampusesState )
                {
                    ConnectionOpportunityConnectorGroup connectionOpportunityConnectorGroups = connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( a => a.Guid == connectionOpportunityConnectorGroupsState.Guid ).FirstOrDefault();
                    if ( connectionOpportunityConnectorGroups == null )
                    {
                        connectionOpportunityConnectorGroups = new ConnectionOpportunityConnectorGroup();
                        connectionOpportunity.ConnectionOpportunityConnectorGroups.Add( connectionOpportunityConnectorGroups );
                    }

                    connectionOpportunityConnectorGroups.CopyPropertiesFrom( connectionOpportunityConnectorGroupsState );
                }

                // remove any campuses that removed in the UI
                var uiCampuses = cblCampus.SelectedValuesAsInt;
                foreach ( var connectionOpportunityCampus in connectionOpportunity.ConnectionOpportunityCampuses.Where( c => !uiCampuses.Contains( c.CampusId ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityCampuses.Remove( connectionOpportunityCampus );
                    connectionOpportunityCampusService.Delete( connectionOpportunityCampus );
                }

                // Add or Update campuses from the UI
                foreach ( var campusId in uiCampuses )
                {
                    ConnectionOpportunityCampus connectionOpportunityCampus = connectionOpportunity.ConnectionOpportunityCampuses.Where( c => c.CampusId == campusId ).FirstOrDefault();
                    if ( connectionOpportunityCampus == null )
                    {
                        connectionOpportunityCampus = new ConnectionOpportunityCampus();
                        connectionOpportunity.ConnectionOpportunityCampuses.Add( connectionOpportunityCampus );
                    }

                    connectionOpportunityCampus.CampusId = campusId;
                }

                // Remove any groups that were removed in the UI
                var uiGroups = GroupsState.Select( r => r.Guid );
                foreach ( var connectionOpportunityGroup in connectionOpportunity.ConnectionOpportunityGroups.Where( r => !uiGroups.Contains( r.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityGroups.Remove( connectionOpportunityGroup );
                    connectionOpportunityGroupService.Delete( connectionOpportunityGroup );
                }

                // Add or Update groups from the UI
                foreach ( var connectionOpportunityGroupState in GroupsState )
                {
                    ConnectionOpportunityGroup connectionOpportunityGroup = connectionOpportunity.ConnectionOpportunityGroups.Where( a => a.Guid == connectionOpportunityGroupState.Guid ).FirstOrDefault();
                    if ( connectionOpportunityGroup == null )
                    {
                        connectionOpportunityGroup = new ConnectionOpportunityGroup();
                        connectionOpportunity.ConnectionOpportunityGroups.Add( connectionOpportunityGroup );
                    }

                    connectionOpportunityGroup.CopyPropertiesFrom( connectionOpportunityGroupState );
                }

                connectionOpportunity.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues( phAttributes, connectionOpportunity );

                if ( !Page.IsValid )
                {
                    return;
                }

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

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();

                    connectionOpportunity.SaveAttributeValues( rockContext );

                    if ( orphanedPhotoId.HasValue )
                    {
                        BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                        var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                        if ( binaryFile != null )
                        {
                            string errorMessage;
                            if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                            {
                                binaryFileService.Delete( binaryFile );
                                rockContext.SaveChanges();
                            }
                        }
                    }
                } );

                var qryParams = new Dictionary<string, string>();
                qryParams["ConnectionTypeId"] = PageParameter( "ConnectionTypeId" );
                NavigateToParentPage( qryParams );
            }
        }
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id )
        {
            var editControl = new RockDropDownList { ID = id };
            editControl.Items.Add( new ListItem() );

            bool includeInactive = ( configurationValues != null && configurationValues.ContainsKey( INCLUDE_INACTIVE_KEY ) && configurationValues[INCLUDE_INACTIVE_KEY].Value.AsBoolean() );

            var opportunities = new ConnectionOpportunityService( new RockContext() )
                .Queryable().AsNoTracking()
                .Where( o => o.IsActive || includeInactive )
                .OrderBy( o => o.ConnectionType.Name )
                .ThenBy( o => o.Name )
                .Select( o => new
                {
                    o.Guid,
                    o.Name,
                    ConnectionTypeName = o.ConnectionType.Name
                } )
                .ToList();

            if ( opportunities.Any() )
            {
                foreach ( var opportunity in opportunities )
                {
                    var listItem = new ListItem( opportunity.Name, opportunity.Guid.ToString().ToUpper() );
                    listItem.Attributes.Add( "OptionGroup", opportunity.ConnectionTypeName );
                    editControl.Items.Add( listItem );
                }

                return editControl;
            }

            return null;
        }
        /// <summary>
        /// Gets the opportunity summary HTML.
        /// </summary>
        /// <param name="opportunitySummaryId">The opportunity summary identifier.</param>
        /// <returns></returns>
        public string GetOpportunitySummaryHtml( OpportunitySummary opportunitySummary )
        {
            var template = this.GetAttributeValue( "OpportunitySummaryTemplate" );

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false } );
            mergeFields.Add( "OpportunitySummary", DotLiquid.Hash.FromAnonymousObject( opportunitySummary ) );

            string result = null;
            using ( var rockContext = new RockContext() )
            {
                var connectionOpportunity = new ConnectionOpportunityService( rockContext ).Queryable().AsNoTracking().FirstOrDefault( a => a.Id == opportunitySummary.Id );
                mergeFields.Add( "ConnectionOpportunity", connectionOpportunity );
                mergeFields.Add( "ConnectionRequests", connectionOpportunity.ConnectionRequests );

                result = template.ResolveMergeFields( mergeFields );
            }

            return result;
        }
Example #58
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="opportunityId">The opportunity identifier.</param>
        public void ShowDetail( int opportunityId )
        {
            using ( var rockContext = new RockContext() )
            {
                // load campus dropdown
                var campuses = CampusCache.All();
                cpCampus.Campuses = campuses;
                cpCampus.Visible = campuses.Count > 1;

                var opportunity = new ConnectionOpportunityService( rockContext ).Get( opportunityId );
                if ( opportunity == null )
                {
                    pnlSignup.Visible = false;
                    ShowError( "Incorrect Opportunity Type", "The requested opportunity does not exist." );
                    return;
                }

                pnlSignup.Visible = true;

                if ( !string.IsNullOrWhiteSpace( opportunity.IconCssClass ) )
                {
                    lIcon.Text = string.Format( "<i class='{0}' ></i>", opportunity.IconCssClass );
                }

                lTitle.Text = opportunity.Name.FormatAsHtmlTitle();

                pnHome.Visible = GetAttributeValue( "DisplayHomePhone" ).AsBoolean();
                pnMobile.Visible = GetAttributeValue( "DisplayMobilePhone" ).AsBoolean();

                if ( CurrentPerson != null )
                {
                    tbFirstName.Text = CurrentPerson.FirstName.EncodeHtml();
                    tbLastName.Text = CurrentPerson.LastName.EncodeHtml();
                    tbEmail.Text = CurrentPerson.Email.EncodeHtml();

                    if ( pnHome.Visible && _homePhone != null )
                    {
                        var homePhoneNumber = CurrentPerson.PhoneNumbers.Where( p => p.NumberTypeValueId == _homePhone.Id ).FirstOrDefault();
                        if ( homePhoneNumber != null )
                        {
                            pnHome.Number = homePhoneNumber.NumberFormatted;
                            pnHome.CountryCode = homePhoneNumber.CountryCode;
                        }
                    }

                    if ( pnMobile.Visible && _cellPhone != null )
                    {
                        var cellPhoneNumber = CurrentPerson.PhoneNumbers.Where( p => p.NumberTypeValueId == _cellPhone.Id ).FirstOrDefault();
                        if ( cellPhoneNumber != null )
                        {
                            pnMobile.Number = cellPhoneNumber.NumberFormatted;
                            pnMobile.CountryCode = cellPhoneNumber.CountryCode;
                        }
                    }

                    var campus = CurrentPerson.GetCampus();
                    if ( campus != null )
                    {
                        cpCampus.SelectedCampusId = campus.Id;
                    }
                }
                else
                {
                    // set the campus to the context
                    if ( GetAttributeValue( "EnableCampusContext" ).AsBoolean() )
                    {
                        var campusEntityType = EntityTypeCache.Read( "Rock.Model.Campus" );
                        var contextCampus = RockPage.GetCurrentContext( campusEntityType ) as Campus;

                        if ( contextCampus != null )
                        {
                            cpCampus.SelectedCampusId = contextCampus.Id;
                        }
                    }
                }

                // show debug info
                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "Opportunity", new ConnectionOpportunityService( rockContext ).Get( PageParameter( "OpportunityId" ).AsInteger() ) );
                mergeFields.Add( "CurrentPerson", CurrentPerson );
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
        }
Example #59
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var shapePageReference = new Rock.Web.PageReference(GetAttributeValue("SHAPEAssessmentPage"));
            var discPageReference = new Rock.Web.PageReference(GetAttributeValue("DISCAssessmentPage"));

            if (!string.IsNullOrWhiteSpace(PageParameter("FormId")))
                {
                    //Load the person based on the FormId
                    var personInUrl = PageParameter("FormId");
                    SelectedPerson = GetPersonFromForm(personInUrl);
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                }

                else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
                {
                    //Load the person based on the PersonId
                    SelectedPerson = GetPersonFromId(PageParameter("PersonId"));
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                 }

                else if (CurrentPerson != null)
                {
                    //Load the person based on the currently logged in person
                    SelectedPerson = CurrentPerson;
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                }

                else
                {
                    //Show Error Message
                    nbNoPerson.Visible = true;
                    Response.Redirect(shapePageReference.BuildUrl(), true);
                    return;
                }

            // Load the attributes

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            string spiritualGift1 = "";
            string spiritualGift2 = "";
            string spiritualGift3 = "";
            string spiritualGift4 = "";
            string heartCategories = "";
            string heartCauses = "";
            string heartPassion = "";
            string ability1 = "";
            string ability2 = "";
            string people = "";
            string places = "";
            string events = "";

            var spiritualGift1AttributeValue =
                attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id);

            // Redirect if they haven't taken the Assessment
            if (spiritualGift1AttributeValue == null)
            {
                Response.Redirect(shapePageReference.BuildUrl(), true);
            }

            else
            {
                var spiritualGift2AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id);

                var spiritualGift3AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id);

                var spiritualGift4AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id);

                var ability1AttributeValue =
                    attributeValueService
                        .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id);

                var ability2AttributeValue =
                    attributeValueService
                        .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id);

                var peopleAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id);

                var placesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id);

                var eventsAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id);

                var heartCategoriesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id);

                var heartCausesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id);

                var heartPassionAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id);

                if (spiritualGift1AttributeValue.Value != null) spiritualGift1 = spiritualGift1AttributeValue.Value;
                if (spiritualGift2AttributeValue.Value != null) spiritualGift2 = spiritualGift2AttributeValue.Value;
                if (spiritualGift3AttributeValue.Value != null) spiritualGift3 = spiritualGift3AttributeValue.Value;
                if (spiritualGift4AttributeValue.Value != null) spiritualGift4 = spiritualGift4AttributeValue.Value;
                if (heartCategoriesAttributeValue.Value != null) heartCategories = heartCategoriesAttributeValue.Value;
                if (heartCausesAttributeValue.Value != null) heartCauses = heartCausesAttributeValue.Value;
                if (heartPassionAttributeValue.Value != null) heartPassion = heartPassionAttributeValue.Value;
                if (ability1AttributeValue.Value != null) ability1 = ability1AttributeValue.Value;
                if (ability2AttributeValue.Value != null) ability2 = ability2AttributeValue.Value;
                if (peopleAttributeValue.Value != null) people = peopleAttributeValue.Value;
                if (placesAttributeValue.Value != null) places = placesAttributeValue.Value;
                if (eventsAttributeValue.Value != null) events = eventsAttributeValue.Value;

                string spiritualGift1Guid;
                string spiritualGift2Guid;
                string spiritualGift3Guid;
                string spiritualGift4Guid;
                string ability1Guid;
                string ability2Guid;

                // Check to see if there are already values saved as an ID.  If so, convert them to GUID
                if (spiritualGift1.ToString().Length < 5)
                {
                    if (spiritualGift1 != null) SpiritualGift1 = Int32.Parse(spiritualGift1);
                    if (spiritualGift2 != null) SpiritualGift2 = Int32.Parse(spiritualGift2);
                    if (spiritualGift3 != null) SpiritualGift3 = Int32.Parse(spiritualGift3);
                    if (spiritualGift4 != null) SpiritualGift4 = Int32.Parse(spiritualGift4);
                    if (ability1 != null) Ability1 = Int32.Parse(ability1);
                    if (ability2 != null) Ability2 = Int32.Parse(ability2);

                    var intsOfGifts =
                        definedValueService.GetByIds(new List<int>
                        {
                            SpiritualGift1,
                            SpiritualGift2,
                            SpiritualGift3,
                            SpiritualGift4,
                            Ability1,
                            Ability2
                        });

                    spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString();
                    spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString();
                    spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString();
                    spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString();
                    ability1Guid = intsOfGifts.ToList()[Ability1].Guid.ToString();
                    ability2Guid = intsOfGifts.ToList()[Ability2].Guid.ToString();
                }
                else
                {
                    spiritualGift1Guid = spiritualGift1;
                    spiritualGift2Guid = spiritualGift2;
                    spiritualGift3Guid = spiritualGift3;
                    spiritualGift4Guid = spiritualGift4;
                    ability1Guid = ability1;
                    ability2Guid = ability2;
                }

                // Get all of the data about the assiciated gifts and ability categories
                var shapeGift1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift1Guid) }).FirstOrDefault();
                var shapeGift2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift2Guid) }).FirstOrDefault();
                var shapeGift3Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift3Guid) }).FirstOrDefault();
                var shapeGift4Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift4Guid) }).FirstOrDefault();
                var ability1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability1Guid) }).FirstOrDefault();
                var ability2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability2Guid) }).FirstOrDefault();

                shapeGift1Object.LoadAttributes();
                shapeGift2Object.LoadAttributes();
                shapeGift3Object.LoadAttributes();
                shapeGift4Object.LoadAttributes();
                ability1Object.LoadAttributes();
                ability2Object.LoadAttributes();

                // Get heart choices Values from Guids
                string heartCategoriesString = "";
                if (!heartCategories.IsNullOrWhiteSpace())
                {
                    string[] heartCategoryArray = heartCategories.Split(',');
                    foreach (string category in heartCategoryArray)
                    {
                        var definedValueObject =
                            definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category));

                        if (category.Equals(heartCategoryArray.Last()))
                        {
                            heartCategoriesString += definedValueObject.Value;
                        }
                        else
                        {
                            heartCategoriesString += definedValueObject.Value + ", ";
                        }
                    }

                }

                // Get Volunteer Opportunities

                string gift1AssociatedVolunteerOpportunities =
                    shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift2AssociatedVolunteerOpportunities =
                    shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift3AssociatedVolunteerOpportunities =
                    shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift4AssociatedVolunteerOpportunities =
                    shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities");

                string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," +
                                                             gift2AssociatedVolunteerOpportunities + "," +
                                                             gift3AssociatedVolunteerOpportunities + "," +
                                                             gift4AssociatedVolunteerOpportunities;

                if (allAssociatedVolunteerOpportunities != ",,,")
                {
                    List<int> associatedVolunteerOpportunitiesList =
                        allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList();
                    Dictionary<int, int> VolunteerOpportunities = new Dictionary<int, int>();

                    var i = 0;
                    var q = from x in associatedVolunteerOpportunitiesList
                            group x by x
                        into g
                            let count = g.Count()
                            orderby count descending
                            select new { Value = g.Key, Count = count };
                    foreach (var x in q)
                    {
                        VolunteerOpportunities.Add(i, x.Value);
                        i++;
                    }

                    ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                    List<ConnectionOpportunity> connectionOpportunityList = new List<ConnectionOpportunity>();

                    foreach (KeyValuePair<int, int> entry in VolunteerOpportunities.Take(4))
                    {
                        var connection = connectionOpportunityService.GetByIds(new List<int> { entry.Value }).FirstOrDefault();

                        // Only display connection if it is marked Active
                        if (connection.IsActive == true)
                        {
                            connectionOpportunityList.Add(connection);
                        }

                    }

                    rpVolunteerOpportunities.DataSource = connectionOpportunityList;
                    rpVolunteerOpportunities.DataBind();
                }

                //Get DISC Info

                DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson);

                if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType))
                {
                    ShowResults(savedScores);
                    DISCResults.Visible = true;
                    NoDISCResults.Visible = false;

                }
                else
                {
                    discPageReference.Parameters = new System.Collections.Generic.Dictionary<string, string>();
                    discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey);
                    Response.Redirect(discPageReference.BuildUrl(), true);
                }

                // Build the UI

                lbPersonName.Text = SelectedPerson.FullName;

                lbGift1Title.Text = shapeGift1Object.Value;
                lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription");

                lbGift2Title.Text = shapeGift2Object.Value;
                lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription");

                lbGift3Title.Text = shapeGift3Object.Value;
                lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription");

                lbGift4Title.Text = shapeGift4Object.Value;
                lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription");

                lbAbility1Title.Text = ability1Object.Value;
                lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription");

                lbAbility2Title.Text = ability2Object.Value;
                lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription");

                lbPeople.Text = people;
                lbPlaces.Text = places;
                lbEvents.Text = events;

                lbHeartCategories.Text = heartCategoriesString;
                lbHeartCauses.Text = heartCauses;
                lbHeartPassion.Text = heartPassion;

                if (spiritualGift1AttributeValue.ModifiedDateTime != null)
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString();
                }
                else
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString();
                }

                // Show create account panel if this person doesn't have an account
                if (SelectedPerson.Users.Count == 0)
                {
                    pnlAccount.Visible = true;
                }

            }
        }
        /// <summary>
        /// Handles the Click event of the DeleteConnectionOpportunity control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param>
        protected void DeleteConnectionOpportunity_Click( object sender, Rock.Web.UI.Controls.RowEventArgs e )
        {
            using ( RockContext rockContext = new RockContext() )
            {
                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                ConnectionOpportunity connectionOpportunity = connectionOpportunityService.Get( e.RowKeyId );
                if ( connectionOpportunity != null )
                {
                    if ( _canEdit )
                    {
                        string errorMessage;
                        if ( !connectionOpportunityService.CanDelete( connectionOpportunity, out errorMessage ) )
                        {
                            mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                            return;
                        }

                        int connectionTypeId = connectionOpportunity.ConnectionTypeId;
                        connectionOpportunityService.Delete( connectionOpportunity );
                        rockContext.SaveChanges();

                        ConnectionWorkflowService.FlushCachedTriggers();

                    }
                    else
                    {
                        mdGridWarning.Show( "You are not authorized to delete this calendar item", ModalAlertType.Warning );
                    }
                }
            }
            BindConnectionOpportunitiesGrid();
        }