Project

General

Profile

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

calebasse / calebasse / dossiers / forms.py @ b057fff0

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 AdministrativeForm(ModelForm):
110
    coordinators = make_ajax_field(PatientRecord, 'coordinators', 'worker', True)
111
    class Meta:
112
        model = PatientRecord
113
        # ID
114
        fields = ('first_name', 'last_name', 'birthdate', 'birthplace',
115
                'gender', 'nationality',)
116
        # inscription
117
        fields += ('analysemotive', 'familymotive', 'provenance',
118
            'advicegiver', 'provenanceplace',)
119
        # out
120
        fields += ('outmotive', 'outto',)
121
        # family
122
        fields += ('sibship_place', 'nb_children_family', 'parental_authority',
123
                'family_situation', 'child_custody', 'job_mother', 'job_father',
124
                'rm_mother', 'rm_father', 'family_comment',)
125
        # transport
126
        fields += ('transporttype', 'transportcompany',
127
                  'simple_appointment_transport', 'periodic_appointment_transport',)
128
        # Follow up
129
        fields += ('coordinators', 'externaldoctor', 'externalintervener',)
130
        widgets = {
131
                'family_comment': forms.Textarea(attrs={'cols': 50, 'rows': 1}),
132
                }
133

    
134

    
135
class PhysiologyForm(ModelForm):
136
    cranium_perimeter = forms.DecimalField(label=u"Périmètre cranien",
137
                    max_digits=5, decimal_places=2, localize=True,
138
                    required=False)
139
    chest_perimeter = forms.DecimalField(label=u"Périmètre thoracique",
140
                    max_digits=5, decimal_places=2, localize=True,
141
                    required=False)
142

    
143
    class Meta:
144
        model = PatientRecord
145
        fields = ('size', 'weight', 'pregnancy_term',
146
            'cranium_perimeter', 'chest_perimeter', 'apgar_score_one',
147
            'apgar_score_two', 'mises_1', 'mises_2', 'mises_3',
148
            'deficiency_intellectual', 'deficiency_autism_and_other_ted',
149
            'deficiency_mental_disorder', 'deficiency_learning_disorder',
150
            'deficiency_auditory', 'deficiency_visual', 'deficiency_motor',
151
            'deficiency_metabolic_disorder', 'deficiency_brain_damage',
152
            'deficiency_polyhandicap', 'deficiency_behavioral_disorder',
153
            'deficiency_in_diagnostic', 'deficiency_other_disorder')
154
        widgets = {
155
                'mises_1': Select2MultipleWidget(attrs={'style': 'width: 32em'}),
156
                'mises_2': Select2MultipleWidget(attrs={'style': 'width: 32em'}),
157
                'mises_3': Select2MultipleWidget(attrs={'style': 'width: 32em'}),
158
                }
159

    
160

    
161
    def __init__(self, instance, **kwargs):
162
        super(PhysiologyForm, self).__init__(instance=instance, **kwargs)
163
        self.fields['mises_1'].queryset = \
164
                CodeCFTMEA.objects.filter(axe=1)
165
        self.fields['mises_2'].queryset = \
166
                CodeCFTMEA.objects.filter(axe=2)
167
        self.fields['mises_3'].queryset = \
168
                CodeCFTMEA.objects.filter(axe=3)
169

    
170

    
171
class PaperIDForm(ModelForm):
172
    class Meta:
173
        model = PatientRecord
174
        fields = ('paper_id', )
175

    
176
class PolicyHolderForm(ModelForm):
177
    class Meta:
178
        model = PatientRecord
179
        fields = ('policyholder', 'contact_comment')
180
        widgets = { 
181
                'policyholder': forms.RadioSelect(),
182
                'contact_comment': forms.Textarea(attrs={'cols': 50, 'rows': 2}),
183
                }
184

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

    
188
    class Meta:
189
        model = PatientContact
190
        widgets = {
191
                'key': forms.TextInput(attrs={'size': 4}),
192
                'twinning_rank': forms.TextInput(attrs={'size': 4}),
193
                'health_org': forms.TextInput(attrs={'size': 9}),
194
                'addresses': forms.CheckboxSelectMultiple(),
195
                'contact_comment': forms.Textarea(attrs={'rows': 2}),
196
                }
197

    
198
    def __init__(self, *args, **kwargs):
199
        self.patient = kwargs.pop('patient', None)
200
        super(PatientContactForm, self).__init__(*args,**kwargs)
201
        if self.instance and self.instance.health_center:
202
            self.fields['health_org'].initial = self.instance.health_center.large_regime.code + self.instance.health_center.health_fund + self.instance.health_center.code
203
        if self.patient:
204
            self.fields['addresses'].queryset = self.patient.addresses
205
            self.fields['addresses'].required = False
206

    
207
    def clean(self):
208
        cleaned_data = super(PatientContactForm, self).clean()
209
        health_org = cleaned_data.get('health_org')
210
        other_health_center = cleaned_data.get('other_health_center')
211
        if health_org:
212
            msg = None
213
            lr = None
214
            hc = None
215
            if len(health_org) < 5:
216
                msg = u"Numéro inférieur à 5 chiffres."
217
            else:
218
                try:
219
                    lr = LargeRegime.objects.get(code=health_org[:2])
220
                except:
221
                    msg = u"Grand régime %s inconnu." % health_org[:2]
222
                else:
223
                    hcs = HealthCenter.objects.filter(health_fund=health_org[2:5], large_regime=lr)
224
                    if not hcs:
225
                        msg = u"Caisse %s inconnue." % health_org[2:5]
226
                    elif len(hcs) == 1:
227
                        hc = hcs[0]
228
                        if not other_health_center and len(health_org) == 9:
229
                            other_health_center = health_org[5:9]
230
                    else:
231
                        if len(health_org) == 9:
232
                            hcs = hcs.filter(code=health_org[5:9])
233
                            if not hcs:
234
                                msg = u"Centre %s inconnu." % health_org[5:9]
235
                            elif len(hcs) == 1:
236
                                hc = hcs[0]
237
                            else:
238
                                msg = u"Ceci ne devrait pas arriver, %s n'est pas unique." % health_org
239
                        else:
240
                            msg = "Plusieurs centres possibles, précisez parmi :"
241
                            for hc in hcs:
242
                                msg += " %s" % str(hc)
243
            if msg:
244
                self._errors["health_org"] = self.error_class([msg])
245
            else:
246
                cleaned_data['large_regime'] = lr.code
247
                cleaned_data['health_center'] = hc
248
                cleaned_data['other_health_center'] = other_health_center
249
        return cleaned_data
250

    
251
    def save(self, commit=True):
252
        contact = super(PatientContactForm, self).save(commit=False)
253
        contact.clean()
254
        if commit:
255
            contact.save()
256
            if self.patient and not self.instance.addresses.all():
257
                self.patient.contacts.add(contact)
258
        return contact
259

    
260
class PatientAddressForm(ModelForm):
261

    
262
    class Meta:
263
        model = PatientAddress
264
        widgets = {
265
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
266
                'zip_code': forms.TextInput(attrs={'size': 10}),
267
                'number': forms.TextInput(attrs={'size': 10}),
268
                }
269

    
270

    
271
class CmppHealthCareTreatmentForm(ModelForm):
272
    class Meta:
273
        model = CmppHealthCareTreatment
274
        fields = ('start_date', 'request_date',
275
                'agree_date', 'insist_date', 'end_date', 'act_number',
276
                'prolongation', 'prolongation_date', 'comment', 'patient',
277
                'author')
278
        widgets = {
279
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
280
                'patient': forms.HiddenInput(),
281
                'author': forms.HiddenInput(),
282
                }
283

    
284
    def clean(self):
285
        cleaned_data = super(CmppHealthCareTreatmentForm, self).clean()
286
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
287
            msg = u"Le nombre d'actes ne peut être inférieur au \
288
                nombre d'actes déja pris en charge (%d)." \
289
                    % self.instance.get_nb_acts_cared()
290
            self._errors["act_number"] = self.error_class([msg])
291
        return cleaned_data
292

    
293

    
294
class CmppHealthCareDiagnosticForm(ModelForm):
295
    class Meta:
296
        model = CmppHealthCareDiagnostic
297
        fields = ('start_date', 'request_date',
298
                'agree_date', 'insist_date', 'end_date', 'act_number',
299
                'comment', 'patient', 'author')
300
        widgets = {
301
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
302
                'patient': forms.HiddenInput(),
303
                'author': forms.HiddenInput(),
304
                }
305

    
306
    def clean(self):
307
        cleaned_data = super(CmppHealthCareDiagnosticForm, self).clean()
308
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
309
            msg = u"Le nombre d'actes ne peut être inférieur au \
310
                nombre d'actes déja pris en charge (%d)." \
311
                    % self.instance.get_nb_acts_cared()
312
            self._errors["act_number"] = self.error_class([msg])
313
        return cleaned_data
314

    
315

    
316
class SessadHealthCareNotificationForm(ModelForm):
317
    class Meta:
318
        model = SessadHealthCareNotification
319
        fields = ('start_date', 'end_date',
320
                'request_date', 'agree_date', 'insist_date',
321
                'comment', 'patient', 'author')
322
        widgets = {
323
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
324
                'patient': forms.HiddenInput(),
325
                'author': forms.HiddenInput(),
326
                }
327

    
328

    
329
class SocialisationDurationForm(ModelForm):
330
    school = make_ajax_field(SocialisationDuration, 'school', 'school', False)
331
    class Meta:
332
        model = SocialisationDuration
333
        fields = ('school', 'start_date',
334
            'end_date', 'level', 'contact', 'comment')
335
        widgets = {
336
                'contact': forms.Textarea(attrs={'cols': 39, 'rows': 2}),
337
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
338
                }
339

    
340
class ProtectionStateForm(ModelForm):
341
    class Meta:
342
        model = ProtectionState
343
        fields = ('status', 'start_date', 'end_date', 'comment')
344
        widgets = {
345
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
346
                }
347

    
348
class MDPHRequestForm(ModelForm):
349
    class Meta:
350
        model = MDPHRequest
351
        fields = ('start_date', 'mdph', 'comment')
352
        widgets = {
353
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
354
                }
355

    
356
class MDPHResponseForm(ModelForm):
357
    class Meta:
358
        model = MDPHResponse
359
        fields = ('start_date', 'end_date', 'mdph', 'comment',
360
            'type_aide', 'name', 'rate')
361
        widgets = {
362
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
363
                }
364

    
365
class AvailableRtfTemplates:
366
    def __iter__(self):
367
        if not settings.RTF_TEMPLATES_DIRECTORY:
368
            return iter([])
369
        if not os.path.exists(settings.RTF_TEMPLATES_DIRECTORY):
370
            logger.warning("RTF_TEMPLATES_DIRECTOR %r doesn't exist" % \
371
                    settings.RTF_TEMPLATES_DIRECTORY)
372
            return iter([])
373

    
374
        templates = []
375
        for filename in os.listdir(settings.RTF_TEMPLATES_DIRECTORY):
376
            templates.append((filename, filename[:-4]))
377
        return iter(templates)
378

    
379
class GenerateRtfForm(Form):
380
    template_filename = forms.ChoiceField(choices=AvailableRtfTemplates())
381
    address = forms.CharField(widget=forms.Textarea(attrs={'rows':5}), required=False)
382
    phone_address = forms.CharField(required=False)
383

    
384
    def __init__(self, *args, **kwargs):
385
        super(GenerateRtfForm, self).__init__(*args, **kwargs)
386
        self.fields['template_filename'].choices = AvailableRtfTemplates()
387

    
388
class QuotationsForm(Form):
389

    
390
    def __init__(self, service=None, *args, **kwargs):
391
        self.service = service
392
        super(QuotationsForm, self).__init__(*args, **kwargs)
393
        self.fields['states'].queryset = Status.objects.filter(services=service)
394

    
395
    states = forms.ModelMultipleChoiceField(queryset=Status.objects.all(),
396
            initial=Status.objects.all(),
397
            widget=forms.CheckboxSelectMultiple(attrs={'class':'checkbox_state'}))
398
    date_actes_start = forms.DateField(label=u'Date', localize=True)
399
    date_actes_end = forms.DateField(label=u'Date', localize=True)
400
    without_quotations = forms.BooleanField()
401

    
402
class PatientRecordPrintForm(Form):
403

    
404
    prev_appointment_start_date = forms.DateField(label=u'De', required=False)
405
    prev_appointment_end_date = forms.DateField(label=u'au', required=False)
406
    next_appointment_start_date = forms.DateField(label=u'De', required=False)
407
    next_appointment_end_date = forms.DateField(label=u'au', required=False)
(3-3/12)