Project

General

Profile

Download (9.31 KB) Statistics
| Branch: | Tag: | Revision:

calebasse / calebasse / personnes / forms.py @ 01e321c7

1
# -*- coding: utf-8 -*-
2
from django import forms
3
from django.forms.models import (inlineformset_factory, modelformset_factory,
4
        BaseInlineFormSet, BaseModelFormSet)
5
from django.utils.translation import gettext_lazy as _
6
from django.contrib.auth.models import User
7

    
8
from calebasse.ressources.models import WorkerType, Service, HolidayType
9

    
10
from models import Worker, UserWorker, TimeTable, Holiday, ExternalTherapist, ExternalWorker
11

    
12

    
13
class UserForm(forms.ModelForm):
14
    error_messages = {
15
        'duplicate_username': _("A user with that username already exists."),
16
        'password_mismatch': _("The two password fields didn't match."),
17
    }
18

    
19
    worker = forms.ModelChoiceField(label=_('Personnel'),
20
            queryset=Worker.objects.filter(enabled=True), empty_label=_('None'),
21
            required=False)
22
    password1 = forms.CharField(label=_("Password"),
23
        widget=forms.PasswordInput, required=False)
24
    password2 = forms.CharField(label=_("Password confirmation"),
25
        widget=forms.PasswordInput,
26
        help_text=_("Enter the same password as above, for verification."),
27
        required=False)
28

    
29
    def __init__(self, service=None, *args, **kwargs):
30
        self.service = service
31
        super(UserForm, self).__init__(*args, **kwargs)
32
        self.fields['worker'].queryset = Worker.objects.for_service(service)
33
        self.fields['username'].label = _('Identifiant')
34
        if self.instance:
35
            try:
36
                worker = self.instance.userworker.worker
37
                self.fields['worker'].initial = worker.pk
38
            except UserWorker.DoesNotExist:
39
                pass
40

    
41
    def clean_username(self):
42
        # Since User.username is unique, this check is redundant,
43
        # but it sets a nicer error message than the ORM. See #13147.
44
        username = self.cleaned_data["username"]
45
        if self.instance is None:
46
            try:
47
                User.objects.get(username=username)
48
                raise forms.ValidationError(self.error_messages['duplicate_username'])
49
            except User.DoesNotExist:
50
                pass
51
        return username
52

    
53
    def clean_password2(self):
54
        password1 = self.cleaned_data.get("password1")
55
        password2 = self.cleaned_data.get("password2")
56
        if password1 and password2 and password1 != password2:
57
            raise forms.ValidationError(
58
                self.error_messages['password_mismatch'])
59
        return password2
60

    
61
    class Meta:
62
        model = User
63
        fields = ('username', 'email', 'password1', 'password2', 'worker', 'groups')
64
        widgets = {
65
                'groups': forms.CheckboxSelectMultiple,
66
        }
67

    
68
    def save(self, commit=True):
69
        instance = super(UserForm, self).save(commit=False)
70
        if self.cleaned_data['password1']:
71
            instance.set_password(self.cleaned_data['password1'])
72
        worker = self.cleaned_data.get('worker')
73
        if worker is not None:
74
            instance.first_name = worker.first_name
75
            instance.last_name = worker.last_name
76
            def save_m2m():
77
                qs = UserWorker.objects.filter(user=instance)
78
                if qs.exists():
79
                    qs.update(worker=worker)
80
                else:
81
                    UserWorker.objects.create(user=instance, worker=worker)
82
            self.save_m2m = save_m2m
83
        else:
84
            try:
85
                instance.userworker.delete()
86
            except UserWorker.DoesNotExist:
87
                pass
88
        if instance.pk:
89
            instance.groups = self.cleaned_data['groups']
90
        if commit:
91
            instance.save()
92
            self.save_m2m()
93
        return instance
94

    
95
class WorkerSearchForm(forms.Form):
96
    last_name = forms.CharField(label=u'Nom', required=False)
97
    first_name = forms.CharField(label=u'Prénom', required=False)
98
    profession = forms.ModelChoiceField(label=u'Profession',
99
            queryset=WorkerType.objects.all(), required=False)
100

    
101
    INTERVENE_STATUS_CHOICES = {
102
            'a': u'Actifs',
103
    }
104

    
105
    intervene_status = forms.MultipleChoiceField(
106
        choices=INTERVENE_STATUS_CHOICES.iteritems(),
107
        widget=forms.CheckboxSelectMultiple,
108
        initial=INTERVENE_STATUS_CHOICES.keys(),
109
        required=False)
110

    
111
class WorkerIdForm(forms.ModelForm):
112
    class Meta:
113
        model = Worker
114
        fields = ('last_name', 'first_name', 'initials', 'gender', 'type', 'enabled')
115
        widgets = {
116
                'initials': forms.TextInput(attrs={'size': 6}),
117
                }
118

    
119
class WorkerServiceForm(forms.ModelForm):
120
    class Meta:
121
        model = Worker
122
        fields = ('services',)
123
        widgets = {
124
                'services': forms.CheckboxSelectMultiple,
125
        }
126

    
127
PERIOD_LIST_TO_FIELDS = [(1, None, None),
128
(2, None, None),
129
(3, None, None),
130
(4, None, None),
131
(5, None, None),
132
(None, 0, None),
133
(None, 1, None),
134
(None, 2, None),
135
(None, 3, None),
136
(None, 4, None),
137
(None, None, 0),
138
(None, None, 1)
139
]
140

    
141
class BaseTimeTableForm(forms.ModelForm):
142
    class Meta:
143
        model = TimeTable
144
        widgets = {
145
                'services': forms.CheckboxSelectMultiple,
146
                'week_period': forms.HiddenInput(),
147
                'week_parity': forms.HiddenInput(),
148
                'week_rank': forms.HiddenInput(),
149
        }
150

    
151
    def clean(self):
152
        cleaned_data = super(BaseTimeTableForm, self).clean()
153
        msg = None
154
        if not cleaned_data.get('periodicity'):
155
            msg = u"Périodicité manquante."
156
        else:
157
            try:
158
                periodicity = int(cleaned_data.get('periodicity'))
159
                if periodicity:
160
                    if periodicity < 1 or periodicity > 12:
161
                        msg = u"Périodicité inconnue."
162
                    else:
163
                        cleaned_data['week_period'], \
164
                        cleaned_data['week_rank'], \
165
                        cleaned_data['week_parity'] = PERIOD_LIST_TO_FIELDS[periodicity - 1]
166
            except:
167
                msg = u"Périodicité invalide."
168
        if msg:
169
            self._errors["periodicity"] = self.error_class([msg])
170
        return cleaned_data
171

    
172
TimetableFormSet = inlineformset_factory(Worker, TimeTable,
173
        form=BaseTimeTableForm,
174
        fields=('start_time', 'end_time', 'start_date', 'end_date',
175
            'services', 'periodicity', 'week_period', 'week_parity', 'week_rank'))
176

    
177
class BaseHolidayForm(forms.ModelForm):
178
    def __init__(self, *args, **kwargs):
179
        super(BaseHolidayForm, self).__init__(*args, **kwargs)
180
        self.fields['holiday_type'].queryset = \
181
                HolidayType.objects.filter(for_group=False)
182
    class Meta:
183
        widgets = {
184
                'comment': forms.Textarea(attrs={'rows': 3}),
185
        }
186

    
187
class HolidayForm(forms.ModelForm):
188

    
189
    def __init__(self, *args, **kwargs):
190
        super(HolidayForm, self).__init__(*args, **kwargs)
191
        self.fields['holiday_type'].queryset = \
192
            HolidayType.objects.filter(for_group=False)
193

    
194
    class Meta:
195
        model = Holiday
196
        widgets = {
197
            'comment': forms.Textarea(attrs = {'rows': 3, 'cols': 18}),
198
            'start_date': forms.DateInput(format = '%d/%m/%Y',
199
                                          attrs = {'size': 10}),
200
            'end_date': forms.DateInput(format = '%d/%m/%Y',
201
                                        attrs = {'size': 10}),
202
            }
203

    
204
    def clean(self):
205
        cleaned_data = super(HolidayForm, self).clean()
206
        if cleaned_data.get('start_date') and cleaned_data.get('end_date'):
207
            if cleaned_data['start_date'] > cleaned_data['end_date']:
208
                raise forms.ValidationError(u'La date de début doit être supérieure à la date de fin')
209
        return cleaned_data
210

    
211
HolidayFormSet = inlineformset_factory(
212
        Worker, Holiday,
213
        form=BaseHolidayForm,
214
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'holiday_type', 'comment'))
215

    
216
class HolidaySearchForm(forms.Form):
217
    start_date = forms.DateField(required=False, localize=True)
218
    end_date = forms.DateField(required=False, localize=True)
219

    
220
    def clean(self):
221
        cleaned_data = super(HolidaySearchForm, self).clean()
222
        if cleaned_data.get('start_date') and cleaned_data.get('end_date'):
223
            if cleaned_data['start_date'] > cleaned_data['end_date']:
224
                raise forms.ValidationError(u'La date de début doit être supérieure à la date de fin')
225
        return cleaned_data
226

    
227
class GroupHolidayBaseFormSet(BaseModelFormSet):
228
    def __init__(self, *args, **kwargs):
229
        self.service = kwargs.pop('service', None)
230
        old_form = self.form
231
        self.form = lambda *args, **kwargs: old_form(*args, service=self.service, **kwargs)
232
        super(GroupHolidayBaseFormSet, self).__init__(*args, **kwargs)
233

    
234
class GroupHolidayForm(forms.ModelForm):
235

    
236
    def __init__(self, *args, **kwargs):
237
        self.service = kwargs.pop('service', None)
238
        super(GroupHolidayForm, self).__init__(*args, **kwargs)
239
        self.fields['holiday_type'].queryset = \
240
                HolidayType.objects.filter(for_group=True)
241

    
242
    class Meta:
243
        model = Holiday
244
        widgets = {
245
            'comment': forms.Textarea(attrs = {'rows': 3, 'cols': 18}),
246
            'services': forms.CheckboxSelectMultiple()
247
        }
248

    
249
GroupHolidayFormSet = modelformset_factory(Holiday,
250
        can_delete=True,
251
        form=GroupHolidayForm,
252
        formset=GroupHolidayBaseFormSet,
253
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'holiday_type', 'comment'))
(3-3/8)