Project

General

Profile

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

calebasse / calebasse / personnes / forms.py @ 8da5a7b6

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
        if instance.pk:
84
            instance.groups = self.cleaned_data['groups']
85
        if commit:
86
            instance.save()
87
            self.save_m2m()
88
        return instance
89

    
90
class WorkerSearchForm(forms.Form):
91
    last_name = forms.CharField(label=u'Nom', required=False)
92
    first_name = forms.CharField(label=u'Prénom', required=False)
93
    profession = forms.ModelChoiceField(label=u'Profession',
94
            queryset=WorkerType.objects.all(), required=False)
95

    
96
    INTERVENE_STATUS_CHOICES = {
97
            'a': u'Actifs',
98
    }
99

    
100
    intervene_status = forms.MultipleChoiceField(
101
        choices=INTERVENE_STATUS_CHOICES.iteritems(),
102
        widget=forms.CheckboxSelectMultiple,
103
        initial=INTERVENE_STATUS_CHOICES.keys(),
104
        required=False)
105

    
106
class WorkerIdForm(forms.ModelForm):
107
    class Meta:
108
        model = Worker
109
        fields = ('last_name', 'first_name', 'initials', 'gender', 'type', 'enabled')
110
        widgets = {
111
                'initials': forms.TextInput(attrs={'size': 6}),
112
                }
113

    
114
class WorkerServiceForm(forms.ModelForm):
115
    class Meta:
116
        model = Worker
117
        fields = ('services',)
118
        widgets = {
119
                'services': forms.CheckboxSelectMultiple,
120
        }
121

    
122
PERIOD_LIST_TO_FIELDS = [(1, None, None),
123
(2, None, None),
124
(3, None, None),
125
(4, None, None),
126
(5, None, None),
127
(None, 0, None),
128
(None, 1, None),
129
(None, 2, None),
130
(None, 3, None),
131
(None, 4, None),
132
(None, None, 0),
133
(None, None, 1)
134
]
135

    
136
class BaseTimeTableForm(forms.ModelForm):
137
    class Meta:
138
        model = TimeTable
139
        widgets = {
140
                'services': forms.CheckboxSelectMultiple,
141
                'week_period': forms.HiddenInput(),
142
                'week_parity': forms.HiddenInput(),
143
                'week_rank': forms.HiddenInput(),
144
        }
145

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

    
167
TimetableFormSet = inlineformset_factory(Worker, TimeTable,
168
        form=BaseTimeTableForm,
169
        fields=('start_time', 'end_time', 'start_date', 'end_date',
170
            'services', 'periodicity', 'week_period', 'week_parity', 'week_rank'))
171

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

    
182
class HolidayForm(forms.ModelForm):
183

    
184
    def __init__(self, *args, **kwargs):
185
        super(HolidayForm, self).__init__(*args, **kwargs)
186
        self.fields['holiday_type'].queryset = \
187
            HolidayType.objects.filter(for_group=False)
188

    
189
    class Meta:
190
        model = Holiday
191
        widgets = {
192
            'comment': forms.Textarea(attrs = {'rows': 3, 'cols': 18}),
193
            'start_date': forms.DateInput(format = '%d/%m/%Y',
194
                                          attrs = {'size': 10}),
195
            'end_date': forms.DateInput(format = '%d/%m/%Y',
196
                                        attrs = {'size': 10}),
197
            }
198

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

    
206
HolidayFormSet = inlineformset_factory(
207
        Worker, Holiday,
208
        form=BaseHolidayForm,
209
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'holiday_type', 'comment'))
210

    
211
class HolidaySearchForm(forms.Form):
212
    start_date = forms.DateField(required=False, localize=True)
213
    end_date = forms.DateField(required=False, localize=True)
214

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

    
222
class GroupHolidayBaseFormSet(BaseModelFormSet):
223
    def __init__(self, *args, **kwargs):
224
        self.service = kwargs.pop('service', None)
225
        old_form = self.form
226
        self.form = lambda *args, **kwargs: old_form(*args, service=self.service, **kwargs)
227
        super(GroupHolidayBaseFormSet, self).__init__(*args, **kwargs)
228

    
229
class GroupHolidayForm(forms.ModelForm):
230
    for_all_services = forms.BooleanField(required=False, initial=True)
231

    
232
    def __init__(self, *args, **kwargs):
233
        self.service = kwargs.pop('service', None)
234
        super(GroupHolidayForm, self).__init__(*args, **kwargs)
235
        self.fields['service'].choices = ((service.id, service.name) for service in Service.objects.all())
236
        if self.instance and self.instance.id:
237
            self.initial['for_all_services'] = self.instance.service is None
238
        self.fields['holiday_type'].queryset = \
239
                HolidayType.objects.filter(for_group=True)
240

    
241

    
242
    def save(self, commit=True):
243
        instance = super(GroupHolidayForm, self).save(commit=False)
244
        if self.cleaned_data.get('for_all_services', False):
245
            instance.service = None
246
        else:
247
            instance.service = self.service
248
        if commit:
249
            instance.save()
250
        return instance
251

    
252
    class Meta:
253
        model = Holiday
254
        widgets = {
255
            'comment': forms.Textarea(attrs = {'rows': 3, 'cols': 18}),
256
            'service': forms.CheckboxSelectMultiple(attrs = {'class': ''})
257
        }
258

    
259
GroupHolidayFormSet = modelformset_factory(Holiday,
260
        can_delete=True,
261
        form=GroupHolidayForm,
262
        formset=GroupHolidayBaseFormSet,
263
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'holiday_type', 'comment'))
(3-3/8)