0047e9d8afe5b576e256e6911b583e3cbc908acc
[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"/>' + a_tag) % (name, value))
36
37 class SubmissionFormBase(forms.ModelForm):
38     class Meta:
39         model = Submission
40         exclude = ('answers', 'marks', 'contact') + 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         for selected in answer['closed_part']:
63             option = get_option(exercise['options'], selected)
64             toret += '%s: %s\n' % (selected, option['text'])
65         else:
66             toret += u'<nie wybrano odpowiedzi>\n'
67         toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
68         toret += answer['open_part']
69
70     return toret
71
72
73 def get_form(request, submission):
74     fields = dict()
75     if submission.answers:
76         answers = simplejson.loads(submission.answers)
77         user_exercises = get_user_exercises(request.user)
78         for exercise in exercises:
79             if exercise not in user_exercises:
80                 continue
81             
82             answer_field_name = 'exercise_%s' % exercise['id']
83             mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
84             if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
85                 if exercise['type'] == 'file_upload':
86                     try:
87                         attachment = Attachment.objects.get(submission = submission, exercise_id = exercise['id'])
88                     except Attachment.DoesNotExist:
89                         attachment = None
90                     widget = AttachmentWidget
91                     initial = attachment.file.url if attachment else None
92                 else:
93                     widget = forms.Textarea(attrs={'readonly':True})
94                     initial = get_open_answer(answers, exercise)
95
96                 fields[answer_field_name] = forms.CharField(
97                         widget = widget,
98                         initial = initial,
99                         label = 'Rozwiązanie zadania %s' % exercise['id']
100                 )
101
102                 fields[mark_field_name] = forms.ChoiceField(
103                     choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
104                     initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
105                     label = u'Twoja ocena zadania %s' % exercise['id']
106                 )
107
108     if not request.user.is_superuser:
109         class Meta(SubmissionFormBase.Meta):
110             pass
111         Meta.exclude += ('examiners',)
112         fields['Meta'] = Meta
113
114     return type('SubmissionForm', (SubmissionFormBase,), fields)
115
116
117 class SubmissionAdmin(admin.ModelAdmin):
118     list_display = ('__unicode__', 'todo', 'examiners_repr')
119     readonly_fields = readonly_fields
120
121     def get_form(self, request, obj, **kwargs):
122         return get_form(request, obj)
123     
124     def submitted_by(self, instance):
125         if instance.contact:
126             return '<a href="%s">%s</a>' % (
127                 reverse('admin:contact_contact_change', args = [instance.contact.id]),
128                 instance.contact.contact
129             )
130         return '-'
131     submitted_by.allow_tags = True
132     submitted_by.short_description = "Zgłoszony/a przez"
133
134     def todo(self, submission):
135         user = get_current_request().user
136         user_exercises = get_user_exercises(user)
137         user_marks = submission.marks.get(str(user.id), {})
138         return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
139     todo.short_description = 'Twoje nieocenione zadania'
140
141     def examiners_repr(self, submission):
142         return ', '.join([u.username for u in submission.examiners.all()])
143     examiners_repr.short_description = 'Przypisani do zgłoszenia'
144
145     def save_model(self, request, submission, form, change):
146         for name, value in form.cleaned_data.items():
147             if name.startswith('markof_'):
148                 parts = name.split('_')
149                 exercise_id = parts[1]
150                 user_id = parts[3]
151                 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
152         submission.save()
153
154     def changelist_view(self, request, extra_context=None):
155         context = dict(examiners = [])
156         assignments = Assignment.objects.all()
157         if not request.user.is_superuser:
158             assignments = assignments.filter(user = request.user)
159         for assignment in assignments:
160             examiner = dict(name = assignment.user.username, todo = 0)
161             for submission in Submission.objects.filter(examiners = assignment.user):
162                 for exercise_id in assignment.exercises:
163                     if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None:
164                         examiner['todo'] += 1
165             context['examiners'].append(examiner)
166         return super(SubmissionAdmin, self).changelist_view(request, extra_context = context)
167
168     def queryset(self, request):
169         qs = super(SubmissionAdmin, self).queryset(request)
170         if not request.user.is_superuser:
171             qs = qs.filter(examiners = request.user)
172         return qs
173
174     def get_urls(self):
175         urls = super(SubmissionAdmin, self).get_urls()
176         return patterns('',
177             url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report')
178         ) + super(SubmissionAdmin, self).get_urls()
179
180
181 class SubmissionsSet:
182     def __init__(self, submissions):
183         self.submissions = submissions
184         self.examiners_by_exercise = dict()
185         for submission in submissions:
186             for user_id, marks in submission.marks.items():
187                 user = User.objects.get(pk=user_id)
188                 for exercise_id in marks.keys():
189                     examiners = self.examiners_by_exercise.setdefault(exercise_id, [])
190                     if not user in examiners:
191                         examiners.append(user)
192
193 def report_view(request):
194     submissions = sorted(Submission.objects.all(), key = lambda s: -s.final_result)
195     toret = render_to_string('wtem/admin_report.csv', dict(
196         submissionsSet = SubmissionsSet(submissions),
197         exercise_ids = map(str, range(1,len(exercises)+1))
198     ))
199     response = HttpResponse(toret, content_type = 'text/csv')
200     response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'
201     return response
202
203 admin.site.register(Submission, SubmissionAdmin)
204 admin.site.register(Assignment)