Skip to content
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

Main language for evaluations #2367

Open
wants to merge 6 commits into
base: main
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
4 changes: 4 additions & 0 deletions evap/contributor/forms.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime

from django import forms
from django.conf import settings
from django.db.models import Q
from django.forms.widgets import CheckboxSelectMultiple
from django.utils.translation import gettext_lazy as _
Expand All @@ -24,6 +25,7 @@ class Meta:
fields = (
"name_de_field",
"name_en_field",
"main_language",
"vote_start_datetime",
"vote_end_date",
"participants",
Expand All @@ -40,6 +42,8 @@ def __init__(self, *args, **kwargs):
self.fields["name_de_field"].initial = self.instance.full_name_de
self.fields["name_en_field"].initial = self.instance.full_name_en

self.fields["main_language"].choices = settings.LANGUAGES

self.fields["general_questionnaires"].queryset = (
Questionnaire.objects.general_questionnaires()
.filter(Q(visibility=Questionnaire.Visibility.EDITORS) | Q(contributions__evaluation=self.instance))
Expand Down
20 changes: 20 additions & 0 deletions evap/contributor/tests/test_views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import xlrd
from django.conf import settings
from django.core import mail
from django.urls import reverse
from model_bakery import baker
Expand Down Expand Up @@ -292,6 +293,25 @@ def test_display_request_buttons(self):
self.assertEqual(page.body.decode().count("Request changes"), 0)
self.assertEqual(page.body.decode().count("Request creation of new account"), 2)

def test_contributor_evaluation_edit_main_language(self):
self.evaluation.main_language = "en"
self.evaluation.save()

response = self.app.get(self.url, user=self.editor, status=200)
form = response.forms["evaluation-form"]

with self.assertRaises(ValueError):
form["main_language"] = "x"

for lang, __ in settings.LANGUAGES:
form["main_language"] = lang
form.submit(name="operation", value="save")
self.assertEqual(Evaluation.objects.get().main_language, lang)

with self.assertRaises(ValueError):
form["main_language"] = "some_other_wrong_value"
form.submit(name="operation", value="save")
Comment on lines +311 to +313
Copy link
Member

Choose a reason for hiding this comment

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

Like the "Invalid value doesn't work"-block in 303, I think this will already fail on setting the form field as django webtest throws when we try to set a value that is not in the choices list. I think testing that server-side validation works is a good idea here, not sure if it can be done with WebTest form framework though. I think in the past we always manually crafted POST requests to achieve this.



class TestContributorResultsExportView(WebTest):
@classmethod
Expand Down
30 changes: 30 additions & 0 deletions evap/evaluation/migrations/0148_evaluation_main_language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Generated by Django 5.1.3 on 2024-11-25 20:19

from django.db import migrations, models


def _migrate(apps, schema_editor):
Evaluation = apps.get_model("evaluation", "Evaluation")
for evaluation in Evaluation.objects.filter(state__gte=40):
evaluation.main_language = "de"
Copy link
Member

Choose a reason for hiding this comment

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

Why? I would have expected "undecided" (which is the default value -> no explicit migration code needed?)

(If we keep this, can we use some named variable instead of the magic 40?)

evaluation.save()

class Migration(migrations.Migration):

dependencies = [
("evaluation", "0147_unusable_password_default"),
]

operations = [
migrations.AddField(
model_name="evaluation",
name="main_language",
field=models.CharField(
choices=[("en", "English"), ("de", "Deutsch"), ("x", "undecided")],
Copy link
Collaborator

@Kakadus Kakadus Jan 27, 2025

Choose a reason for hiding this comment

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

I want to note that now a new migration is needed when the user changes the languages in the settings. Is it okay that this is still a setting then? I can imagine that this is unexpected from a django setting

If not, then this can probably become a models.TextChoices

default="x",
max_length=2,
verbose_name="main language",
),
),
migrations.RunPython(_migrate),
]
21 changes: 19 additions & 2 deletions evap/evaluation/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,14 @@ class State(models.IntegerChoices):
name_en = models.CharField(max_length=1024, verbose_name=_("name (english)"), blank=True)
name = translate(en="name_en", de="name_de")

# questionaire is shown in this language per default
main_language = models.CharField(
max_length=2,
verbose_name=_("main language"),
default="x",
choices=settings.LANGUAGES + [("x", _("undecided"))],
)

# defines how large the influence of this evaluation's grade is on the total grade of its course
weight = models.PositiveSmallIntegerField(verbose_name=_("weight"), default=1)

Expand Down Expand Up @@ -624,6 +632,10 @@ def is_in_evaluation_period(self):
def general_contribution_has_questionnaires(self):
return self.general_contribution and self.general_contribution.questionnaires.count() > 0

@property
def has_valid_main_language(self):
return self.main_language != "x"

@property
def all_contributions_have_questionnaires(self):
if is_prefetched(self, "contributions"):
Expand Down Expand Up @@ -759,15 +771,20 @@ def can_publish_rating_results(self):
def ready_for_editors(self):
pass

@transition(field=state, source=State.PREPARED, target=State.EDITOR_APPROVED)
@transition(
field=state,
source=State.PREPARED,
target=State.EDITOR_APPROVED,
conditions=[lambda self: self.has_valid_main_language],
)
def editor_approve(self):
pass

@transition(
field=state,
source=[State.NEW, State.PREPARED, State.EDITOR_APPROVED],
target=State.APPROVED,
conditions=[lambda self: self.general_contribution_has_questionnaires],
conditions=[lambda self: self.general_contribution_has_questionnaires and self.has_valid_main_language],
Copy link
Member

Choose a reason for hiding this comment

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

The issue says that staff users should be able to set "undecided". I think this change here would block that workflow?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

In preparation, yes. But at the point of approval (not editor approval!), a language has to be determined.

)
def manager_approve(self):
pass
Expand Down
17 changes: 17 additions & 0 deletions evap/evaluation/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.core.cache import caches
from django.core.exceptions import ValidationError
from django.test import override_settings
from django_fsm import TransitionNotAllowed
from model_bakery import baker

from evap.evaluation.models import (
Expand Down Expand Up @@ -537,6 +538,22 @@ def test_textanswer_review_state(self):
evaluation.TextAnswerReviewState.REVIEWED,
)

def test_approve_without_main_language(self):
evaluation = baker.make(
Evaluation,
)
evaluation.general_contribution.questionnaires.set([baker.make(Questionnaire)])

with self.assertRaises(TransitionNotAllowed):
evaluation.editor_approve()

with self.assertRaises(TransitionNotAllowed):
evaluation.manager_approve()

evaluation.main_language = "en"
evaluation.save()
evaluation.manager_approve()


class TestCourse(TestCase):
def test_can_be_deleted_by_manager(self):
Expand Down
8 changes: 8 additions & 0 deletions evap/staff/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@ class Meta:
"course",
"name_de",
"name_en",
"main_language",
"weight",
"allow_editors_to_edit",
"is_rewarded",
Expand All @@ -384,6 +385,7 @@ class Meta:

def __init__(self, *args, **kwargs):
semester = kwargs.pop("semester", None)
self.operation = kwargs.pop("operation", "save")
super().__init__(*args, **kwargs)
self.fields["course"].queryset = Course.objects.filter(semester=semester)

Expand Down Expand Up @@ -446,6 +448,12 @@ def clean_weight(self):
self.add_error("weight", _("At least one evaluation of the course must have a weight greater than 0."))
return weight

def clean_main_language(self):
main_language = self.cleaned_data.get("main_language")
if self.operation == "approve" and main_language == "x":
self.add_error("main_language", _("You have to set a main language to approve this evaluation."))
return main_language

def clean(self):
super().clean()

Expand Down
45 changes: 45 additions & 0 deletions evap/staff/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1920,6 +1920,38 @@ def test_evaluation_create(self):
form.submit()
self.assertEqual(Evaluation.objects.get().name_de, "lfo9e7bmxp1xi")

def _set_valid_form(self, form):
Copy link
Member

Choose a reason for hiding this comment

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

factoring out the helper is nice -- but we should also use it in test_evaluation_create then :D

form["course"] = self.course.pk
form["name_de"] = "lfo9e7bmxp1xi"
form["name_en"] = "asdf"
form["vote_start_datetime"] = "2014-01-01 00:00:00"
form["vote_end_date"] = "2099-01-01"
form["general_questionnaires"] = [self.q1.pk]
form["wait_for_grade_upload_before_publishing"] = True

form["contributions-TOTAL_FORMS"] = 1
form["contributions-INITIAL_FORMS"] = 0
form["contributions-MAX_NUM_FORMS"] = 5
form["contributions-0-evaluation"] = ""
form["contributions-0-contributor"] = self.manager.pk
form["contributions-0-questionnaires"] = [self.q2.pk]
form["contributions-0-order"] = 0
form["contributions-0-role"] = Contribution.Role.EDITOR
form["contributions-0-textanswer_visibility"] = Contribution.TextAnswerVisibility.GENERAL_TEXTANSWERS

def test_evaluation_create_main_language(self):
response = self.app.get(self.url_for_semester, user=self.manager, status=200)
form = response.forms["evaluation-form"]
self._set_valid_form(form)

with self.assertRaises(ValueError):
form["main_language"] = "some_wrong_value"
form.submit()

form["main_language"] = "x"
form.submit()
self.assertEqual(Evaluation.objects.get().main_language, "x")


class TestEvaluationCopyView(WebTestStaffMode):
@classmethod
Expand Down Expand Up @@ -2349,6 +2381,19 @@ def test_state_change_log_translated(self, trans):
response = self.app.get(self.url, user=self.manager)
self.assertContains(response, "TRANSLATED-state: TRANSLATED-new → TRANSLATED-prepared")

def test_evaluation_confirm_without_main_language(self):
response = self.app.get(self.url, user=self.manager, status=200)
form = response.forms["evaluation-form"]

form["main_language"] = "x"
response = form.submit("operation", value="approve")
self.assertContains(response, "You have to set a main language to approve this evaluation.")

self.assertNotEqual(Evaluation.objects.first().state, self.evaluation.State.APPROVED)

form["main_language"] = "en"
form.submit("operation", value="approve")
Copy link
Member

Choose a reason for hiding this comment

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

We probably have to add an assertion that the response now doesn't contain the above error anymore (our views return 200 even if there is a business logic error / form validation failed)



class TestEvaluationDeleteView(WebTestStaffMode):
csrf_checks = False
Expand Down
14 changes: 8 additions & 6 deletions evap/staff/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1330,17 +1330,19 @@ def notify_reward_points(grantings, **_kwargs):
Evaluation, Contribution, formset=ContributionFormset, form=ContributionForm, extra=1 if editable else 0
)

evaluation_form = EvaluationForm(request.POST or None, instance=evaluation, semester=evaluation.course.semester)
operation = request.POST.get("operation")

if request.method == "POST" and operation not in ("save", "approve"):
raise SuspiciousOperation("Invalid POST operation")

evaluation_form = EvaluationForm(
request.POST or None, instance=evaluation, semester=evaluation.course.semester, operation=operation
Copy link
Member

Choose a reason for hiding this comment

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

random consideration: A narrower, more precise interface would be passing require_main_language: bool instead of passing an operation string that implicitly allows to infer that bool

)
formset = InlineContributionFormset(
request.POST or None, instance=evaluation, form_kwargs={"evaluation": evaluation}
)

operation = request.POST.get("operation")

if evaluation_form.is_valid() and formset.is_valid():
if operation not in ("save", "approve"):
raise SuspiciousOperation("Invalid POST operation")

if not evaluation.can_be_edited_by_manager or evaluation.participations_are_archived:
raise SuspiciousOperation("Modifying this evaluation is not allowed.")

Expand Down
13 changes: 0 additions & 13 deletions evap/static/js/sisyphus.min.js

This file was deleted.

21 changes: 21 additions & 0 deletions evap/static/ts/src/sisyphus.LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) 2011-2013 Alexander Kaupanin https://github.com/simsalabim
Copyright (c) 2024 Jonathan Weth <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Loading
Loading