/// <summary> /// Delete the current entity. /// </summary> private void DeleteCurrentEntity() { var targetEntity = this.GetTargetEntity(); if (targetEntity == null) { return; } if (!targetEntity.IsAuthorized(Authorization.ADMINISTRATE, this.CurrentPerson)) { mdDeleteWarning.Show("You are not authorized to delete this item.", ModalAlertType.Information); return; } var rockContext = this.GetDataContext(); var assessmentTypeService = new AssessmentTypeService(rockContext); string errorMessage; if (!assessmentTypeService.CanDelete(targetEntity, out errorMessage)) { mdDeleteWarning.Show(errorMessage, ModalAlertType.Information); return; } assessmentTypeService.Delete(targetEntity); rockContext.SaveChanges(); NavigateToParentPage(); }
/// <summary> /// Returns breadcrumbs specific to the block that should be added to navigation /// based on the current page reference. This function is called during the page's /// oninit to load any initial breadcrumbs /// </summary> /// <param name="pageReference">The page reference.</param> /// <returns></returns> public override List <BreadCrumb> GetBreadCrumbs(PageReference pageReference) { var breadCrumbs = new List <BreadCrumb>(); int?entityId = PageParameter(pageReference, PageParameterKey.EntityId).AsIntegerOrNull(); if (entityId != null) { var assessmentType = new AssessmentTypeService(this.GetDataContext()).Get(entityId.Value); if (assessmentType != null) { breadCrumbs.Add(new BreadCrumb(assessmentType.Title, pageReference)); } else { breadCrumbs.Add(new BreadCrumb("New Assessment Type", pageReference)); } } else { // don't show a breadcrumb if we don't have a pageparam to work with } return(breadCrumbs); }
/// <summary> /// Gets the specified entity data model and sets it as the current model, or retrieves the current model if none is specified. /// If the entity cannot be found, a newly-initialized model is created. /// </summary> /// <param name="entityId">The connection type identifier.</param> /// <returns></returns> private AssessmentType GetTargetEntity(int?entityId = null) { if (entityId == null) { entityId = hfEntityId.ValueAsInt(); } string key = string.Format("AssessmentType:{0}", entityId); var entity = RockPage.GetSharedItem(key) as AssessmentType; if (entity == null) { var rockContext = this.GetDataContext(); entity = new AssessmentTypeService(rockContext).Queryable() .Where(c => c.Id == entityId) .FirstOrDefault(); if (entity == null) { entity = new AssessmentType { Id = 0, IsActive = true }; } RockPage.SaveSharedItem(key, entity); } return(entity); }
/// <summary> /// Get the data source for the list after applying the specified filter settings. /// </summary> /// <param name="dataContext"></param> /// <param name="filterSettingsKeyValueMap"></param> /// <returns></returns> private object OnGetListDataSource(RockContext dataContext, Dictionary <string, string> filterSettingsKeyValueMap, SortProperty sortProperty) { var assessmentService = new AssessmentTypeService(dataContext); var assessmentTypesQry = assessmentService.Queryable(); // Filter by: Title var name = filterSettingsKeyValueMap[FilterSettingName.Title].ToStringSafe(); if (!string.IsNullOrWhiteSpace(name)) { assessmentTypesQry = assessmentTypesQry.Where(a => a.Title.Contains(name)); } // Filter by: Requires Request var requiresRequest = rFilter.GetUserPreference(FilterSettingName.RequiresRequest).AsBooleanOrNull(); if (requiresRequest.HasValue) { assessmentTypesQry = assessmentTypesQry.Where(a => a.RequiresRequest == requiresRequest.Value); } // Filter by: Is Active var isActive = rFilter.GetUserPreference(FilterSettingName.IsActive).AsBooleanOrNull(); if (isActive.HasValue) { assessmentTypesQry = assessmentTypesQry.Where(a => a.IsActive == isActive.Value); } // Apply Sorting. if (sortProperty != null) { assessmentTypesQry = assessmentTypesQry.Sort(sortProperty); } else { assessmentTypesQry = assessmentTypesQry.OrderBy(b => b.Title); } // Retrieve the Assessment Type data models and create corresponding view models to display in the grid. var assessmentTypes = assessmentTypesQry .Select(x => new AssessmentTypeListItemViewModel { Id = x.Id, Title = x.Title, RequiresRequest = x.RequiresRequest, IsActive = x.IsActive, IsSystem = x.IsSystem }) .ToList(); return(assessmentTypes); }
/// <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 { SpiritualGiftsService.AssessmentResults result = SpiritualGiftsService.GetResult(_assessmentResponses.ToDictionary(a => a.Code, b => b.Response.Value)); SpiritualGiftsService.SaveAssessmentResults(_targetPerson, result); var resultData = _assessmentResponses.ToDictionary(a => a.Code, b => b.Response.Value); 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.GIFTS.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 = resultData, TimeToTake = RockDateTime.Now.Subtract(StartDateTime).TotalSeconds }.ToJson(); rockContext.SaveChanges(); ShowResult(result, assessment); } }
/// <summary> /// Save the current record. /// </summary> /// <returns>The Id of the new record, or -1 if the process could not be completed.</returns> private int SaveCurrentEntity() { AssessmentType assessmentType; var rockContext = this.GetDataContext(); var assessmentTypeService = new AssessmentTypeService(rockContext); int assessmentTypeId = int.Parse(hfEntityId.Value); if (assessmentTypeId == 0) { assessmentType = new AssessmentType(); assessmentTypeService.Add(assessmentType); } else { assessmentType = assessmentTypeService.Queryable() .Where(c => c.Id == assessmentTypeId) .FirstOrDefault(); } // Update Basic properties assessmentType.Title = tbTitle.Text; assessmentType.IsActive = cbIsActive.Checked; assessmentType.Description = tbDescription.Text; assessmentType.AssessmentPath = tbAssessmentPath.Text; assessmentType.AssessmentResultsPath = tbResultsPath.Text; assessmentType.RequiresRequest = cbRequiresRequest.Checked; assessmentType.MinimumDaysToRetake = nbDaysBeforeRetake.Text.AsInteger(); if (!assessmentType.IsValid) { // Controls will render the error messages return(-1); } rockContext.SaveChanges(); return(assessmentType.Id); }
/// <summary> /// Delete the entities corresponding to list items that are deleted. /// </summary> /// <param name="dataContext"></param> /// <param name="entityId"></param> /// <returns></returns> private bool OnDeleteEntity(RockContext dataContext, int entityId) { var assessmentTypeService = new AssessmentTypeService(dataContext); var assessmentType = assessmentTypeService.Get(entityId); if (assessmentType == null) { ShowAlert("This item could not be found."); return(false); } string errorMessage; if (!assessmentTypeService.CanDelete(assessmentType, out errorMessage)) { ShowAlert(errorMessage, ModalAlertType.Warning); return(false); } assessmentTypeService.Delete(assessmentType); return(true); }
/// <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.MOTIVATORS.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) { MotivatorService.AssessmentResults savedScores = MotivatorService.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) { MotivatorService.AssessmentResults savedScores = MotivatorService.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} does not have results for 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"); }
/// <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 { MotivatorService.AssessmentResults result = MotivatorService.GetResult(_assessmentResponses.ToDictionary(a => a.Code, b => b.Response.Value)); MotivatorService.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.MOTIVATORS.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 register the script or reload the page. if (_assessmentId == 0) { var removeParams = new List <string> { PageParameterKey.AssessmentId }; NavigateToCurrentPageReferenceWithRemove(removeParams); } else { this.NavigateToCurrentPageReference(); } } }
/// <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); } var 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); }
/// <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.EQ.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) { EQInventoryService.AssessmentResults savedScores = EQInventoryService.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 EQ Inventory 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; } }
/// <summary> /// Bind the data and merges the Lava fields using the template. /// </summary> private void BindData() { lAssessments.Visible = true; // Gets Assessment types and assessments for each RockContext rockContext = new RockContext(); AssessmentTypeService assessmentTypeService = new AssessmentTypeService(rockContext); var allAssessmentsOfEachType = assessmentTypeService.Queryable().AsNoTracking() .Where(x => x.IsActive == true) .Select(t => new AssessmentTypeListItem { Title = t.Title, AssessmentPath = t.AssessmentPath, AssessmentResultsPath = t.AssessmentResultsPath, AssessmentRetakeLinkButton = "", RequiresRequest = t.RequiresRequest, MinDaysToRetake = t.MinimumDaysToRetake, LastRequestObject = t.Assessments .Where(a => a.PersonAlias.Person.Id == CurrentPersonId) .OrderBy(a => a.Status) // pending first .Select(a => new LastAssessmentTaken { RequestedDate = a.RequestedDateTime, CompletedDate = a.CompletedDateTime, Status = a.Status, Requester = a.RequesterPersonAlias.Person.NickName + " " + a.RequesterPersonAlias.Person.LastName }) .OrderBy(x => x.Status) .ThenByDescending(x => x.CompletedDate) .FirstOrDefault(), } ) // order by requested then by pending, completed, then by available to take .OrderByDescending(x => x.LastRequestObject.Status) .ThenBy(x => x.LastRequestObject) .ToList(); // Checks current request types to use against the settings bool areThereAnyPendingRequests = false; bool areThereAnyRequests = false; foreach (var item in allAssessmentsOfEachType.Where(a => a.LastRequestObject != null)) { areThereAnyRequests = true; if (item.LastRequestObject.Status == AssessmentRequestStatus.Pending) { areThereAnyPendingRequests = true; } else if (item.LastRequestObject.Status == AssessmentRequestStatus.Complete) { if (item.LastRequestObject.CompletedDate.HasValue && item.LastRequestObject.CompletedDate.Value.AddDays(item.MinDaysToRetake) <= RockDateTime.Now) { if (IsBlockConfiguredToAllowRetakes(item)) { item.AssessmentRetakeLinkButton = "<a href='" + item.AssessmentPath + "?AssessmentId=0'>Retake Assessment</a>"; } } } } // Decide if anything is going to display bool hideIfNoActiveRequests = GetAttributeValue(AttributeKey.HideIfNoActiveRequests).AsBoolean(); bool hidIfNoRequests = GetAttributeValue(AttributeKey.HideIfNoRequests).AsBoolean(); if ((hideIfNoActiveRequests && !areThereAnyPendingRequests) || (hidIfNoRequests && !areThereAnyRequests)) { lAssessments.Visible = false; } else { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson); // Show only the tests requested or completed?... if (GetAttributeValue(AttributeKey.OnlyShowRequested).AsBoolean()) { // the completed data is only populated if the assessment was actually completed, where as a complete status can be assinged if it was not taken. So use date instead of status for completed. var onlyRequestedOrCompleted = allAssessmentsOfEachType .Where(x => x.LastRequestObject != null) .Where(x => x.LastRequestObject.Requester != null) .Where(x => x.LastRequestObject.Status == AssessmentRequestStatus.Pending || x.LastRequestObject.CompletedDate != null); mergeFields.Add("AssessmentTypes", onlyRequestedOrCompleted); } else { // ...Otherwise show any allowed, requested or completed requests. // the completed data is only populated if the assessment was actually completed, where as a complete status can be assinged if it was not taken. So use date instead of status for completed. var onlyAllowedRequestedOrCompleted = allAssessmentsOfEachType .Where(x => x.RequiresRequest != true || (x.LastRequestObject != null && x.LastRequestObject.Status == AssessmentRequestStatus.Pending) || (x.LastRequestObject != null && x.LastRequestObject.CompletedDate != null) ); mergeFields.Add("AssessmentTypes", onlyAllowedRequestedOrCompleted); } lAssessments.Text = GetAttributeValue(AttributeKey.LavaTemplate).ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands")); } }
/// <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); } } }
/// <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); }
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>"); }
/// <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>"); } } }