Projet

Général

Profil

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

calebasse / calebasse / dossiers / views.py @ fce3e1e6

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

    
3
import os
4

    
5
from datetime import datetime, date
6

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

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

    
37
from calebasse.decorators import validator_only
38

    
39
from ..utils import get_service_setting, is_validator, get_last_file
40

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

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

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

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

    
59
new_patient_record = NewPatientRecordView.as_view()
60

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

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

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

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

    
96
new_patient_contact = NewPatientContactView.as_view()
97

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

    
104
update_patient_contact = UpdatePatientContactView.as_view()
105

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

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

    
122
delete_patient_contact = DeletePatientContactView.as_view()
123

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

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

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

    
140
new_patient_address = NewPatientAddressView.as_view()
141

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

    
148
update_patient_address = UpdatePatientAddressView.as_view()
149

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

    
156
delete_patient_address = DeletePatientAddressView.as_view()
157

    
158

    
159
class NewHealthCareView(cbv.CreateView):
160

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

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

    
210

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

    
216

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

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

    
229
state_form = StateFormView.as_view()
230

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

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

    
254
patient_record = PatientRecordView.as_view()
255

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

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

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

    
283
patient_record_print = PatientRecordPrint.as_view()
284

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

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

    
316
tab1_general = PatientRecordGeneralView.as_view()
317

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

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

    
332
tab2_fiche_adm = PatientRecordAdmView.as_view()
333

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

    
344

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

    
354
tab3_addresses = PatientRecordAddrView.as_view()
355

    
356
class ReadCV2View(cbv.FormView):
357
    template_name = 'dossiers/cv2.html'
358
    form_class = Form
359
    success_url = './view#tab=2'
360

    
361
    def get_context_data(self, **kwargs):
362
        ctx = super(ReadCV2View, self).get_context_data(**kwargs)
363
        cv_files_path = get_service_setting('cv_files_path')
364
        if not cv_files_path or not os.path.isdir(cv_files_path):
365
            return ctx
366
        reader_identifier = None
367
        try:
368
            reader_identifier = self.request.user.userworker.worker.cv2_reader_name
369
        except:
370
            pass
371
        filename = get_last_file(cv_files_path,
372
                prefix=reader_identifier, suffix='.xml')
373
        ctx['carte_vitale'] = filename
374
        return ctx
375

    
376
read_cv2 = validator_only(ReadCV2View.as_view())
377

    
378
class PatientRecordNotifsView(cbv.DetailView):
379
    model = PatientRecord
380
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
381

    
382
    def get_context_data(self, **kwargs):
383
        ctx = super(PatientRecordNotifsView, self).get_context_data(**kwargs)
384
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
385
        if ctx['object'].service.slug == "cmpp":
386
            (acts_not_locked, days_not_locked, acts_not_valide,
387
            acts_not_billable, acts_pause, acts_per_hc, acts_losts) = \
388
                list_acts_for_billing_CMPP_per_patient(self.object,
389
                    datetime.today(), self.service)
390
            ctx['acts_losts'] = acts_losts
391
            ctx['acts_pause'] = acts_pause
392
            hcs_used = acts_per_hc.keys()
393
            hcs = None
394
            if not hcs_used:
395
                hcs = [(hc, None) for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date')]
396
            else:
397
                hcs = []
398
                for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date'):
399
                    acts = None
400
                    if hasattr(hc, 'cmpphealthcarediagnostic') and hc.cmpphealthcarediagnostic in hcs_used:
401
                        acts = acts_per_hc[hc.cmpphealthcarediagnostic]
402
                    elif hasattr(hc, 'cmpphealthcaretreatment') and hc.cmpphealthcaretreatment in hcs_used:
403
                        acts = acts_per_hc[hc.cmpphealthcaretreatment]
404
                    hcs.append((hc, acts))
405
            ctx['hcs'] = []
406
            for hc, acts in hcs:
407
                ctx['hcs'].append((hc, acts, hc.act_set.order_by('date', 'time')))
408
        elif ctx['object'].service.slug == "sessad-ted" or ctx['object'].service.slug == "sessad-dys":
409
            ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
410
        return ctx
411

    
412
tab4_notifs = PatientRecordNotifsView.as_view()
413

    
414
class PatientRecordOldActs(cbv.DetailView):
415
    model = PatientRecord
416
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
417

    
418
    def get_context_data(self, **kwargs):
419
        ctx = super(PatientRecordOldActs, self).get_context_data(**kwargs)
420
        ctx['last_rdvs'] = []
421
        for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
422
            state = act.get_state()
423
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
424
                state = None
425
            missing_workers = []
426
            try:
427
                missing_workers = [participant.worker for participant in act.event.get_missing_participants()]
428
            except:
429
                pass
430
            ctx['last_rdvs'].append((act, state, missing_workers))
431
        history = []
432
        i = 0
433
        for state in ctx['object'].filestate_set.order_by('-date_selected'):
434
            acts = []
435
            try:
436
                while ctx['last_rdvs'][i][0].date >= state.date_selected.date():
437
                    acts.append(ctx['last_rdvs'][i])
438
                    i += 1
439
            except:
440
                pass
441
            history.append((state, acts))
442
        if i < len(ctx['last_rdvs']) - 1:
443
            history.append((None, ctx['last_rdvs'][i:]))
444
        ctx['history'] = history
445
        return ctx
446

    
447
tab5_old_acts = PatientRecordOldActs.as_view()
448

    
449
class PatientRecordNextAppointmentsView(cbv.DetailView):
450
    model = PatientRecord
451
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
452

    
453
    def get_context_data(self, **kwargs):
454
        ctx = super(PatientRecordNextAppointmentsView, self).get_context_data(**kwargs)
455
        ctx['next_rdvs'] = []
456
        Q = models.Q
457
        today = date.today()
458
        qs = EventWithAct.objects.filter(patient=ctx['object']) \
459
                .filter(exception_to__isnull=True, canceled=False) \
460
                .filter(Q(start_datetime__gte=today) \
461
                |  Q(exceptions__isnull=False) \
462
                | ( Q(recurrence_periodicity__isnull=False) \
463
                & (Q(recurrence_end_date__gte=today) \
464
                | Q(recurrence_end_date__isnull=True) \
465
                ))) \
466
                .distinct() \
467
                .select_related() \
468
                .prefetch_related('participants', 'exceptions__eventwithact',
469
                        'act_set__actvalidationstate_set')
470
        occurrences = []
471
        for event in qs:
472
            occurrences.extend(filter(lambda e: e.start_datetime.date() >= today,
473
                event.all_occurences(limit=180)))
474
        occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
475
        for event in occurrences:
476
            state = None
477
            if event.act:
478
                state = event.act.get_state()
479
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
480
                state = None
481
            ctx['next_rdvs'].append((event, state, event.get_missing_participants(), event.get_inactive_participants()))
482
        return ctx
483

    
484
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
485

    
486
class PatientRecordSocialisationView(cbv.DetailView):
487
    model = PatientRecord
488
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
489

    
490
tab7_socialisation = PatientRecordSocialisationView.as_view()
491

    
492
class PatientRecordMedicalView(cbv.UpdateView):
493
    model = PatientRecord
494
    form_class = forms.PhysiologyForm
495
    template_name = 'dossiers/patientrecord_tab8_medical.html'
496
    success_url = './view#tab=7'
497

    
498
tab8_medical = PatientRecordMedicalView.as_view()
499

    
500
class PatientRecordsHomepageView(cbv.ListView):
501
    model = PatientRecord
502
    template_name = 'dossiers/index.html'
503

    
504

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

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

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

    
563
        page = self.request.GET.get('page')
564
        if ctx['object_list']:
565
            patient_records = ctx['object_list'].filter()
566
        else:
567
            patient_records = []
568

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

    
583
        query = self.request.GET.copy()
584
        if 'page' in query:
585
            del query['page']
586
        ctx['query'] = query.urlencode()
587

    
588
        ctx['paginate_patient_records'] = paginate_patient_records
589
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
590
        return ctx
591

    
592
patientrecord_home = PatientRecordsHomepageView.as_view()
593

    
594
class PatientRecordDeleteView(DeleteView):
595
    model = PatientRecord
596
    success_url = ".."
597
    template_name = 'dossiers/patientrecord_confirm_delete.html'
598

    
599
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
600

    
601

    
602
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
603
    model = PatientRecord
604
    form_class = forms.PaperIDForm
605
    template_name = 'dossiers/generic_form.html'
606
    success_url = '../view#tab=0'
607

    
608
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
609

    
610

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

    
617
    def get_success_url(self):
618
        return self.success_url
619

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

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

    
631
new_socialisation_duration = NewSocialisationDurationView.as_view()
632

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

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

    
644
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
645

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

    
652
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
653

    
654

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

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

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

    
673

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

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

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

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

    
707

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

    
723

    
724
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
725

    
726
    def get_initial(self):
727
        initial = super(UpdatePatientStateView, self).get_initial()
728
        initial['date_selected'] = self.object.date_selected.date()
729
        return initial
730

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

    
736
class DeletePatientView(cbv.DeleteView):
737

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

    
751

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

    
762

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

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

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

    
862
        filename = make_doc_from_template(from_path, to_path, variables,
863
            persistent)
864

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

    
881
generate_rtf_form = GenerateRtfFormView.as_view()
882

    
883

    
884
class PatientRecordsQuotationsView(cbv.ListView):
885
    model = PatientRecord
886
    template_name = 'dossiers/quotations.html'
887

    
888
    def _get_search_result(self, paginate_patient_records):
889
        patient_records = []
890
        for patient_record in paginate_patient_records:
891
            current_state = patient_record.get_current_state() or patient_record.get_state()
892
            deficiencies = [getattr(patient_record, field) \
893
                            for field in self.model.DEFICIENCY_FIELDS]
894
            anap = any(deficiencies)
895
            mises = reduce(lambda m1, m2: m1+m2, [list(getattr(patient_record, field).all()) for field in self.model.MISES_FIELDS])
896
            next_rdv = get_next_rdv(patient_record)
897
            last_rdv = get_last_rdv(patient_record)
898

    
899
            if next_rdv:
900
                next_rdv_datetime = next_rdv.start_datetime
901
            else:
902
                next_rdv_datetime = None
903
            if last_rdv:
904
                last_rdv_datetime = last_rdv['start_datetime']
905
            else:
906
                last_rdv_datetime = None
907
            patient_records.append(
908
                    {
909
                        'object': patient_record,
910
                        'state': current_state,
911
                        'anap': anap,
912
                        'mises': mises,
913
                        'next_rdv_date': next_rdv_datetime,
914
                        'last_rdv_date': last_rdv_datetime
915
                        }
916
                    )
917
        return patient_records
918

    
919
    def get_queryset(self):
920
        form = forms.QuotationsForm(data=self.request.GET or None)
921
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
922
        without_quotations = self.request.GET.get('without_quotations')
923
        without_anap_quotations = self.request.GET.get('without_anap_quotations')
924
        if without_quotations:
925
            for field in self.model.MISES_FIELDS:
926
                mise_field = {'%s__isnull' % field: True}
927
                qs = qs.filter(**mise_field)
928

    
929
        if without_anap_quotations:
930
            for field in self.model.DEFICIENCY_FIELDS:
931
                anap_field = {field: 0}
932
                qs = qs.filter(**anap_field)
933

    
934
        states = self.request.GET.getlist('states')
935
        qs = qs.filter(last_state__status__id__in=states)
936

    
937
        try:
938
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
939
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
940
        except (ValueError, KeyError):
941
            pass
942
        try:
943
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
944
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
945
        except (ValueError, KeyError):
946
            pass
947
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
948
        return qs
949

    
950
    def get_context_data(self, **kwargs):
951
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
952
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
953
                service=self.service)
954
        patient_records = []
955
        page = self.request.GET.get('page')
956
        all = 'all' in self.request.GET
957
        if all:
958
            patient_records = ctx['object_list']
959
            ctx['all'] = all
960
            self.template_name = 'dossiers/quotations_print.html'
961
        else:
962
            paginator = Paginator(ctx['object_list'].filter(), 25)
963
            try:
964
                patient_records = paginator.page(page)
965
            except PageNotAnInteger:
966
                patient_records = paginator.page(1)
967
            except EmptyPage:
968
                patient_records = paginator.page(paginator.num_pages)
969
            ctx['paginate_patient_records'] = patient_records
970

    
971
        ctx['patient_records'] = self._get_search_result(patient_records)
972

    
973
        query = self.request.GET.copy()
974
        if 'page' in query:
975
            del query['page']
976
        ctx['query'] = query.urlencode()
977

    
978
        return ctx
979

    
980
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
981

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

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

    
993
new_protection = NewProtectionStateView.as_view()
994

    
995
class UpdateProtectionStateView(cbv.UpdateView):
996
    model = ProtectionState
997
    template_name = 'dossiers/generic_form.html'
998
    success_url = '../../view#tab=1'
999
    form_class = forms.ProtectionStateForm
1000

    
1001
    def form_valid(self, form):
1002
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
1003
        form.instance.patient = self.patient
1004
        return super(UpdateProtectionStateView, self).form_valid(form)
1005

    
1006
update_protection = UpdateProtectionStateView.as_view()
1007

    
1008
class DeleteProtectionStateView(cbv.DeleteView):
1009
    model = ProtectionState
1010
    template_name = 'dossiers/protection_confirm_delete.html'
1011
    success_url = '../../view#tab=1'
1012

    
1013
delete_protection = DeleteProtectionStateView.as_view()
1014

    
1015
class PatientRecordsWaitingQueueView(cbv.ListView):
1016
    model = PatientRecord
1017
    template_name = 'dossiers/waiting_queue.html'
1018

    
1019
    def _get_search_result(self, paginate_patient_records,
1020
            all_patient_records):
1021
        patient_records = []
1022
        if paginate_patient_records:
1023
            position = 1
1024
            for patient_record in paginate_patient_records:
1025
                while patient_record.id != all_patient_records[position - 1].id:
1026
                    position += 1
1027
                patient_records.append(
1028
                        {
1029
                            'object': patient_record,
1030
                            'position': position,
1031
                            }
1032
                        )
1033
        return patient_records
1034

    
1035
    def get_queryset(self):
1036
        form = forms.QuotationsForm(data=self.request.GET or None)
1037
        qs = super(PatientRecordsWaitingQueueView, self).get_queryset()
1038
        first_name = self.request.GET.get('first_name')
1039
        last_name = self.request.GET.get('last_name')
1040
        paper_id = self.request.GET.get('paper_id')
1041
        id = self.request.GET.get('id')
1042
        social_security_id = self.request.GET.get('social_security_id')
1043
        qs = qs.filter(service=self.service,
1044
            last_state__status__type='ACCUEIL')
1045
        if last_name:
1046
            qs = qs.filter(last_name__istartswith=last_name)
1047
        if first_name:
1048
            qs = qs.filter(first_name__istartswith=first_name)
1049
        if paper_id:
1050
            qs = qs.filter(paper_id__startswith=paper_id)
1051
        if id:
1052
            qs = qs.filter(id__startswith=id)
1053
        if social_security_id:
1054
            qs = qs.filter(models.Q(
1055
                social_security_id__startswith=social_security_id)
1056
                | models.Q(
1057
                contacts__social_security_id__startswith=social_security_id))
1058
        qs = qs.order_by('last_state__date_selected', 'created')
1059
        return qs
1060

    
1061
    def get_context_data(self, **kwargs):
1062
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
1063
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
1064
                service=self.service)
1065
        patient_records = []
1066
        page = self.request.GET.get('page')
1067

    
1068
        all = 'all' in self.request.GET
1069
        if all:
1070
            paginate_patient_records = ctx['object_list']
1071
            ctx['all'] = all
1072
            self.template_name = 'dossiers/waiting_queue_print.html'
1073
        else:
1074
            paginator = Paginator(ctx['object_list'].filter(), 25)
1075
            try:
1076
                paginate_patient_records = paginator.page(page)
1077
            except PageNotAnInteger:
1078
                paginate_patient_records = paginator.page(1)
1079
            except EmptyPage:
1080
                paginate_patient_records = paginator.page(paginator.num_pages)
1081
            ctx['paginate_patient_records'] = paginate_patient_records
1082

    
1083
        all_patient_records = PatientRecord.objects.filter(
1084
                service=self.service,
1085
                last_state__status__type='ACCUEIL').order_by(
1086
                'last_state__date_selected', 'created')
1087
        ctx['patient_records'] = self._get_search_result(
1088
            paginate_patient_records, all_patient_records)
1089
        ctx['len_patient_records'] = all_patient_records.count()
1090

    
1091
        query = self.request.GET.copy()
1092
        if 'page' in query:
1093
            del query['page']
1094
        ctx['query'] = query.urlencode()
1095

    
1096
        return ctx
1097

    
1098
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1099

    
1100
class CreateDirectoryView(View, cbv.ServiceViewMixin):
1101
    def post(self, request, *args, **kwargs):
1102
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
1103
        service = Service.objects.get(slug=kwargs['service'])
1104
        patient.get_ondisk_directory(service.name)
1105
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
1106
        return HttpResponseRedirect('view')
1107

    
1108
create_directory = CreateDirectoryView.as_view()
1109

    
1110
class GenerateTransportPrescriptionFormView(cbv.FormView):
1111
    template_name = 'dossiers/generate_transport_prescription_form.html'
1112
    form_class = Form
1113
    success_url = './view#tab=1'
1114

    
1115
    def get_context_data(self, **kwargs):
1116
        ctx = super(GenerateTransportPrescriptionFormView, self).get_context_data(**kwargs)
1117
        ctx['lieu'] = 'Saint-Etienne'
1118
        ctx['date'] = formats.date_format(datetime.today(), "SHORT_DATE_FORMAT")
1119
        ctx['id_etab'] = '''%s SAINT ETIENNE
1120
66/68, RUE MARENGO
1121
42000 SAINT ETIENNE''' % ctx['service'].upper()
1122
        try:
1123
            patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1124
            ctx['object'] = patient
1125
            last_log = TransportPrescriptionLog.objects.filter(patient=patient).latest('created')
1126
            if last_log:
1127
                ctx['choices'] = last_log.get_choices()
1128
                if 'lieu' in ctx['choices'] and ctx['choices']['lieu']:
1129
                    ctx['lieu'] = ctx['choices']['lieu']
1130
                if 'date' in ctx['choices'] and ctx['choices']['date']:
1131
                    ctx['date'] = ctx['choices']['date']
1132
                if 'id_etab' in ctx['choices'] and ctx['choices']['id_etab']:
1133
                    ctx['id_etab'] = ctx['choices']['id_etab']
1134
        except:
1135
            pass
1136
        return ctx
1137

    
1138
    def form_valid(self, form):
1139
        patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1140
        address = PatientAddress.objects.get(id=form.data['address_id'])
1141
        path = render_transport(patient, address, form.data)
1142
        content = File(file(path))
1143
        log = TransportPrescriptionLog(patient=patient)
1144
        log.set_choices(form.data)
1145
        log.save()
1146
        response = HttpResponse(content,'application/pdf')
1147
        response['Content-Length'] = content.size
1148
        dest_filename = "%s--prescription-transport-%s-%s.pdf" \
1149
            % (datetime.now().strftime('%Y-%m-%d--%H:%M:%S'),
1150
            patient.last_name.upper().encode('utf-8'),
1151
            patient.first_name.encode('utf-8'))
1152
        response['Content-Disposition'] = \
1153
            'attachment; filename="%s"' % dest_filename
1154
        return response
1155

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