Project

General

Profile

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

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

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

    
3
import os
4
import logging
5

    
6
from datetime import date
7

    
8
from django import forms
9
from django.conf import settings
10
from django.forms import ModelForm, Form
11
import django.contrib.admin.widgets
12

    
13
from calebasse.dossiers.models import (PatientRecord,
14
    PatientAddress, PatientContact, DEFAULT_ACT_NUMBER_TREATMENT,
15
    CmppHealthCareTreatment, CmppHealthCareDiagnostic,
16
    SessadHealthCareNotification, FileState, Status, ProtectionState)
17
from calebasse.ressources.models import (HealthCenter, LargeRegime,
18
    CodeCFTMEA, SocialisationDuration, MDPHRequest, MDPHResponse)
19

    
20
from ajax_select import make_ajax_field
21
from django_select2.widgets import Select2MultipleWidget
22

    
23
logger = logging.getLogger(__name__)
24

    
25
class EditPatientRecordForm(ModelForm):
26
    class Meta:
27
        model = PatientRecord
28

    
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
    states = forms.ModelMultipleChoiceField(queryset=Status.objects.all(),
35
            initial=Status.objects.exclude(type='CLOS'),
36
            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

    
44
class StateForm(Form):
45
    patient_id = forms.IntegerField()
46
    service_id = forms.IntegerField()
47
    state_type = forms.CharField(max_length=40)
48
    date = forms.DateField(label=u'Date', localize=True)
49
    comment = forms.CharField(label='Commentaire',
50
            required=False, widget=forms.Textarea)
51

    
52
    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
class PatientStateForm(ModelForm):
61
    date_selected = forms.DateTimeField(label=u'Date', localize=True)
62
    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
    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
    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
            if date_selected < self.instance.previous_state.date_selected:
82
                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
            if date_selected > next_state.date_selected:
85
                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
class NewPatientRecordForm(ModelForm):
89
    date_selected = forms.DateField(label=u"Date de contact", localize=True)
90

    
91
    def __init__(self, *args, **kwargs):
92
        super(NewPatientRecordForm, self).__init__(*args, **kwargs)
93
        self.fields['first_name'].required = True
94
        self.fields['date_selected'].initial = date.today()
95

    
96
    class Meta:
97
        model = PatientRecord
98
        fields = ('last_name', 'first_name')
99

    
100
class GeneralForm(ModelForm):
101
    class Meta:
102
        model = PatientRecord
103
        fields = ('comment', 'pause', 'pause_comment', 'confidential')
104
        widgets = {
105
                'comment': forms.Textarea(attrs={'cols': 50, 'rows': 5}),
106
                'pause_comment': forms.Textarea(attrs={'cols': 50, 'rows': 3}),
107
                }
108

    
109
class CivilStatusForm(ModelForm):
110
    class Meta:
111
        model = PatientRecord
112
        fields = ('first_name', 'last_name', 'birthdate', 'birthplace', 'gender', 'nationality')
113

    
114

    
115
class PhysiologyForm(ModelForm):
116
    cranium_perimeter = forms.DecimalField(label=u"Périmètre cranien",
117
                    max_digits=5, decimal_places=2, localize=True,
118
                    required=False)
119
    chest_perimeter = forms.DecimalField(label=u"Périmètre thoracique",
120
                    max_digits=5, decimal_places=2, localize=True,
121
                    required=False)
122

    
123
    class Meta:
124
        model = PatientRecord
125
        fields = ('size', 'weight', 'pregnancy_term',
126
            'cranium_perimeter', 'chest_perimeter', 'apgar_score_one',
127
            '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
        widgets = {
135
                '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

    
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

    
151
class InscriptionForm(ModelForm):
152
    class Meta:
153
        model = PatientRecord
154
        fields = ('analysemotive', 'familymotive', 'provenance',
155
            'advicegiver', 'provenanceplace')
156
        widgets = {}
157

    
158
class OutForm(ModelForm):
159
    class Meta:
160
        model = PatientRecord
161
        fields = ('outmotive', 'outto')
162
        widgets = {}
163

    
164
class FamilyForm(ModelForm):
165
    class Meta:
166
        model = PatientRecord
167
        fields = ('sibship_place', 'nb_children_family', 'parental_authority',
168
                'family_situation', 'child_custody', 'job_mother', 'job_father',
169
                'rm_mother', 'rm_father', 'family_comment')
170
        widgets = {
171
                'family_comment': forms.Textarea(attrs={'cols': 50, 'rows': 1}),
172
                }
173

    
174
class TransportFrom(ModelForm):
175
    class Meta:
176
        model = PatientRecord
177
        fields = ('transporttype', 'transportcompany')
178

    
179
class PaperIDForm(ModelForm):
180
    class Meta:
181
        model = PatientRecord
182
        fields = ('paper_id', )
183

    
184
class PolicyHolderForm(ModelForm):
185
    class Meta:
186
        model = PatientRecord
187
        fields = ('policyholder', 'contact_comment')
188
        widgets = { 
189
                'policyholder': forms.RadioSelect(),
190
                'contact_comment': forms.Textarea(attrs={'cols': 50, 'rows': 2}),
191
                }
192

    
193
class FollowUpForm(ModelForm):
194
    coordinators = make_ajax_field(PatientRecord, 'coordinators', 'worker', True)
195
    class Meta:
196
        model = PatientRecord
197
        fields = ('coordinators', 'externaldoctor', 'externalintervener')
198

    
199
class PatientContactForm(ModelForm):
200
    health_org = forms.CharField(label=u"Numéro de l'organisme destinataire", required=False)
201

    
202
    class Meta:
203
        model = PatientContact
204
        widgets = {
205
                'key': forms.TextInput(attrs={'size': 4}),
206
                'twinning_rank': forms.TextInput(attrs={'size': 4}),
207
                'health_org': forms.TextInput(attrs={'size': 9}),
208
                'addresses': forms.CheckboxSelectMultiple(),
209
                'contact_comment': forms.Textarea(attrs={'rows': 2}),
210
                }
211

    
212
    def __init__(self, *args, **kwargs):
213
        self.patient = kwargs.pop('patient', None)
214
        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
        if self.patient:
218
            self.fields['addresses'].queryset = self.patient.addresses
219
            self.fields['addresses'].required = False
220

    
221
    def clean(self):
222
        cleaned_data = super(PatientContactForm, self).clean()
223
        health_org = cleaned_data.get('health_org')
224
        other_health_center = cleaned_data.get('other_health_center')
225
        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
                        if not other_health_center and len(health_org) == 9:
243
                            other_health_center = health_org[5:9]
244
                    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
                            msg = "Plusieurs centres possibles, précisez parmi :"
255
                            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
                cleaned_data['other_health_center'] = other_health_center
263
        return cleaned_data
264

    
265
    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

    
274
class PatientAddressForm(ModelForm):
275

    
276
    class Meta:
277
        model = PatientAddress
278
        widgets = {
279
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
280
                'zip_code': forms.TextInput(attrs={'size': 10}),
281
                'number': forms.TextInput(attrs={'size': 10}),
282
                }
283

    
284

    
285
class CmppHealthCareTreatmentForm(ModelForm):
286
    class Meta:
287
        model = CmppHealthCareTreatment
288
        fields = ('start_date', 'request_date',
289
                'agree_date', 'insist_date', 'end_date', 'act_number',
290
                'prolongation', 'prolongation_date', 'comment', 'patient',
291
                'author')
292
        widgets = {
293
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
294
                'patient': forms.HiddenInput(),
295
                'author': forms.HiddenInput(),
296
                }
297

    
298
    def clean(self):
299
        cleaned_data = super(CmppHealthCareTreatmentForm, self).clean()
300
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
301
            msg = u"Le nombre d'actes ne peut être inférieur au \
302
                nombre d'actes déja pris en charge (%d)." \
303
                    % self.instance.get_nb_acts_cared()
304
            self._errors["act_number"] = self.error_class([msg])
305
        return cleaned_data
306

    
307

    
308
class CmppHealthCareDiagnosticForm(ModelForm):
309
    class Meta:
310
        model = CmppHealthCareDiagnostic
311
        fields = ('start_date', 'request_date',
312
                'agree_date', 'insist_date', 'end_date', 'act_number',
313
                '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
    def clean(self):
321
        cleaned_data = super(CmppHealthCareDiagnosticForm, self).clean()
322
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
323
            msg = u"Le nombre d'actes ne peut être inférieur au \
324
                nombre d'actes déja pris en charge (%d)." \
325
                    % self.instance.get_nb_acts_cared()
326
            self._errors["act_number"] = self.error_class([msg])
327
        return cleaned_data
328

    
329

    
330
class SessadHealthCareNotificationForm(ModelForm):
331
    class Meta:
332
        model = SessadHealthCareNotification
333
        fields = ('start_date', 'end_date',
334
                'request_date', 'agree_date', 'insist_date',
335
                'comment', 'patient', 'author')
336
        widgets = {
337
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
338
                'patient': forms.HiddenInput(),
339
                'author': forms.HiddenInput(),
340
                }
341

    
342

    
343
class SocialisationDurationForm(ModelForm):
344
    school = make_ajax_field(SocialisationDuration, 'school', 'school', False)
345
    class Meta:
346
        model = SocialisationDuration
347
        fields = ('school', 'start_date',
348
            'end_date', 'level', 'contact', 'comment')
349
        widgets = {
350
                'contact': forms.Textarea(attrs={'cols': 39, 'rows': 2}),
351
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
352
                }
353

    
354
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
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

    
379
class AvailableRtfTemplates:
380
    def __iter__(self):
381
        if not settings.RTF_TEMPLATES_DIRECTORY:
382
            return iter([])
383
        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
        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
    address = forms.CharField(widget=forms.Textarea(attrs={'rows':5}), required=False)
396
    phone_address = forms.CharField(required=False)
397

    
398
    def __init__(self, *args, **kwargs):
399
        super(GenerateRtfForm, self).__init__(*args, **kwargs)
400
        self.fields['template_filename'].choices = AvailableRtfTemplates()
401

    
402
class QuotationsForm(Form):
403

    
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
    date_actes_start = forms.DateField(label=u'Date', localize=True)
413
    date_actes_end = forms.DateField(label=u'Date', localize=True)
414
    without_quotations = forms.BooleanField()
(3-3/12)