Exemple #1
0
        private void BindGridValue( )
        {
            int metricId  = (hfIdMetric.Value != null) ? Int32.Parse(hfIdMetric.Value) : 0;
            var queryable = new Rock.Model.MetricValueService().Queryable();

            queryable = queryable.
                        Where(a => a.MetricId == metricId);

            SortProperty sortProperty = rGridValue.SortProperty;

            if (sortProperty != null)
            {
                queryable = queryable.
                            Sort(sortProperty);
            }
            else
            {
                queryable = queryable.
                            OrderBy(a => a.Id).
                            ThenBy(a => a.Value);
            }

            rGridValue.DataSource = queryable.ToList();
            rGridValue.DataBind();
        }
Exemple #2
0
        protected void ShowEditValue(int metricValueId)
        {
            hfIdValue.Value = metricValueId.ToString();

            var metricValue = new Rock.Model.MetricValueService().Get(metricValueId);

            if (metricValue != null)
            {
                lValue.Text             = "Edit";
                tbValue.Text            = metricValue.Value;
                tbValueDescription.Text = metricValue.Description;
                tbXValue.Text           = metricValue.xValue;
                tbLabel.Text            = metricValue.Label;
                cbIsDateBased.Checked   = metricValue.isDateBased;
            }
            else
            {
                lValue.Text             = "Add";
                tbValue.Text            = string.Empty;
                tbValueDescription.Text = string.Empty;
                tbXValue.Text           = string.Empty;
                tbLabel.Text            = string.Empty;
                cbIsDateBased.Checked   = false;
            }

            ddlMetricFilter.SelectedValue = hfIdMetric.Value;
            modalValue.Show();
        }
Exemple #3
0
        protected void btnSaveValue_Click(object sender, EventArgs e)
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                int metricValueId = (hfIdValue.Value) != null?Int32.Parse(hfIdValue.Value) : 0;

                var metricValueService = new Rock.Model.MetricValueService();
                Rock.Model.MetricValue metricValue;

                if (metricValueId == 0)
                {
                    metricValue          = new Rock.Model.MetricValue();
                    metricValue.IsSystem = false;
                    metricValue.MetricId = Int32.Parse(hfIdMetric.Value);
                    metricValueService.Add(metricValue, CurrentPersonId);
                }
                else
                {
                    metricValue = metricValueService.Get(metricValueId);
                }

                metricValue.Value       = tbValue.Text;
                metricValue.Description = tbValueDescription.Text;
                metricValue.xValue      = tbXValue.Text;
                metricValue.Label       = tbLabel.Text;
                metricValue.isDateBased = cbIsDateBased.Checked;
                metricValue.MetricId    = Int32.Parse(ddlMetricFilter.SelectedValue);
                metricValueService.Save(metricValue, CurrentPersonId);
            }

            BindGridValue();

            modalValue.Hide();
            pnlValueList.Visible = true;
        }
Exemple #4
0
        protected void rGridValue_Delete(object sender, RowEventArgs e)
        {
            var metricValueService = new Rock.Model.MetricValueService();

            Rock.Model.MetricValue metricValue = metricValueService.Get((int)rGridValue.DataKeys[e.RowIndex]["id"]);
            if (metricValue != null)
            {
                metricValueService.Delete(metricValue, CurrentPersonId);
                metricValueService.Save(metricValue, CurrentPersonId);
            }

            BindGridValue();
        }
        /// <summary>
        /// Handles the Delete event of the gMetricValues 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 gMetricValues_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            MetricValueService metricValueService = new MetricValueService( rockContext );
            MetricValue metricValue = metricValueService.Get( e.RowKeyId );
            if ( metricValue != null )
            {
                string errorMessage;
                if ( !metricValueService.CanDelete( metricValue, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                metricValueService.Delete( metricValue );
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Metric metric;

            var rockContext = new RockContext();
            MetricService metricService = new MetricService( rockContext );
            MetricCategoryService metricCategoryService = new MetricCategoryService( rockContext );
            MetricValueService metricValueService = new MetricValueService( rockContext );
            bool deleteValuesOnSave = sender == btnDeleteValuesAndSave;

            int metricId = hfMetricId.Value.AsInteger();

            if ( metricId == 0 )
            {
                metric = new Metric();
            }
            else
            {
                metric = metricService.Get( metricId );
            }

            metric.Title = tbTitle.Text;
            metric.Subtitle = tbSubtitle.Text;
            metric.Description = tbDescription.Text;
            metric.IconCssClass = tbIconCssClass.Text;
            metric.SourceValueTypeId = ddlSourceType.SelectedValueAsId();
            metric.XAxisLabel = tbXAxisLabel.Text;
            metric.YAxisLabel = tbYAxisLabel.Text;
            metric.IsCumulative = cbIsCumulative.Checked;

            var origEntityType = metric.EntityTypeId.HasValue ? EntityTypeCache.Read( metric.EntityTypeId.Value ) : null;
            var newEntityType = etpEntityType.SelectedEntityTypeId.HasValue ? EntityTypeCache.Read( etpEntityType.SelectedEntityTypeId.Value ) : null;
            if ( origEntityType != null && !deleteValuesOnSave )
            {
                if ( newEntityType == null || newEntityType.Id != origEntityType.Id )
                {
                    // if the EntityTypeId of this metric has changed to NULL or to another EntityType, warn about the EntityId values being wrong
                    bool hasEntityValues = metricValueService.Queryable().Any( a => a.MetricId == metric.Id && a.EntityId.HasValue );

                    if ( hasEntityValues )
                    {
                        nbEntityTypeChanged.Text = string.Format(
                            "Warning: You can't change the series partition to {0} when there are values associated with {1}. Do you want to delete existing values?",
                            newEntityType != null ? newEntityType.FriendlyName : "<none>",
                            origEntityType.FriendlyName );
                        mdEntityTypeChanged.Show();
                        nbEntityTypeChanged.Visible = true;
                        return;
                    }
                }
            }

            metric.EntityTypeId = etpEntityType.SelectedEntityTypeId;

            int sourceTypeDataView = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid() ).Id;
            int sourceTypeSQL = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid() ).Id;

            var personService = new PersonService( rockContext );
            var metricChampionPerson = personService.Get( ppMetricChampionPerson.SelectedValue ?? 0 );
            metric.MetricChampionPersonAliasId = metricChampionPerson != null ? metricChampionPerson.PrimaryAliasId : null;
            var adminPerson = personService.Get( ppAdminPerson.SelectedValue ?? 0 );
            metric.AdminPersonAliasId = adminPerson != null ? adminPerson.PrimaryAliasId : null;

            if ( metric.SourceValueTypeId == sourceTypeSQL )
            {
                metric.SourceSql = ceSourceSql.Text;
            }
            else
            {
                metric.SourceSql = string.Empty;
            }

            if ( metric.SourceValueTypeId == sourceTypeDataView )
            {
                metric.DataViewId = ddlDataView.SelectedValueAsId();
            }
            else
            {
                metric.DataViewId = null;
            }

            var scheduleSelectionType = rblScheduleSelect.SelectedValueAsEnum<ScheduleSelectionType>();
            if ( scheduleSelectionType == ScheduleSelectionType.NamedSchedule )
            {
                metric.ScheduleId = ddlSchedule.SelectedValueAsId();
            }
            else
            {
                metric.ScheduleId = hfUniqueScheduleId.ValueAsInt();
            }

            if ( !Page.IsValid )
            {
                return;
            }

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

            if ( !cpMetricCategories.SelectedValuesAsInt().Any() )
            {
                cpMetricCategories.ShowErrorMessage( "Must select at least one category" );
                return;
            }

            // do a WrapTransaction since we are doing multiple SaveChanges()
            rockContext.WrapTransaction( () =>
            {
                var scheduleService = new ScheduleService( rockContext );
                var schedule = scheduleService.Get( metric.ScheduleId ?? 0 );
                int metricScheduleCategoryId = new CategoryService( rockContext ).Get( Rock.SystemGuid.Category.SCHEDULE_METRICS.AsGuid() ).Id;
                if ( schedule == null )
                {
                    schedule = new Schedule();

                    // make it an "Unnamed" metrics schedule
                    schedule.Name = string.Empty;
                    schedule.CategoryId = metricScheduleCategoryId;
                }

                // if the schedule was a unique schedule (configured in the Metric UI, set the schedule's ical content to the schedule builder UI's value
                if ( scheduleSelectionType == ScheduleSelectionType.Unique )
                {
                    schedule.iCalendarContent = sbSchedule.iCalendarContent;
                }

                if ( !schedule.HasSchedule() && scheduleSelectionType == ScheduleSelectionType.Unique )
                {
                    // don't save as a unique schedule if the schedule doesn't do anything
                    schedule = null;
                }
                else
                {
                    if ( schedule.Id == 0 )
                    {
                        scheduleService.Add( schedule );

                        // save to make sure we have a scheduleId
                        rockContext.SaveChanges();
                    }
                }

                if ( schedule != null )
                {
                    metric.ScheduleId = schedule.Id;
                }
                else
                {
                    metric.ScheduleId = null;
                }

                if ( metric.Id == 0 )
                {
                    metricService.Add( metric );

                    // save to make sure we have a metricId
                    rockContext.SaveChanges();
                }

                // update MetricCategories for Metric
                metric.MetricCategories = metric.MetricCategories ?? new List<MetricCategory>();
                var selectedCategoryIds = cpMetricCategories.SelectedValuesAsInt();

                // delete any categories that were removed
                foreach ( var metricCategory in metric.MetricCategories.ToList() )
                {
                    if ( !selectedCategoryIds.Contains( metricCategory.CategoryId ) )
                    {
                        metricCategoryService.Delete( metricCategory );
                    }
                }

                // add any categories that were added
                foreach ( int categoryId in selectedCategoryIds )
                {
                    if ( !metric.MetricCategories.Any( a => a.CategoryId == categoryId ) )
                    {
                        metricCategoryService.Add( new MetricCategory { CategoryId = categoryId, MetricId = metric.Id } );
                    }
                }

                rockContext.SaveChanges();

                // delete MetricValues associated with the old entityType if they confirmed the EntityType change
                if ( deleteValuesOnSave )
                {
                    metricValueService.DeleteRange( metricValueService.Queryable().Where( a => a.MetricId == metric.Id && a.EntityId.HasValue ) );

                    // since there could be 1000s of values that got deleted, do a SaveChanges that skips PrePostProcessing
                    rockContext.SaveChanges( true );
                }

                // delete any orphaned Unnamed metric schedules
                var metricIdSchedulesQry = metricService.Queryable().Select( a => a.ScheduleId );
                int? metricScheduleId = schedule != null ? schedule.Id : (int?)null;
                var orphanedSchedules = scheduleService.Queryable()
                    .Where( a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != ( metricScheduleId ?? 0 ) )
                    .Where( s => !metricIdSchedulesQry.Any( m => m == s.Id ) );
                foreach ( var item in orphanedSchedules )
                {
                    scheduleService.Delete( item );
                }

                if ( orphanedSchedules.Any() )
                {
                    rockContext.SaveChanges();
                }
            } );

            var qryParams = new Dictionary<string, string>();
            qryParams["MetricId"] = metric.Id.ToString();
            if ( hfMetricCategoryId.ValueAsInt() == 0 )
            {
                int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull();
                int? metricCategoryId = new MetricCategoryService( new RockContext() ).Queryable().Where( a => a.MetricId == metric.Id && a.CategoryId == parentCategoryId ).Select( a => a.Id ).FirstOrDefault();
                hfMetricCategoryId.Value = metricCategoryId.ToString();
            }

            qryParams["MetricCategoryId"] = hfMetricCategoryId.Value;
            qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );

            NavigateToPage( RockPage.Guid, qryParams );
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            int metricId = hfMetricId.ValueAsInt();
            var queryable = new MetricValueService().Queryable()
                .Where( a => a.MetricId == metricId );

            SortProperty sortProperty = gMetricValues.SortProperty;
            if ( sortProperty != null )
            {
                queryable = queryable.Sort( sortProperty );
            }
            else
            {
                queryable = queryable.OrderBy( a => a.Id ).ThenBy( a => a.Value );
            }

            gMetricValues.DataSource = queryable.ToList();
            gMetricValues.DataBind();
        }
        /// <summary>
        /// Handles the Delete event of the gMetricValues 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 gMetricValues_Delete( object sender, RowEventArgs e )
        {
            var metricValueService = new MetricValueService();

            MetricValue metricValue = metricValueService.Get( (int)e.RowKeyValue );
            if ( metricValue != null )
            {
                metricValueService.Delete( metricValue, CurrentPersonId );
                metricValueService.Save( metricValue, CurrentPersonId );
            }

            BindGrid();
        }
Exemple #9
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 )
        {
            MetricValue metricValue;
            var rockContext = new RockContext();
            MetricValueService metricValueService = new MetricValueService( rockContext );

            int metricValueId = int.Parse( hfMetricValueId.Value );

            if ( metricValueId == 0 )
            {
                metricValue = new MetricValue();
                metricValueService.Add( metricValue );
                metricValue.MetricId = hfMetricId.ValueAsInt();
                metricValue.Metric = metricValue.Metric ?? new MetricService( rockContext ).Get( metricValue.MetricId );
            }
            else
            {
                metricValue = metricValueService.Get( metricValueId );
            }

            metricValue.MetricValueType = ddlMetricValueType.SelectedValueAsEnum<MetricValueType>();
            metricValue.XValue = tbXValue.Text;
            metricValue.YValue = tbYValue.Text.AsDecimalOrNull();
            metricValue.Note = tbNote.Text;
            metricValue.MetricValueDateTime = dpMetricValueDateTime.SelectedDate;

            // Get EntityId from EntityType UI controls
            var metricEntityType = EntityTypeCache.Read( metricValue.Metric.EntityTypeId ?? 0 );
            Control entityTypeEditControl = phEntityTypeEntityIdValue.FindControl( "entityTypeEditControl" );
            if ( metricEntityType != null && metricEntityType.SingleValueFieldType != null && metricEntityType.SingleValueFieldType.Field is IEntityFieldType )
            {
                metricValue.EntityId = ( metricEntityType.SingleValueFieldType.Field as IEntityFieldType ).GetEditValueAsEntityId( entityTypeEditControl, new Dictionary<string, ConfigurationValue>() );
            }
            else
            {
                metricValue.EntityId = null;
            }

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

            rockContext.SaveChanges();

            var qryParams = new Dictionary<string, string>();
            qryParams.Add( "MetricId", hfMetricId.Value );
            qryParams.Add( "MetricCategoryId", hfMetricCategoryId.Value );
            qryParams.Add( "ExpandedIds", PageParameter( "ExpandedIds" ) );
            NavigateToParentPage( qryParams );
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( Page.IsPostBack )
            {
                // create dynamic controls
                var rockContext = new RockContext();
                var metricValue = new MetricValueService( rockContext ).Get( hfMetricValueId.Value.AsInteger() );
                if ( metricValue == null )
                {
                    metricValue = new MetricValue { MetricId = hfMetricId.Value.AsInteger() };
                    metricValue.Metric = new MetricService( rockContext ).Get( metricValue.MetricId );
                }

                CreateDynamicControls( metricValue, false, false );
            }

            if ( !Page.IsPostBack )
            {
                int? metricValueId = PageParameter( "MetricValueId" ).AsIntegerOrNull();

                // in case called with MetricId as the parent id parameter
                int? metricId = PageParameter( "MetricId" ).AsIntegerOrNull();

                // in case called with MetricCategoryId as the parent id parameter
                int? metricCategoryId = PageParameter( "MetricCategoryId" ).AsIntegerOrNull();
                MetricCategory metricCategory = null;
                if ( metricCategoryId.HasValue )
                {
                    if ( metricCategoryId.Value > 0 )
                    {
                        // editing a metric, but get the metricId from the metricCategory
                        metricCategory = new MetricCategoryService( new RockContext() ).Get( metricCategoryId.Value );
                        if ( metricCategory != null )
                        {
                            metricId = metricCategory.MetricId;
                        }
                    }
                    else
                    {
                        // adding a new metric. Block will (hopefully) not be shown
                        metricId = 0;
                    }
                }

                hfMetricCategoryId.Value = metricCategoryId.ToString();

                if ( metricValueId.HasValue )
                {
                    ShowDetail( metricValueId.Value, metricId );
                }
                else
                {
                    pnlDetails.Visible = false;
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Handles the SaveClick event of the mdMetricPartitionDetail 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 mdMetricPartitionDetail_SaveClick( object sender, EventArgs e )
        {
            if ( !tbMetricPartitionLabel.IsValid )
            {
                return;
            }

            var metricPartition = new MetricPartition();
            var rockContext = new RockContext();
            MetricValueService metricValueService = new MetricValueService( rockContext );
            var metricPartitionState = MetricPartitionsState.FirstOrDefault( a => a.Guid == hfMetricPartitionGuid.Value.AsGuid() );
            if ( metricPartitionState != null )
            {
                metricPartition.CopyPropertiesFrom( metricPartitionState );
            }
            else
            {
                metricPartition.Order = MetricPartitionsState.Any() ? MetricPartitionsState.Max( a => a.Order ) + 1 : 0;
                metricPartition.MetricId = hfMetricId.Value.AsInteger();
            }

            metricPartition.Label = tbMetricPartitionLabel.Text;

            metricPartition.EntityTypeId = etpMetricPartitionEntityType.SelectedEntityTypeId;
            metricPartition.IsRequired = cbMetricPartitionIsRequired.Checked;
            metricPartition.EntityTypeQualifierColumn = tbMetricPartitionEntityTypeQualifierColumn.Text;
            if ( ddlMetricPartitionDefinedTypePicker.Visible )
            {
                metricPartition.EntityTypeQualifierValue = ddlMetricPartitionDefinedTypePicker.SelectedValue;
            }
            else
            {
                metricPartition.EntityTypeQualifierValue = tbMetricPartitionEntityTypeQualifierValue.Text;
            }

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

            if ( metricPartitionState != null )
            {
                MetricPartitionsState.RemoveEntity( metricPartitionState.Guid );
            }

            MetricPartitionsState.Add( metricPartition );

            BindMetricPartitionsGrid();
            mdMetricPartitionDetail.Hide();
        }
        /// <summary>
        /// Binds the metrics.
        /// </summary>
        private void BindMetrics()
        {
            var serviceMetricValues = new List<ServiceMetric>();

            int campusEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Campus ) ).Id;
            int scheduleEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Schedule ) ).Id;

            int? campusId = bddlCampus.SelectedValueAsInt();
            int? scheduleId = bddlService.SelectedValueAsInt();
            DateTime? weekend = bddlWeekend.SelectedValue.AsDateTime();

            var notes = new List<string>();

            if ( campusId.HasValue && scheduleId.HasValue && weekend.HasValue )
            {

                SetBlockUserPreference( "CampusId", campusId.HasValue ? campusId.Value.ToString() : "" );
                SetBlockUserPreference( "ScheduleId", scheduleId.HasValue ? scheduleId.Value.ToString() : "" );

                var metricCategories = MetricCategoriesFieldAttribute.GetValueAsGuidPairs( GetAttributeValue( "MetricCategories" ) );
                var metricGuids = metricCategories.Select( a => a.MetricGuid ).ToList();
                using ( var rockContext = new RockContext() )
                {
                    var metricValueService = new MetricValueService( rockContext );
                    foreach ( var metric in new MetricService( rockContext )
                        .GetByGuids( metricGuids )
                        .Where( m =>
                            m.MetricPartitions.Count == 2 &&
                            m.MetricPartitions.Any( p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == campusEntityTypeId ) &&
                            m.MetricPartitions.Any( p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == scheduleEntityTypeId ) )
                        .OrderBy( m => m.Title )
                        .Select( m => new
                        {
                            m.Id,
                            m.Title,
                            CampusPartitionId = m.MetricPartitions.Where( p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == campusEntityTypeId ).Select( p => p.Id ).FirstOrDefault(),
                            SchedulePartitionId = m.MetricPartitions.Where( p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == scheduleEntityTypeId ).Select( p => p.Id ).FirstOrDefault(),
                        } ) )
                    {
                        var serviceMetric = new ServiceMetric( metric.Id, metric.Title );

                        if ( campusId.HasValue && weekend.HasValue && scheduleId.HasValue )
                        {
                            var metricValue = metricValueService
                                .Queryable().AsNoTracking()
                                .Where( v =>
                                    v.MetricId == metric.Id &&
                                    v.MetricValueDateTime.HasValue && v.MetricValueDateTime.Value == weekend.Value &&
                                    v.MetricValuePartitions.Count == 2 &&
                                    v.MetricValuePartitions.Any( p => p.MetricPartitionId == metric.CampusPartitionId && p.EntityId.HasValue && p.EntityId.Value == campusId.Value ) &&
                                    v.MetricValuePartitions.Any( p => p.MetricPartitionId == metric.SchedulePartitionId && p.EntityId.HasValue && p.EntityId.Value == scheduleId.Value ) )
                                .FirstOrDefault();

                            if ( metricValue != null )
                            {
                                serviceMetric.Value = metricValue.YValue;

                                if ( !string.IsNullOrWhiteSpace ( metricValue.Note) &&
                                    !notes.Contains( metricValue.Note ) )
                                {
                                    notes.Add( metricValue.Note );
                                }

                            }
                        }

                        serviceMetricValues.Add( serviceMetric );
                    }
                }
            }

            rptrMetric.DataSource = serviceMetricValues;
            rptrMetric.DataBind();

            tbNote.Text = notes.AsDelimited( Environment.NewLine + Environment.NewLine );
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            int campusEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Campus ) ).Id;
            int scheduleEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Schedule ) ).Id;

            int? campusId = bddlCampus.SelectedValueAsInt();
            int? scheduleId = bddlService.SelectedValueAsInt();
            DateTime? weekend = bddlWeekend.SelectedValue.AsDateTime();

            if ( campusId.HasValue && scheduleId.HasValue && weekend.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var metricService = new MetricService( rockContext );
                    var metricValueService = new MetricValueService( rockContext );

                    foreach ( RepeaterItem item in rptrMetric.Items )
                    {
                        var hfMetricIId = item.FindControl( "hfMetricId" ) as HiddenField;
                        var nbMetricValue = item.FindControl( "nbMetricValue" ) as NumberBox;

                        if ( hfMetricIId != null && nbMetricValue != null  )
                        {
                            int metricId = hfMetricIId.ValueAsInt();
                            var metric = new MetricService( rockContext ).Get( metricId );

                            if ( metric != null )
                            {
                                int campusPartitionId = metric.MetricPartitions.Where( p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == campusEntityTypeId ).Select( p => p.Id ).FirstOrDefault();
                                int schedulePartitionId = metric.MetricPartitions.Where( p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == scheduleEntityTypeId ).Select( p => p.Id ).FirstOrDefault();

                                var metricValue = metricValueService
                                    .Queryable()
                                    .Where( v =>
                                        v.MetricId == metric.Id &&
                                        v.MetricValueDateTime.HasValue && v.MetricValueDateTime.Value == weekend.Value &&
                                        v.MetricValuePartitions.Count == 2 &&
                                        v.MetricValuePartitions.Any( p => p.MetricPartitionId == campusPartitionId && p.EntityId.HasValue && p.EntityId.Value == campusId.Value ) &&
                                        v.MetricValuePartitions.Any( p => p.MetricPartitionId == schedulePartitionId && p.EntityId.HasValue && p.EntityId.Value == scheduleId.Value ) )
                                    .FirstOrDefault();

                                if ( metricValue == null )
                                {
                                    metricValue = new MetricValue();
                                    metricValue.MetricValueType = MetricValueType.Measure;
                                    metricValue.MetricId = metric.Id;
                                    metricValue.MetricValueDateTime = weekend.Value;
                                    metricValueService.Add( metricValue );

                                    var campusValuePartition = new MetricValuePartition();
                                    campusValuePartition.MetricPartitionId = campusPartitionId;
                                    campusValuePartition.EntityId = campusId.Value;
                                    metricValue.MetricValuePartitions.Add( campusValuePartition );

                                    var scheduleValuePartition = new MetricValuePartition();
                                    scheduleValuePartition.MetricPartitionId = schedulePartitionId;
                                    scheduleValuePartition.EntityId = scheduleId.Value;
                                    metricValue.MetricValuePartitions.Add( scheduleValuePartition );
                                }

                                metricValue.YValue = nbMetricValue.Text.AsDecimalOrNull();
                                metricValue.Note = tbNote.Text;
                            }
                        }
                    }

                    rockContext.SaveChanges();
                }

                nbMetricsSaved.Text = string.Format( "Your metrics for the {0} service on {1} at the {2} Campus have been saved.",
                    bddlService.SelectedItem.Text, bddlWeekend.SelectedItem.Text, bddlCampus.SelectedItem.Text );
                nbMetricsSaved.Visible = true;

                BindMetrics();

            }
        }
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute( IJobExecutionContext context )
        {
            var rockContext = new RockContext();
            var metricService = new MetricService( rockContext );
            var metricValueService = new MetricValueService( rockContext );

            var metricSourceValueTypeDataviewGuid = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid();
            var metricSourceValueTypeSqlGuid = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid();

            var metricsQry = metricService.Queryable( "Schedule" ).Where(
                a => a.ScheduleId.HasValue
                && a.SourceValueTypeId.HasValue
                && ( a.SourceValueType.Guid == metricSourceValueTypeDataviewGuid || a.SourceValueType.Guid == metricSourceValueTypeSqlGuid ) );

            var metricsList = metricsQry.OrderBy( a => a.Title ).ThenBy( a => a.Subtitle ).ToList();

            var metricExceptions = new List<Exception>();

            foreach ( var metric in metricsList )
            {
                try
                {
                    var lastRunDateTime = metric.LastRunDateTime ?? metric.CreatedDateTime ?? metric.ModifiedDateTime;
                    if ( lastRunDateTime.HasValue )
                    {
                        var currentDateTime = RockDateTime.Now;
                        // get all the schedule times that were supposed to run since that last time it was scheduled to run
                        var scheduledDateTimesToProcess = metric.Schedule.GetScheduledStartTimes( lastRunDateTime.Value, currentDateTime ).Where( a => a > lastRunDateTime.Value ).ToList();
                        foreach ( var scheduleDateTime in scheduledDateTimesToProcess )
                        {
                            Dictionary<int, decimal> resultValues = new Dictionary<int, decimal>();
                            if ( metric.SourceValueType.Guid == metricSourceValueTypeDataviewGuid )
                            {
                                // get the metric value from the DataView
                                if ( metric.DataView != null )
                                {
                                    var errorMessages = new List<string>();
                                    var qry = metric.DataView.GetQuery( null, null, out errorMessages );
                                    if ( metric.EntityTypeId.HasValue )
                                    {
                                        throw new NotImplementedException( "Partitioned Metrics using DataViews is not supported." );
                                    }
                                    else
                                    {
                                        resultValues.Add( 0, qry.Count() );
                                    }
                                }
                            }
                            else if ( metric.SourceValueType.Guid == metricSourceValueTypeSqlGuid )
                            {
                                // calculate the metricValue assuming that the SQL returns one row with one numeric field
                                if ( !string.IsNullOrWhiteSpace( metric.SourceSql ) )
                                {
                                    string formattedSql = metric.SourceSql.ResolveMergeFields( metric.GetMergeObjects( scheduleDateTime ) );
                                    var tableResult = DbService.GetDataTable( formattedSql, System.Data.CommandType.Text, null );
                                    foreach ( var row in tableResult.Rows.OfType<System.Data.DataRow>() )
                                    {
                                        int entityId = 0;
                                        decimal countValue;
                                        if ( tableResult.Columns.Count >= 2 )
                                        {
                                            if ( tableResult.Columns.Contains( "EntityId" ) )
                                            {
                                                entityId = Convert.ToInt32( row["EntityId"] );
                                            }
                                            else
                                            {
                                                // assume SQL is in the form "SELECT Count(*), EntityId FROM ..."
                                                entityId = Convert.ToInt32( row[1] );
                                            }
                                        }

                                        if ( tableResult.Columns.Contains( "Value" ) )
                                        {
                                            countValue = Convert.ToDecimal( row["Value"] );
                                        }
                                        else
                                        {
                                            // assume SQL is in the form "SELECT Count(*), EntityId FROM ..."
                                            countValue = Convert.ToDecimal( row[0] );
                                        }

                                        resultValues.Add( entityId, countValue );
                                    }
                                }
                            }

                            metric.LastRunDateTime = scheduleDateTime;

                            if ( resultValues.Any() )
                            {
                                foreach ( var resultValue in resultValues )
                                {
                                    var metricValue = new MetricValue();
                                    metricValue.MetricId = metric.Id;
                                    metricValue.MetricValueDateTime = scheduleDateTime;
                                    metricValue.MetricValueType = MetricValueType.Measure;
                                    metricValue.YValue = resultValue.Value;
                                    metricValue.EntityId = resultValue.Key > 0 ? resultValue.Key : (int?)null;

                                    metricValueService.Add( metricValue );
                                }
                            }

                            rockContext.SaveChanges();
                        }
                    }
                }
                catch ( Exception ex )
                {
                    metricExceptions.Add( new Exception( string.Format( "Exception when calculating metric for ", metric ), ex ) );
                }
            }

            if ( metricExceptions.Any() )
            {
                throw new AggregateException( "One or more metric calculations failed ", metricExceptions );
            }
        }
Exemple #15
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 )
        {
            Metric metric;

            var rockContext = new RockContext();
            MetricService metricService = new MetricService( rockContext );
            MetricCategoryService metricCategoryService = new MetricCategoryService( rockContext );
            MetricValueService metricValueService = new MetricValueService( rockContext );
            MetricPartitionService metricPartitionService = new MetricPartitionService( rockContext );

            int metricId = hfMetricId.Value.AsInteger();

            if ( metricId == 0 )
            {
                metric = new Metric();
            }
            else
            {
                metric = metricService.Get( metricId );

                // remove any metricPartitions that were removed in the UI
                var selectedMetricPartitionGuids = MetricPartitionsState.Select( r => r.Guid );
                foreach ( var item in metric.MetricPartitions.Where( r => !selectedMetricPartitionGuids.Contains( r.Guid ) ).ToList() )
                {
                    metric.MetricPartitions.Remove( item );
                    metricPartitionService.Delete( item );
                }
            }

            metric.MetricPartitions = metric.MetricPartitions ?? new List<MetricPartition>();

            if ( MetricPartitionsState.Count() > 1 && MetricPartitionsState.Any(a => !a.EntityTypeId.HasValue ))
            {
                mdMetricPartitionsEntityTypeWarning.Text = "If multiple partitions are defined for a metric, all the partitions must have an EntityType assigned";
                mdMetricPartitionsEntityTypeWarning.Visible = true;
                pwMetricPartitions.Expanded = true;
                return;
            }

            mdMetricPartitionsEntityTypeWarning.Visible = false;

            foreach ( var metricPartitionState in MetricPartitionsState )
            {
                MetricPartition metricPartition = metric.MetricPartitions.Where( r => r.Guid == metricPartitionState.Guid ).FirstOrDefault();
                if ( metricPartition == null )
                {
                    metricPartition = new MetricPartition();
                    metric.MetricPartitions.Add( metricPartition );
                }
                else
                {
                    metricPartitionState.Id = metricPartition.Id;
                    metricPartitionState.Guid = metricPartition.Guid;
                }

                metricPartition.CopyPropertiesFrom( metricPartitionState );
            }

            // ensure there is at least one partition
            if ( !metric.MetricPartitions.Any() )
            {
                var metricPartition = new MetricPartition();
                metricPartition.EntityTypeId = null;
                metricPartition.IsRequired = true;
                metricPartition.Order = 0;
                metric.MetricPartitions.Add( metricPartition );
            }

            metric.Title = tbTitle.Text;
            metric.Subtitle = tbSubtitle.Text;
            metric.Description = tbDescription.Text;
            metric.IconCssClass = tbIconCssClass.Text;
            metric.SourceValueTypeId = ddlSourceType.SelectedValueAsId();
            metric.YAxisLabel = tbYAxisLabel.Text;
            metric.IsCumulative = cbIsCumulative.Checked;

            int sourceTypeDataView = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid() ).Id;
            int sourceTypeSQL = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid() ).Id;

            var personService = new PersonService( rockContext );
            var metricChampionPerson = personService.Get( ppMetricChampionPerson.SelectedValue ?? 0 );
            metric.MetricChampionPersonAliasId = metricChampionPerson != null ? metricChampionPerson.PrimaryAliasId : null;
            var adminPerson = personService.Get( ppAdminPerson.SelectedValue ?? 0 );
            metric.AdminPersonAliasId = adminPerson != null ? adminPerson.PrimaryAliasId : null;

            if ( metric.SourceValueTypeId == sourceTypeSQL )
            {
                metric.SourceSql = ceSourceSql.Text;
            }
            else
            {
                metric.SourceSql = string.Empty;
            }

            if ( metric.SourceValueTypeId == sourceTypeDataView )
            {
                metric.DataViewId = ddlDataView.SelectedValueAsId();
            }
            else
            {
                metric.DataViewId = null;
            }

            var scheduleSelectionType = rblScheduleSelect.SelectedValueAsEnum<ScheduleSelectionType>();
            if ( scheduleSelectionType == ScheduleSelectionType.NamedSchedule )
            {
                metric.ScheduleId = ddlSchedule.SelectedValueAsId();
            }
            else
            {
                metric.ScheduleId = hfUniqueScheduleId.ValueAsInt();
            }

            if ( !Page.IsValid )
            {
                return;
            }

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

            if ( !cpMetricCategories.SelectedValuesAsInt().Any() )
            {
                cpMetricCategories.ShowErrorMessage( "Must select at least one category" );
                return;
            }

            // do a WrapTransaction since we are doing multiple SaveChanges()
            rockContext.WrapTransaction( () =>
            {
                var scheduleService = new ScheduleService( rockContext );
                var schedule = scheduleService.Get( metric.ScheduleId ?? 0 );
                int metricScheduleCategoryId = new CategoryService( rockContext ).Get( Rock.SystemGuid.Category.SCHEDULE_METRICS.AsGuid() ).Id;
                if ( schedule == null )
                {
                    schedule = new Schedule();

                    // make it an "Unnamed" metrics schedule
                    schedule.Name = string.Empty;
                    schedule.CategoryId = metricScheduleCategoryId;
                }

                // if the schedule was a unique schedule (configured in the Metric UI, set the schedule's ical content to the schedule builder UI's value
                if ( scheduleSelectionType == ScheduleSelectionType.Unique )
                {
                    schedule.iCalendarContent = sbSchedule.iCalendarContent;
                }

                if ( !schedule.HasSchedule() && scheduleSelectionType == ScheduleSelectionType.Unique )
                {
                    // don't save as a unique schedule if the schedule doesn't do anything
                    schedule = null;
                }
                else
                {
                    if ( schedule.Id == 0 )
                    {
                        scheduleService.Add( schedule );

                        // save to make sure we have a scheduleId
                        rockContext.SaveChanges();
                    }
                }

                if ( schedule != null )
                {
                    metric.ScheduleId = schedule.Id;
                }
                else
                {
                    metric.ScheduleId = null;
                }

                if ( metric.Id == 0 )
                {
                    metricService.Add( metric );

                    // save to make sure we have a metricId
                    rockContext.SaveChanges();
                }

                // update MetricCategories for Metric
                metric.MetricCategories = metric.MetricCategories ?? new List<MetricCategory>();
                var selectedCategoryIds = cpMetricCategories.SelectedValuesAsInt();

                // delete any categories that were removed
                foreach ( var metricCategory in metric.MetricCategories.ToList() )
                {
                    if ( !selectedCategoryIds.Contains( metricCategory.CategoryId ) )
                    {
                        metricCategoryService.Delete( metricCategory );
                    }
                }

                // add any categories that were added
                foreach ( int categoryId in selectedCategoryIds )
                {
                    if ( !metric.MetricCategories.Any( a => a.CategoryId == categoryId ) )
                    {
                        metricCategoryService.Add( new MetricCategory { CategoryId = categoryId, MetricId = metric.Id } );
                    }
                }

                rockContext.SaveChanges();

                // delete any orphaned Unnamed metric schedules
                var metricIdSchedulesQry = metricService.Queryable().Select( a => a.ScheduleId );
                int? metricScheduleId = schedule != null ? schedule.Id : (int?)null;
                var orphanedSchedules = scheduleService.Queryable()
                    .Where( a => a.CategoryId == metricScheduleCategoryId && a.Name == string.Empty && a.Id != ( metricScheduleId ?? 0 ) )
                    .Where( s => !metricIdSchedulesQry.Any( m => m == s.Id ) );
                foreach ( var item in orphanedSchedules )
                {
                    scheduleService.Delete( item );
                }

                if ( orphanedSchedules.Any() )
                {
                    rockContext.SaveChanges();
                }
            } );

            var qryParams = new Dictionary<string, string>();
            qryParams["MetricId"] = metric.Id.ToString();
            if ( hfMetricCategoryId.ValueAsInt() == 0 )
            {
                int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull();
                int? metricCategoryId = new MetricCategoryService( new RockContext() ).Queryable().Where( a => a.MetricId == metric.Id && a.CategoryId == parentCategoryId ).Select( a => a.Id ).FirstOrDefault();
                hfMetricCategoryId.Value = metricCategoryId.ToString();
            }

            qryParams["MetricCategoryId"] = hfMetricCategoryId.Value;
            qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );

            NavigateToPage( RockPage.Guid, qryParams );
        }
Exemple #16
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute( IJobExecutionContext context )
        {
            var metricSourceValueTypeDataviewGuid = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid();
            var metricSourceValueTypeSqlGuid = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid();

            var metricsQry = new MetricService( new RockContext() ).Queryable().AsNoTracking().Where(
                a => a.ScheduleId.HasValue
                && a.SourceValueTypeId.HasValue
                && ( a.SourceValueType.Guid == metricSourceValueTypeDataviewGuid || a.SourceValueType.Guid == metricSourceValueTypeSqlGuid ) );

            var metricIdList = metricsQry.OrderBy( a => a.Title ).ThenBy( a => a.Subtitle ).Select( a => a.Id ).ToList();

            var metricExceptions = new List<Exception>();
            int metricsCalculated = 0;
            int metricValuesCalculated = 0;
            Metric metric = null;

            foreach ( var metricId in metricIdList )
            {
                try
                {
                    using ( var rockContextForMetricEntity = new RockContext() )
                    {
                        var metricService = new MetricService( rockContextForMetricEntity );

                        metric = metricService.Get( metricId );
                        var lastRunDateTime = metric.LastRunDateTime ?? metric.CreatedDateTime ?? metric.ModifiedDateTime;
                        if ( lastRunDateTime.HasValue )
                        {
                            var currentDateTime = RockDateTime.Now;

                            // get all the schedule times that were supposed to run since that last time it was scheduled to run
                            var scheduledDateTimesToProcess = metric.Schedule.GetScheduledStartTimes( lastRunDateTime.Value, currentDateTime ).Where( a => a > lastRunDateTime.Value ).ToList();
                            foreach ( var scheduleDateTime in scheduledDateTimesToProcess )
                            {
                                using ( var rockContextForMetricValues = new RockContext() )
                                {
                                    var metricPartitions = new MetricPartitionService( rockContextForMetricValues ).Queryable().Where( a => a.MetricId == metric.Id ).ToList();
                                    var metricValueService = new MetricValueService( rockContextForMetricValues );
                                    List<ResultValue> resultValues = new List<ResultValue>();
                                    bool getMetricValueDateTimeFromResultSet = false;
                                    if ( metric.SourceValueType.Guid == metricSourceValueTypeDataviewGuid )
                                    {
                                        // get the metric value from the DataView
                                        if ( metric.DataView != null )
                                        {
                                            var errorMessages = new List<string>();
                                            var qry = metric.DataView.GetQuery( null, null, out errorMessages );
                                            if ( metricPartitions.Count > 1 || metricPartitions.First().EntityTypeId.HasValue )
                                            {
                                                throw new NotImplementedException( "Partitioned Metrics using DataViews is not supported." );
                                            }
                                            else
                                            {
                                                var resultValue = new ResultValue();
                                                resultValue.Value = Convert.ToDecimal( qry.Count() );
                                                resultValue.Partitions = new List<ResultValuePartition>();
                                                resultValue.MetricValueDateTime = scheduleDateTime;
                                                resultValues.Add( resultValue );
                                            }
                                        }
                                    }
                                    else if ( metric.SourceValueType.Guid == metricSourceValueTypeSqlGuid )
                                    {
                                        //// calculate the metricValue using the results from the SQL
                                        //// assume SQL is in one of the following forms:
                                        //// -- "SELECT Count(*), Partion0EntityId, Partion1EntityId, Partion2EntityId,.. FROM ..."
                                        //// -- "SELECT Count(*), [MetricValueDateTime], Partion0EntityId, Partion1EntityId, Partion2EntityId,.. FROM ..."
                                        if ( !string.IsNullOrWhiteSpace( metric.SourceSql ) )
                                        {
                                            string formattedSql = metric.SourceSql.ResolveMergeFields( metric.GetMergeObjects( scheduleDateTime ) );
                                            var tableResult = DbService.GetDataTable( formattedSql, System.Data.CommandType.Text, null );

                                            if ( tableResult.Columns.Count >= 2 && tableResult.Columns[1].ColumnName == "MetricValueDateTime" )
                                            {
                                                getMetricValueDateTimeFromResultSet = true;
                                            }

                                            foreach ( var row in tableResult.Rows.OfType<System.Data.DataRow>() )
                                            {
                                                var resultValue = new ResultValue();

                                                resultValue.Value = Convert.ToDecimal( row[0] );
                                                if ( getMetricValueDateTimeFromResultSet )
                                                {
                                                    resultValue.MetricValueDateTime = Convert.ToDateTime( row[1] );
                                                }
                                                else
                                                {
                                                    resultValue.MetricValueDateTime = scheduleDateTime;
                                                }

                                                resultValue.Partitions = new List<ResultValuePartition>();
                                                int partitionPosition = 0;
                                                int partitionFieldIndex = getMetricValueDateTimeFromResultSet ? 2 : 1;
                                                int partitionColumnCount = tableResult.Columns.Count - 1;
                                                while ( partitionFieldIndex <= partitionColumnCount )
                                                {
                                                    resultValue.Partitions.Add( new ResultValuePartition
                                                    {
                                                        PartitionPosition = partitionPosition,
                                                        EntityId = row[partitionFieldIndex] as int?
                                                    } );

                                                    partitionPosition++;
                                                    partitionFieldIndex++;
                                                }

                                                resultValues.Add( resultValue );
                                            }
                                        }
                                    }

                                    metric.LastRunDateTime = scheduleDateTime;
                                    metricsCalculated++;
                                    metricValuesCalculated += resultValues.Count();

                                    if ( resultValues.Any() )
                                    {
                                        List<MetricValue> metricValuesToAdd = new List<MetricValue>();
                                        foreach ( var resultValue in resultValues )
                                        {
                                            var metricValue = new MetricValue();
                                            metricValue.MetricId = metric.Id;
                                            metricValue.MetricValueDateTime = resultValue.MetricValueDateTime;
                                            metricValue.MetricValueType = MetricValueType.Measure;
                                            metricValue.YValue = resultValue.Value;
                                            metricValue.CreatedDateTime = RockDateTime.Now;
                                            metricValue.ModifiedDateTime = RockDateTime.Now;
                                            metricValue.MetricValuePartitions = new List<MetricValuePartition>();
                                            var metricPartitionsByPosition = metricPartitions.OrderBy( a => a.Order ).ToList();

                                            if ( !resultValue.Partitions.Any() && metricPartitionsByPosition.Count() == 1 && !metricPartitionsByPosition[0].EntityTypeId.HasValue )
                                            {
                                                // a metric with just the default partition (not partitioned by Entity)
                                                var metricPartition = metricPartitionsByPosition[0];
                                                var metricValuePartition = new MetricValuePartition();
                                                metricValuePartition.MetricPartition = metricPartition;
                                                metricValuePartition.MetricPartitionId = metricPartition.Id;
                                                metricValuePartition.MetricValue = metricValue;
                                                metricValuePartition.EntityId = null;
                                                metricValue.MetricValuePartitions.Add( metricValuePartition );
                                            }
                                            else
                                            {
                                                foreach ( var partitionResult in resultValue.Partitions )
                                                {
                                                    if ( metricPartitionsByPosition.Count > partitionResult.PartitionPosition )
                                                    {
                                                        var metricPartition = metricPartitionsByPosition[partitionResult.PartitionPosition];
                                                        var metricValuePartition = new MetricValuePartition();
                                                        metricValuePartition.MetricPartition = metricPartition;
                                                        metricValuePartition.MetricPartitionId = metricPartition.Id;
                                                        metricValuePartition.MetricValue = metricValue;
                                                        metricValuePartition.EntityId = partitionResult.EntityId;
                                                        metricValue.MetricValuePartitions.Add( metricValuePartition );
                                                    }
                                                }
                                            }

                                            if ( metricValue.MetricValuePartitions == null || !metricValue.MetricValuePartitions.Any() )
                                            {
                                                // shouldn't happen, but just in case
                                                throw new Exception( "MetricValue requires at least one Partition Value" );
                                            }
                                            else
                                            {
                                                metricValuesToAdd.Add( metricValue );
                                            }
                                        }

                                        // if a single metricValueDateTime was specified, delete any existing metric values for this date and refresh with the current results
                                        var dbTransaction = rockContextForMetricValues.Database.BeginTransaction();
                                        if ( getMetricValueDateTimeFromResultSet )
                                        {
                                            var metricValueDateTimes = metricValuesToAdd.Select( a => a.MetricValueDateTime ).Distinct().ToList();
                                            foreach ( var metricValueDateTime in metricValueDateTimes )
                                            {
                                                bool alreadyHasMetricValues = metricValueService.Queryable().Where( a => a.MetricId == metric.Id && a.MetricValueDateTime == metricValueDateTime ).Any();
                                                if ( alreadyHasMetricValues )
                                                {
                                                    // use direct SQL to clean up any existing metric values
                                                    rockContextForMetricValues.Database.ExecuteSqlCommand( @"
                                                        DELETE
                                                        FROM MetricValuePartition
                                                        WHERE MetricValueId IN (
                                                            SELECT Id
                                                            FROM MetricValue
                                                            WHERE MetricId = @metricId
                                                            AND MetricValueDateTime = @metricValueDateTime
                                                        )
                                                    ", new SqlParameter( "@metricId", metric.Id ), new SqlParameter( "@metricValueDateTime", metricValueDateTime ) );

                                                    rockContextForMetricValues.Database.ExecuteSqlCommand( @"
                                                        DELETE
                                                        FROM MetricValue
                                                        WHERE MetricId = @metricId
                                                        AND MetricValueDateTime = @metricValueDateTime
                                                    ", new SqlParameter( "@metricId", metric.Id ), new SqlParameter( "@metricValueDateTime", metricValueDateTime ) );
                                                }
                                            }
                                        }

                                        metricValueService.AddRange( metricValuesToAdd );

                                        // disable savechanges PrePostProcessing since there could be hundreds or thousands of metric values getting inserted/updated
                                        rockContextForMetricValues.SaveChanges( true );
                                        dbTransaction.Commit();
                                    }

                                    rockContextForMetricEntity.SaveChanges();
                                }
                            }
                        }
                    }
                }
                catch ( Exception ex )
                {
                    metricExceptions.Add( new Exception( string.Format( "Exception when calculating metric for {0} ", metric ), ex ) );
                }
            }

            context.Result = string.Format( "Calculated a total of {0} metric values for {1} metrics", metricValuesCalculated, metricsCalculated );

            if ( metricExceptions.Any() )
            {
                throw new AggregateException( "One or more metric calculations failed ", metricExceptions );
            }
        }
Exemple #17
0
        /// <summary>
        /// Shows the Metric Partition dialog for add/edit
        /// </summary>
        /// <param name="metricPartitionGuid">The metric partition unique identifier.</param>
        protected void gMetricPartitions_ShowEdit( Guid? metricPartitionGuid )
        {
            MetricPartition metricPartition;
            if ( !metricPartitionGuid.HasValue )
            {
                metricPartition = new MetricPartition();
                mdMetricPartitionDetail.Title = "Add Partition";
            }
            else
            {
                metricPartition = MetricPartitionsState.FirstOrDefault( a => a.Guid == metricPartitionGuid.Value );
                mdMetricPartitionDetail.Title = "Edit Partition";
            }

            var metricValueService = new MetricValueService( new RockContext() );

            hfMetricPartitionGuid.Value = metricPartition.Guid.ToString();
            tbMetricPartitionLabel.Text = metricPartition.Label;
            etpMetricPartitionEntityType.SetValue( metricPartition.EntityTypeId );
            cbMetricPartitionIsRequired.Checked = metricPartition.IsRequired;
            tbMetricPartitionEntityTypeQualifierColumn.Text = metricPartition.EntityTypeQualifierColumn;
            tbMetricPartitionEntityTypeQualifierValue.Text = metricPartition.EntityTypeQualifierValue;

            if ( metricPartition.EntityTypeQualifierColumn == "DefinedTypeId" )
            {
                ddlMetricPartitionDefinedTypePicker.SetValue( ( metricPartition.EntityTypeQualifierValue ?? string.Empty ).AsIntegerOrNull() );
            }

            UpdateMetricPartionDetailForEntityType();

            mdMetricPartitionDetail.Show();
        }
Exemple #18
0
        public void SaveMetric(DateTime dt, int metric, Decimal value, int campus, string notes, int type)
        {
            int metricValueId = 0;
            RockContext rockContext = new RockContext();
            MetricValue metricValue;
            MetricValueService metricValueService = new MetricValueService(rockContext);

            //Does this metric already exist?
            var existingMetric = metricValueService
                .Queryable(
                    ).FirstOrDefault(a => a.MetricId == metric && a.MetricValueDateTime == dt && a.EntityId == campus);

            if (existingMetric != null)
            {
                metricValueId = existingMetric.Id;
            }

            if (metricValueId == 0)
            {
                metricValue = new MetricValue();
                metricValueService.Add(metricValue);
                metricValue.MetricId = metric;
                metricValue.Metric = metricValue.Metric ?? new MetricService(rockContext).Get(metricValue.MetricId);
            }
            else
            {
                metricValue = metricValueService.Get(metricValueId);
            }

            metricValue.MetricValueType = (MetricValueType)type;
            metricValue.XValue = null;
            metricValue.YValue = value;
            metricValue.Note = notes;
            metricValue.MetricValueDateTime = dt;
            metricValue.EntityId = campus;

            rockContext.SaveChanges();
        }
        /// <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 )
        {
            MetricValue metricValue;
            var rockContext = new RockContext();
            MetricValueService metricValueService = new MetricValueService( rockContext );

            int metricValueId = int.Parse( hfMetricValueId.Value );

            if ( metricValueId == 0 )
            {
                metricValue = new MetricValue();
                metricValueService.Add( metricValue );
                metricValue.MetricId = hfMetricId.ValueAsInt();
                metricValue.Metric = metricValue.Metric ?? new MetricService( rockContext ).Get( metricValue.MetricId );
                metricValue.MetricValuePartitions = new List<MetricValuePartition>();
            }
            else
            {
                metricValue = metricValueService.Get( metricValueId );
            }

            metricValue.MetricValueType = ddlMetricValueType.SelectedValueAsEnum<MetricValueType>();
            metricValue.XValue = tbXValue.Text;
            metricValue.YValue = tbYValue.Text.AsDecimalOrNull();
            metricValue.Note = tbNote.Text;
            metricValue.MetricValueDateTime = dpMetricValueDateTime.SelectedDate;

            // Get EntityId from EntityType UI controls
            foreach ( var metricPartition in metricValue.Metric.MetricPartitions )
            {
                var metricPartitionEntityType = EntityTypeCache.Read( metricPartition.EntityTypeId ?? 0 );
                var controlId = string.Format( "metricPartition{0}_entityTypeEditControl", metricPartition.Id );
                Control entityTypeEditControl = phMetricValuePartitions.FindControl( controlId );
                var metricValuePartition = metricValue.MetricValuePartitions.FirstOrDefault( a => a.MetricPartitionId == metricPartition.Id );
                if ( metricValuePartition == null )
                {
                    metricValuePartition = new MetricValuePartition();
                    metricValuePartition.MetricPartitionId = metricPartition.Id;
                    metricValue.MetricValuePartitions.Add( metricValuePartition );
                }

                if ( metricPartitionEntityType != null && metricPartitionEntityType.SingleValueFieldType != null && metricPartitionEntityType.SingleValueFieldType.Field is IEntityFieldType )
                {
                    metricValuePartition.EntityId = ( metricPartitionEntityType.SingleValueFieldType.Field as IEntityFieldType ).GetEditValueAsEntityId( entityTypeEditControl, new Dictionary<string, ConfigurationValue>() );
                }
                else
                {
                    metricValuePartition.EntityId = null;
                }

                if ( metricPartition.IsRequired && metricPartitionEntityType != null && !metricValuePartition.EntityId.HasValue )
                {
                    nbValueRequired.Text = string.Format( "A value for {0} is required", metricPartition.Label ?? metricPartitionEntityType.FriendlyName );
                    nbValueRequired.Dismissable = true;
                    nbValueRequired.Visible = true;
                    return;
                }
            }

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

            rockContext.SaveChanges();

            var qryParams = new Dictionary<string, string>();
            qryParams.Add( "MetricId", hfMetricId.Value );
            qryParams.Add( "MetricCategoryId", hfMetricCategoryId.Value );
            qryParams.Add( "ExpandedIds", PageParameter( "ExpandedIds" ) );
            NavigateToParentPage( qryParams );
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            int? metricId = hfMetricId.Value.AsIntegerOrNull();

            if ( !metricId.HasValue )
            {
                return;
            }

            var rockContext = new RockContext();
            SortProperty sortProperty = gMetricValues.SortProperty;
            MetricValueService metricValueService = new MetricValueService( rockContext );
            var qry = metricValueService.Queryable().Include( a => a.MetricValuePartitions );

            qry = qry.Where( a => a.MetricId == metricId );

            var metricValuePartitionsColumn = gMetricValues.Columns.OfType<RockLiteralField>().FirstOrDefault( a => a.ID == "lMetricValuePartitions" );
            var metric = new MetricService( rockContext ).Get( metricId ?? 0 );
            metricValuePartitionsColumn.Visible = metric != null && metric.MetricPartitions.Any( a => a.EntityTypeId.HasValue );

            var drp = new DateRangePicker();
            drp.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" );
            if ( drp.LowerValue.HasValue )
            {
                qry = qry.Where( a => a.MetricValueDateTime >= drp.LowerValue.Value );
            }

            if ( drp.UpperValue.HasValue )
            {
                DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                qry = qry.Where( a => a.MetricValueDateTime < upperDate );
            }

            var metricValueType = gfMetricValues.GetUserPreference( "Goal/Measure" ).ConvertToEnumOrNull<MetricValueType>();
            if ( metricValueType.HasValue )
            {
                qry = qry.Where( a => a.MetricValueType == metricValueType.Value );
            }

            var entityTypeEntityUserPreference = gfMetricValues.GetUserPreference( this.EntityTypeEntityPreferenceKey ) ?? string.Empty;

            var entityTypeEntityList = entityTypeEntityUserPreference.Split( ',' ).Select( a => a.Split( '|' ) ).Where( a => a.Length == 2 ).Select( a =>
                new
                {
                    EntityTypeId = a[0].AsIntegerOrNull(),
                    EntityId = a[1].AsIntegerOrNull()
                } );

            foreach ( var entityTypeEntity in entityTypeEntityList )
            {
                if ( entityTypeEntity.EntityTypeId.HasValue && entityTypeEntity.EntityId.HasValue )
                {
                    qry = qry.Where( a => a.MetricValuePartitions.Any( x => x.MetricPartition.EntityTypeId == entityTypeEntity.EntityTypeId && x.EntityId == entityTypeEntity.EntityId ) );
                }
            }

            if ( sortProperty != null )
            {
                qry = qry.Sort( sortProperty );
            }
            else
            {
                qry = qry.OrderBy( s => s.MetricValueDateTime ).ThenBy( s => s.YValue ).ThenBy( s => s.XValue ).ThenByDescending( s => s.ModifiedDateTime );
            }

            gMetricValues.SetLinqDataSource( qry );

            gMetricValues.DataBind();
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="metricValueId">The metric value identifier.</param>
        /// <param name="metricId">The metric identifier.</param>
        public void ShowDetail( int metricValueId, int? metricId )
        {
            pnlDetails.Visible = true;

            // Load depending on Add(0) or Edit
            MetricValue metricValue = null;
            if ( !metricValueId.Equals( 0 ) )
            {
                metricValue = new MetricValueService( new RockContext() ).Get( metricValueId );
                lActionTitle.Text = ActionTitle.Edit( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle();
                pdAuditDetails.SetEntity( metricValue, ResolveRockUrl( "~" ) );
            }

            if ( metricValue == null && metricId.HasValue )
            {
                metricValue = new MetricValue { Id = 0, MetricId = metricId.Value };
                metricValue.Metric = metricValue.Metric ?? new MetricService( new RockContext() ).Get( metricValue.MetricId );
                lActionTitle.Text = ActionTitle.Add( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle();
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            hfMetricValueId.Value = metricValue.Id.ToString();

            LoadDropDowns();

            ddlMetricValueType.SelectedValue = metricValue.MetricValueType.ConvertToInt().ToString();
            tbXValue.Text = metricValue.XValue;
            tbYValue.Text = metricValue.YValue.ToString();
            hfMetricId.Value = metricValue.MetricId.ToString();
            tbNote.Text = metricValue.Note;
            dpMetricValueDateTime.SelectedDate = metricValue.MetricValueDateTime;

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

            nbEditModeMessage.Text = string.Empty;

            bool canEdit = UserCanEdit;
            if ( !canEdit && metricId.HasValue && metricId.Value > 0 )
            {
                var metric = new MetricService( new RockContext() ).Get( metricId.Value );
                if ( metric != null && metric.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                {
                    canEdit = true;
                }
            }

            if ( !canEdit )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( MetricValue.FriendlyTypeName );
            }

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( MetricValue.FriendlyTypeName );
                btnCancel.Text = "Close";
            }

            CreateDynamicControls( metricValue, true, readOnly );

            ddlMetricValueType.Enabled = !readOnly;
            tbXValue.ReadOnly = readOnly;
            tbYValue.ReadOnly = readOnly;
            tbNote.ReadOnly = readOnly;
            dpMetricValueDateTime.Enabled = !readOnly;

            btnSave.Visible = !readOnly;
        }
        public string GetHtmlForBlock( int blockId, int? entityTypeId = null, int? entityId = null )
        {
            RockContext rockContext = this.Service.Context as RockContext ?? new RockContext();
            Block block = new BlockService( rockContext ).Get( blockId );
            if ( block != null )
            {
                block.LoadAttributes();

                string liquidTemplate = block.GetAttributeValue( "LiquidTemplate" );

                var metricCategoryPairList = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs( block.GetAttributeValue( "MetricCategories" ) );

                var metricGuids = metricCategoryPairList.Select( a => a.MetricGuid ).ToList();

                bool roundYValues = block.GetAttributeValue( "RoundValues" ).AsBooleanOrNull() ?? true;

                MetricService metricService = new MetricService( rockContext );
                var metrics = metricService.GetByGuids( metricGuids );
                List<object> metricsData = new List<object>();

                if ( metrics.Count() == 0 )
                {
                    return @"<div class='alert alert-warning'> 
								Please select a metric in the block settings.
							</div>";
                }

                MetricValueService metricValueService = new MetricValueService( rockContext );

                DateTime firstDayOfYear = new DateTime( RockDateTime.Now.Year, 1, 1 );
                DateTime currentDateTime = RockDateTime.Now;
                DateTime firstDayOfNextYear = new DateTime( RockDateTime.Now.Year + 1, 1, 1 );

                foreach ( var metric in metrics )
                {
                    var metricYTDData = JsonConvert.DeserializeObject( metric.ToJson(), typeof( MetricYTDData ) ) as MetricYTDData;
                    var qryMeasureValues = metricValueService.Queryable()
                        .Where( a => a.MetricId == metricYTDData.Id )
                        .Where( a => a.MetricValueDateTime >= firstDayOfYear && a.MetricValueDateTime < currentDateTime )
                        .Where( a => a.MetricValueType == MetricValueType.Measure );

                    //// if an entityTypeId/EntityId filter was specified, and the entityTypeId is the same as the metrics.EntityTypeId, filter the values to the specified entityId
                    //// Note: if a Metric or it's Metric Value doesn't have a context, include it regardless of Context setting
                    if ( entityTypeId.HasValue && ( metric.EntityTypeId == entityTypeId || metric.EntityTypeId == null ) )
                    {
                        if ( entityId.HasValue )
                        {
                            qryMeasureValues = qryMeasureValues.Where( a => a.EntityId == entityId || a.EntityId == null );
                        }
                    }

                    var lastMetricValue = qryMeasureValues.OrderByDescending( a => a.MetricValueDateTime ).FirstOrDefault();
                    if ( lastMetricValue != null )
                    {
                        metricYTDData.LastValue = lastMetricValue.YValue.HasValue ? Math.Round( lastMetricValue.YValue.Value, roundYValues ? 0 : 2 ) : (decimal?)null;
                        metricYTDData.LastValueDate = lastMetricValue.MetricValueDateTime.HasValue ? lastMetricValue.MetricValueDateTime.Value.Date : DateTime.MinValue;
                    }

                    decimal? sum = qryMeasureValues.Sum( a => a.YValue );
                    metricYTDData.CumulativeValue = sum.HasValue ? Math.Round( sum.Value, roundYValues ? 0 : 2 ) : (decimal?)null;

                    // figure out goal as of current date time by figuring out the slope of the goal
                    var qryGoalValuesCurrentYear = metricValueService.Queryable()
                        .Where( a => a.MetricId == metricYTDData.Id )
                        .Where( a => a.MetricValueDateTime >= firstDayOfYear && a.MetricValueDateTime < firstDayOfNextYear )
                        .Where( a => a.MetricValueType == MetricValueType.Goal );

                    // if an entityTypeId/EntityId filter was specified, and the entityTypeId is the same as the metrics.EntityTypeId, filter the values to the specified entityId
                    if ( entityTypeId.HasValue && metric.EntityTypeId == entityTypeId )
                    {
                        if ( entityId.HasValue )
                        {
                            qryGoalValuesCurrentYear = qryGoalValuesCurrentYear.Where( a => a.EntityId == entityId );
                        }
                    }

                    MetricValue goalLineStartPoint = qryGoalValuesCurrentYear.Where( a => a.MetricValueDateTime <= currentDateTime ).OrderByDescending( a => a.MetricValueDateTime ).FirstOrDefault();
                    MetricValue goalLineEndPoint = qryGoalValuesCurrentYear.Where( a => a.MetricValueDateTime >= currentDateTime ).FirstOrDefault();
                    if ( goalLineStartPoint != null && goalLineEndPoint != null )
                    {
                        var changeInX = goalLineEndPoint.DateTimeStamp - goalLineStartPoint.DateTimeStamp;
                        var changeInY = goalLineEndPoint.YValue - goalLineStartPoint.YValue;
                        if ( changeInX != 0 )
                        {
                            decimal? slope = changeInY / changeInX;
                            decimal goalValue = ( ( slope * ( currentDateTime.ToJavascriptMilliseconds() - goalLineStartPoint.DateTimeStamp ) ) + goalLineStartPoint.YValue ).Value;
                            metricYTDData.GoalValue = Math.Round( goalValue, roundYValues ? 0 : 2 );
                        }
                    }
                    else
                    {
                        // if there isn't a both a start goal and end goal within the date range, there wouldn't be a goal line shown in a line chart, so don't display a goal in liquid either
                        metricYTDData.GoalValue = null;
                    }

                    metricsData.Add( metricYTDData.ToLiquid() );
                }

                Dictionary<string, object> mergeValues = new Dictionary<string, object>();
                mergeValues.Add( "Metrics", metricsData );

                string resultHtml = liquidTemplate.ResolveMergeFields( mergeValues );

                // show liquid help for debug
                if ( block.GetAttributeValue( "EnableDebug" ).AsBoolean() )
                {
                    resultHtml += mergeValues.lavaDebugInfo();
                }

                return resultHtml;
            }

            return string.Format(
                @"<div class='alert alert-danger'> 
                    unable to find block_id: {1}
                </div>",
                blockId );
        }
Exemple #23
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="metricValueId">The metric value identifier.</param>
        /// <param name="metricId">The metric identifier.</param>
        public void ShowDetail( int metricValueId, int? metricId )
        {
            pnlDetails.Visible = true;

            // Load depending on Add(0) or Edit
            MetricValue metricValue = null;
            if ( !metricValueId.Equals( 0 ) )
            {
                metricValue = new MetricValueService( new RockContext() ).Get( metricValueId );
                lActionTitle.Text = ActionTitle.Edit( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle();
            }

            if ( metricValue == null && metricId.HasValue )
            {
                metricValue = new MetricValue { Id = 0, MetricId = metricId.Value };
                metricValue.Metric = metricValue.Metric ?? new MetricService( new RockContext() ).Get( metricValue.MetricId );
                lActionTitle.Text = ActionTitle.Add( MetricValue.FriendlyTypeName ).FormatAsHtmlTitle();
            }

            hfMetricValueId.Value = metricValue.Id.ToString();

            LoadDropDowns();

            ddlMetricValueType.SelectedValue = metricValue.MetricValueType.ConvertToInt().ToString();
            tbXValue.Text = metricValue.XValue;
            tbYValue.Text = metricValue.YValue.ToString();
            hfMetricId.Value = metricValue.MetricId.ToString();
            tbNote.Text = metricValue.Note;
            dpMetricValueDateTime.SelectedDate = metricValue.MetricValueDateTime;

            var metricEntityType = EntityTypeCache.Read( metricValue.Metric.EntityTypeId ?? 0 );

            // Setup EntityType UI controls
            Control entityTypeEditControl = null;
            if ( metricEntityType != null && metricEntityType.SingleValueFieldType != null )
            {
                hfSingleValueFieldTypeId.Value = metricEntityType.SingleValueFieldType.Id.ToString();
                FieldTypeCache fieldType = FieldTypeCache.Read( hfSingleValueFieldTypeId.Value.AsInteger() );
                entityTypeEditControl = fieldType.Field.EditControl( new Dictionary<string, Rock.Field.ConfigurationValue>(), "entityTypeEditControl" );

                if ( entityTypeEditControl is IRockControl )
                {
                    ( entityTypeEditControl as IRockControl ).Label = fieldType.Name;
                }

                phEntityTypeEntityIdValue.Controls.Add( entityTypeEditControl );
                IEntityFieldType entityFieldType = metricEntityType.SingleValueFieldType.Field as IEntityFieldType;
                if ( entityFieldType != null )
                {
                    entityFieldType.SetEditValueFromEntityId( entityTypeEditControl, new Dictionary<string, ConfigurationValue>(), metricValue.EntityId );
                }
            }

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

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

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( MetricValue.FriendlyTypeName );
                btnCancel.Text = "Close";
            }

            ddlMetricValueType.Enabled = !readOnly;
            tbXValue.ReadOnly = readOnly;
            tbYValue.ReadOnly = readOnly;
            tbNote.ReadOnly = readOnly;
            dpMetricValueDateTime.Enabled = !readOnly;
            if ( entityTypeEditControl is WebControl )
            {
                ( entityTypeEditControl as WebControl ).Enabled = !readOnly;
            }

            btnSave.Visible = !readOnly;
        }
Exemple #24
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            int? metricId = hfMetricId.Value.AsIntegerOrNull();

            if ( !metricId.HasValue )
            {
                return;
            }

            var rockContext = new RockContext();
            SortProperty sortProperty = gMetricValues.SortProperty;
            MetricValueService metricValueService = new MetricValueService( rockContext );
            var qry = metricValueService.Queryable();

            qry = qry.Where( a => a.MetricId == metricId );

            var entityColumn = gMetricValues.Columns.OfType<BoundField>().FirstOrDefault( a => a.DataField == "EntityId" );
            var metric = new MetricService( rockContext ).Get( metricId ?? 0 );
            entityColumn.Visible = metric != null && metric.EntityTypeId.HasValue;

            if ( metric != null )
            {
                _entityNameLookup = new Dictionary<int, string>();

                var entityTypeCache = EntityTypeCache.Read( metric.EntityTypeId ?? 0 );
                if ( entityTypeCache != null )
                {
                    entityColumn.HeaderText = entityTypeCache.FriendlyName;
                    IQueryable<IEntity> entityQry = null;
                    if ( entityTypeCache.GetEntityType() == typeof( Rock.Model.Group ) )
                    {
                        // special case for Group since there could be a very large number (especially if you include families), so limit to GroupType.ShowInGroupList
                        entityQry = new GroupService( rockContext ).Queryable().Where( a => a.GroupType.ShowInGroupList );
                    }
                    else
                    {
                        Type[] modelType = { entityTypeCache.GetEntityType() };
                        Type genericServiceType = typeof( Rock.Data.Service<> );
                        Type modelServiceType = genericServiceType.MakeGenericType( modelType );
                        var serviceInstance = Activator.CreateInstance( modelServiceType, new object[] { rockContext } ) as IService;
                        MethodInfo qryMethod = serviceInstance.GetType().GetMethod( "Queryable", new Type[] { } );
                        entityQry = qryMethod.Invoke( serviceInstance, new object[] { } ) as IQueryable<IEntity>;
                    }

                    if ( entityQry != null )
                    {
                        var entityList = entityQry.ToList();
                        foreach ( var e in entityList )
                        {
                            _entityNameLookup.AddOrReplace( e.Id, e.ToString() );
                        }
                    }
                }
            }

            var drp = new DateRangePicker();
            drp.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" );
            if ( drp.LowerValue.HasValue )
            {
                qry = qry.Where( a => a.MetricValueDateTime >= drp.LowerValue.Value );
            }

            if ( drp.UpperValue.HasValue )
            {
                DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                qry = qry.Where( a => a.MetricValueDateTime < upperDate );
            }

            var metricValueType = gfMetricValues.GetUserPreference( "Goal/Measure" ).ConvertToEnumOrNull<MetricValueType>();
            if ( metricValueType.HasValue )
            {
                qry = qry.Where( a => a.MetricValueType == metricValueType.Value );
            }

            var entityParts = gfMetricValues.GetUserPreference( this.EntityPreferenceKey ).Split( '|' );
            if ( entityParts.Length == 2 )
            {
                if ( entityParts[0].AsInteger() == metric.EntityTypeId )
                {
                    var entityId = entityParts[1].AsIntegerOrNull();
                    if ( entityId.HasValue )
                    {
                        qry = qry.Where( a => a.EntityId == entityId );
                    }
                }
            }

            if ( sortProperty != null )
            {
                gMetricValues.DataSource = qry.Sort( sortProperty ).ToList();
            }
            else
            {
                gMetricValues.DataSource = qry.OrderBy( s => s.Order ).ThenBy( s => s.MetricValueDateTime ).ThenBy( s => s.YValue ).ThenBy( s => s.XValue ).ToList();
            }

            gMetricValues.DataBind();
        }
Exemple #25
0
        /// <summary>
        /// Handles the Click event of the btnSaveValue 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 btnSaveValue_Click( object sender, EventArgs e )
        {
            using ( new Rock.Data.UnitOfWorkScope() )
            {
                int metricValueId = hfMetricValueId.ValueAsInt();
                var metricValueService = new MetricValueService();
                MetricValue metricValue;

                if ( metricValueId == 0 )
                {
                    metricValue = new MetricValue();
                    metricValue.IsSystem = false;
                    metricValue.MetricId = hfMetricId.ValueAsInt();
                    metricValueService.Add( metricValue, CurrentPersonId );
                }
                else
                {
                    metricValue = metricValueService.Get( metricValueId );
                }

                metricValue.Value = tbValue.Text;
                metricValue.Description = tbValueDescription.Text;
                metricValue.xValue = tbXValue.Text;
                metricValue.Label = tbLabel.Text;
                metricValue.isDateBased = cbIsDateBased.Checked;
                metricValue.MetricId = Int32.Parse(ddlMetricFilter.SelectedValue);

                if ( metricValue.IsValid )
                {
                    metricValueService.Save( metricValue, CurrentPersonId );
                    BindGrid();
                    hfMetricValueId.Value = string.Empty;
                    mdValueDialog.Hide();
                }
            }
        }
        protected void CalulateMetrics(int CampusId)
        {
            // specify which attribute key we want to work with
            var attributeKeyCompositeUseGlobalValue = "CompositeUseGlobalValue";
            var attributeKeyCompositeGoalMultiplier = "CompositeGoalMultiplier";

            var attributeValueService = new AttributeValueService(rockContext);

            // specify NULL as the EntityId since this is a GlobalAttribute
            var compositeUseGlobalValue = attributeValueService.GetGlobalAttributeValue(attributeKeyCompositeUseGlobalValue);
            var compositeGoalMultiplier = attributeValueService.GetGlobalAttributeValue(attributeKeyCompositeGoalMultiplier);

            if (bool.Parse(compositeUseGlobalValue.ToString()) == true)
            {
                UseGlobalAttributeGoal = true;
                GoalMultiplier = Convert.ToDouble(compositeGoalMultiplier.ToString());
            }

            //Set Last Sunday Date
            DateTime now = DateTime.Now;
            DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
            SundayDate = dt.ToShortDateString();
            SundayDateSQLFormatted = dt.Date.ToString("yyyy-MM-dd");

            DateTime lastTuesday = DateTime.Now.AddDays(-1);
            while (lastTuesday.DayOfWeek != DayOfWeek.Wednesday)
                lastTuesday = lastTuesday.AddDays(-1);

            DateTime lastWednesday = DateTime.Now.AddDays(-1);
            while (lastWednesday.DayOfWeek != DayOfWeek.Wednesday)
                lastWednesday = lastWednesday.AddDays(-1);

            FinancialStartDate = lastTuesday.AddDays(-7).ToString("yyyy-MM-dd");
            FinancialEndDate = lastWednesday.ToString("yyyy-MM-dd");

            FinancialStartDateLastWeek = lastTuesday.AddDays(-14).ToString("yyyy-MM-dd");
            FinancialEndDateLastWeek = lastWednesday.AddDays(-7).ToString("yyyy-MM-dd");

            sMonth = DateTime.Now.Month.ToString();
            sYear = DateTime.Now.Year.ToString();
            int iMonth = Int32.Parse(sMonth);
            int iYear = Int32.Parse(sYear);

            int lastDayOfCurrentMonth = DateTime.DaysInMonth(iYear, iMonth);
            int lastDayOfLastMonth = DateTime.DaysInMonth(iYear, iMonth - 1);

            DateTime fiscalYearStartDate = new DateTime(iYear, 9, 1);
            DateTime fiscalYearEndDate = new DateTime(iYear + 1, 8, 31);
            DateTime lastFiscalYearStartDate = new DateTime(iYear - 1, 9, 1);
            DateTime lastFiscalYearEndDate = new DateTime(iYear, 8, 31);

            DateTime start2020 = new DateTime(2020, 1, 1);
            DateTime end2020 = new DateTime(2020, 12, 31);

            if (iMonth < 9)
            {
                fiscalYearStartDate = fiscalYearStartDate.AddYears(-1);
                fiscalYearEndDate = fiscalYearEndDate.AddYears(-1);
                lastFiscalYearStartDate = lastFiscalYearStartDate.AddYears(-1);
                lastFiscalYearEndDate = lastFiscalYearEndDate.AddYears(-1);
            }

            DateTime periodEndDate = new DateTime(iYear, iMonth - 1, lastDayOfLastMonth);
            DateTime lastPeriodEndDate = new DateTime(iYear - 1, iMonth - 1, lastDayOfLastMonth);

            FiscalYearStartDate = fiscalYearStartDate.ToShortDateString();
            FiscalYearEndDate = fiscalYearEndDate.ToShortDateString();
            PeriodStartDate = fiscalYearStartDate.ToShortDateString();
            PeriodEndDate = periodEndDate.ToShortDateString();
            LastPeriodStartDate = lastFiscalYearStartDate.ToShortDateString();
            LastPeriodEndDate = lastPeriodEndDate.ToShortDateString();

            Last8WkStartDate = now.AddDays(-57).ToShortDateString();
            Last8WkEndDate = now.ToShortDateString();
            Last8WkStartDateLy = now.AddDays(-57).AddYears(-1).ToShortDateString();
            Last8WkEndDateLy = now.AddYears(-1).ToShortDateString();

            Last6WkStartDate = now.AddDays(-43).ToShortDateString();
            Last6WkEndDate = now.ToShortDateString();
            Last6WkStartDateLy = now.AddDays(-43).AddYears(-1).ToShortDateString();
            Last6WkEndDateLy = now.AddYears(-1).ToShortDateString();

            DateTime last6WkStartDate = now.AddDays(-43);
            DateTime last6WkEndDate = now;
            DateTime last6WkStartDateLy = now.AddDays(-43).AddYears(-1);
            DateTime last6WkEndDateLy = now.AddYears(-1);

            switch (iMonth)
            {
                case 09:
                    CurrentMonthInFiscalYear = 1;
                    GoalOffsetMultiplier = .083;
                    SecondaryGoalOffsetMultiplier = .89;
                    break;
                case 10:
                    CurrentMonthInFiscalYear = 2;
                    GoalOffsetMultiplier = .167;
                    SecondaryGoalOffsetMultiplier = .90;
                    break;
                case 11:
                    CurrentMonthInFiscalYear = 3;
                    GoalOffsetMultiplier = .25;
                    SecondaryGoalOffsetMultiplier = .91;
                    break;
                case 12:
                    CurrentMonthInFiscalYear = 4;
                    GoalOffsetMultiplier = .333;
                    SecondaryGoalOffsetMultiplier = .92;
                    break;
                case 01:
                    CurrentMonthInFiscalYear = 5;
                    GoalOffsetMultiplier = .417;
                    SecondaryGoalOffsetMultiplier = .93;
                    break;
                case 02:
                    CurrentMonthInFiscalYear = 6;
                    GoalOffsetMultiplier = .5;
                    SecondaryGoalOffsetMultiplier = .94;
                    break;
                case 03:
                    CurrentMonthInFiscalYear = 7;
                    GoalOffsetMultiplier = .583;
                    SecondaryGoalOffsetMultiplier = .95;
                    break;
                case 04:
                    CurrentMonthInFiscalYear = 8;
                    GoalOffsetMultiplier = .667;
                    SecondaryGoalOffsetMultiplier = .96;
                    break;
                case 05:
                    CurrentMonthInFiscalYear = 9;
                    GoalOffsetMultiplier = .75;
                    SecondaryGoalOffsetMultiplier = .97;
                    break;
                case 06:
                    CurrentMonthInFiscalYear = 10;
                    GoalOffsetMultiplier = .883;
                    SecondaryGoalOffsetMultiplier = .98;
                    break;
                case 07:
                    CurrentMonthInFiscalYear = 11;
                    GoalOffsetMultiplier = .917;
                    SecondaryGoalOffsetMultiplier = .99;
                    break;
                case 08:
                    CurrentMonthInFiscalYear = 12;
                    GoalOffsetMultiplier = 1;
                    SecondaryGoalOffsetMultiplier = 1;
                    break;
            }

            //-------Attendance-------

            //Auditorium
            iAttendanceAud = Get6WkAttendanceAuditorium(CampusId, last6WkStartDate, last6WkEndDate);
            iAttendanceAudLastYear = Get6WkAttendanceAuditorium(CampusId, last6WkStartDateLy, last6WkEndDateLy);
            iAttendanceAudGoal2020 = GetMetrics(2, CampusId, start2020, end2020, 1);

            //Kids
            iAttendanceKids = Get6WkAttendanceKids(CampusId, last6WkStartDate, last6WkEndDate);
            iAttendanceKidsLastYear = Get6WkAttendanceKids(CampusId, last6WkStartDateLy, last6WkEndDateLy);
            iAttendanceChildGoal2020 = GetMetrics(3, CampusId, start2020, end2020, 1);

            //Students
            iAttendanceStudents = Get6WkAttendanceStudents(CampusId, last6WkStartDate, last6WkEndDate);
            iAttendanceStudentsLastYear = Get6WkAttendanceStudents(CampusId, last6WkStartDateLy, last6WkEndDateLy);
            iAttendanceStudentGoal2020 = GetMetrics(5, CampusId, start2020, end2020, 1);

            //HighSchool
            iAttendanceHighSchool = Get6WkAttendanceHighSchool(CampusId, last6WkStartDate, last6WkEndDate);
            iAttendanceHighSchoolLastYear = Get6WkAttendanceHighSchool(CampusId, last6WkStartDateLy, last6WkEndDateLy);
            iAttendanceStudentGoal2020 = GetMetrics(5, CampusId, start2020, end2020, 1);

            if (UseGlobalAttributeGoal == true)
            {
                iAttendanceAudGoalCurrent = Convert.ToInt32((double?)iAttendanceAudLastYear * GoalMultiplier);
                iAttendanceChildGoalCurrent = Convert.ToInt32((double?)iAttendanceKidsLastYear * GoalMultiplier);
                iAttendanceStudentGoalCurrent = Convert.ToInt32((double?)iAttendanceStudentsLastYear * GoalMultiplier);
            }
            else
            {
                iAttendanceAudGoalCurrent = GetMetrics(2, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iAttendanceChildGoalCurrent = GetMetrics(3, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iAttendanceStudentGoalCurrent = GetMetrics(5, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
            }

            //All
            iAttendanceAll = Get6WkAttendanceAll(CampusId, last6WkStartDate, last6WkEndDate);
            iAttendanceAllLastYear = Get6WkAttendanceAll(CampusId, last6WkStartDateLy, last6WkEndDateLy);
            iAttendanceAllGoalCurrent = iAttendanceAudGoalCurrent + iAttendanceChildGoalCurrent + iAttendanceStudentGoalCurrent;
            iAttendanceAllGoal2020 = iAttendanceAudGoal2020 + iAttendanceChildGoal2020 + iAttendanceStudentGoal2020;

            //Calculate attendance goal progress
            iAttendanceAudGoalProgress = (double?)iAttendanceAud / ((double?)iAttendanceAudGoalCurrent * SecondaryGoalOffsetMultiplier) * 100;
            iAttendanceChildGoalProgress = (double?)iAttendanceKids / ((double?)iAttendanceChildGoalCurrent * SecondaryGoalOffsetMultiplier) * 100;
            iAttendanceStudentGoalProgress = (double?)iAttendanceStudents / ((double?)iAttendanceStudentGoalCurrent * SecondaryGoalOffsetMultiplier) * 100;
            iAttendanceHighSchoolGoalProgress = (double?)iAttendanceHighSchool / ((double?)iAttendanceHighSchoolGoalCurrent * SecondaryGoalOffsetMultiplier) * 100;
            iAttendanceAllGoalProgress = (double?)iAttendanceAll / ((double?)iAttendanceAllGoalCurrent * SecondaryGoalOffsetMultiplier) * 100;

            //-------Baptisms-------

            //YTD
            iBaptisms = GetMetrics(11, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iBaptismsLastYear = GetMetrics(11, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iBaptismsGoalCurrent = GetMetrics(11, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iBaptismsGoal2020 = GetMetrics(11, CampusId, start2020, end2020, 1);

            //8Wk
            iBaptisms8Wk = GetMetrics(11, CampusId, now.AddDays(-57), now, 0);
            iBaptisms8WkLy = GetMetrics(11, CampusId, now.AddDays(-57).AddYears(-1), now.AddYears(-1), 0);
            iBaptisms8WkProgress = (((double)iBaptisms8Wk - (double)iBaptisms8WkLy) / (double)iBaptisms8WkLy) * 100;

            //-------Partners-------

            //YTD
            iPartners = GetMetricsLatest(20, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iPartnersLastYear = GetMetricsLatest(20, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iPartnersGoalCurrent = GetMetricsLatest(20, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iPartnersGoal2020 = GetMetricsLatest(20, CampusId, start2020, end2020, 1);

            //-------Commitments-------

            //YTD
            iCommitments = GetMetrics(12, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iCommitmentsLastYear = GetMetrics(12, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iCommitmentsGoalCurrent = GetMetrics(12, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iCommitmentsGoal2020 = GetMetrics(12, CampusId, start2020, end2020, 1);

            //8Wk
            iCommitments8Wk = GetMetrics(12, CampusId, now.AddDays(-57), now, 0);
            iCommitments8WkLy = GetMetrics(12, CampusId, now.AddDays(-57).AddYears(-1), now.AddYears(-1), 0);

            //-------Recommitments-------

            //YTD
            iRecommitments = GetMetrics(13, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iRecommitmentsLastYear = GetMetrics(13, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iRecommitmentsGoalCurrent = GetMetrics(13, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iRecommitmentsGoal2020 = GetMetrics(13, CampusId, start2020, end2020, 1);

            //8Wk
            iRecommitments8Wk = GetMetrics(13, CampusId, now.AddDays(-57), now, 0);
            iRecommitments8WkLy = GetMetrics(13, CampusId, now.AddDays(-57).AddYears(-1), now.AddYears(-1), 0);

            //-------Volunteers-------

            //YTD
            iVolunteers = GetMetricsLatest(16, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iVolunteersLastYear = GetMetricsLatest(16, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iVolunteersGoalCurrent = GetMetricsLatest(16, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iVolunteersGoal2020 = GetMetricsLatest(16, CampusId, start2020, end2020, 1);

            //-------SmallGroupParticipants-------

            //YTD
            iSmallGroupParticipants = GetMetricsLatest(17, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iSmallGroupParticipantsLastYear = GetMetricsLatest(17, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iSmallGroupParticipantsGoalCurrent = GetMetricsLatest(17, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iSmallGroupParticipantsGoal2020 = GetMetricsLatest(17, CampusId, start2020, end2020, 1);

            //-------SmallGroupLeaders-------

            //YTD
            iSmallGroupLeaders = GetMetricsLatest(18, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iSmallGroupLeadersLastYear = GetMetricsLatest(18, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iSmallGroupLeadersGoalCurrent = GetMetricsLatest(18, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iSmallGroupLeadersGoal2020 = GetMetricsLatest(18, CampusId, start2020, end2020, 1);

            //-------SmallGroups-------

            //YTD
            iSmallGroups = GetMetricsLatest(34, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iSmallGroupsLastYear = GetMetricsLatest(34, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iSmallGroupsGoalCurrent = GetMetricsLatest(34, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iSmallGroupsGoal2020 = GetMetricsLatest(34, CampusId, start2020, end2020, 1);

            //-------NewtoNewPointe-------

            //YTD
            iNewtoNewPointe = GetMetrics(21, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iNewtoNewPointeLastYear = GetMetrics(21, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iNewtoNewPointeGoalCurrent = GetMetrics(21, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iNewtoNewPointeGoal2020 = GetMetrics(21, CampusId, start2020, end2020, 1);

            //8Wk
            iNewtoNewPointe8Wk = GetMetrics(21, CampusId, now.AddDays(-57), now, 0);
            iNewtoNewPointe8WkLy = GetMetrics(21, CampusId, now.AddDays(-57).AddYears(-1), now.AddYears(-1), 0);
            dNewtoNewPointe8WkProgress = (((double)iNewtoNewPointe8Wk - (double)iNewtoNewPointe8WkLy) / (double)iNewtoNewPointe8WkLy) * 100;

            //-------DiscoverGroups-------

            //YTD
            iDiscoverGroups = GetMetrics(22, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iDiscoverGroupsLastYear = GetMetrics(22, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iDiscoverGroupsGoalCurrent = GetMetrics(22, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iDiscoverGroupsGoal2020 = GetMetrics(2, CampusId, start2020, end2020, 1);

            //8Wk
            iDiscoverGroups8Wk = GetMetrics(22, CampusId, now.AddDays(-57), now, 0);
            iDiscoverGroups8WkLy = GetMetrics(22, CampusId, now.AddDays(-57).AddYears(-1), now.AddYears(-1), 0);
            dDiscoverGroups8WkProgress = (((double)iDiscoverGroups8Wk - (double)iDiscoverGroups8WkLy) / (double)iDiscoverGroups8WkLy) * 100;

            //-------CampusGroups-------

            //YTD
            iCampusGroups = GetMetrics(24, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iCampusGroupsLastYear = GetMetrics(24, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iCampusGroupsGoalCurrent = GetMetrics(24, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iCampusGroupsGoal2020 = GetMetrics(24, CampusId, start2020, end2020, 1);

            //8Wk
            iCampusGroups8Wk = GetMetrics(24, CampusId, now.AddDays(-57), now, 0);
            iCampusGroups8WkLy = GetMetrics(24, CampusId, now.AddDays(-57).AddYears(-1), now.AddYears(-1), 0);
            dCampusGroups8WkProgress = (((double)iCampusGroups8Wk - (double)iCampusGroups8WkLy) / (double)iCampusGroups8WkLy) * 100;

            //-------NewHere-------

            //YTD
            iNewHere = GetMetrics(14, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //LastYTD
            iNewHereLastYear = GetMetrics(14, CampusId, lastFiscalYearStartDate, lastPeriodEndDate, 0);

            //Current Goal
            iNewHereGoalCurrent = GetMetrics(14, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);

            //2020 Goal
            iNewHereGoal2020 = GetMetrics(14, CampusId, start2020, end2020, 1);

            //8Wk
            iNewHere8Wk = GetMetrics(14, CampusId, now.AddDays(-57), now, 0);
            iNewHere8WkLy = GetMetrics(14, CampusId, now.AddDays(-57).AddYears(-1), now.AddYears(-1), 0);
            dNewHere8WkProgress = (((double)iNewHere8Wk - (double)iNewHere8WkLy) / (double)iNewHere8WkLy) * 100;

            //-------Inactive Followups-------

            //Total
            iInactiveFollowup = GetMetrics(35, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //Completed
            iInactiveFollowupComplete = GetMetrics(38, CampusId, fiscalYearStartDate, periodEndDate, 0);

            //Inconplete
            iInactiveFollowupIncomplete = iInactiveFollowup - iInactiveFollowupComplete;

            //Progress
            iInactiveFollowupProgress = (double)iInactiveFollowupComplete / (double)iInactiveFollowup * 100;

            //-------Finances-------

            expenses = .99;
            giving = .95;

            //TODO: need to make a method to get these as a double (not an int)

            //Get Goals based on Global Attribute Multiplier or values stored in metrics table

            if (UseGlobalAttributeGoal == true)
            {
                iBaptismsGoalCurrent = Convert.ToInt32((double?)iBaptismsLastYear * GoalMultiplier);
                iPartnersGoalCurrent = Convert.ToInt32((double?)iPartnersLastYear * GoalMultiplier);
                iCommitmentsGoalCurrent = Convert.ToInt32((double?)iCommitmentsLastYear * GoalMultiplier);
                iRecommitmentsGoalCurrent = Convert.ToInt32((double?)iRecommitmentsLastYear * GoalMultiplier);
                iVolunteersGoalCurrent = Convert.ToInt32((double?)iVolunteersLastYear * GoalMultiplier);
                iSmallGroupParticipantsGoalCurrent = Convert.ToInt32((double?)iSmallGroupParticipantsLastYear * GoalMultiplier);
                iSmallGroupLeadersGoalCurrent = Convert.ToInt32((double?)iSmallGroupLeadersLastYear * GoalMultiplier);
                iNewtoNewPointeGoalCurrent = Convert.ToInt32((double?)iNewtoNewPointeLastYear * GoalMultiplier);
                iDiscoverGroupsGoalCurrent = Convert.ToInt32((double?)iDiscoverGroupsLastYear * GoalMultiplier);
                iCampusGroupsGoalCurrent = Convert.ToInt32((double?)iCampusGroupsLastYear * GoalMultiplier);
                iNewHereGoalCurrent = Convert.ToInt32((double?)iNewHereLastYear * GoalMultiplier);
                iSmallGroupsGoalCurrent = Convert.ToInt32((double?)iSmallGroupsLastYear * GoalMultiplier);

            }
            else
            {
                iBaptismsGoalCurrent = GetMetrics(11, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iPartnersGoalCurrent = GetMetricsLatest(20, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iCommitmentsGoalCurrent = GetMetrics(12, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iRecommitmentsGoalCurrent = GetMetrics(13, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iVolunteersGoalCurrent = GetMetricsLatest(16, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iSmallGroupParticipantsGoalCurrent = GetMetricsLatest(17, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iSmallGroupLeadersGoalCurrent = GetMetricsLatest(17, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iNewtoNewPointeGoalCurrent = GetMetrics(21, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iDiscoverGroupsGoalCurrent = GetMetrics(22, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iCampusGroupsGoalCurrent = GetMetrics(24, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iNewHereGoalCurrent = GetMetrics(14, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
                iSmallGroupsGoalCurrent = GetMetrics(34, CampusId, lastFiscalYearStartDate, fiscalYearEndDate, 1);
            }

            //-------AllCommitments-------

            //YTD
            iAllCommitments = iCommitments + iRecommitments;

            //LastYTD
            iAllCommitmentsLastYear = iCommitmentsLastYear + iRecommitmentsLastYear;

            //Current Goal
            iAllCommitmentsGoalCurrent = iCommitmentsGoalCurrent + iRecommitmentsGoalCurrent;

            //2020 Goal
            iAllCommitmentsGoal2020 = iCommitmentsGoal2020 + iRecommitmentsGoal2020;

            //Current Goal Progress
            iAllCommitmentsGoalProgress = ((double)iCommitments + (double)iRecommitments) / (((double)iCommitmentsGoalCurrent + (double)iRecommitmentsGoalCurrent) * GoalOffsetMultiplier) * 100;

            //8Wk
            iAllCommitments8Wk = iCommitments8Wk + iRecommitments8Wk;
            iAllCommitments8WkLy = iCommitments8WkLy + iRecommitments8WkLy;
            dAllCommitments8WkProgress = (((double)iAllCommitments8Wk - (double)iAllCommitments8WkLy) / (double)iAllCommitments8WkLy) * 100;

            // Caculate the progress toeards the goals
            iBaptismsGoalProgress = (double)iBaptisms / ((double)iBaptismsGoalCurrent * GoalOffsetMultiplier) * 100;
            iPartnersGoalProgress = (double)iPartners / ((double)iPartnersGoalCurrent * GoalOffsetMultiplier) * 100;
            iCommitmentsGoalProgress = (double)iCommitments / ((double)iCommitmentsGoalCurrent * GoalOffsetMultiplier) * 100;
            iRecommitmentsGoalProgress = (double)iRecommitments / ((double)iRecommitmentsGoalCurrent * GoalOffsetMultiplier) * 100;
            iVolunteersGoalProgress = (double)iVolunteers / ((double)iVolunteersGoalCurrent * GoalOffsetMultiplier) * 100;
            iSmallGroupParticipantsGoalProgress = (double)iSmallGroupParticipants / ((double)iSmallGroupParticipantsGoalCurrent * GoalOffsetMultiplier) * 100;
            iSmallGroupLeadersGoalProgress = (double)iSmallGroupLeaders / ((double)iSmallGroupLeadersGoalCurrent * GoalOffsetMultiplier) * 100;
            iNewtoNewPointeGoalProgress = (double)iNewtoNewPointe / ((double)iNewtoNewPointeGoalCurrent * GoalOffsetMultiplier) * 100;
            iDiscoverGroupsGoalProgress = (double)iDiscoverGroups / ((double)iDiscoverGroupsGoalCurrent * GoalOffsetMultiplier) * 100;
            iCampusGroupsGoalProgress = (double)iCampusGroups / ((double)iCampusGroupsGoalCurrent * GoalOffsetMultiplier) * 100;
            iNewHereGoalProgress = (double)iNewHere / ((double)iNewHereGoalCurrent * GoalOffsetMultiplier) * 100;
            iSmallGroupsGoalProgress = (double)iSmallGroups / ((double)iSmallGroupsGoalCurrent * GoalOffsetMultiplier) * 100;

            //Calculate the Composite Score
            CompositeScore = CalculateCompositeScore();

            //Save to the database

            if (CompositeScore > 0 && CompositeScore < 1000)
            {
                MetricValueService metricValueService = new MetricValueService(rockContext);

                MetricValue metricValue;

                metricValue = new MetricValue();
                metricValueService.Add(metricValue);
                metricValue.MetricId = 39;
                metricValue.Metric = metricValue.Metric ?? new MetricService(rockContext).Get(metricValue.MetricId);

                metricValue.MetricValueType = (MetricValueType)0;
                metricValue.XValue = null;
                metricValue.YValue = (decimal)CompositeScore;
                metricValue.Note = "";
                metricValue.MetricValueDateTime = dt;
                metricValue.EntityId = CampusId;

                rockContext.SaveChanges();
            }
        }
Exemple #27
0
        /// <summary>
        /// Shows the edit modal.
        /// </summary>
        /// <param name="valueId">The value unique identifier.</param>
        protected void ShowEdit( int valueId )
        {
            var metricId = hfMetricId.ValueAsInt();
            var metric = new MetricService().Get( metricId );

            MetricValue metricValue = null;
            if ( !valueId.Equals( 0 ) )
            {
                metricValue = new MetricValueService().Get( valueId );
                if ( metric != null )
                {
                    lActionTitle.Text = ActionTitle.Edit( "metric value for " + metric.Title );
                }
            }
            else
            {
                metricValue = new MetricValue { Id = 0 };
                metricValue.MetricId = metricId;
                if ( metric != null )
                {
                    lActionTitle.Text = ActionTitle.Add( "metric value for " + metric.Title );
                }
            }

            hfMetricValueId.SetValue( metricValue.Id );
            ddlMetricFilter.SelectedValue = hfMetricId.Value;
            tbValue.Text = metricValue.Value;
            tbValueDescription.Text = metricValue.Description;
            tbXValue.Text = metricValue.xValue;
            tbLabel.Text = metricValue.Label;
            cbIsDateBased.Checked = metricValue.isDateBased;

            mdValueDialog.Show();
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            MetricValueService metricValueService = new MetricValueService( new RockContext() );
            SortProperty sortProperty = gMetricValues.SortProperty;
            var qry = metricValueService.Queryable();

            // in case called normally
            int? metricId = PageParameter( "MetricId" ).AsInteger( false );

            // in case called from CategoryTreeView
            int? metricCategoryId = PageParameter( "MetricCategoryId" ).AsInteger( false );
            MetricCategory metricCategory = null;
            if ( metricCategoryId.HasValue )
            {
                if ( metricCategoryId.Value > 0 )
                {
                    // editing a metric, but get the metricId from the metricCategory
                    metricCategory = new MetricCategoryService( new RockContext() ).Get( metricCategoryId.Value );
                    if ( metricCategory != null )
                    {
                        metricId = metricCategory.MetricId;
                    }
                }
                else
                {
                    // adding a new metric. Block will (hopefully) not be shown
                    metricId = 0;
                }
            }

            hfMetricId.Value = metricId.ToString();
            hfMetricCategoryId.Value = metricCategoryId.ToString();

            this.Visible = metricId.HasValue;

            qry = qry.Where( a => a.MetricId == metricId );

            if ( sortProperty != null )
            {
                gMetricValues.DataSource = qry.Sort( sortProperty ).ToList();
            }
            else
            {
                gMetricValues.DataSource = qry.OrderBy( s => s.Order ).ThenBy( s => s.XValue ).ThenBy( s => s.MetricValueDateTime ).ThenBy( s => s.YValue ).ToList();
            }

            gMetricValues.DataBind();
        }