Project

General

Profile

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

calebasse / calebasse / dossiers / forms.py @ 78bae9a3

1 562586fb Jérôme Schneider
# -*- coding: utf-8 -*-
2
3 23937808 Frédéric Péters
import os
4 0d5f763c Jérôme Schneider
import logging
5 23937808 Frédéric Péters
6 f78e473c Jérôme Schneider
from datetime import date
7
8 562586fb Jérôme Schneider
from django import forms
9 23937808 Frédéric Péters
from django.conf import settings
10 39ddd165 Jérôme Schneider
from django.forms import ModelForm, Form
11 11f94c15 Frédéric Péters
import django.contrib.admin.widgets
12 da64143d Benjamin Dauvergne
13 b464657d Mikaël Ates
from calebasse.dossiers.models import (PatientRecord,
14 2da0976b Jérôme Schneider
    PatientAddress, PatientContact, DEFAULT_ACT_NUMBER_TREATMENT,
15 b8957f1d Jérôme Schneider
    CmppHealthCareTreatment, CmppHealthCareDiagnostic,
16 5497fedd Mikaël Ates
    SessadHealthCareNotification, FileState, Status, ProtectionState)
17 1117d039 Mikaël Ates
from calebasse.ressources.models import (HealthCenter, LargeRegime,
18 a4bccba9 Mikaël Ates
    CodeCFTMEA, SocialisationDuration, MDPHRequest, MDPHResponse)
19 da64143d Benjamin Dauvergne
20 4aa8bb1d Jérôme Schneider
from ajax_select import make_ajax_field
21 78bae9a3 Jérôme Schneider
from django_select2.widgets import Select2MultipleWidget
22 4aa8bb1d Jérôme Schneider
23 0d5f763c Jérôme Schneider
logger = logging.getLogger(__name__)
24 b464657d Mikaël Ates
25 3087a41c Jérôme Schneider
class EditPatientRecordForm(ModelForm):
26 da64143d Benjamin Dauvergne
    class Meta:
27 e3c5afd2 Jérôme Schneider
        model = PatientRecord
28 562586fb Jérôme Schneider
29
class SearchForm(Form):
30
    last_name = forms.CharField(label=u'Nom', required=False)
31
    first_name = forms.CharField(label=u'Prénom', required=False)
32
    folder_id = forms.CharField(label=u'Numéro de dossier', required=False)
33
    social_security_id = forms.CharField(label=u"Numéro d'assuré social", required=False)
34 e30c9bdb Jérôme Schneider
    states = forms.ModelMultipleChoiceField(queryset=Status.objects.all(),
35 58ffd7f4 Mikaël Ates
            initial=Status.objects.exclude(type='CLOS'),
36 e30c9bdb Jérôme Schneider
            widget=forms.CheckboxSelectMultiple(attrs={'class':'checkbox_state'}))
37
38
    def __init__(self, service=None, *args, **kwargs):
39
        self.service = service
40
        super(SearchForm, self).__init__(*args, **kwargs)
41
        self.fields['states'].queryset = Status.objects.filter(services=service)
42
43 8e6fe119 Jérôme Schneider
44 f78e473c Jérôme Schneider
class StateForm(Form):
45
    patient_id = forms.IntegerField()
46 54f8d003 Jérôme Schneider
    service_id = forms.IntegerField()
47
    state_type = forms.CharField(max_length=40)
48 86f4d2f2 Benjamin Dauvergne
    date = forms.DateField(label=u'Date', localize=True)
49 f78e473c Jérôme Schneider
    comment = forms.CharField(label='Commentaire',
50
            required=False, widget=forms.Textarea)
51
52 e6a65c33 Frédéric Péters
    def clean_date(self):
53
        patient = PatientRecord.objects.get(id=self.cleaned_data['patient_id'])
54
        date_selected = self.cleaned_data['date']
55
        current_state = patient.get_state()
56
        if date_selected < current_state.date_selected.date():
57
            raise forms.ValidationError(u"La date ne peut pas être antérieure à celle du précédent changement d'état.")
58
        return self.cleaned_data['date']
59
60 4a0ff5ea Frédéric Péters
class PatientStateForm(ModelForm):
61 c4c63c3e Jérôme Schneider
    date_selected = forms.DateTimeField(label=u'Date', localize=True)
62 4a0ff5ea Frédéric Péters
    comment = forms.CharField(label='Commentaire',
63
            required=False, widget=forms.Textarea)
64
65
    class Meta:
66
        model = FileState
67
        fields = ('status', 'date_selected', 'comment')
68
        widgets = {
69
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
70
                }
71
72 24c750bb Jérôme Schneider
    def __init__(self, service=None, *args, **kwargs):
73
        self.service = service
74
        super(PatientStateForm, self).__init__(*args, **kwargs)
75
        self.fields['status'].queryset = Status.objects.filter(services=service)
76
77 4a0ff5ea Frédéric Péters
    def clean_date_selected(self):
78
        date_selected = self.cleaned_data['date_selected']
79
        next_state = self.instance.get_next_state()
80
        if self.instance.previous_state:
81 c4c63c3e Jérôme Schneider
            if date_selected < self.instance.previous_state.date_selected:
82 4a0ff5ea Frédéric Péters
                raise forms.ValidationError(u"La date ne peut pas être antérieure à celle du précédent changement d'état.")
83
        if next_state:
84 c4c63c3e Jérôme Schneider
            if date_selected > next_state.date_selected:
85 4a0ff5ea Frédéric Péters
                raise forms.ValidationError(u"La date ne peut pas être postérieure à celle du changement d'état suivant.")
86
        return self.cleaned_data['date_selected']
87
88 554289d5 Jérôme Schneider
class NewPatientRecordForm(ModelForm):
89 23af777c Serghei MIHAI
    date_selected = forms.DateField(label=u"Date de contact", localize=True)
90 5327927f Mikaël Ates
91 9ad6d1ac Serghei MIHAI
    def __init__(self, *args, **kwargs):
92
        super(NewPatientRecordForm, self).__init__(*args, **kwargs)
93
        self.fields['first_name'].required = True
94 23af777c Serghei MIHAI
        self.fields['date_selected'].initial = date.today()
95 9ad6d1ac Serghei MIHAI
96 554289d5 Jérôme Schneider
    class Meta:
97
        model = PatientRecord
98 c0c2ff54 Frédéric Péters
        fields = ('last_name', 'first_name')
99 554289d5 Jérôme Schneider
100 0259c7ef Jérôme Schneider
class GeneralForm(ModelForm):
101
    class Meta:
102
        model = PatientRecord
103 21fb4def Mikaël Ates
        fields = ('comment', 'pause', 'pause_comment', 'confidential')
104 0259c7ef Jérôme Schneider
        widgets = {
105
                'comment': forms.Textarea(attrs={'cols': 50, 'rows': 5}),
106 21fb4def Mikaël Ates
                'pause_comment': forms.Textarea(attrs={'cols': 50, 'rows': 3}),
107 0259c7ef Jérôme Schneider
                }
108
109 f3407c83 Jérôme Schneider
class CivilStatusForm(ModelForm):
110
    class Meta:
111
        model = PatientRecord
112 28ff59f7 Mikaël Ates
        fields = ('first_name', 'last_name', 'birthdate', 'birthplace', 'gender', 'nationality')
113 54f8d003 Jérôme Schneider
114 11f94c15 Frédéric Péters
115 6c5b2d74 Jérôme Schneider
class PhysiologyForm(ModelForm):
116 901f6f98 Frédéric Péters
    cranium_perimeter = forms.DecimalField(label=u"Périmètre cranien",
117 14f0963a Mikaël Ates
                    max_digits=5, decimal_places=2, localize=True,
118
                    required=False)
119 901f6f98 Frédéric Péters
    chest_perimeter = forms.DecimalField(label=u"Périmètre thoracique",
120 14f0963a Mikaël Ates
                    max_digits=5, decimal_places=2, localize=True,
121
                    required=False)
122 901f6f98 Frédéric Péters
123 6c5b2d74 Jérôme Schneider
    class Meta:
124
        model = PatientRecord
125 1117d039 Mikaël Ates
        fields = ('size', 'weight', 'pregnancy_term',
126
            'cranium_perimeter', 'chest_perimeter', 'apgar_score_one',
127 5c6f1b32 Mikaël Ates
            'apgar_score_two', 'mises_1', 'mises_2', 'mises_3',
128
            'deficiency_intellectual', 'deficiency_autism_and_other_ted',
129
            'deficiency_mental_disorder', 'deficiency_learning_disorder',
130
            'deficiency_auditory', 'deficiency_visual', 'deficiency_motor',
131
            'deficiency_metabolic_disorder', 'deficiency_brain_damage',
132
            'deficiency_polyhandicap', 'deficiency_behavioral_disorder',
133
            'deficiency_in_diagnostic', 'deficiency_other_disorder')
134 11f94c15 Frédéric Péters
        widgets = {
135 78bae9a3 Jérôme Schneider
                'mises_1': Select2MultipleWidget(attrs={'style': 'width: 32em'}),
136
                'mises_2': Select2MultipleWidget(attrs={'style': 'width: 32em'}),
137
                'mises_3': Select2MultipleWidget(attrs={'style': 'width: 32em'}),
138
                }
139
140 1117d039 Mikaël Ates
141
    def __init__(self, instance, **kwargs):
142
        super(PhysiologyForm, self).__init__(instance=instance, **kwargs)
143
        self.fields['mises_1'].queryset = \
144
                CodeCFTMEA.objects.filter(axe=1)
145
        self.fields['mises_2'].queryset = \
146
                CodeCFTMEA.objects.filter(axe=2)
147
        self.fields['mises_3'].queryset = \
148
                CodeCFTMEA.objects.filter(axe=3)
149
150 2773b4d4 Jérôme Schneider
151
class InscriptionForm(ModelForm):
152
    class Meta:
153
        model = PatientRecord
154 a37b47e6 Mikaël Ates
        fields = ('analysemotive', 'familymotive', 'provenance',
155
            'advicegiver', 'provenanceplace')
156 cea6ec34 Jérôme Schneider
        widgets = {}
157 2773b4d4 Jérôme Schneider
158 dc1389b8 Mikaël Ates
class OutForm(ModelForm):
159
    class Meta:
160
        model = PatientRecord
161
        fields = ('outmotive', 'outto')
162
        widgets = {}
163
164 428081e0 Jérôme Schneider
class FamilyForm(ModelForm):
165 2773b4d4 Jérôme Schneider
    class Meta:
166
        model = PatientRecord
167 a8dd5599 Jérôme Schneider
        fields = ('sibship_place', 'nb_children_family', 'parental_authority',
168 08391712 Mikaël Ates
                'family_situation', 'child_custody', 'job_mother', 'job_father',
169
                'rm_mother', 'rm_father', 'family_comment')
170
        widgets = {
171 ca1f2836 Jérôme Schneider
                'family_comment': forms.Textarea(attrs={'cols': 50, 'rows': 1}),
172 08391712 Mikaël Ates
                }
173 428081e0 Jérôme Schneider
174
class TransportFrom(ModelForm):
175
    class Meta:
176
        model = PatientRecord
177
        fields = ('transporttype', 'transportcompany')
178
179 11fe262b Jérôme Schneider
class PaperIDForm(ModelForm):
180 3194ad10 Jérôme Schneider
    class Meta:
181
        model = PatientRecord
182 f25ef019 Jérôme Schneider
        fields = ('paper_id', )
183
184
class PolicyHolderForm(ModelForm):
185
    class Meta:
186
        model = PatientRecord
187 56f20753 Jérôme Schneider
        fields = ('policyholder', 'contact_comment')
188
        widgets = { 
189
                'policyholder': forms.RadioSelect(),
190
                'contact_comment': forms.Textarea(attrs={'cols': 50, 'rows': 2}),
191
                }
192 3194ad10 Jérôme Schneider
193 428081e0 Jérôme Schneider
class FollowUpForm(ModelForm):
194 4aa8bb1d Jérôme Schneider
    coordinators = make_ajax_field(PatientRecord, 'coordinators', 'worker', True)
195 428081e0 Jérôme Schneider
    class Meta:
196
        model = PatientRecord
197
        fields = ('coordinators', 'externaldoctor', 'externalintervener')
198 2773b4d4 Jérôme Schneider
199 317bcb4c Jérôme Schneider
class PatientContactForm(ModelForm):
200 f7f9d7c7 Mikaël Ates
    health_org = forms.CharField(label=u"Numéro de l'organisme destinataire", required=False)
201
202 317bcb4c Jérôme Schneider
    class Meta:
203
        model = PatientContact
204
        widgets = {
205 a8dd5599 Jérôme Schneider
                'key': forms.TextInput(attrs={'size': 4}),
206 39ddd165 Jérôme Schneider
                'twinning_rank': forms.TextInput(attrs={'size': 4}),
207 f7f9d7c7 Mikaël Ates
                'health_org': forms.TextInput(attrs={'size': 9}),
208 f34241d5 Frédéric Péters
                'addresses': forms.CheckboxSelectMultiple(),
209 3a91ff50 Jérôme Schneider
                'contact_comment': forms.Textarea(attrs={'rows': 2}),
210 317bcb4c Jérôme Schneider
                }
211
212 f7f9d7c7 Mikaël Ates
    def __init__(self, *args, **kwargs):
213 f8606a78 Benjamin Dauvergne
        self.patient = kwargs.pop('patient', None)
214 f7f9d7c7 Mikaël Ates
        super(PatientContactForm, self).__init__(*args,**kwargs)
215
        if self.instance and self.instance.health_center:
216
            self.fields['health_org'].initial = self.instance.health_center.large_regime.code + self.instance.health_center.health_fund + self.instance.health_center.code
217 f8606a78 Benjamin Dauvergne
        if self.patient:
218
            self.fields['addresses'].queryset = self.patient.addresses
219 724b950f Mikaël Ates
            self.fields['addresses'].required = False
220 f7f9d7c7 Mikaël Ates
221
    def clean(self):
222
        cleaned_data = super(PatientContactForm, self).clean()
223
        health_org = cleaned_data.get('health_org')
224 e20cf07a Mikaël Ates
        other_health_center = cleaned_data.get('other_health_center')
225 f7f9d7c7 Mikaël Ates
        if health_org:
226
            msg = None
227
            lr = None
228
            hc = None
229
            if len(health_org) < 5:
230
                msg = u"Numéro inférieur à 5 chiffres."
231
            else:
232
                try:
233
                    lr = LargeRegime.objects.get(code=health_org[:2])
234
                except:
235
                    msg = u"Grand régime %s inconnu." % health_org[:2]
236
                else:
237
                    hcs = HealthCenter.objects.filter(health_fund=health_org[2:5], large_regime=lr)
238
                    if not hcs:
239
                        msg = u"Caisse %s inconnue." % health_org[2:5]
240
                    elif len(hcs) == 1:
241
                        hc = hcs[0]
242 e20cf07a Mikaël Ates
                        if not other_health_center and len(health_org) == 9:
243
                            other_health_center = health_org[5:9]
244 f7f9d7c7 Mikaël Ates
                    else:
245
                        if len(health_org) == 9:
246
                            hcs = hcs.filter(code=health_org[5:9])
247
                            if not hcs:
248
                                msg = u"Centre %s inconnu." % health_org[5:9]
249
                            elif len(hcs) == 1:
250
                                hc = hcs[0]
251
                            else:
252
                                msg = u"Ceci ne devrait pas arriver, %s n'est pas unique." % health_org
253
                        else:
254 3e10c7d9 Mikaël Ates
                            msg = "Plusieurs centres possibles, précisez parmi :"
255 f7f9d7c7 Mikaël Ates
                            for hc in hcs:
256
                                msg += " %s" % str(hc)
257
            if msg:
258
                self._errors["health_org"] = self.error_class([msg])
259
            else:
260
                cleaned_data['large_regime'] = lr.code
261
                cleaned_data['health_center'] = hc
262 e20cf07a Mikaël Ates
                cleaned_data['other_health_center'] = other_health_center
263 f7f9d7c7 Mikaël Ates
        return cleaned_data
264
265 724b950f Mikaël Ates
    def save(self, commit=True):
266
        contact = super(PatientContactForm, self).save(commit=False)
267
        contact.clean()
268
        if commit:
269
            contact.save()
270
            if self.patient and not self.instance.addresses.all():
271
                self.patient.contacts.add(contact)
272
        return contact
273 f7f9d7c7 Mikaël Ates
274 317bcb4c Jérôme Schneider
class PatientAddressForm(ModelForm):
275 29168b44 Jérôme Schneider
276 317bcb4c Jérôme Schneider
    class Meta:
277
        model = PatientAddress
278 29168b44 Jérôme Schneider
        widgets = {
279 2523f48f Jérôme Schneider
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
280 29168b44 Jérôme Schneider
                'zip_code': forms.TextInput(attrs={'size': 10}),
281
                'number': forms.TextInput(attrs={'size': 10}),
282
                }
283 317bcb4c Jérôme Schneider
284 29aa5385 Mikaël Ates
285 2da0976b Jérôme Schneider
class CmppHealthCareTreatmentForm(ModelForm):
286
    class Meta:
287
        model = CmppHealthCareTreatment
288 5b234990 Mikaël Ates
        fields = ('start_date', 'request_date',
289 44a0fb10 Mikaël Ates
                'agree_date', 'insist_date', 'end_date', 'act_number',
290 61405b31 Mikaël Ates
                'prolongation', 'prolongation_date', 'comment', 'patient',
291
                'author')
292 2da0976b Jérôme Schneider
        widgets = {
293
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
294
                'patient': forms.HiddenInput(),
295
                'author': forms.HiddenInput(),
296
                }
297 b8957f1d Jérôme Schneider
298 29aa5385 Mikaël Ates
    def clean(self):
299
        cleaned_data = super(CmppHealthCareTreatmentForm, self).clean()
300 5b234990 Mikaël Ates
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
301 29aa5385 Mikaël Ates
            msg = u"Le nombre d'actes ne peut être inférieur au \
302
                nombre d'actes déja pris en charge (%d)." \
303 5b234990 Mikaël Ates
                    % self.instance.get_nb_acts_cared()
304 29aa5385 Mikaël Ates
            self._errors["act_number"] = self.error_class([msg])
305
        return cleaned_data
306
307
308 b8957f1d Jérôme Schneider
class CmppHealthCareDiagnosticForm(ModelForm):
309
    class Meta:
310
        model = CmppHealthCareDiagnostic
311 5b234990 Mikaël Ates
        fields = ('start_date', 'request_date',
312 7ecc94f9 Mikaël Ates
                'agree_date', 'insist_date', 'end_date', 'act_number',
313 b8957f1d Jérôme Schneider
                'comment', 'patient', 'author')
314
        widgets = {
315
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
316
                'patient': forms.HiddenInput(),
317
                'author': forms.HiddenInput(),
318
                }
319
320 29aa5385 Mikaël Ates
    def clean(self):
321
        cleaned_data = super(CmppHealthCareDiagnosticForm, self).clean()
322 5b234990 Mikaël Ates
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
323 29aa5385 Mikaël Ates
            msg = u"Le nombre d'actes ne peut être inférieur au \
324
                nombre d'actes déja pris en charge (%d)." \
325 5b234990 Mikaël Ates
                    % self.instance.get_nb_acts_cared()
326 29aa5385 Mikaël Ates
            self._errors["act_number"] = self.error_class([msg])
327
        return cleaned_data
328
329
330 b8957f1d Jérôme Schneider
class SessadHealthCareNotificationForm(ModelForm):
331
    class Meta:
332
        model = SessadHealthCareNotification
333
        fields = ('start_date', 'end_date',
334 416a1188 Mikaël Ates
                'request_date', 'agree_date', 'insist_date',
335 b8957f1d Jérôme Schneider
                'comment', 'patient', 'author')
336
        widgets = {
337
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
338
                'patient': forms.HiddenInput(),
339
                'author': forms.HiddenInput(),
340
                }
341 69f3b883 Mikaël Ates
342
343
class SocialisationDurationForm(ModelForm):
344 6c60a174 Mikaël Ates
    school = make_ajax_field(SocialisationDuration, 'school', 'school', False)
345 69f3b883 Mikaël Ates
    class Meta:
346
        model = SocialisationDuration
347 6c60a174 Mikaël Ates
        fields = ('school', 'start_date',
348 5458878e Mikaël Ates
            'end_date', 'level', 'contact', 'comment')
349 69f3b883 Mikaël Ates
        widgets = {
350 24773178 Mikaël Ates
                'contact': forms.Textarea(attrs={'cols': 39, 'rows': 2}),
351 69f3b883 Mikaël Ates
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
352
                }
353 5bdfc735 Mikaël Ates
354 5497fedd Mikaël Ates
class ProtectionStateForm(ModelForm):
355
    class Meta:
356
        model = ProtectionState
357
        fields = ('status', 'start_date', 'end_date', 'comment')
358
        widgets = {
359
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
360
                }
361
362 5bdfc735 Mikaël Ates
class MDPHRequestForm(ModelForm):
363
    class Meta:
364
        model = MDPHRequest
365
        fields = ('start_date', 'mdph', 'comment')
366
        widgets = {
367
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
368
                }
369
370
class MDPHResponseForm(ModelForm):
371
    class Meta:
372
        model = MDPHResponse
373
        fields = ('start_date', 'end_date', 'mdph', 'comment',
374
            'type_aide', 'name', 'rate')
375
        widgets = {
376
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
377
                }
378 23937808 Frédéric Péters
379
class AvailableRtfTemplates:
380
    def __iter__(self):
381
        if not settings.RTF_TEMPLATES_DIRECTORY:
382
            return iter([])
383 0d5f763c Jérôme Schneider
        if not os.path.exists(settings.RTF_TEMPLATES_DIRECTORY):
384
            logger.warning("RTF_TEMPLATES_DIRECTOR %r doesn't exist" % \
385
                    settings.RTF_TEMPLATES_DIRECTORY)
386
            return iter([])
387
388 23937808 Frédéric Péters
        templates = []
389
        for filename in os.listdir(settings.RTF_TEMPLATES_DIRECTORY):
390
            templates.append((filename, filename[:-4]))
391
        return iter(templates)
392
393
class GenerateRtfForm(Form):
394
    template_filename = forms.ChoiceField(choices=AvailableRtfTemplates())
395 1860b59f Frédéric Péters
    address = forms.CharField(widget=forms.Textarea(attrs={'rows':5}), required=False)
396 b4310641 Mikaël Ates
    phone_address = forms.CharField(required=False)
397 17e36a37 Frédéric Péters
398 a192e19a Mikaël Ates
    def __init__(self, *args, **kwargs):
399
        super(GenerateRtfForm, self).__init__(*args, **kwargs)
400
        self.fields['template_filename'].choices = AvailableRtfTemplates()
401
402 17e36a37 Frédéric Péters
class QuotationsForm(Form):
403 f6be0c7d Jérôme Schneider
404
    def __init__(self, service=None, *args, **kwargs):
405
        self.service = service
406
        super(QuotationsForm, self).__init__(*args, **kwargs)
407
        self.fields['states'].queryset = Status.objects.filter(services=service)
408
409
    states = forms.ModelMultipleChoiceField(queryset=Status.objects.all(),
410
            initial=Status.objects.all(),
411
            widget=forms.CheckboxSelectMultiple(attrs={'class':'checkbox_state'}))
412 86f4d2f2 Benjamin Dauvergne
    date_actes_start = forms.DateField(label=u'Date', localize=True)
413
    date_actes_end = forms.DateField(label=u'Date', localize=True)
414 17e36a37 Frédéric Péters
    without_quotations = forms.BooleanField()