Projet

Général

Profil

Télécharger (47,1 ko) Statistiques
| Branche: | Tag: | Révision:

calebasse / calebasse / dossiers / views.py @ a869df8f

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.views_utils import get_next_rdv, get_last_rdv, get_status
23
from calebasse.dossiers.transport import render_transport
24
from calebasse.agenda.models import Event, EventWithAct
25
from calebasse.actes.models import Act
26
from calebasse.agenda.appointments import Appointment
27
from calebasse.dossiers.models import (PatientRecord, PatientContact,
28
        PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
29
        CmppHealthCareDiagnostic, SessadHealthCareNotification, HealthCare,
30
        TransportPrescriptionLog, ProtectionState)
31
from calebasse.dossiers.states import STATES_MAPPING, STATES_BTN_MAPPER
32
from calebasse.ressources.models import (Service,
33
    SocialisationDuration, MDPHRequest, MDPHResponse)
34
from calebasse.facturation.list_acts import list_acts_for_billing_CMPP_per_patient
35
from calebasse.facturation.invoice_header import render_to_pdf_file
36

    
37
from calebasse.decorators import validator_only
38

    
39

    
40
class NewPatientRecordView(cbv.FormView, cbv.ServiceViewMixin):
41
    form_class = forms.NewPatientRecordForm
42
    template_name = 'dossiers/patientrecord_new.html'
43
    success_url = '..'
44
    patient = None
45

    
46
    def post(self, request, *args, **kwarg):
47
        self.user = request.user
48
        return super(NewPatientRecordView, self).post(request, *args, **kwarg)
49

    
50
    def form_valid(self, form):
51
        self.patient = create_patient(form.data['first_name'], form.data['last_name'], self.service,
52
                self.user, date_selected=datetime.strptime(form.data['date_selected'], "%d/%m/%Y"))
53
        return super(NewPatientRecordView, self).form_valid(form)
54

    
55
    def get_success_url(self):
56
        return '%s/view' % self.patient.id
57

    
58
new_patient_record = NewPatientRecordView.as_view()
59

    
60
class RecordPatientRecordIdMixing(object):
61
    def dispatch(self, request, *args, **kwargs):
62
        self.patientrecord_id = request.session['patientrecord_id'] = int(kwargs['patientrecord_id'])
63
        return super(RecordPatientRecordIdMixing, self).dispatch(request, *args, **kwargs)
64

    
65
    def get_form_kwargs(self):
66
        kwargs = super(RecordPatientRecordIdMixing, self).get_form_kwargs()
67
        kwargs['patient'] = PatientRecord.objects.get(id=self.patientrecord_id)
68
        return kwargs
69

    
70
class NewPatientContactView(RecordPatientRecordIdMixing, cbv.CreateView):
71
    model = PatientContact
72
    form_class = forms.PatientContactForm
73
    template_name = 'dossiers/patientcontact_new.html'
74
    success_url = '../view#tab=2'
75

    
76
    def get_initial(self):
77
        initial = super(NewPatientContactView, self).get_initial()
78
        fields = self.form_class.base_fields.keys()
79
        for arg in self.request.GET.keys():
80
            if arg in fields:
81
                if arg == 'addresses':
82
                    value = self.request.GET.getlist(arg)
83
                else:
84
                    value = self.request.GET.get(arg)
85
                initial[arg] = value
86
        if initial:
87
            if not initial.has_key('addresses'):
88
                initial['addresses'] = []
89
            patient = PatientRecord.objects.get(id=self.patientrecord_id)
90
            addresses = patient.addresses.order_by('-id')
91
            if addresses:
92
                initial['addresses'].append(addresses[0].pk)
93
        return initial
94

    
95
new_patient_contact = NewPatientContactView.as_view()
96

    
97
class UpdatePatientContactView(RecordPatientRecordIdMixing, cbv.NotificationDisplayView, cbv.UpdateView):
98
    model = PatientContact
99
    form_class = forms.PatientContactForm
100
    template_name = 'dossiers/patientcontact_new.html'
101
    success_url = '../../view#tab=2'
102

    
103
update_patient_contact = UpdatePatientContactView.as_view()
104

    
105
class DeletePatientContactView(cbv.DeleteView):
106
    model = PatientContact
107
    form_class = forms.PatientContactForm
108
    template_name = 'dossiers/patientcontact_confirm_delete.html'
109
    success_url = '../../view#tab=2'
110

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

    
121
delete_patient_contact = DeletePatientContactView.as_view()
122

    
123
class NewPatientAddressView(cbv.CreateView):
124
    model = PatientAddress
125
    form_class = forms.PatientAddressForm
126
    template_name = 'dossiers/patientaddress_new.html'
127
    success_url = '../view#tab=2'
128

    
129
    def get_success_url(self):
130
        return self.success_url
131

    
132
    def form_valid(self, form):
133
        patientaddress = form.save()
134
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
135
        patientrecord.addresses.add(patientaddress)
136
        messages.add_message(self.request, messages.INFO, u'Nouvelle adresse enregistrée avec succès.')
137
        return HttpResponseRedirect(self.get_success_url())
138

    
139
new_patient_address = NewPatientAddressView.as_view()
140

    
141
class UpdatePatientAddressView(cbv.NotificationDisplayView, cbv.UpdateView):
142
    model = PatientAddress
143
    form_class = forms.PatientAddressForm
144
    template_name = 'dossiers/patientaddress_new.html'
145
    success_url = '../../view#tab=2'
146

    
147
update_patient_address = UpdatePatientAddressView.as_view()
148

    
149
class DeletePatientAddressView(cbv.DeleteView):
150
    model = PatientAddress
151
    form_class = forms.PatientAddressForm
152
    template_name = 'dossiers/patientaddress_confirm_delete.html'
153
    success_url = '../../view#tab=2'
154

    
155
delete_patient_address = DeletePatientAddressView.as_view()
156

    
157

    
158
class NewHealthCareView(cbv.CreateView):
159

    
160
    def get_initial(self):
161
        initial = super(NewHealthCareView, self).get_initial()
162
        initial['author'] = self.request.user.id
163
        initial['patient'] = self.kwargs['patientrecord_id']
164
        return initial
165

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

    
209

    
210
class StateFormView(cbv.FormView):
211
    template_name = 'dossiers/state.html'
212
    form_class = forms.StateForm
213
    success_url = './view#tab=0'
214

    
215

    
216
    def post(self, request, *args, **kwarg):
217
        self.user = request.user
218
        return super(StateFormView, self).post(request, *args, **kwarg)
219

    
220
    def form_valid(self, form):
221
        service = Service.objects.get(id=form.data['service_id'])
222
        status = Status.objects.filter(services=service).filter(type=form.data['state_type'])
223
        patient = PatientRecord.objects.get(id=form.data['patient_id'])
224
        date_selected = datetime.strptime(form.data['date'], "%d/%m/%Y")
225
        patient.set_state(status[0], self.user, date_selected, form.data['comment'])
226
        return super(StateFormView, self).form_valid(form)
227

    
228
state_form = StateFormView.as_view()
229

    
230
class PatientRecordView(cbv.UpdateView):
231
    model = PatientRecord
232
    template_name = 'dossiers/patientrecord_update.html'
233

    
234
    def get_context_data(self, **kwargs):
235
        ctx = super(PatientRecordView, self).get_context_data(**kwargs)
236
        ctx['object'].create_diag_healthcare(self.request.user)
237
        ctx['object'].automated_switch_state(self.request.user)
238
        current_state = ctx['object'].get_current_state()
239
        if not current_state:
240
            current_state = ctx['object'].get_state()
241
            ctx['future_state'] = True
242
        if STATES_MAPPING.has_key(current_state.status.type):
243
            state = STATES_MAPPING[current_state.status.type]
244
        else:
245
            state = current_state.status.name
246
        ctx['current_state'] = current_state
247
        ctx['service_id'] = self.service.id
248
        ctx['states'] = FileState.objects.filter(patient=self.object) \
249
                .filter(status__services=self.service) \
250
                .order_by('-date_selected')
251
        return ctx
252

    
253
patient_record = PatientRecordView.as_view()
254

    
255
class PatientRecordPrint(cbv.DetailView):
256
    model = PatientRecord
257
    content_type = 'application/pdf'
258
    template_name = 'dossiers/patientrecord_print.html'
259

    
260
    def get_context_data(self, *args, **kwargs):
261
        context = super(PatientRecordPrint, self).get_context_data(*args, **kwargs)
262
        for view in (PatientRecordGeneralView, PatientRecordAdmView,
263
                     PatientRecordAddrView, PatientRecordNotifsView, PatientRecordOldActs,
264
                     PatientRecordNextAppointmentsView, PatientRecordSocialisationView):
265
            view_instance = view(request=self.request, object=self.object,
266
                                 service=self.service)
267
            context.update(view_instance.get_context_data(object=self.object))
268
        return context
269

    
270
    def get(self, request, *args, **kwargs):
271
        self.object = self.get_object()
272
        path = render_to_pdf_file([self.template_name],
273
                                  self.get_context_data(object = self.object))
274
        content = File(file(path))
275
        response = HttpResponse(content, self.content_type)
276
        response['Content-Length'] = content.size
277
        output = 'dossier_%s.pdf' % self.object.id
278
        response['Content-Disposition'] = \
279
            'attachment; filename="%s"' % output
280
        return response
281

    
282
patient_record_print = PatientRecordPrint.as_view()
283

    
284
class PatientRecordGeneralView(cbv.UpdateView):
285
    model = PatientRecord
286
    form_class = forms.GeneralForm
287
    template_name = 'dossiers/patientrecord_tab1_general.html'
288
    success_url = './view'
289

    
290
    def get_context_data(self, **kwargs):
291
        ctx = super(PatientRecordGeneralView, self).get_context_data(**kwargs)
292
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
293
        ctx['initial_state'] = ctx['object'].get_initial_state()
294
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
295
        ctx['next_rdv'] = get_next_rdv(ctx['object'])
296
        current_state = ctx['object'].get_current_state()
297
        if current_state.status and STATES_MAPPING.has_key(current_state.status.type):
298
            state = STATES_MAPPING[current_state.status.type]
299
        elif current_state.status:
300
            state = current_state.status.name
301
        else:
302
            state = "Aucun"
303
        ctx['current_state'] = current_state
304
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
305
        ctx['missing_policy'] = False
306
        if not self.object.policyholder or \
307
                not self.object.policyholder.health_center or \
308
                not self.object.policyholder.social_security_id:
309
            ctx['missing_policy'] = True
310
        ctx['missing_birthdate'] = False
311
        if not self.object.birthdate:
312
            ctx['missing_birthdate'] = True
313
        return ctx
314

    
315
tab1_general = PatientRecordGeneralView.as_view()
316

    
317
class PatientRecordAdmView(cbv.UpdateView):
318
    model = PatientRecord
319
    form_class = forms.AdministrativeForm
320
    template_name = 'dossiers/patientrecord_tab2_fiche_adm.html'
321
    success_url = './view#tab=1'
322

    
323
    def get_context_data(self, **kwargs):
324
        ctx = super(PatientRecordAdmView, self).get_context_data(**kwargs)
325
        try:
326
            ctx['last_prescription'] = TransportPrescriptionLog.objects.filter(patient=ctx['object']).latest('created')
327
        except:
328
            pass
329
        return ctx
330

    
331
tab2_fiche_adm = PatientRecordAdmView.as_view()
332

    
333
class PatientRecordAddrView(cbv.ServiceViewMixin, cbv.NotificationDisplayView, cbv.MultiUpdateView):
334
    model = PatientRecord
335
    forms_classes = {
336
            'contact': forms.PatientContactForm,
337
            'policyholder': forms.PolicyHolderForm,
338
            'comment' : forms.AddrCommentForm,
339
            }
340
    template_name = 'dossiers/patientrecord_tab3_adresses.html'
341
    success_url = './view#tab=2'
342

    
343

    
344
    def get_context_data(self, **kwargs):
345
        ctx = super(PatientRecordAddrView, self).get_context_data(**kwargs)
346
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
347
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
348
        return ctx
349

    
350
tab3_addresses = PatientRecordAddrView.as_view()
351

    
352
class PatientRecordNotifsView(cbv.DetailView):
353
    model = PatientRecord
354
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
355

    
356
    def get_context_data(self, **kwargs):
357
        ctx = super(PatientRecordNotifsView, self).get_context_data(**kwargs)
358
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
359
        if ctx['object'].service.slug == "cmpp":
360
            (acts_not_locked, days_not_locked, acts_not_valide,
361
            acts_not_billable, acts_pause, acts_per_hc, acts_losts) = \
362
                list_acts_for_billing_CMPP_per_patient(self.object,
363
                    datetime.today(), self.service)
364
            ctx['acts_losts'] = acts_losts
365
            ctx['acts_pause'] = acts_pause
366
            hcs_used = acts_per_hc.keys()
367
            hcs = None
368
            if not hcs_used:
369
                hcs = [(hc, None) for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date')]
370
            else:
371
                hcs = []
372
                for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date'):
373
                    acts = None
374
                    if hasattr(hc, 'cmpphealthcarediagnostic') and hc.cmpphealthcarediagnostic in hcs_used:
375
                        acts = acts_per_hc[hc.cmpphealthcarediagnostic]
376
                    elif hasattr(hc, 'cmpphealthcaretreatment') and hc.cmpphealthcaretreatment in hcs_used:
377
                        acts = acts_per_hc[hc.cmpphealthcaretreatment]
378
                    hcs.append((hc, acts))
379
            ctx['hcs'] = []
380
            for hc, acts in hcs:
381
                ctx['hcs'].append((hc, acts, hc.act_set.order_by('date', 'time')))
382
        elif ctx['object'].service.slug == "sessad-ted" or ctx['object'].service.slug == "sessad-dys":
383
            ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
384
        return ctx
385

    
386
tab4_notifs = PatientRecordNotifsView.as_view()
387

    
388
class PatientRecordOldActs(cbv.DetailView):
389
    model = PatientRecord
390
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
391

    
392
    def get_context_data(self, **kwargs):
393
        ctx = super(PatientRecordOldActs, self).get_context_data(**kwargs)
394
        ctx['last_rdvs'] = []
395
        for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
396
            state = act.get_state()
397
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
398
                state = None
399
            missing_workers = []
400
            try:
401
                missing_workers = [participant.worker for participant in act.event.get_missing_participants()]
402
            except:
403
                pass
404
            ctx['last_rdvs'].append((act, state, missing_workers))
405
        history = []
406
        i = 0
407
        for state in ctx['object'].filestate_set.order_by('-date_selected'):
408
            acts = []
409
            try:
410
                while ctx['last_rdvs'][i][0].date >= state.date_selected.date():
411
                    acts.append(ctx['last_rdvs'][i])
412
                    i += 1
413
            except:
414
                pass
415
            history.append((state, acts))
416
        if i < len(ctx['last_rdvs']) - 1:
417
            history.append((None, ctx['last_rdvs'][i:]))
418
        ctx['history'] = history
419
        return ctx
420

    
421
tab5_old_acts = PatientRecordOldActs.as_view()
422

    
423
class PatientRecordNextAppointmentsView(cbv.DetailView):
424
    model = PatientRecord
425
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
426

    
427
    def get_context_data(self, **kwargs):
428
        ctx = super(PatientRecordNextAppointmentsView, self).get_context_data(**kwargs)
429
        ctx['next_rdvs'] = []
430
        Q = models.Q
431
        today = date.today()
432
        qs = EventWithAct.objects.filter(patient=ctx['object']) \
433
                .filter(exception_to__isnull=True, canceled=False) \
434
                .filter(Q(start_datetime__gte=today) \
435
                |  Q(exceptions__isnull=False) \
436
                | ( Q(recurrence_periodicity__isnull=False) \
437
                & (Q(recurrence_end_date__gte=today) \
438
                | Q(recurrence_end_date__isnull=True) \
439
                ))) \
440
                .distinct() \
441
                .select_related() \
442
                .prefetch_related('participants', 'exceptions__eventwithact',
443
                        'act_set__actvalidationstate_set')
444
        occurrences = []
445
        for event in qs:
446
            occurrences.extend(filter(lambda e: e.start_datetime.date() >= today,
447
                event.all_occurences(limit=180)))
448
        occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
449
        for event in occurrences:
450
            state = None
451
            if event.act:
452
                state = event.act.get_state()
453
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
454
                state = None
455
            ctx['next_rdvs'].append((event, state, event.get_missing_participants(), event.get_inactive_participants()))
456
        return ctx
457

    
458
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
459

    
460
class PatientRecordSocialisationView(cbv.DetailView):
461
    model = PatientRecord
462
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
463

    
464
tab7_socialisation = PatientRecordSocialisationView.as_view()
465

    
466
class PatientRecordMedicalView(cbv.UpdateView):
467
    model = PatientRecord
468
    form_class = forms.PhysiologyForm
469
    template_name = 'dossiers/patientrecord_tab8_medical.html'
470
    success_url = './view#tab=7'
471

    
472
tab8_medical = PatientRecordMedicalView.as_view()
473

    
474
class PatientRecordsHomepageView(cbv.ListView):
475
    model = PatientRecord
476
    template_name = 'dossiers/index.html'
477

    
478

    
479
    def _get_search_result(self, paginate_patient_records):
480
        patient_records = []
481
        for patient_record in paginate_patient_records:
482
            next_rdv = get_next_rdv(patient_record)
483
            last_rdv = get_last_rdv(patient_record)
484
            current_status = patient_record.last_state.status
485
            state = current_status.name
486
            state_class = current_status.type.lower()
487
            patient_records.append(
488
                    {
489
                        'object': patient_record,
490
                        'next_rdv': next_rdv,
491
                        'last_rdv': last_rdv,
492
                        'state': state,
493
                        'state_class': state_class
494
                        }
495
                    )
496
        return patient_records
497

    
498
    def get_queryset(self):
499
        first_name = self.request.GET.get('first_name')
500
        last_name = self.request.GET.get('last_name')
501
        paper_id = self.request.GET.get('paper_id')
502
        id = self.request.GET.get('id')
503
        social_security_id = self.request.GET.get('social_security_id')
504
        if not (first_name or last_name or paper_id or id or social_security_id):
505
            return None
506
        if (first_name and len(first_name) < 2) or (last_name and len(last_name) < 2):
507
            return None
508
        qs = super(PatientRecordsHomepageView, self).get_queryset()
509
        states = self.request.GET.getlist('states')
510
        if last_name:
511
            qs = qs.filter(last_name__istartswith=last_name)
512
        if first_name:
513
            qs = qs.filter(first_name__istartswith=first_name)
514
        if paper_id:
515
            qs = qs.filter(paper_id__startswith=paper_id)
516
        if id:
517
            qs = qs.filter(id__startswith=id)
518
        if social_security_id:
519
            qs = qs.filter(models.Q(social_security_id__startswith=social_security_id) | \
520
                models.Q(contacts__social_security_id__startswith=social_security_id))
521
        if states:
522
            qs = qs.filter(last_state__status__id__in=states)
523
        else:
524
            qs = qs.filter(last_state__status__type__in="")
525
        qs = qs.filter(service=self.service).order_by('last_name').\
526
                prefetch_related('last_state',
527
                        'patientcontact', 'last_state__status')
528
        return qs
529

    
530
    def get_context_data(self, **kwargs):
531
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
532
        ctx['search_form'] = forms.SearchForm(service=self.service, data=self.request.GET or None)
533
        ctx['stats'] = [["Dossiers", 0]]
534
        for status in Status.objects.filter(services=self.service):
535
            ctx['stats'].append([status.name, 0])
536

    
537
        page = self.request.GET.get('page')
538
        if ctx['object_list']:
539
            patient_records = ctx['object_list'].filter()
540
        else:
541
            patient_records = []
542

    
543
        # TODO: use a sql query to do this
544
        for patient_record in patient_records:
545
            ctx['stats'][0][1] += 1
546
            for elem in ctx['stats']:
547
                if elem[0] == patient_record.last_state.status.name:
548
                    elem[1] += 1
549
        paginator = Paginator(patient_records, 50)
550
        try:
551
            paginate_patient_records = paginator.page(page)
552
        except PageNotAnInteger:
553
            paginate_patient_records = paginator.page(1)
554
        except EmptyPage:
555
            paginate_patient_records = paginator.page(paginator.num_pages)
556

    
557
        query = self.request.GET.copy()
558
        if 'page' in query:
559
            del query['page']
560
        ctx['query'] = query.urlencode()
561

    
562
        ctx['paginate_patient_records'] = paginate_patient_records
563
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
564
        return ctx
565

    
566
patientrecord_home = PatientRecordsHomepageView.as_view()
567

    
568
class PatientRecordDeleteView(DeleteView):
569
    model = PatientRecord
570
    success_url = ".."
571
    template_name = 'dossiers/patientrecord_confirm_delete.html'
572

    
573
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
574

    
575

    
576
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
577
    model = PatientRecord
578
    form_class = forms.PaperIDForm
579
    template_name = 'dossiers/generic_form.html'
580
    success_url = '../view#tab=0'
581

    
582
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
583

    
584

    
585
class NewSocialisationDurationView(cbv.CreateView):
586
    model = SocialisationDuration
587
    form_class = forms.SocialisationDurationForm
588
    template_name = 'dossiers/generic_form.html'
589
    success_url = '../view#tab=6'
590

    
591
    def get_success_url(self):
592
        return self.success_url
593

    
594
    def get(self, request, *args, **kwargs):
595
        if kwargs.has_key('patientrecord_id'):
596
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
597
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
598

    
599
    def form_valid(self, form):
600
        duration = form.save()
601
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
602
        patientrecord.socialisation_durations.add(duration)
603
        return HttpResponseRedirect(self.get_success_url())
604

    
605
new_socialisation_duration = NewSocialisationDurationView.as_view()
606

    
607
class UpdateSocialisationDurationView(cbv.UpdateView):
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(self, request, *args, **kwargs):
614
        if kwargs.has_key('patientrecord_id'):
615
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
616
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
617

    
618
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
619

    
620
class DeleteSocialisationDurationView(cbv.DeleteView):
621
    model = SocialisationDuration
622
    form_class = forms.SocialisationDurationForm
623
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
624
    success_url = '../../view#tab=6'
625

    
626
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
627

    
628

    
629
class NewMDPHRequestView(cbv.CreateView):
630
    def get(self, request, *args, **kwargs):
631
        if kwargs.has_key('patientrecord_id'):
632
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
633
        return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
634

    
635
    def form_valid(self, form):
636
        request = form.save()
637
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
638
        patientrecord.mdph_requests.add(request)
639
        return HttpResponseRedirect(self.success_url)
640

    
641
class UpdateMDPHRequestView(cbv.UpdateView):
642
    def get(self, request, *args, **kwargs):
643
        if kwargs.has_key('patientrecord_id'):
644
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
645
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
646

    
647

    
648
new_mdph_request = \
649
    NewMDPHRequestView.as_view(model=MDPHRequest,
650
        template_name = 'dossiers/generic_form.html',
651
        success_url = '../view#tab=6',
652
        form_class=forms.MDPHRequestForm)
653
update_mdph_request = \
654
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
655
        template_name = 'dossiers/generic_form.html',
656
        success_url = '../../view#tab=6',
657
        form_class=forms.MDPHRequestForm)
658
delete_mdph_request = \
659
    cbv.DeleteView.as_view(model=MDPHRequest,
660
        template_name = 'dossiers/generic_confirm_delete.html',
661
        success_url = '../../view#tab=6')
662

    
663
class NewMDPHResponseView(cbv.CreateView):
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(NewMDPHResponseView, self).get(request, *args, **kwargs)
668

    
669
    def form_valid(self, form):
670
        response = form.save()
671
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
672
        patientrecord.mdph_responses.add(response)
673
        return HttpResponseRedirect(self.success_url)
674

    
675
class UpdateMDPHResponseView(cbv.UpdateView):
676
    def get(self, request, *args, **kwargs):
677
        if kwargs.has_key('patientrecord_id'):
678
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
679
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
680

    
681

    
682
new_mdph_response = \
683
    NewMDPHResponseView.as_view(model=MDPHResponse,
684
        template_name = 'dossiers/generic_form.html',
685
        success_url = '../view#tab=6',
686
        form_class=forms.MDPHResponseForm)
687
update_mdph_response = \
688
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
689
        template_name = 'dossiers/generic_form.html',
690
        success_url = '../../view#tab=6',
691
        form_class=forms.MDPHResponseForm)
692
delete_mdph_response = \
693
    cbv.DeleteView.as_view(model=MDPHResponse,
694
        template_name = 'dossiers/generic_confirm_delete.html',
695
        success_url = '../../view#tab=6')
696

    
697

    
698
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
699

    
700
    def get_initial(self):
701
        initial = super(UpdatePatientStateView, self).get_initial()
702
        initial['date_selected'] = self.object.date_selected.date()
703
        return initial
704

    
705
    def get(self, request, *args, **kwargs):
706
        if kwargs.has_key('patientrecord_id'):
707
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
708
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
709

    
710
class DeletePatientView(cbv.DeleteView):
711

    
712
    def delete(self, request, *args, **kwargs):
713
        self.object = self.get_object()
714
        if self.object == self.object.patient.last_state:
715
            status = self.object.patient.filestate_set.all().order_by('-created')
716
            if len(status) > 1:
717
                self.object.patient.last_state = status[1]
718
                self.object.patient.save()
719
            else:
720
                # TODO return an error here
721
                return HttpResponseRedirect(self.get_success_url())
722
        self.object.delete()
723
        return HttpResponseRedirect(self.get_success_url())
724

    
725

    
726
update_patient_state = \
727
    UpdatePatientStateView.as_view(model=FileState,
728
        template_name = 'dossiers/generic_form.html',
729
        success_url = '../../view#tab=0',
730
        form_class=forms.PatientStateForm)
731
delete_patient_state = \
732
    DeletePatientView.as_view(model=FileState,
733
        template_name = 'dossiers/generic_confirm_delete.html',
734
        success_url = '../../view#tab=0')
735

    
736

    
737
class GenerateRtfFormView(cbv.FormView):
738
    template_name = 'dossiers/generate_rtf_form.html'
739
    form_class = forms.GenerateRtfForm
740
    success_url = './view#tab=0'
741

    
742
    def get_context_data(self, **kwargs):
743
        ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
744
        ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
745
        ctx['service_id'] = self.service.id
746
        if self.request.GET.get('event-id'):
747
            date = self.request.GET.get('date')
748
            date = datetime.strptime(date, '%Y-%m-%d').date()
749
            appointment = Appointment()
750
            event = EventWithAct.objects.get(id=self.request.GET.get('event-id'))
751
            event = event.today_occurrence(date)
752
            appointment.init_from_event(event, self.service)
753
            ctx['event'] = event
754
            ctx['appointment'] = appointment
755
        return ctx
756

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

    
836
        filename = make_doc_from_template(from_path, to_path, variables,
837
            persistent)
838

    
839
        client_dir = patient.get_client_side_directory(self.service.name)
840
        event.convocation_sent = True
841
        event.save()
842
        if not client_dir:
843
            content = File(file(filename))
844
            response = HttpResponse(content,'text/rtf')
845
            response['Content-Length'] = content.size
846
            response['Content-Disposition'] = 'attachment; filename="%s"' \
847
                % dest_filename.encode('utf-8')
848
            return response
849
        else:
850
            class LocalFileHttpResponseRedirect(HttpResponseRedirect):
851
                allowed_schemes = ['file']
852
            client_filepath = os.path.join(client_dir, dest_filename)
853
            return LocalFileHttpResponseRedirect('file://' + client_filepath)
854

    
855
generate_rtf_form = GenerateRtfFormView.as_view()
856

    
857

    
858
class PatientRecordsQuotationsView(cbv.ListView):
859
    model = PatientRecord
860
    template_name = 'dossiers/quotations.html'
861

    
862
    def _get_search_result(self, paginate_patient_records):
863
        patient_records = []
864
        for patient_record in paginate_patient_records:
865
            current_state = patient_record.get_current_state() or patient_record.get_state()
866
            state = current_state.status.name
867
            state_class = current_state.status.type.lower()
868
            deficiencies = [getattr(patient_record, field) \
869
                            for field in self.model.DEFICIENCY_FIELDS]
870
            anap = any(deficiencies)
871
            mises = reduce(lambda m1, m2: m1+m2, [list(getattr(patient_record, field).all()) for field in self.model.MISES_FIELDS])
872
            next_rdv = get_next_rdv(patient_record)
873
            last_rdv = get_last_rdv(patient_record)
874

    
875
            if next_rdv:
876
                next_rdv_datetime = next_rdv.start_datetime
877
            else:
878
                next_rdv_datetime = None
879
            if last_rdv:
880
                last_rdv_datetime = last_rdv['start_datetime']
881
            else:
882
                last_rdv_datetime = None
883
            patient_records.append(
884
                    {
885
                        'object': patient_record,
886
                        'state': state,
887
                        'state_class': state_class,
888
                        'anap': anap,
889
                        'mises': mises,
890
                        'next_rdv_date': next_rdv_datetime,
891
                        'last_rdv_date': last_rdv_datetime
892
                        }
893
                    )
894
        return patient_records
895

    
896
    def get_queryset(self):
897
        form = forms.QuotationsForm(data=self.request.GET or None)
898
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
899
        without_quotations = self.request.GET.get('without_quotations')
900
        without_anap_quotations = self.request.GET.get('without_anap_quotations')
901
        if without_quotations:
902
            for field in self.model.MISES_FIELDS:
903
                mise_field = {'%s__isnull' % field: True}
904
                qs = qs.filter(**mise_field)
905

    
906
        if without_anap_quotations:
907
            for field in self.model.DEFICIENCY_FIELDS:
908
                anap_field = {field: 0}
909
                qs = qs.filter(**anap_field)
910

    
911
        states = self.request.GET.getlist('states')
912
        qs = qs.filter(last_state__status__id__in=states)
913

    
914
        try:
915
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
916
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
917
        except (ValueError, KeyError):
918
            pass
919
        try:
920
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
921
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
922
        except (ValueError, KeyError):
923
            pass
924
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
925
        return qs
926

    
927
    def get_context_data(self, **kwargs):
928
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
929
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
930
                service=self.service)
931
        patient_records = []
932
        page = self.request.GET.get('page')
933
        all = 'all' in self.request.GET
934
        if all:
935
            patient_records = ctx['object_list']
936
            ctx['all'] = all
937
            self.template_name = 'dossiers/quotations_print.html'
938
        else:
939
            paginator = Paginator(ctx['object_list'].filter(), 50)
940
            try:
941
                patient_records = paginator.page(page)
942
            except PageNotAnInteger:
943
                patient_records = paginator.page(1)
944
            except EmptyPage:
945
                patient_records = paginator.page(paginator.num_pages)
946
            ctx['paginate_patient_records'] = patient_records
947

    
948
        ctx['patient_records'] = self._get_search_result(patient_records)
949

    
950
        query = self.request.GET.copy()
951
        if 'page' in query:
952
            del query['page']
953
        ctx['query'] = query.urlencode()
954

    
955
        return ctx
956

    
957
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
958

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

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

    
970
new_protection = NewProtectionStateView.as_view()
971

    
972
class UpdateProtectionStateView(cbv.UpdateView):
973
    model = ProtectionState
974
    template_name = 'dossiers/generic_form.html'
975
    success_url = '../../view#tab=1'
976
    form_class = forms.ProtectionStateForm
977

    
978
    def form_valid(self, form):
979
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
980
        form.instance.patient = self.patient
981
        return super(UpdateProtectionStateView, self).form_valid(form)
982

    
983
update_protection = UpdateProtectionStateView.as_view()
984

    
985
class DeleteProtectionStateView(cbv.DeleteView):
986
    model = ProtectionState
987
    template_name = 'dossiers/protection_confirm_delete.html'
988
    success_url = '../../view#tab=1'
989

    
990
delete_protection = DeleteProtectionStateView.as_view()
991

    
992
class PatientRecordsWaitingQueueView(cbv.ListView):
993
    model = PatientRecord
994
    template_name = 'dossiers/waiting_queue.html'
995

    
996
    def _get_search_result(self, paginate_patient_records,
997
            all_patient_records):
998
        patient_records = []
999
        if paginate_patient_records:
1000
            position = 1
1001
            for patient_record in paginate_patient_records:
1002
                while patient_record.id != all_patient_records[position - 1].id:
1003
                    position += 1
1004
                patient_records.append(
1005
                        {
1006
                            'object': patient_record,
1007
                            'position': position,
1008
                            }
1009
                        )
1010
        return patient_records
1011

    
1012
    def get_queryset(self):
1013
        form = forms.QuotationsForm(data=self.request.GET or None)
1014
        qs = super(PatientRecordsWaitingQueueView, self).get_queryset()
1015
        first_name = self.request.GET.get('first_name')
1016
        last_name = self.request.GET.get('last_name')
1017
        paper_id = self.request.GET.get('paper_id')
1018
        id = self.request.GET.get('id')
1019
        social_security_id = self.request.GET.get('social_security_id')
1020
        qs = qs.filter(service=self.service,
1021
            last_state__status__type='ACCUEIL')
1022
        if last_name:
1023
            qs = qs.filter(last_name__istartswith=last_name)
1024
        if first_name:
1025
            qs = qs.filter(first_name__istartswith=first_name)
1026
        if paper_id:
1027
            qs = qs.filter(paper_id__startswith=paper_id)
1028
        if id:
1029
            qs = qs.filter(id__startswith=id)
1030
        if social_security_id:
1031
            qs = qs.filter(models.Q(
1032
                social_security_id__startswith=social_security_id)
1033
                | models.Q(
1034
                contacts__social_security_id__startswith=social_security_id))
1035
        qs = qs.order_by('last_state__date_selected', 'created')
1036
        return qs
1037

    
1038
    def get_context_data(self, **kwargs):
1039
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
1040
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
1041
                service=self.service)
1042
        patient_records = []
1043
        page = self.request.GET.get('page')
1044
        paginator = Paginator(ctx['object_list'].filter(), 50)
1045
        try:
1046
            paginate_patient_records = paginator.page(page)
1047
        except PageNotAnInteger:
1048
            paginate_patient_records = paginator.page(1)
1049
        except EmptyPage:
1050
            paginate_patient_records = paginator.page(paginator.num_pages)
1051

    
1052
        all_patient_records = PatientRecord.objects.filter(
1053
                service=self.service,
1054
                last_state__status__type='ACCUEIL').order_by(
1055
                'last_state__date_selected', 'created')
1056
        ctx['patient_records'] = self._get_search_result(
1057
            paginate_patient_records, all_patient_records)
1058
        ctx['paginate_patient_records'] = paginate_patient_records
1059
        ctx['len_patient_records'] = all_patient_records.count()
1060

    
1061
        query = self.request.GET.copy()
1062
        if 'page' in query:
1063
            del query['page']
1064
        ctx['query'] = query.urlencode()
1065

    
1066
        return ctx
1067

    
1068
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1069

    
1070
class CreateDirectoryView(View, cbv.ServiceViewMixin):
1071
    def post(self, request, *args, **kwargs):
1072
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
1073
        service = Service.objects.get(slug=kwargs['service'])
1074
        patient.get_ondisk_directory(service.name)
1075
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
1076
        return HttpResponseRedirect('view')
1077

    
1078
create_directory = CreateDirectoryView.as_view()
1079

    
1080
class GenerateTransportPrescriptionFormView(cbv.FormView):
1081
    template_name = 'dossiers/generate_transport_prescription_form.html'
1082
    form_class = Form
1083
    success_url = './view#tab=1'
1084

    
1085
    def get_context_data(self, **kwargs):
1086
        ctx = super(GenerateTransportPrescriptionFormView, self).get_context_data(**kwargs)
1087
        ctx['lieu'] = 'Saint-Etienne'
1088
        ctx['date'] = formats.date_format(datetime.today(), "SHORT_DATE_FORMAT")
1089
        ctx['id_etab'] = '''%s SAINT ETIENNE
1090
66/68, RUE MARENGO
1091
42000 SAINT ETIENNE''' % ctx['service'].upper()
1092
        try:
1093
            patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1094
            ctx['object'] = patient
1095
            last_log = TransportPrescriptionLog.objects.filter(patient=patient).latest('created')
1096
            if last_log:
1097
                ctx['choices'] = last_log.get_choices()
1098
                if 'lieu' in ctx['choices'] and ctx['choices']['lieu']:
1099
                    ctx['lieu'] = ctx['choices']['lieu']
1100
                if 'date' in ctx['choices'] and ctx['choices']['date']:
1101
                    ctx['date'] = ctx['choices']['date']
1102
                if 'id_etab' in ctx['choices'] and ctx['choices']['id_etab']:
1103
                    ctx['id_etab'] = ctx['choices']['id_etab']
1104
        except:
1105
            pass
1106
        return ctx
1107

    
1108
    def form_valid(self, form):
1109
        patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1110
        address = PatientAddress.objects.get(id=form.data['address_id'])
1111
        path = render_transport(patient, address, form.data)
1112
        content = File(file(path))
1113
        log = TransportPrescriptionLog(patient=patient)
1114
        log.set_choices(form.data)
1115
        log.save()
1116
        response = HttpResponse(content,'application/pdf')
1117
        response['Content-Length'] = content.size
1118
        dest_filename = "%s--prescription-transport-%s-%s.pdf" \
1119
            % (datetime.now().strftime('%Y-%m-%d--%H:%M:%S'),
1120
            patient.last_name.upper().encode('utf-8'),
1121
            patient.first_name.encode('utf-8'))
1122
        response['Content-Disposition'] = \
1123
            'attachment; filename="%s"' % dest_filename
1124
        return response
1125

    
1126
prescription_transport = GenerateTransportPrescriptionFormView.as_view()
(11-11/12)