Project

General

Profile

Download (47.9 KB) Statistics
| Branch: | Tag: | Revision:

calebasse / calebasse / dossiers / views.py @ 3c5df84d

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.transport import render_transport
23
from calebasse.agenda.models import Event, EventWithAct
24
from calebasse.actes.models import Act
25
from calebasse.agenda.appointments import Appointment
26
from calebasse.dossiers.models import (PatientRecord, PatientContact,
27
        PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
28
        CmppHealthCareDiagnostic, SessadHealthCareNotification, HealthCare,
29
        TransportPrescriptionLog, ProtectionState)
30
from calebasse.dossiers.states import STATES_MAPPING, STATES_BTN_MAPPER
31
from calebasse.ressources.models import (Service,
32
    SocialisationDuration, MDPHRequest, MDPHResponse)
33
from calebasse.facturation.list_acts import list_acts_for_billing_CMPP_per_patient
34

    
35
from calebasse.decorators import validator_only
36

    
37
def get_next_rdv(patient_record):
38
    Q = models.Q
39
    today = date.today()
40
    qs = EventWithAct.objects.filter(patient=patient_record) \
41
            .filter(exception_to__isnull=True, canceled=False) \
42
            .filter(Q(start_datetime__gte=today) \
43
            |  Q(exceptions__isnull=False) \
44
            | ( Q(recurrence_periodicity__isnull=False) \
45
            & (Q(recurrence_end_date__gte=today) \
46
            | Q(recurrence_end_date__isnull=True) \
47
            ))) \
48
            .distinct() \
49
            .select_related() \
50
            .prefetch_related('participants', 'exceptions__eventwithact')
51
    occurrences = []
52
    for event in qs:
53
        occurrences.extend(filter(lambda e: e.start_datetime.date() >= today, event.all_occurences(limit=180)))
54
    occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
55
    if occurrences:
56
        return occurrences[0]
57
    else:
58
        return None
59

    
60
def get_last_rdv(patient_record):
61
    last_rdv = {}
62
    event = Event.objects.last_appointment(patient_record)
63
    if event:
64
        last_rdv['start_datetime'] = event.start_datetime
65
        last_rdv['participants'] = event.participants.all()
66
        last_rdv['act_type'] = event.eventwithact.act_type
67
        last_rdv['act_state'] = event.act.get_state()
68
        last_rdv['is_absent'] = event.is_absent()
69
    return last_rdv
70

    
71
class NewPatientRecordView(cbv.FormView, cbv.ServiceViewMixin):
72
    form_class = forms.NewPatientRecordForm
73
    template_name = 'dossiers/patientrecord_new.html'
74
    success_url = '..'
75
    patient = None
76

    
77
    def post(self, request, *args, **kwarg):
78
        self.user = request.user
79
        return super(NewPatientRecordView, self).post(request, *args, **kwarg)
80

    
81
    def form_valid(self, form):
82
        self.patient = create_patient(form.data['first_name'], form.data['last_name'], self.service,
83
                self.user, date_selected=datetime.strptime(form.data['date_selected'], "%d/%m/%Y"))
84
        return super(NewPatientRecordView, self).form_valid(form)
85

    
86
    def get_success_url(self):
87
        return '%s/view' % self.patient.id
88

    
89
new_patient_record = NewPatientRecordView.as_view()
90

    
91
class RecordPatientRecordIdMixing(object):
92
    def dispatch(self, request, *args, **kwargs):
93
        self.patientrecord_id = request.session['patientrecord_id'] = int(kwargs['patientrecord_id'])
94
        return super(RecordPatientRecordIdMixing, self).dispatch(request, *args, **kwargs)
95

    
96
    def get_form_kwargs(self):
97
        kwargs = super(RecordPatientRecordIdMixing, self).get_form_kwargs()
98
        kwargs['patient'] = PatientRecord.objects.get(id=self.patientrecord_id)
99
        return kwargs
100

    
101
class NewPatientContactView(RecordPatientRecordIdMixing, cbv.CreateView):
102
    model = PatientContact
103
    form_class = forms.PatientContactForm
104
    template_name = 'dossiers/patientcontact_new.html'
105
    success_url = '../view#tab=2'
106

    
107
new_patient_contact = NewPatientContactView.as_view()
108

    
109
class UpdatePatientContactView(RecordPatientRecordIdMixing, cbv.UpdateView):
110
    model = PatientContact
111
    form_class = forms.PatientContactForm
112
    template_name = 'dossiers/patientcontact_new.html'
113
    success_url = '../../view#tab=2'
114

    
115
update_patient_contact = UpdatePatientContactView.as_view()
116

    
117
class DeletePatientContactView(cbv.DeleteView):
118
    model = PatientContact
119
    form_class = forms.PatientContactForm
120
    template_name = 'dossiers/patientcontact_confirm_delete.html'
121
    success_url = '../../view#tab=2'
122

    
123
    def post(self, request, *args, **kwargs):
124
        try:
125
            patient = PatientRecord.objects.get(id=kwargs.get('pk'))
126
        except PatientRecord.DoesNotExist:
127
            return super(DeletePatientContactView, self).post(request, *args, **kwargs)
128
        # the contact is also a patient record; it shouldn't be deleted; just
129
        # altered to remove an address
130
        patient.addresses.remove(self.request.GET['address'])
131
        return HttpResponseRedirect(self.get_success_url())
132

    
133
delete_patient_contact = DeletePatientContactView.as_view()
134

    
135
class NewPatientAddressView(cbv.CreateView):
136
    model = PatientAddress
137
    form_class = forms.PatientAddressForm
138
    template_name = 'dossiers/patientaddress_new.html'
139
    success_url = '../view#tab=2'
140

    
141
    def get_success_url(self):
142
        return self.success_url
143

    
144
    def form_valid(self, form):
145
        patientaddress = form.save()
146
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
147
        patientrecord.addresses.add(patientaddress)
148
        messages.add_message(self.request, messages.INFO, u'Nouvelle adresse enregistrée avec succès.')
149
        return HttpResponseRedirect(self.get_success_url())
150

    
151
new_patient_address = NewPatientAddressView.as_view()
152

    
153
class UpdatePatientAddressView(cbv.UpdateView):
154
    model = PatientAddress
155
    form_class = forms.PatientAddressForm
156
    template_name = 'dossiers/patientaddress_new.html'
157
    success_url = '../../view#tab=2'
158

    
159
    def form_valid(self, form):
160
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
161
        return super(UpdatePatientAddressView, self).form_valid(form)
162

    
163
update_patient_address = UpdatePatientAddressView.as_view()
164

    
165
class DeletePatientAddressView(cbv.DeleteView):
166
    model = PatientAddress
167
    form_class = forms.PatientAddressForm
168
    template_name = 'dossiers/patientaddress_confirm_delete.html'
169
    success_url = '../../view#tab=2'
170

    
171
delete_patient_address = DeletePatientAddressView.as_view()
172

    
173

    
174
class NewHealthCareView(cbv.CreateView):
175

    
176
    def get_initial(self):
177
        initial = super(NewHealthCareView, self).get_initial()
178
        initial['author'] = self.request.user.id
179
        initial['patient'] = self.kwargs['patientrecord_id']
180
        return initial
181

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

    
225

    
226
class StateFormView(cbv.FormView):
227
    template_name = 'dossiers/state.html'
228
    form_class = forms.StateForm
229
    success_url = './view#tab=0'
230

    
231

    
232
    def post(self, request, *args, **kwarg):
233
        self.user = request.user
234
        return super(StateFormView, self).post(request, *args, **kwarg)
235

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

    
244
state_form = StateFormView.as_view()
245

    
246

    
247
class PatientRecordView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
248
    model = PatientRecord
249
    forms_classes = {
250
            'general': forms.GeneralForm,
251
            'id': forms.CivilStatusForm,
252
            'physiology': forms.PhysiologyForm,
253
            'inscription': forms.InscriptionForm,
254
            'out': forms.OutForm,
255
            'family': forms.FamilyForm,
256
            'transport': forms.TransportFrom,
257
            'followup': forms.FollowUpForm,
258
            'policyholder': forms.PolicyHolderForm
259
            }
260
    template_name = 'dossiers/patientrecord_update.html'
261
    success_url = './view'
262

    
263
    def get_success_url(self):
264
        if self.request.POST.has_key('tab'):
265
            return self.success_url + '#tab=' + self.request.POST['tab']
266
        else:
267
            return self.success_url
268

    
269
    def get_context_data(self, **kwargs):
270
        ctx = super(PatientRecordView, self).get_context_data(**kwargs)
271
        ctx['object'].create_diag_healthcare(self.request.user)
272
        ctx['object'].automated_switch_state(self.request.user)
273
        ctx['initial_state'] = ctx['object'].get_initial_state()
274
        current_state = ctx['object'].get_current_state()
275
        if STATES_MAPPING.has_key(current_state.status.type):
276
            state = STATES_MAPPING[current_state.status.type]
277
        else:
278
            state = current_state.status.name
279
        ctx['current_state'] = current_state
280
        ctx['service_id'] = self.service.id
281
        ctx['states'] = FileState.objects.filter(patient=self.object) \
282
                .filter(status__services=self.service) \
283
                .order_by('-date_selected')
284
        ctx['next_rdvs'] = []
285
        Q = models.Q
286
        today = date.today()
287
        qs = EventWithAct.objects.filter(patient=ctx['object']) \
288
                .filter(exception_to__isnull=True, canceled=False) \
289
                .filter(Q(start_datetime__gte=today) \
290
                |  Q(exceptions__isnull=False) \
291
                | ( Q(recurrence_periodicity__isnull=False) \
292
                & (Q(recurrence_end_date__gte=today) \
293
                | Q(recurrence_end_date__isnull=True) \
294
                ))) \
295
                .distinct() \
296
                .select_related() \
297
                .prefetch_related('participants', 'exceptions__eventwithact',
298
                        'act_set__actvalidationstate_set')
299
        occurrences = []
300
        for event in qs:
301
            occurrences.extend(filter(lambda e: e.start_datetime.date() >= today,
302
                event.all_occurences(limit=180)))
303
        occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
304
        for event in occurrences:
305
            state = None
306
            if event.act:
307
                state = event.act.get_state()
308
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
309
                state = None
310
            ctx['next_rdvs'].append((event, state, event.get_missing_participants()))
311
        if ctx['next_rdvs']:
312
            ctx['next_rdv'] = ctx['next_rdvs'][0][0]
313
        ctx['last_rdvs'] = []
314
        for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
315
            state = act.get_state()
316
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
317
                state = None
318
            missing_workers = []
319
            try:
320
                missing_workers = [participant.worker for participant in act.event.get_missing_participants()]
321
            except:
322
                pass
323
            ctx['last_rdvs'].append((act, state, missing_workers))
324
        history = []
325
        i = 0
326
        for state in ctx['object'].filestate_set.order_by('-date_selected'):
327
            acts = []
328
            try:
329
                while ctx['last_rdvs'][i][0].date >= state.date_selected.date():
330
                    acts.append(ctx['last_rdvs'][i])
331
                    i += 1
332
            except:
333
                pass
334
            history.append((state, acts))
335
        if i < len(ctx['last_rdvs']) -1:
336
            history.append((None, ctx['last_rdvs'][i:]))
337
        ctx['history'] = history
338
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
339

    
340
        ctx['missing_policy'] = False
341
        if not self.object.policyholder or \
342
                not self.object.policyholder.health_center or \
343
                not self.object.policyholder.social_security_id:
344
            ctx['missing_policy'] = True
345
        ctx['missing_birthdate'] = False
346
        if not self.object.birthdate:
347
            ctx['missing_birthdate'] = True
348

    
349
        ctx['status'] = []
350
        close_btn = STATES_BTN_MAPPER['CLOS']
351
        if 'next_rdv' in ctx:
352
            close_btn = STATES_BTN_MAPPER['CLOS_RDV']
353
        if ctx['object'].service.name == "CMPP":
354
            ctx['can_rediag'] = self.object.create_diag_healthcare(self.request.user)
355
            status = self.object.get_healthcare_status()
356
            highlight = False
357
            if status[0] == -1:
358
                status = 'Indéterminé.'
359
                highlight = True
360
            elif status[0] == 0:
361
                status = "Prise en charge de diagnostic en cours."
362
            elif status[0] == 1:
363
                status = 'Patient jamais pris en charge.'
364
            elif status[0] == 2:
365
                status = "Prise en charge de diagnostic complète, faire une demande de prise en charge de traitement."
366
                highlight = True
367
            elif status[0] == 3:
368
                if ctx['can_rediag']:
369
                    status = "Prise en charge de traitement expirée. Patient élligible en rediagnostic."
370
                    highlight = True
371
                else:
372
                    status = "Prise en charge de traitement expirée. La demande d'un renouvellement est possible."
373
                    highlight = True
374
            elif status[0] == 4:
375
                status = "Il existe une prise en charge de traitement mais qui ne prendra effet que le %s." % str(status[1])
376
            elif status[0] == 5:
377
                status = "Prise en charge de traitement en cours."
378
            elif status[0] == 6:
379
                status = "Prise en charge de traitement complète mais qui peut être prolongée."
380
                highlight = True
381
            elif status[0] == 7:
382
                status = "Prise en charge de traitement complète et déjà prolongée, se terminant le %s." % \
383
                    formats.date_format(status[2], "SHORT_DATE_FORMAT")
384
            else:
385
                status = 'Statut inconnu.'
386
            ctx['hc_status'] = (status, highlight)
387
            if ctx['object'].last_state.status.type == "ACCUEIL":
388
                # Inscription automatique au premier acte facturable valide
389
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
390
                        STATES_BTN_MAPPER['DIAGNOSTIC'],
391
                        STATES_BTN_MAPPER['TRAITEMENT']]
392
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
393
                # Passage automatique en diagnostic ou traitement
394
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
395
                        STATES_BTN_MAPPER['DIAGNOSTIC'],
396
                        STATES_BTN_MAPPER['TRAITEMENT']]
397
            elif ctx['object'].last_state.status.type == "DIAGNOSTIC":
398
                # Passage automatique en traitement
399
                ctx['status'] = [STATES_BTN_MAPPER['TRAITEMENT'],
400
                        close_btn,
401
                        STATES_BTN_MAPPER['ACCUEIL']]
402
            elif ctx['object'].last_state.status.type == "TRAITEMENT":
403
                # Passage automatique en diagnostic si on ajoute une prise en charge diagnostic,
404
                # ce qui est faisable dans l'onglet prise en charge par un bouton visible sous conditions
405
                ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
406
                        close_btn,
407
                        STATES_BTN_MAPPER['ACCUEIL']]
408
            elif ctx['object'].last_state.status.type == "CLOS":
409
                # Passage automatique en diagnostic ou traitement
410
                ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
411
                        STATES_BTN_MAPPER['TRAITEMENT'],
412
                        STATES_BTN_MAPPER['ACCUEIL']]
413
            (acts_not_locked, days_not_locked, acts_not_valide,
414
            acts_not_billable, acts_pause, acts_per_hc, acts_losts) = \
415
                list_acts_for_billing_CMPP_per_patient(self.object,
416
                    datetime.today(), self.service)
417
            ctx['acts_losts'] = acts_losts
418
            ctx['acts_pause'] = acts_pause
419
            hcs_used = acts_per_hc.keys()
420
            hcs = None
421
            if not hcs_used:
422
                hcs = [(hc, None) for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date')]
423
            else:
424
                hcs = []
425
                for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date'):
426
                    acts = None
427
                    if hasattr(hc, 'cmpphealthcarediagnostic') and hc.cmpphealthcarediagnostic in hcs_used:
428
                        acts = acts_per_hc[hc.cmpphealthcarediagnostic]
429
                    elif hasattr(hc, 'cmpphealthcaretreatment') and hc.cmpphealthcaretreatment in hcs_used:
430
                        acts = acts_per_hc[hc.cmpphealthcaretreatment]
431
                    hcs.append((hc, acts))
432
            ctx['hcs'] = []
433
            for hc, acts in hcs:
434
                ctx['hcs'].append((hc, acts, hc.act_set.order_by('date', 'time')))
435
        elif ctx['object'].service.name == "CAMSP":
436
            if ctx['object'].last_state.status.type == "ACCUEIL":
437
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
438
                        STATES_BTN_MAPPER['BILAN']]
439
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
440
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
441
                        STATES_BTN_MAPPER['BILAN'],
442
                        STATES_BTN_MAPPER['SURVEILLANCE'],
443
                        STATES_BTN_MAPPER['SUIVI'],
444
                        close_btn]
445
            elif ctx['object'].last_state.status.type == "BILAN":
446
                ctx['status'] = [STATES_BTN_MAPPER['SURVEILLANCE'],
447
                        STATES_BTN_MAPPER['SUIVI'],
448
                        close_btn,
449
                        STATES_BTN_MAPPER['ACCUEIL']]
450
            elif ctx['object'].last_state.status.type == "SURVEILLANCE":
451
                ctx['status'] = [STATES_BTN_MAPPER['SUIVI'],
452
                        close_btn,
453
                        STATES_BTN_MAPPER['ACCUEIL'],
454
                        STATES_BTN_MAPPER['BILAN']]
455
            elif ctx['object'].last_state.status.type == "SUIVI":
456
                ctx['status'] = [close_btn,
457
                        STATES_BTN_MAPPER['ACCUEIL'],
458
                        STATES_BTN_MAPPER['BILAN'],
459
                        STATES_BTN_MAPPER['SURVEILLANCE']]
460
            elif ctx['object'].last_state.status.type == "CLOS":
461
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
462
                        STATES_BTN_MAPPER['BILAN'],
463
                        STATES_BTN_MAPPER['SURVEILLANCE'],
464
                        STATES_BTN_MAPPER['SUIVI']]
465
        elif ctx['object'].service.name == "SESSAD TED" or ctx['object'].service.name == "SESSAD DYS":
466
            if ctx['object'].last_state.status.type == "ACCUEIL":
467
                ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
468
                        STATES_BTN_MAPPER['TRAITEMENT']]
469
            elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
470
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
471
                        STATES_BTN_MAPPER['TRAITEMENT'],
472
                        close_btn]
473
            elif ctx['object'].last_state.status.type == "TRAITEMENT":
474
                ctx['status'] = [close_btn,
475
                        STATES_BTN_MAPPER['ACCUEIL']]
476
            elif ctx['object'].last_state.status.type == "CLOS":
477
                ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
478
                        STATES_BTN_MAPPER['TRAITEMENT']]
479
            ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
480
        try:
481
            ctx['last_prescription'] = TransportPrescriptionLog.objects.filter(patient=ctx['object']).latest('created')
482
        except:
483
            pass
484
        return ctx
485

    
486
    def form_valid(self, form):
487
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
488
        return super(PatientRecordView, self).form_valid(form)
489

    
490

    
491
patient_record = PatientRecordView.as_view()
492

    
493
class PatientRecordsHomepageView(cbv.ListView):
494
    model = PatientRecord
495
    template_name = 'dossiers/index.html'
496

    
497

    
498
    def _get_search_result(self, paginate_patient_records):
499
        patient_records = []
500
        for patient_record in paginate_patient_records:
501
            next_rdv = get_next_rdv(patient_record)
502
            last_rdv = get_last_rdv(patient_record)
503
            current_status = patient_record.last_state.status
504
            state = current_status.name
505
            state_class = current_status.type.lower()
506
            patient_records.append(
507
                    {
508
                        'object': patient_record,
509
                        'next_rdv': next_rdv,
510
                        'last_rdv': last_rdv,
511
                        'state': state,
512
                        'state_class': state_class
513
                        }
514
                    )
515
        return patient_records
516

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

    
549
    def get_context_data(self, **kwargs):
550
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
551
        ctx['search_form'] = forms.SearchForm(service=self.service, data=self.request.GET or None)
552
        ctx['stats'] = [["Dossiers", 0]]
553
        for status in Status.objects.filter(services=self.service):
554
            ctx['stats'].append([status.name, 0])
555

    
556
        page = self.request.GET.get('page')
557
        if ctx['object_list']:
558
            patient_records = ctx['object_list'].filter()
559
        else:
560
            patient_records = []
561

    
562
        # TODO: use a sql query to do this
563
        for patient_record in patient_records:
564
            ctx['stats'][0][1] += 1
565
            for elem in ctx['stats']:
566
                if elem[0] == patient_record.last_state.status.name:
567
                    elem[1] += 1
568
        paginator = Paginator(patient_records, 50)
569
        try:
570
            paginate_patient_records = paginator.page(page)
571
        except PageNotAnInteger:
572
            paginate_patient_records = paginator.page(1)
573
        except EmptyPage:
574
            paginate_patient_records = paginator.page(paginator.num_pages)
575

    
576
        query = self.request.GET.copy()
577
        if 'page' in query:
578
            del query['page']
579
        ctx['query'] = query.urlencode()
580

    
581
        ctx['paginate_patient_records'] = paginate_patient_records
582
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
583
        return ctx
584

    
585
patientrecord_home = PatientRecordsHomepageView.as_view()
586

    
587
class PatientRecordDeleteView(DeleteView):
588
    model = PatientRecord
589
    success_url = ".."
590
    template_name = 'dossiers/patientrecord_confirm_delete.html'
591

    
592
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
593

    
594

    
595
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
596
    model = PatientRecord
597
    form_class = forms.PaperIDForm
598
    template_name = 'dossiers/generic_form.html'
599
    success_url = '../..'
600

    
601
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
602

    
603

    
604
class NewSocialisationDurationView(cbv.CreateView):
605
    model = SocialisationDuration
606
    form_class = forms.SocialisationDurationForm
607
    template_name = 'dossiers/generic_form.html'
608
    success_url = '../view#tab=6'
609

    
610
    def get_success_url(self):
611
        return self.success_url
612

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

    
618
    def form_valid(self, form):
619
        duration = form.save()
620
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
621
        patientrecord.socialisation_durations.add(duration)
622
        return HttpResponseRedirect(self.get_success_url())
623

    
624
new_socialisation_duration = NewSocialisationDurationView.as_view()
625

    
626
class UpdateSocialisationDurationView(cbv.UpdateView):
627
    model = SocialisationDuration
628
    form_class = forms.SocialisationDurationForm
629
    template_name = 'dossiers/generic_form.html'
630
    success_url = '../../view#tab=6'
631

    
632
    def get(self, request, *args, **kwargs):
633
        if kwargs.has_key('patientrecord_id'):
634
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
635
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
636

    
637
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
638

    
639
class DeleteSocialisationDurationView(cbv.DeleteView):
640
    model = SocialisationDuration
641
    form_class = forms.SocialisationDurationForm
642
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
643
    success_url = '../../view#tab=6'
644

    
645
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
646

    
647

    
648
class NewMDPHRequestView(cbv.CreateView):
649
    def get(self, request, *args, **kwargs):
650
        if kwargs.has_key('patientrecord_id'):
651
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
652
        return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
653

    
654
    def form_valid(self, form):
655
        request = form.save()
656
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
657
        patientrecord.mdph_requests.add(request)
658
        return HttpResponseRedirect(self.success_url)
659

    
660
class UpdateMDPHRequestView(cbv.UpdateView):
661
    def get(self, request, *args, **kwargs):
662
        if kwargs.has_key('patientrecord_id'):
663
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
664
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
665

    
666

    
667
new_mdph_request = \
668
    NewMDPHRequestView.as_view(model=MDPHRequest,
669
        template_name = 'dossiers/generic_form.html',
670
        success_url = '../view#tab=6',
671
        form_class=forms.MDPHRequestForm)
672
update_mdph_request = \
673
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
674
        template_name = 'dossiers/generic_form.html',
675
        success_url = '../../view#tab=6',
676
        form_class=forms.MDPHRequestForm)
677
delete_mdph_request = \
678
    cbv.DeleteView.as_view(model=MDPHRequest,
679
        template_name = 'dossiers/generic_confirm_delete.html',
680
        success_url = '../../view#tab=6')
681

    
682
class NewMDPHResponseView(cbv.CreateView):
683
    def get(self, request, *args, **kwargs):
684
        if kwargs.has_key('patientrecord_id'):
685
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
686
        return super(NewMDPHResponseView, self).get(request, *args, **kwargs)
687

    
688
    def form_valid(self, form):
689
        response = form.save()
690
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
691
        patientrecord.mdph_responses.add(response)
692
        return HttpResponseRedirect(self.success_url)
693

    
694
class UpdateMDPHResponseView(cbv.UpdateView):
695
    def get(self, request, *args, **kwargs):
696
        if kwargs.has_key('patientrecord_id'):
697
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
698
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
699

    
700

    
701
new_mdph_response = \
702
    NewMDPHResponseView.as_view(model=MDPHResponse,
703
        template_name = 'dossiers/generic_form.html',
704
        success_url = '../view#tab=6',
705
        form_class=forms.MDPHResponseForm)
706
update_mdph_response = \
707
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
708
        template_name = 'dossiers/generic_form.html',
709
        success_url = '../../view#tab=6',
710
        form_class=forms.MDPHResponseForm)
711
delete_mdph_response = \
712
    cbv.DeleteView.as_view(model=MDPHResponse,
713
        template_name = 'dossiers/generic_confirm_delete.html',
714
        success_url = '../../view#tab=6')
715

    
716

    
717
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
718

    
719
    def get_initial(self):
720
        initial = super(UpdatePatientStateView, self).get_initial()
721
        initial['date_selected'] = self.object.date_selected.date()
722
        return initial
723

    
724
    def get(self, request, *args, **kwargs):
725
        if kwargs.has_key('patientrecord_id'):
726
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
727
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
728

    
729
class DeletePatientView(cbv.DeleteView):
730

    
731
    def delete(self, request, *args, **kwargs):
732
        self.object = self.get_object()
733
        if self.object == self.object.patient.last_state:
734
            status = self.object.patient.filestate_set.all().order_by('-created')
735
            if len(status) > 1:
736
                self.object.patient.last_state = status[1]
737
                self.object.patient.save()
738
            else:
739
                # TODO return an error here
740
                return HttpResponseRedirect(self.get_success_url())
741
        self.object.delete()
742
        return HttpResponseRedirect(self.get_success_url())
743

    
744

    
745
update_patient_state = \
746
    UpdatePatientStateView.as_view(model=FileState,
747
        template_name = 'dossiers/generic_form.html',
748
        success_url = '../../view#tab=0',
749
        form_class=forms.PatientStateForm)
750
delete_patient_state = \
751
    DeletePatientView.as_view(model=FileState,
752
        template_name = 'dossiers/generic_confirm_delete.html',
753
        success_url = '../../view#tab=0')
754

    
755

    
756
class GenerateRtfFormView(cbv.FormView):
757
    template_name = 'dossiers/generate_rtf_form.html'
758
    form_class = forms.GenerateRtfForm
759
    success_url = './view#tab=0'
760

    
761
    def get_context_data(self, **kwargs):
762
        ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
763
        ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
764
        ctx['service_id'] = self.service.id
765
        if self.request.GET.get('event-id'):
766
            date = self.request.GET.get('date')
767
            date = datetime.strptime(date, '%Y-%m-%d').date()
768
            appointment = Appointment()
769
            event = EventWithAct.objects.get(id=self.request.GET.get('event-id'))
770
            event = event.today_occurrence(date)
771
            appointment.init_from_event(event, self.service)
772
            ctx['event'] = event
773
            ctx['appointment'] = appointment
774
        return ctx
775

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

    
855
        filename = make_doc_from_template(from_path, to_path, variables,
856
            persistent)
857

    
858
        client_dir = patient.get_client_side_directory(self.service.name)
859
        event.convocation_sent = True
860
        event.save()
861
        if not client_dir:
862
            content = File(file(filename))
863
            response = HttpResponse(content,'text/rtf')
864
            response['Content-Length'] = content.size
865
            response['Content-Disposition'] = 'attachment; filename="%s"' \
866
                % dest_filename.encode('utf-8')
867
            return response
868
        else:
869
            class LocalFileHttpResponseRedirect(HttpResponseRedirect):
870
                allowed_schemes = ['file']
871
            client_filepath = os.path.join(client_dir, dest_filename)
872
            return LocalFileHttpResponseRedirect('file://' + client_filepath)
873

    
874
generate_rtf_form = GenerateRtfFormView.as_view()
875

    
876

    
877
class PatientRecordsQuotationsView(cbv.ListView):
878
    model = PatientRecord
879
    template_name = 'dossiers/quotations.html'
880

    
881
    def _get_search_result(self, paginate_patient_records):
882
        patient_records = []
883
        for patient_record in paginate_patient_records:
884
            current_state = patient_record.get_current_state()
885
            state = current_state.status.name
886
            state_class = current_state.status.type.lower()
887
            patient_records.append(
888
                    {
889
                        'object': patient_record,
890
                        'state': state,
891
                        'state_class': state_class
892
                        }
893
                    )
894
        return patient_records
895

    
896
    def get_queryset(self):
897
        form = forms.QuotationsForm(data=self.request.GET or None)
898
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
899
        without_quotations = self.request.GET.get('without_quotations')
900
        if without_quotations:
901
            qs = qs.filter(mises_1=None).filter(mises_2=None).filter(mises_3=None)
902
        states = self.request.GET.getlist('states')
903
        qs = qs.filter(last_state__status__id__in=states)
904

    
905
        try:
906
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
907
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
908
        except (ValueError, KeyError):
909
            pass
910
        try:
911
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
912
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
913
        except (ValueError, KeyError):
914
            pass
915
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
916
        return qs
917

    
918
    def get_context_data(self, **kwargs):
919
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
920
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
921
                service=self.service)
922
        patient_records = []
923
        page = self.request.GET.get('page')
924
        paginator = Paginator(ctx['object_list'].filter(), 50)
925
        try:
926
            paginate_patient_records = paginator.page(page)
927
        except PageNotAnInteger:
928
            paginate_patient_records = paginator.page(1)
929
        except EmptyPage:
930
            paginate_patient_records = paginator.page(paginator.num_pages)
931

    
932
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
933
        ctx['paginate_patient_records'] = paginate_patient_records
934

    
935
        query = self.request.GET.copy()
936
        if 'page' in query:
937
            del query['page']
938
        ctx['query'] = query.urlencode()
939

    
940
        return ctx
941

    
942
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
943

    
944
class NewProtectionStateView(cbv.CreateView):
945
    model = ProtectionState
946
    template_name = 'dossiers/generic_form.html'
947
    success_url = '../view#tab=1'
948
    form_class = forms.ProtectionStateForm
949

    
950
    def form_valid(self, form):
951
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
952
        form.instance.patient = self.patient
953
        return super(NewProtectionStateView, self).form_valid(form)
954

    
955
new_protection = NewProtectionStateView.as_view()
956

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

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

    
968
update_protection = UpdateProtectionStateView.as_view()
969

    
970
class DeleteProtectionStateView(cbv.DeleteView):
971
    model = ProtectionState
972
    template_name = 'dossiers/protection_confirm_delete.html'
973
    success_url = '../../view#tab=1'
974

    
975
delete_protection = DeleteProtectionStateView.as_view()
976

    
977
class PatientRecordsWaitingQueueView(cbv.ListView):
978
    model = PatientRecord
979
    template_name = 'dossiers/waiting_queue.html'
980

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

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

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

    
1037
        all_patient_records = PatientRecord.objects.filter(
1038
                service=self.service,
1039
                last_state__status__type='ACCUEIL').order_by(
1040
                'last_state__date_selected', 'created')
1041
        ctx['patient_records'] = self._get_search_result(
1042
            paginate_patient_records, all_patient_records)
1043
        ctx['paginate_patient_records'] = paginate_patient_records
1044
        ctx['len_patient_records'] = all_patient_records.count()
1045

    
1046
        query = self.request.GET.copy()
1047
        if 'page' in query:
1048
            del query['page']
1049
        ctx['query'] = query.urlencode()
1050

    
1051
        return ctx
1052

    
1053
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1054

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

    
1063
create_directory = CreateDirectoryView.as_view()
1064

    
1065
class GenerateTransportPrescriptionFormView(cbv.FormView):
1066
    template_name = 'dossiers/generate_transport_prescription_form.html'
1067
    form_class = Form
1068
    success_url = './view#tab=1'
1069

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

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

    
1111
prescription_transport = GenerateTransportPrescriptionFormView.as_view()
(11-11/11)