Projet

Général

Profil

Télécharger (46,9 ko) Statistiques
| Branche: | Tag: | Révision:

calebasse / calebasse / dossiers / views.py @ 97fbc132

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
            deficiencies = [getattr(patient_record, field) \
867
                            for field in self.model.DEFICIENCY_FIELDS]
868
            anap = any(deficiencies)
869
            mises = reduce(lambda m1, m2: m1+m2, [list(getattr(patient_record, field).all()) for field in self.model.MISES_FIELDS])
870
            next_rdv = get_next_rdv(patient_record)
871
            last_rdv = get_last_rdv(patient_record)
872

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

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

    
903
        if without_anap_quotations:
904
            for field in self.model.DEFICIENCY_FIELDS:
905
                anap_field = {field: 0}
906
                qs = qs.filter(**anap_field)
907

    
908
        states = self.request.GET.getlist('states')
909
        qs = qs.filter(last_state__status__id__in=states)
910

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

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

    
945
        ctx['patient_records'] = self._get_search_result(patient_records)
946

    
947
        query = self.request.GET.copy()
948
        if 'page' in query:
949
            del query['page']
950
        ctx['query'] = query.urlencode()
951

    
952
        return ctx
953

    
954
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
955

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

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

    
967
new_protection = NewProtectionStateView.as_view()
968

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

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

    
980
update_protection = UpdateProtectionStateView.as_view()
981

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

    
987
delete_protection = DeleteProtectionStateView.as_view()
988

    
989
class PatientRecordsWaitingQueueView(cbv.ListView):
990
    model = PatientRecord
991
    template_name = 'dossiers/waiting_queue.html'
992

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

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

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

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

    
1058
        query = self.request.GET.copy()
1059
        if 'page' in query:
1060
            del query['page']
1061
        ctx['query'] = query.urlencode()
1062

    
1063
        return ctx
1064

    
1065
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1066

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

    
1075
create_directory = CreateDirectoryView.as_view()
1076

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

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

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

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