Projet

Général

Profil

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

calebasse / calebasse / dossiers / views.py @ b057fff0

1
# -*- coding: utf-8 -*-
2

    
3
import os
4

    
5
from datetime import datetime, date
6

    
7
from django.conf import settings
8
from django.db import models
9
from django.http import HttpResponseRedirect, HttpResponse
10
from django.views.generic import View
11
from django.views.generic.edit import DeleteView
12
from django.contrib import messages
13
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
14
from django.core.files import File
15
from django.forms import Form
16
from django.utils import formats
17
from django.shortcuts import get_object_or_404
18

    
19
from calebasse import cbv
20
from calebasse.doc_templates import make_doc_from_template
21
from calebasse.dossiers import forms
22
from calebasse.dossiers.views_utils import get_next_rdv, get_last_rdv, get_status
23
from calebasse.dossiers.transport import render_transport
24
from calebasse.agenda.models import Event, EventWithAct
25
from calebasse.actes.models import Act
26
from calebasse.agenda.appointments import Appointment
27
from calebasse.dossiers.models import (PatientRecord, PatientContact,
28
        PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
29
        CmppHealthCareDiagnostic, SessadHealthCareNotification, HealthCare,
30
        TransportPrescriptionLog, ProtectionState)
31
from calebasse.dossiers.states import STATES_MAPPING, STATES_BTN_MAPPER
32
from calebasse.ressources.models import (Service,
33
    SocialisationDuration, MDPHRequest, MDPHResponse)
34
from calebasse.facturation.list_acts import list_acts_for_billing_CMPP_per_patient
35
from calebasse.facturation.invoice_header import render_to_pdf_file
36

    
37
from calebasse.decorators import validator_only
38

    
39

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

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

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

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

    
58
new_patient_record = NewPatientRecordView.as_view()
59

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

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

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

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

    
95
new_patient_contact = NewPatientContactView.as_view()
96

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

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

    
108
update_patient_contact = UpdatePatientContactView.as_view()
109

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

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

    
126
delete_patient_contact = DeletePatientContactView.as_view()
127

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

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

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

    
144
new_patient_address = NewPatientAddressView.as_view()
145

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

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

    
158
update_patient_address = UpdatePatientAddressView.as_view()
159

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

    
166
delete_patient_address = DeletePatientAddressView.as_view()
167

    
168

    
169
class NewHealthCareView(cbv.CreateView):
170

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

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

    
220

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

    
226

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

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

    
239
state_form = StateFormView.as_view()
240

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

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

    
264
patient_record = PatientRecordView.as_view()
265

    
266
class PatientRecordPrint(cbv.DetailView):
267
    model = PatientRecord
268
    content_type = 'application/pdf'
269
    template_name = 'dossiers/patientrecord_print.html'
270

    
271
    def get_context_data(self, *args, **kwargs):
272
        context = super(PatientRecordPrint, self).get_context_data(*args, **kwargs)
273
        for view in (PatientRecordGeneralView, PatientRecordAdmView,
274
                     PatientRecordAddrView, PatientRecordNotifsView, PatientRecordOldActs,
275
                     PatientRecordNextAppointmentsView, PatientRecordSocialisationView):
276
            view_instance = view(request=self.request, object=self.object,
277
                                 service=self.service)
278
            context.update(view_instance.get_context_data(object=self.object))
279
        return context
280

    
281
    def get(self, request, *args, **kwargs):
282
        self.object = self.get_object()
283
        path = render_to_pdf_file([self.template_name],
284
                                  self.get_context_data(object = self.object))
285
        content = File(file(path))
286
        response = HttpResponse(content, self.content_type)
287
        response['Content-Length'] = content.size
288
        output = 'dossier_%s.pdf' % self.object.id
289
        response['Content-Disposition'] = \
290
            'attachment; filename="%s"' % output
291
        return response
292

    
293
patient_record_print = PatientRecordPrint.as_view()
294

    
295
class PatientRecordGeneralView(cbv.UpdateView):
296
    model = PatientRecord
297
    form_class = forms.GeneralForm
298
    template_name = 'dossiers/patientrecord_tab1_general.html'
299
    success_url = './view'
300

    
301
    def get_context_data(self, **kwargs):
302
        ctx = super(PatientRecordGeneralView, self).get_context_data(**kwargs)
303
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
304
        ctx['initial_state'] = ctx['object'].get_initial_state()
305
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
306
        ctx['next_rdv'] = get_next_rdv(ctx['object'])
307
        current_state = ctx['object'].get_current_state()
308
        if current_state.status and STATES_MAPPING.has_key(current_state.status.type):
309
            state = STATES_MAPPING[current_state.status.type]
310
        elif current_state.status:
311
            state = current_state.status.name
312
        else:
313
            state = "Aucun"
314
        ctx['current_state'] = current_state
315
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
316
        ctx['missing_policy'] = False
317
        if not self.object.policyholder or \
318
                not self.object.policyholder.health_center or \
319
                not self.object.policyholder.social_security_id:
320
            ctx['missing_policy'] = True
321
        ctx['missing_birthdate'] = False
322
        if not self.object.birthdate:
323
            ctx['missing_birthdate'] = True
324
        return ctx
325

    
326
tab1_general = PatientRecordGeneralView.as_view()
327

    
328
class PatientRecordAdmView(cbv.UpdateView):
329
    model = PatientRecord
330
    form_class = forms.AdministrativeForm
331
    template_name = 'dossiers/patientrecord_tab2_fiche_adm.html'
332
    success_url = './view#tab=1'
333

    
334
    def get_context_data(self, **kwargs):
335
        ctx = super(PatientRecordAdmView, self).get_context_data(**kwargs)
336
        try:
337
            ctx['last_prescription'] = TransportPrescriptionLog.objects.filter(patient=ctx['object']).latest('created')
338
        except:
339
            pass
340
        return ctx
341

    
342
tab2_fiche_adm = PatientRecordAdmView.as_view()
343

    
344
class PatientRecordAddrView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
345
    model = PatientRecord
346
    forms_classes = {
347
            'contact': forms.PatientContactForm,
348
            'policyholder': forms.PolicyHolderForm
349
            }
350
    template_name = 'dossiers/patientrecord_tab3_adresses.html'
351
    success_url = './view#tab=2'
352

    
353

    
354
    def get_context_data(self, **kwargs):
355
        ctx = super(PatientRecordAddrView, self).get_context_data(**kwargs)
356
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
357
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
358
        return ctx
359

    
360
tab3_addresses = PatientRecordAddrView.as_view()
361

    
362
class PatientRecordNotifsView(cbv.DetailView):
363
    model = PatientRecord
364
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
365

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

    
396
tab4_notifs = PatientRecordNotifsView.as_view()
397

    
398
class PatientRecordOldActs(cbv.DetailView):
399
    model = PatientRecord
400
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
401

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

    
431
tab5_old_acts = PatientRecordOldActs.as_view()
432

    
433
class PatientRecordNextAppointmentsView(cbv.DetailView):
434
    model = PatientRecord
435
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
436

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

    
468
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
469

    
470
class PatientRecordSocialisationView(cbv.DetailView):
471
    model = PatientRecord
472
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
473

    
474
tab7_socialisation = PatientRecordSocialisationView.as_view()
475

    
476
class PatientRecordMedicalView(cbv.UpdateView):
477
    model = PatientRecord
478
    form_class = forms.PhysiologyForm
479
    template_name = 'dossiers/patientrecord_tab8_medical.html'
480
    success_url = './view#tab=7'
481

    
482
tab8_medical = PatientRecordMedicalView.as_view()
483

    
484
class PatientRecordsHomepageView(cbv.ListView):
485
    model = PatientRecord
486
    template_name = 'dossiers/index.html'
487

    
488

    
489
    def _get_search_result(self, paginate_patient_records):
490
        patient_records = []
491
        for patient_record in paginate_patient_records:
492
            next_rdv = get_next_rdv(patient_record)
493
            last_rdv = get_last_rdv(patient_record)
494
            current_status = patient_record.last_state.status
495
            state = current_status.name
496
            state_class = current_status.type.lower()
497
            patient_records.append(
498
                    {
499
                        'object': patient_record,
500
                        'next_rdv': next_rdv,
501
                        'last_rdv': last_rdv,
502
                        'state': state,
503
                        'state_class': state_class
504
                        }
505
                    )
506
        return patient_records
507

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

    
540
    def get_context_data(self, **kwargs):
541
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
542
        ctx['search_form'] = forms.SearchForm(service=self.service, data=self.request.GET or None)
543
        ctx['stats'] = [["Dossiers", 0]]
544
        for status in Status.objects.filter(services=self.service):
545
            ctx['stats'].append([status.name, 0])
546

    
547
        page = self.request.GET.get('page')
548
        if ctx['object_list']:
549
            patient_records = ctx['object_list'].filter()
550
        else:
551
            patient_records = []
552

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

    
567
        query = self.request.GET.copy()
568
        if 'page' in query:
569
            del query['page']
570
        ctx['query'] = query.urlencode()
571

    
572
        ctx['paginate_patient_records'] = paginate_patient_records
573
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
574
        return ctx
575

    
576
patientrecord_home = PatientRecordsHomepageView.as_view()
577

    
578
class PatientRecordDeleteView(DeleteView):
579
    model = PatientRecord
580
    success_url = ".."
581
    template_name = 'dossiers/patientrecord_confirm_delete.html'
582

    
583
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
584

    
585

    
586
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
587
    model = PatientRecord
588
    form_class = forms.PaperIDForm
589
    template_name = 'dossiers/generic_form.html'
590
    success_url = '../view#tab=0'
591

    
592
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
593

    
594

    
595
class NewSocialisationDurationView(cbv.CreateView):
596
    model = SocialisationDuration
597
    form_class = forms.SocialisationDurationForm
598
    template_name = 'dossiers/generic_form.html'
599
    success_url = '../view#tab=6'
600

    
601
    def get_success_url(self):
602
        return self.success_url
603

    
604
    def get(self, request, *args, **kwargs):
605
        if kwargs.has_key('patientrecord_id'):
606
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
607
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
608

    
609
    def form_valid(self, form):
610
        duration = form.save()
611
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
612
        patientrecord.socialisation_durations.add(duration)
613
        return HttpResponseRedirect(self.get_success_url())
614

    
615
new_socialisation_duration = NewSocialisationDurationView.as_view()
616

    
617
class UpdateSocialisationDurationView(cbv.UpdateView):
618
    model = SocialisationDuration
619
    form_class = forms.SocialisationDurationForm
620
    template_name = 'dossiers/generic_form.html'
621
    success_url = '../../view#tab=6'
622

    
623
    def get(self, request, *args, **kwargs):
624
        if kwargs.has_key('patientrecord_id'):
625
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
626
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
627

    
628
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
629

    
630
class DeleteSocialisationDurationView(cbv.DeleteView):
631
    model = SocialisationDuration
632
    form_class = forms.SocialisationDurationForm
633
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
634
    success_url = '../../view#tab=6'
635

    
636
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
637

    
638

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

    
645
    def form_valid(self, form):
646
        request = form.save()
647
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
648
        patientrecord.mdph_requests.add(request)
649
        return HttpResponseRedirect(self.success_url)
650

    
651
class UpdateMDPHRequestView(cbv.UpdateView):
652
    def get(self, request, *args, **kwargs):
653
        if kwargs.has_key('patientrecord_id'):
654
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
655
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
656

    
657

    
658
new_mdph_request = \
659
    NewMDPHRequestView.as_view(model=MDPHRequest,
660
        template_name = 'dossiers/generic_form.html',
661
        success_url = '../view#tab=6',
662
        form_class=forms.MDPHRequestForm)
663
update_mdph_request = \
664
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
665
        template_name = 'dossiers/generic_form.html',
666
        success_url = '../../view#tab=6',
667
        form_class=forms.MDPHRequestForm)
668
delete_mdph_request = \
669
    cbv.DeleteView.as_view(model=MDPHRequest,
670
        template_name = 'dossiers/generic_confirm_delete.html',
671
        success_url = '../../view#tab=6')
672

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

    
679
    def form_valid(self, form):
680
        response = form.save()
681
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
682
        patientrecord.mdph_responses.add(response)
683
        return HttpResponseRedirect(self.success_url)
684

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

    
691

    
692
new_mdph_response = \
693
    NewMDPHResponseView.as_view(model=MDPHResponse,
694
        template_name = 'dossiers/generic_form.html',
695
        success_url = '../view#tab=6',
696
        form_class=forms.MDPHResponseForm)
697
update_mdph_response = \
698
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
699
        template_name = 'dossiers/generic_form.html',
700
        success_url = '../../view#tab=6',
701
        form_class=forms.MDPHResponseForm)
702
delete_mdph_response = \
703
    cbv.DeleteView.as_view(model=MDPHResponse,
704
        template_name = 'dossiers/generic_confirm_delete.html',
705
        success_url = '../../view#tab=6')
706

    
707

    
708
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
709

    
710
    def get_initial(self):
711
        initial = super(UpdatePatientStateView, self).get_initial()
712
        initial['date_selected'] = self.object.date_selected.date()
713
        return initial
714

    
715
    def get(self, request, *args, **kwargs):
716
        if kwargs.has_key('patientrecord_id'):
717
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
718
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
719

    
720
class DeletePatientView(cbv.DeleteView):
721

    
722
    def delete(self, request, *args, **kwargs):
723
        self.object = self.get_object()
724
        if self.object == self.object.patient.last_state:
725
            status = self.object.patient.filestate_set.all().order_by('-created')
726
            if len(status) > 1:
727
                self.object.patient.last_state = status[1]
728
                self.object.patient.save()
729
            else:
730
                # TODO return an error here
731
                return HttpResponseRedirect(self.get_success_url())
732
        self.object.delete()
733
        return HttpResponseRedirect(self.get_success_url())
734

    
735

    
736
update_patient_state = \
737
    UpdatePatientStateView.as_view(model=FileState,
738
        template_name = 'dossiers/generic_form.html',
739
        success_url = '../../view#tab=0',
740
        form_class=forms.PatientStateForm)
741
delete_patient_state = \
742
    DeletePatientView.as_view(model=FileState,
743
        template_name = 'dossiers/generic_confirm_delete.html',
744
        success_url = '../../view#tab=0')
745

    
746

    
747
class GenerateRtfFormView(cbv.FormView):
748
    template_name = 'dossiers/generate_rtf_form.html'
749
    form_class = forms.GenerateRtfForm
750
    success_url = './view#tab=0'
751

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

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

    
846
        filename = make_doc_from_template(from_path, to_path, variables,
847
            persistent)
848

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

    
865
generate_rtf_form = GenerateRtfFormView.as_view()
866

    
867

    
868
class PatientRecordsQuotationsView(cbv.ListView):
869
    model = PatientRecord
870
    template_name = 'dossiers/quotations.html'
871

    
872
    def _get_search_result(self, paginate_patient_records):
873
        patient_records = []
874
        for patient_record in paginate_patient_records:
875
            current_state = patient_record.get_current_state() or patient_record.get_state()
876
            state = current_state.status.name
877
            state_class = current_state.status.type.lower()
878
            deficiencies = [getattr(patient_record, field) \
879
                            for field in self.model.DEFICIENCY_FIELDS]
880
            anap = any(deficiencies)
881
            mises = reduce(lambda m1, m2: m1+m2, [list(getattr(patient_record, field).all()) for field in self.model.MISES_FIELDS])
882
            next_rdv = get_next_rdv(patient_record)
883
            last_rdv = get_last_rdv(patient_record)
884

    
885
            if next_rdv:
886
                next_rdv_datetime = next_rdv.start_datetime
887
            else:
888
                next_rdv_datetime = None
889
            if last_rdv:
890
                last_rdv_datetime = last_rdv['start_datetime']
891
            else:
892
                last_rdv_datetime = None
893
            patient_records.append(
894
                    {
895
                        'object': patient_record,
896
                        'state': state,
897
                        'state_class': state_class,
898
                        'anap': anap,
899
                        'mises': mises,
900
                        'next_rdv_date': next_rdv_datetime,
901
                        'last_rdv_date': last_rdv_datetime
902
                        }
903
                    )
904
        return patient_records
905

    
906
    def get_queryset(self):
907
        form = forms.QuotationsForm(data=self.request.GET or None)
908
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
909
        without_quotations = self.request.GET.get('without_quotations')
910
        without_anap_quotations = self.request.GET.get('without_anap_quotations')
911
        if without_quotations:
912
            for field in self.model.MISES_FIELDS:
913
                mise_field = {'%s__isnull' % field: True}
914
                qs = qs.filter(**mise_field)
915

    
916
        if without_anap_quotations:
917
            for field in self.model.DEFICIENCY_FIELDS:
918
                anap_field = {field: 0}
919
                qs = qs.filter(**anap_field)
920

    
921
        states = self.request.GET.getlist('states')
922
        qs = qs.filter(last_state__status__id__in=states)
923

    
924
        try:
925
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
926
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
927
        except (ValueError, KeyError):
928
            pass
929
        try:
930
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
931
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
932
        except (ValueError, KeyError):
933
            pass
934
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
935
        return qs
936

    
937
    def get_context_data(self, **kwargs):
938
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
939
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
940
                service=self.service)
941
        patient_records = []
942
        page = self.request.GET.get('page')
943
        all = 'all' in self.request.GET
944
        if all:
945
            patient_records = ctx['object_list']
946
            ctx['all'] = all
947
            self.template_name = 'dossiers/quotations_print.html'
948
        else:
949
            paginator = Paginator(ctx['object_list'].filter(), 50)
950
            try:
951
                patient_records = paginator.page(page)
952
            except PageNotAnInteger:
953
                patient_records = paginator.page(1)
954
            except EmptyPage:
955
                patient_records = paginator.page(paginator.num_pages)
956
            ctx['paginate_patient_records'] = patient_records
957

    
958
        ctx['patient_records'] = self._get_search_result(patient_records)
959

    
960
        query = self.request.GET.copy()
961
        if 'page' in query:
962
            del query['page']
963
        ctx['query'] = query.urlencode()
964

    
965
        return ctx
966

    
967
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
968

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

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

    
980
new_protection = NewProtectionStateView.as_view()
981

    
982
class UpdateProtectionStateView(cbv.UpdateView):
983
    model = ProtectionState
984
    template_name = 'dossiers/generic_form.html'
985
    success_url = '../../view#tab=1'
986
    form_class = forms.ProtectionStateForm
987

    
988
    def form_valid(self, form):
989
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
990
        form.instance.patient = self.patient
991
        return super(UpdateProtectionStateView, self).form_valid(form)
992

    
993
update_protection = UpdateProtectionStateView.as_view()
994

    
995
class DeleteProtectionStateView(cbv.DeleteView):
996
    model = ProtectionState
997
    template_name = 'dossiers/protection_confirm_delete.html'
998
    success_url = '../../view#tab=1'
999

    
1000
delete_protection = DeleteProtectionStateView.as_view()
1001

    
1002
class PatientRecordsWaitingQueueView(cbv.ListView):
1003
    model = PatientRecord
1004
    template_name = 'dossiers/waiting_queue.html'
1005

    
1006
    def _get_search_result(self, paginate_patient_records,
1007
            all_patient_records):
1008
        patient_records = []
1009
        if paginate_patient_records:
1010
            position = 1
1011
            for patient_record in paginate_patient_records:
1012
                while patient_record.id != all_patient_records[position - 1].id:
1013
                    position += 1
1014
                patient_records.append(
1015
                        {
1016
                            'object': patient_record,
1017
                            'position': position,
1018
                            }
1019
                        )
1020
        return patient_records
1021

    
1022
    def get_queryset(self):
1023
        form = forms.QuotationsForm(data=self.request.GET or None)
1024
        qs = super(PatientRecordsWaitingQueueView, self).get_queryset()
1025
        first_name = self.request.GET.get('first_name')
1026
        last_name = self.request.GET.get('last_name')
1027
        paper_id = self.request.GET.get('paper_id')
1028
        id = self.request.GET.get('id')
1029
        social_security_id = self.request.GET.get('social_security_id')
1030
        qs = qs.filter(service=self.service,
1031
            last_state__status__type='ACCUEIL')
1032
        if last_name:
1033
            qs = qs.filter(last_name__istartswith=last_name)
1034
        if first_name:
1035
            qs = qs.filter(first_name__istartswith=first_name)
1036
        if paper_id:
1037
            qs = qs.filter(paper_id__startswith=paper_id)
1038
        if id:
1039
            qs = qs.filter(id__startswith=id)
1040
        if social_security_id:
1041
            qs = qs.filter(models.Q(
1042
                social_security_id__startswith=social_security_id)
1043
                | models.Q(
1044
                contacts__social_security_id__startswith=social_security_id))
1045
        qs = qs.order_by('last_state__date_selected', 'created')
1046
        return qs
1047

    
1048
    def get_context_data(self, **kwargs):
1049
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
1050
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
1051
                service=self.service)
1052
        patient_records = []
1053
        page = self.request.GET.get('page')
1054
        paginator = Paginator(ctx['object_list'].filter(), 50)
1055
        try:
1056
            paginate_patient_records = paginator.page(page)
1057
        except PageNotAnInteger:
1058
            paginate_patient_records = paginator.page(1)
1059
        except EmptyPage:
1060
            paginate_patient_records = paginator.page(paginator.num_pages)
1061

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

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

    
1076
        return ctx
1077

    
1078
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1079

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

    
1088
create_directory = CreateDirectoryView.as_view()
1089

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

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

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

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