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