Exemplo n.º 1
0
        public void GetPersonCompletingProgramQuery_ReturnsCorrectData()
        {
            var startDate = new DateTime(2019, 1, 1);
            var endDate   = new DateTime(2019, 2, 4);

            var rockContext = new RockContext();
            var service     = new StepProgramService(rockContext);
            var stepProgram = service.Queryable().Where(sp => sp.ForeignKey == ForeignKey).First();
            var result      = service.GetPersonCompletingProgramQuery(stepProgram.Id).ToList();

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count);

            var personService = new PersonService(rockContext);
            var kathy         = personService.Get(KathyKolePersonGuidString.AsGuid());
            var jerry         = personService.Get(JerryJenkinsPersonGuidString.AsGuid());

            var kathyResult = result.FirstOrDefault(r => r.PersonId == kathy.Id);
            var jerryResult = result.FirstOrDefault(r => r.PersonId == jerry.Id);

            // Kathy completed once in 2019 and once in 2020 - we should only get the first
            Assert.IsNotNull(kathyResult);
            Assert.AreEqual(new DateTime(2019, 1, 1), kathyResult.StartedDateTime);
            Assert.AreEqual(new DateTime(2019, 4, 1), kathyResult.CompletedDateTime);

            // Jerry completed with two aliases. The first alias started in 2019. The second alias finished in 2020
            Assert.IsNotNull(jerryResult);
            Assert.AreEqual(new DateTime(2019, 1, 1), jerryResult.StartedDateTime);
            Assert.AreEqual(new DateTime(2020, 3, 1), jerryResult.CompletedDateTime);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the step program (model) that should be displayed in the block
        /// 1.) Use the block setting
        /// 2.) Use the page parameter
        /// 3.) Use the first active program
        /// </summary>
        /// <returns></returns>
        private StepProgram GetStepProgram()
        {
            if (_stepProgram == null)
            {
                var programGuid = GetAttributeValue(AttributeKey.StepProgram).AsGuidOrNull();
                var programId   = PageParameter(PageParameterKey.StepProgramId).AsIntegerOrNull();
                var rockContext = GetRockContext();
                var service     = new StepProgramService(rockContext);

                if (programGuid.HasValue)
                {
                    // 1.) Use the block setting
                    _stepProgram = service.Queryable()
                                   .AsNoTracking()
                                   .FirstOrDefault(sp => sp.Guid == programGuid.Value && sp.IsActive);
                }
                else if (programId.HasValue)
                {
                    // 2.) Use the page parameter
                    _stepProgram = service.Queryable()
                                   .AsNoTracking()
                                   .FirstOrDefault(sp => sp.Id == programId.Value && sp.IsActive);
                }
                else
                {
                    // 3.) Just use the first active program
                    _stepProgram = service.Queryable()
                                   .AsNoTracking()
                                   .FirstOrDefault(sp => sp.IsActive);
                }
            }

            return(_stepProgram);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Loads the drop down items.
        /// </summary>
        /// <param name="picker">The picker.</param>
        /// <param name="includeEmptyOption">if set to <c>true</c> [include empty option].</param>
        public static void LoadDropDownItems(IStepProgramPicker picker, bool includeEmptyOption)
        {
            var selectedItems = picker.Items.Cast <ListItem>()
                                .Where(i => i.Selected)
                                .Select(i => i.Value).AsIntegerList();

            picker.Items.Clear();

            if (includeEmptyOption)
            {
                // add Empty option first
                picker.Items.Add(new ListItem());
            }

            var stepProgramService = new StepProgramService(new RockContext());
            var stepPrograms       = stepProgramService.Queryable().AsNoTracking()
                                     .Where(sp => sp.IsActive)
                                     .OrderBy(sp => sp.Order)
                                     .ThenBy(sp => sp.Name)
                                     .ToList();

            foreach (var stepProgram in stepPrograms)
            {
                var li = new ListItem(stepProgram.Name, stepProgram.Id.ToString());
                li.Selected = selectedItems.Contains(stepProgram.Id);
                picker.Items.Add(li);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Handles the Delete event of the gStepProgram 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 gStepProgram_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();

            var stepProgramService = new StepProgramService(rockContext);

            var stepProgram = stepProgramService.Get(e.RowKeyId);

            if (stepProgram == null)
            {
                mdGridWarning.Show("This item could not be found.", ModalAlertType.Information);
                return;
            }

            string errorMessage;

            if (!stepProgramService.CanDelete(stepProgram, out errorMessage))
            {
                mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                return;
            }

            stepProgramService.Delete(stepProgram);

            rockContext.SaveChanges();

            BindGrid();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var dataContext = new RockContext();

            var stepProgramsQry = new StepProgramService(dataContext)
                                  .Queryable();

            // Filter by: Category
            if (_categoryGuids.Any())
            {
                stepProgramsQry = stepProgramsQry.Where(a => a.Category != null && _categoryGuids.Contains(a.Category.Guid));
            }
            else
            {
                var categoryId = rFilter.GetUserPreference("Category").AsIntegerOrNull();

                if (categoryId.HasValue && categoryId > 0)
                {
                    stepProgramsQry = stepProgramsQry.Where(a => a.CategoryId == categoryId.Value);
                }
            }

            // Filter by: Active
            var activeFilter = rFilter.GetUserPreference("Active").ToLower();

            switch (activeFilter)
            {
            case "active":
                stepProgramsQry = stepProgramsQry.Where(a => a.IsActive);
                break;

            case "inactive":
                stepProgramsQry = stepProgramsQry.Where(a => !a.IsActive);
                break;
            }

            // Sort by: Order
            stepProgramsQry = stepProgramsQry.OrderBy(b => b.Order);

            // Retrieve the Step Program data models and create corresponding view models to display in the grid.
            var stepService = new StepService(dataContext);

            var completedStepsQry = stepService.Queryable().Where(x => x.StepStatus != null && x.StepStatus.IsCompleteStatus);

            var stepPrograms = stepProgramsQry.Select(x =>
                                                      new StepProgramListItemViewModel
            {
                Id                 = x.Id,
                Name               = x.Name,
                IconCssClass       = x.IconCssClass,
                Category           = x.Category.Name,
                StepTypeCount      = x.StepTypes.Count,
                StepCompletedCount = completedStepsQry.Count(y => y.StepType.StepProgramId == x.Id)
            })
                               .ToList();

            gStepProgram.DataSource = stepPrograms;

            gStepProgram.DataBind();
        }
        /// <summary>
        /// Creates the test step program.
        /// There are 2 step statuses: 1 complete and 1 in-progress
        /// There are 4 step types:
        ///     1) Allow multiple with an auto-complete dataview
        ///     2) Allow multiple without an autocomplete dataview
        ///     3) No multiple with an auto-complete dataview
        ///     4) No multiple with no auto-complete dataview
        /// </summary>
        private static void CreateTestStepProgram()
        {
            var rockContext        = new RockContext();
            var stepProgramService = new StepProgramService(rockContext);

            var dataViewService = new DataViewService(rockContext);
            var dataView        = dataViewService.Queryable().FirstOrDefault(dv => dv.ForeignKey == ForeignKey);

            var stepProgram = new StepProgram
            {
                Name         = "Test",
                ForeignKey   = ForeignKey,
                StepStatuses = new List <StepStatus> {
                    new StepStatus
                    {
                        ForeignKey       = ForeignKey,
                        Name             = "Complete",
                        IsCompleteStatus = true
                    },
                    new StepStatus
                    {
                        ForeignKey       = ForeignKey,
                        Name             = "In-progress",
                        IsCompleteStatus = false
                    }
                },
                StepTypes = new List <StepType>
                {
                    new StepType
                    {
                        Name                 = "Test: AllowMultiple with DataView",
                        ForeignKey           = ForeignKey,
                        AllowMultiple        = true,
                        AutoCompleteDataView = dataView
                    },
                    new StepType
                    {
                        Name          = "Test: AllowMultiple without DataView",
                        ForeignKey    = ForeignKey,
                        AllowMultiple = true
                    },
                    new StepType
                    {
                        Name                 = "Test: No multiple with DataView",
                        ForeignKey           = ForeignKey,
                        AllowMultiple        = false,
                        AutoCompleteDataView = dataView
                    },
                    new StepType
                    {
                        Name          = "Test: No multiple and no dataview",
                        ForeignKey    = ForeignKey,
                        AllowMultiple = false
                    }
                }
            };

            stepProgramService.Add(stepProgram);
            rockContext.SaveChanges();
        }
Exemplo n.º 7
0
        private StepProgram GetStepProgram(RockContext dataContext, int stepProgramId)
        {
            var programService = new StepProgramService(dataContext);

            var stepProgram = programService.Get(stepProgramId);

            return(stepProgram);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Clears the block data.
 /// </summary>
 private void ClearBlockData()
 {
     _rockContext        = null;
     _stepProgramService = null;
     _stepProgram        = null;
     _stepType           = null;
     _person             = null;
     _personService      = null;
 }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the step program service.
        /// </summary>
        /// <returns></returns>
        private StepProgramService GetStepProgramService()
        {
            if (_stepProgramService == null)
            {
                var rockContext = GetRockContext();
                _stepProgramService = new StepProgramService(rockContext);
            }

            return(_stepProgramService);
        }
        public static void ClassInitialize(TestContext testContext)
        {
            _rockContext            = new RockContext();
            _stepProgramService     = new StepProgramService(_rockContext);
            _achievementTypeService = new AchievementTypeService(_rockContext);

            DeleteTestData();
            CreateStepProgramData();
            CreateAchievementTypeData();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Populates the selection lists for Step Type and Step Status.
        /// </summary>
        /// <param name="filterField">The filter field.</param>
        private void PopulateStepProgramRelatedSelectionLists(FilterField filterField)
        {
            var dataContext = new RockContext();

            var programService = new StepProgramService(dataContext);

            SingleEntityPicker <StepProgram> stepProgramSingleEntityPicker = filterField.ControlsOfTypeRecursive <SingleEntityPicker <StepProgram> >().FirstOrDefault(c => c.HasCssClass("js-step-program-picker"));
            RockCheckBoxList cblStepType    = filterField.ControlsOfTypeRecursive <RockCheckBoxList>().FirstOrDefault(c => c.HasCssClass("js-step-type"));
            RockCheckBoxList _cblStepStatus = filterField.ControlsOfTypeRecursive <RockCheckBoxList>().FirstOrDefault(c => c.HasCssClass("js-step-status"));

            int?stepProgramId = stepProgramSingleEntityPicker.SelectedId;

            StepProgram stepProgram = null;

            if (stepProgramId != null)
            {
                stepProgram = programService.Get(stepProgramId.Value);
            }

            if (stepProgram != null)
            {
                // Step Type list
                cblStepType.Items.Clear();

                var stepTypeService = new StepTypeService(dataContext);

                var stepTypes = stepTypeService.Queryable().Where(x => x.StepProgramId == stepProgramId);

                foreach (var item in stepTypes)
                {
                    cblStepType.Items.Add(new ListItem(item.Name, item.Guid.ToString()));
                }

                cblStepType.Visible = cblStepType.Items.Count > 0;

                // Step Status list
                _cblStepStatus.Items.Clear();

                var stepStatusService = new StepStatusService(dataContext);

                var stepStatuses = stepStatusService.Queryable().Where(x => x.StepProgramId == stepProgramId);

                foreach (var item in stepStatuses)
                {
                    _cblStepStatus.Items.Add(new ListItem(item.Name, item.Guid.ToString()));
                }

                _cblStepStatus.Visible = _cblStepStatus.Items.Count > 0;
            }
            else
            {
                cblStepType.Visible    = false;
                _cblStepStatus.Visible = false;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            var stepProgramPicker = (controls[0] as SingleEntityPicker <StepProgram>);
            var cblStepTypes      = (controls[1] as RockCheckBoxList);
            var cblStepStatuses   = (controls[2] as RockCheckBoxList);
            var sdpDateStarted    = (controls[3] as SlidingDateRangePicker);
            var sdpDateCompleted  = (controls[4] as SlidingDateRangePicker);
            var cblStepCampuses   = (controls[5] as RockCheckBoxList);

            var settings = new FilterSettings(selection);

            // Step Program
            var dataContext = new RockContext();

            StepProgram stepProgram = null;

            if (settings.StepProgramGuid.HasValue)
            {
                stepProgram = new StepProgramService(dataContext).Get(settings.StepProgramGuid.Value);
            }

            int?stepProgramId = null;

            if (stepProgram != null)
            {
                stepProgramId = stepProgram.Id;
            }

            stepProgramPicker.SetValue(stepProgramId);
            var filterField = stepProgramPicker.FirstParentControlOfType <FilterField>();

            PopulateStepProgramRelatedSelectionLists(filterField);

            foreach (var item in cblStepTypes.Items.OfType <ListItem>())
            {
                item.Selected = settings.StepTypeGuids.Contains(item.Value.AsGuid());
            }

            foreach (var item in cblStepStatuses.Items.OfType <ListItem>())
            {
                item.Selected = settings.StepStatusGuids.Contains(item.Value.AsGuid());
            }

            sdpDateStarted.DelimitedValues = settings.StartedInPeriod.ToDelimitedString();

            sdpDateCompleted.DelimitedValues = settings.CompletedInPeriod.ToDelimitedString();

            PopulateStepCampuses(cblStepCampuses);

            foreach (var item in cblStepCampuses.Items.OfType <ListItem>())
            {
                item.Selected = settings.StepCampusGuids.Contains(item.Value.AsGuid());
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Handles the GridReorder event of the gStepProgram control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs" /> instance containing the event data.</param>
        void gStepProgram_GridReorder(object sender, GridReorderEventArgs e)
        {
            var rockContext  = new RockContext();
            var service      = new StepProgramService(rockContext);
            var stepPrograms = service.Queryable().OrderBy(b => b.Order);

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

            BindGrid();
        }
Exemplo n.º 14
0
        private StepProgram GetStepProgram(RockContext dataContext, Guid?stepProgramGuid)
        {
            if (stepProgramGuid == null)
            {
                return(null);
            }

            var programService = new StepProgramService(dataContext);

            var stepProgram = programService.Get(stepProgramGuid.Value);

            return(stepProgram);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gets the specified <see cref="StepProgram"/> by Id.
        /// </summary>
        /// <param name="stepProgramGuid">The identifier of the <see cref="StepProgram"/>.</param>
        /// <returns>A <see cref="StepProgram"/> or null.</returns>
        private StepProgram GetStepProgram(Guid?stepProgramGuid)
        {
            if (!stepProgramGuid.HasValue || stepProgramGuid.Value == Guid.Empty)
            {
                return(null);
            }

            using (var rockContext = new RockContext())
            {
                var stepTypeService = new StepProgramService(rockContext);
                return(stepTypeService.Get(stepProgramGuid.Value));
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Delete the test data
        /// </summary>
        private static void DeleteTestData()
        {
            using (var rockContext = new RockContext())
            {
                var stepService = new StepService(rockContext);
                var stepQuery   = stepService.Queryable().Where(s => s.ForeignKey == ForeignKey);
                stepService.DeleteRange(stepQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var stepProgramService = new StepProgramService(rockContext);
                var stepProgramQuery   = stepProgramService.Queryable().Where(sp => sp.ForeignKey == ForeignKey);
                stepProgramService.DeleteRange(stepProgramQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var personSearchKeyService = new PersonSearchKeyService(rockContext);
                var personSearchKeyQuery   = personSearchKeyService.Queryable()
                                             .Where(psk =>
                                                    psk.PersonAlias.Person.ForeignKey == ForeignKey ||
                                                    PersonGuids.Contains(psk.PersonAlias.Person.Guid));
                personSearchKeyService.DeleteRange(personSearchKeyQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var personAliasService = new PersonAliasService(rockContext);
                var personAliasQuery   = personAliasService.Queryable()
                                         .Where(pa =>
                                                pa.Person.ForeignKey == ForeignKey ||
                                                PersonGuids.Contains(pa.Person.Guid));
                personAliasService.DeleteRange(personAliasQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);
                var personQuery   = personService.Queryable()
                                    .Where(p =>
                                           p.ForeignKey == ForeignKey ||
                                           PersonGuids.Contains(p.Guid));
                personService.DeleteRange(personQuery);
                rockContext.SaveChanges();
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Populates the selection lists for Step Type and Step Status.
        /// </summary>
        /// <param name="stepProgramId">The Step Program identifier.</param>
        private void PopulateStepProgramRelatedSelectionLists(int?stepProgramId)
        {
            var dataContext = new RockContext();

            var programService = new StepProgramService(dataContext);

            StepProgram stepProgram = null;

            if (stepProgramId != null)
            {
                stepProgram = programService.Get(stepProgramId.Value);
            }

            if (stepProgram != null)
            {
                // Step Type list
                _cblStepType.Items.Clear();

                var stepTypeService = new StepTypeService(dataContext);

                var stepTypes = stepTypeService.Queryable().Where(x => x.StepProgramId == stepProgramId);

                foreach (var item in stepTypes)
                {
                    _cblStepType.Items.Add(new ListItem(item.Name, item.Guid.ToString()));
                }

                _cblStepType.Visible = _cblStepType.Items.Count > 0;

                // Step Status list
                _cblStepStatus.Items.Clear();

                var stepStatusService = new StepStatusService(dataContext);

                var stepStatuses = stepStatusService.Queryable().Where(x => x.StepProgramId == stepProgramId);

                foreach (var item in stepStatuses)
                {
                    _cblStepStatus.Items.Add(new ListItem(item.Name, item.Guid.ToString()));
                }

                _cblStepStatus.Visible = _cblStepStatus.Items.Count > 0;
            }
            else
            {
                _cblStepType.Visible   = false;
                _cblStepStatus.Visible = false;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Get a list of triggers that may be fired by a state change in the entity being processed.
        /// </summary>
        /// <param name="dataContext"></param>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        protected override List <StepWorkflowTrigger> GetEntityChangeTriggers(RockContext dataContext, Guid entityGuid)
        {
            // Get the triggers associated with the Step Type to which this Step is related.
            var triggers = new List <StepWorkflowTrigger>();

            var stepTypeService = new StepTypeService(dataContext);

            var stepType = stepTypeService.Queryable()
                           .AsNoTracking()
                           .Include(x => x.StepWorkflowTriggers)
                           .FirstOrDefault(x => x.Id == this.StepTypeId);

            if (stepType == null)
            {
                ExceptionLogService.LogException($"StepChangeTransaction failed. Step Type does not exist [StepTypeId={ StepTypeId }].");
                return(null);
            }

            var stepTypeTriggers = stepType.StepWorkflowTriggers
                                   .Where(w => w.TriggerType != StepWorkflowTrigger.WorkflowTriggerCondition.Manual)
                                   .ToList();

            triggers.AddRange(stepTypeTriggers);

            var stepProgramId = stepType.StepProgramId;

            // Get the triggers associated with the Step Program to which this Step is related, but are not associated with a specific Step Type.
            var stepProgramService = new StepProgramService(dataContext);

            var stepProgram = stepProgramService.Queryable()
                              .AsNoTracking()
                              .Include(x => x.StepWorkflowTriggers)
                              .FirstOrDefault(x => x.Id == stepProgramId);

            if (stepProgram == null)
            {
                ExceptionLogService.LogException($"StepChangeTransaction failed. Step Program does not exist [StepProgramId={ stepProgramId }].");
                return(null);
            }

            var stepProgramTriggers = stepProgram.StepWorkflowTriggers
                                      .Where(w => w.StepTypeId == null &&
                                             w.TriggerType != StepWorkflowTrigger.WorkflowTriggerCondition.Manual)
                                      .ToList();

            triggers.AddRange(stepProgramTriggers);

            return(triggers);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Returns a dictionary of the items available for selection.
        /// </summary>
        /// <returns></returns>
        protected override Dictionary <Guid, string> OnGetItemList()
        {
            var service = new StepProgramService(new RockContext());

            var items = service
                        .Queryable()
                        .AsNoTracking()
                        .OrderBy(o => o.Name)
                        .Select(o => new
            {
                o.Guid,
                o.Name,
            })
                        .ToDictionary(o => o.Guid, o => o.Name);

            return(items);
        }
        /// <summary>
        /// Adds the step.
        /// </summary>
        /// <param name="stepTypeId">The step type identifier.</param>
        /// <param name="stepStatusId">The step status identifier.</param>
        /// <param name="personAliasId">The person alias identifier.</param>
        private void AddStep(int stepTypeId, int stepStatusId, int personAliasId)
        {
            var rockContext        = new RockContext();
            var stepService        = new StepService(rockContext);
            var stepProgramService = new StepProgramService(rockContext);

            // Get the step program with step types and statuses to better calculate the dates for the new step
            var stepProgram = stepProgramService.Queryable("StepTypes, StepStatuses").FirstOrDefault(sp =>
                                                                                                     sp.StepTypes.Any(st => st.Id == stepTypeId) &&
                                                                                                     sp.StepStatuses.Any(ss => ss.Id == stepStatusId));

            var stepType   = stepProgram?.StepTypes.FirstOrDefault(st => st.Id == stepTypeId);
            var stepStatus = stepProgram?.StepStatuses.FirstOrDefault(ss => ss.Id == stepStatusId);

            if (stepType == null)
            {
                ExceptionLogService.LogException($"Error adding step related to an achievement. The step type {stepTypeId} did not resolve.");
                return;
            }

            if (stepStatus == null)
            {
                ExceptionLogService.LogException($"Error adding step related to an achievement. The step status {stepStatusId} did not resolve.");
                return;
            }

            // Add the new step
            var step = new Step
            {
                StepTypeId        = stepTypeId,
                StepStatusId      = stepStatusId,
                CompletedDateTime = stepStatus.IsCompleteStatus ? EndDate : null,
                StartDateTime     = StartDate,
                EndDateTime       = stepType.HasEndDate ? EndDate : null,
                PersonAliasId     = personAliasId
            };

            // If the person cannot be added to the step type, then don't add anything since some step types only allow one step
            // or require pre-requisites
            if (stepService.CanAdd(step, out _))
            {
                stepService.Add(step);
            }

            rockContext.SaveChanges();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            var editControl = new StepProgramStepTypePicker {
                ID = id
            };

            if (configurationValues != null && configurationValues.ContainsKey(ConfigKey.DefaultStepProgramGuid))
            {
                var stepProgramGuid = configurationValues[ConfigKey.DefaultStepProgramGuid].Value.AsGuidOrNull();

                if (stepProgramGuid.HasValue)
                {
                    var stepProgram = new StepProgramService(new RockContext()).GetNoTracking(stepProgramGuid.Value);
                    editControl.DefaultStepProgramId = stepProgram?.Id;
                }
            }

            return(editControl);
        }
Exemplo n.º 22
0
        public void PersonSteps_WithStepProgramParameter_ReturnsStepsForProgramOnly()
        {
            // Test with Step Program Guid
            PersonStepsTestWithTemplate(TestGuids.TestPeople.TedDecker,
                                        Tests.Shared.TestGuids.Steps.ProgramAlphaGuid.ToString(),
                                        null,
                                        null,
                                        "Ted Decker:<p>Attender - Completed</p><p>Volunteer - Started</p>");

            // Test with Step Program Id.
            var dataContext = new RockContext();

            var stepProgramId = new StepProgramService(dataContext).GetId(Tests.Shared.TestGuids.Steps.ProgramAlphaGuid);

            PersonStepsTestWithTemplate(TestGuids.TestPeople.TedDecker,
                                        stepProgramId.ToString(),
                                        null,
                                        null,
                                        "Ted Decker: <p>Attender - Completed</p><p>Volunteer - Started</p>");
        }
Exemplo n.º 23
0
        /// <summary>
        /// Delete the test data
        /// </summary>
        private static void DeleteTestData()
        {
            var rockContext = new RockContext();

            var stepProgramService = new StepProgramService(rockContext);
            var stepProgramQuery   = stepProgramService.Queryable().Where(sp => sp.ForeignKey == ForeignKey);

            stepProgramService.DeleteRange(stepProgramQuery);
            rockContext.SaveChanges();

            var dataViewFilterService = new DataViewFilterService(rockContext);
            var dvfQuery = dataViewFilterService.Queryable().Where(dvf => dvf.DataView.ForeignKey == ForeignKey || dvf.ForeignKey == ForeignKey);

            dataViewFilterService.DeleteRange(dvfQuery);
            rockContext.SaveChanges();

            var dataViewService = new DataViewService(rockContext);
            var dvQuery         = dataViewService.Queryable().Where(dv => dv.ForeignKey == ForeignKey);

            dataViewService.DeleteRange(dvQuery);
            rockContext.SaveChanges();

            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var personSearchKeyQuery   = personSearchKeyService.Queryable().Where(psk => psk.PersonAlias.Person.ForeignKey == ForeignKey);

            personSearchKeyService.DeleteRange(personSearchKeyQuery);

            var personAliasService = new PersonAliasService(rockContext);
            var personAliasQuery   = personAliasService.Queryable().Where(pa => pa.Person.ForeignKey == ForeignKey || pa.ForeignKey == ForeignKey);

            personAliasService.DeleteRange(personAliasQuery);
            rockContext.SaveChanges();

            var personService = new PersonService(rockContext);
            var personQuery   = personService.Queryable().Where(p => p.ForeignKey == ForeignKey);

            personService.DeleteRange(personQuery);
            rockContext.SaveChanges();
        }
Exemplo n.º 24
0
        /// <summary>
        /// Reads new values entered by the user for the field ( as Guid )
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public override string GetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            var stepProgramStepTypePicker = control as StepProgramStepTypePicker;

            if (stepProgramStepTypePicker != null)
            {
                var  rockContext     = new RockContext();
                Guid?stepProgramGuid = null;
                Guid?stepTypeGuid    = null;

                if (stepProgramStepTypePicker.StepProgramId.HasValue)
                {
                    var stepProgram = new StepProgramService(rockContext).GetNoTracking(stepProgramStepTypePicker.StepProgramId.Value);

                    if (stepProgram != null)
                    {
                        stepProgramGuid = stepProgram.Guid;
                    }
                }

                if (stepProgramStepTypePicker.StepTypeId.HasValue)
                {
                    var stepType = new StepTypeService(rockContext).GetNoTracking(stepProgramStepTypePicker.StepTypeId.Value);

                    if (stepType != null)
                    {
                        stepTypeGuid = stepType.Guid;
                    }
                }

                if (stepProgramGuid.HasValue || stepTypeGuid.HasValue)
                {
                    return(string.Format("{0}|{1}", stepProgramGuid, stepTypeGuid));
                }
            }

            return(null);
        }
Exemplo n.º 25
0
        public void Execute_AddsNewStep()
        {
            var jobContext = new TestJobContext();

            jobContext.JobDetail.JobDataMap[StepsAutomation.AttributeKey.DuplicatePreventionDayRange] = 7.ToString();

            var job = new StepsAutomation();

            job.Execute(jobContext);

            var rockContext        = new RockContext();
            var stepProgramService = new StepProgramService(rockContext);
            var stepProgram        = stepProgramService.Queryable("StepTypes.Steps.StepStatus").FirstOrDefault(sp => sp.ForeignKey == ForeignKey);

            Assert.AreEqual(4, stepProgram.StepTypes.Count);

            foreach (var stepType in stepProgram.StepTypes)
            {
                if (stepType.AutoCompleteDataViewId.HasValue)
                {
                    // The three people in the dataview should have completed steps
                    Assert.AreEqual(3, stepType.Steps.Count);

                    foreach (var step in stepType.Steps)
                    {
                        Assert.IsTrue(step.IsComplete);
                        Assert.IsTrue(step.StepStatus.IsCompleteStatus);
                        Assert.IsNotNull(step.CompletedDateTime);
                    }
                }
                else
                {
                    // No steps should exist for a step type with no auto-complete dataview
                    Assert.AreEqual(0, stepType.Steps.Count);
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Gets the models from the delimited values.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="stepProgram">The step program</param>
        /// <param name="stepType">The step type</param>
        private void GetModelsFromAttributeValue(string value, out StepProgram stepProgram, out StepType stepType)
        {
            stepProgram = null;
            stepType    = null;

            ParseDelimitedGuids(value, out var stepProgramGuid, out var stepTypeGuid);

            if (stepProgramGuid.HasValue || stepTypeGuid.HasValue)
            {
                var rockContext = new RockContext();

                if (stepProgramGuid.HasValue)
                {
                    var stepProgramService = new StepProgramService(rockContext);
                    stepProgram = stepProgramService.Queryable().AsNoTracking().FirstOrDefault(sp => sp.Guid == stepProgramGuid.Value);
                }

                if (stepTypeGuid.HasValue)
                {
                    var stepTypeService = new StepTypeService(rockContext);
                    stepType = stepTypeService.Queryable().AsNoTracking().FirstOrDefault(sp => sp.Guid == stepTypeGuid.Value);
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            var dataContext = new RockContext();

            // Step Program selection
            var stepProgramSingleEntityPicker = new SingleEntityPicker <StepProgram>();

            stepProgramSingleEntityPicker.ID = filterControl.ID + "_StepProgramPicker";
            stepProgramSingleEntityPicker.AddCssClass("js-step-program-picker");
            stepProgramSingleEntityPicker.Label    = "Step Program";
            stepProgramSingleEntityPicker.Help     = "The Program in which the Step was undertaken.";
            stepProgramSingleEntityPicker.Required = true;

            stepProgramSingleEntityPicker.SelectedIndexChanged += StepProgramSingleEntityPicker_SelectedIndexChanged;
            stepProgramSingleEntityPicker.AutoPostBack          = true;

            var programService = new StepProgramService(dataContext);

            var availablePrograms = programService.Queryable()
                                    .Where(x => x.IsActive)
                                    .OrderBy(a => a.Order)
                                    .ThenBy(a => a.Name)
                                    .ToList();

            stepProgramSingleEntityPicker.InitializeListItems(availablePrograms, x => x.Name, allowEmptySelection: true);


            filterControl.Controls.Add(stepProgramSingleEntityPicker);

            // Step Type selection
            var cblStepType = new RockCheckBoxList();

            cblStepType.ID = filterControl.ID + "_cblStepType";
            cblStepType.AddCssClass("js-step-type");
            cblStepType.Label = "Steps";
            cblStepType.Help  = "If selected, specifies the required Steps that have been undertaken.";

            filterControl.Controls.Add(cblStepType);

            // Step Status selection
            var cblStepStatus = new RockCheckBoxList();

            cblStepStatus.ID = filterControl.ID + "_cblStepStatus";
            cblStepStatus.AddCssClass("js-step-status");
            cblStepStatus.Label = "Statuses";
            cblStepStatus.Help  = "If selected, specifies the required Statuses of the Steps.";

            filterControl.Controls.Add(cblStepStatus);

            // Date Started
            var drpStarted = new SlidingDateRangePicker();

            drpStarted.ID = filterControl.ID + "_drpDateStarted";
            drpStarted.AddCssClass("js-date-started");
            drpStarted.Label = "Date Started";
            drpStarted.Help  = "The date range within which the Step was started";

            filterControl.Controls.Add(drpStarted);

            // Date Completed
            var drpCompleted = new SlidingDateRangePicker();

            drpCompleted.ID = filterControl.ID + "_drpDateCompleted";
            drpCompleted.AddCssClass("js-date-completed");
            drpCompleted.Label = "Date Completed";
            drpCompleted.Help  = "The date range within which the Step was completed";

            filterControl.Controls.Add(drpCompleted);

            // Step Campus selection
            var cblStepCampus = new RockCheckBoxList();

            cblStepCampus.ID = filterControl.ID + "_cblStepCampus";
            cblStepCampus.AddCssClass("js-step-campus");
            cblStepCampus.Label = "Campuses";
            cblStepCampus.Help  = "Select the campuses that the steps were completed at. Not selecting a value will select all campuses.";

            filterControl.Controls.Add(cblStepCampus);

            // Populate lists
            PopulateStepProgramRelatedSelectionLists(filterControl);
            PopulateStepCampuses(cblStepCampus);

            return(new Control[] { stepProgramSingleEntityPicker, cblStepType, cblStepStatus, drpStarted, drpCompleted, cblStepCampus });
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initialize the essential context in which this block is operating.
        /// </summary>
        /// <returns>True, if the block context is valid.</returns>
        private bool InitializeBlockContext()
        {
            _program = null;

            // Try to load the Step Program from the cache.
            var programGuid = GetAttributeValue(AttributeKey.StepProgram).AsGuid();

            int    programId = 0;
            string sharedItemKey;

            // If a Step Program is specified in the block settings use it, otherwise use the PageParameters.
            if (programGuid != Guid.Empty)
            {
                sharedItemKey = string.Format("{0}:{1}", PageParameterKey.StepProgramId, programGuid);
            }
            else
            {
                programId = PageParameter(PageParameterKey.StepProgramId).AsInteger();

                sharedItemKey = string.Format("{0}:{1}", PageParameterKey.StepProgramId, programId);
            }

            if (!string.IsNullOrEmpty(sharedItemKey))
            {
                _program = RockPage.GetSharedItem(sharedItemKey) as StepProgram;
            }

            // Retrieve the program from the data store and cache for subsequent use.
            if (_program == null)
            {
                var dataContext = this.GetDataContext();

                var stepProgramService = new StepProgramService(dataContext);

                if (programGuid != Guid.Empty)
                {
                    _program = stepProgramService.Queryable().Where(g => g.Guid == programGuid).FirstOrDefault();
                }
                else if (programId != 0)
                {
                    _program = stepProgramService.Queryable().Where(g => g.Id == programId).FirstOrDefault();
                }

                if (_program != null)
                {
                    RockPage.SaveSharedItem(sharedItemKey, _program);
                }
            }

            // Verify the Step Program is valid.
            if (_program == null)
            {
                this.ShowNotification("There are no Step Types available in this context.", NotificationBoxType.Info, true);
                return(false);
            }

            // Check for View permissions.
            if (!_program.IsAuthorized(Authorization.VIEW, CurrentPerson))
            {
                this.ShowNotification("Sorry, you are not authorized to view this content.", NotificationBoxType.Danger, true);
                return(false);
            }

            return(true);
        }
Exemplo n.º 29
0
        public void AddStepsRandomParticipationEntries()
        {
            // Get a complete set of active Step Types ordered by Program and structure order.
            var dataContext = new RockContext();

            var programService = new StepProgramService(dataContext);

            var programIdList = programService.Queryable().Where(x => x.StepTypes.Any()).OrderBy(x => x.Order).Select(x => x.Id).ToList();

            var statusService = new StepStatusService(dataContext);

            var statuses = statusService.Queryable().ToList();

            // Get a random selection of people that are not system users or specific users for which test data already exists.
            var personService = new PersonService(dataContext);

            int tedPersonAliasId = 0;

            var testPeopleIdList = new List <int> {
                tedPersonAliasId
            };

            var personQuery = personService.Queryable().Where(x => !x.IsSystem && x.LastName != "Anonymous" && !testPeopleIdList.Contains(x.Id)).Select(x => x.Id);

            var personAliasService = new PersonAliasService(dataContext);

            var personAliasIdList = personAliasService.Queryable().Where(x => personQuery.Contains(x.PersonId)).Select(x => x.Id).ToList();

            var personAliasIdQueue = new Queue <int>(personAliasIdList.GetRandomizedList(_MaxPersonCount));

            int      stepCounter   = 0;
            int      personAliasId = 0;
            int      stepProgramId = 0;
            DateTime startDateTime = RockDateTime.Now;
            DateTime newStepDateTime;
            int      campusId;
            int      maxStepTypeCount;
            int      stepsToAddCount;
            int      offsetDays;
            int      personCounter = 0;
            bool     isCompleted;

            // Loop through the set of people, adding at least 1 program and 1 step for each person.
            var rng = new Random();

            var typeService = new StepTypeService(dataContext);

            var stepTypesAll = typeService.Queryable().ToList();

            var campusList = CampusCache.All();

            StepService stepService = null;

            while (personAliasIdQueue.Any())
            {
                personAliasId = personAliasIdQueue.Dequeue();

                personCounter += 1;

                // Randomly select the Programs that this person will participate in.
                var addProgramCount = rng.Next(1, programIdList.Count + 1);

                var programsToAdd = new Queue <int>(programIdList.GetRandomizedList(addProgramCount));

                while (programsToAdd.Any())
                {
                    stepProgramId = programsToAdd.Dequeue();

                    newStepDateTime = startDateTime;

                    // Get a random campus at which the step was completed.
                    campusId = campusList.GetRandomElement().Id;

                    var stepStatuses = statusService.Queryable().Where(x => x.StepProgramId == stepProgramId).ToList();

                    maxStepTypeCount = stepTypesAll.Count(x => x.StepProgramId == stepProgramId);

                    // Randomly select a number of Steps that this person will achieve in the Program, in Step order.
                    // This creates a distribution weighted toward achievement of earlier Steps, which is the likely scenario for most Programs.
                    // Steps are added from last to first in reverse chronological order, with the last step being achieved in the current year.
                    stepsToAddCount = rng.Next(1, maxStepTypeCount);

                    Debug.Print($"Adding Steps: PersonAliasId: {personAliasId}, ProgramId={stepProgramId}, Steps={stepsToAddCount}");

                    var stepTypesToAdd = new Queue <StepType>(stepTypesAll.Take(stepsToAddCount).Reverse());

                    while (stepTypesToAdd.Any())
                    {
                        var stepTypeToAdd = stepTypesToAdd.Dequeue();

                        // If this is not the last step to be added for this person, make sure the status represents a completion.
                        if (stepTypesToAdd.Any())
                        {
                            isCompleted = true;
                        }
                        else
                        {
                            isCompleted = rng.Next(1, 100) <= _PercentChanceOfLastStepCompletion;
                        }

                        var eligibleStatuses = stepStatuses.Where(x => x.IsCompleteStatus == isCompleted).ToList();

                        // If there is no status that represents completion, allow any status.
                        if (eligibleStatuses.Count == 0)
                        {
                            eligibleStatuses = stepStatuses;
                        }

                        var newStatus = eligibleStatuses.GetRandomElement();

                        // Subtract a random number of days from the current step date to get a suitable date for the preceding step in the program.
                        offsetDays = rng.Next(1, _MaxDaysBetweenSteps);

                        newStepDateTime = newStepDateTime.AddDays(-1 * offsetDays);

                        var newStep = new Step();

                        newStep.StepTypeId = stepTypeToAdd.Id;

                        if (newStatus != null)
                        {
                            newStep.StepStatusId = newStatus.Id;
                        }

                        newStep.PersonAliasId = personAliasId;
                        newStep.CampusId      = campusId;
                        newStep.StartDateTime = newStepDateTime;

                        if (isCompleted)
                        {
                            newStep.CompletedDateTime = newStepDateTime;
                        }

                        newStep.ForeignKey = _SampleDataForeignKey;

                        if (stepService == null)
                        {
                            var stepDataContext = new RockContext();

                            stepService = new StepService(stepDataContext);
                        }

                        stepService.Add(newStep);

                        // Save a batch of records and recycle the context to speed up processing.
                        if (stepCounter % 100 == 0)
                        {
                            stepService.Context.SaveChanges();

                            stepService = null;
                        }

                        stepCounter++;
                    }
                }
            }

            Debug.Print($"--> Created {stepCounter} steps for {personCounter} people.");
        }
Exemplo n.º 30
0
        public void AddTestDataStepPrograms()
        {
            var dataContext = new RockContext();

            // Add Step Categories
            var categoryService = new CategoryService(dataContext);

            var categoryId = EntityTypeCache.Get(typeof(Rock.Model.StepProgram)).Id;

            var adultCategory = CreateCategory("Adult", Constants.CategoryAdultsGuid, 1, categoryId);
            var childCategory = CreateCategory("Youth", Constants.CategoryYouthGuid, 2, categoryId);

            categoryService.Add(adultCategory);
            categoryService.Add(childCategory);

            dataContext.SaveChanges();

            var stepProgramService = new StepProgramService(dataContext);

            // Add Step Program "Sacraments"
            var programSacraments = CreateStepProgram(Constants.ProgramSacramentsGuid, Constants.CategoryAdultsGuid, "Sacraments", "The sacraments represent significant milestones in the Christian faith journey.", "fa fa-bible", 1);

            stepProgramService.Add(programSacraments);

            AddStepStatusToStepProgram(programSacraments, Constants.StatusSacramentsSuccessGuid, "Success", true, Constants.ColorCodeGreen, 1);
            AddStepStatusToStepProgram(programSacraments, Constants.StatusSacramentsPendingGuid, "Pending", false, Constants.ColorCodeBlue, 2);
            AddStepStatusToStepProgram(programSacraments, Constants.StatusSacramentsIncompleteGuid, "Incomplete", false, Constants.ColorCodeRed, 3);

            AddStepTypeToStepProgram(programSacraments, Constants.StepTypeBaptismGuid, "Baptism", "fa fa-tint", 1);

            var confirmationStepType = AddStepTypeToStepProgram(programSacraments, Constants.StepTypeConfirmationGuid, "Confirmation", "fa fa-bible", 2);

            AddStepTypeToStepProgram(programSacraments, Constants.StepTypeEucharistGuid, "Eucharist", "fa fa-cookie", 3);
            AddStepTypeToStepProgram(programSacraments, Constants.StepTypeConfessionGuid, "Confession", "fa fa-praying-hands", 4);
            AddStepTypeToStepProgram(programSacraments, Constants.StepTypeAnnointingGuid, "Annointing of the Sick", "fa fa-comment-medical", 5);
            AddStepTypeToStepProgram(programSacraments, Constants.StepTypeMarriageGuid, "Marriage", "fa fa-ring", 6);

            var holyOrdersStepType = AddStepTypeToStepProgram(programSacraments, Constants.StepTypeHolyOrdersGuid, "Holy Orders", "fa fa-cross", 7);

            dataContext.SaveChanges();

            // Add prerequisites
            var prerequisiteService = new StepTypePrerequisiteService(dataContext);

            var stepPrerequisite = new StepTypePrerequisite();

            stepPrerequisite.Guid                   = Constants.PrerequisiteHolyOrdersGuid;
            stepPrerequisite.StepTypeId             = holyOrdersStepType.Id;
            stepPrerequisite.PrerequisiteStepTypeId = confirmationStepType.Id;

            prerequisiteService.Add(stepPrerequisite);

            dataContext.SaveChanges();

            // Add Step Program "Alpha"
            var programAlpha = CreateStepProgram(Constants.ProgramAlphaGuid, Constants.CategoryAdultsGuid, "Alpha", "Alpha is a series of interactive sessions that freely explore the basics of the Christian faith.", "fa fa-question", 2);

            stepProgramService.Add(programAlpha);

            AddStepStatusToStepProgram(programAlpha, Constants.StatusAlphaCompletedGuid, "Completed", true, Constants.ColorCodeGreen, 1);
            AddStepStatusToStepProgram(programAlpha, Constants.StatusAlphaStartedGuid, "Started", false, Constants.ColorCodeBlue, 2);

            AddStepTypeToStepProgram(programAlpha, Constants.StepTypeAttenderGuid, "Attender", "fa fa-user", 1, hasEndDate: true);
            AddStepTypeToStepProgram(programAlpha, Constants.StepTypeVolunteerGuid, "Volunteer", "fa fa-hand-paper", 2, hasEndDate: true);
            AddStepTypeToStepProgram(programAlpha, Constants.StepTypeLeaderGuid, "Leader", "fa fa-user-graduate", 3, hasEndDate: true);

            dataContext.SaveChanges();
        }