Projet

Général

Profil

Télécharger (48,1 ko) Statistiques
| Branche: | Tag: | Révision:

calebasse / calebasse / dossiers / views.py @ 7c83c026

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
            'contact': forms.PatientContactForm,
252
            'id': forms.CivilStatusForm,
253
            'physiology': forms.PhysiologyForm,
254
            'inscription': forms.InscriptionForm,
255
            'out': forms.OutForm,
256
            'family': forms.FamilyForm,
257
            'transport': forms.TransportFrom,
258
            'followup': forms.FollowUpForm,
259
            'policyholder': forms.PolicyHolderForm
260
            }
261
    template_name = 'dossiers/patientrecord_update.html'
262
    success_url = './view'
263

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

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

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

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

    
486
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
487
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
488
        return ctx
489

    
490
    def form_valid(self, form):
491
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
492
        return super(PatientRecordView, self).form_valid(form)
493

    
494

    
495
patient_record = PatientRecordView.as_view()
496

    
497
class PatientRecordsHomepageView(cbv.ListView):
498
    model = PatientRecord
499
    template_name = 'dossiers/index.html'
500

    
501

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

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

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

    
560
        page = self.request.GET.get('page')
561
        if ctx['object_list']:
562
            patient_records = ctx['object_list'].filter()
563
        else:
564
            patient_records = []
565

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

    
580
        query = self.request.GET.copy()
581
        if 'page' in query:
582
            del query['page']
583
        ctx['query'] = query.urlencode()
584

    
585
        ctx['paginate_patient_records'] = paginate_patient_records
586
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
587
        return ctx
588

    
589
patientrecord_home = PatientRecordsHomepageView.as_view()
590

    
591
class PatientRecordDeleteView(DeleteView):
592
    model = PatientRecord
593
    success_url = ".."
594
    template_name = 'dossiers/patientrecord_confirm_delete.html'
595

    
596
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
597

    
598

    
599
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
600
    model = PatientRecord
601
    form_class = forms.PaperIDForm
602
    template_name = 'dossiers/generic_form.html'
603
    success_url = '../..'
604

    
605
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
606

    
607

    
608
class NewSocialisationDurationView(cbv.CreateView):
609
    model = SocialisationDuration
610
    form_class = forms.SocialisationDurationForm
611
    template_name = 'dossiers/generic_form.html'
612
    success_url = '../view#tab=6'
613

    
614
    def get_success_url(self):
615
        return self.success_url
616

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

    
622
    def form_valid(self, form):
623
        duration = form.save()
624
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
625
        patientrecord.socialisation_durations.add(duration)
626
        return HttpResponseRedirect(self.get_success_url())
627

    
628
new_socialisation_duration = NewSocialisationDurationView.as_view()
629

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

    
636
    def get(self, request, *args, **kwargs):
637
        if kwargs.has_key('patientrecord_id'):
638
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
639
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
640

    
641
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
642

    
643
class DeleteSocialisationDurationView(cbv.DeleteView):
644
    model = SocialisationDuration
645
    form_class = forms.SocialisationDurationForm
646
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
647
    success_url = '../../view#tab=6'
648

    
649
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
650

    
651

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

    
658
    def form_valid(self, form):
659
        request = form.save()
660
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
661
        patientrecord.mdph_requests.add(request)
662
        return HttpResponseRedirect(self.success_url)
663

    
664
class UpdateMDPHRequestView(cbv.UpdateView):
665
    def get(self, request, *args, **kwargs):
666
        if kwargs.has_key('patientrecord_id'):
667
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
668
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
669

    
670

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

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

    
692
    def form_valid(self, form):
693
        response = form.save()
694
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
695
        patientrecord.mdph_responses.add(response)
696
        return HttpResponseRedirect(self.success_url)
697

    
698
class UpdateMDPHResponseView(cbv.UpdateView):
699
    def get(self, request, *args, **kwargs):
700
        if kwargs.has_key('patientrecord_id'):
701
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
702
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
703

    
704

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

    
720

    
721
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
722

    
723
    def get_initial(self):
724
        initial = super(UpdatePatientStateView, self).get_initial()
725
        initial['date_selected'] = self.object.date_selected.date()
726
        return initial
727

    
728
    def get(self, request, *args, **kwargs):
729
        if kwargs.has_key('patientrecord_id'):
730
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
731
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
732

    
733
class DeletePatientView(cbv.DeleteView):
734

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

    
748

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

    
759

    
760
class GenerateRtfFormView(cbv.FormView):
761
    template_name = 'dossiers/generate_rtf_form.html'
762
    form_class = forms.GenerateRtfForm
763
    success_url = './view#tab=0'
764

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

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

    
859
        filename = make_doc_from_template(from_path, to_path, variables,
860
            persistent)
861

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

    
878
generate_rtf_form = GenerateRtfFormView.as_view()
879

    
880

    
881
class PatientRecordsQuotationsView(cbv.ListView):
882
    model = PatientRecord
883
    template_name = 'dossiers/quotations.html'
884

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

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

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

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

    
936
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
937
        ctx['paginate_patient_records'] = paginate_patient_records
938

    
939
        query = self.request.GET.copy()
940
        if 'page' in query:
941
            del query['page']
942
        ctx['query'] = query.urlencode()
943

    
944
        return ctx
945

    
946
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
947

    
948
class NewProtectionStateView(cbv.CreateView):
949
    model = ProtectionState
950
    template_name = 'dossiers/generic_form.html'
951
    success_url = '../view#tab=1'
952
    form_class = forms.ProtectionStateForm
953

    
954
    def form_valid(self, form):
955
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
956
        form.instance.patient = self.patient
957
        return super(NewProtectionStateView, self).form_valid(form)
958

    
959
new_protection = NewProtectionStateView.as_view()
960

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

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

    
972
update_protection = UpdateProtectionStateView.as_view()
973

    
974
class DeleteProtectionStateView(cbv.DeleteView):
975
    model = ProtectionState
976
    template_name = 'dossiers/protection_confirm_delete.html'
977
    success_url = '../../view#tab=1'
978

    
979
delete_protection = DeleteProtectionStateView.as_view()
980

    
981
class PatientRecordsWaitingQueueView(cbv.ListView):
982
    model = PatientRecord
983
    template_name = 'dossiers/waiting_queue.html'
984

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

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

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

    
1041
        all_patient_records = PatientRecord.objects.filter(
1042
                service=self.service,
1043
                last_state__status__type='ACCUEIL').order_by(
1044
                'last_state__date_selected', 'created')
1045
        ctx['patient_records'] = self._get_search_result(
1046
            paginate_patient_records, all_patient_records)
1047
        ctx['paginate_patient_records'] = paginate_patient_records
1048
        ctx['len_patient_records'] = all_patient_records.count()
1049

    
1050
        query = self.request.GET.copy()
1051
        if 'page' in query:
1052
            del query['page']
1053
        ctx['query'] = query.urlencode()
1054

    
1055
        return ctx
1056

    
1057
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1058

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

    
1067
create_directory = CreateDirectoryView.as_view()
1068

    
1069
class GenerateTransportPrescriptionFormView(cbv.FormView):
1070
    template_name = 'dossiers/generate_transport_prescription_form.html'
1071
    form_class = Form
1072
    success_url = './view#tab=1'
1073

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

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

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