efaf253f1e207e7a91b7e1ace29e32f3f2f3cc34
[edumed.git] / wtem / admin.py
1 # -*- coding: utf-8 -*-
2 import json
3
4 from django import forms
5 from django.conf.urls import url, patterns
6 from django.contrib import admin
7 from django.contrib.auth.models import User
8 from django.core.urlresolvers import reverse
9 from django.http import HttpResponse
10 from django.template.loader import render_to_string
11 from django.utils.safestring import mark_safe
12
13 from wtem.models import Confirmation, CompetitionState
14 from .middleware import get_current_request
15 from .models import Submission, Assignment, Attachment, exercises
16
17
18 def get_user_exercises(user):
19     try:
20         assignment = Assignment.objects.get(user=user)
21         return [e for e in exercises if e['id'] in assignment.exercises]
22     except Assignment.DoesNotExist:
23         return []
24
25
26 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
27
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
38 class TextareaWithLinks(forms.Textarea):
39     def render(self, name, value, *args, **kwargs):
40         t, links = value
41         self.links = links
42         output = super(TextareaWithLinks, self).render(name, t, *args, **kwargs)
43         moreoutput = "<div style='margin-left: 106px'>"
44         for k, n, v in links:
45             moreoutput += u"<br>%s: %s" % (k, AttachmentWidget().render(n, v))
46         output += mark_safe(moreoutput + "</div>")
47         return output
48
49
50 class SubmissionFormBase(forms.ModelForm):
51     class Meta:
52         model = Submission
53         exclude = ('answers', 'marks', 'contact', 'end_time') + readonly_fields
54
55
56 def get_open_answer(answers, exercise):
57     def get_option(options, id):
58         for option in options:
59             if str(option['id']) == id:
60                 return option
61
62     exercise_id = str(exercise['id'])
63     answer = answers[exercise_id]
64     if exercise['type'] == 'open':
65         if isinstance(answer, list):
66             toret = ''
67             for part in answer:
68                 field = get_option(exercise['fields'], part['id'])
69                 toret += '- %s:\n\n%s\n\n' % (field['caption'], part['text'])
70         else:
71             toret = answer
72     if exercise['type'] == 'edumed_wybor':
73         ok = set(map(str, exercise['answer'])) == set(map(str, answer['closed_part']))
74         toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
75         if len(answer['closed_part']):
76             for selected in answer['closed_part']:
77                 option = get_option(exercise['options'], selected)
78                 toret += '%s: %s\n' % (selected, option['text'])
79         else:
80             toret += u'<nie wybrano odpowiedzi>\n'
81         toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
82         toret += answer['open_part']
83
84     return toret
85
86
87 def get_form(request, submission):
88     fields = dict()
89     if submission and submission.answers:
90         answers = json.loads(submission.answers)
91         user_exercises = get_user_exercises(request.user)
92         for exercise in exercises:
93             if exercise not in user_exercises:
94                 continue
95             
96             answer_field_name = 'exercise_%s' % exercise['id']
97             mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
98             if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
99                 if exercise['type'] == 'file_upload':
100                     try:
101                         attachment = Attachment.objects.get(submission=submission, exercise_id=exercise['id'])
102                     except Attachment.DoesNotExist:
103                         attachment = None
104                     widget = AttachmentWidget
105                     initial = attachment.file.url if attachment else None
106                 else:
107                     # widget = forms.Textarea(attrs={'readonly':True})
108                     widget = TextareaWithLinks(attrs={'readonly': True})
109                     links = []
110                     qfiles = []
111                     for qfield in exercise.get('fields', []):
112                         if qfield.get('type') == 'file':
113                             qfiles.append((qfield['id'], qfield['caption']))
114                     if qfiles:
115                         eid = int(exercise['id'])
116                         by_tag = {}
117                         for att in Attachment.objects.filter(submission=submission, exercise_id=eid).order_by('tag'):
118                             by_tag[att.tag] = att.file.url
119                         for tag, caption in qfiles:
120                             v = by_tag.get(tag)
121                             if v:
122                                 links.append((caption, "file_%s__%s" % (eid, tag), v))
123                     initial = get_open_answer(answers, exercise), links
124
125                 fields[answer_field_name] = forms.CharField(
126                     widget=widget,
127                     initial=initial,
128                     label=u'Rozwiązanie zadania %s' % exercise['id'],
129                     required=False
130                 )
131
132                 choices = [(None, '-')]  # + [(i,i) for i in range(exercise['max_points']+1)],
133                 i = 0
134                 while i <= exercise['max_points']:
135                     choices.append((i, i))
136                     i += .5
137                 fields[mark_field_name] = forms.ChoiceField(
138                     choices=choices,
139                     initial=submission.get_mark(user_id=request.user.id, exercise_id=exercise['id']),
140                     label=u'Twoja ocena zadania %s' % exercise['id']
141                 )
142
143     if not request.user.is_superuser:
144         class Meta(SubmissionFormBase.Meta):
145             pass
146         Meta.exclude += ('examiners',)
147         fields['Meta'] = Meta
148
149     return type('SubmissionForm', (SubmissionFormBase,), fields)
150
151
152 class SubmissionAdmin(admin.ModelAdmin):
153     list_display = ('__unicode__', 'todo', 'examiners_repr')
154     readonly_fields = readonly_fields
155
156     def get_form(self, request, obj=None, **kwargs):
157         return get_form(request, obj)
158
159     def submitted_by(self, instance):
160         if instance.contact:
161             return '<a href="%s">%s</a>' % (
162                 reverse('admin:contact_contact_change', args=[instance.contact.id]),
163                 instance.contact.contact
164             )
165         return '-'
166     submitted_by.allow_tags = True
167     submitted_by.short_description = "Zgłoszony/a przez"
168
169     def todo(self, submission):
170         user = get_current_request().user
171         user_exercises = get_user_exercises(user)
172         user_marks = submission.marks.get(str(user.id), {})
173         return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
174     todo.short_description = 'Twoje nieocenione zadania'
175
176     def examiners_repr(self, submission):
177         return ', '.join([u.username for u in submission.examiners.all()])
178     examiners_repr.short_description = 'Przypisani do zgłoszenia'
179
180     def save_model(self, request, submission, form, change):
181         for name, value in form.cleaned_data.items():
182             if name.startswith('markof_'):
183                 parts = name.split('_')
184                 exercise_id = parts[1]
185                 user_id = parts[3]
186                 submission.set_mark(user_id=user_id, exercise_id=exercise_id, mark=value)
187         submission.save()
188
189     def changelist_view(self, request, extra_context=None):
190         context = dict(examiners=[])
191         assignments = Assignment.objects.all()
192         if not request.user.is_superuser:
193             assignments = assignments.filter(user=request.user)
194         for assignment in assignments:
195             examiner = dict(name=assignment.user.username, todo=0)
196             for submission in Submission.objects.filter(examiners=assignment.user):
197                 for exercise_id in assignment.exercises:
198                     if submission.get_mark(user_id=assignment.user.id, exercise_id=exercise_id) is None:
199                         examiner['todo'] += 1
200             context['examiners'].append(examiner)
201         return super(SubmissionAdmin, self).changelist_view(request, extra_context=context)
202
203     def queryset(self, request):
204         qs = super(SubmissionAdmin, self).queryset(request)
205         if not request.user.is_superuser:
206             qs = qs.filter(examiners=request.user)
207         return qs
208
209     def get_urls(self):
210         return patterns(
211             '',
212             url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report')
213         ) + super(SubmissionAdmin, self).get_urls()
214
215
216 class SubmissionsSet:
217     def __init__(self, submissions):
218         self.submissions = submissions
219         self.examiners_by_exercise = {}
220         for submission in submissions:
221             for user_id, marks in submission.marks.items():
222                 user = User.objects.get(pk=user_id)
223                 for exercise_id in marks.keys():
224                     examiners = self.examiners_by_exercise.setdefault(exercise_id, [])
225                     if user not in examiners:
226                         examiners.append(user)
227             if submission.contact:
228                 contact_body = submission.contact.body
229                 submission.school = '%s %s' % (contact_body.get('school'), contact_body.get('school_address'))
230
231
232 def report_view(request):
233     submissions = sorted(Submission.objects.all(), key=lambda s: -s.final_result)
234     toret = render_to_string('wtem/admin_report.csv', {
235         'submissionsSet': SubmissionsSet(submissions),
236         'exercise_ids': [str(e['id']) for e in exercises]})
237     response = HttpResponse(toret, content_type='text/csv')
238     response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'
239     return response
240
241
242 class ConfirmationAdmin(admin.ModelAdmin):
243     list_display = ('email', 'first_name', 'last_name', 'readable_contact', 'school_phone', 'readable_age', 'confirmed')
244     readonly_fields = ('contact', 'readable_contact', 'readable_age', 'school_phone', 'key', 'confirmed')
245     list_filter = ('confirmed',)
246     list_select_related = ('contact',)
247
248     def resend_mail(self, request, queryset):
249         for confirmation in queryset:
250             confirmation.send_mail()
251     resend_mail.short_description = "Wyślij kod ponownie"
252
253     actions = [resend_mail]
254
255 admin.site.register(Submission, SubmissionAdmin)
256 admin.site.register(Assignment)
257 admin.site.register(Confirmation, ConfirmationAdmin)
258 admin.site.register(CompetitionState)