disable submit button temporarily after submit
[edumed.git] / stage2 / views.py
index 22eeda4..3f24d38 100644 (file)
@@ -7,11 +7,10 @@ from django.shortcuts import get_object_or_404, render
 from django.utils import timezone
 from django.utils.cache import patch_cache_control
 from django.views.decorators.cache import never_cache
-from django.views.decorators.http import require_POST
 from unidecode import unidecode
 
 from stage2.forms import AttachmentForm, MarkForm, AssignmentFieldForm
-from stage2.models import Participant, Assignment, Answer, Attachment, Mark, FieldOption
+from stage2.models import Participant, Assignment, Answer, Attachment, Mark
 
 
 def all_assignments(participant, sent_forms):
@@ -52,30 +51,10 @@ def participant_view(request, participant_id, key):
         assignment = get_object_or_404(Assignment, id=assignment_id)
         now = timezone.now()
         if assignment.deadline < now:
-            raise Http404  # TODO za późno
-        all_valid = True
-        attachment_forms = []
-        field_forms = []
-        for i, (label, ext) in enumerate(assignment.file_descriptions, 1):
-            answer, created = Answer.objects.get_or_create(participant=participant, assignment=assignment)
-            attachment, created = Attachment.objects.get_or_create(answer=answer, file_no=i)
-            form = AttachmentForm(
-                data=request.POST, files=request.FILES,
-                assignment=assignment, file_no=i, label=label, instance=attachment, extensions=ext)
-            if form.is_valid():
-                form.save()
-            else:
-                all_valid = False
-            attachment_forms.append(form)
-        for i, (label, options) in enumerate(assignment.field_descriptions, 1):
-            answer = Answer.objects.get(participant=participant, assignment=assignment)
-            form = AssignmentFieldForm(data=request.POST, label=label, field_no=i, options=options, answer=answer)
-            if form.is_valid():
-                form.save()
-            else:
-                all_valid = False
-            field_forms.append(form)
-        if all_valid:
+            return HttpResponseForbidden('Not Allowed')
+        attachments_valid, attachment_forms = get_attachment_forms(assignment, participant, request)
+        fields_valid, field_forms = get_field_forms(assignment, participant, request)
+        if attachments_valid and fields_valid:
             return HttpResponseRedirect(reverse('stage2_participant', args=(participant_id, key)))
         else:
             sent_forms = (assignment, field_forms, attachment_forms)
@@ -89,6 +68,37 @@ def participant_view(request, participant_id, key):
     return response
 
 
+def get_attachment_forms(assignment, participant, request):
+    all_valid = True
+    attachment_forms = []
+    for i, (label, ext) in enumerate(assignment.file_descriptions, 1):
+        answer, created = Answer.objects.get_or_create(participant=participant, assignment=assignment)
+        attachment, created = Attachment.objects.get_or_create(answer=answer, file_no=i)
+        form = AttachmentForm(
+            data=request.POST, files=request.FILES,
+            assignment=assignment, file_no=i, label=label, instance=attachment, extensions=ext)
+        if form.is_valid():
+            form.save()
+        else:
+            all_valid = False
+        attachment_forms.append(form)
+    return all_valid, attachment_forms
+
+
+def get_field_forms(assignment, participant, request):
+    all_valid = True
+    field_forms = []
+    for i, (label, options) in enumerate(assignment.field_descriptions, 1):
+        answer = Answer.objects.get(participant=participant, assignment=assignment)
+        form = AssignmentFieldForm(data=request.POST, label=label, field_no=i, options=options, answer=answer)
+        if form.is_valid():
+            form.save()
+        else:
+            all_valid = False
+        field_forms.append(form)
+    return all_valid, field_forms
+
+
 def attachment_download(attachment):
     response = HttpResponse(content_type='application/force-download')
     response.write(attachment.file.read())
@@ -112,14 +122,15 @@ def get_file(request, assignment_id, file_no, participant_id, key):
 
 @login_required
 def assignment_list(request):
-    assignments = request.user.stage2_assignments.all()
+    expert = request.user
+    assignments = expert.stage2_assignments.all()
     if not assignments:
         return HttpResponseForbidden('Not allowed')
     for assignment in assignments:
-        assignment.marked_count = Mark.objects.filter(expert=request.user, answer__assignment=assignment).count()
-        assignment.to_mark_count = assignment.available_answers(request.user).count()
-        assignment.supervisor = request.user in assignment.supervisors.all()
-        assignment.arbiter_count = assignment.answer_set.filter(need_arbiter=True).count()
+        assignment.marked_count = assignment.available_answers(expert, marked=True).count()
+        assignment.to_mark_count = assignment.available_answers(expert).count()
+        assignment.supervisor = expert in assignment.supervisors.all()
+        assignment.arbiter_count = assignment.needing_arbiter().count()
 
     non_empty_assignments = [ass for ass in assignments if ass.marked_count > 0 or ass.to_mark_count > 0]
     if len(non_empty_assignments) == 1 and non_empty_assignments[0].to_mark_count > 0:
@@ -127,48 +138,94 @@ def assignment_list(request):
     return render(request, 'stage2/assignment_list.html', {'assignments': assignments})
 
 
-def available_answers(assignment, expert, answer_with_errors=None, form_with_errors=None, marked=False):
+def available_answers(assignment, expert, sent_forms=None, marked=False):
     if marked:
-        answers = Answer.objects.filter(mark__expert=expert, assignment=assignment)
+        answers = assignment.available_answers(expert, marked=True)
+    else:
+        answers = assignment.available_answers(expert).order_by('participant__last_name')
+    answers = answers.prefetch_related('attachment_set')
+    if sent_forms:
+        sent_answer_id, mark_forms = sent_forms
     else:
-        answers = assignment.available_answers(expert)
-    answers = answers.order_by('participant__last_name').prefetch_related('attachment_set')
+        sent_answer_id = mark_forms = None
     for answer in answers:
         attachments = answer.attachment_set.all()
         attachments_by_file_no = {attachment.file_no: attachment for attachment in attachments}
         answer.attachments = [
             (desc, attachments_by_file_no.get(i))
             for (i, (desc, ext)) in enumerate(assignment.file_descriptions, 1)]
-        if answer == answer_with_errors:
-            answer.form = form_with_errors
+        if answer.id == sent_answer_id:
+            answer.forms = mark_forms
         else:
-            answer.form = MarkForm(
-                answer=answer, instance=answer.mark_set.filter(expert=expert).first(), prefix='ans%s' % answer.id)
+            answer.forms = []
+            for criterion in assignment.markcriterion_set.all():
+                answer.forms.append(MarkForm(
+                    answer=answer,
+                    criterion=criterion,
+                    instance=answer.mark_set.filter(expert=expert, criterion=criterion).first(),
+                    prefix='mark%s-%s' % (answer.id, criterion.id)))
     return answers
 
 
 @login_required
-def answer_list(request, assignment_id):
+def answer_list(request, assignment_id, marked=False):
     assignment = get_object_or_404(Assignment, id=assignment_id)
-    if request.user not in assignment.experts.all():
+    expert = request.user
+    if expert not in assignment.experts.all():
         return HttpResponseForbidden('Not allowed')
-    answers = available_answers(assignment, request.user)
+    if request.POST:
+        # ugly :/
+        answer_id = None
+        for post_key, value in request.POST.iteritems():
+            if post_key.endswith('answer_id'):
+                answer_id = int(value)
+        answer = get_object_or_404(Answer, id=answer_id)
+
+        if answer not in assignment.available_answers(expert, marked=marked):
+            return HttpResponseForbidden('Not allowed')
+        if answer.assignment.is_active():
+            return HttpResponseForbidden('Not allowed')
+        all_valid, forms = get_mark_forms(answer, request)
+        if all_valid:
+            if marked:
+                return HttpResponseRedirect(reverse('stage2_marked_answers', args=[answer.assignment_id]))
+            else:
+                return HttpResponseRedirect(reverse('stage2_answer_list', args=[answer.assignment_id]))
+        else:
+            sent_forms = answer_id, forms
+    else:
+        sent_forms = None
+    answers = available_answers(assignment, expert, sent_forms=sent_forms, marked=marked)
     return render(request, 'stage2/answer_list.html', {
         'answers': answers,
         'assignment': assignment,
+        'field_counts': assignment.field_counts(answers) if not marked else None,
+        'supervisor': expert in assignment.supervisors.all(),
+        'marked': marked
     })
 
 
-@login_required
-def marked_answer_list(request, assignment_id):
-    assignment = get_object_or_404(Assignment, id=assignment_id)
-    if request.user not in assignment.experts.all():
-        return HttpResponseForbidden('Not allowed')
-    return render(request, 'stage2/answer_list.html', {
-        'answers': available_answers(assignment, request.user, marked=True),
-        'assignment': assignment,
-        'marked': True,
-    })
+def get_mark_forms(answer, request):
+    all_valid = True
+    created_marks = []
+    forms = []
+    for criterion in answer.assignment.markcriterion_set.all():
+        mark, created = Mark.objects.get_or_create(
+            answer=answer, criterion=criterion, expert=request.user, defaults={'points': 0})
+        if created:
+            created_marks.append(mark)
+        form = MarkForm(
+            data=request.POST, answer=answer, criterion=criterion, instance=mark,
+            prefix='mark%s-%s' % (answer.id, criterion.id))
+        if form.is_valid():
+            form.save()
+        else:
+            all_valid = False
+        forms.append(form)
+    if not all_valid:
+        for mark in created_marks:
+            mark.delete()
+    return all_valid, forms
 
 
 @login_required
@@ -177,23 +234,8 @@ def expert_download(request, attachment_id):
     return attachment_download(attachment)
 
 
-@require_POST
-@login_required
-def mark_answer(request, answer_id):
-    answer = get_object_or_404(Answer, id=answer_id)
-    if request.user not in answer.assignment.experts.all():
-        return HttpResponseForbidden('Not allowed')
-    if answer.assignment.is_active():
-        return HttpResponseForbidden('Not allowed')
-    mark, created = Mark.objects.get_or_create(answer=answer, expert=request.user, defaults={'points': 0})
-    form = MarkForm(data=request.POST, answer=answer, instance=mark, prefix='ans%s' % answer.id)
-    if form.is_valid():
-        form.save()
-    elif created:
-        mark.delete()
-
-    return HttpResponseRedirect(reverse(
-        'stage2_answer_list' if created else 'stage2_marked_answers', args=[answer.assignment_id]))
+def write_row(row, writer):
+    writer.writerow([unicode(item).encode('utf-8') for item in row])
 
 
 @login_required
@@ -203,7 +245,7 @@ def csv_results(request):
     writer = csv.writer(response)
     assignments = Assignment.objects.all()
     participants = Participant.objects.filter(complete_set=True)
-    headers = [u'imię', u'nazwisko', u'szkoła']
+    headers = [u'imię', u'nazwisko', u'szkoła', u'adres szkoły']
     assignments_experts = []
     for assignment in assignments:
         for expert in assignment.experts.filter(mark__answer__assignment=assignment).distinct():
@@ -212,23 +254,51 @@ def csv_results(request):
     for assignment in assignments:
         headers.append(u'%s - średnia' % assignment.title.encode('utf-8'))
     headers.append(u'ostateczny wynik')
-    writer.writerow([unicode(item).encode('utf-8') for item in headers])
+    write_row(headers, writer)
     for participant in participants:
         row = [
             participant.first_name,
             participant.last_name,
             participant.contact.body['school'],
+            participant.contact.body['school_address'],
         ]
         for assignment, expert in assignments_experts:
-            try:
-                row.append(
-                    Mark.objects.get(
-                        expert=expert, answer__assignment=assignment, answer__participant=participant).points)
-            except Mark.DoesNotExist:
+            marks = expert.mark_set.filter(answer__assignment=assignment, answer__participant=participant)
+            if marks:
+                row.append(sum(mark.points for mark in marks))
+            else:
                 row.append('')
         for assignment in assignments:
             row.append('%.2f' % participant.answer_set.get(assignment=assignment).score())
         row.append('%.2f' % participant.score())
-        writer.writerow([unicode(item).encode('utf-8') for item in row])
+        write_row(row, writer)
     response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'
     return response
+
+
+@login_required
+def csv_details(request, assignment_id):
+    import csv
+    response = HttpResponse(content_type='text/csv')
+    writer = csv.writer(response)
+    assignment = get_object_or_404(Assignment, id=assignment_id)
+    criteria = tuple(assignment.markcriterion_set.all())
+    expert_headers = (u"ekspert",) + criteria
+    headers = (u"imię", u"nazwisko", u"numer", u"wynik") + expert_headers * 2
+    write_row(headers, writer)
+
+    for a in assignment.answer_set.filter(participant__complete_set=True).order_by('participant__last_name'):
+        row = (
+            a.participant.first_name,
+            a.participant.last_name,
+            str(a.participant.id),
+            '%.2f' % a.score(),
+        )
+        experts = a.mark_set.values_list('expert__username', flat=True).order_by().distinct()
+        for expert in experts:
+            row += (expert,)
+            marks = a.mark_set.filter(expert__username=expert).order_by('criterion__order')
+            row += tuple(marks.values_list('points', flat=True))
+        write_row(row, writer)
+    response['Content-Disposition'] = 'attachment; filename="%s.csv"' % assignment.title
+    return response