Projet

Général

Profil

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

calebasse / calebasse / dossiers / views.py @ 0a8aab32

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

    
36
from calebasse.decorators import validator_only
37

    
38

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

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

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

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

    
57
new_patient_record = NewPatientRecordView.as_view()
58

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

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

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

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

    
94
new_patient_contact = NewPatientContactView.as_view()
95

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

    
102
    def form_valid(self, form):
103
        valid = super(UpdatePatientContactView, self).form_valid(form)
104
        messages.info(self.request, u'Modification enregistrée avec succès')
105
        return valid
106

    
107
update_patient_contact = UpdatePatientContactView.as_view()
108

    
109
class DeletePatientContactView(cbv.DeleteView):
110
    model = PatientContact
111
    form_class = forms.PatientContactForm
112
    template_name = 'dossiers/patientcontact_confirm_delete.html'
113
    success_url = '../../view#tab=2'
114

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

    
125
delete_patient_contact = DeletePatientContactView.as_view()
126

    
127
class NewPatientAddressView(cbv.CreateView):
128
    model = PatientAddress
129
    form_class = forms.PatientAddressForm
130
    template_name = 'dossiers/patientaddress_new.html'
131
    success_url = '../view#tab=2'
132

    
133
    def get_success_url(self):
134
        return self.success_url
135

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

    
143
new_patient_address = NewPatientAddressView.as_view()
144

    
145
class UpdatePatientAddressView(cbv.UpdateView):
146
    model = PatientAddress
147
    form_class = forms.PatientAddressForm
148
    template_name = 'dossiers/patientaddress_new.html'
149
    success_url = '../../view#tab=2'
150

    
151
    def form_valid(self, form):
152
        messages.add_message(self.request,
153
                messages.INFO,
154
                u'Modification enregistrée avec succès.')
155
        return super(UpdatePatientAddressView, self).form_valid(form)
156

    
157
update_patient_address = UpdatePatientAddressView.as_view()
158

    
159
class DeletePatientAddressView(cbv.DeleteView):
160
    model = PatientAddress
161
    form_class = forms.PatientAddressForm
162
    template_name = 'dossiers/patientaddress_confirm_delete.html'
163
    success_url = '../../view#tab=2'
164

    
165
delete_patient_address = DeletePatientAddressView.as_view()
166

    
167

    
168
class NewHealthCareView(cbv.CreateView):
169

    
170
    def get_initial(self):
171
        initial = super(NewHealthCareView, self).get_initial()
172
        initial['author'] = self.request.user.id
173
        initial['patient'] = self.kwargs['patientrecord_id']
174
        return initial
175

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

    
219

    
220
class StateFormView(cbv.FormView):
221
    template_name = 'dossiers/state.html'
222
    form_class = forms.StateForm
223
    success_url = './view#tab=0'
224

    
225

    
226
    def post(self, request, *args, **kwarg):
227
        self.user = request.user
228
        return super(StateFormView, self).post(request, *args, **kwarg)
229

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

    
238
state_form = StateFormView.as_view()
239

    
240
class PatientRecordView(cbv.UpdateView):
241
    model = PatientRecord
242
    template_name = 'dossiers/patientrecord_update.html'
243

    
244
    def get_context_data(self, **kwargs):
245
        ctx = super(PatientRecordView, self).get_context_data(**kwargs)
246
        ctx['object'].create_diag_healthcare(self.request.user)
247
        ctx['object'].automated_switch_state(self.request.user)
248
        current_state = ctx['object'].get_current_state()
249
        if not current_state:
250
            current_state = ctx['object'].get_state()
251
            ctx['future_state'] = True
252
        if STATES_MAPPING.has_key(current_state.status.type):
253
            state = STATES_MAPPING[current_state.status.type]
254
        else:
255
            state = current_state.status.name
256
        ctx['current_state'] = current_state
257
        ctx['service_id'] = self.service.id
258
        ctx['states'] = FileState.objects.filter(patient=self.object) \
259
                .filter(status__services=self.service) \
260
                .order_by('-date_selected')
261
        return ctx
262

    
263
patient_record = PatientRecordView.as_view()
264

    
265
class PatientRecordGeneralView(cbv.UpdateView):
266
    model = PatientRecord
267
    form_class = forms.GeneralForm
268
    template_name = 'dossiers/patientrecord_tab1_general.html'
269
    success_url = './view'
270

    
271
    def get_context_data(self, **kwargs):
272
        ctx = super(PatientRecordGeneralView, self).get_context_data(**kwargs)
273
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
274
        ctx['initial_state'] = ctx['object'].get_initial_state()
275
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
276
        ctx['next_rdv'] = get_next_rdv(ctx['object'])
277
        current_state = ctx['object'].get_current_state()
278
        if current_state.status and STATES_MAPPING.has_key(current_state.status.type):
279
            state = STATES_MAPPING[current_state.status.type]
280
        elif current_state.status:
281
            state = current_state.status.name
282
        else:
283
            state = "Aucun"
284
        ctx['current_state'] = current_state
285
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
286
        ctx['missing_policy'] = False
287
        if not self.object.policyholder or \
288
                not self.object.policyholder.health_center or \
289
                not self.object.policyholder.social_security_id:
290
            ctx['missing_policy'] = True
291
        ctx['missing_birthdate'] = False
292
        if not self.object.birthdate:
293
            ctx['missing_birthdate'] = True
294
        return ctx
295

    
296
tab1_general = PatientRecordGeneralView.as_view()
297

    
298
class PatientRecordAdmView(cbv.UpdateView):
299
    model = PatientRecord
300
    form_class = forms.AdministrativeForm
301
    template_name = 'dossiers/patientrecord_tab2_fiche_adm.html'
302
    success_url = './view#tab=1'
303

    
304
    def get_context_data(self, **kwargs):
305
        ctx = super(PatientRecordAdmView, self).get_context_data(**kwargs)
306
        try:
307
            ctx['last_prescription'] = TransportPrescriptionLog.objects.filter(patient=ctx['object']).latest('created')
308
        except:
309
            pass
310
        return ctx
311

    
312
tab2_fiche_adm = PatientRecordAdmView.as_view()
313

    
314
class PatientRecordAddrView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
315
    model = PatientRecord
316
    forms_classes = {
317
            'contact': forms.PatientContactForm,
318
            'policyholder': forms.PolicyHolderForm
319
            }
320
    template_name = 'dossiers/patientrecord_tab3_adresses.html'
321
    success_url = './view#tab=2'
322

    
323

    
324
    def get_context_data(self, **kwargs):
325
        ctx = super(PatientRecordAddrView, self).get_context_data(**kwargs)
326
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
327
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
328
        return ctx
329

    
330
tab3_addresses = PatientRecordAddrView.as_view()
331

    
332
class PatientRecordNotifsView(cbv.DetailView):
333
    model = PatientRecord
334
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
335

    
336
    def get_context_data(self, **kwargs):
337
        ctx = super(PatientRecordNotifsView, self).get_context_data(**kwargs)
338
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
339
        if ctx['object'].service.slug == "cmpp":
340
            (acts_not_locked, days_not_locked, acts_not_valide,
341
            acts_not_billable, acts_pause, acts_per_hc, acts_losts) = \
342
                list_acts_for_billing_CMPP_per_patient(self.object,
343
                    datetime.today(), self.service)
344
            ctx['acts_losts'] = acts_losts
345
            ctx['acts_pause'] = acts_pause
346
            hcs_used = acts_per_hc.keys()
347
            hcs = None
348
            if not hcs_used:
349
                hcs = [(hc, None) for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date')]
350
            else:
351
                hcs = []
352
                for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date'):
353
                    acts = None
354
                    if hasattr(hc, 'cmpphealthcarediagnostic') and hc.cmpphealthcarediagnostic in hcs_used:
355
                        acts = acts_per_hc[hc.cmpphealthcarediagnostic]
356
                    elif hasattr(hc, 'cmpphealthcaretreatment') and hc.cmpphealthcaretreatment in hcs_used:
357
                        acts = acts_per_hc[hc.cmpphealthcaretreatment]
358
                    hcs.append((hc, acts))
359
            ctx['hcs'] = []
360
            for hc, acts in hcs:
361
                ctx['hcs'].append((hc, acts, hc.act_set.order_by('date', 'time')))
362
        elif ctx['object'].service.slug == "sessad-ted" or ctx['object'].service.slug == "sessad-dys":
363
            ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
364
        return ctx
365

    
366
tab4_notifs = PatientRecordNotifsView.as_view()
367

    
368
class PatientRecordOldActs(cbv.DetailView):
369
    model = PatientRecord
370
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
371

    
372
    def get_context_data(self, **kwargs):
373
        ctx = super(PatientRecordOldActs, self).get_context_data(**kwargs)
374
        ctx['last_rdvs'] = []
375
        for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
376
            state = act.get_state()
377
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
378
                state = None
379
            missing_workers = []
380
            try:
381
                missing_workers = [participant.worker for participant in act.event.get_missing_participants()]
382
            except:
383
                pass
384
            ctx['last_rdvs'].append((act, state, missing_workers))
385
        history = []
386
        i = 0
387
        for state in ctx['object'].filestate_set.order_by('-date_selected'):
388
            acts = []
389
            try:
390
                while ctx['last_rdvs'][i][0].date >= state.date_selected.date():
391
                    acts.append(ctx['last_rdvs'][i])
392
                    i += 1
393
            except:
394
                pass
395
            history.append((state, acts))
396
        if i < len(ctx['last_rdvs']) - 1:
397
            history.append((None, ctx['last_rdvs'][i:]))
398
        ctx['history'] = history
399
        return ctx
400

    
401
tab5_old_acts = PatientRecordOldActs.as_view()
402

    
403
class PatientRecordNextAppointmentsView(cbv.DetailView):
404
    model = PatientRecord
405
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
406

    
407
    def get_context_data(self, **kwargs):
408
        ctx = super(PatientRecordNextAppointmentsView, self).get_context_data(**kwargs)
409
        ctx['next_rdvs'] = []
410
        Q = models.Q
411
        today = date.today()
412
        qs = EventWithAct.objects.filter(patient=ctx['object']) \
413
                .filter(exception_to__isnull=True, canceled=False) \
414
                .filter(Q(start_datetime__gte=today) \
415
                |  Q(exceptions__isnull=False) \
416
                | ( Q(recurrence_periodicity__isnull=False) \
417
                & (Q(recurrence_end_date__gte=today) \
418
                | Q(recurrence_end_date__isnull=True) \
419
                ))) \
420
                .distinct() \
421
                .select_related() \
422
                .prefetch_related('participants', 'exceptions__eventwithact',
423
                        'act_set__actvalidationstate_set')
424
        occurrences = []
425
        for event in qs:
426
            occurrences.extend(filter(lambda e: e.start_datetime.date() >= today,
427
                event.all_occurences(limit=180)))
428
        occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
429
        for event in occurrences:
430
            state = None
431
            if event.act:
432
                state = event.act.get_state()
433
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
434
                state = None
435
            ctx['next_rdvs'].append((event, state, event.get_missing_participants(), event.get_inactive_participants()))
436
        return ctx
437

    
438
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
439

    
440
class PatientRecordSocialisationView(cbv.DetailView):
441
    model = PatientRecord
442
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
443

    
444
tab7_socialisation = PatientRecordSocialisationView.as_view()
445

    
446
class PatientRecordMedicalView(cbv.UpdateView):
447
    model = PatientRecord
448
    form_class = forms.PhysiologyForm
449
    template_name = 'dossiers/patientrecord_tab8_medical.html'
450
    success_url = './view#tab=7'
451

    
452
tab8_medical = PatientRecordMedicalView.as_view()
453

    
454
class PatientRecordsHomepageView(cbv.ListView):
455
    model = PatientRecord
456
    template_name = 'dossiers/index.html'
457

    
458

    
459
    def _get_search_result(self, paginate_patient_records):
460
        patient_records = []
461
        for patient_record in paginate_patient_records:
462
            next_rdv = get_next_rdv(patient_record)
463
            last_rdv = get_last_rdv(patient_record)
464
            current_status = patient_record.last_state.status
465
            state = current_status.name
466
            state_class = current_status.type.lower()
467
            patient_records.append(
468
                    {
469
                        'object': patient_record,
470
                        'next_rdv': next_rdv,
471
                        'last_rdv': last_rdv,
472
                        'state': state,
473
                        'state_class': state_class
474
                        }
475
                    )
476
        return patient_records
477

    
478
    def get_queryset(self):
479
        first_name = self.request.GET.get('first_name')
480
        last_name = self.request.GET.get('last_name')
481
        paper_id = self.request.GET.get('paper_id')
482
        id = self.request.GET.get('id')
483
        social_security_id = self.request.GET.get('social_security_id')
484
        if not (first_name or last_name or paper_id or id or social_security_id):
485
            return None
486
        if (first_name and len(first_name) < 2) or (last_name and len(last_name) < 2):
487
            return None
488
        qs = super(PatientRecordsHomepageView, self).get_queryset()
489
        states = self.request.GET.getlist('states')
490
        if last_name:
491
            qs = qs.filter(last_name__istartswith=last_name)
492
        if first_name:
493
            qs = qs.filter(first_name__istartswith=first_name)
494
        if paper_id:
495
            qs = qs.filter(paper_id__startswith=paper_id)
496
        if id:
497
            qs = qs.filter(id__startswith=id)
498
        if social_security_id:
499
            qs = qs.filter(models.Q(social_security_id__startswith=social_security_id) | \
500
                models.Q(contacts__social_security_id__startswith=social_security_id))
501
        if states:
502
            qs = qs.filter(last_state__status__id__in=states)
503
        else:
504
            qs = qs.filter(last_state__status__type__in="")
505
        qs = qs.filter(service=self.service).order_by('last_name').\
506
                prefetch_related('last_state',
507
                        'patientcontact', 'last_state__status')
508
        return qs
509

    
510
    def get_context_data(self, **kwargs):
511
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
512
        ctx['search_form'] = forms.SearchForm(service=self.service, data=self.request.GET or None)
513
        ctx['stats'] = [["Dossiers", 0]]
514
        for status in Status.objects.filter(services=self.service):
515
            ctx['stats'].append([status.name, 0])
516

    
517
        page = self.request.GET.get('page')
518
        if ctx['object_list']:
519
            patient_records = ctx['object_list'].filter()
520
        else:
521
            patient_records = []
522

    
523
        # TODO: use a sql query to do this
524
        for patient_record in patient_records:
525
            ctx['stats'][0][1] += 1
526
            for elem in ctx['stats']:
527
                if elem[0] == patient_record.last_state.status.name:
528
                    elem[1] += 1
529
        paginator = Paginator(patient_records, 50)
530
        try:
531
            paginate_patient_records = paginator.page(page)
532
        except PageNotAnInteger:
533
            paginate_patient_records = paginator.page(1)
534
        except EmptyPage:
535
            paginate_patient_records = paginator.page(paginator.num_pages)
536

    
537
        query = self.request.GET.copy()
538
        if 'page' in query:
539
            del query['page']
540
        ctx['query'] = query.urlencode()
541

    
542
        ctx['paginate_patient_records'] = paginate_patient_records
543
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
544
        return ctx
545

    
546
patientrecord_home = PatientRecordsHomepageView.as_view()
547

    
548
class PatientRecordDeleteView(DeleteView):
549
    model = PatientRecord
550
    success_url = ".."
551
    template_name = 'dossiers/patientrecord_confirm_delete.html'
552

    
553
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
554

    
555

    
556
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
557
    model = PatientRecord
558
    form_class = forms.PaperIDForm
559
    template_name = 'dossiers/generic_form.html'
560
    success_url = '../view#tab=0'
561

    
562
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
563

    
564

    
565
class NewSocialisationDurationView(cbv.CreateView):
566
    model = SocialisationDuration
567
    form_class = forms.SocialisationDurationForm
568
    template_name = 'dossiers/generic_form.html'
569
    success_url = '../view#tab=6'
570

    
571
    def get_success_url(self):
572
        return self.success_url
573

    
574
    def get(self, request, *args, **kwargs):
575
        if kwargs.has_key('patientrecord_id'):
576
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
577
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
578

    
579
    def form_valid(self, form):
580
        duration = form.save()
581
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
582
        patientrecord.socialisation_durations.add(duration)
583
        return HttpResponseRedirect(self.get_success_url())
584

    
585
new_socialisation_duration = NewSocialisationDurationView.as_view()
586

    
587
class UpdateSocialisationDurationView(cbv.UpdateView):
588
    model = SocialisationDuration
589
    form_class = forms.SocialisationDurationForm
590
    template_name = 'dossiers/generic_form.html'
591
    success_url = '../../view#tab=6'
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(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
597

    
598
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
599

    
600
class DeleteSocialisationDurationView(cbv.DeleteView):
601
    model = SocialisationDuration
602
    form_class = forms.SocialisationDurationForm
603
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
604
    success_url = '../../view#tab=6'
605

    
606
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
607

    
608

    
609
class NewMDPHRequestView(cbv.CreateView):
610
    def get(self, request, *args, **kwargs):
611
        if kwargs.has_key('patientrecord_id'):
612
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
613
        return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
614

    
615
    def form_valid(self, form):
616
        request = form.save()
617
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
618
        patientrecord.mdph_requests.add(request)
619
        return HttpResponseRedirect(self.success_url)
620

    
621
class UpdateMDPHRequestView(cbv.UpdateView):
622
    def get(self, request, *args, **kwargs):
623
        if kwargs.has_key('patientrecord_id'):
624
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
625
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
626

    
627

    
628
new_mdph_request = \
629
    NewMDPHRequestView.as_view(model=MDPHRequest,
630
        template_name = 'dossiers/generic_form.html',
631
        success_url = '../view#tab=6',
632
        form_class=forms.MDPHRequestForm)
633
update_mdph_request = \
634
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
635
        template_name = 'dossiers/generic_form.html',
636
        success_url = '../../view#tab=6',
637
        form_class=forms.MDPHRequestForm)
638
delete_mdph_request = \
639
    cbv.DeleteView.as_view(model=MDPHRequest,
640
        template_name = 'dossiers/generic_confirm_delete.html',
641
        success_url = '../../view#tab=6')
642

    
643
class NewMDPHResponseView(cbv.CreateView):
644
    def get(self, request, *args, **kwargs):
645
        if kwargs.has_key('patientrecord_id'):
646
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
647
        return super(NewMDPHResponseView, self).get(request, *args, **kwargs)
648

    
649
    def form_valid(self, form):
650
        response = form.save()
651
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
652
        patientrecord.mdph_responses.add(response)
653
        return HttpResponseRedirect(self.success_url)
654

    
655
class UpdateMDPHResponseView(cbv.UpdateView):
656
    def get(self, request, *args, **kwargs):
657
        if kwargs.has_key('patientrecord_id'):
658
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
659
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
660

    
661

    
662
new_mdph_response = \
663
    NewMDPHResponseView.as_view(model=MDPHResponse,
664
        template_name = 'dossiers/generic_form.html',
665
        success_url = '../view#tab=6',
666
        form_class=forms.MDPHResponseForm)
667
update_mdph_response = \
668
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
669
        template_name = 'dossiers/generic_form.html',
670
        success_url = '../../view#tab=6',
671
        form_class=forms.MDPHResponseForm)
672
delete_mdph_response = \
673
    cbv.DeleteView.as_view(model=MDPHResponse,
674
        template_name = 'dossiers/generic_confirm_delete.html',
675
        success_url = '../../view#tab=6')
676

    
677

    
678
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
679

    
680
    def get_initial(self):
681
        initial = super(UpdatePatientStateView, self).get_initial()
682
        initial['date_selected'] = self.object.date_selected.date()
683
        return initial
684

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

    
690
class DeletePatientView(cbv.DeleteView):
691

    
692
    def delete(self, request, *args, **kwargs):
693
        self.object = self.get_object()
694
        if self.object == self.object.patient.last_state:
695
            status = self.object.patient.filestate_set.all().order_by('-created')
696
            if len(status) > 1:
697
                self.object.patient.last_state = status[1]
698
                self.object.patient.save()
699
            else:
700
                # TODO return an error here
701
                return HttpResponseRedirect(self.get_success_url())
702
        self.object.delete()
703
        return HttpResponseRedirect(self.get_success_url())
704

    
705

    
706
update_patient_state = \
707
    UpdatePatientStateView.as_view(model=FileState,
708
        template_name = 'dossiers/generic_form.html',
709
        success_url = '../../view#tab=0',
710
        form_class=forms.PatientStateForm)
711
delete_patient_state = \
712
    DeletePatientView.as_view(model=FileState,
713
        template_name = 'dossiers/generic_confirm_delete.html',
714
        success_url = '../../view#tab=0')
715

    
716

    
717
class GenerateRtfFormView(cbv.FormView):
718
    template_name = 'dossiers/generate_rtf_form.html'
719
    form_class = forms.GenerateRtfForm
720
    success_url = './view#tab=0'
721

    
722
    def get_context_data(self, **kwargs):
723
        ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
724
        ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
725
        ctx['service_id'] = self.service.id
726
        if self.request.GET.get('event-id'):
727
            date = self.request.GET.get('date')
728
            date = datetime.strptime(date, '%Y-%m-%d').date()
729
            appointment = Appointment()
730
            event = EventWithAct.objects.get(id=self.request.GET.get('event-id'))
731
            event = event.today_occurrence(date)
732
            appointment.init_from_event(event, self.service)
733
            ctx['event'] = event
734
            ctx['appointment'] = appointment
735
        return ctx
736

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

    
816
        filename = make_doc_from_template(from_path, to_path, variables,
817
            persistent)
818

    
819
        client_dir = patient.get_client_side_directory(self.service.name)
820
        event.convocation_sent = True
821
        event.save()
822
        if not client_dir:
823
            content = File(file(filename))
824
            response = HttpResponse(content,'text/rtf')
825
            response['Content-Length'] = content.size
826
            response['Content-Disposition'] = 'attachment; filename="%s"' \
827
                % dest_filename.encode('utf-8')
828
            return response
829
        else:
830
            class LocalFileHttpResponseRedirect(HttpResponseRedirect):
831
                allowed_schemes = ['file']
832
            client_filepath = os.path.join(client_dir, dest_filename)
833
            return LocalFileHttpResponseRedirect('file://' + client_filepath)
834

    
835
generate_rtf_form = GenerateRtfFormView.as_view()
836

    
837

    
838
class PatientRecordsQuotationsView(cbv.ListView):
839
    model = PatientRecord
840
    template_name = 'dossiers/quotations.html'
841

    
842
    def _get_search_result(self, paginate_patient_records):
843
        patient_records = []
844
        for patient_record in paginate_patient_records:
845
            current_state = patient_record.get_current_state() or patient_record.get_state()
846
            state = current_state.status.name
847
            state_class = current_state.status.type.lower()
848
            deficiencies = [getattr(patient_record, field) \
849
                            for field in self.model.DEFICIENCY_FIELDS]
850
            anap = any(deficiencies)
851
            mises = reduce(lambda m1, m2: m1+m2, [list(getattr(patient_record, field).all()) for field in self.model.MISES_FIELDS])
852
            next_rdv = get_next_rdv(patient_record)
853
            last_rdv = get_last_rdv(patient_record)
854

    
855
            if next_rdv:
856
                next_rdv_datetime = next_rdv.start_datetime
857
            else:
858
                next_rdv_datetime = None
859
            if last_rdv:
860
                last_rdv_datetime = last_rdv['start_datetime']
861
            else:
862
                last_rdv_datetime = None
863
            patient_records.append(
864
                    {
865
                        'object': patient_record,
866
                        'state': state,
867
                        'state_class': state_class,
868
                        'anap': anap,
869
                        'mises': mises,
870
                        'next_rdv_date': next_rdv_datetime,
871
                        'last_rdv_date': last_rdv_datetime
872
                        }
873
                    )
874
        return patient_records
875

    
876
    def get_queryset(self):
877
        form = forms.QuotationsForm(data=self.request.GET or None)
878
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
879
        without_quotations = self.request.GET.get('without_quotations')
880
        without_anap_quotations = self.request.GET.get('without_anap_quotations')
881
        if without_quotations:
882
            for field in self.model.MISES_FIELDS:
883
                mise_field = {'%s__isnull' % field: True}
884
                qs = qs.filter(**mise_field)
885

    
886
        if without_anap_quotations:
887
            for field in self.model.DEFICIENCY_FIELDS:
888
                anap_field = {field: 0}
889
                qs = qs.filter(**anap_field)
890

    
891
        states = self.request.GET.getlist('states')
892
        qs = qs.filter(last_state__status__id__in=states)
893

    
894
        try:
895
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
896
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
897
        except (ValueError, KeyError):
898
            pass
899
        try:
900
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
901
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
902
        except (ValueError, KeyError):
903
            pass
904
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
905
        return qs
906

    
907
    def get_context_data(self, **kwargs):
908
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
909
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
910
                service=self.service)
911
        patient_records = []
912
        page = self.request.GET.get('page')
913
        all = 'all' in self.request.GET
914
        if all:
915
            patient_records = ctx['object_list']
916
            ctx['all'] = all
917
            self.template_name = 'dossiers/quotations_print.html'
918
        else:
919
            paginator = Paginator(ctx['object_list'].filter(), 50)
920
            try:
921
                patient_records = paginator.page(page)
922
            except PageNotAnInteger:
923
                patient_records = paginator.page(1)
924
            except EmptyPage:
925
                patient_records = paginator.page(paginator.num_pages)
926
            ctx['paginate_patient_records'] = patient_records
927

    
928
        ctx['patient_records'] = self._get_search_result(patient_records)
929

    
930
        query = self.request.GET.copy()
931
        if 'page' in query:
932
            del query['page']
933
        ctx['query'] = query.urlencode()
934

    
935
        return ctx
936

    
937
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
938

    
939
class NewProtectionStateView(cbv.CreateView):
940
    model = ProtectionState
941
    template_name = 'dossiers/generic_form.html'
942
    success_url = '../view#tab=1'
943
    form_class = forms.ProtectionStateForm
944

    
945
    def form_valid(self, form):
946
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
947
        form.instance.patient = self.patient
948
        return super(NewProtectionStateView, self).form_valid(form)
949

    
950
new_protection = NewProtectionStateView.as_view()
951

    
952
class UpdateProtectionStateView(cbv.UpdateView):
953
    model = ProtectionState
954
    template_name = 'dossiers/generic_form.html'
955
    success_url = '../../view#tab=1'
956
    form_class = forms.ProtectionStateForm
957

    
958
    def form_valid(self, form):
959
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
960
        form.instance.patient = self.patient
961
        return super(UpdateProtectionStateView, self).form_valid(form)
962

    
963
update_protection = UpdateProtectionStateView.as_view()
964

    
965
class DeleteProtectionStateView(cbv.DeleteView):
966
    model = ProtectionState
967
    template_name = 'dossiers/protection_confirm_delete.html'
968
    success_url = '../../view#tab=1'
969

    
970
delete_protection = DeleteProtectionStateView.as_view()
971

    
972
class PatientRecordsWaitingQueueView(cbv.ListView):
973
    model = PatientRecord
974
    template_name = 'dossiers/waiting_queue.html'
975

    
976
    def _get_search_result(self, paginate_patient_records,
977
            all_patient_records):
978
        patient_records = []
979
        if paginate_patient_records:
980
            position = 1
981
            for patient_record in paginate_patient_records:
982
                while patient_record.id != all_patient_records[position - 1].id:
983
                    position += 1
984
                patient_records.append(
985
                        {
986
                            'object': patient_record,
987
                            'position': position,
988
                            }
989
                        )
990
        return patient_records
991

    
992
    def get_queryset(self):
993
        form = forms.QuotationsForm(data=self.request.GET or None)
994
        qs = super(PatientRecordsWaitingQueueView, self).get_queryset()
995
        first_name = self.request.GET.get('first_name')
996
        last_name = self.request.GET.get('last_name')
997
        paper_id = self.request.GET.get('paper_id')
998
        id = self.request.GET.get('id')
999
        social_security_id = self.request.GET.get('social_security_id')
1000
        qs = qs.filter(service=self.service,
1001
            last_state__status__type='ACCUEIL')
1002
        if last_name:
1003
            qs = qs.filter(last_name__istartswith=last_name)
1004
        if first_name:
1005
            qs = qs.filter(first_name__istartswith=first_name)
1006
        if paper_id:
1007
            qs = qs.filter(paper_id__startswith=paper_id)
1008
        if id:
1009
            qs = qs.filter(id__startswith=id)
1010
        if social_security_id:
1011
            qs = qs.filter(models.Q(
1012
                social_security_id__startswith=social_security_id)
1013
                | models.Q(
1014
                contacts__social_security_id__startswith=social_security_id))
1015
        qs = qs.order_by('last_state__date_selected', 'created')
1016
        return qs
1017

    
1018
    def get_context_data(self, **kwargs):
1019
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
1020
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
1021
                service=self.service)
1022
        patient_records = []
1023
        page = self.request.GET.get('page')
1024
        paginator = Paginator(ctx['object_list'].filter(), 50)
1025
        try:
1026
            paginate_patient_records = paginator.page(page)
1027
        except PageNotAnInteger:
1028
            paginate_patient_records = paginator.page(1)
1029
        except EmptyPage:
1030
            paginate_patient_records = paginator.page(paginator.num_pages)
1031

    
1032
        all_patient_records = PatientRecord.objects.filter(
1033
                service=self.service,
1034
                last_state__status__type='ACCUEIL').order_by(
1035
                'last_state__date_selected', 'created')
1036
        ctx['patient_records'] = self._get_search_result(
1037
            paginate_patient_records, all_patient_records)
1038
        ctx['paginate_patient_records'] = paginate_patient_records
1039
        ctx['len_patient_records'] = all_patient_records.count()
1040

    
1041
        query = self.request.GET.copy()
1042
        if 'page' in query:
1043
            del query['page']
1044
        ctx['query'] = query.urlencode()
1045

    
1046
        return ctx
1047

    
1048
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1049

    
1050
class CreateDirectoryView(View, cbv.ServiceViewMixin):
1051
    def post(self, request, *args, **kwargs):
1052
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
1053
        service = Service.objects.get(slug=kwargs['service'])
1054
        patient.get_ondisk_directory(service.name)
1055
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
1056
        return HttpResponseRedirect('view')
1057

    
1058
create_directory = CreateDirectoryView.as_view()
1059

    
1060
class GenerateTransportPrescriptionFormView(cbv.FormView):
1061
    template_name = 'dossiers/generate_transport_prescription_form.html'
1062
    form_class = Form
1063
    success_url = './view#tab=1'
1064

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

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

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