Project

General

Profile

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

calebasse / calebasse / dossiers / views.py @ 0ae9ecd6

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

    
36
from calebasse.decorators import validator_only
37

    
38

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

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

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

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

    
57
new_patient_record = NewPatientRecordView.as_view()
58

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

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

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

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

    
94
new_patient_contact = NewPatientContactView.as_view()
95

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

    
102
update_patient_contact = UpdatePatientContactView.as_view()
103

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

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

    
120
delete_patient_contact = DeletePatientContactView.as_view()
121

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

    
128
    def get_success_url(self):
129
        return self.success_url
130

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

    
138
new_patient_address = NewPatientAddressView.as_view()
139

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

    
146
    def form_valid(self, form):
147
        messages.add_message(self.request,
148
                messages.INFO,
149
                u'Modification enregistrée avec succès.')
150
        return super(UpdatePatientAddressView, self).form_valid(form)
151

    
152
update_patient_address = UpdatePatientAddressView.as_view()
153

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

    
160
delete_patient_address = DeletePatientAddressView.as_view()
161

    
162

    
163
class NewHealthCareView(cbv.CreateView):
164

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

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

    
214

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

    
220

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

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

    
233
state_form = StateFormView.as_view()
234

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

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

    
258
patient_record = PatientRecordView.as_view()
259

    
260
class PatientRecordGeneralView(cbv.UpdateView):
261
    model = PatientRecord
262
    form_class = forms.GeneralForm
263
    template_name = 'dossiers/patientrecord_tab1_general.html'
264
    success_url = './view'
265

    
266
    def get_context_data(self, **kwargs):
267
        ctx = super(PatientRecordGeneralView, self).get_context_data(**kwargs)
268
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
269
        ctx['initial_state'] = ctx['object'].get_initial_state()
270
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
271
        ctx['next_rdv'] = get_next_rdv(ctx['object'])
272
        current_state = ctx['object'].get_current_state()
273
        if current_state.status and STATES_MAPPING.has_key(current_state.status.type):
274
            state = STATES_MAPPING[current_state.status.type]
275
        elif current_state.status:
276
            state = current_state.status.name
277
        else:
278
            state = "Aucun"
279
        ctx['current_state'] = current_state
280
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
281
        ctx['missing_policy'] = False
282
        if not self.object.policyholder or \
283
                not self.object.policyholder.health_center or \
284
                not self.object.policyholder.social_security_id:
285
            ctx['missing_policy'] = True
286
        ctx['missing_birthdate'] = False
287
        if not self.object.birthdate:
288
            ctx['missing_birthdate'] = True
289
        return ctx
290

    
291
tab1_general = PatientRecordGeneralView.as_view()
292

    
293
class PatientRecordAdmView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
294
    model = PatientRecord
295
    forms_classes = {
296
            'id': forms.CivilStatusForm,
297
            'inscription': forms.InscriptionForm,
298
            'out': forms.OutForm,
299
            'family': forms.FamilyForm,
300
            'transport': forms.TransportFrom,
301
            'followup': forms.FollowUpForm,
302
            }
303
    template_name = 'dossiers/patientrecord_tab2_fiche_adm.html'
304
    success_url = './view#tab=1'
305

    
306

    
307
    def get_context_data(self, **kwargs):
308
        ctx = super(PatientRecordAdmView, self).get_context_data(**kwargs)
309
        try:
310
            ctx['last_prescription'] = TransportPrescriptionLog.objects.filter(patient=ctx['object']).latest('created')
311
        except:
312
            pass
313
        return ctx
314

    
315
tab2_fiche_adm = PatientRecordAdmView.as_view()
316

    
317
class PatientRecordAddrView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
318
    model = PatientRecord
319
    forms_classes = {
320
            'contact': forms.PatientContactForm,
321
            'policyholder': forms.PolicyHolderForm
322
            }
323
    template_name = 'dossiers/patientrecord_tab3_adresses.html'
324
    success_url = './view#tab=2'
325

    
326

    
327
    def get_context_data(self, **kwargs):
328
        ctx = super(PatientRecordAddrView, self).get_context_data(**kwargs)
329
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
330
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
331
        return ctx
332

    
333
tab3_addresses = PatientRecordAddrView.as_view()
334

    
335
class PatientRecordNotifsView(cbv.DetailView):
336
    model = PatientRecord
337
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
338

    
339
    def get_context_data(self, **kwargs):
340
        ctx = super(PatientRecordNotifsView, self).get_context_data(**kwargs)
341
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
342
        if ctx['object'].service.slug == "cmpp":
343
            (acts_not_locked, days_not_locked, acts_not_valide,
344
            acts_not_billable, acts_pause, acts_per_hc, acts_losts) = \
345
                list_acts_for_billing_CMPP_per_patient(self.object,
346
                    datetime.today(), self.service)
347
            ctx['acts_losts'] = acts_losts
348
            ctx['acts_pause'] = acts_pause
349
            hcs_used = acts_per_hc.keys()
350
            hcs = None
351
            if not hcs_used:
352
                hcs = [(hc, None) for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date')]
353
            else:
354
                hcs = []
355
                for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date'):
356
                    acts = None
357
                    if hasattr(hc, 'cmpphealthcarediagnostic') and hc.cmpphealthcarediagnostic in hcs_used:
358
                        acts = acts_per_hc[hc.cmpphealthcarediagnostic]
359
                    elif hasattr(hc, 'cmpphealthcaretreatment') and hc.cmpphealthcaretreatment in hcs_used:
360
                        acts = acts_per_hc[hc.cmpphealthcaretreatment]
361
                    hcs.append((hc, acts))
362
            ctx['hcs'] = []
363
            for hc, acts in hcs:
364
                ctx['hcs'].append((hc, acts, hc.act_set.order_by('date', 'time')))
365
        elif ctx['object'].service.slug == "sessad-ted" or ctx['object'].service.slug == "sessad-dys":
366
            ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
367
        return ctx
368

    
369
tab4_notifs = PatientRecordNotifsView.as_view()
370

    
371
class PatientRecordOldActs(cbv.DetailView):
372
    model = PatientRecord
373
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
374

    
375
    def get_context_data(self, **kwargs):
376
        ctx = super(PatientRecordOldActs, self).get_context_data(**kwargs)
377
        ctx['last_rdvs'] = []
378
        for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
379
            state = act.get_state()
380
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
381
                state = None
382
            missing_workers = []
383
            try:
384
                missing_workers = [participant.worker for participant in act.event.get_missing_participants()]
385
            except:
386
                pass
387
            ctx['last_rdvs'].append((act, state, missing_workers))
388
        history = []
389
        i = 0
390
        for state in ctx['object'].filestate_set.order_by('-date_selected'):
391
            acts = []
392
            try:
393
                while ctx['last_rdvs'][i][0].date >= state.date_selected.date():
394
                    acts.append(ctx['last_rdvs'][i])
395
                    i += 1
396
            except:
397
                pass
398
            history.append((state, acts))
399
        if i < len(ctx['last_rdvs']) - 1:
400
            history.append((None, ctx['last_rdvs'][i:]))
401
        ctx['history'] = history
402
        return ctx
403

    
404
tab5_old_acts = PatientRecordOldActs.as_view()
405

    
406
class PatientRecordNextAppointmentsView(cbv.DetailView):
407
    model = PatientRecord
408
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
409

    
410
    def get_context_data(self, **kwargs):
411
        ctx = super(PatientRecordNextAppointmentsView, self).get_context_data(**kwargs)
412
        ctx['next_rdvs'] = []
413
        Q = models.Q
414
        today = date.today()
415
        qs = EventWithAct.objects.filter(patient=ctx['object']) \
416
                .filter(exception_to__isnull=True, canceled=False) \
417
                .filter(Q(start_datetime__gte=today) \
418
                |  Q(exceptions__isnull=False) \
419
                | ( Q(recurrence_periodicity__isnull=False) \
420
                & (Q(recurrence_end_date__gte=today) \
421
                | Q(recurrence_end_date__isnull=True) \
422
                ))) \
423
                .distinct() \
424
                .select_related() \
425
                .prefetch_related('participants', 'exceptions__eventwithact',
426
                        'act_set__actvalidationstate_set')
427
        occurrences = []
428
        for event in qs:
429
            occurrences.extend(filter(lambda e: e.start_datetime.date() >= today,
430
                event.all_occurences(limit=180)))
431
        occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
432
        for event in occurrences:
433
            state = None
434
            if event.act:
435
                state = event.act.get_state()
436
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
437
                state = None
438
            ctx['next_rdvs'].append((event, state, event.get_missing_participants(), event.get_inactive_participants()))
439
        return ctx
440

    
441
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
442

    
443
class PatientRecordSocialisationView(cbv.DetailView):
444
    model = PatientRecord
445
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
446

    
447
tab7_socialisation = PatientRecordSocialisationView.as_view()
448

    
449
class PatientRecordMedicalView(cbv.UpdateView):
450
    model = PatientRecord
451
    form_class = forms.PhysiologyForm
452
    template_name = 'dossiers/patientrecord_tab8_medical.html'
453
    success_url = './view#tab=7'
454

    
455
tab8_medical = PatientRecordMedicalView.as_view()
456

    
457
class PatientRecordsHomepageView(cbv.ListView):
458
    model = PatientRecord
459
    template_name = 'dossiers/index.html'
460

    
461

    
462
    def _get_search_result(self, paginate_patient_records):
463
        patient_records = []
464
        for patient_record in paginate_patient_records:
465
            next_rdv = get_next_rdv(patient_record)
466
            last_rdv = get_last_rdv(patient_record)
467
            current_status = patient_record.last_state.status
468
            state = current_status.name
469
            state_class = current_status.type.lower()
470
            patient_records.append(
471
                    {
472
                        'object': patient_record,
473
                        'next_rdv': next_rdv,
474
                        'last_rdv': last_rdv,
475
                        'state': state,
476
                        'state_class': state_class
477
                        }
478
                    )
479
        return patient_records
480

    
481
    def get_queryset(self):
482
        first_name = self.request.GET.get('first_name')
483
        last_name = self.request.GET.get('last_name')
484
        paper_id = self.request.GET.get('paper_id')
485
        id = self.request.GET.get('id')
486
        social_security_id = self.request.GET.get('social_security_id')
487
        if not (first_name or last_name or paper_id or id or social_security_id):
488
            return None
489
        if (first_name and len(first_name) < 2) or (last_name and len(last_name) < 2):
490
            return None
491
        qs = super(PatientRecordsHomepageView, self).get_queryset()
492
        states = self.request.GET.getlist('states')
493
        if last_name:
494
            qs = qs.filter(last_name__istartswith=last_name)
495
        if first_name:
496
            qs = qs.filter(first_name__istartswith=first_name)
497
        if paper_id:
498
            qs = qs.filter(paper_id__startswith=paper_id)
499
        if id:
500
            qs = qs.filter(id__startswith=id)
501
        if social_security_id:
502
            qs = qs.filter(models.Q(social_security_id__startswith=social_security_id) | \
503
                models.Q(contacts__social_security_id__startswith=social_security_id))
504
        if states:
505
            qs = qs.filter(last_state__status__id__in=states)
506
        else:
507
            qs = qs.filter(last_state__status__type__in="")
508
        qs = qs.filter(service=self.service).order_by('last_name').\
509
                prefetch_related('last_state',
510
                        'patientcontact', 'last_state__status')
511
        return qs
512

    
513
    def get_context_data(self, **kwargs):
514
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
515
        ctx['search_form'] = forms.SearchForm(service=self.service, data=self.request.GET or None)
516
        ctx['stats'] = [["Dossiers", 0]]
517
        for status in Status.objects.filter(services=self.service):
518
            ctx['stats'].append([status.name, 0])
519

    
520
        page = self.request.GET.get('page')
521
        if ctx['object_list']:
522
            patient_records = ctx['object_list'].filter()
523
        else:
524
            patient_records = []
525

    
526
        # TODO: use a sql query to do this
527
        for patient_record in patient_records:
528
            ctx['stats'][0][1] += 1
529
            for elem in ctx['stats']:
530
                if elem[0] == patient_record.last_state.status.name:
531
                    elem[1] += 1
532
        paginator = Paginator(patient_records, 50)
533
        try:
534
            paginate_patient_records = paginator.page(page)
535
        except PageNotAnInteger:
536
            paginate_patient_records = paginator.page(1)
537
        except EmptyPage:
538
            paginate_patient_records = paginator.page(paginator.num_pages)
539

    
540
        query = self.request.GET.copy()
541
        if 'page' in query:
542
            del query['page']
543
        ctx['query'] = query.urlencode()
544

    
545
        ctx['paginate_patient_records'] = paginate_patient_records
546
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
547
        return ctx
548

    
549
patientrecord_home = PatientRecordsHomepageView.as_view()
550

    
551
class PatientRecordDeleteView(DeleteView):
552
    model = PatientRecord
553
    success_url = ".."
554
    template_name = 'dossiers/patientrecord_confirm_delete.html'
555

    
556
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
557

    
558

    
559
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
560
    model = PatientRecord
561
    form_class = forms.PaperIDForm
562
    template_name = 'dossiers/generic_form.html'
563
    success_url = '../..'
564

    
565
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
566

    
567

    
568
class NewSocialisationDurationView(cbv.CreateView):
569
    model = SocialisationDuration
570
    form_class = forms.SocialisationDurationForm
571
    template_name = 'dossiers/generic_form.html'
572
    success_url = '../view#tab=6'
573

    
574
    def get_success_url(self):
575
        return self.success_url
576

    
577
    def get(self, request, *args, **kwargs):
578
        if kwargs.has_key('patientrecord_id'):
579
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
580
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
581

    
582
    def form_valid(self, form):
583
        duration = form.save()
584
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
585
        patientrecord.socialisation_durations.add(duration)
586
        return HttpResponseRedirect(self.get_success_url())
587

    
588
new_socialisation_duration = NewSocialisationDurationView.as_view()
589

    
590
class UpdateSocialisationDurationView(cbv.UpdateView):
591
    model = SocialisationDuration
592
    form_class = forms.SocialisationDurationForm
593
    template_name = 'dossiers/generic_form.html'
594
    success_url = '../../view#tab=6'
595

    
596
    def get(self, request, *args, **kwargs):
597
        if kwargs.has_key('patientrecord_id'):
598
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
599
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
600

    
601
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
602

    
603
class DeleteSocialisationDurationView(cbv.DeleteView):
604
    model = SocialisationDuration
605
    form_class = forms.SocialisationDurationForm
606
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
607
    success_url = '../../view#tab=6'
608

    
609
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
610

    
611

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

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

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

    
630

    
631
new_mdph_request = \
632
    NewMDPHRequestView.as_view(model=MDPHRequest,
633
        template_name = 'dossiers/generic_form.html',
634
        success_url = '../view#tab=6',
635
        form_class=forms.MDPHRequestForm)
636
update_mdph_request = \
637
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
638
        template_name = 'dossiers/generic_form.html',
639
        success_url = '../../view#tab=6',
640
        form_class=forms.MDPHRequestForm)
641
delete_mdph_request = \
642
    cbv.DeleteView.as_view(model=MDPHRequest,
643
        template_name = 'dossiers/generic_confirm_delete.html',
644
        success_url = '../../view#tab=6')
645

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

    
652
    def form_valid(self, form):
653
        response = form.save()
654
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
655
        patientrecord.mdph_responses.add(response)
656
        return HttpResponseRedirect(self.success_url)
657

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

    
664

    
665
new_mdph_response = \
666
    NewMDPHResponseView.as_view(model=MDPHResponse,
667
        template_name = 'dossiers/generic_form.html',
668
        success_url = '../view#tab=6',
669
        form_class=forms.MDPHResponseForm)
670
update_mdph_response = \
671
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
672
        template_name = 'dossiers/generic_form.html',
673
        success_url = '../../view#tab=6',
674
        form_class=forms.MDPHResponseForm)
675
delete_mdph_response = \
676
    cbv.DeleteView.as_view(model=MDPHResponse,
677
        template_name = 'dossiers/generic_confirm_delete.html',
678
        success_url = '../../view#tab=6')
679

    
680

    
681
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
682

    
683
    def get_initial(self):
684
        initial = super(UpdatePatientStateView, self).get_initial()
685
        initial['date_selected'] = self.object.date_selected.date()
686
        return initial
687

    
688
    def get(self, request, *args, **kwargs):
689
        if kwargs.has_key('patientrecord_id'):
690
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
691
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
692

    
693
class DeletePatientView(cbv.DeleteView):
694

    
695
    def delete(self, request, *args, **kwargs):
696
        self.object = self.get_object()
697
        if self.object == self.object.patient.last_state:
698
            status = self.object.patient.filestate_set.all().order_by('-created')
699
            if len(status) > 1:
700
                self.object.patient.last_state = status[1]
701
                self.object.patient.save()
702
            else:
703
                # TODO return an error here
704
                return HttpResponseRedirect(self.get_success_url())
705
        self.object.delete()
706
        return HttpResponseRedirect(self.get_success_url())
707

    
708

    
709
update_patient_state = \
710
    UpdatePatientStateView.as_view(model=FileState,
711
        template_name = 'dossiers/generic_form.html',
712
        success_url = '../../view#tab=0',
713
        form_class=forms.PatientStateForm)
714
delete_patient_state = \
715
    DeletePatientView.as_view(model=FileState,
716
        template_name = 'dossiers/generic_confirm_delete.html',
717
        success_url = '../../view#tab=0')
718

    
719

    
720
class GenerateRtfFormView(cbv.FormView):
721
    template_name = 'dossiers/generate_rtf_form.html'
722
    form_class = forms.GenerateRtfForm
723
    success_url = './view#tab=0'
724

    
725
    def get_context_data(self, **kwargs):
726
        ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
727
        ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
728
        ctx['service_id'] = self.service.id
729
        if self.request.GET.get('event-id'):
730
            date = self.request.GET.get('date')
731
            date = datetime.strptime(date, '%Y-%m-%d').date()
732
            appointment = Appointment()
733
            event = EventWithAct.objects.get(id=self.request.GET.get('event-id'))
734
            event = event.today_occurrence(date)
735
            appointment.init_from_event(event, self.service)
736
            ctx['event'] = event
737
            ctx['appointment'] = appointment
738
        return ctx
739

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

    
819
        filename = make_doc_from_template(from_path, to_path, variables,
820
            persistent)
821

    
822
        client_dir = patient.get_client_side_directory(self.service.name)
823
        event.convocation_sent = True
824
        event.save()
825
        if not client_dir:
826
            content = File(file(filename))
827
            response = HttpResponse(content,'text/rtf')
828
            response['Content-Length'] = content.size
829
            response['Content-Disposition'] = 'attachment; filename="%s"' \
830
                % dest_filename.encode('utf-8')
831
            return response
832
        else:
833
            class LocalFileHttpResponseRedirect(HttpResponseRedirect):
834
                allowed_schemes = ['file']
835
            client_filepath = os.path.join(client_dir, dest_filename)
836
            return LocalFileHttpResponseRedirect('file://' + client_filepath)
837

    
838
generate_rtf_form = GenerateRtfFormView.as_view()
839

    
840

    
841
class PatientRecordsQuotationsView(cbv.ListView):
842
    model = PatientRecord
843
    template_name = 'dossiers/quotations.html'
844

    
845
    def _get_search_result(self, paginate_patient_records):
846
        patient_records = []
847
        for patient_record in paginate_patient_records:
848
            current_state = patient_record.get_current_state() or patient_record.get_state()
849
            state = current_state.status.name
850
            state_class = current_state.status.type.lower()
851
            patient_records.append(
852
                    {
853
                        'object': patient_record,
854
                        'state': state,
855
                        'state_class': state_class
856
                        }
857
                    )
858
        return patient_records
859

    
860
    def get_queryset(self):
861
        form = forms.QuotationsForm(data=self.request.GET or None)
862
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
863
        without_quotations = self.request.GET.get('without_quotations')
864
        if without_quotations:
865
            qs = qs.filter(mises_1=None).filter(mises_2=None).filter(mises_3=None)
866
        states = self.request.GET.getlist('states')
867
        qs = qs.filter(last_state__status__id__in=states)
868

    
869
        try:
870
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
871
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
872
        except (ValueError, KeyError):
873
            pass
874
        try:
875
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
876
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
877
        except (ValueError, KeyError):
878
            pass
879
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
880
        return qs
881

    
882
    def get_context_data(self, **kwargs):
883
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
884
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
885
                service=self.service)
886
        patient_records = []
887
        page = self.request.GET.get('page')
888
        paginator = Paginator(ctx['object_list'].filter(), 50)
889
        try:
890
            paginate_patient_records = paginator.page(page)
891
        except PageNotAnInteger:
892
            paginate_patient_records = paginator.page(1)
893
        except EmptyPage:
894
            paginate_patient_records = paginator.page(paginator.num_pages)
895

    
896
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
897
        ctx['paginate_patient_records'] = paginate_patient_records
898

    
899
        query = self.request.GET.copy()
900
        if 'page' in query:
901
            del query['page']
902
        ctx['query'] = query.urlencode()
903

    
904
        return ctx
905

    
906
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
907

    
908
class NewProtectionStateView(cbv.CreateView):
909
    model = ProtectionState
910
    template_name = 'dossiers/generic_form.html'
911
    success_url = '../view#tab=1'
912
    form_class = forms.ProtectionStateForm
913

    
914
    def form_valid(self, form):
915
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
916
        form.instance.patient = self.patient
917
        return super(NewProtectionStateView, self).form_valid(form)
918

    
919
new_protection = NewProtectionStateView.as_view()
920

    
921
class UpdateProtectionStateView(cbv.UpdateView):
922
    model = ProtectionState
923
    template_name = 'dossiers/generic_form.html'
924
    success_url = '../../view#tab=1'
925
    form_class = forms.ProtectionStateForm
926

    
927
    def form_valid(self, form):
928
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
929
        form.instance.patient = self.patient
930
        return super(UpdateProtectionStateView, self).form_valid(form)
931

    
932
update_protection = UpdateProtectionStateView.as_view()
933

    
934
class DeleteProtectionStateView(cbv.DeleteView):
935
    model = ProtectionState
936
    template_name = 'dossiers/protection_confirm_delete.html'
937
    success_url = '../../view#tab=1'
938

    
939
delete_protection = DeleteProtectionStateView.as_view()
940

    
941
class PatientRecordsWaitingQueueView(cbv.ListView):
942
    model = PatientRecord
943
    template_name = 'dossiers/waiting_queue.html'
944

    
945
    def _get_search_result(self, paginate_patient_records,
946
            all_patient_records):
947
        patient_records = []
948
        if paginate_patient_records:
949
            position = 1
950
            for patient_record in paginate_patient_records:
951
                while patient_record.id != all_patient_records[position - 1].id:
952
                    position += 1
953
                patient_records.append(
954
                        {
955
                            'object': patient_record,
956
                            'position': position,
957
                            }
958
                        )
959
        return patient_records
960

    
961
    def get_queryset(self):
962
        form = forms.QuotationsForm(data=self.request.GET or None)
963
        qs = super(PatientRecordsWaitingQueueView, self).get_queryset()
964
        first_name = self.request.GET.get('first_name')
965
        last_name = self.request.GET.get('last_name')
966
        paper_id = self.request.GET.get('paper_id')
967
        id = self.request.GET.get('id')
968
        social_security_id = self.request.GET.get('social_security_id')
969
        qs = qs.filter(service=self.service,
970
            last_state__status__type='ACCUEIL')
971
        if last_name:
972
            qs = qs.filter(last_name__istartswith=last_name)
973
        if first_name:
974
            qs = qs.filter(first_name__istartswith=first_name)
975
        if paper_id:
976
            qs = qs.filter(paper_id__startswith=paper_id)
977
        if id:
978
            qs = qs.filter(id__startswith=id)
979
        if social_security_id:
980
            qs = qs.filter(models.Q(
981
                social_security_id__startswith=social_security_id)
982
                | models.Q(
983
                contacts__social_security_id__startswith=social_security_id))
984
        qs = qs.order_by('last_state__date_selected', 'created')
985
        return qs
986

    
987
    def get_context_data(self, **kwargs):
988
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
989
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
990
                service=self.service)
991
        patient_records = []
992
        page = self.request.GET.get('page')
993
        paginator = Paginator(ctx['object_list'].filter(), 50)
994
        try:
995
            paginate_patient_records = paginator.page(page)
996
        except PageNotAnInteger:
997
            paginate_patient_records = paginator.page(1)
998
        except EmptyPage:
999
            paginate_patient_records = paginator.page(paginator.num_pages)
1000

    
1001
        all_patient_records = PatientRecord.objects.filter(
1002
                service=self.service,
1003
                last_state__status__type='ACCUEIL').order_by(
1004
                'last_state__date_selected', 'created')
1005
        ctx['patient_records'] = self._get_search_result(
1006
            paginate_patient_records, all_patient_records)
1007
        ctx['paginate_patient_records'] = paginate_patient_records
1008
        ctx['len_patient_records'] = all_patient_records.count()
1009

    
1010
        query = self.request.GET.copy()
1011
        if 'page' in query:
1012
            del query['page']
1013
        ctx['query'] = query.urlencode()
1014

    
1015
        return ctx
1016

    
1017
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1018

    
1019
class CreateDirectoryView(View, cbv.ServiceViewMixin):
1020
    def post(self, request, *args, **kwargs):
1021
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
1022
        service = Service.objects.get(slug=kwargs['service'])
1023
        patient.get_ondisk_directory(service.name)
1024
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
1025
        return HttpResponseRedirect('view')
1026

    
1027
create_directory = CreateDirectoryView.as_view()
1028

    
1029
class GenerateTransportPrescriptionFormView(cbv.FormView):
1030
    template_name = 'dossiers/generate_transport_prescription_form.html'
1031
    form_class = Form
1032
    success_url = './view#tab=1'
1033

    
1034
    def get_context_data(self, **kwargs):
1035
        ctx = super(GenerateTransportPrescriptionFormView, self).get_context_data(**kwargs)
1036
        ctx['lieu'] = 'Saint-Etienne'
1037
        ctx['date'] = formats.date_format(datetime.today(), "SHORT_DATE_FORMAT")
1038
        ctx['id_etab'] = '''%s SAINT ETIENNE
1039
66/68, RUE MARENGO
1040
42000 SAINT ETIENNE''' % ctx['service'].upper()
1041
        try:
1042
            patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1043
            ctx['object'] = patient
1044
            last_log = TransportPrescriptionLog.objects.filter(patient=patient).latest('created')
1045
            if last_log:
1046
                ctx['choices'] = last_log.get_choices()
1047
                if 'lieu' in ctx['choices'] and ctx['choices']['lieu']:
1048
                    ctx['lieu'] = ctx['choices']['lieu']
1049
                if 'date' in ctx['choices'] and ctx['choices']['date']:
1050
                    ctx['date'] = ctx['choices']['date']
1051
                if 'id_etab' in ctx['choices'] and ctx['choices']['id_etab']:
1052
                    ctx['id_etab'] = ctx['choices']['id_etab']
1053
        except:
1054
            pass
1055
        return ctx
1056

    
1057
    def form_valid(self, form):
1058
        patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1059
        address = PatientAddress.objects.get(id=form.data['address_id'])
1060
        path = render_transport(patient, address, form.data)
1061
        content = File(file(path))
1062
        log = TransportPrescriptionLog(patient=patient)
1063
        log.set_choices(form.data)
1064
        log.save()
1065
        response = HttpResponse(content,'application/pdf')
1066
        response['Content-Length'] = content.size
1067
        dest_filename = "%s--prescription-transport-%s-%s.pdf" \
1068
            % (datetime.now().strftime('%Y-%m-%d--%H:%M:%S'),
1069
            patient.last_name.upper().encode('utf-8'),
1070
            patient.first_name.encode('utf-8'))
1071
        response['Content-Disposition'] = \
1072
            'attachment; filename="%s"' % dest_filename
1073
        return response
1074

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