Project

General

Profile

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

calebasse / calebasse / agenda / forms.py @ abb68dff

1
# -*- coding: utf-8 -*-
2

    
3
from datetime import datetime, timedelta
4

    
5
from django import forms
6

    
7
from ..dossiers.models import PatientRecord
8
from ..personnes.models import Worker
9
from ..ressources.models import ActType
10
from ..middleware.request import get_request
11

    
12
from ajax_select import make_ajax_field
13
from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField
14
from models import Event, EventWithAct, EventType
15

    
16
class BaseForm(forms.ModelForm):
17
    date = forms.DateField(label=u'Date', localize=True)
18
    time = forms.TimeField(label=u'Heure de début')
19
    duration = forms.CharField(label=u'Durée',
20
            help_text=u'en minutes; vous pouvez utiliser la roulette de votre souris.')
21
    participants = make_ajax_field(EventWithAct, 'participants', 'worker-or-group', True)
22

    
23

    
24
class NewAppointmentForm(BaseForm):
25
    patient = AutoCompleteSelectMultipleField('patientrecord')
26

    
27
    class Meta:
28
        model = EventWithAct
29
        fields = (
30
                'start_datetime',
31
                'date',
32
                'time',
33
                'duration',
34
                'patient',
35
                'participants',
36
                'ressource',
37
                'act_type',
38
                'description',
39
                'recurrence_periodicity',
40
                'recurrence_end_date'
41
        )
42
        widgets = {
43
                'start_datetime': forms.HiddenInput,
44
        }
45

    
46

    
47

    
48
    def __init__(self, instance, service=None, **kwargs):
49
        self.service = None
50
        super(NewAppointmentForm, self).__init__(instance=instance, **kwargs)
51
        self.fields['date'].css = 'datepicker'
52
        self.fields['participants'].required = True
53
        if service:
54
            self.service = service
55
            self.fields['participants'].queryset = \
56
                    Worker.objects.for_service(service)
57
            self.fields['patient'].queryset = \
58
                    PatientRecord.objects.for_service(service)
59
            self.fields['act_type'].queryset = \
60
                    ActType.objects.for_service(service) \
61
                    .order_by('name')
62

    
63
    def clean_duration(self):
64
        duration = self.cleaned_data['duration']
65
        try:
66
            return int(duration)
67
        except ValueError:
68
            return 0
69

    
70
    def clean_patient(self):
71
        patients = self.cleaned_data['patient']
72
        if patients:
73
            return [patient for patient in PatientRecord.objects.filter(pk__in=patients)]
74

    
75
    def clean(self):
76
        cleaned_data = super(NewAppointmentForm, self).clean()
77
        if not cleaned_data.get('recurrence_periodicity'):
78
            cleaned_data['recurrence_end_date'] = None
79
        if cleaned_data.has_key('date') and cleaned_data.has_key('time'):
80
            cleaned_data['start_datetime'] = datetime.combine(cleaned_data['date'],
81
                    cleaned_data['time'])
82
        if 'patient' in cleaned_data and isinstance(cleaned_data['patient'], list):
83
            # nasty trick to store the list of patients and pass the form
84
            # validation
85
            cleaned_data['patients'] = cleaned_data['patient']
86
            cleaned_data['patient'] = cleaned_data['patient'][0]
87
        return cleaned_data
88

    
89
    def save(self, commit=True):
90

    
91
        patients = self.cleaned_data.pop('patients')
92
        for patient in patients:
93
            appointment = forms.save_instance(self, self._meta.model(), commit=False)
94
            appointment.start_datetime = datetime.combine(self.cleaned_data['date'],
95
                                                          self.cleaned_data['time'])
96
            appointment.end_datetime = appointment.start_datetime + timedelta(
97
                minutes=self.cleaned_data['duration'])
98
            appointment.creator = get_request().user
99
            appointment.clean()
100
            if commit:
101
                appointment.patient = patient
102
                appointment.save()
103
                self.save_m2m()
104
                appointment.services = [self.service]
105

    
106
class UpdateAppointmentForm(NewAppointmentForm):
107

    
108
    patient = make_ajax_field(EventWithAct, 'patient', 'patientrecord', False)
109

    
110
    class Meta(NewAppointmentForm.Meta):
111
        fields = (
112
                'start_datetime',
113
                'date',
114
                'time',
115
                'duration',
116
                'patient',
117
                'participants',
118
                'ressource',
119
                'act_type',
120
        )
121

    
122
    def clean_patient(self):
123
        return self.cleaned_data['patient']
124

    
125
    def save(self, commit=True):
126
        appointment = super(NewAppointmentForm, self).save(commit=False)
127
        appointment.start_datetime = datetime.combine(self.cleaned_data['date'],
128
                    self.cleaned_data['time'])
129
        appointment.end_datetime = appointment.start_datetime + timedelta(
130
                minutes=self.cleaned_data['duration'])
131
        appointment.creator = get_request().user
132
        appointment.clean()
133
        if commit:
134
            appointment.save()
135
            appointment.services = [self.service]
136
        return appointment
137

    
138

    
139
class UpdatePeriodicAppointmentForm(UpdateAppointmentForm):
140
    patient = make_ajax_field(EventWithAct, 'patient', 'patientrecord', False)
141
    recurrence_periodicity = forms.ChoiceField(label=u"Périodicité",
142
            choices=Event.PERIODICITIES, required=True)
143

    
144
    def clean(self):
145
        cleaned_data = super(UpdatePeriodicAppointmentForm, self).clean()
146
        acts = self.instance.act_set.filter(is_billed=True).order_by('-date')
147
        if acts and cleaned_data.get('recurrence_end_date'):
148
            recurrence_end_date = cleaned_data['recurrence_end_date']
149
            if recurrence_end_date < acts[0].date:
150
                self._errors['recurrence_end_date'] = self.error_class([
151
                            u"La date doit être supérieur au dernier acte facturé de la récurrence"])
152
        return cleaned_data
153

    
154
class DisablePatientAppointmentForm(UpdateAppointmentForm):
155

    
156
    def __init__(self, instance, service=None, **kwargs):
157
        super(DisablePatientAppointmentForm, self).__init__(instance,
158
                service, **kwargs)
159
        if instance and instance.pk:
160
            self.fields['patient'].required = False
161
            self.fields['patient'].widget.attrs['disabled'] = 'disabled'
162

    
163
    def clean_patient(self):
164
        instance = getattr(self, 'instance', None)
165
        if instance:
166
            return instance.patient
167
        else:
168
            return self.cleaned_data.get('patient', None)
169

    
170

    
171
class NewEventForm(BaseForm):
172
    title = forms.CharField(label=u"Complément de l'intitulé", max_length=32, required=False)
173

    
174
    class Meta:
175
        model = Event
176
        fields = (
177
                'start_datetime',
178
                'title',
179
                'date',
180
                'time',
181
                'duration',
182
                'ressource',
183
                'participants',
184
                'event_type',
185
                'services',
186
                'description',
187
                'recurrence_periodicity',
188
                'recurrence_end_date'
189
        )
190
        widgets = {
191
                'start_datetime': forms.HiddenInput,
192
                'services': forms.CheckboxSelectMultiple,
193
        }
194

    
195
    def __init__(self, instance, service=None, **kwargs):
196
        self.service = service
197
        super(NewEventForm, self).__init__(instance=instance, **kwargs)
198
        self.fields['date'].css = 'datepicker'
199
        self.fields['event_type'].queryset = \
200
                    EventType.objects.exclude(id=1).exclude(id=3).order_by('rank', 'label')
201

    
202
    def clean_duration(self):
203
        duration = self.cleaned_data['duration']
204
        try:
205
            return int(duration)
206
        except:
207
            raise forms.ValidationError('Veuillez saisir un entier')
208

    
209
    def save(self, commit=True):
210
        event = super(NewEventForm, self).save(commit=False)
211
        event.start_datetime = datetime.combine(self.cleaned_data['date'],
212
                    self.cleaned_data['time'])
213
        event.end_datetime = event.start_datetime + timedelta(
214
                minutes=self.cleaned_data['duration'])
215
        event.creator = get_request().user
216
        event.clean()
217
        if commit:
218
            event.save()
219
            event.services = [self.service]
220
        return event
221

    
222
    def clean(self):
223
        cleaned_data = super(NewEventForm, self).clean()
224
        if cleaned_data.has_key('date') and cleaned_data.has_key('time'):
225
            cleaned_data['start_datetime'] = datetime.combine(cleaned_data['date'],
226
                    cleaned_data['time'])
227
        if not cleaned_data.get('recurrence_periodicity'):
228
            cleaned_data['recurrence_end_date'] = None
229
        event_type = cleaned_data.get('event_type')
230
        if event_type and event_type.id == 4 and not cleaned_data.get('title'): # 'Autre'
231
            self._errors['title'] = self.error_class([
232
                            u"Ce champ est obligatoire pour les événements de type « Autre »."])
233
        return cleaned_data
234

    
235
class UpdatePeriodicEventForm(NewEventForm):
236
    recurrence_periodicity = forms.ChoiceField(label=u"Périodicité",
237
            choices=Event.PERIODICITIES, required=True)
238

    
239
class UpdateEventForm(NewEventForm):
240
    class Meta(NewEventForm.Meta):
241
        fields = (
242
                'start_datetime',
243
                'title',
244
                'date',
245
                'time',
246
                'duration',
247
                'ressource',
248
                'participants',
249
                'event_type',
250
                'services',
251
        )
252

    
253
class PeriodicEventsSearchForm(forms.Form):
254
    start_date = forms.DateField(localize=True, required = False)
255
    end_date = forms.DateField(required=False, localize=True)
256

    
257
    event_type = forms.MultipleChoiceField(
258
            choices=(
259
                (0, 'Rendez-vous patient'),
260
                (1, 'Évènement')),
261
            widget=forms.CheckboxSelectMultiple,
262
            initial=[0,1])
263
    no_end_date = forms.BooleanField(label=u'Sans date de fin', required=False)
264
    patient = AutoCompleteSelectField('patientrecord', required=False, help_text='')
265
    worker = AutoCompleteSelectField('worker', required=False, help_text='')
266

    
267
    def clean(self):
268
        cleaned_data = super(PeriodicEventsSearchForm, self).clean()
269
        if cleaned_data.get('start_date') and cleaned_data.get('end_date'):
270
            if cleaned_data['start_date'] > cleaned_data['end_date']:
271
                raise forms.ValidationError(u'La date de début doit être supérieure à la date de fin')
272
        return cleaned_data
(5-5/10)