Projet

Général

Profil

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

calebasse / calebasse / dossiers / views.py @ 6452a969

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
from ..utils import get_service_setting, is_validator
40

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

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

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

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

    
59
new_patient_record = NewPatientRecordView.as_view()
60

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

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

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

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

    
96
new_patient_contact = NewPatientContactView.as_view()
97

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

    
104
update_patient_contact = UpdatePatientContactView.as_view()
105

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

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

    
122
delete_patient_contact = DeletePatientContactView.as_view()
123

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

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

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

    
140
new_patient_address = NewPatientAddressView.as_view()
141

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

    
148
update_patient_address = UpdatePatientAddressView.as_view()
149

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

    
156
delete_patient_address = DeletePatientAddressView.as_view()
157

    
158

    
159
class NewHealthCareView(cbv.CreateView):
160

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

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

    
210

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

    
216

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

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

    
229
state_form = StateFormView.as_view()
230

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

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

    
254
patient_record = PatientRecordView.as_view()
255

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

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

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

    
283
patient_record_print = PatientRecordPrint.as_view()
284

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

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

    
316
tab1_general = PatientRecordGeneralView.as_view()
317

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

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

    
332
tab2_fiche_adm = PatientRecordAdmView.as_view()
333

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

    
344

    
345
    def get_context_data(self, **kwargs):
346
        ctx = super(PatientRecordAddrView, self).get_context_data(**kwargs)
347
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
348
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
349
        cv_files_path = get_service_setting('cv_files_path')
350
        if is_validator(self.request.user) and cv_files_path and os.path.isdir(cv_files_path):
351
            ctx['cv2_reading'] = True
352
        return ctx
353

    
354
tab3_addresses = PatientRecordAddrView.as_view()
355

    
356
class PatientRecordNotifsView(cbv.DetailView):
357
    model = PatientRecord
358
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
359

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

    
390
tab4_notifs = PatientRecordNotifsView.as_view()
391

    
392
class PatientRecordOldActs(cbv.DetailView):
393
    model = PatientRecord
394
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
395

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

    
425
tab5_old_acts = PatientRecordOldActs.as_view()
426

    
427
class PatientRecordNextAppointmentsView(cbv.DetailView):
428
    model = PatientRecord
429
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
430

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

    
462
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
463

    
464
class PatientRecordSocialisationView(cbv.DetailView):
465
    model = PatientRecord
466
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
467

    
468
tab7_socialisation = PatientRecordSocialisationView.as_view()
469

    
470
class PatientRecordMedicalView(cbv.UpdateView):
471
    model = PatientRecord
472
    form_class = forms.PhysiologyForm
473
    template_name = 'dossiers/patientrecord_tab8_medical.html'
474
    success_url = './view#tab=7'
475

    
476
tab8_medical = PatientRecordMedicalView.as_view()
477

    
478
class PatientRecordsHomepageView(cbv.ListView):
479
    model = PatientRecord
480
    template_name = 'dossiers/index.html'
481

    
482

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

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

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

    
541
        page = self.request.GET.get('page')
542
        if ctx['object_list']:
543
            patient_records = ctx['object_list'].filter()
544
        else:
545
            patient_records = []
546

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

    
561
        query = self.request.GET.copy()
562
        if 'page' in query:
563
            del query['page']
564
        ctx['query'] = query.urlencode()
565

    
566
        ctx['paginate_patient_records'] = paginate_patient_records
567
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
568
        return ctx
569

    
570
patientrecord_home = PatientRecordsHomepageView.as_view()
571

    
572
class PatientRecordDeleteView(DeleteView):
573
    model = PatientRecord
574
    success_url = ".."
575
    template_name = 'dossiers/patientrecord_confirm_delete.html'
576

    
577
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
578

    
579

    
580
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
581
    model = PatientRecord
582
    form_class = forms.PaperIDForm
583
    template_name = 'dossiers/generic_form.html'
584
    success_url = '../view#tab=0'
585

    
586
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
587

    
588

    
589
class NewSocialisationDurationView(cbv.CreateView):
590
    model = SocialisationDuration
591
    form_class = forms.SocialisationDurationForm
592
    template_name = 'dossiers/generic_form.html'
593
    success_url = '../view#tab=6'
594

    
595
    def get_success_url(self):
596
        return self.success_url
597

    
598
    def get(self, request, *args, **kwargs):
599
        if kwargs.has_key('patientrecord_id'):
600
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
601
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
602

    
603
    def form_valid(self, form):
604
        duration = form.save()
605
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
606
        patientrecord.socialisation_durations.add(duration)
607
        return HttpResponseRedirect(self.get_success_url())
608

    
609
new_socialisation_duration = NewSocialisationDurationView.as_view()
610

    
611
class UpdateSocialisationDurationView(cbv.UpdateView):
612
    model = SocialisationDuration
613
    form_class = forms.SocialisationDurationForm
614
    template_name = 'dossiers/generic_form.html'
615
    success_url = '../../view#tab=6'
616

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

    
622
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
623

    
624
class DeleteSocialisationDurationView(cbv.DeleteView):
625
    model = SocialisationDuration
626
    form_class = forms.SocialisationDurationForm
627
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
628
    success_url = '../../view#tab=6'
629

    
630
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
631

    
632

    
633
class NewMDPHRequestView(cbv.CreateView):
634
    def get(self, request, *args, **kwargs):
635
        if kwargs.has_key('patientrecord_id'):
636
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
637
        return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
638

    
639
    def form_valid(self, form):
640
        request = form.save()
641
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
642
        patientrecord.mdph_requests.add(request)
643
        return HttpResponseRedirect(self.success_url)
644

    
645
class UpdateMDPHRequestView(cbv.UpdateView):
646
    def get(self, request, *args, **kwargs):
647
        if kwargs.has_key('patientrecord_id'):
648
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
649
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
650

    
651

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

    
667
class NewMDPHResponseView(cbv.CreateView):
668
    def get(self, request, *args, **kwargs):
669
        if kwargs.has_key('patientrecord_id'):
670
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
671
        return super(NewMDPHResponseView, self).get(request, *args, **kwargs)
672

    
673
    def form_valid(self, form):
674
        response = form.save()
675
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
676
        patientrecord.mdph_responses.add(response)
677
        return HttpResponseRedirect(self.success_url)
678

    
679
class UpdateMDPHResponseView(cbv.UpdateView):
680
    def get(self, request, *args, **kwargs):
681
        if kwargs.has_key('patientrecord_id'):
682
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
683
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
684

    
685

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

    
701

    
702
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
703

    
704
    def get_initial(self):
705
        initial = super(UpdatePatientStateView, self).get_initial()
706
        initial['date_selected'] = self.object.date_selected.date()
707
        return initial
708

    
709
    def get(self, request, *args, **kwargs):
710
        if kwargs.has_key('patientrecord_id'):
711
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
712
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
713

    
714
class DeletePatientView(cbv.DeleteView):
715

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

    
729

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

    
740

    
741
class GenerateRtfFormView(cbv.FormView):
742
    template_name = 'dossiers/generate_rtf_form.html'
743
    form_class = forms.GenerateRtfForm
744
    success_url = './view#tab=0'
745

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

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

    
840
        filename = make_doc_from_template(from_path, to_path, variables,
841
            persistent)
842

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

    
859
generate_rtf_form = GenerateRtfFormView.as_view()
860

    
861

    
862
class PatientRecordsQuotationsView(cbv.ListView):
863
    model = PatientRecord
864
    template_name = 'dossiers/quotations.html'
865

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

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

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

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

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

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

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

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

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

    
956
        return ctx
957

    
958
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
959

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

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

    
971
new_protection = NewProtectionStateView.as_view()
972

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

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

    
984
update_protection = UpdateProtectionStateView.as_view()
985

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

    
991
delete_protection = DeleteProtectionStateView.as_view()
992

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

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

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

    
1039
    def get_context_data(self, **kwargs):
1040
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
1041
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
1042
                service=self.service)
1043
        patient_records = []
1044
        page = self.request.GET.get('page')
1045

    
1046
        all = 'all' in self.request.GET
1047
        if all:
1048
            paginate_patient_records = ctx['object_list']
1049
            ctx['all'] = all
1050
            self.template_name = 'dossiers/waiting_queue_print.html'
1051
        else:
1052
            paginator = Paginator(ctx['object_list'].filter(), 25)
1053
            try:
1054
                paginate_patient_records = paginator.page(page)
1055
            except PageNotAnInteger:
1056
                paginate_patient_records = paginator.page(1)
1057
            except EmptyPage:
1058
                paginate_patient_records = paginator.page(paginator.num_pages)
1059
            ctx['paginate_patient_records'] = paginate_patient_records
1060

    
1061
        all_patient_records = PatientRecord.objects.filter(
1062
                service=self.service,
1063
                last_state__status__type='ACCUEIL').order_by(
1064
                'last_state__date_selected', 'created')
1065
        ctx['patient_records'] = self._get_search_result(
1066
            paginate_patient_records, all_patient_records)
1067
        ctx['len_patient_records'] = all_patient_records.count()
1068

    
1069
        query = self.request.GET.copy()
1070
        if 'page' in query:
1071
            del query['page']
1072
        ctx['query'] = query.urlencode()
1073

    
1074
        return ctx
1075

    
1076
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1077

    
1078
class CreateDirectoryView(View, cbv.ServiceViewMixin):
1079
    def post(self, request, *args, **kwargs):
1080
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
1081
        service = Service.objects.get(slug=kwargs['service'])
1082
        patient.get_ondisk_directory(service.name)
1083
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
1084
        return HttpResponseRedirect('view')
1085

    
1086
create_directory = CreateDirectoryView.as_view()
1087

    
1088
class GenerateTransportPrescriptionFormView(cbv.FormView):
1089
    template_name = 'dossiers/generate_transport_prescription_form.html'
1090
    form_class = Form
1091
    success_url = './view#tab=1'
1092

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

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

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