Project

General

Profile

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

calebasse / calebasse / dossiers / forms.py @ d17efc19

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 AddrCommentForm(ModelForm):
177
    class Meta:
178
        model = PatientRecord
179
        fields = ('addresses_contacts_comment', )
180
        widgets = {
181
                'addresses_contacts_comment': forms.Textarea(attrs={'cols': 50, 'rows': 2}),
182
                }
183

    
184
class PolicyHolderForm(ModelForm):
185
    class Meta:
186
        model = PatientRecord
187
        fields = ('policyholder',)
188
        widgets = {
189
                'policyholder': forms.RadioSelect(),
190
                }
191

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

    
195
    class Meta:
196
        model = PatientContact
197
        widgets = {
198
                'key': forms.TextInput(attrs={'size': 4}),
199
                'twinning_rank': forms.TextInput(attrs={'size': 4}),
200
                'health_org': forms.TextInput(attrs={'size': 9}),
201
                'addresses': forms.CheckboxSelectMultiple(),
202
                'contact_comment': forms.Textarea(attrs={'rows': 2}),
203
                }
204

    
205
    def __init__(self, *args, **kwargs):
206
        self.patient = kwargs.pop('patient', None)
207
        super(PatientContactForm, self).__init__(*args,**kwargs)
208
        if self.instance and self.instance.health_center:
209
            self.fields['health_org'].initial = self.instance.health_center.large_regime.code + self.instance.health_center.health_fund + self.instance.health_center.code
210
        if self.patient:
211
            self.fields['addresses'].queryset = self.patient.addresses
212
            self.fields['addresses'].required = False
213

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

    
258
    def save(self, commit=True):
259
        contact = super(PatientContactForm, self).save(commit=False)
260
        contact.clean()
261
        if commit:
262
            contact.save()
263
            if self.patient and not self.instance.addresses.all():
264
                self.patient.contacts.add(contact)
265
        return contact
266

    
267
class PatientAddressForm(ModelForm):
268

    
269
    class Meta:
270
        model = PatientAddress
271
        widgets = {
272
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
273
                'zip_code': forms.TextInput(attrs={'size': 10}),
274
                'number': forms.TextInput(attrs={'size': 10}),
275
                }
276

    
277

    
278
class CmppHealthCareTreatmentForm(ModelForm):
279
    class Meta:
280
        model = CmppHealthCareTreatment
281
        fields = ('start_date', 'request_date',
282
                'agree_date', 'insist_date', 'end_date', 'act_number',
283
                'prolongation', 'prolongation_date', 'comment', 'patient',
284
                'author')
285
        widgets = {
286
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
287
                'patient': forms.HiddenInput(),
288
                'author': forms.HiddenInput(),
289
                }
290

    
291
    def clean(self):
292
        cleaned_data = super(CmppHealthCareTreatmentForm, self).clean()
293
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
294
            msg = u"Le nombre d'actes ne peut être inférieur au \
295
                nombre d'actes déja pris en charge (%d)." \
296
                    % self.instance.get_nb_acts_cared()
297
            self._errors["act_number"] = self.error_class([msg])
298
        return cleaned_data
299

    
300

    
301
class CmppHealthCareDiagnosticForm(ModelForm):
302
    class Meta:
303
        model = CmppHealthCareDiagnostic
304
        fields = ('start_date', 'request_date',
305
                'agree_date', 'insist_date', 'end_date', 'act_number',
306
                'comment', 'patient', 'author')
307
        widgets = {
308
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
309
                'patient': forms.HiddenInput(),
310
                'author': forms.HiddenInput(),
311
                }
312

    
313
    def clean(self):
314
        cleaned_data = super(CmppHealthCareDiagnosticForm, self).clean()
315
        if self.instance.pk and cleaned_data.get('act_number') < self.instance.get_nb_acts_cared():
316
            msg = u"Le nombre d'actes ne peut être inférieur au \
317
                nombre d'actes déja pris en charge (%d)." \
318
                    % self.instance.get_nb_acts_cared()
319
            self._errors["act_number"] = self.error_class([msg])
320
        return cleaned_data
321

    
322

    
323
class SessadHealthCareNotificationForm(ModelForm):
324
    class Meta:
325
        model = SessadHealthCareNotification
326
        fields = ('start_date', 'end_date',
327
                'request_date', 'agree_date', 'insist_date',
328
                'comment', 'patient', 'author')
329
        widgets = {
330
                'comment': forms.Textarea(attrs={'cols': 40, 'rows': 4}),
331
                'patient': forms.HiddenInput(),
332
                'author': forms.HiddenInput(),
333
                }
334

    
335

    
336
class SocialisationDurationForm(ModelForm):
337
    school = make_ajax_field(SocialisationDuration, 'school', 'school', False)
338
    class Meta:
339
        model = SocialisationDuration
340
        fields = ('school', 'start_date',
341
            'end_date', 'level', 'contact', 'comment')
342
        widgets = {
343
                'contact': forms.Textarea(attrs={'cols': 39, 'rows': 2}),
344
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
345
                }
346

    
347
class ProtectionStateForm(ModelForm):
348
    class Meta:
349
        model = ProtectionState
350
        fields = ('status', 'start_date', 'end_date', 'comment')
351
        widgets = {
352
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
353
                }
354

    
355
class MDPHRequestForm(ModelForm):
356
    class Meta:
357
        model = MDPHRequest
358
        fields = ('start_date', 'mdph', 'comment')
359
        widgets = {
360
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
361
                }
362

    
363
class MDPHResponseForm(ModelForm):
364
    class Meta:
365
        model = MDPHResponse
366
        fields = ('start_date', 'end_date', 'mdph', 'comment',
367
            'type_aide', 'name', 'rate')
368
        widgets = {
369
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
370
                }
371

    
372
class AvailableRtfTemplates:
373
    def __iter__(self):
374
        if not settings.RTF_TEMPLATES_DIRECTORY:
375
            return iter([])
376
        if not os.path.exists(settings.RTF_TEMPLATES_DIRECTORY):
377
            logger.warning("RTF_TEMPLATES_DIRECTOR %r doesn't exist" % \
378
                    settings.RTF_TEMPLATES_DIRECTORY)
379
            return iter([])
380

    
381
        templates = []
382
        for filename in os.listdir(settings.RTF_TEMPLATES_DIRECTORY):
383
            templates.append((filename, filename[:-4]))
384
        return iter(templates)
385

    
386
class GenerateRtfForm(Form):
387
    template_filename = forms.ChoiceField(choices=AvailableRtfTemplates())
388
    address = forms.CharField(widget=forms.Textarea(attrs={'rows':5}), required=False)
389
    phone_address = forms.CharField(required=False)
390

    
391
    def __init__(self, *args, **kwargs):
392
        super(GenerateRtfForm, self).__init__(*args, **kwargs)
393
        self.fields['template_filename'].choices = AvailableRtfTemplates()
394

    
395
class QuotationsForm(Form):
396

    
397
    def __init__(self, service=None, *args, **kwargs):
398
        self.service = service
399
        super(QuotationsForm, self).__init__(*args, **kwargs)
400
        self.fields['states'].queryset = Status.objects.filter(services=service)
401

    
402
    states = forms.ModelMultipleChoiceField(queryset=Status.objects.all(),
403
            initial=Status.objects.all(),
404
            widget=forms.CheckboxSelectMultiple(attrs={'class':'checkbox_state'}))
405
    date_actes_start = forms.DateField(label=u'Date', localize=True)
406
    date_actes_end = forms.DateField(label=u'Date', localize=True)
407
    without_quotations = forms.BooleanField()
408

    
409
class PatientRecordPrintForm(Form):
410

    
411
    prev_appointment_start_date = forms.DateField(label=u'De', required=False)
412
    prev_appointment_end_date = forms.DateField(label=u'au', required=False)
413
    next_appointment_start_date = forms.DateField(label=u'De', required=False)
414
    next_appointment_end_date = forms.DateField(label=u'au', required=False)
(3-3/12)