Project

General

Profile

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

calebasse / calebasse / personnes / forms.py @ 7d0d13bc

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
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')
64

    
65
    def save(self, commit=True):
66
        instance = super(UserForm, self).save(commit=False)
67
        if self.cleaned_data['password1']:
68
            instance.set_password(self.cleaned_data['password1'])
69
        worker = self.cleaned_data.get('worker')
70
        if worker is not None:
71
            instance.first_name = worker.first_name
72
            instance.last_name = worker.last_name
73
            def save_m2m():
74
                qs = UserWorker.objects.filter(user=instance)
75
                if qs.exists():
76
                    qs.update(worker=worker)
77
                else:
78
                    UserWorker.objects.create(user=instance, worker=worker)
79
            self.save_m2m = save_m2m
80
        if commit:
81
            instance.save()
82
            self.save_m2m()
83
        return instance
84

    
85
class WorkerSearchForm(forms.Form):
86
    last_name = forms.CharField(label=u'Nom', required=False)
87
    first_name = forms.CharField(label=u'Prénom', required=False)
88
    profession = forms.ModelChoiceField(label=u'Profession',
89
            queryset=WorkerType.objects.all(), required=False)
90

    
91
    INTERVENE_STATUS_CHOICES = {
92
            'a': u'Actifs',
93
    }
94

    
95
    intervene_status = forms.MultipleChoiceField(
96
        choices=INTERVENE_STATUS_CHOICES.iteritems(),
97
        widget=forms.CheckboxSelectMultiple,
98
        initial=INTERVENE_STATUS_CHOICES.keys(),
99
        required=False)
100

    
101
class WorkerIdForm(forms.ModelForm):
102
    class Meta:
103
        model = Worker
104
        fields = ('last_name', 'first_name', 'gender', 'type', 'enabled')
105

    
106
class WorkerServiceForm(forms.ModelForm):
107
    class Meta:
108
        model = Worker
109
        fields = ('services',)
110
        widgets = {
111
                'services': forms.CheckboxSelectMultiple,
112
        }
113

    
114
PERIOD_LIST_TO_FIELDS = [(1, None, None),
115
(2, None, None),
116
(3, None, None),
117
(4, None, None),
118
(5, None, None),
119
(None, 0, None),
120
(None, 1, None),
121
(None, 2, None),
122
(None, 3, None),
123
(None, 4, None),
124
(None, None, 0),
125
(None, None, 1)
126
]
127

    
128
class BaseTimeTableForm(forms.ModelForm):
129
    class Meta:
130
        model = TimeTable
131
        widgets = {
132
                'services': forms.CheckboxSelectMultiple,
133
                'week_period': forms.HiddenInput(),
134
                'week_parity': forms.HiddenInput(),
135
                'week_rank': forms.HiddenInput(),
136
        }
137

    
138
    def clean(self):
139
        cleaned_data = super(BaseTimeTableForm, self).clean()
140
        msg = None
141
        if not cleaned_data.get('periodicity'):
142
            msg = u"Périodicité manquante."
143
        else:
144
            try:
145
                periodicity = int(cleaned_data.get('periodicity'))
146
                if periodicity:
147
                    if periodicity < 1 or periodicity > 12:
148
                        msg = u"Périodicité inconnue."
149
                    else:
150
                        cleaned_data['week_period'], \
151
                        cleaned_data['week_rank'], \
152
                        cleaned_data['week_parity'] = PERIOD_LIST_TO_FIELDS[periodicity - 1]
153
            except:
154
                msg = u"Périodicité invalide."
155
        if msg:
156
            self._errors["periodicity"] = self.error_class([msg])
157
        return cleaned_data
158

    
159
TimetableFormSet = inlineformset_factory(Worker, TimeTable,
160
        form=BaseTimeTableForm,
161
        fields=('start_time', 'end_time', 'start_date', 'end_date',
162
            'services', 'periodicity', 'week_period', 'week_parity', 'week_rank'))
163

    
164
class BaseHolidayForm(forms.ModelForm):
165
    def __init__(self, *args, **kwargs):
166
        super(BaseHolidayForm, self).__init__(*args, **kwargs)
167
        self.fields['holiday_type'].queryset = \
168
                HolidayType.objects.filter(for_group=False)
169
    class Meta:
170
        widgets = {
171
                'comment': forms.Textarea(attrs={'rows': 3}),
172
        }
173

    
174
HolidayFormSet = inlineformset_factory(
175
        Worker, Holiday,
176
        form=BaseHolidayForm,
177
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'holiday_type', 'comment'))
178

    
179
class HolidaySearchForm(forms.Form):
180
    start_date = forms.DateField(required=False)
181
    end_date = forms.DateField(required=False)
182

    
183
    def clean(self):
184
        cleaned_data = super(HolidaySearchForm, self).clean()
185
        if cleaned_data.get('start_date') or cleaned_data.get('end_date'):
186
            if not cleaned_data.get('start_date') \
187
                   or not cleaned_data.get('end_date'):
188
                raise forms.ValidationError(u'Vous devez fournir une date de début et de fin')
189
            if cleaned_data['start_date'] > cleaned_data['end_date']:
190
                raise forms.ValidationError(u'La date de début doit être supérieure à la date de fin')
191
        return cleaned_data
192

    
193
class GroupHolidayBaseFormSet(BaseModelFormSet):
194
    def __init__(self, *args, **kwargs):
195
        self.service = kwargs.pop('service', None)
196
        old_form = self.form
197
        self.form = lambda *args, **kwargs: old_form(*args, service=self.service, **kwargs)
198
        super(GroupHolidayBaseFormSet, self).__init__(*args, **kwargs)
199

    
200
class GroupHolidayForm(forms.ModelForm):
201
    for_all_services = forms.BooleanField(required=False, initial=True)
202

    
203
    def __init__(self, *args, **kwargs):
204
        self.service = kwargs.pop('service', None)
205
        super(GroupHolidayForm, self).__init__(*args, **kwargs)
206
        if self.instance and self.instance.id:
207
            self.initial['for_all_services'] = self.instance.service is None
208
        self.fields['holiday_type'].queryset = \
209
                HolidayType.objects.filter(for_group=True)
210

    
211

    
212
    def save(self, commit=True):
213
        instance = super(GroupHolidayForm, self).save(commit=False)
214
        if not self.cleaned_data.get('for_all_services', False):
215
            instance.service = self.service
216
        if commit:
217
            instance.save()
218
        return instance
219

    
220
    class Meta:
221
        form = Holiday
222
        widgets = {
223
                'comment': forms.Textarea(attrs={'rows': 3}),
224
        }
225

    
226
GroupHolidayFormSet = modelformset_factory(Holiday,
227
        can_delete=True,
228
        form=GroupHolidayForm,
229
        formset=GroupHolidayBaseFormSet,
230
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'holiday_type', 'comment'))
(3-3/8)