Projet

Général

Profil

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

calebasse / calebasse / dossiers / views.py @ 95593005

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
            }
339
    template_name = 'dossiers/patientrecord_tab3_adresses.html'
340
    success_url = './view#tab=2'
341

    
342

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

    
349
tab3_addresses = PatientRecordAddrView.as_view()
350

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

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

    
385
tab4_notifs = PatientRecordNotifsView.as_view()
386

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

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

    
420
tab5_old_acts = PatientRecordOldActs.as_view()
421

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

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

    
457
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
458

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

    
463
tab7_socialisation = PatientRecordSocialisationView.as_view()
464

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

    
471
tab8_medical = PatientRecordMedicalView.as_view()
472

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

    
477

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

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

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

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

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

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

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

    
565
patientrecord_home = PatientRecordsHomepageView.as_view()
566

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

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

    
574

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

    
581
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
582

    
583

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

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

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

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

    
604
new_socialisation_duration = NewSocialisationDurationView.as_view()
605

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

    
612
    def get(self, request, *args, **kwargs):
613
        if kwargs.has_key('patientrecord_id'):
614
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
615
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
616

    
617
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
618

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

    
625
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
626

    
627

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

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

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

    
646

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

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

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

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

    
680

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

    
696

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

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

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

    
709
class DeletePatientView(cbv.DeleteView):
710

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

    
724

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

    
735

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

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

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

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

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

    
854
generate_rtf_form = GenerateRtfFormView.as_view()
855

    
856

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

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

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

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

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

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

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

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

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

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

    
954
        return ctx
955

    
956
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
957

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

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

    
969
new_protection = NewProtectionStateView.as_view()
970

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

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

    
982
update_protection = UpdateProtectionStateView.as_view()
983

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

    
989
delete_protection = DeleteProtectionStateView.as_view()
990

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

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

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

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

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

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

    
1065
        return ctx
1066

    
1067
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1068

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

    
1077
create_directory = CreateDirectoryView.as_view()
1078

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

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

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

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