Skip to content

Commit

Permalink
Simplified the start survey logic, changed the order to use question.…
Browse files Browse the repository at this point in the history
…aswers_order field, improved the questions import.
  • Loading branch information
Ruslan Baidan committed Dec 14, 2021
1 parent afcd133 commit 6472199
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 72 deletions.
3 changes: 2 additions & 1 deletion data/fit4cybersecurity/context-questions.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"label": "What is your sector?",
"service_category": "Context",
"section": "__context",
"qtype": "SO",
"qtype": "SS",
"maxPoints": 0,
"answers_order": "label",
"answers": [
{
"label": "Banking, insurance and real estate",
Expand Down
3 changes: 2 additions & 1 deletion data/survey4operators/context-questions.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"label": "What is your sector?",
"service_category": "Context",
"section": "__context",
"qtype": "SO",
"qtype": "SS",
"maxPoints": 0,
"answers_order": "label",
"answers": [
{
"label": "Energy",
Expand Down
16 changes: 1 addition & 15 deletions survey/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,6 @@
import json


def sort_tuple_alphabetically(tuple, elementNumber):
tuple.sort(key=lambda x: x[elementNumber])

return tuple


class AnswerMChoice(forms.Form):
unique_answers = forms.CharField(widget=forms.HiddenInput(), required=False)
free_text_answer_id = forms.CharField(widget=forms.HiddenInput(), required=False)
Expand All @@ -37,18 +31,10 @@ def __init__(self, tanswers=None, *args, **kwargs):
elif answers_field_type == "SS":
self.fields["answers"] = forms.ChoiceField(
required=False,
choices=[],
widget=forms.Select(),
label="",
)
elif answers_field_type == "SO":
self.fields["answers"] = forms.ChoiceField(
required=False,
choices=[],
choices=question_answers,
widget=forms.Select(),
label="",
)
tanswers = sort_tuple_alphabetically(tanswers, 1)
elif answers_field_type[0] == "S":
self.fields["answers"] = forms.ChoiceField(
required=True,
Expand Down
1 change: 0 additions & 1 deletion survey/globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@
("M", "Multiple Choice"),
("S", "Single Choice"),
("SS", "Single Select Choice"),
("SO", "Single Select Ordered Choice "),
("T", "Free text"),
("MT", "Multiple Choice + Free Text"),
("ST", "Single Choice + Free Text"),
Expand Down
25 changes: 15 additions & 10 deletions survey/management/commands/import_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,11 @@ def handle(self, *args, **options):
qindex = int(question.get("qindex", 1))
is_context_question = question["section"] == "__context"
if is_context_question:
res = SurveyQuestion.objects.order_by("-qindex").all()
res = SurveyQuestion.objects.order_by("-qindex").filter(
section__label__contains="__context"
)
if self.does_question_exists(question["label"], res):
continue
# if res.count() is 0, qindex is 1
qindex = res[res.count() - 1].qindex - 1 if res.count() else qindex
qindex = -abs(qindex)
Expand All @@ -60,6 +64,7 @@ def handle(self, *args, **options):
service_category=service_cat,
qindex=qindex,
maxPoints=question["maxPoints"],
answers_order=question.get("answers_order", "aindex")
)
if created:
nb_imported_questions += 1
Expand All @@ -68,22 +73,15 @@ def handle(self, *args, **options):
# Create the answers
answers_dependencies = {}
for answer in question["answers"]:
bonus_points = 0
if "bonus_points" in answer.keys():
bonus_points = answer["bonus_points"]
tooltip = ""
if "tooltip" in answer.keys():
tooltip = answer["tooltip"]

answer_obj, created = SurveyQuestionAnswer.objects.get_or_create(
question=question_obj,
label=answer["label"],
aindex=answer["aindex"],
uniqueAnswer=answer["uniqueAnswer"],
score=answer.get("score", 0),
atype=answer["atype"],
bonus_points=bonus_points,
tooltip=tooltip,
bonus_points=int(answer.get("bonus_points", 0)),
tooltip=answer.get("tooltip", ""),
)

if created:
Expand Down Expand Up @@ -128,6 +126,13 @@ def handle(self, *args, **options):
)
)

@staticmethod
def does_question_exists(label: str, questions):
for question in questions:
if question.label == label:
return True
return False

@staticmethod
def process_answers_dependencies(answers_dependencies: Dict):
for answer_label in answers_dependencies:
Expand Down
28 changes: 28 additions & 0 deletions survey/migrations/1008_surveyquestion_answers_order_and_more.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 4.0 on 2021-12-14 15:58

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('survey', '1007_auto_20211209_1203'),
]

operations = [
migrations.AddField(
model_name='surveyquestion',
name='answers_order',
field=models.CharField(default='aindex', max_length=100),
),
migrations.AlterField(
model_name='surveyquestion',
name='qtype',
field=models.CharField(choices=[('M', 'Multiple Choice'), ('S', 'Single Choice'), ('SS', 'Single Select Choice'), ('T', 'Free text'), ('MT', 'Multiple Choice + Free Text'), ('ST', 'Single Choice + Free Text')], default='M', max_length=2),
),
migrations.AlterField(
model_name='surveyquestionanswer',
name='dependant_answers',
field=models.ManyToManyField(blank=True, to='survey.SurveyQuestionAnswer'),
),
]
1 change: 1 addition & 0 deletions survey/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ class SurveyQuestion(models.Model, RightMixin):
)
qindex = models.IntegerField(unique=True)
maxPoints = models.IntegerField(default=10)
answers_order = models.CharField(max_length=100, default="aindex")

@staticmethod
def _fields_base_read():
Expand Down
57 changes: 13 additions & 44 deletions survey/viewLogic.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ def handle_start_survey(request: HttpRequest, lang: str) -> Union[Dict, SurveyUs

for question in questions:
try:
question_answers = SurveyQuestionAnswer.objects.order_by("aindex").filter(
question=question
)
tuple_answers = [(qa["id"], _(qa["label"])) for qa in question_answers.values()]
question_answers = SurveyQuestionAnswer.objects.order_by(
question.answers_order
).filter(question=question)
tuple_answers = get_answer_choices(question_answers, lang)
except Exception as e:
raise e
forms[question.id] = AnswerMChoice(
Expand All @@ -89,46 +89,20 @@ def handle_start_survey(request: HttpRequest, lang: str) -> Union[Dict, SurveyUs
)

if request.method == "POST":
res_forms = {}
for question in questions:
try:
question_answers = SurveyQuestionAnswer.objects.order_by(
"aindex"
).filter(question=question)
tuple_answers = [(qa["id"], _(qa["label"])) for qa in question_answers.values()]
except Exception as e:
raise e

res_forms[question.id] = AnswerMChoice(
tuple_answers,
data=request.POST,
lang=lang,
answers_field_type=question.qtype,
question_answers=question_answers,
prefix="form" + str(question.id),
)

if all([form.is_valid() for question_id, form in res_forms.items()]):
if all([form.is_valid() for question_id, form in forms.items()]):
# create the user
user = create_user(lang)
request.session["user_id"] = str(user.user_id)

for question in questions:
form = res_forms[question.id]
form = forms[question.id]
answers = form.cleaned_data["answers"]
answer_content = ""
if "answer_content" in form.cleaned_data:
answer_content = form.cleaned_data["answer_content"]

try:
question_answers = SurveyQuestionAnswer.objects.order_by(
"aindex"
).filter(question=question)
except Exception as e:
raise e

# create the answers
save_answers(user, question, question_answers, answers, answer_content)
save_answers(user, question, answers, answer_content)

return user

Expand All @@ -153,9 +127,9 @@ def handle_question_answers_request(
) = get_questions_slice(question_index)

try:
question_answers = SurveyQuestionAnswer.objects.order_by("aindex").filter(
question=current_question
)
question_answers = SurveyQuestionAnswer.objects.order_by(
current_question.answers_order
).filter(question=current_question)
tuple_answers = get_answer_choices(question_answers, user.choosen_lang)
except Exception as e:
raise e
Expand All @@ -177,17 +151,13 @@ def handle_question_answers_request(
question_answers=question_answers,
)
if form.is_valid():
user = SurveyUser.objects.select_for_update(nowait=True).filter(id=user.id)[
0
]
user = SurveyUser.objects.select_for_update(nowait=True).filter(id=user.id)[0]
answers = form.cleaned_data["answers"]
answer_content = ""
if "answer_content" in form.cleaned_data:
answer_content = form.cleaned_data["answer_content"]

save_answers(
user, current_question, question_answers, answers, answer_content
)
save_answers(user, current_question, answers, answer_content)

feedback = form.cleaned_data["feedback"]
if feedback:
Expand Down Expand Up @@ -264,12 +234,11 @@ def handle_question_answers_request(
def save_answers(
user: SurveyUser,
current_question: SurveyQuestion,
question_answers: List[SurveyQuestionAnswer],
posted_answers: List[SurveyQuestionAnswer],
answer_content: str,
) -> None:
posted_answers_ids = [int(i) for i in posted_answers]
for question_answer in question_answers:
for question_answer in current_question.surveyquestionanswer_set.all():
user_answers = SurveyUserAnswer.objects.filter(
user=user, answer=question_answer
)[:1]
Expand Down

0 comments on commit 6472199

Please sign in to comment.