d4b6682287f66fe65c3fc218661f9e6db92491a4
[edumed.git] / wtem / admin.py
1 # -*- coding: utf-8 -*-
2
3 import os
4
5 from django.contrib import admin
6 from django import forms
7 from django.utils import simplejson
8 from django.utils.safestring import mark_safe
9 from django.core.urlresolvers import reverse
10 from django.conf.urls import url, patterns
11 from django.shortcuts import render
12 from django.contrib.auth.models import User
13 from django.http import HttpResponse
14 from django.template.loader import render_to_string
15 from .models import Submission, Assignment, Attachment, exercises
16 from .middleware import get_current_request
17
18
19 def get_user_exercises(user):
20     try:
21         assignment = Assignment.objects.get(user = user)
22         return [e for e in exercises if e['id'] in assignment.exercises]
23     except Assignment.DoesNotExist:
24         return []
25
26
27 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
28
29 class AttachmentWidget(forms.Widget):
30     def render(self, name, value, *args, **kwargs):
31         if value:
32             a_tag = '<a href="%s">%s</a>' % (value, value)
33         else:
34             a_tag = 'brak'
35         return mark_safe(('<input type="hidden" name="%s" value="%s"/>' % (name, value)) + a_tag)
36
37 class SubmissionFormBase(forms.ModelForm):
38     class Meta:
39         model = Submission
40         exclude = ('answers', 'marks', 'contact', 'end_time') + readonly_fields
41
42
43 def get_open_answer(answers, exercise):
44     def get_option(options, id):
45         for option in options:
46             if option['id'] == int(id):
47                 return option
48
49     exercise_id = str(exercise['id'])
50     answer = answers[exercise_id]
51     if exercise['type'] == 'open':
52         if isinstance(answer, list):
53             toret = ''
54             for part in answer:
55                 field = get_option(exercise['fields'], part['id'])
56                 toret += '- %s:\n\n%s\n\n' % (field['caption'], part['text'])
57         else:
58             toret = answer
59     if exercise['type'] == 'edumed_wybor':
60         ok = set(map(str, exercise['answer'])) == set(map(str,answer['closed_part']))
61         toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
62         if len(answer['closed_part']):
63             for selected in answer['closed_part']:
64                 option = get_option(exercise['options'], selected)
65                 toret += '%s: %s\n' % (selected, option['text'])
66         else:
67             toret += u'<nie wybrano odpowiedzi>\n'
68         toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
69         toret += answer['open_part']
70
71     return toret
72
73
74 def get_form(request, submission):
75     fields = dict()
76     if submission.answers:
77         answers = simplejson.loads(submission.answers)
78         user_exercises = get_user_exercises(request.user)
79         for exercise in exercises:
80             if exercise not in user_exercises:
81                 continue
82             
83             answer_field_name = 'exercise_%s' % exercise['id']
84             mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
85             if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
86                 if exercise['type'] == 'file_upload':
87                     try:
88                         attachment = Attachment.objects.get(submission = submission, exercise_id = exercise['id'])
89                     except Attachment.DoesNotExist:
90                         attachment = None
91                     widget = AttachmentWidget
92                     initial = attachment.file.url if attachment else None
93                 else:
94                     widget = forms.Textarea(attrs={'readonly':True})
95                     initial = get_open_answer(answers, exercise)
96
97                 fields[answer_field_name] = forms.CharField(
98                         widget = widget,
99                         initial = initial,
100                         label = 'Rozwiązanie zadania %s' % exercise['id']
101                 )
102
103                 fields[mark_field_name] = forms.ChoiceField(
104                     choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
105                     initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
106                     label = u'Twoja ocena zadania %s' % exercise['id']
107                 )
108
109     if not request.user.is_superuser:
110         class Meta(SubmissionFormBase.Meta):
111             pass
112         Meta.exclude += ('examiners',)
113         fields['Meta'] = Meta
114
115     return type('SubmissionForm', (SubmissionFormBase,), fields)
116
117
118 class SubmissionAdmin(admin.ModelAdmin):
119     list_display = ('__unicode__', 'todo', 'examiners_repr')
120     readonly_fields = readonly_fields
121
122     def get_form(self, request, obj, **kwargs):
123         return get_form(request, obj)
124     
125     def submitted_by(self, instance):
126         if instance.contact:
127             return '<a href="%s">%s</a>' % (
128                 reverse('admin:contact_contact_change', args = [instance.contact.id]),
129                 instance.contact.contact
130             )
131         return '-'
132     submitted_by.allow_tags = True
133     submitted_by.short_description = "Zgłoszony/a przez"
134
135     def todo(self, submission):
136         user = get_current_request().user
137         user_exercises = get_user_exercises(user)
138         user_marks = submission.marks.get(str(user.id), {})
139         return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
140     todo.short_description = 'Twoje nieocenione zadania'
141
142     def examiners_repr(self, submission):
143         return ', '.join([u.username for u in submission.examiners.all()])
144     examiners_repr.short_description = 'Przypisani do zgłoszenia'
145
146     def save_model(self, request, submission, form, change):
147         for name, value in form.cleaned_data.items():
148             if name.startswith('markof_'):
149                 parts = name.split('_')
150                 exercise_id = parts[1]
151                 user_id = parts[3]
152                 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
153         submission.save()
154
155     def changelist_view(self, request, extra_context=None):
156         context = dict(examiners = [])
157         assignments = Assignment.objects.all()
158         if not request.user.is_superuser:
159             assignments = assignments.filter(user = request.user)
160         for assignment in assignments:
161             examiner = dict(name = assignment.user.username, todo = 0)
162             for submission in Submission.objects.filter(examiners = assignment.user):
163                 for exercise_id in assignment.exercises:
164                     if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None:
165                         examiner['todo'] += 1
166             context['examiners'].append(examiner)
167         return super(SubmissionAdmin, self).changelist_view(request, extra_context = context)
168
169     def queryset(self, request):
170         qs = super(SubmissionAdmin, self).queryset(request)
171         if not request.user.is_superuser:
172             qs = qs.filter(examiners = request.user)
173         return qs
174
175     def get_urls(self):
176         urls = super(SubmissionAdmin, self).get_urls()
177         return patterns('',
178             url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report')
179         ) + super(SubmissionAdmin, self).get_urls()
180
181
182 class SubmissionsSet:
183     def __init__(self, submissions):
184         self.submissions = submissions
185         self.examiners_by_exercise = dict()
186         for submission in submissions:
187             for user_id, marks in submission.marks.items():
188                 user = User.objects.get(pk=user_id)
189                 for exercise_id in marks.keys():
190                     examiners = self.examiners_by_exercise.setdefault(exercise_id, [])
191                     if not user in examiners:
192                         examiners.append(user)
193
194 def report_view(request):
195     submissions = sorted(Submission.objects.all(), key = lambda s: -s.final_result)
196     toret = render_to_string('wtem/admin_report.csv', dict(
197         submissionsSet = SubmissionsSet(submissions),
198         exercise_ids = map(str, range(1,len(exercises)+1))
199     ))
200     response = HttpResponse(toret, content_type = 'text/csv')
201     response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'
202     return response
203
204 admin.site.register(Submission, SubmissionAdmin)
205 admin.site.register(Assignment)