Project

General

Profile

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

calebasse / calebasse / dossiers / views.py @ 76974b6f

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

    
3
import os
4

    
5
from datetime import datetime
6

    
7
from django.conf import settings
8
from django.core.urlresolvers import reverse_lazy
9
from django.db import models
10
from django.http import HttpResponseRedirect, HttpResponse
11
from django.views.generic import View
12
from django.views.generic.edit import DeleteView, FormMixin
13
from django.contrib import messages
14

    
15
from calebasse import cbv
16
from calebasse.doc_templates import make_doc_from_template
17
from calebasse.dossiers import forms
18
from calebasse.agenda.models import Event, EventWithAct
19
from calebasse.actes.models import Act
20
from calebasse.agenda.appointments import Appointment
21
from calebasse.dossiers.models import (PatientRecord, PatientContact,
22
        PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
23
        CmppHealthCareDiagnostic, SessadHealthCareNotification, HealthCare)
24
from calebasse.dossiers.states import STATES_MAPPING, STATE_CHOICES_TYPE, STATES_BTN_MAPPER
25
from calebasse.ressources.models import (Service,
26
    SocialisationDuration, MDPHRequest, MDPHResponse)
27

    
28

    
29
def get_next_rdv(patient_record):
30
    next_rdv = {}
31
    event = Event.objects.next_appointment(patient_record)
32
    if event:
33
        next_rdv['start_datetime'] = event.start_time
34
        next_rdv['participants'] = event.participants.all()
35
        next_rdv['act_type'] = event.eventact.act_type
36
    return next_rdv
37

    
38
def get_last_rdv(patient_record):
39
    last_rdv = {}
40
    event = Event.objects.last_appointment(patient_record)
41
    if event:
42
        last_rdv['start_datetime'] = event.start_time
43
        last_rdv['participants'] = event.participants.all()
44
        last_rdv['act_type'] = event.eventact.act_type
45
    return last_rdv
46

    
47
class NewPatientRecordView(cbv.FormView, cbv.ServiceViewMixin):
48
    form_class = forms.NewPatientRecordForm
49
    template_name = 'dossiers/patientrecord_new.html'
50
    success_url = '..'
51
    patient = None
52

    
53
    def post(self, request, *args, **kwarg):
54
        self.user = request.user
55
        return super(NewPatientRecordView, self).post(request, *args, **kwarg)
56

    
57
    def form_valid(self, form):
58
        self.patient = create_patient(form.data['first_name'], form.data['last_name'], self.service,
59
                self.user, date_selected=datetime.strptime(form.data['date_selected'], "%d/%m/%Y"))
60
        return super(NewPatientRecordView, self).form_valid(form)
61

    
62
    def get_success_url(self):
63
        return '%s/view' % self.patient.id
64

    
65
new_patient_record = NewPatientRecordView.as_view()
66

    
67
def dynamic_patient_contact_form(patientrecord_id):
68
    patient = PatientRecord.objects.get(id=patientrecord_id)
69
    class DynamicPatientContactForm(forms.PatientContactForm):
70
        def __init__(self, *args, **kwargs):
71
            super(DynamicPatientContactForm, self).__init__(*args, **kwargs)
72
            self.fields['addresses'].queryset = patient.addresses
73
    return DynamicPatientContactForm
74

    
75
class NewPatientContactView(cbv.CreateView):
76
    model = PatientContact
77
    template_name = 'dossiers/patientcontact_new.html'
78
    success_url = '../view#tab=2'
79

    
80
    def get(self, request, *args, **kwargs):
81
        request.session['patientrecord_id'] = kwargs['patientrecord_id']
82
        self.form_class = dynamic_patient_contact_form(kwargs['patientrecord_id'])
83
        return super(NewPatientContactView, self).get(request, *args, **kwargs)
84

    
85
new_patient_contact = NewPatientContactView.as_view()
86

    
87
class UpdatePatientContactView(cbv.UpdateView):
88
    model = PatientContact
89
    template_name = 'dossiers/patientcontact_new.html'
90
    success_url = '../../view#tab=2'
91

    
92
    def get(self, request, *args, **kwargs):
93
        request.session['patientrecord_id'] = kwargs['patientrecord_id']
94
        self.form_class = dynamic_patient_contact_form(kwargs['patientrecord_id'])
95
        return super(UpdatePatientContactView, self).get(request, *args, **kwargs)
96

    
97
update_patient_contact = UpdatePatientContactView.as_view()
98

    
99
class DeletePatientContactView(cbv.DeleteView):
100
    model = PatientContact
101
    form_class = forms.PatientContactForm
102
    template_name = 'dossiers/patientcontact_confirm_delete.html'
103
    success_url = '../../view#tab=2'
104

    
105
    def post(self, request, *args, **kwargs):
106
        try:
107
            patient = PatientRecord.objects.get(id=kwargs.get('pk'))
108
        except PatientRecord.DoesNotExist:
109
            return super(DeletePatientContactView, self).post(request, *args, **kwargs)
110
        # the contact is also a patient record; it shouldn't be deleted; just
111
        # altered to remove an address
112
        patient.addresses.remove(self.request.GET['address'])
113
        return HttpResponseRedirect(self.get_success_url())
114

    
115
delete_patient_contact = DeletePatientContactView.as_view()
116

    
117
class NewPatientAddressView(cbv.CreateView):
118
    model = PatientAddress
119
    form_class = forms.PatientAddressForm
120
    template_name = 'dossiers/patientaddress_new.html'
121
    success_url = '../view#tab=2'
122

    
123
    def get_success_url(self):
124
        return self.success_url
125

    
126
    def form_valid(self, form):
127
        patientaddress = form.save()
128
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
129
        patientrecord.addresses.add(patientaddress)
130
        return HttpResponseRedirect(self.get_success_url())
131

    
132
new_patient_address = NewPatientAddressView.as_view()
133

    
134
class UpdatePatientAddressView(cbv.UpdateView):
135
    model = PatientAddress
136
    form_class = forms.PatientAddressForm
137
    template_name = 'dossiers/patientaddress_new.html'
138
    success_url = '../../view#tab=2'
139

    
140
update_patient_address = UpdatePatientAddressView.as_view()
141

    
142
class DeletePatientAddressView(cbv.DeleteView):
143
    model = PatientAddress
144
    form_class = forms.PatientAddressForm
145
    template_name = 'dossiers/patientaddress_confirm_delete.html'
146
    success_url = '../../view#tab=2'
147

    
148
delete_patient_address = DeletePatientAddressView.as_view()
149

    
150

    
151
class NewHealthCareView(cbv.CreateView):
152

    
153
    def get_initial(self):
154
        initial = super(NewHealthCareView, self).get_initial()
155
        initial['author'] = self.request.user.id
156
        initial['patient'] = self.kwargs['patientrecord_id']
157
        return initial
158

    
159
new_healthcare_treatment = \
160
    NewHealthCareView.as_view(model=CmppHealthCareTreatment,
161
        template_name = 'dossiers/generic_form.html',
162
        success_url = '../view#tab=3',
163
        form_class=forms.CmppHealthCareTreatmentForm)
164
new_healthcare_diagnostic = \
165
    NewHealthCareView.as_view(model=CmppHealthCareDiagnostic,
166
        template_name = 'dossiers/generic_form.html',
167
        success_url = '../view#tab=3',
168
        form_class=forms.CmppHealthCareDiagnosticForm)
169
new_healthcare_notification = \
170
    NewHealthCareView.as_view(model=SessadHealthCareNotification,
171
        template_name = 'dossiers/generic_form.html',
172
        success_url = '../view#tab=3',
173
        form_class=forms.SessadHealthCareNotificationForm)
174
update_healthcare_treatment = \
175
    cbv.UpdateView.as_view(model=CmppHealthCareTreatment,
176
        template_name = 'dossiers/generic_form.html',
177
        success_url = '../../view#tab=3',
178
        form_class=forms.CmppHealthCareTreatmentForm)
179
update_healthcare_diagnostic = \
180
    cbv.UpdateView.as_view(model=CmppHealthCareDiagnostic,
181
        template_name = 'dossiers/generic_form.html',
182
        success_url = '../../view#tab=3',
183
        form_class=forms.CmppHealthCareDiagnosticForm)
184
update_healthcare_notification = \
185
    cbv.UpdateView.as_view(model=SessadHealthCareNotification,
186
        template_name = 'dossiers/generic_form.html',
187
        success_url = '../../view#tab=3',
188
        form_class=forms.SessadHealthCareNotificationForm)
189
delete_healthcare_treatment = \
190
    cbv.DeleteView.as_view(model=CmppHealthCareTreatment,
191
        template_name = 'dossiers/generic_confirm_delete.html',
192
        success_url = '../../view#tab=3')
193
delete_healthcare_diagnostic = \
194
    cbv.DeleteView.as_view(model=CmppHealthCareDiagnostic,
195
        template_name = 'dossiers/generic_confirm_delete.html',
196
        success_url = '../../view#tab=3')
197
delete_healthcare_notification = \
198
    cbv.DeleteView.as_view(model=SessadHealthCareNotification,
199
        template_name = 'dossiers/generic_confirm_delete.html',
200
        success_url = '../../view#tab=3')
201

    
202

    
203
class StateFormView(cbv.FormView):
204
    template_name = 'dossiers/state.html'
205
    form_class = forms.StateForm
206
    success_url = './view#tab=0'
207

    
208
    def post(self, request, *args, **kwarg):
209
        self.user = request.user
210
        return super(StateFormView, self).post(request, *args, **kwarg)
211

    
212
    def form_valid(self, form):
213
        service = Service.objects.get(id=form.data['service_id'])
214
        status = Status.objects.filter(services=service).filter(type=form.data['state_type'])
215
        patient = PatientRecord.objects.get(id=form.data['patient_id'])
216
        date_selected = datetime.strptime(form.data['date'], "%d/%m/%Y")
217
        patient.set_state(status[0], self.user, date_selected, form.data['comment'])
218
        return super(StateFormView, self).form_valid(form)
219

    
220
state_form = StateFormView.as_view()
221

    
222

    
223
class PatientRecordView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
224
    model = PatientRecord
225
    forms_classes = {
226
            'general': forms.GeneralForm,
227
            'id': forms.CivilStatusForm,
228
            'physiology': forms.PhysiologyForm,
229
            'inscription': forms.InscriptionForm,
230
            'family': forms.FamilyForm,
231
            'transport': forms.TransportFrom,
232
            'followup': forms.FollowUpForm,
233
            'policyholder': forms.PolicyHolderForm
234
            }
235
    template_name = 'dossiers/patientrecord_update.html'
236
    success_url = './view'
237

    
238
    def get_success_url(self):
239
        if self.request.POST.has_key('tab'):
240
            return self.success_url + '#tab=' + self.request.POST['tab']
241
        else:
242
            return self.success_url
243

    
244
    def get_context_data(self, **kwargs):
245
        ctx = super(PatientRecordView, self).get_context_data(**kwargs)
246
        ctx['next_rdv'] = get_next_rdv(ctx['object'])
247
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
248
        ctx['initial_state'] = ctx['object'].get_initial_state()
249
        current_state = ctx['object'].get_current_state()
250
        if STATES_MAPPING.has_key(current_state.status.type):
251
            state = STATES_MAPPING[current_state.status.type]
252
        else:
253
            state = current_state.status.name
254
        ctx['current_state'] = current_state
255
        ctx['service_id'] = self.service.id
256
        ctx['states'] = FileState.objects.filter(patient=self.object).filter(status__services=self.service)
257
        ctx['next_rdvs'] = []
258
        for act in Act.objects.next_acts(ctx['object']).select_related():
259
            state = act.get_state()
260
            if not state.previous_state:
261
                state = None
262
            ctx['next_rdvs'].append((act.parent_event, state))
263
        ctx['last_rdvs'] = []
264
        for act in Act.objects.last_acts(ctx['object']):
265
            state = act.get_state()
266
            if not state.previous_state:
267
                state = None
268
            ctx['last_rdvs'].append((act.parent_event, state))
269
        ctx['status'] = []
270
        if ctx['object'].service.name == "CMPP":
271
            if ctx['object'].last_state.status.type == "ACCUEIL":
272
                # Inscription automatique au premier acte facturable valide
273
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
274
                        STATES_BTN_MAPPER['DIAGNOSTIC'],
275
                        STATES_BTN_MAPPER['TRAITEMENT']]
276
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
277
                # Passage automatique en diagnostic ou traitement
278
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
279
                        STATES_BTN_MAPPER['DIAGNOSTIC'],
280
                        STATES_BTN_MAPPER['TRAITEMENT']]
281
            elif ctx['object'].last_state.status.type == "DIAGNOSTIC":
282
                # Passage automatique en traitement
283
                ctx['status'] = [STATES_BTN_MAPPER['TRAITEMENT'],
284
                        STATES_BTN_MAPPER['CLOS'],
285
                        STATES_BTN_MAPPER['ACCUEIL']]
286
            elif ctx['object'].last_state.status.type == "TRAITEMENT":
287
                # Passage automatique en diagnostic si on ajoute une prise en charge diagnostic,
288
                # ce qui est faisable dans l'onglet prise en charge par un bouton visible sous conditions
289
                ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
290
                        STATES_BTN_MAPPER['CLOS'],
291
                        STATES_BTN_MAPPER['ACCUEIL']]
292
            elif ctx['object'].last_state.status.type == "CLOS":
293
                # Passage automatique en diagnostic ou traitement
294
                ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
295
                        STATES_BTN_MAPPER['TRAITEMENT'],
296
                        STATES_BTN_MAPPER['ACCUEIL']]
297
        elif ctx['object'].service.name == "CAMSP":
298
            if ctx['object'].last_state.status.type == "ACCUEIL":
299
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
300
                        STATES_BTN_MAPPER['BILAN']]
301
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
302
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
303
                        STATES_BTN_MAPPER['BILAN'],
304
                        STATES_BTN_MAPPER['SURVEILLANCE'],
305
                        STATES_BTN_MAPPER['SUIVI'],
306
                        STATES_BTN_MAPPER['CLOS']]
307
            elif ctx['object'].last_state.status.type == "BILAN":
308
                ctx['status'] = [STATES_BTN_MAPPER['SURVEILLANCE'],
309
                        STATES_BTN_MAPPER['SUIVI'],
310
                        STATES_BTN_MAPPER['CLOS'],
311
                        STATES_BTN_MAPPER['ACCUEIL']]
312
            elif ctx['object'].last_state.status.type == "SURVEILLANCE":
313
                ctx['status'] = [STATES_BTN_MAPPER['SUIVI'],
314
                        STATES_BTN_MAPPER['CLOS'],
315
                        STATES_BTN_MAPPER['ACCUEIL'],
316
                        STATES_BTN_MAPPER['BILAN']]
317
            elif ctx['object'].last_state.status.type == "SUIVI":
318
                ctx['status'] = [STATES_BTN_MAPPER['CLOS'],
319
                        STATES_BTN_MAPPER['ACCUEIL'],
320
                        STATES_BTN_MAPPER['BILAN'],
321
                        STATES_BTN_MAPPER['SURVEILLANCE']]
322
            elif ctx['object'].last_state.status.type == "CLOS":
323
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
324
                        STATES_BTN_MAPPER['BILAN'],
325
                        STATES_BTN_MAPPER['SURVEILLANCE'],
326
                        STATES_BTN_MAPPER['SUIVI']]
327
        elif ctx['object'].service.name == "SESSAD TED" or ctx['object'].service.name == "SESSAD DYS":
328
            if ctx['object'].last_state.status.type == "ACCUEIL":
329
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
330
                        STATES_BTN_MAPPER['TRAITEMENT']]
331
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
332
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
333
                        STATES_BTN_MAPPER['TRAITEMENT'],
334
                        STATES_BTN_MAPPER['CLOS']]
335
            elif ctx['object'].last_state.status.type == "TRAITEMENT":
336
                ctx['status'] = [STATES_BTN_MAPPER['CLOS'],
337
                        STATES_BTN_MAPPER['ACCUEIL']]
338
            elif ctx['object'].last_state.status.type == "CLOS":
339
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
340
                        STATES_BTN_MAPPER['TRAITEMENT']]
341
        ctx['can_rediag'] = self.object.create_diag_healthcare(self.request.user)
342
        ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
343
        return ctx
344

    
345
    def form_valid(self, form):
346
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
347
        return super(PatientRecordView, self).form_valid(form)
348

    
349

    
350
patient_record = PatientRecordView.as_view()
351

    
352
class PatientRecordsHomepageView(cbv.ListView):
353
    model = PatientRecord
354
    template_name = 'dossiers/index.html'
355

    
356
    def get_queryset(self):
357
        qs = super(PatientRecordsHomepageView, self).get_queryset()
358
        first_name = self.request.GET.get('first_name')
359
        last_name = self.request.GET.get('last_name')
360
        paper_id = self.request.GET.get('paper_id')
361
        id = self.request.GET.get('id')
362
        states = self.request.GET.getlist('states')
363
        social_security_id = self.request.GET.get('social_security_id')
364
        if last_name:
365
            qs = qs.filter(last_name__icontains=last_name)
366
        if first_name:
367
            qs = qs.filter(first_name__icontains=first_name)
368
        if paper_id:
369
            qs = qs.filter(paper_id__contains=paper_id)
370
        if id:
371
            qs = qs.filter(id__contains=id)
372
        if social_security_id:
373
            qs = qs.filter(social_security_id__contains=social_security_id)
374
        if states:
375
            status_types = ['BILAN', 'SURVEILLANCE', 'SUIVI']
376
            for state in states:
377
                status_types.append(STATE_CHOICES_TYPE[state])
378
            qs = qs.filter(last_state__status__type__in=status_types)
379
        else:
380
            qs = qs.filter(last_state__status__type__in="")
381
        qs = qs.filter(service=self.service).order_by('last_name')
382
        return qs
383

    
384
    def get_context_data(self, **kwargs):
385
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
386
        ctx['search_form'] = forms.SearchForm(data=self.request.GET or None)
387
        ctx['patient_records'] = []
388
        ctx['stats'] = {"dossiers": 0,
389
                "En_contact": 0,
390
                "Fin_daccueil": 0,
391
                "Diagnostic": 0,
392
                "Traitement": 0,
393
                "Clos": 0}
394
        if self.request.GET:
395
            for patient_record in ctx['object_list'].filter():
396
                ctx['stats']['dossiers'] += 1
397
                next_rdv = get_next_rdv(patient_record)
398
                last_rdv = get_last_rdv(patient_record)
399
                current_state = patient_record.get_current_state()
400
                if STATES_MAPPING.has_key(current_state.status.type):
401
                    state = STATES_MAPPING[current_state.status.type]
402
                else:
403
                    state = current_state.status.name
404
                state_class = current_state.status.type.lower()
405
                ctx['patient_records'].append(
406
                        {
407
                            'object': patient_record,
408
                            'next_rdv': next_rdv,
409
                            'last_rdv': last_rdv,
410
                            'state': state,
411
                            'state_class': state_class
412
                            }
413
                        )
414
                state = state.replace(' ', '_')
415
                state = state.replace("'", '')
416
                if not ctx['stats'].has_key(state):
417
                    ctx['stats'][state] = 0
418
                ctx['stats'][state] += 1
419

    
420
        return ctx
421

    
422
patientrecord_home = PatientRecordsHomepageView.as_view()
423

    
424
class PatientRecordDeleteView(DeleteView):
425
    model = PatientRecord
426
    success_url = ".."
427
    template_name = 'dossiers/patientrecord_confirm_delete.html'
428

    
429
patientrecord_delete = PatientRecordDeleteView.as_view()
430

    
431

    
432
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
433
    model = PatientRecord
434
    form_class = forms.PaperIDForm
435
    template_name = 'dossiers/generic_form.html'
436
    success_url = '../..'
437

    
438
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
439

    
440

    
441
class NewSocialisationDurationView(cbv.CreateView):
442
    model = SocialisationDuration
443
    form_class = forms.SocialisationDurationForm
444
    template_name = 'dossiers/generic_form.html'
445
    success_url = '../view#tab=6'
446

    
447
    def get_success_url(self):
448
        return self.success_url
449

    
450
    def get(self, request, *args, **kwargs):
451
        if kwargs.has_key('patientrecord_id'):
452
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
453
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
454

    
455
    def form_valid(self, form):
456
        duration = form.save()
457
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
458
        patientrecord.socialisation_durations.add(duration)
459
        return HttpResponseRedirect(self.get_success_url())
460

    
461
new_socialisation_duration = NewSocialisationDurationView.as_view()
462

    
463
class UpdateSocialisationDurationView(cbv.UpdateView):
464
    model = SocialisationDuration
465
    form_class = forms.SocialisationDurationForm
466
    template_name = 'dossiers/generic_form.html'
467
    success_url = '../../view#tab=6'
468

    
469
    def get(self, request, *args, **kwargs):
470
        if kwargs.has_key('patientrecord_id'):
471
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
472
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
473

    
474
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
475

    
476
class DeleteSocialisationDurationView(cbv.DeleteView):
477
    model = SocialisationDuration
478
    form_class = forms.SocialisationDurationForm
479
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
480
    success_url = '../../view#tab=6'
481

    
482
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
483

    
484

    
485
class NewMDPHRequestView(cbv.CreateView):
486
    def get(self, request, *args, **kwargs):
487
        if kwargs.has_key('patientrecord_id'):
488
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
489
        return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
490

    
491
    def form_valid(self, form):
492
        request = form.save()
493
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
494
        patientrecord.mdph_requests.add(request)
495
        return HttpResponseRedirect(self.success_url)
496

    
497
class UpdateMDPHRequestView(cbv.UpdateView):
498
    def get(self, request, *args, **kwargs):
499
        if kwargs.has_key('patientrecord_id'):
500
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
501
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
502

    
503

    
504
new_mdph_request = \
505
    NewMDPHRequestView.as_view(model=MDPHRequest,
506
        template_name = 'dossiers/generic_form.html',
507
        success_url = '../view#tab=6',
508
        form_class=forms.MDPHRequestForm)
509
update_mdph_request = \
510
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
511
        template_name = 'dossiers/generic_form.html',
512
        success_url = '../../view#tab=6',
513
        form_class=forms.MDPHRequestForm)
514
delete_mdph_request = \
515
    cbv.DeleteView.as_view(model=MDPHRequest,
516
        template_name = 'dossiers/generic_confirm_delete.html',
517
        success_url = '../../view#tab=6')
518

    
519
class NewMDPHResponseView(cbv.CreateView):
520
    def get(self, request, *args, **kwargs):
521
        if kwargs.has_key('patientrecord_id'):
522
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
523
        return super(NewMDPHResponseView, self).get(request, *args, **kwargs)
524

    
525
    def form_valid(self, form):
526
        response = form.save()
527
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
528
        patientrecord.mdph_responses.add(response)
529
        return HttpResponseRedirect(self.success_url)
530

    
531
class UpdateMDPHResponseView(cbv.UpdateView):
532
    def get(self, request, *args, **kwargs):
533
        if kwargs.has_key('patientrecord_id'):
534
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
535
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
536

    
537

    
538
new_mdph_response = \
539
    NewMDPHResponseView.as_view(model=MDPHResponse,
540
        template_name = 'dossiers/generic_form.html',
541
        success_url = '../view#tab=6',
542
        form_class=forms.MDPHResponseForm)
543
update_mdph_response = \
544
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
545
        template_name = 'dossiers/generic_form.html',
546
        success_url = '../../view#tab=6',
547
        form_class=forms.MDPHResponseForm)
548
delete_mdph_response = \
549
    cbv.DeleteView.as_view(model=MDPHResponse,
550
        template_name = 'dossiers/generic_confirm_delete.html',
551
        success_url = '../../view#tab=6')
552

    
553

    
554
class UpdatePatientStateView(cbv.UpdateView):
555
    def get(self, request, *args, **kwargs):
556
        if kwargs.has_key('patientrecord_id'):
557
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
558
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
559

    
560
update_patient_state = \
561
    UpdatePatientStateView.as_view(model=FileState,
562
        template_name = 'dossiers/generic_form.html',
563
        success_url = '../../view#tab=0',
564
        form_class=forms.PatientStateForm)
565
delete_patient_state = \
566
    cbv.DeleteView.as_view(model=FileState,
567
        template_name = 'dossiers/generic_confirm_delete.html',
568
        success_url = '../../view#tab=0')
569

    
570

    
571
class GenerateRtfFormView(cbv.FormView):
572
    template_name = 'dossiers/generate_rtf_form.html'
573
    form_class = forms.GenerateRtfForm
574
    success_url = './view#tab=0'
575

    
576
    def get_context_data(self, **kwargs):
577
        ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
578
        ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
579
        ctx['service_id'] = self.service.id
580
        if self.request.GET.get('event-id'):
581
            date = self.request.GET.get('date')
582
            date = datetime.strptime(date, '%Y-%m-%d').date()
583
            appointment = Appointment()
584
            event = Event.objects.get(id=self.request.GET.get('event-id'))
585
            event = event.today_occurence(date)
586
            appointment.init_from_event(event, self.service)
587
            ctx['appointment'] = appointment
588
        return ctx
589

    
590
    def form_valid(self, form):
591
        patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
592
        template_filename = form.cleaned_data.get('template_filename')
593
        dest_filename = datetime.now().strftime('%Y-%m-%d--%H:%M') + '--' + template_filename
594
        from_path = os.path.join(settings.RTF_TEMPLATES_DIRECTORY, template_filename)
595
        to_path = os.path.join(patient.get_ondisk_directory(self.service.name), dest_filename)
596
        vars = {'AD11': '', 'AD12': '', 'AD13': '', 'AD14': '', 'AD15': '',
597
                'JOU1': datetime.today().strftime('%d/%m/%Y'),
598
                'VIL1': u'Saint-Étienne',
599
                'PRE1': form.cleaned_data.get('first_name'),
600
                'NOM1': form.cleaned_data.get('last_name'),
601
                'DPA1': form.cleaned_data.get('appointment_intervenants')
602
               }
603
        for i, line in enumerate(form.cleaned_data.get('address').splitlines()):
604
            vars['AD%d' % (11+i)] = line
605
        make_doc_from_template(from_path, to_path, vars)
606

    
607
        client_dir = patient.get_client_side_directory(self.service.name)
608
        if not client_dir:
609
            response = HttpResponse(mimetype='text/rtf')
610
            response['Content-Disposition'] = 'attachment; filename="%s"' % dest_filename
611
            response.write(file(to_path).read())
612
            return response
613
        else:
614
            client_filepath = os.path.join(client_dir, dest_filename)
615
            return HttpResponseRedirect('file://' + client_filepath)
616

    
617
generate_rtf_form = GenerateRtfFormView.as_view()
618

    
619

    
620
class PatientRecordsQuotationsView(cbv.ListView):
621
    model = PatientRecord
622
    template_name = 'dossiers/quotations.html'
623

    
624
    def get_queryset(self):
625
        form = forms.QuotationsForm(data=self.request.GET or None)
626
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
627
        without_quotations = self.request.GET.get('without_quotations')
628
        if without_quotations:
629
            qs = qs.filter(mises_1=None).filter(mises_2=None).filter(mises_3=None)
630
        states = self.request.GET.getlist('states')
631
        if states:
632
            status_types = ['BILAN', 'SURVEILLANCE', 'SUIVI']
633
            for state in states:
634
                status_types.append(STATE_CHOICES_TYPE[state])
635
            qs = qs.filter(last_state__status__type__in=status_types)
636
        else:
637
            qs = qs.filter(last_state__status__type__in='')
638

    
639
        try:
640
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
641
            qs = qs.filter(act_set__date__gte=date_actes_start.date())
642
        except (ValueError, KeyError):
643
            pass
644
        try:
645
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
646
            qs = qs.filter(act_set__date__lte=date_actes_end.date())
647
        except (ValueError, KeyError):
648
            pass
649
        qs = qs.filter(service=self.service).order_by('last_name')
650
        return qs
651

    
652
    def get_context_data(self, **kwargs):
653
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
654
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None)
655
        ctx['patient_records'] = []
656
        if self.request.GET:
657
            for patient_record in ctx['object_list'].filter():
658
                next_rdv = get_next_rdv(patient_record)
659
                last_rdv = get_last_rdv(patient_record)
660
                current_state = patient_record.get_current_state()
661
                if STATES_MAPPING.has_key(current_state.status.type):
662
                    state = STATES_MAPPING[current_state.status.type]
663
                else:
664
                    state = current_state.status.name
665
                state_class = current_state.status.type.lower()
666
                ctx['patient_records'].append(
667
                        {
668
                            'object': patient_record,
669
                            'state': state,
670
                            'state_class': state_class
671
                            }
672
                        )
673
                state = state.replace(' ', '_')
674
                state = state.replace("'", '')
675

    
676
        return ctx
677

    
678
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
679

    
680

    
681
class CreateDirectoryView(View, cbv.ServiceViewMixin):
682
    def post(self, request, *args, **kwargs):
683
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
684
        service = Service.objects.get(slug=kwargs['service'])
685
        patient.get_ondisk_directory(service.name)
686
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
687
        return HttpResponseRedirect('view')
688

    
689
create_directory = CreateDirectoryView.as_view()
(9-9/9)