Project

General

Profile

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

calebasse / calebasse / personnes / forms.py @ 53647eb3

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
    class Meta:
185
        model = Holiday
186
        widgets = {
187
            'comment': forms.Textarea(attrs = {'rows': 3, 'cols': 18}),
188
            'start_date': forms.TextInput(attrs = {'size': 10}),
189
            'end_date': forms.TextInput(attrs = {'size': 10}),
190
            }
191

    
192
    def clean(self):
193
        cleaned_data = super(HolidayForm, self).clean()
194
        if cleaned_data.get('start_date') and cleaned_data.get('end_date'):
195
            if cleaned_data['start_date'] > cleaned_data['end_date']:
196
                raise forms.ValidationError(u'La date de début doit être supérieure à la date de fin')
197
        return cleaned_data
198

    
199
HolidayFormSet = inlineformset_factory(
200
        Worker, Holiday,
201
        form=BaseHolidayForm,
202
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'holiday_type', 'comment'))
203

    
204
class HolidaySearchForm(forms.Form):
205
    start_date = forms.DateField(required=False, localize=True)
206
    end_date = forms.DateField(required=False, localize=True)
207

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

    
215
class GroupHolidayBaseFormSet(BaseModelFormSet):
216
    def __init__(self, *args, **kwargs):
217
        self.service = kwargs.pop('service', None)
218
        old_form = self.form
219
        self.form = lambda *args, **kwargs: old_form(*args, service=self.service, **kwargs)
220
        super(GroupHolidayBaseFormSet, self).__init__(*args, **kwargs)
221

    
222
class GroupHolidayForm(forms.ModelForm):
223
    for_all_services = forms.BooleanField(required=False, initial=True)
224

    
225
    def __init__(self, *args, **kwargs):
226
        self.service = kwargs.pop('service', None)
227
        super(GroupHolidayForm, self).__init__(*args, **kwargs)
228
        if self.instance and self.instance.id:
229
            self.initial['for_all_services'] = self.instance.service is None
230
        self.fields['holiday_type'].queryset = \
231
                HolidayType.objects.filter(for_group=True)
232

    
233

    
234
    def save(self, commit=True):
235
        instance = super(GroupHolidayForm, self).save(commit=False)
236
        if self.cleaned_data.get('for_all_services', False):
237
            instance.service = None
238
        else:
239
            instance.service = self.service
240
        if commit:
241
            instance.save()
242
        return instance
243

    
244
    class Meta:
245
        form = Holiday
246
        widgets = {
247
                'comment': forms.Textarea(attrs={'rows': 3}),
248
        }
249

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