Example #1
0
        /// <summary>
        /// Job that will send out Assessment reminders
        /// </summary>
        /// <param name="context">The context.</param>
        /// <exception cref="NotImplementedException"></exception>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            DateTime   sendreminderDateTime      = DateTime.Now.Date.AddDays(-1 * dataMap.GetInt(AttributeKeys.ReminderEveryDays));
            int        cutOffDays                = dataMap.GetInt(AttributeKeys.CutoffDays);
            var        assessmentSystemEmailGuid = dataMap.GetString(AttributeKeys.AssessmentSystemEmail).AsGuid();

            DateTime currentDate             = DateTime.Now.Date;
            int      assessmentRemindersSent = 0;
            int      errorCount    = 0;
            var      errorMessages = new List <string>();

            using (var rockContext = new RockContext())
            {
                // Get a list of unique PersonAliasIDs from Assessments where the CreatedDateTime is less than the cut off date and LastReminderDate is null or greater than the reminder date.
                var assessmentService = new AssessmentService(rockContext);
                var personAliasIds    = assessmentService
                                        .Queryable()
                                        .AsNoTracking()
                                        .Where(a => a.Status == AssessmentRequestStatus.Pending)
                                        .Where(a => currentDate <= DbFunctions.AddDays(a.RequestedDateTime, cutOffDays))
                                        .Where(a => (a.LastReminderDate == null && sendreminderDateTime >= DbFunctions.TruncateTime(a.RequestedDateTime)) ||
                                               (sendreminderDateTime >= DbFunctions.TruncateTime(a.LastReminderDate)))
                                        .Select(a => a.PersonAliasId)
                                        .Distinct()
                                        .ToList();

                // Go through the list, send a reminder, and update the LastReminderDate for all pending assessments for the person alias
                foreach (var personAliasId in personAliasIds)
                {
                    var errors = SendReminderEmail(assessmentSystemEmailGuid, personAliasId);

                    if (errors.Any())
                    {
                        errorMessages.AddRange(errors);
                    }
                    else
                    {
                        assessmentRemindersSent++;
                    }

                    assessmentService.UpdateLastReminderDateForPersonAlias(personAliasId);
                }

                context.Result = string.Format("{0} assessment reminders sent", assessmentRemindersSent);
                if (errorMessages.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append(string.Format("{0} Errors: ", errorCount));
                    errorMessages.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errors = sb.ToString();
                    context.Result += errors;
                    var         exception = new Exception(errors);
                    HttpContext context2  = HttpContext.Current;
                    ExceptionLogService.LogException(exception, context2);
                    throw exception;
                }
            }
        }
Example #2
0
        /// <summary>
        /// Converts the assessment results.
        /// </summary>
        private void ConvertSpiritualGiftsAssessmentResults()
        {
            using (var rockContext = new RockContext())
            {
                rockContext.Database.CommandTimeout = _commandTimeout;

                var spiritualGiftsGuid = SystemGuid.AssessmentType.GIFTS.AsGuidOrNull();
                if (!spiritualGiftsGuid.HasValue)
                {
                    return;
                }

                int?assessmentTypeId = AssessmentTypeCache.GetId(spiritualGiftsGuid.Value);
                if (!assessmentTypeId.HasValue)
                {
                    return;
                }

                // Load all completed Spiritual Gifts Assessments that have AssessmentResultData
                var assessmentService = new AssessmentService(rockContext);
                var assessments       = assessmentService.Queryable("PersonAlias.Person")
                                        .Where(a => a.AssessmentTypeId == assessmentTypeId.Value)
                                        .Where(a => a.Status == AssessmentRequestStatus.Complete)
                                        .Where(a => !string.IsNullOrEmpty(a.AssessmentResultData))
                                        .ToList();

                foreach (Assessment assessment in assessments)
                {
                    if (assessment.PersonAlias?.Person == null)
                    {
                        continue;
                    }

                    // Deserialize the stored JSON
                    var resultData = assessment.AssessmentResultData.FromJsonOrNull <SpiritualGiftsService.AssessmentResultData>();
                    if (resultData == null || resultData.Result == null)
                    {
                        continue;
                    }

                    // Re-score the origninal Assessment responses
                    SpiritualGiftsService.AssessmentResults results = SpiritualGiftsService.GetResult(resultData.Result);
                    if (results == null)
                    {
                        continue;
                    }

                    // Re-save the Assessment result AttributeValues
                    SpiritualGiftsService.SaveAssessmentResults(assessment.PersonAlias.Person, results);

                    // Add the scores to the Assessment's data object
                    resultData.ResultScores         = results.SpiritualGiftScores;
                    assessment.AssessmentResultData = resultData.ToJson();
                }

                rockContext.SaveChanges();
            }
        }
Example #3
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext       = new RockContext();
            var assessmentService = new AssessmentService(rockContext);
            var query             = assessmentService.Queryable("RequesterPersonAlias.Person, AssessmentType");

            // Filter by the person id in the context
            var personId = PageParameter(PageParameterKey.PersonId).AsIntegerOrNull();

            if (personId.HasValue)
            {
                query = query.Where(a => a.PersonAlias.PersonId == personId.Value);
            }

            // Filter by assessment type if specified by the user
            var assessmentTypeId = rFilter.GetUserPreference(FilterKey.AssessmentTypeId).AsIntegerOrNull();

            if (assessmentTypeId.HasValue)
            {
                query = query.Where(a => a.AssessmentTypeId == assessmentTypeId.Value);
            }

            // Transform to view models, which the sort options are based upon. Cannot use FullName here because it will throw a linq to entity
            // exception since linq cannot use the FullName property.
            var viewModelQuery = query.Select(a => new AssessmentViewModel
            {
                AssessmentId            = a.Id,
                AssessmentTypeTitle     = a.AssessmentType.Title,
                IsCompleted             = a.Status == AssessmentRequestStatus.Complete,
                RequestedDateTime       = a.RequestedDateTime,
                RequesterPersonFullName =
                    (string.IsNullOrEmpty(a.RequesterPersonAlias.Person.NickName) ?
                     a.RequesterPersonAlias.Person.FirstName :
                     a.RequesterPersonAlias.Person.NickName) +
                    " " + a.RequesterPersonAlias.Person.LastName,
                Status            = a.Status,
                StatusText        = a.Status == AssessmentRequestStatus.Complete ? "Complete" : "Pending",
                CompletedDateTime = a.CompletedDateTime
            });

            // Sort if specified by the user
            var sortProperty = gAssessments.SortProperty;

            if (sortProperty != null)
            {
                viewModelQuery = viewModelQuery.Sort(sortProperty);
            }
            else
            {
                viewModelQuery = viewModelQuery.OrderByDescending(a => a.RequestedDateTime).ThenBy(a => a.AssessmentTypeTitle);
            }

            gAssessments.SetLinqDataSource(viewModelQuery);
            gAssessments.DataBind();
        }
Example #4
0
        /// <summary>
        /// Handles the Click event of the btnDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (!UserCanDelete())
            {
                return;
            }

            // Get the id of the assessment from the command argument
            var button       = sender as LinkButton;
            var assessmentId = button.CommandArgument.AsInteger();

            // Use a query to delete the record with a single DB trip. Safeguard the query to not delete complete assessments.
            var rockContext       = new RockContext();
            var assessmentService = new AssessmentService(rockContext);
            var query             = assessmentService.Queryable().Where(a => a.Id == assessmentId && a.Status == AssessmentRequestStatus.Pending);

            assessmentService.DeleteRange(query);

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

            errorMessages = new List <string>();

            var assessmentTypesGuidString = GetAttributeValue(action, AttributeKey.AssessmentTypesKey, true);
            var assessmentTypeGuids       = assessmentTypesGuidString.IsNullOrWhiteSpace() ? null : assessmentTypesGuidString.Split(new char[] { ',' });

            var  personAliasGuid      = GetAttributeValue(action, AttributeKey.Person, true).AsGuidOrNull();
            Guid?requestedByAliasGuid = GetAttributeValue(action, AttributeKey.RequestedBy, true).AsGuidOrNull();
            var  dueDate = GetAttributeValue(action, AttributeKey.DueDate, true).AsDateTime();

            // Validate attribute data
            if (!assessmentTypeGuids.Any())
            {
                errorMessages.Add("No Assessments selected.");
                return(false);
            }

            if (personAliasGuid == null)
            {
                errorMessages.Add("Invalid Person Attribute or Value.");
                return(false);
            }

            var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);

            if (personAlias == null)
            {
                errorMessages.Add("Invalid Person Attribute or Value.");
                return(false);
            }

            var requestedByAlias = new PersonAliasService(rockContext).Get(requestedByAliasGuid.Value);

            foreach (string assessmentTypeGuid in assessmentTypeGuids)
            {
                // Check for an existing record
                var assessmentTypeService = new AssessmentTypeService(rockContext);
                int?assessmentTypeId      = assessmentTypeService.GetId(assessmentTypeGuid.AsGuid());

                var assessmentService  = new AssessmentService(rockContext);
                var existingAssessment = assessmentService
                                         .Queryable()
                                         .Where(a => a.PersonAliasId == personAlias.Id)
                                         .Where(a => a.AssessmentTypeId == assessmentTypeId)
                                         .Where(a => a.Status == AssessmentRequestStatus.Pending)
                                         .FirstOrDefault();

                // If a pending record for this person/type is found mark it complete.
                if (existingAssessment != null)
                {
                    existingAssessment.Status = AssessmentRequestStatus.Complete;
                }

                // Create a new assessment
                var assessment = new Assessment
                {
                    PersonAliasId          = personAlias.Id,
                    AssessmentTypeId       = assessmentTypeId.Value,
                    RequesterPersonAliasId = requestedByAlias.Id,
                    RequestedDateTime      = RockDateTime.Now,
                    RequestedDueDate       = dueDate,
                    Status = AssessmentRequestStatus.Pending
                };

                assessmentService.Add(assessment);
                rockContext.SaveChanges();
            }

            return(true);
        }