Project

General

Profile

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

calebasse / calebasse / agenda / forms.py @ 392c5526

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
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 = make_ajax_field(EventWithAct, 'patient', 'patientrecord', False)
26

    
27
    class Meta:
28
        model = EventWithAct
29
        fields = (
30
                'start_datetime',
31
                'date',
32
                'time',
33
                'duration',
34
                'patient',
35
                'participants',
36
                'room',
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(self):
71
        cleaned_data = super(NewAppointmentForm, self).clean()
72
        if not cleaned_data.get('recurrence_periodicity'):
73
            cleaned_data['recurrence_end_date'] = None
74
        if cleaned_data.has_key('date') and cleaned_data.has_key('time'):
75
            cleaned_data['start_datetime'] = datetime.combine(cleaned_data['date'],
76
                    cleaned_data['time'])
77
        return cleaned_data
78

    
79
    def save(self, commit=True):
80
        appointment = super(NewAppointmentForm, self).save(commit=False)
81
        appointment.start_datetime = datetime.combine(self.cleaned_data['date'],
82
                    self.cleaned_data['time'])
83
        appointment.end_datetime = appointment.start_datetime + timedelta(
84
                minutes=self.cleaned_data['duration'])
85
        appointment.creator = get_request().user
86
        appointment.title = appointment.patient.display_name
87
        appointment.clean()
88
        if commit:
89
            appointment.save()
90
            appointment.services = [self.service]
91
        return appointment
92

    
93

    
94
class UpdateAppointmentForm(NewAppointmentForm):
95
    class Meta(NewAppointmentForm.Meta):
96
        fields = (
97
                'start_datetime',
98
                'date',
99
                'time',
100
                'duration',
101
                'patient',
102
                'participants',
103
                'room',
104
                'act_type',
105
        )
106

    
107

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

    
111
    class Meta:
112
        model = Event
113
        fields = (
114
                'start_datetime',
115
                'title',
116
                'date',
117
                'time',
118
                'duration',
119
                'room',
120
                'participants',
121
                'event_type',
122
                'services',
123
                'description',
124
                'recurrence_periodicity',
125
                'recurrence_end_date'
126
        )
127
        widgets = {
128
                'start_datetime': forms.HiddenInput,
129
                'services': forms.CheckboxSelectMultiple,
130
        }
131

    
132
    def __init__(self, instance, service=None, **kwargs):
133
        self.service = service
134
        super(NewEventForm, self).__init__(instance=instance, **kwargs)
135
        self.fields['date'].css = 'datepicker'
136
        self.fields['event_type'].queryset = \
137
                    EventType.objects.exclude(id=1).exclude(id=3).order_by('rank', 'label')
138

    
139
    def clean_duration(self):
140
        duration = self.cleaned_data['duration']
141
        try:
142
            return int(duration)
143
        except:
144
            return None
145

    
146
    def save(self, commit=True):
147
        event = super(NewEventForm, self).save(commit=False)
148
        event.start_datetime = datetime.combine(self.cleaned_data['date'],
149
                    self.cleaned_data['time'])
150
        event.end_datetime = event.start_datetime + timedelta(
151
                minutes=self.cleaned_data['duration'])
152
        event.creator = get_request().user
153
        event.clean()
154
        if commit:
155
            event.save()
156
            event.services = [self.service]
157
        return event
158

    
159
    def clean(self):
160
        cleaned_data = super(NewEventForm, self).clean()
161
        if cleaned_data.has_key('date') and cleaned_data.has_key('time'):
162
            cleaned_data['start_datetime'] = datetime.combine(cleaned_data['date'],
163
                    cleaned_data['time'])
164
        if not cleaned_data.get('recurrence_periodicity'):
165
            cleaned_data['recurrence_end_date'] = None
166
        event_type = cleaned_data.get('event_type')
167
        if event_type and event_type.id == 4 and not cleaned_data.get('title'): # 'Autre'
168
            self._errors['title'] = self.error_class([
169
                            u"Ce champ est obligatoire pour les événements de type « Autre »."])
170
        return cleaned_data
171

    
172

    
173
class UpdateEventForm(NewEventForm):
174
    class Meta(NewEventForm.Meta):
175
        fields = (
176
                'start_datetime',
177
                'title',
178
                'date',
179
                'time',
180
                'duration',
181
                'room',
182
                'participants',
183
                'event_type',
184
                'services',
185
        )
186

    
187
class PeriodicEventsSearchForm(forms.Form):
188
    start_date = forms.DateField(localize=True)
189
    end_date = forms.DateField(required=False, localize=True)
190

    
191
    event_type = forms.MultipleChoiceField(
192
            choices=(
193
                (0, 'Rendez-vous patient'),
194
                (1, 'Autre')),
195
            widget=forms.CheckboxSelectMultiple,
196
            initial=[0,1])
197
    no_end_date = forms.BooleanField(label=u'Sans date de fin', required=False)
198
    patient = AutoCompleteSelectField('patientrecord', required=False, help_text='')
199

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