Project

General

Profile

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

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

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

    
3
import os
4

    
5
from datetime import datetime, date
6

    
7
from django.conf import settings
8
from django.db import models
9
from django.http import HttpResponseRedirect, HttpResponse
10
from django.views.generic import View
11
from django.views.generic.edit import DeleteView
12
from django.contrib import messages
13
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
14
from django.core.files import File
15
from django.forms import Form
16
from django.utils import formats
17
from django.shortcuts import get_object_or_404
18

    
19
from calebasse import cbv
20
from calebasse.doc_templates import make_doc_from_template
21
from calebasse.dossiers import forms
22
from calebasse.dossiers.transport import render_transport
23
from calebasse.agenda.models import Event, EventWithAct
24
from calebasse.actes.models import Act
25
from calebasse.agenda.appointments import Appointment
26
from calebasse.dossiers.models import (PatientRecord, PatientContact,
27
        PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
28
        CmppHealthCareDiagnostic, SessadHealthCareNotification, HealthCare,
29
        TransportPrescriptionLog, ProtectionState)
30
from calebasse.dossiers.states import STATES_MAPPING, STATES_BTN_MAPPER
31
from calebasse.ressources.models import (Service,
32
    SocialisationDuration, MDPHRequest, MDPHResponse)
33
from calebasse.facturation.list_acts import list_acts_for_billing_CMPP_per_patient
34

    
35
from calebasse.decorators import validator_only
36

    
37
def get_next_rdv(patient_record):
38
    Q = models.Q
39
    today = date.today()
40
    qs = EventWithAct.objects.filter(patient=patient_record) \
41
            .filter(exception_to__isnull=True, canceled=False) \
42
            .filter(Q(start_datetime__gte=today) \
43
            |  Q(exceptions__isnull=False) \
44
            | ( Q(recurrence_periodicity__isnull=False) \
45
            & (Q(recurrence_end_date__gte=today) \
46
            | Q(recurrence_end_date__isnull=True) \
47
            ))) \
48
            .distinct() \
49
            .select_related() \
50
            .prefetch_related('participants', 'exceptions__eventwithact')
51
    occurrences = []
52
    for event in qs:
53
        occurrences.extend(filter(lambda e: e.start_datetime.date() >= today, event.all_occurences(limit=180)))
54
    occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
55
    if occurrences:
56
        return occurrences[0]
57
    else:
58
        return None
59

    
60
def get_last_rdv(patient_record):
61
    last_rdv = {}
62
    event = Event.objects.last_appointment(patient_record)
63
    if event:
64
        last_rdv['start_datetime'] = event.start_datetime
65
        last_rdv['participants'] = event.participants.all()
66
        last_rdv['act_type'] = event.eventwithact.act_type
67
        last_rdv['act_state'] = event.act.get_state()
68
        last_rdv['is_absent'] = event.is_absent()
69
    return last_rdv
70

    
71
class NewPatientRecordView(cbv.FormView, cbv.ServiceViewMixin):
72
    form_class = forms.NewPatientRecordForm
73
    template_name = 'dossiers/patientrecord_new.html'
74
    success_url = '..'
75
    patient = None
76

    
77
    def post(self, request, *args, **kwarg):
78
        self.user = request.user
79
        return super(NewPatientRecordView, self).post(request, *args, **kwarg)
80

    
81
    def form_valid(self, form):
82
        self.patient = create_patient(form.data['first_name'], form.data['last_name'], self.service,
83
                self.user, date_selected=datetime.strptime(form.data['date_selected'], "%d/%m/%Y"))
84
        return super(NewPatientRecordView, self).form_valid(form)
85

    
86
    def get_success_url(self):
87
        return '%s/view' % self.patient.id
88

    
89
new_patient_record = NewPatientRecordView.as_view()
90

    
91
class RecordPatientRecordIdMixing(object):
92
    def dispatch(self, request, *args, **kwargs):
93
        self.patientrecord_id = request.session['patientrecord_id'] = int(kwargs['patientrecord_id'])
94
        return super(RecordPatientRecordIdMixing, self).dispatch(request, *args, **kwargs)
95

    
96
    def get_form_kwargs(self):
97
        kwargs = super(RecordPatientRecordIdMixing, self).get_form_kwargs()
98
        kwargs['patient'] = PatientRecord.objects.get(id=self.patientrecord_id)
99
        return kwargs
100

    
101
class NewPatientContactView(RecordPatientRecordIdMixing, cbv.CreateView):
102
    model = PatientContact
103
    form_class = forms.PatientContactForm
104
    template_name = 'dossiers/patientcontact_new.html'
105
    success_url = '../view#tab=2'
106

    
107
new_patient_contact = NewPatientContactView.as_view()
108

    
109
class UpdatePatientContactView(RecordPatientRecordIdMixing, cbv.UpdateView):
110
    model = PatientContact
111
    form_class = forms.PatientContactForm
112
    template_name = 'dossiers/patientcontact_new.html'
113
    success_url = '../../view#tab=2'
114

    
115
update_patient_contact = UpdatePatientContactView.as_view()
116

    
117
class DeletePatientContactView(cbv.DeleteView):
118
    model = PatientContact
119
    form_class = forms.PatientContactForm
120
    template_name = 'dossiers/patientcontact_confirm_delete.html'
121
    success_url = '../../view#tab=2'
122

    
123
    def post(self, request, *args, **kwargs):
124
        try:
125
            patient = PatientRecord.objects.get(id=kwargs.get('pk'))
126
        except PatientRecord.DoesNotExist:
127
            return super(DeletePatientContactView, self).post(request, *args, **kwargs)
128
        # the contact is also a patient record; it shouldn't be deleted; just
129
        # altered to remove an address
130
        patient.addresses.remove(self.request.GET['address'])
131
        return HttpResponseRedirect(self.get_success_url())
132

    
133
delete_patient_contact = DeletePatientContactView.as_view()
134

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

    
141
    def get_success_url(self):
142
        return self.success_url
143

    
144
    def form_valid(self, form):
145
        patientaddress = form.save()
146
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
147
        patientrecord.addresses.add(patientaddress)
148
        messages.add_message(self.request, messages.INFO, u'Nouvelle adresse enregistrée avec succès.')
149
        return HttpResponseRedirect(self.get_success_url())
150

    
151
new_patient_address = NewPatientAddressView.as_view()
152

    
153
class UpdatePatientAddressView(cbv.UpdateView):
154
    model = PatientAddress
155
    form_class = forms.PatientAddressForm
156
    template_name = 'dossiers/patientaddress_new.html'
157
    success_url = '../../view#tab=2'
158

    
159
    def form_valid(self, form):
160
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
161
        return super(UpdatePatientAddressView, self).form_valid(form)
162

    
163
update_patient_address = UpdatePatientAddressView.as_view()
164

    
165
class DeletePatientAddressView(cbv.DeleteView):
166
    model = PatientAddress
167
    form_class = forms.PatientAddressForm
168
    template_name = 'dossiers/patientaddress_confirm_delete.html'
169
    success_url = '../../view#tab=2'
170

    
171
delete_patient_address = DeletePatientAddressView.as_view()
172

    
173

    
174
class NewHealthCareView(cbv.CreateView):
175

    
176
    def get_initial(self):
177
        initial = super(NewHealthCareView, self).get_initial()
178
        initial['author'] = self.request.user.id
179
        initial['patient'] = self.kwargs['patientrecord_id']
180
        return initial
181

    
182
new_healthcare_treatment = \
183
    NewHealthCareView.as_view(model=CmppHealthCareTreatment,
184
        template_name = 'dossiers/generic_form.html',
185
        success_url = '../view#tab=3',
186
        form_class=forms.CmppHealthCareTreatmentForm)
187
new_healthcare_diagnostic = \
188
    NewHealthCareView.as_view(model=CmppHealthCareDiagnostic,
189
        template_name = 'dossiers/generic_form.html',
190
        success_url = '../view#tab=3',
191
        form_class=forms.CmppHealthCareDiagnosticForm)
192
new_healthcare_notification = \
193
    NewHealthCareView.as_view(model=SessadHealthCareNotification,
194
        template_name = 'dossiers/generic_form.html',
195
        success_url = '../view#tab=3',
196
        form_class=forms.SessadHealthCareNotificationForm)
197
update_healthcare_treatment = \
198
    cbv.UpdateView.as_view(model=CmppHealthCareTreatment,
199
        template_name = 'dossiers/generic_form.html',
200
        success_url = '../../view#tab=3',
201
        form_class=forms.CmppHealthCareTreatmentForm)
202
update_healthcare_diagnostic = \
203
    cbv.UpdateView.as_view(model=CmppHealthCareDiagnostic,
204
        template_name = 'dossiers/generic_form.html',
205
        success_url = '../../view#tab=3',
206
        form_class=forms.CmppHealthCareDiagnosticForm)
207
update_healthcare_notification = \
208
    cbv.UpdateView.as_view(model=SessadHealthCareNotification,
209
        template_name = 'dossiers/generic_form.html',
210
        success_url = '../../view#tab=3',
211
        form_class=forms.SessadHealthCareNotificationForm)
212
delete_healthcare_treatment = \
213
    cbv.DeleteView.as_view(model=CmppHealthCareTreatment,
214
        template_name = 'dossiers/generic_confirm_delete.html',
215
        success_url = '../../view#tab=3')
216
delete_healthcare_diagnostic = \
217
    cbv.DeleteView.as_view(model=CmppHealthCareDiagnostic,
218
        template_name = 'dossiers/generic_confirm_delete.html',
219
        success_url = '../../view#tab=3')
220
delete_healthcare_notification = \
221
    cbv.DeleteView.as_view(model=SessadHealthCareNotification,
222
        template_name = 'dossiers/generic_confirm_delete.html',
223
        success_url = '../../view#tab=3')
224

    
225

    
226
class StateFormView(cbv.FormView):
227
    template_name = 'dossiers/state.html'
228
    form_class = forms.StateForm
229
    success_url = './view#tab=0'
230

    
231

    
232
    def post(self, request, *args, **kwarg):
233
        self.user = request.user
234
        return super(StateFormView, self).post(request, *args, **kwarg)
235

    
236
    def form_valid(self, form):
237
        service = Service.objects.get(id=form.data['service_id'])
238
        status = Status.objects.filter(services=service).filter(type=form.data['state_type'])
239
        patient = PatientRecord.objects.get(id=form.data['patient_id'])
240
        date_selected = datetime.strptime(form.data['date'], "%d/%m/%Y")
241
        patient.set_state(status[0], self.user, date_selected, form.data['comment'])
242
        return super(StateFormView, self).form_valid(form)
243

    
244
state_form = StateFormView.as_view()
245

    
246

    
247
class PatientRecordView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
248
    model = PatientRecord
249
    forms_classes = {
250
            'general': forms.GeneralForm,
251
            'id': forms.CivilStatusForm,
252
            'physiology': forms.PhysiologyForm,
253
            'inscription': forms.InscriptionForm,
254
            'out': forms.OutForm,
255
            'family': forms.FamilyForm,
256
            'transport': forms.TransportFrom,
257
            'followup': forms.FollowUpForm,
258
            'policyholder': forms.PolicyHolderForm
259
            }
260
    template_name = 'dossiers/patientrecord_update.html'
261
    success_url = './view'
262

    
263
    def get_success_url(self):
264
        if self.request.POST.has_key('tab'):
265
            return self.success_url + '#tab=' + self.request.POST['tab']
266
        else:
267
            return self.success_url
268

    
269
    def get_context_data(self, **kwargs):
270
        ctx = super(PatientRecordView, self).get_context_data(**kwargs)
271
        ctx['object'].create_diag_healthcare(self.request.user)
272
        ctx['object'].automated_switch_state(self.request.user)
273
        ctx['initial_state'] = ctx['object'].get_initial_state()
274
        current_state = ctx['object'].get_current_state()
275
        if STATES_MAPPING.has_key(current_state.status.type):
276
            state = STATES_MAPPING[current_state.status.type]
277
        else:
278
            state = current_state.status.name
279
        ctx['current_state'] = current_state
280
        ctx['service_id'] = self.service.id
281
        ctx['states'] = FileState.objects.filter(patient=self.object) \
282
                .filter(status__services=self.service) \
283
                .order_by('-date_selected')
284
        ctx['next_rdvs'] = []
285
        Q = models.Q
286
        today = date.today()
287
        qs = EventWithAct.objects.filter(patient=ctx['object']) \
288
                .filter(exception_to__isnull=True, canceled=False) \
289
                .filter(Q(start_datetime__gte=today) \
290
                |  Q(exceptions__isnull=False) \
291
                | ( Q(recurrence_periodicity__isnull=False) \
292
                & (Q(recurrence_end_date__gte=today) \
293
                | Q(recurrence_end_date__isnull=True) \
294
                ))) \
295
                .distinct() \
296
                .select_related() \
297
                .prefetch_related('participants', 'exceptions__eventwithact',
298
                        'act_set__actvalidationstate_set')
299
        occurrences = []
300
        for event in qs:
301
            occurrences.extend(filter(lambda e: e.start_datetime.date() >= today,
302
                event.all_occurences(limit=180)))
303
        occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
304
        for event in occurrences:
305
            state = None
306
            if event.act:
307
                state = event.act.get_state()
308
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
309
                state = None
310
            ctx['next_rdvs'].append((event, state, event.get_missing_participants()))
311
        if ctx['next_rdvs']:
312
            ctx['next_rdv'] = ctx['next_rdvs'][0][0]
313
        ctx['last_rdvs'] = []
314
        for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
315
            state = act.get_state()
316
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
317
                state = None
318
            missing_workers = []
319
            try:
320
                missing_workers = [participant.worker for participant in act.event.get_missing_participants()]
321
            except:
322
                pass
323
            ctx['last_rdvs'].append((act, state, missing_workers))
324
        history = []
325
        i = 0
326
        for state in ctx['object'].filestate_set.order_by('-date_selected'):
327
            acts = []
328
            try:
329
                while ctx['last_rdvs'][i][0].date >= state.date_selected.date():
330
                    acts.append(ctx['last_rdvs'][i])
331
                    i += 1
332
            except:
333
                pass
334
            history.append((state, acts))
335
        if i < len(ctx['last_rdvs']) -1:
336
            history.append((None, ctx['last_rdvs'][i:]))
337
        ctx['history'] = history
338
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
339

    
340
        ctx['missing_policy'] = False
341
        if not self.object.policyholder or \
342
                not self.object.policyholder.health_center or \
343
                not self.object.policyholder.social_security_id:
344
            ctx['missing_policy'] = True
345
        ctx['missing_birthdate'] = False
346
        if not self.object.birthdate:
347
            ctx['missing_birthdate'] = True
348

    
349
        ctx['status'] = []
350
        close_btn = STATES_BTN_MAPPER['CLOS']
351
        if 'next_rdv' in ctx:
352
            close_btn = STATES_BTN_MAPPER['CLOS_RDV']
353
        if ctx['object'].service.name == "CMPP":
354
            ctx['can_rediag'] = self.object.create_diag_healthcare(self.request.user)
355
            status = self.object.get_healthcare_status()
356
            highlight = False
357
            if status[0] == -1:
358
                status = 'Indéterminé.'
359
                highlight = True
360
            elif status[0] == 0:
361
                status = "Prise en charge de diagnostic en cours."
362
            elif status[0] == 1:
363
                status = 'Patient jamais pris en charge.'
364
            elif status[0] == 2:
365
                status = "Prise en charge de diagnostic complète, faire une demande de prise en charge de traitement."
366
                highlight = True
367
            elif status[0] == 3:
368
                if ctx['can_rediag']:
369
                    status = "Prise en charge de traitement expirée. Patient élligible en rediagnostic."
370
                    highlight = True
371
                else:
372
                    status = "Prise en charge de traitement expirée. La demande d'un renouvellement est possible."
373
                    highlight = True
374
            elif status[0] == 4:
375
                status = "Il existe une prise en charge de traitement mais qui ne prendra effet que le %s." % str(status[1])
376
            elif status[0] == 5:
377
                status = "Prise en charge de traitement en cours."
378
            elif status[0] == 6:
379
                status = "Prise en charge de traitement complète mais qui peut être prolongée."
380
                highlight = True
381
            elif status[0] == 7:
382
                status = "Prise en charge de traitement complète et déjà prolongée, se terminant le %s." % \
383
                    formats.date_format(status[2], "SHORT_DATE_FORMAT")
384
            else:
385
                status = 'Statut inconnu.'
386
            ctx['hc_status'] = (status, highlight)
387
            if ctx['object'].last_state.status.type == "ACCUEIL":
388
                # Inscription automatique au premier acte facturable valide
389
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
390
                        STATES_BTN_MAPPER['DIAGNOSTIC'],
391
                        STATES_BTN_MAPPER['TRAITEMENT']]
392
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
393
                # Passage automatique en diagnostic ou traitement
394
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
395
                        STATES_BTN_MAPPER['DIAGNOSTIC'],
396
                        STATES_BTN_MAPPER['TRAITEMENT']]
397
            elif ctx['object'].last_state.status.type == "DIAGNOSTIC":
398
                # Passage automatique en traitement
399
                ctx['status'] = [STATES_BTN_MAPPER['TRAITEMENT'],
400
                        close_btn,
401
                        STATES_BTN_MAPPER['ACCUEIL']]
402
            elif ctx['object'].last_state.status.type == "TRAITEMENT":
403
                # Passage automatique en diagnostic si on ajoute une prise en charge diagnostic,
404
                # ce qui est faisable dans l'onglet prise en charge par un bouton visible sous conditions
405
                ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
406
                        close_btn,
407
                        STATES_BTN_MAPPER['ACCUEIL']]
408
            elif ctx['object'].last_state.status.type == "CLOS":
409
                # Passage automatique en diagnostic ou traitement
410
                ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
411
                        STATES_BTN_MAPPER['TRAITEMENT'],
412
                        STATES_BTN_MAPPER['ACCUEIL']]
413
            (acts_not_locked, days_not_locked, acts_not_valide,
414
            acts_not_billable, acts_pause, acts_per_hc, acts_losts) = \
415
                list_acts_for_billing_CMPP_per_patient(self.object,
416
                    datetime.today(), self.service)
417
            ctx['acts_losts'] = acts_losts
418
            ctx['acts_pause'] = acts_pause
419
            hcs_used = acts_per_hc.keys()
420
            hcs = None
421
            if not hcs_used:
422
                hcs = [(hc, None) for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date')]
423
            else:
424
                hcs = []
425
                for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date'):
426
                    acts = None
427
                    if hasattr(hc, 'cmpphealthcarediagnostic') and hc.cmpphealthcarediagnostic in hcs_used:
428
                        acts = acts_per_hc[hc.cmpphealthcarediagnostic]
429
                    elif hasattr(hc, 'cmpphealthcaretreatment') and hc.cmpphealthcaretreatment in hcs_used:
430
                        acts = acts_per_hc[hc.cmpphealthcaretreatment]
431
                    hcs.append((hc, acts))
432
            ctx['hcs'] = []
433
            for hc, acts in hcs:
434
                ctx['hcs'].append((hc, acts, hc.act_set.order_by('date', 'time')))
435
        elif ctx['object'].service.name == "CAMSP":
436
            if ctx['object'].last_state.status.type == "ACCUEIL":
437
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
438
                        STATES_BTN_MAPPER['BILAN']]
439
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
440
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
441
                        STATES_BTN_MAPPER['BILAN'],
442
                        STATES_BTN_MAPPER['SURVEILLANCE'],
443
                        STATES_BTN_MAPPER['SUIVI'],
444
                        close_btn]
445
            elif ctx['object'].last_state.status.type == "BILAN":
446
                ctx['status'] = [STATES_BTN_MAPPER['SURVEILLANCE'],
447
                        STATES_BTN_MAPPER['SUIVI'],
448
                        close_btn,
449
                        STATES_BTN_MAPPER['ACCUEIL']]
450
            elif ctx['object'].last_state.status.type == "SURVEILLANCE":
451
                ctx['status'] = [STATES_BTN_MAPPER['SUIVI'],
452
                        close_btn,
453
                        STATES_BTN_MAPPER['ACCUEIL'],
454
                        STATES_BTN_MAPPER['BILAN']]
455
            elif ctx['object'].last_state.status.type == "SUIVI":
456
                ctx['status'] = [close_btn,
457
                        STATES_BTN_MAPPER['ACCUEIL'],
458
                        STATES_BTN_MAPPER['BILAN'],
459
                        STATES_BTN_MAPPER['SURVEILLANCE']]
460
            elif ctx['object'].last_state.status.type == "CLOS":
461
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
462
                        STATES_BTN_MAPPER['BILAN'],
463
                        STATES_BTN_MAPPER['SURVEILLANCE'],
464
                        STATES_BTN_MAPPER['SUIVI']]
465
        elif ctx['object'].service.name == "SESSAD TED" or ctx['object'].service.name == "SESSAD DYS":
466
            if ctx['object'].last_state.status.type == "ACCUEIL":
467
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
468
                        STATES_BTN_MAPPER['TRAITEMENT']]
469
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
470
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
471
                        STATES_BTN_MAPPER['TRAITEMENT'],
472
                        close_btn]
473
            elif ctx['object'].last_state.status.type == "TRAITEMENT":
474
                ctx['status'] = [close_btn,
475
                        STATES_BTN_MAPPER['ACCUEIL']]
476
            elif ctx['object'].last_state.status.type == "CLOS":
477
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
478
                        STATES_BTN_MAPPER['TRAITEMENT']]
479
            ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
480
        try:
481
            ctx['last_prescription'] = TransportPrescriptionLog.objects.filter(patient=ctx['object']).latest('created')
482
        except:
483
            pass
484

    
485
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
486
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
487
        return ctx
488

    
489
    def form_valid(self, form):
490
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
491
        return super(PatientRecordView, self).form_valid(form)
492

    
493

    
494
patient_record = PatientRecordView.as_view()
495

    
496
class PatientRecordsHomepageView(cbv.ListView):
497
    model = PatientRecord
498
    template_name = 'dossiers/index.html'
499

    
500

    
501
    def _get_search_result(self, paginate_patient_records):
502
        patient_records = []
503
        for patient_record in paginate_patient_records:
504
            next_rdv = get_next_rdv(patient_record)
505
            last_rdv = get_last_rdv(patient_record)
506
            current_status = patient_record.last_state.status
507
            state = current_status.name
508
            state_class = current_status.type.lower()
509
            patient_records.append(
510
                    {
511
                        'object': patient_record,
512
                        'next_rdv': next_rdv,
513
                        'last_rdv': last_rdv,
514
                        'state': state,
515
                        'state_class': state_class
516
                        }
517
                    )
518
        return patient_records
519

    
520
    def get_queryset(self):
521
        first_name = self.request.GET.get('first_name')
522
        last_name = self.request.GET.get('last_name')
523
        paper_id = self.request.GET.get('paper_id')
524
        id = self.request.GET.get('id')
525
        social_security_id = self.request.GET.get('social_security_id')
526
        if not (first_name or last_name or paper_id or id or social_security_id):
527
            return None
528
        if (first_name and len(first_name) < 2) or (last_name and len(last_name) < 2):
529
            return None
530
        qs = super(PatientRecordsHomepageView, self).get_queryset()
531
        states = self.request.GET.getlist('states')
532
        if last_name:
533
            qs = qs.filter(last_name__istartswith=last_name)
534
        if first_name:
535
            qs = qs.filter(first_name__istartswith=first_name)
536
        if paper_id:
537
            qs = qs.filter(paper_id__startswith=paper_id)
538
        if id:
539
            qs = qs.filter(id__startswith=id)
540
        if social_security_id:
541
            qs = qs.filter(models.Q(social_security_id__startswith=social_security_id) | \
542
                models.Q(contacts__social_security_id__startswith=social_security_id))
543
        if states:
544
            qs = qs.filter(last_state__status__id__in=states)
545
        else:
546
            qs = qs.filter(last_state__status__type__in="")
547
        qs = qs.filter(service=self.service).order_by('last_name').\
548
                prefetch_related('last_state',
549
                        'patientcontact', 'last_state__status')
550
        return qs
551

    
552
    def get_context_data(self, **kwargs):
553
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
554
        ctx['search_form'] = forms.SearchForm(service=self.service, data=self.request.GET or None)
555
        ctx['stats'] = [["Dossiers", 0]]
556
        for status in Status.objects.filter(services=self.service):
557
            ctx['stats'].append([status.name, 0])
558

    
559
        page = self.request.GET.get('page')
560
        if ctx['object_list']:
561
            patient_records = ctx['object_list'].filter()
562
        else:
563
            patient_records = []
564

    
565
        # TODO: use a sql query to do this
566
        for patient_record in patient_records:
567
            ctx['stats'][0][1] += 1
568
            for elem in ctx['stats']:
569
                if elem[0] == patient_record.last_state.status.name:
570
                    elem[1] += 1
571
        paginator = Paginator(patient_records, 50)
572
        try:
573
            paginate_patient_records = paginator.page(page)
574
        except PageNotAnInteger:
575
            paginate_patient_records = paginator.page(1)
576
        except EmptyPage:
577
            paginate_patient_records = paginator.page(paginator.num_pages)
578

    
579
        query = self.request.GET.copy()
580
        if 'page' in query:
581
            del query['page']
582
        ctx['query'] = query.urlencode()
583

    
584
        ctx['paginate_patient_records'] = paginate_patient_records
585
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
586
        return ctx
587

    
588
patientrecord_home = PatientRecordsHomepageView.as_view()
589

    
590
class PatientRecordDeleteView(DeleteView):
591
    model = PatientRecord
592
    success_url = ".."
593
    template_name = 'dossiers/patientrecord_confirm_delete.html'
594

    
595
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
596

    
597

    
598
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
599
    model = PatientRecord
600
    form_class = forms.PaperIDForm
601
    template_name = 'dossiers/generic_form.html'
602
    success_url = '../..'
603

    
604
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
605

    
606

    
607
class NewSocialisationDurationView(cbv.CreateView):
608
    model = SocialisationDuration
609
    form_class = forms.SocialisationDurationForm
610
    template_name = 'dossiers/generic_form.html'
611
    success_url = '../view#tab=6'
612

    
613
    def get_success_url(self):
614
        return self.success_url
615

    
616
    def get(self, request, *args, **kwargs):
617
        if kwargs.has_key('patientrecord_id'):
618
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
619
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
620

    
621
    def form_valid(self, form):
622
        duration = form.save()
623
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
624
        patientrecord.socialisation_durations.add(duration)
625
        return HttpResponseRedirect(self.get_success_url())
626

    
627
new_socialisation_duration = NewSocialisationDurationView.as_view()
628

    
629
class UpdateSocialisationDurationView(cbv.UpdateView):
630
    model = SocialisationDuration
631
    form_class = forms.SocialisationDurationForm
632
    template_name = 'dossiers/generic_form.html'
633
    success_url = '../../view#tab=6'
634

    
635
    def get(self, request, *args, **kwargs):
636
        if kwargs.has_key('patientrecord_id'):
637
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
638
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
639

    
640
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
641

    
642
class DeleteSocialisationDurationView(cbv.DeleteView):
643
    model = SocialisationDuration
644
    form_class = forms.SocialisationDurationForm
645
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
646
    success_url = '../../view#tab=6'
647

    
648
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
649

    
650

    
651
class NewMDPHRequestView(cbv.CreateView):
652
    def get(self, request, *args, **kwargs):
653
        if kwargs.has_key('patientrecord_id'):
654
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
655
        return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
656

    
657
    def form_valid(self, form):
658
        request = form.save()
659
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
660
        patientrecord.mdph_requests.add(request)
661
        return HttpResponseRedirect(self.success_url)
662

    
663
class UpdateMDPHRequestView(cbv.UpdateView):
664
    def get(self, request, *args, **kwargs):
665
        if kwargs.has_key('patientrecord_id'):
666
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
667
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
668

    
669

    
670
new_mdph_request = \
671
    NewMDPHRequestView.as_view(model=MDPHRequest,
672
        template_name = 'dossiers/generic_form.html',
673
        success_url = '../view#tab=6',
674
        form_class=forms.MDPHRequestForm)
675
update_mdph_request = \
676
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
677
        template_name = 'dossiers/generic_form.html',
678
        success_url = '../../view#tab=6',
679
        form_class=forms.MDPHRequestForm)
680
delete_mdph_request = \
681
    cbv.DeleteView.as_view(model=MDPHRequest,
682
        template_name = 'dossiers/generic_confirm_delete.html',
683
        success_url = '../../view#tab=6')
684

    
685
class NewMDPHResponseView(cbv.CreateView):
686
    def get(self, request, *args, **kwargs):
687
        if kwargs.has_key('patientrecord_id'):
688
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
689
        return super(NewMDPHResponseView, self).get(request, *args, **kwargs)
690

    
691
    def form_valid(self, form):
692
        response = form.save()
693
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
694
        patientrecord.mdph_responses.add(response)
695
        return HttpResponseRedirect(self.success_url)
696

    
697
class UpdateMDPHResponseView(cbv.UpdateView):
698
    def get(self, request, *args, **kwargs):
699
        if kwargs.has_key('patientrecord_id'):
700
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
701
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
702

    
703

    
704
new_mdph_response = \
705
    NewMDPHResponseView.as_view(model=MDPHResponse,
706
        template_name = 'dossiers/generic_form.html',
707
        success_url = '../view#tab=6',
708
        form_class=forms.MDPHResponseForm)
709
update_mdph_response = \
710
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
711
        template_name = 'dossiers/generic_form.html',
712
        success_url = '../../view#tab=6',
713
        form_class=forms.MDPHResponseForm)
714
delete_mdph_response = \
715
    cbv.DeleteView.as_view(model=MDPHResponse,
716
        template_name = 'dossiers/generic_confirm_delete.html',
717
        success_url = '../../view#tab=6')
718

    
719

    
720
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
721

    
722
    def get_initial(self):
723
        initial = super(UpdatePatientStateView, self).get_initial()
724
        initial['date_selected'] = self.object.date_selected.date()
725
        return initial
726

    
727
    def get(self, request, *args, **kwargs):
728
        if kwargs.has_key('patientrecord_id'):
729
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
730
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
731

    
732
class DeletePatientView(cbv.DeleteView):
733

    
734
    def delete(self, request, *args, **kwargs):
735
        self.object = self.get_object()
736
        if self.object == self.object.patient.last_state:
737
            status = self.object.patient.filestate_set.all().order_by('-created')
738
            if len(status) > 1:
739
                self.object.patient.last_state = status[1]
740
                self.object.patient.save()
741
            else:
742
                # TODO return an error here
743
                return HttpResponseRedirect(self.get_success_url())
744
        self.object.delete()
745
        return HttpResponseRedirect(self.get_success_url())
746

    
747

    
748
update_patient_state = \
749
    UpdatePatientStateView.as_view(model=FileState,
750
        template_name = 'dossiers/generic_form.html',
751
        success_url = '../../view#tab=0',
752
        form_class=forms.PatientStateForm)
753
delete_patient_state = \
754
    DeletePatientView.as_view(model=FileState,
755
        template_name = 'dossiers/generic_confirm_delete.html',
756
        success_url = '../../view#tab=0')
757

    
758

    
759
class GenerateRtfFormView(cbv.FormView):
760
    template_name = 'dossiers/generate_rtf_form.html'
761
    form_class = forms.GenerateRtfForm
762
    success_url = './view#tab=0'
763

    
764
    def get_context_data(self, **kwargs):
765
        ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
766
        ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
767
        ctx['service_id'] = self.service.id
768
        if self.request.GET.get('event-id'):
769
            date = self.request.GET.get('date')
770
            date = datetime.strptime(date, '%Y-%m-%d').date()
771
            appointment = Appointment()
772
            event = EventWithAct.objects.get(id=self.request.GET.get('event-id'))
773
            event = event.today_occurrence(date)
774
            appointment.init_from_event(event, self.service)
775
            ctx['event'] = event
776
            ctx['appointment'] = appointment
777
        return ctx
778

    
779
    def form_valid(self, form, **kwargs):
780
        ctx = self.get_context_data(**kwargs)
781
        patient = ctx['object']
782
        appointment = ctx['appointment']
783
        event = ctx['event']
784
        template_filename = form.cleaned_data.get('template_filename')
785
        dest_filename = datetime.now().strftime('%Y-%m-%d--%H:%M:%S') + '--' + template_filename
786
        from_path = os.path.join(settings.RTF_TEMPLATES_DIRECTORY, template_filename)
787
        to_path = ''
788
        persistent = True
789
        if settings.USE_PATIENT_FILE_RTF_REPOSITORY_DIRECTORY \
790
                or settings.RTF_REPOSITORY_DIRECTORY:
791
            if settings.USE_PATIENT_FILE_RTF_REPOSITORY_DIRECTORY:
792
                to_path = patient.get_ondisk_directory(self.service.name)
793
            if settings.RTF_REPOSITORY_DIRECTORY:
794
                to_path = os.path.join(to_path,
795
                    settings.RTF_REPOSITORY_DIRECTORY)
796
            to_path = os.path.join(to_path, dest_filename)
797
        else:
798
            # else : use temporary files
799
            persistent = False
800
            to_path = dest_filename
801
        variables = {'AD11': '', 'AD12': '', 'AD13': '', 'AD14': '',
802
            'AD15': '', 'AD18': '',
803
            'JOU1': formats.date_format(datetime.today(), "DATE_FORMAT"),
804
            'VIL1': u'Saint-Étienne',
805
            'RDV1': '', 'HEU1': '', 'THE1': '', 'DPA1': '',
806
            'NOM1': '', 'PRE1': '', 'NAI1': '', 'NUM2': '',
807
            'NOM2': '', 'PRE2': '', 'TPA1': '', 'NSS1': '',
808
            'TR01': '', 'TR02': '', 'TR03': '', 'TR04': '', 'TR05': '',
809
            'AD16': '', 'AD17': '', 'AD19': '',
810
            'AD21': '', 'AD22': '', 'AD23': '', 'AD24': '', 'AD25': '',
811
            'AD26': '', 'AD27': '', 'AD28': '', 'AD29': '',
812
            'RDV2': '' ,
813
        }
814
        list_rdvs = []
815
        for act in Act.objects.last_acts(patient):
816
            state = act.get_state()
817
            if state and state.state_name in ('VALIDE', 'ACT_DOUBLE'):
818
                rdv = "\t- %s" % formats.date_format(act.date, "DATE_FORMAT")
819
                if act.time:
820
                    rdv += " à %s" % formats.date_format(act.time, "TIME_FORMAT")
821
                list_rdvs.append(rdv)
822
        variables['RDV2'] = '\par'.join(list_rdvs)
823
        if appointment:
824
            variables['RDV1'] = formats.date_format(appointment.date, "DATE_FORMAT")
825
            variables['HEU1'] = appointment.begin_hour
826
            variables['THE1'] = ' '.join([str(i) for i in appointment.workers])# ou DPA1?
827
            variables['DPA1'] = variables['THE1']
828
        if patient:
829
            variables['NOM1'] = patient.last_name
830
            variables['PRE1'] = patient.first_name
831
            if patient.birthdate :
832
                variables['NAI1'] = patient.birthdate.strftime('%d/%m/%Y')
833
            variables['NUM2'] = patient.paper_id
834
            if patient.policyholder:
835
                variables['NOM2'] = patient.policyholder.last_name
836
                variables['PRE2'] = patient.policyholder.first_name
837
                if patient.policyholder.health_center:
838
                    variables['TPA1'] = patient.policyholder.health_center.name
839
                if patient.policyholder.social_security_id:
840
                    key = str(patient.policyholder.get_control_key())
841
                    if len(key) == 1:
842
                        key = '0' + key
843
                    variables['NSS1'] = \
844
                        ' '.join([patient.policyholder.social_security_id,
845
                            key])
846
            if patient.transportcompany:
847
                variables['TR01'] = patient.transportcompany.name
848
                variables['TR02'] = patient.transportcompany.address
849
                variables['TR03'] = patient.transportcompany.address_complement
850
                variables['TR04'] = patient.transportcompany.zip_code
851
                variables['TR05'] = patient.transportcompany.city
852
        variables['AD18'] = form.cleaned_data.get('phone_address') or ''
853
        for i, line in enumerate(form.cleaned_data.get('address').splitlines()):
854
            variables['AD%d' % (11+i)] = line
855
            if i == 4:
856
                break
857

    
858
        filename = make_doc_from_template(from_path, to_path, variables,
859
            persistent)
860

    
861
        client_dir = patient.get_client_side_directory(self.service.name)
862
        event.convocation_sent = True
863
        event.save()
864
        if not client_dir:
865
            content = File(file(filename))
866
            response = HttpResponse(content,'text/rtf')
867
            response['Content-Length'] = content.size
868
            response['Content-Disposition'] = 'attachment; filename="%s"' \
869
                % dest_filename.encode('utf-8')
870
            return response
871
        else:
872
            class LocalFileHttpResponseRedirect(HttpResponseRedirect):
873
                allowed_schemes = ['file']
874
            client_filepath = os.path.join(client_dir, dest_filename)
875
            return LocalFileHttpResponseRedirect('file://' + client_filepath)
876

    
877
generate_rtf_form = GenerateRtfFormView.as_view()
878

    
879

    
880
class PatientRecordsQuotationsView(cbv.ListView):
881
    model = PatientRecord
882
    template_name = 'dossiers/quotations.html'
883

    
884
    def _get_search_result(self, paginate_patient_records):
885
        patient_records = []
886
        for patient_record in paginate_patient_records:
887
            current_state = patient_record.get_current_state()
888
            state = current_state.status.name
889
            state_class = current_state.status.type.lower()
890
            patient_records.append(
891
                    {
892
                        'object': patient_record,
893
                        'state': state,
894
                        'state_class': state_class
895
                        }
896
                    )
897
        return patient_records
898

    
899
    def get_queryset(self):
900
        form = forms.QuotationsForm(data=self.request.GET or None)
901
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
902
        without_quotations = self.request.GET.get('without_quotations')
903
        if without_quotations:
904
            qs = qs.filter(mises_1=None).filter(mises_2=None).filter(mises_3=None)
905
        states = self.request.GET.getlist('states')
906
        qs = qs.filter(last_state__status__id__in=states)
907

    
908
        try:
909
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
910
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
911
        except (ValueError, KeyError):
912
            pass
913
        try:
914
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
915
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
916
        except (ValueError, KeyError):
917
            pass
918
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
919
        return qs
920

    
921
    def get_context_data(self, **kwargs):
922
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
923
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
924
                service=self.service)
925
        patient_records = []
926
        page = self.request.GET.get('page')
927
        paginator = Paginator(ctx['object_list'].filter(), 50)
928
        try:
929
            paginate_patient_records = paginator.page(page)
930
        except PageNotAnInteger:
931
            paginate_patient_records = paginator.page(1)
932
        except EmptyPage:
933
            paginate_patient_records = paginator.page(paginator.num_pages)
934

    
935
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
936
        ctx['paginate_patient_records'] = paginate_patient_records
937

    
938
        query = self.request.GET.copy()
939
        if 'page' in query:
940
            del query['page']
941
        ctx['query'] = query.urlencode()
942

    
943
        return ctx
944

    
945
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
946

    
947
class NewProtectionStateView(cbv.CreateView):
948
    model = ProtectionState
949
    template_name = 'dossiers/generic_form.html'
950
    success_url = '../view#tab=1'
951
    form_class = forms.ProtectionStateForm
952

    
953
    def form_valid(self, form):
954
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
955
        form.instance.patient = self.patient
956
        return super(NewProtectionStateView, self).form_valid(form)
957

    
958
new_protection = NewProtectionStateView.as_view()
959

    
960
class UpdateProtectionStateView(cbv.UpdateView):
961
    model = ProtectionState
962
    template_name = 'dossiers/generic_form.html'
963
    success_url = '../../view#tab=1'
964
    form_class = forms.ProtectionStateForm
965

    
966
    def form_valid(self, form):
967
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
968
        form.instance.patient = self.patient
969
        return super(UpdateProtectionStateView, self).form_valid(form)
970

    
971
update_protection = UpdateProtectionStateView.as_view()
972

    
973
class DeleteProtectionStateView(cbv.DeleteView):
974
    model = ProtectionState
975
    template_name = 'dossiers/protection_confirm_delete.html'
976
    success_url = '../../view#tab=1'
977

    
978
delete_protection = DeleteProtectionStateView.as_view()
979

    
980
class PatientRecordsWaitingQueueView(cbv.ListView):
981
    model = PatientRecord
982
    template_name = 'dossiers/waiting_queue.html'
983

    
984
    def _get_search_result(self, paginate_patient_records,
985
            all_patient_records):
986
        patient_records = []
987
        if paginate_patient_records:
988
            position = 1
989
            for patient_record in paginate_patient_records:
990
                while patient_record.id != all_patient_records[position - 1].id:
991
                    position += 1
992
                patient_records.append(
993
                        {
994
                            'object': patient_record,
995
                            'position': position,
996
                            }
997
                        )
998
        return patient_records
999

    
1000
    def get_queryset(self):
1001
        form = forms.QuotationsForm(data=self.request.GET or None)
1002
        qs = super(PatientRecordsWaitingQueueView, self).get_queryset()
1003
        first_name = self.request.GET.get('first_name')
1004
        last_name = self.request.GET.get('last_name')
1005
        paper_id = self.request.GET.get('paper_id')
1006
        id = self.request.GET.get('id')
1007
        social_security_id = self.request.GET.get('social_security_id')
1008
        qs = qs.filter(service=self.service,
1009
            last_state__status__type='ACCUEIL')
1010
        if last_name:
1011
            qs = qs.filter(last_name__istartswith=last_name)
1012
        if first_name:
1013
            qs = qs.filter(first_name__istartswith=first_name)
1014
        if paper_id:
1015
            qs = qs.filter(paper_id__startswith=paper_id)
1016
        if id:
1017
            qs = qs.filter(id__startswith=id)
1018
        if social_security_id:
1019
            qs = qs.filter(models.Q(
1020
                social_security_id__startswith=social_security_id)
1021
                | models.Q(
1022
                contacts__social_security_id__startswith=social_security_id))
1023
        qs = qs.order_by('last_state__date_selected', 'created')
1024
        return qs
1025

    
1026
    def get_context_data(self, **kwargs):
1027
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
1028
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
1029
                service=self.service)
1030
        patient_records = []
1031
        page = self.request.GET.get('page')
1032
        paginator = Paginator(ctx['object_list'].filter(), 50)
1033
        try:
1034
            paginate_patient_records = paginator.page(page)
1035
        except PageNotAnInteger:
1036
            paginate_patient_records = paginator.page(1)
1037
        except EmptyPage:
1038
            paginate_patient_records = paginator.page(paginator.num_pages)
1039

    
1040
        all_patient_records = PatientRecord.objects.filter(
1041
                service=self.service,
1042
                last_state__status__type='ACCUEIL').order_by(
1043
                'last_state__date_selected', 'created')
1044
        ctx['patient_records'] = self._get_search_result(
1045
            paginate_patient_records, all_patient_records)
1046
        ctx['paginate_patient_records'] = paginate_patient_records
1047
        ctx['len_patient_records'] = all_patient_records.count()
1048

    
1049
        query = self.request.GET.copy()
1050
        if 'page' in query:
1051
            del query['page']
1052
        ctx['query'] = query.urlencode()
1053

    
1054
        return ctx
1055

    
1056
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1057

    
1058
class CreateDirectoryView(View, cbv.ServiceViewMixin):
1059
    def post(self, request, *args, **kwargs):
1060
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
1061
        service = Service.objects.get(slug=kwargs['service'])
1062
        patient.get_ondisk_directory(service.name)
1063
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
1064
        return HttpResponseRedirect('view')
1065

    
1066
create_directory = CreateDirectoryView.as_view()
1067

    
1068
class GenerateTransportPrescriptionFormView(cbv.FormView):
1069
    template_name = 'dossiers/generate_transport_prescription_form.html'
1070
    form_class = Form
1071
    success_url = './view#tab=1'
1072

    
1073
    def get_context_data(self, **kwargs):
1074
        ctx = super(GenerateTransportPrescriptionFormView, self).get_context_data(**kwargs)
1075
        ctx['lieu'] = 'Saint-Etienne'
1076
        ctx['date'] = formats.date_format(datetime.today(), "SHORT_DATE_FORMAT")
1077
        ctx['id_etab'] = '''%s SAINT ETIENNE
1078
66/68, RUE MARENGO
1079
42000 SAINT ETIENNE''' % ctx['service'].upper()
1080
        try:
1081
            patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1082
            ctx['object'] = patient
1083
            last_log = TransportPrescriptionLog.objects.filter(patient=patient).latest('created')
1084
            if last_log:
1085
                ctx['choices'] = last_log.get_choices()
1086
                if 'lieu' in ctx['choices'] and ctx['choices']['lieu']:
1087
                    ctx['lieu'] = ctx['choices']['lieu']
1088
                if 'date' in ctx['choices'] and ctx['choices']['date']:
1089
                    ctx['date'] = ctx['choices']['date']
1090
                if 'id_etab' in ctx['choices'] and ctx['choices']['id_etab']:
1091
                    ctx['id_etab'] = ctx['choices']['id_etab']
1092
        except:
1093
            pass
1094
        return ctx
1095

    
1096
    def form_valid(self, form):
1097
        patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1098
        address = PatientAddress.objects.get(id=form.data['address_id'])
1099
        path = render_transport(patient, address, form.data)
1100
        content = File(file(path))
1101
        log = TransportPrescriptionLog(patient=patient)
1102
        log.set_choices(form.data)
1103
        log.save()
1104
        response = HttpResponse(content,'application/pdf')
1105
        response['Content-Length'] = content.size
1106
        dest_filename = "%s--prescription-transport-%s-%s.pdf" \
1107
            % (datetime.now().strftime('%Y-%m-%d--%H:%M:%S'),
1108
            patient.last_name.upper().encode('utf-8'),
1109
            patient.first_name.encode('utf-8'))
1110
        response['Content-Disposition'] = \
1111
            'attachment; filename="%s"' % dest_filename
1112
        return response
1113

    
1114
prescription_transport = GenerateTransportPrescriptionFormView.as_view()
(11-11/11)