Skip to content

Conditional question fix for removing questions bug rails7 #3516

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Changelog

- Fix for bug in Conditional questions functionality. In the case of a conditional question with answers that removed questions, any answers of removed questions was not removed. Nor were the removed answers deleted in the database. The Rspec tests were also updated to reflect this change.
- Fix failing eslint workflow / upgrade `actions/checkout` & `actions/setup-node` to v3 [#3503](https://github.com/DMPRoadmap/roadmap/pull/3503)
- Fix rendering of `confirm_merge` partial [#3515](https://github.com/DMPRoadmap/roadmap/pull/3515)
- Remove Auto-Generated TinyMCE Skins and Add `public/tinymce/skins/` to `.gitignore` [#3466](https://github.com/DMPRoadmap/roadmap/pull/3466)
Expand Down
30 changes: 24 additions & 6 deletions app/controllers/answers_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,32 @@ def create_or_update
@section = @plan.sections.find_by(id: @question.section_id)
template = @section.phase.template

remove_list_after = remove_list(@plan)

# Get list of questions to be removed from the plan based on any conditional questions.
questions_remove_list_before_destroying_answers = remove_list(@plan)
all_question_ids = @plan.questions.pluck(:id)
# rubocop pointed out that these variable is not used
# all_answers = @plan.answers

# Destroy all answers for removed questions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like an important PR that fixes a number of lingering bugs. Also, I'm reading the "TODO:" and disabled rubocop offences at the top of this action:

  # POST /answers/create_or_update
  # TODO: Why!? This method is overly complex. Needs a serious refactor!
  #       We should break apart into separate create/update actions to simplify
  #       logic and we should stop using custom JSON here and instead use
  #       `remote: true` in the <form> tag and just send back the ERB.
  #       Consider using ActionCable for the progress bar(s)
  # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
  # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

I share the concerns expressed there and worry about the state of this controller action. It suggests creating separate create and update actions. Now it looks we are destroying answers within def create_or_update as well. I'd like to branch off of this PR and make an attempt at cleaning things up here a bit.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be good if you can simplify.

questions_remove_list_before_destroying_answers.each do |id|
Answer.where(question_id: id, plan: @plan).each do |a|
Answer.destroy(a.id)
end
end
# Now update @plan after removing answers of questions removed from the plan.
@plan = Plan.includes(
sections: {
questions: %i[
answers
question_format
]
}
).find(p_params[:plan_id])

# Now get list of question ids to remove based on remaining answers.
remove_list_question_ids = remove_list(@plan)

qn_data = {
to_show: all_question_ids - remove_list_after,
to_hide: remove_list_after
to_show: all_question_ids - remove_list_question_ids,
to_hide: remove_list_question_ids
}

section_data = []
Expand Down
12 changes: 10 additions & 2 deletions app/helpers/conditions_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,19 @@ def answer_remove_list(answer, user = nil)
id_list = []
return id_list unless answer.question.option_based?

chosen = answer.question_option_ids.sort

answer.question.conditions.each do |cond|
opts = cond.option_list.map(&:to_i).sort
action = cond.action_type
chosen = answer.question_option_ids.sort
if chosen == opts

# If the chosen (options) include the opts (options list) in the condition,
# then we apply the action.
# Currently, the Template edit through the UI only allows an action to be
# added to a single option at a time,
# so the opts array is always length 0 or 1.
# This if checks that all elements in opts are also in chosen.
if !opts.empty? && !chosen.empty? && opts.intersection(chosen) == opts
if action == 'remove'
rems = cond.remove_data.map(&:to_i)
id_list += rems
Expand Down
8 changes: 2 additions & 6 deletions app/javascript/src/answers/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from '../utils/isType';
import { Tinymce } from '../utils/tinymce.js';
import debounce from '../utils/debounce';
import { updateSectionProgress, getQuestionDiv } from '../utils/sectionUpdate';
import { updateSectionProgress, getQuestionDiv , deleteAllAnswersForQuestion } from '../utils/sectionUpdate';
import datePicker from '../utils/datePicker';
import TimeagoFactory from '../utils/timeagoFactory.js.erb';

Expand All @@ -23,6 +23,7 @@ $(() => {
updateSectionProgress(section.sec_id, section.no_ans, section.no_qns);
});
data.qn_data.to_hide.forEach((questionid) => {
deleteAllAnswersForQuestion(questionid);
getQuestionDiv(questionid).slideUp();
});
data.qn_data.to_show.forEach((questionid) => {
Expand Down Expand Up @@ -100,11 +101,6 @@ $(() => {
const form = target.closest('form');
const id = questionId(target);

console.log('SUBMITTING');
console.log(target);
console.log(form);
console.log(id);

if (debounceMap[id]) {
// Cancels the delated execution of autoSaving
// (e.g. user clicks the button before the delay is met)
Expand Down
47 changes: 29 additions & 18 deletions app/javascript/src/utils/sectionUpdate.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
import { Tinymce } from './tinymce.js';

// update details in section progress panel
export const updateSectionProgress = (id, numSecAnswers, numSecQuestions) => {
const progressDiv = $(`#section-panel-${id}`).find('.section-status');
progressDiv.html(`(${numSecAnswers} / ${numSecQuestions})`);

/**
// THIS CODE MAY BE OBSOLETE.
// RETAINING IT TILL SURE.
const heading = progressDiv.closest('.card-heading');
if (numSecQuestions === 0) { // disable section if empty
if (heading.parent().attr('aria-expanded') === 'true') {
heading.parent().trigger('click');
}
heading.addClass('empty-section');
heading.closest('.card').find(`#collapse-${id}`).hide();
heading.closest('.card').find('i.fa-plus, i.fa-minus').removeClass('fa-plus').removeClass('fa-minus');
} else if (heading.hasClass('empty-section')) { // enable section if questions re-added
heading.removeClass('empty-section');
heading.closest('.card').find('i[aria-hidden="true"]').addClass('fa-plus');
heading.closest('.card').find(`#collapse-${id}`).css('display', '');
}
*/
};

// given a question id find the containing div
// used inconditional questions
export const getQuestionDiv = (id) => $(`#answer-form-${id}`).closest('.question-body');

// Clear an answers for a given question id.
export const deleteAllAnswersForQuestion = (questionid) => {
const answerFormDiv = $(`#answer-form-${questionid}`);
const editAnswerForm = $(`#answer-form-${questionid}`).find('.form-answer');

editAnswerForm.find('input:checkbox').prop('checked', false);
editAnswerForm.find('input:radio').prop('checked', false);
editAnswerForm.find('option').prop('selected', false);
editAnswerForm.find('input:text').val('');

// Get the TinyMce editor textarea and rest content to ''
const editorAnswerTextAreaId = `answer-text-${questionid}`;
const tinyMceAnswerEditor = Tinymce.findEditorById(editorAnswerTextAreaId);
if (tinyMceAnswerEditor) {
tinyMceAnswerEditor.setContent('');
}
// Date fields in form are input of type="date"
// The editAnswerForm.find('input:date') throws error, so
// we need an alternate way to reset date.
editAnswerForm.find('#answer_text').each ( (el) => {
if($(el).attr('type') === 'date') {
$(el).val('');
}

});
};
8 changes: 7 additions & 1 deletion app/models/condition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,18 @@ class Condition < ApplicationRecord

# Sort order: Number ASC
default_scope { order(number: :asc) }

# rubocop:disable Metrics/AbcSize
def deep_copy(**options)
copy = dup
copy.question_id = options.fetch(:question_id, nil)
# Added to allow options to be passed in for all fields
copy.option_list = options[:option_list] if options.key?(:option_list)
copy.remove_data = options[:remove_data] if options.key?(:remove_data)
copy.action_type = options[:action_type] if options.key?(:action_type)
copy.webhook_data = options[:webhook_data] if options.key?(:webhook_data)
# TODO: why call validate false here
copy.save!(validate: false) if options.fetch(:save, false)
copy
end
# rubocop:enable Metrics/AbcSize
end
Loading