public override Task When()
 {
     _stage3Result = AssessmentService.ValidateAssessmentsAsync(_aoUkprn, _stage2Response);
     return(Task.CompletedTask);
 }
示例#2
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;
            var        sendreminderDateTime      = RockDateTime.Now.Date.AddDays(-1 * dataMap.GetInt(AttributeKeys.ReminderEveryDays));
            int        cutOffDays                = dataMap.GetInt(AttributeKeys.CutoffDays);
            var        assessmentSystemEmailGuid = dataMap.GetString(AttributeKeys.AssessmentSystemEmail).AsGuid();

            var currentDate = RockDateTime.Now.Date;
            var result      = new SendMessageResult();

            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.
                // Only the latest assessment for each type and person is considered. For example a past DISC assessment that is still pending but a newer one is complete. The past one will
                // not be considered.
                var assessmentService = new AssessmentService(rockContext);
                var personAliasIds    = assessmentService
                                        .GetLatestAssessments()
                                        .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 sendResult = SendReminderEmail(assessmentSystemEmailGuid, personAliasId);

                    result.MessagesSent += sendResult.MessagesSent;
                    result.Warnings.AddRange(sendResult.Warnings);
                    result.Errors.AddRange(sendResult.Errors);

                    assessmentService.UpdateLastReminderDateForPersonAlias(personAliasId);
                }

                var results = new StringBuilder();
                results.AppendLine($"{result.MessagesSent}  assessment reminders sent.");
                if (result.Warnings.Count > 0)
                {
                    var warning = "Warning".PluralizeIf(result.Warnings.Count > 1);
                    results.AppendLine($"{result.Warnings.Count} {warning}:");
                    result.Warnings.ForEach(e => { results.AppendLine(e); });
                }
                context.Result = results.ToString();

                if (result.Errors.Any())
                {
                    var error = "Error".PluralizeIf(result.Errors.Count > 1);

                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.AppendLine($"{result.Errors.Count()} {error}: ");
                    result.Errors.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;
                }
            }
        }
示例#3
0
 public AssessmentController(AssessmentService assessmentService)
 {
     _assessmentService = assessmentService;
 }
示例#4
0
        public override void Given()
        {
            // Parameters
            AoUkprn = 10011881;
            _ulns   = new Dictionary <long, RegistrationPathwayStatus>
            {
                { 1111111111, RegistrationPathwayStatus.Active },
                { 1111111112, RegistrationPathwayStatus.Active },
                { 1111111113, RegistrationPathwayStatus.Withdrawn },
                { 1111111114, RegistrationPathwayStatus.Active },
                { 1111111115, RegistrationPathwayStatus.Active },
            };

            // Create mapper
            CreateMapper();

            // Registrations seed
            SeedTestData(EnumAwardingOrganisation.Pearson, true);
            _registrations = SeedRegistrationsData(_ulns, TqProvider);

            // Assessments seed
            var tqPathwayAssessmentsSeedData = new List <TqPathwayAssessment>();
            var tqPathwayResultsSeedData     = new List <TqPathwayResult>();

            foreach (var registration in _registrations.Where(x => x.UniqueLearnerNumber != 1111111111))
            {
                var hasHitoricData = new List <long> {
                    1111111112
                };
                var isHistoricAssessent = hasHitoricData.Any(x => x == registration.UniqueLearnerNumber);
                var isLatestActive      = _ulns[registration.UniqueLearnerNumber] != RegistrationPathwayStatus.Withdrawn;

                var pathwayAssessments = GetPathwayAssessmentsDataToProcess(registration.TqRegistrationPathways.ToList(), isLatestActive, isHistoricAssessent);
                tqPathwayAssessmentsSeedData.AddRange(pathwayAssessments);

                //Build Pathway results
                var ulnWithResult = new List <long> {
                    1111111114, 1111111115
                };
                if (ulnWithResult.Any(x => x == registration.UniqueLearnerNumber))
                {
                    foreach (var assessment in pathwayAssessments)
                    {
                        var hasHitoricResult = new List <long> {
                            1111111115
                        };
                        var isHistoricResult     = hasHitoricResult.Any(x => x == registration.UniqueLearnerNumber);
                        var isLatestActiveResult = !isHistoricResult;

                        var tqPathwayResultSeedData = GetPathwayResultDataToProcess(assessment, isLatestActiveResult, isHistoricResult);
                        tqPathwayResultsSeedData.AddRange(tqPathwayResultSeedData);
                    }
                }
            }

            _pathwayAssessments = SeedPathwayAssessmentsData(tqPathwayAssessmentsSeedData, false);
            SeedPathwayResultsData(tqPathwayResultsSeedData);

            AssessmentRepositoryLogger       = new Logger <AssessmentRepository>(new NullLoggerFactory());
            AssessmentSeriesRepositoryLogger = new Logger <GenericRepository <AssessmentSeries> >(new NullLoggerFactory());
            AssessmentRepository             = new AssessmentRepository(AssessmentRepositoryLogger, DbContext);
            AssessmentSeriesRepository       = new GenericRepository <AssessmentSeries>(AssessmentSeriesRepositoryLogger, DbContext);
            AssessmentService = new AssessmentService(AssessmentRepository, PathwayAssessmentRepository, SpecialismAssessmentRepository, AssessmentSeriesRepository, AssessmentMapper, AssessmentRepositoryLogger);
        }
示例#5
0
        private bool CheckNameExist(string fileName)
        {
            AssessmentService assessmentService = new AssessmentService();

            return(assessmentService.CheckNameExist(fileName));
        }
示例#6
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)
        {
            /*
             * 2019-12-09 - ED
             * This activity will create a new assessment for each assessment type selected. If an assessment already exists for that type it is left in a pending status but a new assessment is still created.
             * Per Jon, code in Rock should account for the possibility of multiple assessments for a type that are in a pending state and only select the latest one.
             */

            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);
            }

            PersonAlias requestedByAlias = null;

            if (requestedByAliasGuid != null)
            {
                requestedByAlias = new PersonAliasService(rockContext).Get(requestedByAliasGuid.Value);
            }

            foreach (string assessmentTypeGuid in assessmentTypeGuids)
            {
                var assessmentTypeService = new AssessmentTypeService(rockContext);
                int?assessmentTypeId      = assessmentTypeService.GetId(assessmentTypeGuid.AsGuid());

                if (assessmentTypeId == null)
                {
                    // This really shouldn't be able to happen, but let's not risk an NRE.
                    errorMessages.Add($"Invalid Assessment Type: {assessmentTypeGuid}");
                    continue;
                }

                // 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
                };

                var assessmentService = new AssessmentService(rockContext);
                assessmentService.Add(assessment);
                rockContext.SaveChanges();
            }

            return(true);
        }
示例#7
0
        /// <summary>
        /// Handles the Click event of the btnNext 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 btnNext_Click(object sender, EventArgs e)
        {
            int pageNumber = hfPageNo.ValueAsInt() + 1;

            GetResponse();

            LinkButton btn             = ( LinkButton )sender;
            string     commandArgument = btn.CommandArgument;

            var totalQuestion = pageNumber * QuestionCount;

            if ((_assessmentResponses.Count > totalQuestion && !_assessmentResponses.All(a => !string.IsNullOrEmpty(a.MostScore) && !string.IsNullOrEmpty(a.LeastScore))) || "Next".Equals(commandArgument))
            {
                BindRepeater(pageNumber);
            }
            else
            {
                try
                {
                    var moreD = _assessmentResponses.Where(a => a.MostScore == "D").Count();
                    var moreI = _assessmentResponses.Where(a => a.MostScore == "I").Count();
                    var moreS = _assessmentResponses.Where(a => a.MostScore == "S").Count();
                    var moreC = _assessmentResponses.Where(a => a.MostScore == "C").Count();
                    var lessD = _assessmentResponses.Where(a => a.LeastScore == "D").Count();
                    var lessI = _assessmentResponses.Where(a => a.LeastScore == "I").Count();
                    var lessS = _assessmentResponses.Where(a => a.LeastScore == "S").Count();
                    var lessC = _assessmentResponses.Where(a => a.LeastScore == "C").Count();

                    // Score the responses and return the results
                    DiscService.AssessmentResults results = DiscService.Score(moreD, moreI, moreS, moreC, lessD, lessI, lessS, lessC);

                    // Now save the results for this person
                    DiscService.SaveAssessmentResults(
                        _targetPerson,
                        results.AdaptiveBehaviorD.ToString(),
                        results.AdaptiveBehaviorI.ToString(),
                        results.AdaptiveBehaviorS.ToString(),
                        results.AdaptiveBehaviorC.ToString(),
                        results.NaturalBehaviorD.ToString(),
                        results.NaturalBehaviorI.ToString(),
                        results.NaturalBehaviorS.ToString(),
                        results.NaturalBehaviorC.ToString(),
                        results.PersonalityType);

                    var assessmentData = _assessmentResponses.ToDictionary(a => a.QuestionNumber, b => new { Most = new string[2] {
                                                                                                                 b.MostScore, b.Questions[b.MostScore]
                                                                                                             }, Least = new string[2] {
                                                                                                                 b.LeastScore, b.Questions[b.LeastScore]
                                                                                                             } });
                    var rockContext = new RockContext();

                    var        assessmentService = new AssessmentService(rockContext);
                    Assessment assessment        = null;

                    if (hfAssessmentId.ValueAsInt() != 0)
                    {
                        assessment = assessmentService.Get(int.Parse(hfAssessmentId.Value));
                    }

                    if (assessment == null)
                    {
                        var assessmentType = new AssessmentTypeService(rockContext).Get(Rock.SystemGuid.AssessmentType.DISC.AsGuid());
                        assessment = new Assessment()
                        {
                            AssessmentTypeId = assessmentType.Id,
                            PersonAliasId    = _targetPerson.PrimaryAliasId.Value
                        };
                        assessmentService.Add(assessment);
                    }

                    assessment.Status               = AssessmentRequestStatus.Complete;
                    assessment.CompletedDateTime    = RockDateTime.Now;
                    assessment.AssessmentResultData = new { Result = assessmentData, TimeToTake = RockDateTime.Now.Subtract(StartDateTime).TotalSeconds }.ToJson();
                    rockContext.SaveChanges();

                    ShowResult(results, assessment);
                }
                catch (Exception ex)
                {
                    nbError.Visible = true;
                    nbError.Title   = "We're Sorry...";
                    nbError.Text    = "Something went wrong while trying to save your test results.";
                    LogException(ex);
                }
            }
        }
示例#8
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var        rockContext    = new RockContext();
                var        assessmentType = new AssessmentTypeService(rockContext).Get(Rock.SystemGuid.AssessmentType.CONFLICT.AsGuid());
                Assessment assessment     = null;

                if (_targetPerson != null)
                {
                    var primaryAliasId = _targetPerson.PrimaryAliasId;

                    if (_assessmentId == 0)
                    {
                        // This indicates that the block should create a new assessment instead of looking for an existing one. e.g. a user directed re-take
                        assessment = null;
                    }
                    else
                    {
                        // Look for an existing pending or completed assessment.
                        assessment = new AssessmentService(rockContext)
                                     .Queryable()
                                     .Where(a => (_assessmentId.HasValue && a.Id == _assessmentId) || (a.PersonAliasId == primaryAliasId && a.AssessmentTypeId == assessmentType.Id))
                                     .OrderByDescending(a => a.CreatedDateTime)
                                     .FirstOrDefault();
                    }

                    if (assessment != null)
                    {
                        hfAssessmentId.SetValue(assessment.Id);
                    }
                    else
                    {
                        hfAssessmentId.SetValue(0);
                    }

                    if (assessment != null && assessment.Status == AssessmentRequestStatus.Complete)
                    {
                        ConflictProfileService.AssessmentResults savedScores = ConflictProfileService.LoadSavedAssessmentResults(_targetPerson);
                        ShowResult(savedScores, assessment);
                    }
                    else if ((assessment == null && !assessmentType.RequiresRequest) || (assessment != null && assessment.Status == AssessmentRequestStatus.Pending))
                    {
                        if (_targetPerson.Id != CurrentPerson.Id)
                        {
                            // If the current person is not the target person and there are no results to show then show a not taken message.
                            HidePanelsAndShowError(string.Format("{0} does not have results for the Conflict Profile Assessment.", _targetPerson.FullName));
                        }
                        else
                        {
                            ShowInstructions();
                        }
                    }
                    else
                    {
                        HidePanelsAndShowError("Sorry, this test requires a request from someone before it can be taken.");
                    }
                }
            }
            else
            {
                // Hide notification panels on every postback
                nbError.Visible = false;
            }
        }
示例#9
0
        public override void Given()
        {
            expectedStage2Response = new List <AssessmentCsvRecordResponse>
            {
                new AssessmentCsvRecordResponse {
                    RowNum = 1, Uln = 1111111111, CoreCode = "12345678", CoreAssessmentEntry = "Summer 2022", SpecialismCode = "LAR12345", SpecialismAssessmentEntry = "Autumn 2023", ValidationErrors = new List <BulkProcessValidationError>
                    {
                        new BulkProcessValidationError {
                            RowNum = "1", Uln = "1111111111", ErrorMessage = "Core code must have 8 digits only"
                        }
                    }
                },
                new AssessmentCsvRecordResponse {
                    RowNum = 2, Uln = 1111111112, CoreCode = "12345678", CoreAssessmentEntry = "Summer 2022", SpecialismCode = "LAR12345", SpecialismAssessmentEntry = "Autumn 2023", ValidationErrors = new List <BulkProcessValidationError>
                    {
                        new BulkProcessValidationError {
                            RowNum = "2", Uln = "1111111112", ErrorMessage = "Last name required"
                        }
                    }
                },
                new AssessmentCsvRecordResponse {
                    RowNum = 3, Uln = 1111111113, CoreCode = "12345678", CoreAssessmentEntry = "Summer 2022", SpecialismCode = "LAR12345", SpecialismAssessmentEntry = "Autumn 2023"
                },
                new AssessmentCsvRecordResponse {
                    RowNum = 4, Uln = 1111111114, CoreCode = "12345678", CoreAssessmentEntry = "Summer 2022", SpecialismCode = "LAR12345", SpecialismAssessmentEntry = "Autumn 2023"
                },
                new AssessmentCsvRecordResponse {
                    RowNum = 5, Uln = 1111111115, CoreCode = "12345678", CoreAssessmentEntry = "Summer 2022", SpecialismCode = "LAR12345", SpecialismAssessmentEntry = "Autumn 2023"
                }
            };

            var expectedStage3Response = new List <AssessmentRecordResponse>
            {
                new AssessmentRecordResponse {
                    ValidationErrors = new List <BulkProcessValidationError>
                    {
                        new BulkProcessValidationError {
                            RowNum = "3", Uln = "1111111113", ErrorMessage = "Core code either not recognised or not registered for this ULN"
                        },
                    }
                },
                new AssessmentRecordResponse {
                    ValidationErrors = new List <BulkProcessValidationError>
                    {
                        new BulkProcessValidationError {
                            RowNum = "4", Uln = "1111111114", ErrorMessage = "Specialism code either not recognised or not registered for this ULN"
                        }
                    }
                },
                new AssessmentRecordResponse {
                    ValidationErrors = new List <BulkProcessValidationError>
                    {
                        new BulkProcessValidationError {
                            RowNum = "5", Uln = "1111111115", ErrorMessage = "Specialism assessment entry must be the second series in the second academic year or the first series in the third academic year and be in the format detailed in the 'format rules' and 'example' columns in the technical specification"
                        }
                    }
                },
            };

            var csvResponse = new CsvResponseModel <AssessmentCsvRecordResponse> {
                Rows = expectedStage2Response
            };
            var expectedWriteFileBytes = new byte[5];

            BlobService.DownloadFileAsync(Arg.Any <BlobStorageData>()).Returns(new MemoryStream(Encoding.ASCII.GetBytes("Test File")));
            CsvService.ReadAndParseFileAsync(Arg.Any <AssessmentCsvRecordRequest>()).Returns(csvResponse);
            AssessmentService.ValidateAssessmentsAsync(AoUkprn, Arg.Any <IEnumerable <AssessmentCsvRecordResponse> >()).Returns(expectedStage3Response);
            CsvService.WriteFileAsync(Arg.Any <List <BulkProcessValidationError> >()).Returns(expectedWriteFileBytes);
        }
示例#10
0
        /// <summary>
        /// Shows the assessment.
        /// A null value for _targetPerson is already handled in OnInit() so this method assumes there is a value
        /// </summary>
        private void ShowAssessment()
        {
            /*
             * 2020-01-09 - ETD
             * This block will either show the assessment results of the most recent assessment test or give the assessment test.
             * The following use cases are considered:
             * 1. If the assessment ID "0" was provided then create a new test for the current user. This covers user directed retakes.
             * 2. If the assessment ID was provided and is not "0"
             *  Note: The assessment results are stored on the person's attributes and are overwritten if the assessment is retaken. So past Assessments will not be loaded by this block.
             *  The test data is saved in the assessment table but would need to be recomputed, which may be a future feature.
             *  a. The assessment ID is ignored and the current person is used.
             *  b. If the assessment exists for the current person and is completed then show the results
             *  c. If the assessment exists for the current person and is pending then show the questions.
             *  d. If the assessment does not exist for the current person then nothing loads.
             * 3. If the assessment ID was not provided and the PersonKey was provided
             *  a. If there is only one test of the type
             *      1. If the assessment is completed show the results
             *      2. If the assessment is pending and the current person is the one assigned the test then show the questions.
             *      3. If the assessment is pending and the current person is not the one assigned then show a message that the test has not been completed.
             *  b. If more than one of type
             *      1. If the latest requested assessment is completed show the results.
             *      2. If the latest requested assessment is pending and the current person is the one assigned then show the questions.
             *      3. If the latest requested assessment is pending and the current person is not the one assigned the show the results of the last completed test.
             *      4. If the latest requested assessment is pending and the current person is not the one assigned and there are no previous completed assessments then show a message that the test has not been completed.
             * 4. If an assessment ID or PersonKey were not provided or are not valid then show an error message
             */

            var        rockContext    = new RockContext();
            var        assessmentType = new AssessmentTypeService(rockContext).Get(Rock.SystemGuid.AssessmentType.DISC.AsGuid());
            Assessment assessment     = null;
            Assessment previouslyCompletedAssessment = null;

            // A "0" value indicates that the block should create a new assessment instead of looking for an existing one, so keep assessment null. e.g. a user directed re-take
            if (_assessmentId != 0)
            {
                var assessments = new AssessmentService(rockContext)
                                  .Queryable()
                                  .AsNoTracking()
                                  .Where(a => a.PersonAlias != null &&
                                         a.PersonAlias.PersonId == _targetPerson.Id &&
                                         a.AssessmentTypeId == assessmentType.Id)
                                  .OrderByDescending(a => a.CompletedDateTime ?? a.RequestedDateTime)
                                  .ToList();

                if (_assessmentId == null && assessments.Count == 0)
                {
                    // For this to happen the user has to have never taken the assessment, the user isn't using a link with the assessment ID, AND they are arriving at the block directly rather than through the assessment list block.
                    // So treat this as a user directed take/retake.
                    _assessmentId = 0;
                }
                else
                {
                    if (assessments.Count > 0)
                    {
                        // If there are any results then pick the first one. If the assesement ID was specified then the query will only return one result
                        assessment = assessments[0];
                    }
                    if (assessments.Count > 1)
                    {
                        // If there are more than one result then we need to pick the right one (see developer note)
                        // If the most recent assessment is "Completed" then it is already set as the assessment and we can move on. Otherwise check if there are previoulsy completed assessments.
                        if (assessment.Status == AssessmentRequestStatus.Pending)
                        {
                            // If the most recent assessment is pending then check for a prior completed one
                            previouslyCompletedAssessment = assessments.Where(a => a.Status == AssessmentRequestStatus.Complete).FirstOrDefault();
                        }
                    }
                }
            }

            if (assessment == null)
            {
                // If assessment is null and _assessmentId = 0 this is user directed. If the type does not require a request then show instructions
                if (_assessmentId == 0 && !assessmentType.RequiresRequest)
                {
                    hfAssessmentId.SetValue(0);
                    ShowInstructions();
                }
                else
                {
                    // If assessment is null and _assessmentId != 0 or is 0 but the type does require a request then show requires request error
                    HidePanelsAndShowError("Sorry, this test requires a request from someone before it can be taken.");
                }

                return;
            }

            hfAssessmentId.SetValue(assessment.Id);

            // If assessment is completed show the results
            if (assessment.Status == AssessmentRequestStatus.Complete)
            {
                DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(_targetPerson);
                ShowResult(savedScores, assessment);
                return;
            }

            if (assessment.Status == AssessmentRequestStatus.Pending)
            {
                if (_targetPerson.Id != CurrentPerson.Id)
                {
                    // If assessment is pending and the current person is not the one assigned the show previouslyCompletedAssessment results
                    if (previouslyCompletedAssessment != null)
                    {
                        DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(_targetPerson);
                        ShowResult(savedScores, previouslyCompletedAssessment, true);
                        return;
                    }

                    // If assessment is pending and the current person is not the one assigned and previouslyCompletedAssessment is null show a message that the test has not been completed.
                    HidePanelsAndShowError(string.Format("{0} has not yet taken the {1} Assessment.", _targetPerson.FullName, assessmentType.Title));
                }
                else
                {
                    // If assessment is pending and the current person is the one assigned then show the questions
                    ShowInstructions();
                }

                return;
            }

            // This should never happen, if the block gets to this point then something is not right
            HidePanelsAndShowError("Unable to load assessment");
        }
示例#11
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);
        }
示例#12
0
        public override void Render(PersonBadgeCache badge, HtmlTextWriter writer)
        {
            string[] assessmentTypeGuids = new string[] { };

            // Create a list of assessments that should be included in the badge
            if (!String.IsNullOrEmpty(GetAttributeValue(badge, AttributeKeys.AssessmentsToShow)))
            {
                // Get from attribute if available
                var assessmentTypesGuidString = GetAttributeValue(badge, AttributeKeys.AssessmentsToShow);
                assessmentTypeGuids = assessmentTypesGuidString.IsNullOrWhiteSpace() ? null : assessmentTypesGuidString.Split(new char[] { ',' });
            }
            else
            {
                // If none are selected then all are used.
                assessmentTypeGuids = new string[]
                {
                    Rock.SystemGuid.AssessmentType.CONFLICT,
                    Rock.SystemGuid.AssessmentType.DISC,
                    Rock.SystemGuid.AssessmentType.EQ,
                    Rock.SystemGuid.AssessmentType.GIFTS,
                    Rock.SystemGuid.AssessmentType.MOTIVATORS
                };
            }

            StringBuilder toolTipText = new StringBuilder();
            StringBuilder badgeIcons  = new StringBuilder();

            foreach (var assessmentTypeGuid in assessmentTypeGuids)
            {
                var    assessmentType         = new AssessmentTypeService(new RockContext()).GetNoTracking(assessmentTypeGuid.AsGuid());
                string resultsPath            = assessmentType.AssessmentResultsPath;
                string resultsPageUrl         = System.Web.VirtualPathUtility.ToAbsolute($"~{resultsPath}?Person={Person.UrlEncodedKey}");
                string iconCssClass           = assessmentType.IconCssClass;
                string badgeHtml              = string.Empty;
                string assessmentTitle        = string.Empty;
                var    mergeFields            = new Dictionary <string, object>();
                string mergedBadgeSummaryLava = "Not taken";

                switch (assessmentTypeGuid.ToUpper())
                {
                case Rock.SystemGuid.AssessmentType.CONFLICT:

                    var conflictsThemes = new Dictionary <string, decimal>();
                    conflictsThemes.Add("Winning", Person.GetAttributeValue("core_ConflictThemeWinning").AsDecimalOrNull() ?? 0);
                    conflictsThemes.Add("Solving", Person.GetAttributeValue("core_ConflictThemeSolving").AsDecimalOrNull() ?? 0);
                    conflictsThemes.Add("Accommodating", Person.GetAttributeValue("core_ConflictThemeAccommodating").AsDecimalOrNull() ?? 0);

                    string highestScoringTheme = conflictsThemes.Where(x => x.Value == conflictsThemes.Max(v => v.Value)).Select(x => x.Key).FirstOrDefault() ?? string.Empty;
                    mergeFields.Add("ConflictTheme", highestScoringTheme);
                    assessmentTitle = "Conflict Theme";
                    break;

                case Rock.SystemGuid.AssessmentType.DISC:
                    assessmentTitle = "DISC";
                    break;

                case Rock.SystemGuid.AssessmentType.EQ:
                    assessmentTitle = "EQ Self Aware";
                    break;

                case Rock.SystemGuid.AssessmentType.GIFTS:
                    assessmentTitle = "Spiritual Gifts";
                    break;

                case Rock.SystemGuid.AssessmentType.MOTIVATORS:
                    assessmentTitle = "Motivators";
                    break;
                }

                // Check if person has taken test
                var assessmentTest = new AssessmentService(new RockContext())
                                     .Queryable()
                                     .Where(a => a.PersonAlias.PersonId == Person.Id)
                                     .Where(a => a.AssessmentTypeId == assessmentType.Id)
                                     .Where(a => a.Status == AssessmentRequestStatus.Complete)
                                     .OrderByDescending(a => a.CreatedDateTime)
                                     .FirstOrDefault();

                string badgeColor = assessmentTest != null ? assessmentType.BadgeColor : UNTAKEN_BADGE_COLOR;

                badgeIcons.AppendLine($@"<div class='badge'>");
                // If the latest request has been taken we want to link to it and provide a Lava merged summary
                if (assessmentTest != null)
                {
                    badgeIcons.AppendLine($@"<a href='{resultsPageUrl}' target='_blank'>");

                    mergeFields.Add("Person", Person);
                    mergedBadgeSummaryLava = assessmentType.BadgeSummaryLava.ResolveMergeFields(mergeFields);
                }

                badgeIcons.AppendLine($@"
                        <span class='fa-stack'>
                            <i style='color:{badgeColor};' class='fa fa-circle fa-stack-2x'></i>
                            <i class='{iconCssClass} fa-stack-1x'></i>
                        </span>");

                // Close the anchor for the linked assessment test
                if (assessmentTest != null)
                {
                    badgeIcons.AppendLine("</a>");
                }

                badgeIcons.AppendLine($@"</div>");

                toolTipText.AppendLine($@"
                    <p class='margin-b-sm'>
                        <span class='fa-stack'>
                            <i style='color:{assessmentType.BadgeColor};' class='fa fa-circle fa-stack-2x'></i>
                            <i style='font-size:15px; color:#ffffff;' class='{iconCssClass} fa-stack-1x'></i>
                        </span>
                        <strong>{assessmentTitle}:</strong> {mergedBadgeSummaryLava}
                    </p>");
            }

            writer.Write($@"<div class='badge badge-id-{badge.Id}'><div class='badge-grid' data-toggle='tooltip' data-html='true' data-sanitize='false' data-original-title=""{toolTipText.ToString()}"">");
            writer.Write(badgeIcons.ToString());
            writer.Write("</div></div>");
            writer.Write($@"
                <script>
                    Sys.Application.add_load(function () {{
                        $('.badge-id-{badge.Id}').children('.badge-grid').tooltip({{ sanitize: false }});
                    }});
                </script>");
        }
示例#13
0
        /// <summary>
        /// Renders the specified writer.
        /// </summary>
        /// <param name="badge">The badge.</param>
        /// <param name="writer">The writer.</param>
        public override void Render(BadgeCache badge, HtmlTextWriter writer)
        {
            if (Person == null)
            {
                return;
            }

            var assessmentTypes = new List <AssessmentTypeCache>();

            // Create a list of assessments that should be included in the badge
            if (!string.IsNullOrEmpty(GetAttributeValue(badge, AttributeKeys.AssessmentsToShow)))
            {
                // Get from attribute if available
                var assessmentTypesGuidString = GetAttributeValue(badge, AttributeKeys.AssessmentsToShow);
                var assessmentTypeGuids       = assessmentTypesGuidString.IsNullOrWhiteSpace() ? null : assessmentTypesGuidString.Split(new char[] { ',' });
                foreach (var assessmentGuid in assessmentTypeGuids)
                {
                    assessmentTypes.Add(AssessmentTypeCache.Get(assessmentGuid));
                }
            }
            else
            {
                // If none are selected then all are used.
                assessmentTypes = AssessmentTypeCache.All();
            }

            // Need a list of primitive types for assessmentTestsTaken linq
            var availableTypes = assessmentTypes.Select(t => t.Id).ToList();

            var assessmentTestsTaken = new AssessmentService(new RockContext())
                                       .Queryable()
                                       .AsNoTracking()
                                       .Where(a => a.PersonAlias != null &&
                                              a.PersonAlias.PersonId == Person.Id &&
                                              availableTypes.Contains(a.AssessmentTypeId))
                                       .OrderByDescending(a => a.CompletedDateTime ?? a.RequestedDateTime)
                                       .Select(a => new PersonBadgeAssessment {
                AssessmentTypeId = a.AssessmentTypeId, RequestedDateTime = a.RequestedDateTime, Status = a.Status
            })
                                       .ToList();

            StringBuilder toolTipText = new StringBuilder();
            StringBuilder badgeRow1   = new StringBuilder($@"<div class='badge-row'>");
            StringBuilder badgeRow2   = new StringBuilder();

            if (assessmentTypes.Count > 1)
            {
                badgeRow2.AppendLine($@"<div class='badge-row'>");
            }

            for (int i = 0; i < assessmentTypes.Count; i++)
            {
                StringBuilder badgeIcons = new StringBuilder();

                badgeIcons = i % 2 == 0 ? badgeRow1 : badgeRow2;

                var assessmentType         = assessmentTypes[i];
                var resultsPageUrl         = System.Web.VirtualPathUtility.ToAbsolute($"~{assessmentType.AssessmentResultsPath}?Person={this.Person.GetPersonActionIdentifier( "Assessment" ) }");
                var assessmentTitle        = assessmentType.Title;
                var mergeFields            = new Dictionary <string, object>();
                var mergedBadgeSummaryLava = "Not requested";

                switch (assessmentType.Guid.ToString().ToUpper())
                {
                case Rock.SystemGuid.AssessmentType.CONFLICT:

                    var conflictsThemes = new Dictionary <string, decimal>
                    {
                        { "Winning", Person.GetAttributeValue("core_ConflictThemeWinning").AsDecimalOrNull() ?? 0 },
                        { "Solving", Person.GetAttributeValue("core_ConflictThemeSolving").AsDecimalOrNull() ?? 0 },
                        { "Accommodating", Person.GetAttributeValue("core_ConflictThemeAccommodating").AsDecimalOrNull() ?? 0 }
                    };

                    string highestScoringTheme = conflictsThemes.Where(x => x.Value == conflictsThemes.Max(v => v.Value)).Select(x => x.Key).FirstOrDefault() ?? string.Empty;
                    mergeFields.Add("ConflictTheme", highestScoringTheme);
                    assessmentTitle = "Conflict Theme";
                    break;

                case Rock.SystemGuid.AssessmentType.EQ:
                    assessmentTitle = "EQ Self Aware";
                    break;
                }

                string assessmentTypeClass   = AssessmentBadgeCssClasses.AssessmentTypePrefix + assessmentTitle.RemoveSpaces().ToLower();
                string assessmentStatusClass = AssessmentBadgeCssClasses.NotRequested;
                PersonBadgeAssessment previouslyCompletedAssessmentTest = null;

                // Get the status of the assessment
                var assessmentTests = assessmentTestsTaken.Where(t => t.AssessmentTypeId == assessmentType.Id).ToList();
                PersonBadgeAssessment assessmentTest = null;
                if (assessmentTests.Count > 0)
                {
                    assessmentTest        = assessmentTests.First();
                    assessmentStatusClass = assessmentTest.Status == AssessmentRequestStatus.Pending ? AssessmentBadgeCssClasses.Requested : AssessmentBadgeCssClasses.Taken;
                }

                if (assessmentTests.Count > 1)
                {
                    // If the most recent one is completed then it is already set as the test and we can move on, the initial query ordered them by RequestedDateTime. Otherwise check if there are previoulsy completed assessments.
                    if (assessmentTests[0].Status != AssessmentRequestStatus.Complete)
                    {
                        // If the most recent one is pending then check for a completed one prior, if found then we need to display the competed text and note that an the assessment has been requested. The link should go to the completed assessment.
                        previouslyCompletedAssessmentTest = assessmentTests.Where(a => a.Status == AssessmentRequestStatus.Complete).FirstOrDefault();
                        if (previouslyCompletedAssessmentTest != null)
                        {
                            // There is a new pending assessment and a previously completed assessment, display both classes
                            assessmentStatusClass = $"{AssessmentBadgeCssClasses.Requested} {AssessmentBadgeCssClasses.Taken}";
                        }
                    }
                }

                // Only set the color if the test has been taken.
                string badgeColorHtml = string.Empty;

                // If there is a completed request we want to link to it and provide a Lava merged summary
                if (assessmentTest != null)
                {
                    if (assessmentTest.Status == AssessmentRequestStatus.Complete || previouslyCompletedAssessmentTest != null)
                    {
                        badgeColorHtml = assessmentType.BadgeColor.IsNotNullOrWhiteSpace() ? $"style='color:{assessmentType.BadgeColor};' " : string.Empty;

                        badgeIcons.AppendLine($@"<div {badgeColorHtml} class='badge {assessmentTypeClass} {assessmentStatusClass}'>");
                        badgeIcons.AppendLine($@"<a href='{resultsPageUrl}' target='_blank'>");

                        mergeFields.Add("Person", Person);
                        mergedBadgeSummaryLava = assessmentType.BadgeSummaryLava.ResolveMergeFields(mergeFields);
                    }

                    if (assessmentTest.Status == AssessmentRequestStatus.Pending && previouslyCompletedAssessmentTest == null)
                    {
                        badgeIcons.AppendLine($@"<div class='badge {assessmentTypeClass} {assessmentStatusClass}'>");

                        // set the request string and requested datetime to the merged lava
                        mergedBadgeSummaryLava = $"Requested: {assessmentTest.RequestedDateTime.ToShortDateString()}";
                    }
                }
                else
                {
                    badgeIcons.AppendLine($@"<div class='badge {assessmentTypeClass} {assessmentStatusClass}'>");
                }

                badgeIcons.AppendLine($@"
                        <span class='fa-stack'>
                            <i class='fa fa-circle fa-stack-2x'></i>
                            <i class='{assessmentType.IconCssClass} fa-stack-1x {AssessmentBadgeCssClasses.AssessmentIcon}'></i>
                        </span>");

                // Close the anchor for the linked assessment test
                if (assessmentTest != null)
                {
                    badgeIcons.AppendLine("</a>");
                }

                badgeIcons.AppendLine($@"</div>");

                string badgeToolTipColorHtml = assessmentType.BadgeColor.IsNotNullOrWhiteSpace() ? $"style='color:{assessmentType.BadgeColor};'" : string.Empty;
                toolTipText.AppendLine($@"
                    <p class='margin-b-sm'>
                        <span {badgeToolTipColorHtml} class='{assessmentTypeClass}'>
                            <span class='fa-stack'>
                                <i class='fa fa-circle fa-stack-2x'></i>
                                <i class='{assessmentType.IconCssClass} fa-stack-1x {AssessmentBadgeCssClasses.AssessmentIcon}'></i>
                            </span>
                        </span>
                        <strong>{assessmentTitle}:</strong> {mergedBadgeSummaryLava}
                    </p>");
            }

            badgeRow1.AppendLine($@"</div>");

            if (assessmentTypes.Count > 1)
            {
                badgeRow2.AppendLine($@"</div>");
            }

            writer.Write($@" <div class='badge badge-id-{badge.Id}'><div class='badge-grid' data-toggle='tooltip' data-html='true' data-sanitize='false' data-original-title=""{toolTipText.ToString()}"">");
            writer.Write(badgeRow1.ToString());
            writer.Write(badgeRow2.ToString());
            writer.Write("</div></div>");
            writer.Write($@"
                <script>
                    Sys.Application.add_load(function () {{
                        $('.badge-id-{badge.Id}').children('.badge-grid').tooltip({{ sanitize: false }});
                    }});
                </script>");
        }
示例#14
0
        public InspectionList()
        {
            Title = "Tom's Inspections";
            NavigationPage.SetHasNavigationBar(this, true);

            activityIndicator                   = new ActivityIndicator();
            activityIndicator.Color             = Color.FromHex("#3693FF");
            activityIndicator.VerticalOptions   = LayoutOptions.Center;
            activityIndicator.HorizontalOptions = LayoutOptions.Center;

            ToolbarItem toolbarItem = new ToolbarItem();

            toolbarItem.Icon = "Contact.png";
            ToolbarItems.Add(toolbarItem);

            newButton = new Button();
            newButton.WidthRequest      = 100;
            newButton.HeightRequest     = 100;
            newButton.CornerRadius      = 50;
            newButton.Text              = "6";
            newButton.BackgroundColor   = Color.FromHex("#C0BF07");
            newButton.HorizontalOptions = LayoutOptions.Start;
            //newButton.Margin = new Thickness(150, 0, 0, 0);
            newButton.FontSize  = 50;
            newButton.TextColor = Color.White;

            Label lblNew = new Label();

            lblNew.Text = "New";
            //lblNew.Margin = new Thickness(185, 0, 0, 0);

            inprogressButton = new Button();
            inprogressButton.WidthRequest      = 100;
            inprogressButton.HeightRequest     = 100;
            inprogressButton.CornerRadius      = 50;
            inprogressButton.Text              = "2";
            inprogressButton.BackgroundColor   = Color.FromHex("#CBCBCB");
            inprogressButton.HorizontalOptions = LayoutOptions.CenterAndExpand;
            inprogressButton.FontSize          = 50;
            inprogressButton.TextColor         = Color.White;

            Label lblInprogress = new Label();

            lblInprogress.Text = "In Progress";
            lblInprogress.HorizontalOptions = LayoutOptions.CenterAndExpand;

            completedButton = new Button();
            completedButton.WidthRequest      = 100;
            completedButton.HeightRequest     = 100;
            completedButton.CornerRadius      = 50;
            completedButton.Text              = "12";
            completedButton.BackgroundColor   = Color.FromHex("#CBCBCB");
            completedButton.HorizontalOptions = LayoutOptions.End;
            //completedButton.Margin = new Thickness(0, 0, 150, 0);
            completedButton.FontSize  = 50;
            completedButton.TextColor = Color.White;

            Label lblCompleted = new Label();

            lblCompleted.Text = "Completed";
            //lblCompleted.Margin= new Thickness(0, 0, 150, 0);
            lblCompleted.HorizontalOptions = LayoutOptions.End;

            syncButton = new Button();
            syncButton.WidthRequest    = 100;
            syncButton.HeightRequest   = 40;
            syncButton.Text            = "Sync All";
            syncButton.BorderColor     = Color.FromHex("#CBCBCB");
            syncButton.BorderWidth     = 1;
            syncButton.BackgroundColor = Color.White;
            syncButton.TextColor       = Color.FromHex("#3693FF");
            //syncButton.Margin = new Thickness(25, 0, 0, 0);
            //syncButton.FontSize = 20;
            syncButton.HorizontalOptions = LayoutOptions.Start;

            deleteList                 = new Button();
            deleteList.Clicked        += DeleteList_Clicked;
            deleteList.WidthRequest    = 100;
            deleteList.HeightRequest   = 40;
            deleteList.Text            = "Delete All";
            deleteList.BorderColor     = Color.FromHex("#CBCBCB");
            deleteList.BorderWidth     = 1;
            deleteList.BackgroundColor = Color.White;
            deleteList.TextColor       = Color.FromHex("#3693FF");
            //deleteList.Padding = new Thickness(25, 0, 0, 0);
            //syncButton.FontSize = 20;
            //deleteList.HorizontalOptions = LayoutOptions.Start;

            refreshList                 = new Button();
            refreshList.Clicked        += RefreshList_Clicked;
            refreshList.WidthRequest    = 100;
            refreshList.HeightRequest   = 40;
            refreshList.Text            = "Get All";
            refreshList.BorderColor     = Color.FromHex("#CBCBCB");
            refreshList.BorderWidth     = 1;
            refreshList.BackgroundColor = Color.White;
            refreshList.TextColor       = Color.FromHex("#3693FF");
            //refreshList.Padding = new Thickness(25, 0, 0, 0);


            inspectionList = new ListView();
            Content        = new StackLayout
            {
                //Padding = 10,
                Orientation = StackOrientation.Vertical,
                Children    =
                {
                    new StackLayout             {
                        HeightRequest   = 175,
                        BackgroundColor = Color.FromHex("#F8F9F9"),

                        Children =
                        {
                            new StackLayout
                            {
                                Padding           = new Thickness(25, 25, 25, 25),
                                Orientation       = StackOrientation.Horizontal,
                                HorizontalOptions = LayoutOptions.CenterAndExpand,
                                Children          =
                                {
                                    new StackLayout
                                    {
                                        Padding = new Thickness(0, 0, 25, 0),//

                                        Orientation = StackOrientation.Vertical,
                                        //HorizontalOptions = LayoutOptions.Start,
                                        Children =
                                        {
                                            newButton,
                                            new StackLayout
                                            {
                                                VerticalOptions   = LayoutOptions.Center,
                                                HorizontalOptions = LayoutOptions.Center,
                                                Children          =
                                                {
                                                    lblNew
                                                }
                                            }
                                        }
                                    },
                                    new StackLayout
                                    {
                                        Orientation = StackOrientation.Vertical,
                                        //HorizontalOptions = LayoutOptions.CenterAndExpand,
                                        Padding  = new Thickness(25, 0, 25, 0),
                                        Children =
                                        {
                                            inprogressButton,
                                            new StackLayout
                                            {
                                                VerticalOptions   = LayoutOptions.Center,
                                                HorizontalOptions = LayoutOptions.Center,
                                                Children          =
                                                {
                                                    lblInprogress
                                                }
                                            }
                                        }
                                    },
                                    new StackLayout
                                    {
                                        Orientation = StackOrientation.Vertical,
                                        //HorizontalOptions = LayoutOptions.End,
                                        Padding  = new Thickness(25, 0, 0, 0),//
                                        Children =
                                        {
                                            completedButton,
                                            new StackLayout
                                            {
                                                VerticalOptions   = LayoutOptions.Center,
                                                HorizontalOptions = LayoutOptions.Center,
                                                Children          =
                                                {
                                                    lblCompleted
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    new StackLayout
                    {
                        Padding     = 25,
                        Orientation = StackOrientation.Horizontal,
                        Children    =
                        {
                            syncButton,
                            deleteList,
                            refreshList
                        }
                    }

                    , inspectionList
                }
            };


            AssessmentService assessmentService         = new AssessmentService();
            List <AssessmentMetadataEntity> assessments = assessmentService.GetListOfAllAssignedAssessmentsFromDevice();
            var customAssessmentCell = new DataTemplate(typeof(CustomInspectionCell));

            //Bind forms
            inspectionList.ItemsSource    = assessments;
            inspectionList.ItemTemplate   = customAssessmentCell;
            inspectionList.ItemSelected  += InspectionList_ItemSelected;
            inspectionList.HeightRequest  = 500;
            inspectionList.RowHeight      = 100;
            inspectionList.SelectionMode  = ListViewSelectionMode.Single;
            inspectionList.SeparatorColor = Color.Gray;
            inspectionList.HasUnevenRows  = false;

            UpdateInspectionCountCircles(assessments);
        }
示例#15
0
        /// <summary>
        /// Handles the Click event of the btnNext 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 btnNext_Click(object sender, EventArgs e)
        {
            int pageNumber = hfPageNo.ValueAsInt() + 1;

            GetResponse();

            LinkButton btn             = ( LinkButton )sender;
            string     commandArgument = btn.CommandArgument;

            var totalQuestion = pageNumber * QuestionCount;

            if ((_assessmentResponses.Count > totalQuestion && !_assessmentResponses.All(a => a.Response.HasValue)) || "Next".Equals(commandArgument))
            {
                BindRepeater(pageNumber);
            }
            else
            {
                ConflictProfileService.AssessmentResults result = ConflictProfileService.GetResult(_assessmentResponses.ToDictionary(a => a.Code, b => b.Response.Value));
                ConflictProfileService.SaveAssessmentResults(_targetPerson, result);
                var rockContext = new RockContext();

                var        assessmentService = new AssessmentService(rockContext);
                Assessment assessment        = null;

                if (hfAssessmentId.ValueAsInt() != 0)
                {
                    assessment = assessmentService.Get(int.Parse(hfAssessmentId.Value));
                }

                if (assessment == null)
                {
                    var assessmentType = new AssessmentTypeService(rockContext).Get(Rock.SystemGuid.AssessmentType.CONFLICT.AsGuid());
                    assessment = new Assessment()
                    {
                        AssessmentTypeId = assessmentType.Id,
                        PersonAliasId    = _targetPerson.PrimaryAliasId.Value
                    };
                    assessmentService.Add(assessment);
                }

                assessment.Status               = AssessmentRequestStatus.Complete;
                assessment.CompletedDateTime    = RockDateTime.Now;
                assessment.AssessmentResultData = new { Result = result.AssessmentData, TimeToTake = RockDateTime.Now.Subtract(StartDateTime).TotalSeconds }.ToJson();
                rockContext.SaveChanges();

                // Since we are rendering chart.js we have to reload the page.
                if (_assessmentId == 0)
                {
                    var removeParams = new List <string>
                    {
                        PageParameterKey.AssessmentId
                    };

                    NavigateToCurrentPageReferenceWithRemove(removeParams);
                }
                else
                {
                    this.NavigateToCurrentPageReference();
                }
            }
        }
示例#16
0
 public override Task When()
 {
     _result = AssessmentService.TransformAssessmentsModel(_assessmentRecords, _performedBy);
     return(Task.CompletedTask);
 }
 public DivergencesResolver(AssessmentService assessmentService)
 {
     this.assessmentService = assessmentService;
 }
 public AssessmentController(AssessmentService assessmentService)
 {
     AssessmentService = assessmentService;
 }
示例#19
0
        /// <summary>
        /// Renders the specified writer.
        /// </summary>
        /// <param name="badge">The badge.</param>
        /// <param name="writer">The writer.</param>
        public override void Render(BadgeCache badge, System.Web.UI.HtmlTextWriter writer)
        {
            if (Person == null)
            {
                return;
            }

            // Grab the DISC Scores
            bool isValidDiscScore = true;
            int  discStrength     = 0;

            int?[] discScores = new int?[] { Person.GetAttributeValue("NaturalD").AsIntegerOrNull(), Person.GetAttributeValue("NaturalI").AsIntegerOrNull(), Person.GetAttributeValue("NaturalS").AsIntegerOrNull(), Person.GetAttributeValue("NaturalC").AsIntegerOrNull() };

            // Validate the DISC Scores, find the strength
            for (int i = 0; i < discScores.Length; i++)
            {
                // Does the scores have values?
                if (!discScores[i].HasValue)
                {
                    isValidDiscScore = false;
                }
                else
                {
                    // Are the scores valid values?
                    if ((discScores[i].Value < 0) || (discScores[i].Value > MAX))
                    {
                        isValidDiscScore = false;
                    }
                    else
                    {
                        if (discScores[i].Value > discScores[discStrength].Value)
                        {
                            discStrength = i;
                        }
                    }
                }
            }

            // Create the badge
            if (isValidDiscScore)
            {
                // Find the DISC Personality Type / Strength
                String description     = string.Empty;
                string personalityType = Person.GetAttributeValue("PersonalityType");
                if (!string.IsNullOrEmpty(personalityType))
                {
                    var personalityValue = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.DISC_RESULTS_TYPE.AsGuid()).DefinedValues.Where(v => v.Value == personalityType).FirstOrDefault();
                    if (personalityValue != null)
                    {
                        description = personalityValue.Description;
                    }
                }

                // create url for link to details if configured
                string detailPageUrl = string.Empty;
                if (!String.IsNullOrEmpty(GetAttributeValue(badge, "DISCResultDetail")))
                {
                    int pageId = PageCache.Get(Guid.Parse(GetAttributeValue(badge, "DISCResultDetail"))).Id;
                    detailPageUrl = System.Web.VirtualPathUtility.ToAbsolute(String.Format("~/page/{0}?Person={1}", pageId, Person.UrlEncodedKey));
                    writer.Write("<a href='{0}'>", detailPageUrl);
                }

                //Badge HTML
                writer.Write(String.Format("<div class='badge badge-disc badge-id-{0}' data-toggle='tooltip' data-original-title='{1}'>", badge.Id, description));
                writer.Write("<ul class='badge-disc-chart list-unstyled'>");
                writer.Write(string.Format("<li class='badge-disc-d {1}' title='D'><span style='height:{0}%'></span></li>", Math.Floor(( double )(( double )discScores[0].Value / ( double )MAX) * 100), (discStrength == 0) ? "badge-disc-primary" : String.Empty));
                writer.Write(string.Format("<li class='badge-disc-i {1}' title='I'><span style='height:{0}%'></span></li>", Math.Floor(( double )(( double )discScores[1].Value / ( double )MAX) * 100), (discStrength == 1) ? "badge-disc-primary" : String.Empty));
                writer.Write(string.Format("<li class='badge-disc-s {1}' title='S'><span style='height:{0}%'></span></li>", Math.Floor(( double )(( double )discScores[2].Value / ( double )MAX) * 100), (discStrength == 2) ? "badge-disc-primary" : String.Empty));
                writer.Write(string.Format("<li class='badge-disc-c {1}' title='C'><span style='height:{0}%'></span></li>", Math.Floor(( double )(( double )discScores[3].Value / ( double )MAX) * 100), (discStrength == 3) ? "badge-disc-primary" : String.Empty));
                writer.Write("</ul></div>");

                if (!String.IsNullOrEmpty(detailPageUrl))
                {
                    writer.Write("</a>");
                }
            }
            else
            {
                var rockContext     = new RockContext();
                var assessmentType  = new AssessmentTypeService(rockContext).Get(Rock.SystemGuid.AssessmentType.DISC.AsGuid());
                var lastRequestDate = new AssessmentService(rockContext)
                                      .Queryable()
                                      .AsNoTracking()
                                      .Where(a => a.PersonAlias != null &&
                                             a.PersonAlias.PersonId == Person.Id &&
                                             a.Status == AssessmentRequestStatus.Pending &&
                                             a.AssessmentTypeId == assessmentType.Id &&
                                             a.RequestedDateTime.HasValue)
                                      .Select(a => a.RequestedDateTime)
                                      .OrderByDescending(a => a)
                                      .FirstOrDefault();

                bool recentRequest = lastRequestDate.HasValue && lastRequestDate.Value > (RockDateTime.Now.AddDays(-30));

                if (recentRequest)
                {
                    writer.Write(String.Format("<div class='badge badge-disc badge-id-{0}' data-toggle='tooltip' data-original-title='A DISC request was made on {1}'>", badge.Id, lastRequestDate.Value.ToShortDateString()));
                    writer.Write("<ul class='badge-disc-chart list-unstyled'>");
                    writer.Write(string.Format("<li class='badge-disc-d badge-disc-disabled' title='D'><span style='height:{0}%'></span></li>", 80));
                    writer.Write(string.Format("<li class='badge-disc-i badge-disc-disabled' title='I'><span style='height:{0}%'></span></li>", 20));
                    writer.Write(string.Format("<li class='badge-disc-s badge-disc-disabled' title='S'><span style='height:{0}%'></span></li>", 60));
                    writer.Write(string.Format("<li class='badge-disc-c badge-disc-disabled' title='C'><span style='height:{0}%'></span></li>", 10));
                    writer.Write("</ul><div class='requested'>R</div></div>");
                }
            }
        }