Projet

Général

Profil

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

calebasse / calebasse / dossiers / views.py @ 233fda5f

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
if settings.CV2PARSER:
42
    import cv2parser
43

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

    
50
    def post(self, request, *args, **kwarg):
51
        self.user = request.user
52
        return super(NewPatientRecordView, self).post(request, *args, **kwarg)
53

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

    
59
    def get_success_url(self):
60
        return '%s/view' % self.patient.id
61

    
62
new_patient_record = NewPatientRecordView.as_view()
63

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

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

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

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

    
99
new_patient_contact = NewPatientContactView.as_view()
100

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

    
107
update_patient_contact = UpdatePatientContactView.as_view()
108

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

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

    
125
delete_patient_contact = DeletePatientContactView.as_view()
126

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

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

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

    
143
new_patient_address = NewPatientAddressView.as_view()
144

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

    
151
update_patient_address = UpdatePatientAddressView.as_view()
152

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

    
159
delete_patient_address = DeletePatientAddressView.as_view()
160

    
161

    
162
class NewHealthCareView(cbv.CreateView):
163

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

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

    
213

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

    
219

    
220
    def post(self, request, *args, **kwarg):
221
        self.user = request.user
222
        return super(StateFormView, self).post(request, *args, **kwarg)
223

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

    
232
state_form = StateFormView.as_view()
233

    
234
class PatientRecordView(cbv.UpdateView):
235
    model = PatientRecord
236
    template_name = 'dossiers/patientrecord_update.html'
237

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

    
257
patient_record = PatientRecordView.as_view()
258

    
259
class PatientRecordPrint(cbv.DetailView):
260
    model = PatientRecord
261
    content_type = 'application/pdf'
262
    template_name = 'dossiers/patientrecord_print.html'
263

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

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

    
286
patient_record_print = PatientRecordPrint.as_view()
287

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

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

    
319
tab1_general = PatientRecordGeneralView.as_view()
320

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

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

    
335
tab2_fiche_adm = PatientRecordAdmView.as_view()
336

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

    
347

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

    
357
tab3_addresses = PatientRecordAddrView.as_view()
358

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

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

    
379
if settings.CV2PARSER:
380
    read_cv2 = validator_only(ReadCV2View.as_view())
381

    
382
class PatientRecordNotifsView(cbv.DetailView):
383
    model = PatientRecord
384
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
385

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

    
416
tab4_notifs = PatientRecordNotifsView.as_view()
417

    
418
class PatientRecordOldActs(cbv.DetailView):
419
    model = PatientRecord
420
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
421

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

    
451
tab5_old_acts = PatientRecordOldActs.as_view()
452

    
453
class PatientRecordNextAppointmentsView(cbv.DetailView):
454
    model = PatientRecord
455
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
456

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

    
488
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
489

    
490
class PatientRecordSocialisationView(cbv.DetailView):
491
    model = PatientRecord
492
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
493

    
494
tab7_socialisation = PatientRecordSocialisationView.as_view()
495

    
496
class PatientRecordMedicalView(cbv.UpdateView):
497
    model = PatientRecord
498
    form_class = forms.PhysiologyForm
499
    template_name = 'dossiers/patientrecord_tab8_medical.html'
500
    success_url = './view#tab=7'
501

    
502
tab8_medical = PatientRecordMedicalView.as_view()
503

    
504
class PatientRecordsHomepageView(cbv.ListView):
505
    model = PatientRecord
506
    template_name = 'dossiers/index.html'
507

    
508

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

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

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

    
567
        page = self.request.GET.get('page')
568
        if ctx['object_list']:
569
            patient_records = ctx['object_list'].filter()
570
        else:
571
            patient_records = []
572

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

    
587
        query = self.request.GET.copy()
588
        if 'page' in query:
589
            del query['page']
590
        ctx['query'] = query.urlencode()
591

    
592
        ctx['paginate_patient_records'] = paginate_patient_records
593
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
594
        return ctx
595

    
596
patientrecord_home = PatientRecordsHomepageView.as_view()
597

    
598
class PatientRecordDeleteView(DeleteView):
599
    model = PatientRecord
600
    success_url = ".."
601
    template_name = 'dossiers/patientrecord_confirm_delete.html'
602

    
603
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
604

    
605

    
606
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
607
    model = PatientRecord
608
    form_class = forms.PaperIDForm
609
    template_name = 'dossiers/generic_form.html'
610
    success_url = '../view#tab=0'
611

    
612
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
613

    
614

    
615
class NewSocialisationDurationView(cbv.CreateView):
616
    model = SocialisationDuration
617
    form_class = forms.SocialisationDurationForm
618
    template_name = 'dossiers/generic_form.html'
619
    success_url = '../view#tab=6'
620

    
621
    def get_success_url(self):
622
        return self.success_url
623

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

    
629
    def form_valid(self, form):
630
        duration = form.save()
631
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
632
        patientrecord.socialisation_durations.add(duration)
633
        return HttpResponseRedirect(self.get_success_url())
634

    
635
new_socialisation_duration = NewSocialisationDurationView.as_view()
636

    
637
class UpdateSocialisationDurationView(cbv.UpdateView):
638
    model = SocialisationDuration
639
    form_class = forms.SocialisationDurationForm
640
    template_name = 'dossiers/generic_form.html'
641
    success_url = '../../view#tab=6'
642

    
643
    def get(self, request, *args, **kwargs):
644
        if kwargs.has_key('patientrecord_id'):
645
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
646
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
647

    
648
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
649

    
650
class DeleteSocialisationDurationView(cbv.DeleteView):
651
    model = SocialisationDuration
652
    form_class = forms.SocialisationDurationForm
653
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
654
    success_url = '../../view#tab=6'
655

    
656
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
657

    
658

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

    
665
    def form_valid(self, form):
666
        request = form.save()
667
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
668
        patientrecord.mdph_requests.add(request)
669
        return HttpResponseRedirect(self.success_url)
670

    
671
class UpdateMDPHRequestView(cbv.UpdateView):
672
    def get(self, request, *args, **kwargs):
673
        if kwargs.has_key('patientrecord_id'):
674
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
675
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
676

    
677

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

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

    
699
    def form_valid(self, form):
700
        response = form.save()
701
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
702
        patientrecord.mdph_responses.add(response)
703
        return HttpResponseRedirect(self.success_url)
704

    
705
class UpdateMDPHResponseView(cbv.UpdateView):
706
    def get(self, request, *args, **kwargs):
707
        if kwargs.has_key('patientrecord_id'):
708
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
709
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
710

    
711

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

    
727

    
728
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
729

    
730
    def get_initial(self):
731
        initial = super(UpdatePatientStateView, self).get_initial()
732
        initial['date_selected'] = self.object.date_selected.date()
733
        return initial
734

    
735
    def get(self, request, *args, **kwargs):
736
        if kwargs.has_key('patientrecord_id'):
737
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
738
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
739

    
740
class DeletePatientView(cbv.DeleteView):
741

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

    
755

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

    
766

    
767
class GenerateRtfFormView(cbv.FormView):
768
    template_name = 'dossiers/generate_rtf_form.html'
769
    form_class = forms.GenerateRtfForm
770
    success_url = './view#tab=0'
771

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

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

    
866
        filename = make_doc_from_template(from_path, to_path, variables,
867
            persistent)
868

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

    
885
generate_rtf_form = GenerateRtfFormView.as_view()
886

    
887

    
888
class PatientRecordsQuotationsView(cbv.ListView):
889
    model = PatientRecord
890
    template_name = 'dossiers/quotations.html'
891

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

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

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

    
933
        if without_anap_quotations:
934
            for field in self.model.DEFICIENCY_FIELDS:
935
                anap_field = {field: 0}
936
                qs = qs.filter(**anap_field)
937

    
938
        states = self.request.GET.getlist('states')
939
        qs = qs.filter(last_state__status__id__in=states)
940

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

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

    
975
        ctx['patient_records'] = self._get_search_result(patient_records)
976

    
977
        query = self.request.GET.copy()
978
        if 'page' in query:
979
            del query['page']
980
        ctx['query'] = query.urlencode()
981

    
982
        return ctx
983

    
984
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
985

    
986
class NewProtectionStateView(cbv.CreateView):
987
    model = ProtectionState
988
    template_name = 'dossiers/generic_form.html'
989
    success_url = '../view#tab=1'
990
    form_class = forms.ProtectionStateForm
991

    
992
    def form_valid(self, form):
993
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
994
        form.instance.patient = self.patient
995
        return super(NewProtectionStateView, self).form_valid(form)
996

    
997
new_protection = NewProtectionStateView.as_view()
998

    
999
class UpdateProtectionStateView(cbv.UpdateView):
1000
    model = ProtectionState
1001
    template_name = 'dossiers/generic_form.html'
1002
    success_url = '../../view#tab=1'
1003
    form_class = forms.ProtectionStateForm
1004

    
1005
    def form_valid(self, form):
1006
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
1007
        form.instance.patient = self.patient
1008
        return super(UpdateProtectionStateView, self).form_valid(form)
1009

    
1010
update_protection = UpdateProtectionStateView.as_view()
1011

    
1012
class DeleteProtectionStateView(cbv.DeleteView):
1013
    model = ProtectionState
1014
    template_name = 'dossiers/protection_confirm_delete.html'
1015
    success_url = '../../view#tab=1'
1016

    
1017
delete_protection = DeleteProtectionStateView.as_view()
1018

    
1019
class PatientRecordsWaitingQueueView(cbv.ListView):
1020
    model = PatientRecord
1021
    template_name = 'dossiers/waiting_queue.html'
1022

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

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

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

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

    
1087
        all_patient_records = PatientRecord.objects.filter(
1088
                service=self.service,
1089
                last_state__status__type='ACCUEIL').order_by(
1090
                'last_state__date_selected', 'created')
1091
        ctx['patient_records'] = self._get_search_result(
1092
            paginate_patient_records, all_patient_records)
1093
        ctx['len_patient_records'] = all_patient_records.count()
1094

    
1095
        query = self.request.GET.copy()
1096
        if 'page' in query:
1097
            del query['page']
1098
        ctx['query'] = query.urlencode()
1099

    
1100
        return ctx
1101

    
1102
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1103

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

    
1112
create_directory = CreateDirectoryView.as_view()
1113

    
1114
class GenerateTransportPrescriptionFormView(cbv.FormView):
1115
    template_name = 'dossiers/generate_transport_prescription_form.html'
1116
    form_class = Form
1117
    success_url = './view#tab=1'
1118

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

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

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