-
Notifications
You must be signed in to change notification settings - Fork 146
/
views.py
2534 lines (2063 loc) · 96.7 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import itertools
from collections import OrderedDict, defaultdict, namedtuple
from collections.abc import Container
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from typing import Any, cast
import openpyxl
from django.conf import settings
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.db import IntegrityError, transaction
from django.db.models import (
BooleanField,
Case,
Count,
ExpressionWrapper,
Func,
IntegerField,
OuterRef,
Prefetch,
Q,
Sum,
When,
)
from django.dispatch import receiver
from django.forms import BaseForm, formset_factory
from django.forms.models import inlineformset_factory, modelformset_factory
from django.http import Http404, HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse, reverse_lazy
from django.utils.html import format_html
from django.utils.translation import get_language
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy, ngettext
from django.views.decorators.http import require_POST
from django.views.generic import CreateView, FormView, UpdateView
from evap.contributor.views import export_contributor_results
from evap.evaluation.auth import manager_required, reviewer_required, staff_permission_required
from evap.evaluation.models import (
Answer,
Contribution,
Course,
CourseType,
Degree,
EmailTemplate,
Evaluation,
FaqQuestion,
FaqSection,
Infotext,
Question,
Questionnaire,
RatingAnswerCounter,
Semester,
TextAnswer,
UserProfile,
VoteTimestamp,
)
from evap.evaluation.tools import (
AttachmentResponse,
FormsetView,
HttpResponseNoContent,
SaveValidFormMixin,
StrOrPromise,
get_object_from_dict_pk_entry_or_logged_40x,
get_parameter_from_url_or_session,
sort_formset,
)
from evap.grades.models import GradeDocument
from evap.results.exporters import ResultsExporter
from evap.results.tools import TextResult, calculate_average_distribution, distribution_to_grade
from evap.results.views import update_template_cache_of_published_evaluations_in_course
from evap.rewards.models import RewardPointGranting
from evap.rewards.tools import can_reward_points_be_used_by, is_semester_activated
from evap.staff import staff_mode
from evap.staff.forms import (
AtLeastOneFormset,
ContributionCopyForm,
ContributionCopyFormset,
ContributionForm,
ContributionFormset,
CourseCopyForm,
CourseForm,
CourseTypeForm,
CourseTypeMergeSelectionForm,
DegreeForm,
EvaluationCopyForm,
EvaluationEmailForm,
EvaluationForm,
EvaluationParticipantCopyForm,
ExportSheetForm,
FaqQuestionForm,
FaqSectionForm,
ImportForm,
InfotextForm,
ModelWithImportNamesFormset,
QuestionForm,
QuestionnaireForm,
QuestionnairesAssignForm,
RemindResponsibleForm,
SemesterForm,
SingleResultForm,
TextAnswerForm,
TextAnswerWarningForm,
UserBulkUpdateForm,
UserEditSelectionForm,
UserForm,
UserImportForm,
UserMergeSelectionForm,
)
from evap.staff.importers import (
ImporterLogEntry,
import_enrollments,
import_persons_from_evaluation,
import_persons_from_file,
import_users,
)
from evap.staff.tools import (
ImportType,
bulk_update_users,
delete_import_file,
find_unreviewed_evaluations,
get_import_file_content_or_raise,
import_file_exists,
merge_users,
save_import_file,
)
from evap.student.forms import QuestionnaireVotingForm
from evap.student.models import TextAnswerWarning
from evap.student.views import render_vote_page
@manager_required
def index(request):
template_data = {
"semesters": Semester.objects.all(),
"templates": EmailTemplate.objects.all().order_by("id"),
"sections": FaqSection.objects.all(),
"disable_breadcrumb_manager": True,
}
return render(request, "staff_index.html", template_data)
def annotate_evaluations_with_grade_document_counts(evaluations):
return evaluations.annotate(
midterm_grade_documents_count=Count(
"course__grade_documents",
filter=Q(course__grade_documents__type=GradeDocument.Type.MIDTERM_GRADES),
distinct=True,
),
final_grade_documents_count=Count(
"course__grade_documents",
filter=Q(course__grade_documents__type=GradeDocument.Type.FINAL_GRADES),
distinct=True,
),
)
def get_evaluations_with_prefetched_data(semester):
evaluations = (
semester.evaluations.select_related("course__type")
.prefetch_related(
Prefetch(
"contributions", queryset=Contribution.objects.filter(contributor=None), to_attr="general_contribution"
),
"course__degrees",
"course__responsibles",
"course__semester",
"contributions__questionnaires",
)
.annotate(
num_contributors=Count("contributions", filter=~Q(contributions__contributor=None), distinct=True),
num_textanswers=Count(
"contributions__textanswer_set",
filter=Q(contributions__evaluation__can_publish_text_results=True),
distinct=True,
),
num_reviewed_textanswers=Count(
"contributions__textanswer_set",
filter=~Q(contributions__textanswer_set__review_decision=TextAnswer.ReviewDecision.UNDECIDED),
distinct=True,
),
num_course_evaluations=Count("course__evaluations", distinct=True),
)
).order_by("pk")
evaluations = annotate_evaluations_with_grade_document_counts(evaluations)
return Evaluation.annotate_with_participant_and_voter_counts(evaluations)
@reviewer_required
def semester_view(request, semester_id) -> HttpResponse:
semester = get_object_or_404(Semester, id=semester_id)
if semester.results_are_archived and not request.user.is_manager:
raise PermissionDenied
rewards_active = is_semester_activated(semester)
evaluations = get_evaluations_with_prefetched_data(semester)
evaluations = sorted(evaluations, key=lambda cr: cr.full_name)
courses = Course.objects.filter(semester=semester).prefetch_related(
"type", "degrees", "responsibles", "evaluations"
)
# semester statistics (per degree)
@dataclass
class Stats:
# pylint: disable=too-many-instance-attributes
num_enrollments_in_evaluation: int = 0
num_votes: int = 0
num_evaluations_evaluated: int = 0
num_evaluations: int = 0
num_textanswers: int = 0
num_textanswers_reviewed: int = 0
first_start: datetime = datetime(9999, 1, 1)
last_end: date = date(2000, 1, 1)
degree_stats: dict[Degree, Stats] = defaultdict(Stats)
total_stats = Stats()
for evaluation in evaluations:
if evaluation.is_single_result:
continue
degrees = evaluation.course.degrees.all()
stats_objects = [degree_stats[degree] for degree in degrees]
stats_objects += [total_stats]
for stats in stats_objects:
if evaluation.state >= Evaluation.State.IN_EVALUATION:
stats.num_enrollments_in_evaluation += evaluation.num_participants
stats.num_votes += evaluation.num_voters
stats.num_textanswers += evaluation.num_textanswers
stats.num_textanswers_reviewed += evaluation.num_reviewed_textanswers
if evaluation.state >= Evaluation.State.EVALUATED:
stats.num_evaluations_evaluated += 1
if evaluation.state != Evaluation.State.NEW:
stats.num_evaluations += 1
stats.first_start = min(stats.first_start, evaluation.vote_start_datetime)
stats.last_end = max(stats.last_end, evaluation.vote_end_date)
degree_stats = OrderedDict(sorted(degree_stats.items(), key=lambda x: x[0].order))
degree_stats_with_total = cast(dict[Degree | str, Stats], degree_stats)
degree_stats_with_total["total"] = total_stats
template_data = {
"semester": semester,
"evaluations": evaluations,
"Evaluation": Evaluation,
"disable_breadcrumb_semester": True,
"rewards_active": rewards_active,
"num_evaluations": len(evaluations),
"degree_stats": degree_stats_with_total,
"courses": courses,
"approval_states": [
Evaluation.State.NEW,
Evaluation.State.PREPARED,
Evaluation.State.EDITOR_APPROVED,
Evaluation.State.APPROVED,
],
}
return render(request, "staff_semester_view.html", template_data)
class EvaluationOperation:
email_template_name: str | None = None
email_template_contributor_name: str | None = None
email_template_participant_name: str | None = None
confirmation_message: StrOrPromise | None = None
@staticmethod
def applicable_to(evaluation):
raise NotImplementedError
@staticmethod
def warning_for_inapplicables(amount):
raise NotImplementedError
@staticmethod
def apply(
request, evaluations, email_template=None, email_template_contributor=None, email_template_participant=None
):
raise NotImplementedError
class RevertToNewOperation(EvaluationOperation):
confirmation_message = gettext_lazy("Do you want to revert the following evaluations to preparation?")
@staticmethod
def applicable_to(evaluation):
return Evaluation.State.PREPARED <= evaluation.state <= Evaluation.State.APPROVED
@staticmethod
def warning_for_inapplicables(amount):
return ngettext(
"{} evaluation can not be reverted, because it already started. It was removed from the selection.",
"{} evaluations can not be reverted, because they already started. They were removed from the selection.",
amount,
).format(amount)
@staticmethod
def apply(
request, evaluations, email_template=None, email_template_contributor=None, email_template_participant=None
):
assert email_template_contributor is None
assert email_template_participant is None
for evaluation in evaluations:
evaluation.revert_to_new()
evaluation.save()
messages.success(
request,
ngettext(
"Successfully reverted {} evaluation to in preparation.",
"Successfully reverted {} evaluations to in preparation.",
len(evaluations),
).format(len(evaluations)),
)
class ReadyForEditorsOperation(EvaluationOperation):
email_template_name = EmailTemplate.EDITOR_REVIEW_NOTICE
confirmation_message = gettext_lazy("Do you want to send the following evaluations to editor review?")
@staticmethod
def applicable_to(evaluation):
return evaluation.state in [Evaluation.State.NEW, Evaluation.State.EDITOR_APPROVED]
@staticmethod
def warning_for_inapplicables(amount):
return ngettext(
"{} evaluation can not be reverted, because it already started. It was removed from the selection.",
"{} evaluations can not be reverted, because they already started. They were removed from the selection.",
amount,
).format(amount)
@staticmethod
def apply(
request, evaluations, email_template=None, email_template_contributor=None, email_template_participant=None
):
assert email_template_contributor is None
assert email_template_participant is None
for evaluation in evaluations:
evaluation.ready_for_editors()
evaluation.save()
messages.success(
request,
ngettext(
"Successfully enabled {} evaluation for editor review.",
"Successfully enabled {} evaluations for editor review.",
len(evaluations),
).format(len(evaluations)),
)
if email_template:
evaluations_by_responsible = {}
for evaluation in evaluations:
for responsible in evaluation.course.responsibles.all():
evaluations_by_responsible.setdefault(responsible, []).append(evaluation)
for responsible, responsible_evaluations in evaluations_by_responsible.items():
body_params = {"user": responsible, "evaluations": responsible_evaluations}
editors = UserProfile.objects.filter(
contributions__evaluation__in=responsible_evaluations,
contributions__role=Contribution.Role.EDITOR,
).exclude(pk=responsible.pk)
email_template.send_to_user(
responsible,
subject_params={},
body_params=body_params,
use_cc=True,
additional_cc_users=editors,
request=request,
)
class BeginEvaluationOperation(EvaluationOperation):
email_template_name = EmailTemplate.EVALUATION_STARTED
confirmation_message = gettext_lazy("Do you want to immediately start the following evaluations?")
@staticmethod
def applicable_to(evaluation):
return evaluation.state == Evaluation.State.APPROVED and evaluation.vote_end_date >= date.today()
@staticmethod
def warning_for_inapplicables(amount):
return ngettext(
"{} evaluation can not be started, because it was not approved, was already evaluated or its evaluation end date lies in the past. It was removed from the selection.",
"{} evaluations can not be started, because they were not approved, were already evaluated or their evaluation end dates lie in the past. They were removed from the selection.",
amount,
).format(amount)
@staticmethod
def apply(
request, evaluations, email_template=None, email_template_contributor=None, email_template_participant=None
):
assert email_template_contributor is None
assert email_template_participant is None
for evaluation in evaluations:
evaluation.vote_start_datetime = datetime.now()
evaluation.begin_evaluation()
evaluation.save()
messages.success(
request,
ngettext(
"Successfully started {} evaluation.", "Successfully started {} evaluations.", len(evaluations)
).format(len(evaluations)),
)
if email_template:
email_template.send_to_users_in_evaluations(
evaluations, [EmailTemplate.Recipients.ALL_PARTICIPANTS], use_cc=False, request=request
)
class UnpublishOperation(EvaluationOperation):
confirmation_message = gettext_lazy("Do you want to unpublish the following evaluations?")
@staticmethod
def applicable_to(evaluation):
return evaluation.state == Evaluation.State.PUBLISHED
@staticmethod
def warning_for_inapplicables(amount):
return ngettext(
"{} evaluation can not be unpublished, because it's results have not been published. It was removed from the selection.",
"{} evaluations can not be unpublished because their results have not been published. They were removed from the selection.",
amount,
).format(amount)
@staticmethod
def apply(
request, evaluations, email_template=None, email_template_contributor=None, email_template_participant=None
):
assert email_template_contributor is None
assert email_template_participant is None
for evaluation in evaluations:
evaluation.unpublish()
evaluation.save()
messages.success(
request,
ngettext(
"Successfully unpublished {} evaluation.", "Successfully unpublished {} evaluations.", len(evaluations)
).format(len(evaluations)),
)
class PublishOperation(EvaluationOperation):
email_template_contributor_name = EmailTemplate.PUBLISHING_NOTICE_CONTRIBUTOR
email_template_participant_name = EmailTemplate.PUBLISHING_NOTICE_PARTICIPANT
confirmation_message = gettext_lazy("Do you want to publish the following evaluations?")
@staticmethod
def applicable_to(evaluation):
return evaluation.state == Evaluation.State.REVIEWED
@staticmethod
def warning_for_inapplicables(amount):
return ngettext(
"{} evaluation can not be published, because it's not finished or not all of its text answers have been reviewed. It was removed from the selection.",
"{} evaluations can not be published, because they are not finished or not all of their text answers have been reviewed. They were removed from the selection.",
amount,
).format(amount)
@staticmethod
def apply(
request, evaluations, email_template=None, email_template_contributor=None, email_template_participant=None
):
assert email_template is None
for evaluation in evaluations:
evaluation.publish()
evaluation.save()
messages.success(
request,
ngettext(
"Successfully published {} evaluation.", "Successfully published {} evaluations.", len(evaluations)
).format(len(evaluations)),
)
if email_template_contributor:
EmailTemplate.send_contributor_publish_notifications(evaluations, template=email_template_contributor)
if email_template_participant:
EmailTemplate.send_participant_publish_notifications(evaluations, template=email_template_participant)
EVALUATION_OPERATIONS = {
Evaluation.State.NEW: RevertToNewOperation,
Evaluation.State.PREPARED: ReadyForEditorsOperation,
Evaluation.State.IN_EVALUATION: BeginEvaluationOperation,
Evaluation.State.REVIEWED: UnpublishOperation,
Evaluation.State.PUBLISHED: PublishOperation,
}
def target_state_and_operation_from_str(target_state_str: str) -> tuple[int, type[EvaluationOperation]]:
try:
target_state = int(target_state_str)
except (KeyError, ValueError, TypeError) as err:
raise SuspiciousOperation("Could not parse target_state") from err
if target_state not in EVALUATION_OPERATIONS:
raise SuspiciousOperation(f"Unknown target state: {target_state}")
return target_state, EVALUATION_OPERATIONS[target_state]
@manager_required
def evaluation_operation(request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
if semester.participations_are_archived:
raise PermissionDenied
evaluation_ids = (request.GET if request.method == "GET" else request.POST).getlist("evaluation")
evaluations = list(
annotate_evaluations_with_grade_document_counts(
Evaluation.objects.filter(id__in=evaluation_ids).prefetch_related("course__semester")
)
)
if any(evaluation.course.semester != semester for evaluation in evaluations):
raise SuspiciousOperation
evaluations.sort(key=lambda evaluation: evaluation.full_name)
target_state, operation = target_state_and_operation_from_str(request.GET["target_state"])
if request.method == "POST":
email_template = None
email_template_contributor = None
email_template_participant = None
if request.POST.get("send_email") == "on":
email_template = EmailTemplate(
subject=request.POST["email_subject"],
plain_content=request.POST["email_plain"],
html_content=request.POST["email_html"],
)
if request.POST.get("send_email_contributor") == "on":
email_template_contributor = EmailTemplate(
subject=request.POST["email_subject_contributor"],
plain_content=request.POST["email_plain_contributor"],
html_content=request.POST["email_html_contributor"],
)
if request.POST.get("send_email_participant") == "on":
email_template_participant = EmailTemplate(
subject=request.POST["email_subject_participant"],
plain_content=request.POST["email_plain_participant"],
html_content=request.POST["email_html_participant"],
)
operation.apply(request, evaluations, email_template, email_template_contributor, email_template_participant)
return redirect("staff:semester_view", semester.id)
applicable_evaluations = list(filter(operation.applicable_to, evaluations))
difference = len(evaluations) - len(applicable_evaluations)
if difference:
messages.warning(request, operation.warning_for_inapplicables(difference))
if not applicable_evaluations: # no evaluations where applicable or none were selected
messages.warning(request, _("Please select at least one evaluation."))
return redirect("staff:semester_view", semester.id)
email_template = None
email_template_contributor = None
email_template_participant = None
if operation.email_template_name:
email_template = EmailTemplate.objects.get(name=operation.email_template_name)
if operation.email_template_contributor_name:
email_template_contributor = EmailTemplate.objects.get(name=operation.email_template_contributor_name)
if operation.email_template_participant_name:
email_template_participant = EmailTemplate.objects.get(name=operation.email_template_participant_name)
template_data = {
"semester": semester,
"evaluations": applicable_evaluations,
"target_state": target_state,
"confirmation_message": operation.confirmation_message,
"email_template": email_template,
"email_template_contributor": email_template_contributor,
"email_template_participant": email_template_participant,
"show_email_checkbox": email_template is not None
or email_template_contributor is not None
or email_template_participant is not None,
}
return render(request, "staff_evaluation_operation.html", template_data)
@manager_required
class SemesterCreateView(SuccessMessageMixin, CreateView):
template_name = "staff_semester_form.html"
model = Semester
form_class = SemesterForm
success_message = gettext_lazy("Successfully created semester.")
def get_success_url(self) -> str:
assert self.object is not None
return reverse("staff:semester_view", args=[self.object.id])
@manager_required
class SemesterEditView(SuccessMessageMixin, UpdateView):
template_name = "staff_semester_form.html"
model = Semester
form_class = SemesterForm
pk_url_kwarg = "semester_id"
success_message = gettext_lazy("Successfully updated semester.")
def get_success_url(self) -> str:
return reverse("staff:semester_view", args=[self.object.id])
@require_POST
@manager_required
@transaction.atomic
def semester_make_active(request):
semester = get_object_from_dict_pk_entry_or_logged_40x(Semester, request.POST, "semester_id")
Semester.objects.update(is_active=None)
semester.is_active = True
semester.save()
return HttpResponse()
@require_POST
@manager_required
def semester_delete(request):
semester = get_object_from_dict_pk_entry_or_logged_40x(Semester, request.POST, "semester_id")
if not semester.can_be_deleted_by_manager:
raise SuspiciousOperation("Deleting semester not allowed")
with transaction.atomic():
RatingAnswerCounter.objects.filter(contribution__evaluation__course__semester=semester).delete()
TextAnswer.objects.filter(contribution__evaluation__course__semester=semester).delete()
Contribution.objects.filter(evaluation__course__semester=semester).delete()
Evaluation.objects.filter(course__semester=semester).delete()
Course.objects.filter(semester=semester).delete()
semester.delete()
return redirect("staff:index")
@manager_required
def semester_import(request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
if semester.participations_are_archived:
raise PermissionDenied
excel_form = ImportForm(request.POST or None, request.FILES or None)
import_type = ImportType.SEMESTER
importer_log = None
if request.method == "POST":
operation = request.POST.get("operation")
if operation not in ("test", "import"):
raise SuspiciousOperation("Invalid POST operation")
if operation == "test":
delete_import_file(request.user.id, import_type) # remove old files if still exist
excel_form.fields["excel_file"].required = True
if excel_form.is_valid():
excel_file = excel_form.cleaned_data["excel_file"]
file_content = excel_file.read()
importer_log = import_enrollments(
file_content, semester, vote_start_datetime=None, vote_end_date=None, test_run=True
)
if not importer_log.has_errors():
save_import_file(excel_file, request.user.id, import_type)
elif operation == "import":
file_content = get_import_file_content_or_raise(request.user.id, import_type)
excel_form.fields["vote_start_datetime"].required = True
excel_form.fields["vote_end_date"].required = True
if excel_form.is_valid():
vote_start_datetime = excel_form.cleaned_data["vote_start_datetime"]
vote_end_date = excel_form.cleaned_data["vote_end_date"]
importer_log = import_enrollments(
file_content, semester, vote_start_datetime, vote_end_date, test_run=False
)
importer_log.forward_messages_to_django(request)
delete_import_file(request.user.id, import_type)
return redirect("staff:semester_view", semester_id)
test_passed = import_file_exists(request.user.id, import_type)
# casting warnings to a normal dict is necessary for the template to iterate over it.
return render(
request,
"staff_semester_import.html",
{
"semester": semester,
"importer_log": importer_log,
"excel_form": excel_form,
"test_passed": test_passed,
},
)
@manager_required
def semester_export(request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
ExportSheetFormset = formset_factory(form=ExportSheetForm, can_delete=True, extra=0, min_num=1, validate_min=True)
formset = ExportSheetFormset(request.POST or None, form_kwargs={"semester": semester})
if formset.is_valid():
include_not_enough_voters = request.POST.get("include_not_enough_voters") == "on"
include_unpublished = request.POST.get("include_unpublished") == "on"
selection_list = [
(form.cleaned_data["selected_degrees"], form.cleaned_data["selected_course_types"]) for form in formset
]
filename = f"Evaluation-{semester.name}-{get_language()}.xls"
response = AttachmentResponse(filename, content_type="application/vnd.ms-excel")
ResultsExporter().export(response, [semester], selection_list, include_not_enough_voters, include_unpublished)
return response
return render(request, "staff_semester_export.html", {"semester": semester, "formset": formset})
@manager_required
def semester_raw_export(_request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
filename = f"Evaluation-{semester.name}-{get_language()}_raw.csv"
response = AttachmentResponse(filename, content_type="text/csv")
writer = csv.writer(response, delimiter=";", lineterminator="\n")
writer.writerow(
[
_("Name"),
_("Degrees"),
_("Type"),
_("Single result"),
_("State"),
_("#Voters"),
_("#Participants"),
_("#Text answers"),
_("Average grade"),
]
)
for evaluation in sorted(semester.evaluations.all(), key=lambda cr: cr.full_name):
degrees = ", ".join([degree.name for degree in evaluation.course.degrees.all()])
avg_grade = ""
if evaluation.can_staff_see_average_grade:
distribution = calculate_average_distribution(evaluation)
if distribution is not None:
avg_grade = f"{distribution_to_grade(distribution):.1f}"
writer.writerow(
[
evaluation.full_name,
degrees,
evaluation.course.type.name,
evaluation.is_single_result,
evaluation.state_str,
evaluation.num_voters,
evaluation.num_participants,
evaluation.textanswer_set.count(),
avg_grade,
]
)
return response
@manager_required
def semester_participation_export(_request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
participants = (
UserProfile.objects.filter(evaluations_participating_in__course__semester=semester).distinct().order_by("email")
)
filename = f"Evaluation-{semester.name}-{get_language()}_participation.csv"
response = AttachmentResponse(filename, content_type="text/csv")
writer = csv.writer(response, delimiter=";", lineterminator="\n")
writer.writerow(
[
_("Email"),
_("Can use reward points"),
_("#Required evaluations voted for"),
_("#Required evaluations"),
_("#Optional evaluations voted for"),
_("#Optional evaluations"),
_("Earned reward points"),
]
)
for participant in participants:
number_of_required_evaluations = semester.evaluations.filter(participants=participant, is_rewarded=True).count()
number_of_required_evaluations_voted_for = semester.evaluations.filter(
voters=participant, is_rewarded=True
).count()
number_of_optional_evaluations = semester.evaluations.filter(
participants=participant, is_rewarded=False
).count()
number_of_optional_evaluations_voted_for = semester.evaluations.filter(
voters=participant, is_rewarded=False
).count()
query = RewardPointGranting.objects.filter(semester=semester, user_profile=participant).aggregate(Sum("value"))
earned_reward_points = query["value__sum"] or 0
writer.writerow(
[
participant.email,
can_reward_points_be_used_by(participant),
number_of_required_evaluations_voted_for,
number_of_required_evaluations,
number_of_optional_evaluations_voted_for,
number_of_optional_evaluations,
earned_reward_points,
]
)
return response
@manager_required
def vote_timestamps_export(_request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
timestamps = VoteTimestamp.objects.filter(evaluation__course__semester=semester).prefetch_related(
"evaluation__course__degrees"
)
filename = f"Voting-Timestamps-{semester.name}.csv"
response = AttachmentResponse(filename, content_type="text/csv")
writer = csv.writer(response, delimiter=";", lineterminator="\n")
writer.writerow(
[
_("Evaluation id"),
_("Course type"),
_("Course degrees"),
_("Vote end date"),
_("Timestamp"),
]
)
for timestamp in timestamps:
writer.writerow(
[
timestamp.evaluation.id,
timestamp.evaluation.course.type.name,
", ".join([degree.name for degree in timestamp.evaluation.course.degrees.all()]),
timestamp.evaluation.vote_end_date,
timestamp.timestamp,
]
)
return response
@manager_required
def semester_questionnaire_assign(request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
if semester.participations_are_archived:
raise PermissionDenied
evaluations = semester.evaluations.filter(state=Evaluation.State.NEW)
course_types = CourseType.objects.filter(courses__evaluations__in=evaluations)
form = QuestionnairesAssignForm(request.POST or None, course_types=course_types)
if form.is_valid():
for evaluation in evaluations:
if form.cleaned_data[evaluation.course.type.name]:
evaluation.general_contribution.questionnaires.set(form.cleaned_data[evaluation.course.type.name])
if form.cleaned_data["all-contributors"]:
for contribution in evaluation.contributions.exclude(contributor=None):
contribution.questionnaires.set(form.cleaned_data["all-contributors"])
evaluation.save()
messages.success(request, _("Successfully assigned questionnaires."))
return redirect("staff:semester_view", semester_id)
return render(request, "staff_semester_questionnaire_assign_form.html", {"semester": semester, "form": form})
@manager_required
def semester_preparation_reminder(request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
evaluations = semester.evaluations.filter(
state__in=[Evaluation.State.PREPARED, Evaluation.State.EDITOR_APPROVED]
).prefetch_related("course__degrees")
prepared_evaluations = semester.evaluations.filter(state=Evaluation.State.PREPARED)
responsibles = UserProfile.objects.filter(courses_responsible_for__evaluations__in=prepared_evaluations).distinct()
responsible_list = [
(
responsible,
[evaluation for evaluation in evaluations if responsible in evaluation.course.responsibles.all()],
responsible.delegates.all(),
)
for responsible in responsibles
]
if request.method == "POST":
template = EmailTemplate.objects.get(name=EmailTemplate.EDITOR_REVIEW_REMINDER)
subject_params = {}
for responsible, evaluations, __ in responsible_list:
body_params = {"user": responsible, "evaluations": evaluations}
template.send_to_user(responsible, subject_params, body_params, use_cc=True, request=request)
messages.success(request, _("Successfully sent reminders to everyone."))
return HttpResponse()
template_data = {"semester": semester, "responsible_list": responsible_list}
return render(request, "staff_semester_preparation_reminder.html", template_data)
@manager_required
def semester_grade_reminder(request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
courses = (
semester.courses.filter(
evaluations__state__gte=Evaluation.State.EVALUATED,
evaluations__wait_for_grade_upload_before_publishing=True,
gets_no_grade_documents=False,
)
.distinct()
.prefetch_related("responsibles")
)
courses = [course for course in courses if not course.final_grade_documents.exists()]
courses.sort(key=lambda course: course.name)
responsibles = UserProfile.objects.filter(courses_responsible_for__in=courses).distinct()
responsible_list = [
(responsible, [course for course in courses if responsible in course.responsibles.all()])
for responsible in responsibles
]
template_data = {"semester": semester, "responsible_list": responsible_list}
return render(request, "staff_semester_grade_reminder.html", template_data)
@manager_required
def send_reminder(request, semester_id, responsible_id):
responsible = get_object_or_404(UserProfile, id=responsible_id)
semester = get_object_or_404(Semester, id=semester_id)
form = RemindResponsibleForm(request.POST or None, responsible=responsible)
evaluations = Evaluation.objects.filter(state=Evaluation.State.PREPARED, course__responsibles__in=[responsible])
if form.is_valid():
form.send(request, evaluations)
messages.success(request, _("Successfully sent reminder to {}.").format(responsible.full_name))
return redirect("staff:semester_preparation_reminder", semester_id)
return render(
request, "staff_semester_send_reminder.html", {"semester": semester, "responsible": responsible, "form": form}
)
@require_POST
@manager_required
def semester_archive_participations(request):
semester = get_object_from_dict_pk_entry_or_logged_40x(Semester, request.POST, "semester_id")
if not semester.participations_can_be_archived:
raise SuspiciousOperation("Archiving participations for this semester is not allowed")
semester.archive()
return HttpResponse() # 200 OK
@require_POST
@manager_required
def semester_delete_grade_documents(request):
semester = get_object_from_dict_pk_entry_or_logged_40x(Semester, request.POST, "semester_id")
if not semester.grade_documents_can_be_deleted:
raise SuspiciousOperation("Deleting grade documents for this semester is not allowed")
semester.delete_grade_documents()
return HttpResponse() # 200 OK
@require_POST
@manager_required
def semester_archive_results(request):
semester_id = request.POST.get("semester_id")
semester = get_object_or_404(Semester, id=semester_id)
if not semester.results_can_be_archived:
raise SuspiciousOperation("Archiving results for this semester is not allowed")
semester.archive_results()
return HttpResponse() # 200 OK
@manager_required
def course_create(request, semester_id):
semester = get_object_or_404(Semester, id=semester_id)
if semester.participations_are_archived:
raise PermissionDenied
course = Course(semester=semester)
course_form = CourseForm(request.POST or None, instance=course)
operation = request.POST.get("operation")
if course_form.is_valid():
if operation not in ("save", "save_create_evaluation", "save_create_single_result"):
raise SuspiciousOperation("Invalid POST operation")