ADS System
[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 .middleware import get_current_request
14 from .models import Submission, Assignment, Attachment, exercises
15
16
17 def get_user_exercises(user):
18     try:
19         assignment = Assignment.objects.get(user=user)
20         return [e for e in exercises if e['id'] in assignment.exercises]
21     except Assignment.DoesNotExist:
22         return []
23
24
25 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
26
27
28 class AttachmentWidget(forms.Widget):
29     def render(self, name, value, *args, **kwargs):
30         if value:
31             a_tag = '<a href="%s">%s</a>' % (value, value)
32         else:
33             a_tag = 'brak'
34         return mark_safe(('<input type="hidden" name="%s" value="%s"/>' % (name, value)) + a_tag)
35
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
49 class SubmissionFormBase(forms.ModelForm):
50     class Meta:
51         model = Submission
52         exclude = ('answers', 'marks', 'contact', 'end_time') + readonly_fields
53
54
55 def get_open_answer(answers, exercise):
56     def get_option(options, id):
57         for option in options:
58             if str(option['id']) == id:
59                 return option
60
61     exercise_id = str(exercise['id'])
62     answer = answers[exercise_id]
63     if exercise['type'] == 'open':
64         if isinstance(answer, list):
65             toret = ''
66             for part in answer:
67                 field = get_option(exercise['fields'], part['id'])
68                 toret += '- %s:\n\n%s\n\n' % (field['caption'], part['text'])
69         else:
70             toret = answer
71     if exercise['type'] == 'edumed_wybor':
72         ok = set(map(str, exercise['answer'])) == set(map(str, answer['closed_part']))
73         toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
74         if len(answer['closed_part']):
75             for selected in answer['closed_part']:
76                 option = get_option(exercise['options'], selected)
77                 toret += '%s: %s\n' % (selected, option['text'])
78         else:
79             toret += u'<nie wybrano odpowiedzi>\n'
80         toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
81         toret += answer['open_part']
82
83     return toret
84
85
86 def get_form(request, submission):
87     fields = dict()
88     if submission and submission.answers:
89         answers = json.loads(submission.answers)
90         user_exercises = get_user_exercises(request.user)
91         for exercise in exercises:
92             if exercise not in user_exercises:
93                 continue
94             
95             answer_field_name = 'exercise_%s' % exercise['id']
96             mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
97             if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
98                 if exercise['type'] == 'file_upload':
99                     try:
100                         attachment = Attachment.objects.get(submission=submission, exercise_id=exercise['id'])
101                     except Attachment.DoesNotExist:
102                         attachment = None
103                     widget = AttachmentWidget
104                     initial = attachment.file.url if attachment else None
105                 else:
106                     # widget = forms.Textarea(attrs={'readonly':True})
107                     widget = TextareaWithLinks(attrs={'readonly': True})
108                     links = []
109                     qfiles = []
110                     for qfield in exercise.get('fields', []):
111                         if qfield.get('type') == 'file':
112                             qfiles.append((qfield['id'], qfield['caption']))
113                     if qfiles:
114                         eid = int(exercise['id'])
115                         by_tag = {}
116                         for att in Attachment.objects.filter(submission=submission, exercise_id=eid).order_by('tag'):
117                             by_tag[att.tag] = att.file.url
118                         for tag, caption in qfiles:
119                             v = by_tag.get(tag)
120                             if v:
121                                 links.append((caption, "file_%s__%s" % (eid, tag), v))
122                     initial = get_open_answer(answers, exercise), links
123
124                 fields[answer_field_name] = forms.CharField(
125                     widget=widget,
126                     initial=initial,
127                     label=u'Rozwiązanie zadania %s' % exercise['id'],
128                     required=False
129                 )
130
131                 choices = [(None, '-')]  # + [(i,i) for i in range(exercise['max_points']+1)],
132                 i = 0
133                 while i <= exercise['max_points']:
134                     choices.append((i, i))
135                     i += .5
136                 fields[mark_field_name] = forms.ChoiceField(
137                     choices=choices,
138                     initial=submission.get_mark(user_id=request.user.id, exercise_id=exercise['id']),
139                     label=u'Twoja ocena zadania %s' % exercise['id']
140                 )
141
142     if not request.user.is_superuser:
143         class Meta(SubmissionFormBase.Meta):
144             pass
145         Meta.exclude += ('examiners',)
146         fields['Meta'] = Meta
147
148     return type('SubmissionForm', (SubmissionFormBase,), fields)
149
150
151 class SubmissionAdmin(admin.ModelAdmin):
152     list_display = ('__unicode__', 'todo', 'examiners_repr')
153     readonly_fields = readonly_fields
154
155     def get_form(self, request, obj=None, **kwargs):
156         return get_form(request, obj)
157
158     @staticmethod
159     def submitted_by(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     @staticmethod
170     def todo(submission):
171         user = get_current_request().user
172         user_exercises = get_user_exercises(user)
173         user_marks = submission.marks.get(str(user.id), {})
174         return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
175     todo.short_description = 'Twoje nieocenione zadania'
176
177     @staticmethod
178     def examiners_repr(submission):
179         return ', '.join([u.username for u in submission.examiners.all()])
180     examiners_repr.short_description = 'Przypisani do zgłoszenia'
181
182     def save_model(self, request, submission, form, change):
183         for name, value in form.cleaned_data.items():
184             if name.startswith('markof_'):
185                 parts = name.split('_')
186                 exercise_id = parts[1]
187                 user_id = parts[3]
188                 submission.set_mark(user_id=user_id, exercise_id=exercise_id, mark=value)
189         submission.save()
190
191     def changelist_view(self, request, extra_context=None):
192         context = dict(examiners=[])
193         assignments = Assignment.objects.all()
194         if not request.user.is_superuser:
195             assignments = assignments.filter(user=request.user)
196         for assignment in assignments:
197             examiner = dict(name=assignment.user.username, todo=0)
198             for submission in Submission.objects.filter(examiners=assignment.user):
199                 for exercise_id in assignment.exercises:
200                     if submission.get_mark(user_id=assignment.user.id, exercise_id=exercise_id) is None:
201                         examiner['todo'] += 1
202             context['examiners'].append(examiner)
203         return super(SubmissionAdmin, self).changelist_view(request, extra_context=context)
204
205     def queryset(self, request):
206         qs = super(SubmissionAdmin, self).queryset(request)
207         if not request.user.is_superuser:
208             qs = qs.filter(examiners=request.user)
209         return qs
210
211     def get_urls(self):
212         urls = super(SubmissionAdmin, self).get_urls()
213         return patterns(
214             '',
215             url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report')
216         ) + super(SubmissionAdmin, self).get_urls()
217
218
219 class SubmissionsSet:
220     def __init__(self, submissions):
221         self.submissions = submissions
222         self.examiners_by_exercise = {}
223         for submission in submissions:
224             for user_id, marks in submission.marks.items():
225                 user = User.objects.get(pk=user_id)
226                 for exercise_id in marks.keys():
227                     examiners = self.examiners_by_exercise.setdefault(exercise_id, [])
228                     if user not in examiners:
229                         examiners.append(user)
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 admin.site.register(Submission, SubmissionAdmin)
242 admin.site.register(Assignment)