summaryrefslogtreecommitdiffstats
path: root/polynum_blackboard/forms.py
blob: 8b0dab627f442256ca5987ba4bed1e606bfac4d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# -*- coding: utf-8 -*-

from django import forms
from django.utils.translation import ugettext_lazy as _

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, HTML, Field, Fieldset

from polynum.base.models import Entity
from polynum.request import widgets , forms as request_forms

import django_ws
import constant
import models
from . import app_settings

DEFAULT_CATEGORY = ''

def categories():
    '''Retrieve categories from MyCourse. Beware identifiers are the name of
       the categories not their id.
    '''
    yield ('', '---')
    ok, response = django_ws.get_bb_conn().get_categories()
    if ok:
        for category in response.categories:
            yield (category.name, category.name)


class func2iter(object):
    '''Adaptor to transform a generator returning function into an iterator.
       Each iteration() will come from a new generator.
    '''
    def __init__(self, func):
        self.func = func

    def __iter__(self):
        return self.func()


class CreateCourseForm(forms.Form):
    helper = FormHelper()
    helper.form_tag = False
    helper.layout = Layout(
            Div(
                HTML('<div id="id_course_label">&nbsp;</div>'),
                css_class='row-fluid'),
            'entity',
            Div(
                Div(Field('category', css_class="span12"), 
                    css_class="span8"),
                Div('td_group', css_class="span4"),
                css_class="row-fluid"),
            Div(
                Div('subscription_policy', css_class="span6"),
                Div('open_to_visitors', css_class="span6"),
                css_class="row-fluid"),
            Div(Field('password'), css_class="hide"))

    SUBSCRIPTION_POLICIES = (
            ('auto', u'oui'),
            ('password', u'avec mot de passe'),
            ('no', u'non'))
    entity = forms.ModelChoiceField(Entity.objects.all(),
            label=u'Unité d\'enseignement')
    category = forms.ChoiceField(label=u'Catégorie',
            choices=func2iter(categories))
    td_group = forms.CharField(label=u'Groupe de TD', max_length=16,
            required=False)
    open_to_visitors = forms.BooleanField(label=u'Ouvert aux visiteurs',
            required=False)
    subscription_policy = forms.ChoiceField(label=u'Auto-inscription', choices=SUBSCRIPTION_POLICIES,
            help_text=u'Si vous choisissez "Non", notez que vous devrez gérer'
            u' vous-même les inscriptions, avec votre secrétariat.')
    password = forms.CharField(label=u'Mot de passe', max_length=32, required=False)

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        super(CreateCourseForm, self).__init__(*args, **kwargs)
        self.fields['entity'].widget = widgets.MillerColumns(
                attrs={'data-entity-type': app_settings.UE_DESIGNATION})

    def clean(self):
        '''Check that category, subscription_policy and entity are correctly
           chosen. Generate a course_id.
        '''
        cleaned_data = self.cleaned_data
        if not cleaned_data.get('category'):
            cleaned_data['category'] = DEFAULT_CATEGORY
        if cleaned_data['subscription_policy'] == 'password' and not cleaned_data['password']:
            raise forms.ValidationError(u'vous devez fournir un mot de passe')
        if cleaned_data['entity'].entity_type.name != app_settings.UE_DESIGNATION:
            raise forms.ValidationError(u'vous devez sélectionner une UE')
        return cleaned_data

class MyCourseForm(request_forms.CopyrigtsForm):
    visible_to_students = forms.BooleanField(
            label=u'Document visible aux étudiants',
            initial=True)
    ue = forms.ModelChoiceField(Entity.objects.all(),
            label=u'Sinon sélectionnez l\'unité d\'enseignement dans \
laquelle vous souhaitez diffuser votre document')
    course_code = forms.CharField(max_length=128, widget=forms.HiddenInput)
    course_name = forms.CharField(max_length=128, widget=forms.HiddenInput)

    class Meta(request_forms.CopyrigtsForm.Meta):
        fields = ('copyright', 'licence')
        required = ('copyright', 'licence')

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        self.push = push = None
        if instance:
            try:
                self.push = push = models.BlackBoardPush.objects.get(request=instance)
            except models.BlackBoardPush.DoesNotExist:
                pass
        initial = kwargs.setdefault('initial', {})
        initial['ue'] = instance.entity.pk if instance and instance.entity else None
        if push:
            initial['course_name'] = push.course_name
        super(MyCourseForm, self).__init__(*args, **kwargs)
        self.fields['ue'].widget = widgets.MillerColumns(attrs={
            'data-entity-type': app_settings.UE_DESIGNATION
        })
        licence_pks_with_mycourse_tag = []
        for licence in self.fields['licence'].queryset:
            if constant.MYCOURSE_TAG in licence.diffusion_tags:
                licence_pks_with_mycourse_tag.append(licence.pk)
        self.helper.layout = Layout(
            Field('copyright', css_class="span12"),
            Field('licence', css_class="span12"),
            HTML('''
{% if form.course_name.errors %}
<div class="alert-error">
  {{ form.course_name.errors }}
</div>
{% endif %}'''),
            HTML('<script>var licence_pks_with_mycourse_tag = [%s];</script>' %
                    ', '.join(map(str, licence_pks_with_mycourse_tag))),
            Fieldset(u'Diffusion sur la plate-forme MyCourse',
                Div(
                    'visible_to_students',
                    HTML('{% include \'_select_my_course.html\' %}'),
                    HTML('{% include \'_select_sponsor_course.html\' %}'),
                    'ue',
                    'course_name',
                    'course_code',
                    HTML('{% include \'_select_ue_course.html\' %}')),
                    css_id='mycourse-block', css_class='hide'))

    def clean_course_name(self):
        if self.cleaned_data['licence'] and \
            constant.MYCOURSE_TAG in self.cleaned_data['licence'].diffusion_tags and \
            not self.cleaned_data.get('course_name'):
                raise forms.ValidationError(_(u'Vous devez choisir un cours'))
        return self.cleaned_data.get('course_name')

    def save(self, commit=True):
        instance = super(MyCourseForm, self).save(commit=commit)
        if self.cleaned_data['licence'] and \
            constant.MYCOURSE_TAG in self.cleaned_data['licence'].diffusion_tags:
            push, created = models.BlackBoardPush.objects.get_or_create(request=instance)
            push.course_code = self.cleaned_data['course_name']
            push.course_name = self.cleaned_data['course_name']
            push.visible_to_students = self.cleaned_data['visible_to_students']
            push.save()
        else:
            models.BlackBoardPush.objects.filter(request=instance).delete()
        return instance

    def pprint_data(self, data):
        ret = super(MyCourseForm, self).pprint_data(data)
        if self.push and self.push.course_name:
            ret.append((u'Déposer dans le cours', self.push.course_name, False))
            if app_settings.RESUME_MESSAGE:
                ret.append(('', app_settings.RESUME_MESSAGE, False))
        return ret