Projet

Général

Profil

Télécharger (10,5 ko) Statistiques
| Branche: | Tag: | Révision:

calebasse / calebasse / agenda / forms.py @ a01d85be

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

    
61
    def clean_duration(self):
62
        duration = self.cleaned_data['duration']
63
        try:
64
            return int(duration)
65
        except ValueError:
66
            raise forms.ValidationError('Veuillez saisir un entier')
67

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

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

    
87
    def save(self, commit=True):
88

    
89
        patients = self.cleaned_data.pop('patients')
90
        for patient in patients:
91
            appointment = forms.save_instance(self, self._meta.model(), commit=False)
92
            appointment.start_datetime = datetime.combine(self.cleaned_data['date'],
93
                                                          self.cleaned_data['time'])
94
            appointment.end_datetime = appointment.start_datetime + timedelta(
95
                minutes=self.cleaned_data['duration'])
96
            appointment.creator = get_request().user
97
            appointment.clean()
98
            if commit:
99
                appointment.patient = patient
100
                appointment.save()
101
                get_request().record('new-eventwithact',
102
                                    '{obj_id} created by {user} from {ip}',
103
                                     obj_id=appointment.id)
104
                self.save_m2m()
105
                appointment.services = [self.service]
106

    
107
class UpdateAppointmentForm(NewAppointmentForm):
108

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

    
111
    def clean_patient(self):
112
        return self.cleaned_data['patient']
113

    
114
    def save(self, commit=True):
115
        appointment = super(NewAppointmentForm, self).save(commit=False)
116
        appointment.start_datetime = datetime.combine(self.cleaned_data['date'],
117
                    self.cleaned_data['time'])
118
        appointment.end_datetime = appointment.start_datetime + timedelta(
119
                minutes=self.cleaned_data['duration'])
120
        appointment.creator = get_request().user
121
        appointment.clean()
122
        if commit:
123
            appointment.save()
124
            get_request().record('update-eventwithact',
125
                                 '{obj_id} saved by {user} from {ip}',
126
                                 obj_id=appointment.id)
127
            self.save_m2m()
128
            appointment.services = [self.service]
129
        return appointment
130

    
131

    
132
class UpdatePeriodicAppointmentForm(UpdateAppointmentForm):
133
    patient = make_ajax_field(EventWithAct, 'patient', 'patientrecord', False)
134
    recurrence_periodicity = forms.ChoiceField(label=u"Périodicité",
135
            choices=Event.PERIODICITIES, required=True)
136

    
137
    def clean(self):
138
        cleaned_data = super(UpdatePeriodicAppointmentForm, self).clean()
139
        acts = self.instance.act_set.filter(is_billed=True).order_by('-date')
140
        if acts and cleaned_data.get('recurrence_end_date'):
141
            recurrence_end_date = cleaned_data['recurrence_end_date']
142
            if recurrence_end_date < acts[0].date:
143
                self._errors['recurrence_end_date'] = self.error_class([
144
                            u"La date doit être supérieur au dernier acte facturé de la récurrence"])
145
        return cleaned_data
146

    
147
class DisablePatientAppointmentForm(UpdateAppointmentForm):
148

    
149
    def __init__(self, instance, service=None, **kwargs):
150
        super(DisablePatientAppointmentForm, self).__init__(instance,
151
                service, **kwargs)
152
        if instance and instance.pk:
153
            self.fields['patient'].required = False
154
            self.fields['patient'].widget.attrs['disabled'] = 'disabled'
155

    
156
    def clean_patient(self):
157
        instance = getattr(self, 'instance', None)
158
        if instance:
159
            return instance.patient
160
        else:
161
            return self.cleaned_data.get('patient', None)
162

    
163

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

    
167
    class Meta:
168
        model = Event
169
        fields = (
170
                'start_datetime',
171
                'title',
172
                'date',
173
                'time',
174
                'duration',
175
                'ressource',
176
                'participants',
177
                'event_type',
178
                'services',
179
                'description',
180
                'recurrence_periodicity',
181
                'recurrence_end_date',
182
        )
183
        widgets = {
184
                'start_datetime': forms.HiddenInput,
185
                'services': forms.CheckboxSelectMultiple,
186
        }
187

    
188
    def __init__(self, instance, service=None, **kwargs):
189
        self.service = service
190
        super(NewEventForm, self).__init__(instance=instance, **kwargs)
191
        self.fields['date'].css = 'datepicker'
192
        self.fields['event_type'].queryset = \
193
                    EventType.objects.exclude(id=1).exclude(id=3).order_by('rank', 'label')
194

    
195
    def clean_duration(self):
196
        duration = self.cleaned_data['duration']
197
        try:
198
            return int(duration)
199
        except:
200
            raise forms.ValidationError('Veuillez saisir un entier')
201

    
202
    def save(self, commit=True):
203
        event = super(NewEventForm, self).save(commit=False)
204
        event.start_datetime = datetime.combine(self.cleaned_data['date'],
205
                    self.cleaned_data['time'])
206
        event.end_datetime = event.start_datetime + timedelta(
207
                minutes=self.cleaned_data['duration'])
208
        event.creator = get_request().user
209
        event.clean()
210
        if commit:
211
            event.save()
212
            get_request().record('new-event', '{obj_id} created by {user} from {ip}',
213
                                 obj_id=event.id)
214
            event.services = [self.service]
215
        return event
216

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

    
230
class UpdatePeriodicEventForm(NewEventForm):
231
    recurrence_periodicity = forms.ChoiceField(label=u"Périodicité",
232
            choices=Event.PERIODICITIES, required=True)
233

    
234
class UpdateEventForm(NewEventForm):
235
    class Meta(NewEventForm.Meta):
236
        fields = (
237
                'start_datetime',
238
                'title',
239
                'date',
240
                'time',
241
                'duration',
242
                'ressource',
243
                'participants',
244
                'event_type',
245
                'services',
246
        )
247

    
248
class PeriodicEventsSearchForm(forms.Form):
249
    start_date = forms.DateField(localize=True, required = False)
250
    end_date = forms.DateField(required=False, localize=True)
251

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

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