示例#1
0
        public void StepDateKeySavesCorrectly()
        {
            var rockContext = new RockContext();
            var stepService = new StepService(rockContext);

            var step = BuildStep(rockContext, Convert.ToDateTime("3/16/2010"),
                                 Convert.ToDateTime("3/15/2010"),
                                 Convert.ToDateTime("3/17/2010"));

            stepService.Add(step);
            rockContext.SaveChanges();

            var stepId = step.Id;

            // We're bypassing the model because the model doesn't user the StepDateKey from the database,
            // but it still needs to be correct for inner joins to work correctly.
            var result = rockContext.Database.
                         SqlQuery <int>($"SELECT CompletedDateKey FROM Step WHERE Id = {stepId}").First();

            Assert.AreEqual(20100316, result);

            result = rockContext.Database.
                     SqlQuery <int>($"SELECT StartDateKey FROM Step WHERE Id = {stepId}").First();

            Assert.AreEqual(20100315, result);

            result = rockContext.Database.
                     SqlQuery <int>($"SELECT EndDateKey FROM Step WHERE Id = {stepId}").First();

            Assert.AreEqual(20100317, result);
        }
        /// <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();
        }
示例#3
0
        /// <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 static void AddStep(int stepTypeId, int stepStatusId, int personAliasId)
        {
            var rockContext = new RockContext();
            var stepService = new StepService(rockContext);

            var step = new Step
            {
                StepTypeId        = stepTypeId,
                StepStatusId      = stepStatusId,
                CompletedDateTime = RockDateTime.Today,
                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();
        }
示例#4
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var rockContext        = GetRockContext();
            var service            = new StepService(rockContext);
            var step               = GetStep();
            var stepType           = GetStepType();
            var person             = GetPerson();
            var isPersonSelectable = IsPersonSelectable();

            // If the person is allowed to be selected and the person is missing, query for it
            if (isPersonSelectable && ppPerson.PersonId.HasValue && person == null)
            {
                var personService = new PersonService(rockContext);
                person = personService.Get(ppPerson.PersonId.Value);
            }

            // Person is the only required field for the step
            if (person == null)
            {
                ShowError("The person is required to save a step record.");
            }

            // If the step is null, then the aim is to create a new step
            var isAdd = step == null;

            if (isAdd)
            {
                step = new Step
                {
                    StepTypeId    = stepType.Id,
                    PersonAliasId = person.PrimaryAliasId.Value
                };
            }

            // Update the step properties. Person cannot be changed (only set when the step is added)
            step.StartDateTime = rdpStartDate.SelectedDate;
            step.EndDateTime   = stepType.HasEndDate ? rdpEndDate.SelectedDate : null;
            step.StepStatusId  = rsspStatus.SelectedValueAsId();

            // Update the completed date time, which is based on the start, end, and status
            if (!step.StepStatusId.HasValue)
            {
                step.CompletedDateTime = null;
            }
            else
            {
                var stepStatusService = new StepStatusService(rockContext);
                var stepStatus        = stepStatusService.Get(step.StepStatusId.Value);

                if (stepStatus == null || !stepStatus.IsCompleteStatus)
                {
                    step.CompletedDateTime = null;
                }
                else
                {
                    step.CompletedDateTime = step.EndDateTime ?? step.StartDateTime;
                }
            }

            if (!step.IsValid)
            {
                ShowError(step.ValidationResults.Select(vr => vr.ErrorMessage).ToList().AsDelimited("<br />"));
                return;
            }

            if (isAdd)
            {
                var errorMessage = string.Empty;
                var canAdd       = service.CanAdd(step, out errorMessage);

                if (!errorMessage.IsNullOrWhiteSpace())
                {
                    ShowError(errorMessage);
                    return;
                }

                if (!canAdd)
                {
                    ShowError("The step cannot be added for an unspecified reason");
                    return;
                }

                service.Add(step);
            }

            // Save the step record
            rockContext.SaveChanges();

            // Save the step attributes from the attribute controls
            step.LoadAttributes(rockContext);
            avcAttributes.GetEditValues(step);
            step.SaveAttributeValues(rockContext);

            GoToSuccessPage(step.Id);
        }
        public object PostAddEditUserTask(PostAddEditUserTaskDTO userTaskDTO)
        {
            using (ProcessService processService = new ProcessService())
            {
                if (!processService.GetInfo(userTaskDTO.ProcessID).AllowEdit())
                {
                    return(new PostMethodMessage(LangUtility.Get("NotAllowEdit.Text", nameof(sysBpmsProcess)), DisplayMessageType.error));
                }
            }
            ResultOperation resultOperation = new ResultOperation();

            using (TaskService taskService = new TaskService())
            {
                //save access
                sysBpmsTask       task = taskService.GetInfo(userTaskDTO.ID);
                UserTaskRuleModel userTaskRuleModel = new UserTaskRuleModel();
                if (userTaskDTO.OwnerTypeLU.HasValue)
                {
                    switch ((sysBpmsTask.e_OwnerTypeLU)userTaskDTO.OwnerTypeLU)
                    {
                    case sysBpmsTask.e_OwnerTypeLU.User:
                        userTaskRuleModel.AccessType = userTaskDTO.UserAccessType.ToIntObj();
                        switch ((UserTaskRuleModel.e_UserAccessType)userTaskDTO.UserAccessType)
                        {
                        case UserTaskRuleModel.e_UserAccessType.Static:
                            //userTaskDTO.UserID is filled automativally
                            break;

                        case UserTaskRuleModel.e_UserAccessType.Variable:
                            userTaskRuleModel.Variable = userTaskDTO.ddlUserVariable;
                            break;
                        }

                        break;

                    case sysBpmsTask.e_OwnerTypeLU.Role:
                        userTaskRuleModel.AccessType = userTaskDTO.RoleAccessType.ToIntObj();
                        switch ((UserTaskRuleModel.e_RoleAccessType)userTaskDTO.RoleAccessType)
                        {
                        case UserTaskRuleModel.e_RoleAccessType.Static:
                            //userTaskRuleModel.RoleCode = Request.Form["RoleName"];
                            userTaskRuleModel.SpecificDepartmentId = userTaskDTO.SpecificDepartmentID;
                            break;

                        case UserTaskRuleModel.e_RoleAccessType.Variable:
                            userTaskRuleModel.Variable             = userTaskDTO.ddlRoleVariable;
                            userTaskRuleModel.SpecificDepartmentId = userTaskDTO.SpecificDepartmentID;
                            break;

                        case UserTaskRuleModel.e_RoleAccessType.CorrespondentRole:
                            userTaskRuleModel.RoleCode       = userTaskDTO.ddlRoleRuleRoleName;
                            userTaskRuleModel.UserType       = userTaskDTO.ddlRoleRuleUserType;
                            userTaskRuleModel.GoUpDepartment = userTaskDTO.GoUpDepartment;
                            break;
                        }
                        break;
                    }

                    userTaskDTO.Rule = userTaskRuleModel.BuildXml();
                    resultOperation  = task.Update(userTaskDTO.RoleName, userTaskDTO.SpecificDepartmentID, userTaskDTO.OwnerTypeLU, userTaskDTO.UserID, userTaskDTO.Rule);
                    if (!resultOperation.IsSuccess)
                    {
                        return(new PostMethodMessage(resultOperation.GetErrors(), DisplayMessageType.error));
                    }
                }
                resultOperation = taskService.Update(task);

                //save step
                int index = 0;
                userTaskDTO.ListSteps = userTaskDTO.ListSteps ?? new List <StepDTO>();
                userTaskDTO.ListSteps.ForEach(c => { c.Position = ++index; });

                using (StepService stepService = new StepService())
                {
                    List <sysBpmsStep> CurrentSteps = stepService.GetList(userTaskDTO.ID, null);
                    foreach (sysBpmsStep item in CurrentSteps.Where(c => !userTaskDTO.ListSteps.Any(d => d.ID == c.ID)))
                    {
                        resultOperation = stepService.Delete(item.ID);
                        if (!resultOperation.IsSuccess)
                        {
                            return(new PostMethodMessage(resultOperation.GetErrors(), DisplayMessageType.error));
                        }
                    }
                    foreach (StepDTO item in userTaskDTO.ListSteps)
                    {
                        resultOperation = null;
                        if (item.ID != Guid.Empty)
                        {
                            resultOperation = stepService.Update(new sysBpmsStep(item.ID, item.TaskID, item.Position, item.DynamicFormID, item.Name));
                        }
                        else
                        {
                            resultOperation = stepService.Add(new sysBpmsStep(item.ID, item.TaskID, item.Position, item.DynamicFormID, item.Name));
                        }

                        if (!resultOperation.IsSuccess)
                        {
                            return(new PostMethodMessage(resultOperation.GetErrors(), DisplayMessageType.error));
                        }
                    }

                    if (resultOperation.IsSuccess)
                    {
                        return(new PostMethodMessage(SharedLang.Get("Success.Text"), DisplayMessageType.success));
                    }
                    else
                    {
                        return(new PostMethodMessage(resultOperation.GetErrors(), DisplayMessageType.error));
                    }
                }
            }
        }
示例#6
0
文件: AddStep.cs 项目: waldo2590/Rock
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var mergeFields = GetMergeFields(action);

            // Validate the person exists
            var personGuid = GetAttributeValue(action, AttributeKey.Person, true).AsGuidOrNull();

            if (!personGuid.HasValue)
            {
                errorMessages.Add("The person guid is required but was missing");
                return(LogMessagesForExit(action, errorMessages));
            }

            var personService = new PersonService(rockContext);
            var person        = personService.Queryable("Aliases").AsNoTracking()
                                .FirstOrDefault(p => p.Guid == personGuid.Value || p.Aliases.Any(pa => pa.Guid == personGuid.Value));

            if (person == null)
            {
                errorMessages.Add($"The person with the guid '{personGuid.Value}' was not found");
                return(LogMessagesForExit(action, errorMessages));
            }

            if (!person.PrimaryAliasId.HasValue)
            {
                errorMessages.Add($"{person.FullName} does not have a primary alias identifier");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step type exists. Could be a step type id or a guid
            var stepType = GetStepType(rockContext, action, out var errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepType == null)
            {
                errorMessages.Add("The step type could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step status exists and is in the same program as the step type
            var stepStatus = GetStepStatus(stepType, action, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepStatus == null)
            {
                errorMessages.Add("The step status could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Get the start and end dates
            var startDate = GetLavaAttributeValue(action, AttributeKey.StartDate).AsDateTime() ?? RockDateTime.Now;
            var endDate   = GetLavaAttributeValue(action, AttributeKey.EndDate).AsDateTime();

            var campusAttributeValue = GetLavaAttributeValue(action, AttributeKey.Campus);
            var campusId             = campusAttributeValue.AsIntegerOrNull();
            var campusGuid           = campusAttributeValue.AsGuidOrNull();

            if (campusGuid != null)
            {
                var campus = CampusCache.Get(campusGuid.Value);
                if (campus != null)
                {
                    campusId = campus.Id;
                }
            }

            // The completed date is today or the end date if the status is a completed status
            var completedDate = stepStatus.IsCompleteStatus ? (endDate ?? RockDateTime.Now) : ( DateTime? )null;

            // Create the step object
            var step = new Step
            {
                StepTypeId        = stepType.Id,
                PersonAliasId     = person.PrimaryAliasId.Value,
                StartDateTime     = startDate,
                EndDateTime       = endDate,
                CompletedDateTime = completedDate,
                StepStatusId      = stepStatus.Id,
                CampusId          = campusId
            };

            // Validate the step
            if (!step.IsValid)
            {
                errorMessages.AddRange(step.ValidationResults.Select(a => a.ErrorMessage));
                return(LogMessagesForExit(action, errorMessages));
            }

            // Check if the step can be created because of Allow Multiple rules on the step type and also prerequisite requirements
            var stepService = new StepService(rockContext);
            var canAdd      = stepService.CanAdd(step, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
            }
            else if (!canAdd)
            {
                errorMessages.Add("Cannot add the step for an unspecified reason");
            }
            else
            {
                try
                {
                    stepService.Add(step);
                    rockContext.SaveChanges();

                    SetCreatedItemAttribute(action, AttributeKey.StepAttribute, step, rockContext);
                }
                catch (Exception exception)
                {
                    errorMessages.Add($"Exception thrown: {exception.Message}");
                    ExceptionLogService.LogException(exception);
                }
            }

            return(LogMessagesForExit(action, errorMessages));
        }
        /// <summary>
        /// Migrates a baptism record from a Attribute Matrix Item to a Step
        /// </summary>
        /// <param name="itemId">Matrix Item Id</param>
        /// <param name="personId">The Person Id of the person who was baptized.</param>
        /// <returns></returns>
        private bool MigrateBaptismItem(int itemId, int personId)
        {
            using (var context = new RockContext())
            {
                var matrixItem = new AttributeMatrixItemService(context).Get(itemId);

                var person = new PersonService(context).Get(personId);

                if (matrixItem == null)
                {
                    results["Fail"] += String.Format("Failed Migration {0} - {1}, baptism matrix item not found.",
                                                     itemId,
                                                     person != null ? person.FullName : "Unknown") + Environment.NewLine;
                    return(false);
                }



                matrixItem.LoadAttributes(context);
                var campusGuid      = matrixItem.GetAttributeValue("BaptismLocation").AsGuidOrNull();
                var baptismDate     = matrixItem.GetAttributeValue("BaptismDate").AsDateTime();
                var baptizedBy      = matrixItem.GetAttributeValue("BaptizedBy");
                var baptismTypeGuid = matrixItem.GetAttributeValue("BaptismType").AsGuidOrNull();


                var stepService = new StepService(context);



                var step = stepService.Queryable()
                           .Where(s => s.ForeignId == itemId)
                           .Where(s => s.PersonAlias.PersonId == personId)
                           .SingleOrDefault();

                if (step == null)
                {
                    step = new Step()
                    {
                        StepTypeId    = BaptismStepType.Id,
                        PersonAliasId = person.PrimaryAliasId.Value,
                        ForeignId     = matrixItem.Id
                    };

                    stepService.Add(step);
                }

                if (baptismDate >= new DateTime(1753, 1, 1))     //datetime minimum date
                {
                    step.StartDateTime     = baptismDate;
                    step.CompletedDateTime = baptismDate;
                }

                step.StepStatusId = StepStatus.Id;

                if (campusGuid.HasValue)
                {
                    step.CampusId = CampusCache.Get(campusGuid.Value).Id;
                }

                context.SaveChanges();
                step.LoadAttributes(context);

                step.SetAttributeValue("BaptismType", baptismTypeGuid);

                if (baptizedBy.IsNotNullOrWhiteSpace())
                {
                    step.SetAttributeValue("BaptizedBy", baptizedBy);
                }
                else
                {
                    step.SetAttributeValue("BaptizedBy", null);
                }

                step.SaveAttributeValues(context);

                results["Success"] += String.Format("Successfully migrated baptism item {0}-{1} for {2}.",
                                                    matrixItem.Id,
                                                    baptismTypeGuid.HasValue ? DefinedValueCache.Get(baptismTypeGuid.Value).Value : "Unknown Type",
                                                    person != null ? person.FullName : "Unknown") + Environment.NewLine;

                return(true);
            }
        }
示例#8
0
        public void AddKnownStepParticipations()
        {
            var dataContext = new RockContext();

            var stepService = new StepService(dataContext);

            // Baptism
            Step baptism;

            baptism = this.CreateWellKnownStep(Constants.TedDeckerStepBaptismGuid,
                                               Constants.StepTypeBaptismGuid,
                                               Constants.TedDeckerPersonGuid,
                                               Constants.StatusSacramentsSuccessGuid,
                                               new DateTime(2001, 4, 13));
            stepService.Add(baptism);

            baptism = this.CreateWellKnownStep(Constants.BillMarbleStepBaptismGuid,
                                               Constants.StepTypeBaptismGuid,
                                               Constants.BillMarblePersonGuid,
                                               Constants.StatusSacramentsSuccessGuid,
                                               new DateTime(2001, 10, 2));
            stepService.Add(baptism);

            baptism = this.CreateWellKnownStep(Constants.AlishaMarbleStepBaptismGuid,
                                               Constants.StepTypeBaptismGuid,
                                               Constants.AlishaMarblePersonGuid,
                                               Constants.StatusSacramentsSuccessGuid,
                                               new DateTime(2001, 10, 2));
            stepService.Add(baptism);

            baptism = this.CreateWellKnownStep(Constants.BrianJonesStepBaptismGuid,
                                               Constants.StepTypeBaptismGuid,
                                               Constants.BrianJonesPersonGuid,
                                               Constants.StatusSacramentsPendingGuid,
                                               new DateTime(2012, 5, 16));
            stepService.Add(baptism);

            // Confirmation
            Step confirmation;

            confirmation = this.CreateWellKnownStep(Constants.TedDeckerStepConfirmationGuid,
                                                    Constants.StepTypeConfirmationGuid,
                                                    Constants.TedDeckerPersonGuid,
                                                    Constants.StatusSacramentsSuccessGuid,
                                                    new DateTime(1996, 10, 25));
            stepService.Add(confirmation);

            confirmation = this.CreateWellKnownStep(Constants.BillMarbleStepConfirmationGuid,
                                                    Constants.StepTypeConfirmationGuid,
                                                    Constants.BillMarblePersonGuid,
                                                    Constants.StatusSacramentsSuccessGuid,
                                                    new DateTime(1999, 08, 04));
            stepService.Add(confirmation);

            confirmation = this.CreateWellKnownStep(Constants.SarahSimmonsStepConfirmationGuid,
                                                    Constants.StepTypeConfirmationGuid,
                                                    Constants.SarahSimmonsPersonGuid,
                                                    Constants.StatusSacramentsSuccessGuid,
                                                    new DateTime(1998, 11, 30));
            stepService.Add(confirmation);

            // Marriage - First
            Step marriage;

            marriage = this.CreateWellKnownStep(Constants.TedDeckerStepMarriage1Guid,
                                                Constants.StepTypeMarriageGuid,
                                                Constants.TedDeckerPersonGuid,
                                                Constants.StatusSacramentsIncompleteGuid,
                                                new DateTime(1998, 2, 10));
            stepService.Add(marriage);

            marriage = this.CreateWellKnownStep(Constants.BillMarbleStepMarriage1Guid,
                                                Constants.StepTypeMarriageGuid,
                                                Constants.BillMarblePersonGuid,
                                                Constants.StatusSacramentsSuccessGuid,
                                                new DateTime(1993, 4, 12));
            stepService.Add(marriage);

            // Marriage - Second
            var marriage2 = this.CreateWellKnownStep(Constants.TedDeckerStepMarriage2Guid,
                                                     Constants.StepTypeMarriageGuid,
                                                     Constants.TedDeckerPersonGuid,
                                                     Constants.StatusSacramentsSuccessGuid,
                                                     new DateTime(2001, 4, 1));

            stepService.Add(marriage2);

            // Alpha/Attender
            var alphaAttender = this.CreateWellKnownStep(Constants.BenJonesStepAlphaAttenderGuid,
                                                         Constants.StepTypeAttenderGuid,
                                                         Constants.BenJonesPersonGuid,
                                                         Constants.StatusAlphaStartedGuid,
                                                         new DateTime(2015, 10, 13));

            stepService.Add(alphaAttender);

            dataContext.SaveChanges();
        }
示例#9
0
        public void StepDateKeyJoinsCorrectly()
        {
            var expectedRecordCount = 15;
            var startYear           = 2015;
            var completedYear       = 2016;
            var endYear             = 2017;

            using (var rockContext = new RockContext())
            {
                var stepService = new StepService(rockContext);

                var minStartDateValue = TestDataHelper.GetAnalyticsSourceMinDateForYear(rockContext, startYear);
                var maxStartDateValue = TestDataHelper.GetAnalyticsSourceMaxDateForYear(rockContext, startYear);

                var minCompletedDateValue = TestDataHelper.GetAnalyticsSourceMinDateForYear(rockContext, completedYear);
                var maxCompletedDateValue = TestDataHelper.GetAnalyticsSourceMaxDateForYear(rockContext, completedYear);

                var minEndDateValue = TestDataHelper.GetAnalyticsSourceMinDateForYear(rockContext, endYear);
                var maxEndDateValue = TestDataHelper.GetAnalyticsSourceMaxDateForYear(rockContext, endYear);

                for (var i = 0; i < 15; i++)
                {
                    var startDate     = TestDataHelper.GetRandomDateInRange(minStartDateValue, maxStartDateValue);
                    var endDate       = TestDataHelper.GetRandomDateInRange(minEndDateValue, maxEndDateValue);
                    var completedDate = TestDataHelper.GetRandomDateInRange(minCompletedDateValue, maxCompletedDateValue);

                    while (endDate < startDate)
                    {
                        endDate = TestDataHelper.GetRandomDateInRange(minEndDateValue, maxEndDateValue);
                    }

                    while (completedDate < startDate)
                    {
                        completedDate = TestDataHelper.GetRandomDateInRange(minCompletedDateValue, maxCompletedDateValue);
                    }

                    var step = BuildStep(rockContext, completedDate, startDate, endDate);

                    stepService.Add(step);
                }

                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var stepService = new StepService(rockContext);

                var steps = stepService.
                            Queryable().
                            Where(i => i.ForeignKey == stepForiegnKey).
                            Where(i => i.CompletedSourceDate.CalendarYear == completedYear);

                Assert.AreEqual(expectedRecordCount, steps.Count());
                Assert.IsNotNull(steps.First().CompletedSourceDate);

                steps = stepService.
                        Queryable().
                        Where(i => i.ForeignKey == stepForiegnKey).
                        Where(i => i.StartSourceDate.CalendarYear == startYear);

                Assert.AreEqual(expectedRecordCount, steps.Count());
                Assert.IsNotNull(steps.First().StartSourceDate);

                steps = stepService.
                        Queryable().
                        Where(i => i.ForeignKey == stepForiegnKey).
                        Where(i => i.EndSourceDate.CalendarYear == endYear);

                Assert.AreEqual(expectedRecordCount, steps.Count());
                Assert.IsNotNull(steps.First().EndSourceDate);
            }
        }
        public void Execute_RespectsAllowMultipleTrue()
        {
            // Create a complete step for a step type that does allow multiple for a person in the dataview
            var stepGuid = Guid.NewGuid();
            var stepCompletedDateTime = new DateTime(2000, 1, 1);
            int stepTypeId;

            using (var rockContext = new RockContext())
            {
                var stepProgramService = new StepProgramService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var stepService        = new StepService(rockContext);

                var stepProgram = stepProgramService.Queryable("StepTypes.Steps.StepStatus").FirstOrDefault(sp => sp.ForeignKey == ForeignKey);
                stepTypeId = stepProgram.StepTypes.FirstOrDefault(st => st.AutoCompleteDataViewId.HasValue && st.AllowMultiple).Id;

                stepService.Add(new Step
                {
                    ForeignKey        = ForeignKey,
                    StepTypeId        = stepTypeId,
                    StepStatus        = stepProgram.StepStatuses.FirstOrDefault(ss => ss.IsCompleteStatus),
                    CompletedDateTime = stepCompletedDateTime,
                    PersonAlias       = personAliasService.Queryable().FirstOrDefault(pa =>
                                                                                      pa.ForeignKey == ForeignKey &&
                                                                                      pa.Person.MiddleName == DataViewMiddleName),
                    Guid = stepGuid
                });

                rockContext.SaveChanges();
            }

            // Run the job
            var jobContext = new TestJobContext();

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

            var job = new StepsAutomation();

            job.Execute(jobContext);

            // Refresh the data from the database
            using (var rockContext = new RockContext())
            {
                var stepProgramService = new StepProgramService(rockContext);
                var stepProgram        = stepProgramService.Queryable("StepTypes.Steps.StepStatus").FirstOrDefault(sp => sp.ForeignKey == ForeignKey);
                var foundOriginalStep  = false;

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

                foreach (var stepType in stepProgram.StepTypes)
                {
                    if (stepType.Id == stepTypeId)
                    {
                        // This is the allow multiple type with an autocomplete dataview
                        // There should be the original step and now also 3 new ones.
                        Assert.AreEqual(4, stepType.Steps.Count);

                        foreach (var step in stepType.Steps)
                        {
                            // The original step should be found and the completed datetime should not have changed
                            if (step.Guid == stepGuid)
                            {
                                foundOriginalStep = true;
                                Assert.IsTrue(step.CompletedDateTime.HasValue);
                                Assert.AreEqual(stepCompletedDateTime, step.CompletedDateTime.Value);
                            }

                            Assert.IsTrue(step.IsComplete);
                            Assert.IsTrue(step.StepStatus.IsCompleteStatus);
                            Assert.IsNotNull(step.CompletedDateTime);
                        }
                    }
                    else if (stepType.AutoCompleteDataViewId.HasValue)
                    {
                        // There should be a completed step for each person in the dataview
                        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 for types with no dataview
                        Assert.AreEqual(0, stepType.Steps.Count);
                    }
                }

                Assert.IsTrue(foundOriginalStep);
            }
        }
        public void Execute_CompletesExistingStep()
        {
            // Add an in-progress step that should be made complete by the job
            var stepGuid = Guid.NewGuid();

            using (var rockContext = new RockContext())
            {
                var stepProgramService = new StepProgramService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var stepService        = new StepService(rockContext);

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

                stepService.Add(new Step
                {
                    ForeignKey        = ForeignKey,
                    StepTypeId        = stepProgram.StepTypes.FirstOrDefault(st => st.AutoCompleteDataViewId.HasValue).Id,
                    StepStatus        = stepProgram.StepStatuses.FirstOrDefault(ss => !ss.IsCompleteStatus),
                    CompletedDateTime = null,
                    PersonAlias       = personAliasService.Queryable().FirstOrDefault(pa =>
                                                                                      pa.ForeignKey == ForeignKey &&
                                                                                      pa.Person.MiddleName == DataViewMiddleName),
                    Guid = stepGuid
                });

                rockContext.SaveChanges();
            }

            // Run the job
            var jobContext = new TestJobContext();

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

            var job = new StepsAutomation();

            job.Execute(jobContext);

            // Refresh the data from the database
            using (var rockContext = new RockContext())
            {
                var stepProgramService = new StepProgramService(rockContext);
                var stepProgram        = stepProgramService.Queryable("StepTypes.Steps.StepStatus").FirstOrDefault(sp => sp.ForeignKey == ForeignKey);
                var foundOriginalStep  = false;

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

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

                        foreach (var step in stepType.Steps)
                        {
                            if (step.Guid == stepGuid)
                            {
                                // We need to ensure that the original step (was in-progress) still exists
                                foundOriginalStep = true;
                            }

                            Assert.IsTrue(step.IsComplete);
                            Assert.IsTrue(step.StepStatus.IsCompleteStatus);
                            Assert.IsNotNull(step.CompletedDateTime);
                        }
                    }
                    else
                    {
                        // No steps should exist for a type with no auto-complete dataview
                        Assert.AreEqual(0, stepType.Steps.Count);
                    }
                }

                Assert.IsTrue(foundOriginalStep);
            }
        }