Project

General

Profile

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

calebasse / calebasse / dossiers / forms.py @ 6188a681

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

    
3
import os
4

    
5
from datetime import date
6

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

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

    
19
from ajax_select import make_ajax_field
20

    
21

    
22
class EditPatientRecordForm(ModelForm):
23
    class Meta:
24
        model = PatientRecord
25

    
26
class SearchForm(Form):
27
    last_name = forms.CharField(label=u'Nom', required=False)
28
    first_name = forms.CharField(label=u'Prénom', required=False)
29
    folder_id = forms.CharField(label=u'Numéro de dossier', required=False)
30
    social_security_id = forms.CharField(label=u"Numéro d'assuré social", required=False)
31
    states = forms.ModelMultipleChoiceField(queryset=Status.objects.all(),
32
            initial=Status.objects.exclude(type='CLOS'),
33
            widget=forms.CheckboxSelectMultiple(attrs={'class':'checkbox_state'}))
34

    
35
    def __init__(self, service=None, *args, **kwargs):
36
        self.service = service
37
        super(SearchForm, self).__init__(*args, **kwargs)
38
        self.fields['states'].queryset = Status.objects.filter(services=service)
39

    
40

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

    
49
    def clean_date(self):
50
        patient = PatientRecord.objects.get(id=self.cleaned_data['patient_id'])
51
        date_selected = self.cleaned_data['date']
52
        current_state = patient.get_state()
53
        if date_selected < current_state.date_selected.date():
54
            raise forms.ValidationError(u"La date ne peut pas être antérieure à celle du précédent changement d'état.")
55
        return self.cleaned_data['date']
56

    
57
class PatientStateForm(ModelForm):
58
    date_selected = forms.DateTimeField(label=u'Date', localize=True)
59
    comment = forms.CharField(label='Commentaire',
60
            required=False, widget=forms.Textarea)
61

    
62
    class Meta:
63
        model = FileState
64
        fields = ('status', 'date_selected', 'comment')
65
        widgets = {
66
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
67
                }
68

    
69
    def __init__(self, service=None, *args, **kwargs):
70
        self.service = service
71
        super(PatientStateForm, self).__init__(*args, **kwargs)
72
        self.fields['status'].queryset = Status.objects.filter(services=service)
73

    
74
    def clean_date_selected(self):
75
        date_selected = self.cleaned_data['date_selected']
76
        next_state = self.instance.get_next_state()
77
        if self.instance.previous_state:
78
            if date_selected < self.instance.previous_state.date_selected:
79
                raise forms.ValidationError(u"La date ne peut pas être antérieure à celle du précédent changement d'état.")
80
        if next_state:
81
            if date_selected > next_state.date_selected:
82
                raise forms.ValidationError(u"La date ne peut pas être postérieure à celle du changement d'état suivant.")
83
        return self.cleaned_data['date_selected']
84

    
85
class NewPatientRecordForm(ModelForm):
86
    date_selected = forms.DateField(label=u"Date de contact", localize=True)
87

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

    
93
    class Meta:
94
        model = PatientRecord
95
        fields = ('last_name', 'first_name')
96

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

    
106
class CivilStatusForm(ModelForm):
107
    class Meta:
108
        model = PatientRecord
109
        fields = ('first_name', 'last_name', 'birthdate', 'birthplace', 'gender', 'nationality')
110

    
111

    
112
class FilteredSelectMultipleMise(django.contrib.admin.widgets.FilteredSelectMultiple):
113
    def __init__(self, **kwargs):
114
        super(FilteredSelectMultipleMise, self).__init__(u'Catégorie', False)
115

    
116

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

    
125
    class Meta:
126
        model = PatientRecord
127
        fields = ('size', 'weight', 'pregnancy_term',
128
            'cranium_perimeter', 'chest_perimeter', 'apgar_score_one',
129
            'apgar_score_two', 'mises_1', 'mises_2', 'mises_3',
130
            'deficiency_intellectual', 'deficiency_autism_and_other_ted',
131
            'deficiency_mental_disorder', 'deficiency_learning_disorder',
132
            'deficiency_auditory', 'deficiency_visual', 'deficiency_motor',
133
            'deficiency_metabolic_disorder', 'deficiency_brain_damage',
134
            'deficiency_polyhandicap', 'deficiency_behavioral_disorder',
135
            'deficiency_in_diagnostic', 'deficiency_other_disorder')
136
        widgets = {
137
            'mises_1': FilteredSelectMultipleMise,
138
            'mises_2': FilteredSelectMultipleMise,
139
            'mises_3': FilteredSelectMultipleMise,
140
        }
141

    
142
    def __init__(self, instance, **kwargs):
143
        super(PhysiologyForm, self).__init__(instance=instance, **kwargs)
144
        self.fields['mises_1'].queryset = \
145
                CodeCFTMEA.objects.filter(axe=1)
146
        self.fields['mises_2'].queryset = \
147
                CodeCFTMEA.objects.filter(axe=2)
148
        self.fields['mises_3'].queryset = \
149
                CodeCFTMEA.objects.filter(axe=3)
150

    
151

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

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

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

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

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

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

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

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

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

    
210
    def __init__(self, *args, **kwargs):
211
        self.patient = kwargs.pop('patient', None)
212
        super(PatientContactForm, self).__init__(*args,**kwargs)
213
        if self.instance and self.instance.health_center:
214
            self.fields['health_org'].initial = self.instance.health_center.large_regime.code + self.instance.health_center.health_fund + self.instance.health_center.code
215
        if self.patient:
216
            self.fields['addresses'].queryset = self.patient.addresses
217
            self.fields['addresses'].required = False
218

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

    
263
    def save(self, commit=True):
264
        contact = super(PatientContactForm, self).save(commit=False)
265
        contact.clean()
266
        if commit:
267
            contact.save()
268
            if self.patient and not self.instance.addresses.all():
269
                self.patient.contacts.add(contact)
270
        return contact
271

    
272
class PatientAddressForm(ModelForm):
273

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

    
282

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

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

    
305

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

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

    
327

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

    
340

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

    
352
class ProtectionStateForm(ModelForm):
353
    class Meta:
354
        model = ProtectionState
355
        fields = ('status', 'start_date', 'end_date', 'comment')
356
        widgets = {
357
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
358
                }
359

    
360
class MDPHRequestForm(ModelForm):
361
    class Meta:
362
        model = MDPHRequest
363
        fields = ('start_date', 'mdph', 'comment')
364
        widgets = {
365
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
366
                }
367

    
368
class MDPHResponseForm(ModelForm):
369
    class Meta:
370
        model = MDPHResponse
371
        fields = ('start_date', 'end_date', 'mdph', 'comment',
372
            'type_aide', 'name', 'rate')
373
        widgets = {
374
                'comment': forms.Textarea(attrs={'cols': 39, 'rows': 4}),
375
                }
376

    
377
class AvailableRtfTemplates:
378
    def __iter__(self):
379
        if not settings.RTF_TEMPLATES_DIRECTORY:
380
            return iter([])
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()
(3-3/11)