Project

General

Profile

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

calebasse / calebasse / dossiers / views.py @ a9520794

1 f6203b66 Frédéric Péters
# -*- coding: utf-8 -*-
2
3 23937808 Frédéric Péters
import os
4
5 4e8467aa Benjamin Dauvergne
from datetime import datetime, date
6 54f8d003 Jérôme Schneider
7 23937808 Frédéric Péters
from django.conf import settings
8 17e36a37 Frédéric Péters
from django.db import models
9 23937808 Frédéric Péters
from django.http import HttpResponseRedirect, HttpResponse
10 7bc87b6f Frédéric Péters
from django.views.generic import View
11 3c5df84d Jérôme Schneider
from django.views.generic.edit import DeleteView
12 f6203b66 Frédéric Péters
from django.contrib import messages
13 43a5b181 Frédéric Péters
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
14 364eecbe Mikaël Ates
from django.core.files import File
15 cda02476 Mikaël Ates
from django.forms import Form
16 61c88ce1 Mikaël Ates
from django.utils import formats
17 5497fedd Mikaël Ates
from django.shortcuts import get_object_or_404
18 e7898322 Jérôme Schneider
19 554289d5 Jérôme Schneider
from calebasse import cbv
20 23937808 Frédéric Péters
from calebasse.doc_templates import make_doc_from_template
21 317bcb4c Jérôme Schneider
from calebasse.dossiers import forms
22 aa31cdc8 Jérôme Schneider
from calebasse.dossiers.views_utils import get_next_rdv, get_last_rdv, get_status
23 cda02476 Mikaël Ates
from calebasse.dossiers.transport import render_transport
24 76974b6f Benjamin Dauvergne
from calebasse.agenda.models import Event, EventWithAct
25
from calebasse.actes.models import Act
26 23937808 Frédéric Péters
from calebasse.agenda.appointments import Appointment
27 29168b44 Jérôme Schneider
from calebasse.dossiers.models import (PatientRecord, PatientContact,
28 b8957f1d Jérôme Schneider
        PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
29 07b0577e Mikaël Ates
        CmppHealthCareDiagnostic, SessadHealthCareNotification, HealthCare,
30 5497fedd Mikaël Ates
        TransportPrescriptionLog, ProtectionState)
31 3c5df84d Jérôme Schneider
from calebasse.dossiers.states import STATES_MAPPING, STATES_BTN_MAPPER
32 00c7103f Mikaël Ates
from calebasse.ressources.models import (Service,
33 c8083788 Mikaël Ates
    SocialisationDuration, MDPHRequest, MDPHResponse)
34 523c5aaf Mikaël Ates
from calebasse.facturation.list_acts import list_acts_for_billing_CMPP_per_patient
35 3b4bba4a Serghei MIHAI
from calebasse.facturation.invoice_header import render_to_pdf_file
36 c20d5459 Jérôme Schneider
37 8630b77b Mikaël Ates
from calebasse.decorators import validator_only
38 f3407c83 Jérôme Schneider
39 e24683bd Jérôme Schneider
40 cea6ec34 Jérôme Schneider
class NewPatientRecordView(cbv.FormView, cbv.ServiceViewMixin):
41 317bcb4c Jérôme Schneider
    form_class = forms.NewPatientRecordForm
42 554289d5 Jérôme Schneider
    template_name = 'dossiers/patientrecord_new.html'
43
    success_url = '..'
44 77c6fe82 Frédéric Péters
    patient = None
45 554289d5 Jérôme Schneider
46
    def post(self, request, *args, **kwarg):
47
        self.user = request.user
48
        return super(NewPatientRecordView, self).post(request, *args, **kwarg)
49
50
    def form_valid(self, form):
51 5327927f Mikaël Ates
        self.patient = create_patient(form.data['first_name'], form.data['last_name'], self.service,
52
                self.user, date_selected=datetime.strptime(form.data['date_selected'], "%d/%m/%Y"))
53 554289d5 Jérôme Schneider
        return super(NewPatientRecordView, self).form_valid(form)
54
55 77c6fe82 Frédéric Péters
    def get_success_url(self):
56
        return '%s/view' % self.patient.id
57
58 554289d5 Jérôme Schneider
new_patient_record = NewPatientRecordView.as_view()
59
60 f8606a78 Benjamin Dauvergne
class RecordPatientRecordIdMixing(object):
61
    def dispatch(self, request, *args, **kwargs):
62 5d625358 Jérôme Schneider
        self.patientrecord_id = request.session['patientrecord_id'] = int(kwargs['patientrecord_id'])
63 f8606a78 Benjamin Dauvergne
        return super(RecordPatientRecordIdMixing, self).dispatch(request, *args, **kwargs)
64
65
    def get_form_kwargs(self):
66
        kwargs = super(RecordPatientRecordIdMixing, self).get_form_kwargs()
67
        kwargs['patient'] = PatientRecord.objects.get(id=self.patientrecord_id)
68
        return kwargs
69
70
class NewPatientContactView(RecordPatientRecordIdMixing, cbv.CreateView):
71 317bcb4c Jérôme Schneider
    model = PatientContact
72 f8606a78 Benjamin Dauvergne
    form_class = forms.PatientContactForm
73 dfd4bd12 Jérôme Schneider
    template_name = 'dossiers/patientcontact_new.html'
74
    success_url = '../view#tab=2'
75 317bcb4c Jérôme Schneider
76 6d9e4005 Jérôme Schneider
    def get_initial(self):
77
        initial = super(NewPatientContactView, self).get_initial()
78
        fields = self.form_class.base_fields.keys()
79
        for arg in self.request.GET.keys():
80
            if arg in fields:
81 5a1c0763 Jérôme Schneider
                if arg == 'addresses':
82
                    value = self.request.GET.getlist(arg)
83
                else:
84
                    value = self.request.GET.get(arg)
85 0bbd4c47 Jérôme Schneider
                initial[arg] = value
86
        if initial:
87 5a1c0763 Jérôme Schneider
            if not initial.has_key('addresses'):
88
                initial['addresses'] = []
89 0bbd4c47 Jérôme Schneider
            patient = PatientRecord.objects.get(id=self.patientrecord_id)
90
            addresses = patient.addresses.order_by('-id')
91
            if addresses:
92
                initial['addresses'].append(addresses[0].pk)
93 6d9e4005 Jérôme Schneider
        return initial
94
95 1a9b2fe9 Jérôme Schneider
new_patient_contact = NewPatientContactView.as_view()
96 317bcb4c Jérôme Schneider
97 95593005 Serghei MIHAI
class UpdatePatientContactView(RecordPatientRecordIdMixing, cbv.NotificationDisplayView, cbv.UpdateView):
98 0ad2d82a Jérôme Schneider
    model = PatientContact
99 f8606a78 Benjamin Dauvergne
    form_class = forms.PatientContactForm
100 0ad2d82a Jérôme Schneider
    template_name = 'dossiers/patientcontact_new.html'
101
    success_url = '../../view#tab=2'
102
103
update_patient_contact = UpdatePatientContactView.as_view()
104
105 dfd4bd12 Jérôme Schneider
class DeletePatientContactView(cbv.DeleteView):
106
    model = PatientContact
107
    form_class = forms.PatientContactForm
108
    template_name = 'dossiers/patientcontact_confirm_delete.html'
109
    success_url = '../../view#tab=2'
110
111 40de3ad2 Frédéric Péters
    def post(self, request, *args, **kwargs):
112
        try:
113
            patient = PatientRecord.objects.get(id=kwargs.get('pk'))
114
        except PatientRecord.DoesNotExist:
115
            return super(DeletePatientContactView, self).post(request, *args, **kwargs)
116
        # the contact is also a patient record; it shouldn't be deleted; just
117
        # altered to remove an address
118
        patient.addresses.remove(self.request.GET['address'])
119
        return HttpResponseRedirect(self.get_success_url())
120
121 dfd4bd12 Jérôme Schneider
delete_patient_contact = DeletePatientContactView.as_view()
122
123 1a9b2fe9 Jérôme Schneider
class NewPatientAddressView(cbv.CreateView):
124 29168b44 Jérôme Schneider
    model = PatientAddress
125
    form_class = forms.PatientAddressForm
126 dfd4bd12 Jérôme Schneider
    template_name = 'dossiers/patientaddress_new.html'
127
    success_url = '../view#tab=2'
128 29168b44 Jérôme Schneider
129 1a9b2fe9 Jérôme Schneider
    def get_success_url(self):
130
        return self.success_url
131
132
    def form_valid(self, form):
133
        patientaddress = form.save()
134
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
135
        patientrecord.addresses.add(patientaddress)
136 fca68db0 Jérôme Schneider
        messages.add_message(self.request, messages.INFO, u'Nouvelle adresse enregistrée avec succès.')
137 1a9b2fe9 Jérôme Schneider
        return HttpResponseRedirect(self.get_success_url())
138 29168b44 Jérôme Schneider
139 1a9b2fe9 Jérôme Schneider
new_patient_address = NewPatientAddressView.as_view()
140 29168b44 Jérôme Schneider
141 95593005 Serghei MIHAI
class UpdatePatientAddressView(cbv.NotificationDisplayView, cbv.UpdateView):
142 4e9e8ae5 Jérôme Schneider
    model = PatientAddress
143
    form_class = forms.PatientAddressForm
144
    template_name = 'dossiers/patientaddress_new.html'
145
    success_url = '../../view#tab=2'
146
147
update_patient_address = UpdatePatientAddressView.as_view()
148
149 dfd4bd12 Jérôme Schneider
class DeletePatientAddressView(cbv.DeleteView):
150
    model = PatientAddress
151
    form_class = forms.PatientAddressForm
152
    template_name = 'dossiers/patientaddress_confirm_delete.html'
153
    success_url = '../../view#tab=2'
154
155
delete_patient_address = DeletePatientAddressView.as_view()
156
157 b464657d Mikaël Ates
158 1d205fa9 Mikaël Ates
class NewHealthCareView(cbv.CreateView):
159 b464657d Mikaël Ates
160 2da0976b Jérôme Schneider
    def get_initial(self):
161 b8957f1d Jérôme Schneider
        initial = super(NewHealthCareView, self).get_initial()
162 2da0976b Jérôme Schneider
        initial['author'] = self.request.user.id
163
        initial['patient'] = self.kwargs['patientrecord_id']
164
        return initial
165 b464657d Mikaël Ates
166 1d205fa9 Mikaël Ates
new_healthcare_treatment = \
167
    NewHealthCareView.as_view(model=CmppHealthCareTreatment,
168
        template_name = 'dossiers/generic_form.html',
169
        success_url = '../view#tab=3',
170
        form_class=forms.CmppHealthCareTreatmentForm)
171
new_healthcare_diagnostic = \
172
    NewHealthCareView.as_view(model=CmppHealthCareDiagnostic,
173
        template_name = 'dossiers/generic_form.html',
174
        success_url = '../view#tab=3',
175
        form_class=forms.CmppHealthCareDiagnosticForm)
176
new_healthcare_notification = \
177
    NewHealthCareView.as_view(model=SessadHealthCareNotification,
178
        template_name = 'dossiers/generic_form.html',
179
        success_url = '../view#tab=3',
180
        form_class=forms.SessadHealthCareNotificationForm)
181
update_healthcare_treatment = \
182
    cbv.UpdateView.as_view(model=CmppHealthCareTreatment,
183
        template_name = 'dossiers/generic_form.html',
184
        success_url = '../../view#tab=3',
185 b8957f1d Jérôme Schneider
        form_class=forms.CmppHealthCareTreatmentForm)
186 1d205fa9 Mikaël Ates
update_healthcare_diagnostic = \
187
    cbv.UpdateView.as_view(model=CmppHealthCareDiagnostic,
188
        template_name = 'dossiers/generic_form.html',
189
        success_url = '../../view#tab=3',
190 b8957f1d Jérôme Schneider
        form_class=forms.CmppHealthCareDiagnosticForm)
191 1d205fa9 Mikaël Ates
update_healthcare_notification = \
192
    cbv.UpdateView.as_view(model=SessadHealthCareNotification,
193
        template_name = 'dossiers/generic_form.html',
194
        success_url = '../../view#tab=3',
195 b8957f1d Jérôme Schneider
        form_class=forms.SessadHealthCareNotificationForm)
196 1d205fa9 Mikaël Ates
delete_healthcare_treatment = \
197
    cbv.DeleteView.as_view(model=CmppHealthCareTreatment,
198
        template_name = 'dossiers/generic_confirm_delete.html',
199
        success_url = '../../view#tab=3')
200
delete_healthcare_diagnostic = \
201
    cbv.DeleteView.as_view(model=CmppHealthCareDiagnostic,
202
        template_name = 'dossiers/generic_confirm_delete.html',
203
        success_url = '../../view#tab=3')
204
delete_healthcare_notification = \
205
    cbv.DeleteView.as_view(model=SessadHealthCareNotification,
206
        template_name = 'dossiers/generic_confirm_delete.html',
207
        success_url = '../../view#tab=3')
208 b464657d Mikaël Ates
209
210 554289d5 Jérôme Schneider
class StateFormView(cbv.FormView):
211 f78e473c Jérôme Schneider
    template_name = 'dossiers/state.html'
212 317bcb4c Jérôme Schneider
    form_class = forms.StateForm
213 dfd4bd12 Jérôme Schneider
    success_url = './view#tab=0'
214 f78e473c Jérôme Schneider
215 5f476468 Jérôme Schneider
216 54f8d003 Jérôme Schneider
    def post(self, request, *args, **kwarg):
217
        self.user = request.user
218
        return super(StateFormView, self).post(request, *args, **kwarg)
219
220 f78e473c Jérôme Schneider
    def form_valid(self, form):
221 54f8d003 Jérôme Schneider
        service = Service.objects.get(id=form.data['service_id'])
222
        status = Status.objects.filter(services=service).filter(type=form.data['state_type'])
223
        patient = PatientRecord.objects.get(id=form.data['patient_id'])
224
        date_selected = datetime.strptime(form.data['date'], "%d/%m/%Y")
225
        patient.set_state(status[0], self.user, date_selected, form.data['comment'])
226 f78e473c Jérôme Schneider
        return super(StateFormView, self).form_valid(form)
227
228
state_form = StateFormView.as_view()
229
230 aa31cdc8 Jérôme Schneider
class PatientRecordView(cbv.UpdateView):
231 f3407c83 Jérôme Schneider
    model = PatientRecord
232
    template_name = 'dossiers/patientrecord_update.html'
233 380f5426 Jérôme Schneider
234 f3407c83 Jérôme Schneider
    def get_context_data(self, **kwargs):
235
        ctx = super(PatientRecordView, self).get_context_data(**kwargs)
236 f3c2d53a Mikaël Ates
        ctx['object'].create_diag_healthcare(self.request.user)
237
        ctx['object'].automated_switch_state(self.request.user)
238 3665f853 Mikaël Ates
        current_state = ctx['object'].get_current_state()
239 aa31cdc8 Jérôme Schneider
        if not current_state:
240
            current_state = ctx['object'].get_state()
241
            ctx['future_state'] = True
242 3665f853 Mikaël Ates
        if STATES_MAPPING.has_key(current_state.status.type):
243
            state = STATES_MAPPING[current_state.status.type]
244
        else:
245
            state = current_state.status.name
246
        ctx['current_state'] = current_state
247 54f8d003 Jérôme Schneider
        ctx['service_id'] = self.service.id
248 7f360e71 Jérôme Schneider
        ctx['states'] = FileState.objects.filter(patient=self.object) \
249
                .filter(status__services=self.service) \
250
                .order_by('-date_selected')
251 aa31cdc8 Jérôme Schneider
        return ctx
252
253
patient_record = PatientRecordView.as_view()
254
255 3b4bba4a Serghei MIHAI
class PatientRecordPrint(cbv.DetailView):
256
    model = PatientRecord
257
    content_type = 'application/pdf'
258
    template_name = 'dossiers/patientrecord_print.html'
259
260
    def get_context_data(self, *args, **kwargs):
261
        context = super(PatientRecordPrint, self).get_context_data(*args, **kwargs)
262
        for view in (PatientRecordGeneralView, PatientRecordAdmView,
263
                     PatientRecordAddrView, PatientRecordNotifsView, PatientRecordOldActs,
264
                     PatientRecordNextAppointmentsView, PatientRecordSocialisationView):
265
            view_instance = view(request=self.request, object=self.object,
266
                                 service=self.service)
267
            context.update(view_instance.get_context_data(object=self.object))
268
        return context
269
270
    def get(self, request, *args, **kwargs):
271
        self.object = self.get_object()
272
        path = render_to_pdf_file([self.template_name],
273
                                  self.get_context_data(object = self.object))
274
        content = File(file(path))
275
        response = HttpResponse(content, self.content_type)
276
        response['Content-Length'] = content.size
277
        output = 'dossier_%s.pdf' % self.object.id
278
        response['Content-Disposition'] = \
279
            'attachment; filename="%s"' % output
280
        return response
281
282
patient_record_print = PatientRecordPrint.as_view()
283
284 aa31cdc8 Jérôme Schneider
class PatientRecordGeneralView(cbv.UpdateView):
285
    model = PatientRecord
286
    form_class = forms.GeneralForm
287
    template_name = 'dossiers/patientrecord_tab1_general.html'
288
    success_url = './view'
289 a72d40ba Mikaël Ates
290 aa31cdc8 Jérôme Schneider
    def get_context_data(self, **kwargs):
291
        ctx = super(PatientRecordGeneralView, self).get_context_data(**kwargs)
292
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
293
        ctx['initial_state'] = ctx['object'].get_initial_state()
294
        ctx['last_rdv'] = get_last_rdv(ctx['object'])
295
        ctx['next_rdv'] = get_next_rdv(ctx['object'])
296
        current_state = ctx['object'].get_current_state()
297 c14fdef9 Jérôme Schneider
        if current_state.status and STATES_MAPPING.has_key(current_state.status.type):
298 aa31cdc8 Jérôme Schneider
            state = STATES_MAPPING[current_state.status.type]
299 c0ae5eb9 Jérôme Schneider
        elif current_state.status:
300
            state = current_state.status.name
301 aa31cdc8 Jérôme Schneider
        else:
302 c0ae5eb9 Jérôme Schneider
            state = "Aucun"
303 aa31cdc8 Jérôme Schneider
        ctx['current_state'] = current_state
304
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
305 a72d40ba Mikaël Ates
        ctx['missing_policy'] = False
306
        if not self.object.policyholder or \
307
                not self.object.policyholder.health_center or \
308
                not self.object.policyholder.social_security_id:
309
            ctx['missing_policy'] = True
310 67992ef6 Mikaël Ates
        ctx['missing_birthdate'] = False
311
        if not self.object.birthdate:
312
            ctx['missing_birthdate'] = True
313 aa31cdc8 Jérôme Schneider
        return ctx
314 a72d40ba Mikaël Ates
315 aa31cdc8 Jérôme Schneider
tab1_general = PatientRecordGeneralView.as_view()
316
317 1a3d8912 Jérôme Schneider
class PatientRecordAdmView(cbv.UpdateView):
318 aa31cdc8 Jérôme Schneider
    model = PatientRecord
319 1a3d8912 Jérôme Schneider
    form_class = forms.AdministrativeForm
320 aa31cdc8 Jérôme Schneider
    template_name = 'dossiers/patientrecord_tab2_fiche_adm.html'
321
    success_url = './view#tab=1'
322
323
    def get_context_data(self, **kwargs):
324
        ctx = super(PatientRecordAdmView, self).get_context_data(**kwargs)
325
        try:
326
            ctx['last_prescription'] = TransportPrescriptionLog.objects.filter(patient=ctx['object']).latest('created')
327
        except:
328
            pass
329
        return ctx
330
331
tab2_fiche_adm = PatientRecordAdmView.as_view()
332
333 95593005 Serghei MIHAI
class PatientRecordAddrView(cbv.ServiceViewMixin, cbv.NotificationDisplayView, cbv.MultiUpdateView):
334 aa31cdc8 Jérôme Schneider
    model = PatientRecord
335
    forms_classes = {
336
            'contact': forms.PatientContactForm,
337 a869df8f Mikaël Ates
            'policyholder': forms.PolicyHolderForm,
338
            'comment' : forms.AddrCommentForm,
339 aa31cdc8 Jérôme Schneider
            }
340
    template_name = 'dossiers/patientrecord_tab3_adresses.html'
341
    success_url = './view#tab=2'
342
343
344
    def get_context_data(self, **kwargs):
345
        ctx = super(PatientRecordAddrView, self).get_context_data(**kwargs)
346
        ctx['nb_place_of_lifes'] = ctx['object'].addresses.filter(place_of_life=True).count()
347
        ctx['addresses'] = ctx['object'].addresses.order_by('-place_of_life', 'id')
348
        return ctx
349
350
tab3_addresses = PatientRecordAddrView.as_view()
351
352
class PatientRecordNotifsView(cbv.DetailView):
353
    model = PatientRecord
354
    template_name = 'dossiers/patientrecord_tab4_notifs.html'
355
356
    def get_context_data(self, **kwargs):
357
        ctx = super(PatientRecordNotifsView, self).get_context_data(**kwargs)
358
        ctx['status'], ctx['hc_status'] = get_status(ctx, self.request.user)
359
        if ctx['object'].service.slug == "cmpp":
360 3b1f5878 Mikaël Ates
            (acts_not_locked, days_not_locked, acts_not_valide,
361
            acts_not_billable, acts_pause, acts_per_hc, acts_losts) = \
362 523c5aaf Mikaël Ates
                list_acts_for_billing_CMPP_per_patient(self.object,
363 3b1f5878 Mikaël Ates
                    datetime.today(), self.service)
364
            ctx['acts_losts'] = acts_losts
365
            ctx['acts_pause'] = acts_pause
366
            hcs_used = acts_per_hc.keys()
367 d5ca00ed Mikaël Ates
            hcs = None
368 3b1f5878 Mikaël Ates
            if not hcs_used:
369 d5ca00ed Mikaël Ates
                hcs = [(hc, None) for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date')]
370 3b1f5878 Mikaël Ates
            else:
371 d5ca00ed Mikaël Ates
                hcs = []
372 3b1f5878 Mikaël Ates
                for hc in HealthCare.objects.filter(patient=self.object).order_by('-start_date'):
373
                    acts = None
374
                    if hasattr(hc, 'cmpphealthcarediagnostic') and hc.cmpphealthcarediagnostic in hcs_used:
375
                        acts = acts_per_hc[hc.cmpphealthcarediagnostic]
376
                    elif hasattr(hc, 'cmpphealthcaretreatment') and hc.cmpphealthcaretreatment in hcs_used:
377
                        acts = acts_per_hc[hc.cmpphealthcaretreatment]
378 d5ca00ed Mikaël Ates
                    hcs.append((hc, acts))
379
            ctx['hcs'] = []
380
            for hc, acts in hcs:
381
                ctx['hcs'].append((hc, acts, hc.act_set.order_by('date', 'time')))
382 aa31cdc8 Jérôme Schneider
        elif ctx['object'].service.slug == "sessad-ted" or ctx['object'].service.slug == "sessad-dys":
383 3b1f5878 Mikaël Ates
            ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
384 aa31cdc8 Jérôme Schneider
        return ctx
385 eb3a7e71 Jérôme Schneider
386 aa31cdc8 Jérôme Schneider
tab4_notifs = PatientRecordNotifsView.as_view()
387
388
class PatientRecordOldActs(cbv.DetailView):
389
    model = PatientRecord
390
    template_name = 'dossiers/patientrecord_tab5_actes_passes.html'
391
392
    def get_context_data(self, **kwargs):
393
        ctx = super(PatientRecordOldActs, self).get_context_data(**kwargs)
394
        ctx['last_rdvs'] = []
395
        for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
396
            state = act.get_state()
397
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
398
                state = None
399
            missing_workers = []
400
            try:
401
                missing_workers = [participant.worker for participant in act.event.get_missing_participants()]
402
            except:
403
                pass
404
            ctx['last_rdvs'].append((act, state, missing_workers))
405
        history = []
406
        i = 0
407
        for state in ctx['object'].filestate_set.order_by('-date_selected'):
408
            acts = []
409
            try:
410
                while ctx['last_rdvs'][i][0].date >= state.date_selected.date():
411
                    acts.append(ctx['last_rdvs'][i])
412
                    i += 1
413
            except:
414
                pass
415
            history.append((state, acts))
416
        if i < len(ctx['last_rdvs']) - 1:
417
            history.append((None, ctx['last_rdvs'][i:]))
418
        ctx['history'] = history
419 f3407c83 Jérôme Schneider
        return ctx
420
421 aa31cdc8 Jérôme Schneider
tab5_old_acts = PatientRecordOldActs.as_view()
422 f6203b66 Frédéric Péters
423 aa31cdc8 Jérôme Schneider
class PatientRecordNextAppointmentsView(cbv.DetailView):
424
    model = PatientRecord
425
    template_name = 'dossiers/patientrecord_tab6_next_rdv.html'
426 f6203b66 Frédéric Péters
427 aa31cdc8 Jérôme Schneider
    def get_context_data(self, **kwargs):
428
        ctx = super(PatientRecordNextAppointmentsView, self).get_context_data(**kwargs)
429
        ctx['next_rdvs'] = []
430
        Q = models.Q
431
        today = date.today()
432 3cdae7c3 Serghei MIHAI
        qs = EventWithAct.objects.filter(patient=ctx['object']) \
433 aa31cdc8 Jérôme Schneider
                .filter(exception_to__isnull=True, canceled=False) \
434
                .filter(Q(start_datetime__gte=today) \
435
                |  Q(exceptions__isnull=False) \
436
                | ( Q(recurrence_periodicity__isnull=False) \
437
                & (Q(recurrence_end_date__gte=today) \
438
                | Q(recurrence_end_date__isnull=True) \
439
                ))) \
440
                .distinct() \
441
                .select_related() \
442
                .prefetch_related('participants', 'exceptions__eventwithact',
443
                        'act_set__actvalidationstate_set')
444
        occurrences = []
445
        for event in qs:
446
            occurrences.extend(filter(lambda e: e.start_datetime.date() >= today,
447
                event.all_occurences(limit=180)))
448
        occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
449
        for event in occurrences:
450
            state = None
451
            if event.act:
452
                state = event.act.get_state()
453
            if state and not state.previous_state and state.state_name == 'NON_VALIDE':
454
                state = None
455 bba85766 Serghei MIHAI
            ctx['next_rdvs'].append((event, state, event.get_missing_participants(), event.get_inactive_participants()))
456 aa31cdc8 Jérôme Schneider
        return ctx
457
458
tab6_next_rdv = PatientRecordNextAppointmentsView.as_view()
459
460
class PatientRecordSocialisationView(cbv.DetailView):
461
    model = PatientRecord
462
    template_name = 'dossiers/patientrecord_tab7_socialisation.html'
463
464
tab7_socialisation = PatientRecordSocialisationView.as_view()
465
466 63975fa8 Jérôme Schneider
class PatientRecordMedicalView(cbv.UpdateView):
467 aa31cdc8 Jérôme Schneider
    model = PatientRecord
468 63975fa8 Jérôme Schneider
    form_class = forms.PhysiologyForm
469 aa31cdc8 Jérôme Schneider
    template_name = 'dossiers/patientrecord_tab8_medical.html'
470
    success_url = './view#tab=7'
471
472
tab8_medical = PatientRecordMedicalView.as_view()
473 f3407c83 Jérôme Schneider
474 554289d5 Jérôme Schneider
class PatientRecordsHomepageView(cbv.ListView):
475 562586fb Jérôme Schneider
    model = PatientRecord
476 c20d5459 Jérôme Schneider
    template_name = 'dossiers/index.html'
477 562586fb Jérôme Schneider
478 e16b3817 Jérôme Schneider
479
    def _get_search_result(self, paginate_patient_records):
480
        patient_records = []
481
        for patient_record in paginate_patient_records:
482
            next_rdv = get_next_rdv(patient_record)
483
            last_rdv = get_last_rdv(patient_record)
484
            current_status = patient_record.last_state.status
485
            state = current_status.name
486
            state_class = current_status.type.lower()
487
            patient_records.append(
488
                    {
489
                        'object': patient_record,
490
                        'next_rdv': next_rdv,
491
                        'last_rdv': last_rdv,
492
                        'state': state,
493
                        'state_class': state_class
494
                        }
495
                    )
496
        return patient_records
497
498 562586fb Jérôme Schneider
    def get_queryset(self):
499
        first_name = self.request.GET.get('first_name')
500
        last_name = self.request.GET.get('last_name')
501
        paper_id = self.request.GET.get('paper_id')
502 301ff5c0 Frédéric Péters
        id = self.request.GET.get('id')
503 562586fb Jérôme Schneider
        social_security_id = self.request.GET.get('social_security_id')
504 a75ff93a Mikaël Ates
        if not (first_name or last_name or paper_id or id or social_security_id):
505
            return None
506
        if (first_name and len(first_name) < 2) or (last_name and len(last_name) < 2):
507
            return None
508
        qs = super(PatientRecordsHomepageView, self).get_queryset()
509
        states = self.request.GET.getlist('states')
510 562586fb Jérôme Schneider
        if last_name:
511 86aba266 Jérôme Schneider
            qs = qs.filter(last_name__istartswith=last_name)
512 562586fb Jérôme Schneider
        if first_name:
513 86aba266 Jérôme Schneider
            qs = qs.filter(first_name__istartswith=first_name)
514 562586fb Jérôme Schneider
        if paper_id:
515 a75ff93a Mikaël Ates
            qs = qs.filter(paper_id__startswith=paper_id)
516 301ff5c0 Frédéric Péters
        if id:
517 a75ff93a Mikaël Ates
            qs = qs.filter(id__startswith=id)
518 562586fb Jérôme Schneider
        if social_security_id:
519 a75ff93a Mikaël Ates
            qs = qs.filter(models.Q(social_security_id__startswith=social_security_id) | \
520
                models.Q(contacts__social_security_id__startswith=social_security_id))
521 7328a577 Jérôme Schneider
        if states:
522 e30c9bdb Jérôme Schneider
            qs = qs.filter(last_state__status__id__in=states)
523 348bd1f9 Jérôme Schneider
        else:
524
            qs = qs.filter(last_state__status__type__in="")
525 e30c9bdb Jérôme Schneider
        qs = qs.filter(service=self.service).order_by('last_name').\
526
                prefetch_related('last_state',
527
                        'patientcontact', 'last_state__status')
528 562586fb Jérôme Schneider
        return qs
529
530
    def get_context_data(self, **kwargs):
531 f3407c83 Jérôme Schneider
        ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
532 e30c9bdb Jérôme Schneider
        ctx['search_form'] = forms.SearchForm(service=self.service, data=self.request.GET or None)
533
        ctx['stats'] = [["Dossiers", 0]]
534
        for status in Status.objects.filter(services=self.service):
535
            ctx['stats'].append([status.name, 0])
536 ca4afcae Jérôme Schneider
537 43a5b181 Frédéric Péters
        page = self.request.GET.get('page')
538 e16b3817 Jérôme Schneider
        if ctx['object_list']:
539
            patient_records = ctx['object_list'].filter()
540
        else:
541
            patient_records = []
542
543
        # TODO: use a sql query to do this
544
        for patient_record in patient_records:
545
            ctx['stats'][0][1] += 1
546
            for elem in ctx['stats']:
547
                if elem[0] == patient_record.last_state.status.name:
548
                    elem[1] += 1
549 36e10f58 Frédéric Péters
        paginator = Paginator(patient_records, 50)
550 43a5b181 Frédéric Péters
        try:
551 e16b3817 Jérôme Schneider
            paginate_patient_records = paginator.page(page)
552 43a5b181 Frédéric Péters
        except PageNotAnInteger:
553 e16b3817 Jérôme Schneider
            paginate_patient_records = paginator.page(1)
554 43a5b181 Frédéric Péters
        except EmptyPage:
555 e16b3817 Jérôme Schneider
            paginate_patient_records = paginator.page(paginator.num_pages)
556 43a5b181 Frédéric Péters
557
        query = self.request.GET.copy()
558
        if 'page' in query:
559
            del query['page']
560
        ctx['query'] = query.urlencode()
561
562 e16b3817 Jérôme Schneider
        ctx['paginate_patient_records'] = paginate_patient_records
563
        ctx['patient_records'] = self._get_search_result(paginate_patient_records)
564 562586fb Jérôme Schneider
        return ctx
565
566 f78e473c Jérôme Schneider
patientrecord_home = PatientRecordsHomepageView.as_view()
567 e7898322 Jérôme Schneider
568
class PatientRecordDeleteView(DeleteView):
569
    model = PatientRecord
570
    success_url = ".."
571
    template_name = 'dossiers/patientrecord_confirm_delete.html'
572
573 8630b77b Mikaël Ates
patientrecord_delete = validator_only(PatientRecordDeleteView.as_view())
574 e7898322 Jérôme Schneider
575 29168b44 Jérôme Schneider
576 729480ef Jérôme Schneider
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
577
    model = PatientRecord
578
    form_class = forms.PaperIDForm
579
    template_name = 'dossiers/generic_form.html'
580 33c3c6d1 Jérôme Schneider
    success_url = '../view#tab=0'
581 729480ef Jérôme Schneider
582
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
583 00c7103f Mikaël Ates
584
585
class NewSocialisationDurationView(cbv.CreateView):
586
    model = SocialisationDuration
587
    form_class = forms.SocialisationDurationForm
588
    template_name = 'dossiers/generic_form.html'
589
    success_url = '../view#tab=6'
590
591
    def get_success_url(self):
592
        return self.success_url
593
594
    def get(self, request, *args, **kwargs):
595
        if kwargs.has_key('patientrecord_id'):
596
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
597
        return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
598
599
    def form_valid(self, form):
600
        duration = form.save()
601
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
602
        patientrecord.socialisation_durations.add(duration)
603
        return HttpResponseRedirect(self.get_success_url())
604
605
new_socialisation_duration = NewSocialisationDurationView.as_view()
606
607
class UpdateSocialisationDurationView(cbv.UpdateView):
608
    model = SocialisationDuration
609
    form_class = forms.SocialisationDurationForm
610
    template_name = 'dossiers/generic_form.html'
611
    success_url = '../../view#tab=6'
612
613
    def get(self, request, *args, **kwargs):
614
        if kwargs.has_key('patientrecord_id'):
615
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
616
        return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
617
618
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
619
620
class DeleteSocialisationDurationView(cbv.DeleteView):
621
    model = SocialisationDuration
622
    form_class = forms.SocialisationDurationForm
623
    template_name = 'dossiers/socialisationduration_confirm_delete.html'
624
    success_url = '../../view#tab=6'
625
626
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
627 c8083788 Mikaël Ates
628
629
class NewMDPHRequestView(cbv.CreateView):
630
    def get(self, request, *args, **kwargs):
631
        if kwargs.has_key('patientrecord_id'):
632
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
633
        return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
634
635
    def form_valid(self, form):
636
        request = form.save()
637
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
638
        patientrecord.mdph_requests.add(request)
639
        return HttpResponseRedirect(self.success_url)
640
641
class UpdateMDPHRequestView(cbv.UpdateView):
642
    def get(self, request, *args, **kwargs):
643
        if kwargs.has_key('patientrecord_id'):
644
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
645
        return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
646
647
648
new_mdph_request = \
649
    NewMDPHRequestView.as_view(model=MDPHRequest,
650
        template_name = 'dossiers/generic_form.html',
651
        success_url = '../view#tab=6',
652
        form_class=forms.MDPHRequestForm)
653
update_mdph_request = \
654
    UpdateMDPHRequestView.as_view(model=MDPHRequest,
655
        template_name = 'dossiers/generic_form.html',
656
        success_url = '../../view#tab=6',
657
        form_class=forms.MDPHRequestForm)
658
delete_mdph_request = \
659
    cbv.DeleteView.as_view(model=MDPHRequest,
660
        template_name = 'dossiers/generic_confirm_delete.html',
661
        success_url = '../../view#tab=6')
662
663
class NewMDPHResponseView(cbv.CreateView):
664
    def get(self, request, *args, **kwargs):
665
        if kwargs.has_key('patientrecord_id'):
666
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
667
        return super(NewMDPHResponseView, self).get(request, *args, **kwargs)
668
669
    def form_valid(self, form):
670
        response = form.save()
671
        patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
672
        patientrecord.mdph_responses.add(response)
673
        return HttpResponseRedirect(self.success_url)
674
675
class UpdateMDPHResponseView(cbv.UpdateView):
676
    def get(self, request, *args, **kwargs):
677
        if kwargs.has_key('patientrecord_id'):
678
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
679
        return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
680
681
682
new_mdph_response = \
683
    NewMDPHResponseView.as_view(model=MDPHResponse,
684
        template_name = 'dossiers/generic_form.html',
685
        success_url = '../view#tab=6',
686
        form_class=forms.MDPHResponseForm)
687
update_mdph_response = \
688
    UpdateMDPHResponseView.as_view(model=MDPHResponse,
689
        template_name = 'dossiers/generic_form.html',
690
        success_url = '../../view#tab=6',
691
        form_class=forms.MDPHResponseForm)
692
delete_mdph_response = \
693
    cbv.DeleteView.as_view(model=MDPHResponse,
694
        template_name = 'dossiers/generic_confirm_delete.html',
695
        success_url = '../../view#tab=6')
696 4a0ff5ea Frédéric Péters
697
698 24c750bb Jérôme Schneider
class UpdatePatientStateView(cbv.ServiceFormMixin, cbv.UpdateView):
699 5f476468 Jérôme Schneider
700
    def get_initial(self):
701
        initial = super(UpdatePatientStateView, self).get_initial()
702
        initial['date_selected'] = self.object.date_selected.date()
703
        return initial
704
705 4a0ff5ea Frédéric Péters
    def get(self, request, *args, **kwargs):
706
        if kwargs.has_key('patientrecord_id'):
707
            request.session['patientrecord_id'] = kwargs['patientrecord_id']
708
        return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
709
710 0cebd645 Jérôme Schneider
class DeletePatientView(cbv.DeleteView):
711
712
    def delete(self, request, *args, **kwargs):
713
        self.object = self.get_object()
714 1f5cae7f Jérôme Schneider
        if self.object == self.object.patient.last_state:
715
            status = self.object.patient.filestate_set.all().order_by('-created')
716
            if len(status) > 1:
717
                self.object.patient.last_state = status[1]
718 32061a0e Jérôme Schneider
                self.object.patient.save()
719 1f5cae7f Jérôme Schneider
            else:
720
                # TODO return an error here
721
                return HttpResponseRedirect(self.get_success_url())
722
        self.object.delete()
723 0cebd645 Jérôme Schneider
        return HttpResponseRedirect(self.get_success_url())
724
725
726 4a0ff5ea Frédéric Péters
update_patient_state = \
727
    UpdatePatientStateView.as_view(model=FileState,
728
        template_name = 'dossiers/generic_form.html',
729
        success_url = '../../view#tab=0',
730
        form_class=forms.PatientStateForm)
731
delete_patient_state = \
732 0cebd645 Jérôme Schneider
    DeletePatientView.as_view(model=FileState,
733 4a0ff5ea Frédéric Péters
        template_name = 'dossiers/generic_confirm_delete.html',
734
        success_url = '../../view#tab=0')
735 23937808 Frédéric Péters
736
737
class GenerateRtfFormView(cbv.FormView):
738
    template_name = 'dossiers/generate_rtf_form.html'
739
    form_class = forms.GenerateRtfForm
740
    success_url = './view#tab=0'
741
742
    def get_context_data(self, **kwargs):
743
        ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
744
        ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
745
        ctx['service_id'] = self.service.id
746
        if self.request.GET.get('event-id'):
747 76974b6f Benjamin Dauvergne
            date = self.request.GET.get('date')
748
            date = datetime.strptime(date, '%Y-%m-%d').date()
749 23937808 Frédéric Péters
            appointment = Appointment()
750 c2246b82 Benjamin Dauvergne
            event = EventWithAct.objects.get(id=self.request.GET.get('event-id'))
751 5c2d0ea2 Benjamin Dauvergne
            event = event.today_occurrence(date)
752 76974b6f Benjamin Dauvergne
            appointment.init_from_event(event, self.service)
753 577ecc05 Jérôme Schneider
            ctx['event'] = event
754 23937808 Frédéric Péters
            ctx['appointment'] = appointment
755
        return ctx
756
757 b4310641 Mikaël Ates
    def form_valid(self, form, **kwargs):
758
        ctx = self.get_context_data(**kwargs)
759
        patient = ctx['object']
760
        appointment = ctx['appointment']
761 577ecc05 Jérôme Schneider
        event = ctx['event']
762 23937808 Frédéric Péters
        template_filename = form.cleaned_data.get('template_filename')
763 7296f9f1 Mikaël Ates
        dest_filename = datetime.now().strftime('%Y-%m-%d--%H:%M:%S') + '--' + template_filename
764 23937808 Frédéric Péters
        from_path = os.path.join(settings.RTF_TEMPLATES_DIRECTORY, template_filename)
765 364eecbe Mikaël Ates
        to_path = ''
766
        persistent = True
767
        if settings.USE_PATIENT_FILE_RTF_REPOSITORY_DIRECTORY \
768
                or settings.RTF_REPOSITORY_DIRECTORY:
769
            if settings.USE_PATIENT_FILE_RTF_REPOSITORY_DIRECTORY:
770
                to_path = patient.get_ondisk_directory(self.service.name)
771
            if settings.RTF_REPOSITORY_DIRECTORY:
772
                to_path = os.path.join(to_path,
773
                    settings.RTF_REPOSITORY_DIRECTORY)
774
            to_path = os.path.join(to_path, dest_filename)
775
        else:
776
            # else : use temporary files
777
            persistent = False
778
            to_path = dest_filename
779 b4310641 Mikaël Ates
        variables = {'AD11': '', 'AD12': '', 'AD13': '', 'AD14': '',
780
            'AD15': '', 'AD18': '',
781 61c88ce1 Mikaël Ates
            'JOU1': formats.date_format(datetime.today(), "DATE_FORMAT"),
782 b4310641 Mikaël Ates
            'VIL1': u'Saint-Étienne',
783
            'RDV1': '', 'HEU1': '', 'THE1': '', 'DPA1': '',
784
            'NOM1': '', 'PRE1': '', 'NAI1': '', 'NUM2': '',
785
            'NOM2': '', 'PRE2': '', 'TPA1': '', 'NSS1': '',
786
            'TR01': '', 'TR02': '', 'TR03': '', 'TR04': '', 'TR05': '',
787
            'AD16': '', 'AD17': '', 'AD19': '',
788
            'AD21': '', 'AD22': '', 'AD23': '', 'AD24': '', 'AD25': '',
789
            'AD26': '', 'AD27': '', 'AD28': '', 'AD29': '',
790 c0fe0fc5 Mikaël Ates
            'RDV2': '' ,
791 b4310641 Mikaël Ates
        }
792 c0fe0fc5 Mikaël Ates
        list_rdvs = []
793
        for act in Act.objects.last_acts(patient):
794
            state = act.get_state()
795
            if state and state.state_name in ('VALIDE', 'ACT_DOUBLE'):
796
                rdv = "\t- %s" % formats.date_format(act.date, "DATE_FORMAT")
797
                if act.time:
798
                    rdv += " à %s" % formats.date_format(act.time, "TIME_FORMAT")
799
                list_rdvs.append(rdv)
800
        variables['RDV2'] = '\par'.join(list_rdvs)
801 b4310641 Mikaël Ates
        if appointment:
802 1193006a Mikaël Ates
            variables['RDV1'] = formats.date_format(appointment.date, "DATE_FORMAT")
803 b4310641 Mikaël Ates
            variables['HEU1'] = appointment.begin_hour
804
            variables['THE1'] = ' '.join([str(i) for i in appointment.workers])# ou DPA1?
805
            variables['DPA1'] = variables['THE1']
806
        if patient:
807
            variables['NOM1'] = patient.last_name
808
            variables['PRE1'] = patient.first_name
809
            if patient.birthdate :
810
                variables['NAI1'] = patient.birthdate.strftime('%d/%m/%Y')
811
            variables['NUM2'] = patient.paper_id
812
            if patient.policyholder:
813
                variables['NOM2'] = patient.policyholder.last_name
814
                variables['PRE2'] = patient.policyholder.first_name
815 2a5c234c Mikaël Ates
                if patient.policyholder.health_center:
816
                    variables['TPA1'] = patient.policyholder.health_center.name
817 b4310641 Mikaël Ates
                if patient.policyholder.social_security_id:
818
                    key = str(patient.policyholder.get_control_key())
819
                    if len(key) == 1:
820
                        key = '0' + key
821
                    variables['NSS1'] = \
822
                        ' '.join([patient.policyholder.social_security_id,
823
                            key])
824
            if patient.transportcompany:
825
                variables['TR01'] = patient.transportcompany.name
826
                variables['TR02'] = patient.transportcompany.address
827
                variables['TR03'] = patient.transportcompany.address_complement
828
                variables['TR04'] = patient.transportcompany.zip_code
829
                variables['TR05'] = patient.transportcompany.city
830
        variables['AD18'] = form.cleaned_data.get('phone_address') or ''
831 23937808 Frédéric Péters
        for i, line in enumerate(form.cleaned_data.get('address').splitlines()):
832 b4310641 Mikaël Ates
            variables['AD%d' % (11+i)] = line
833 bc17dbd7 Mikaël Ates
            if i == 4:
834
                break
835 b4310641 Mikaël Ates
836
        filename = make_doc_from_template(from_path, to_path, variables,
837
            persistent)
838 23937808 Frédéric Péters
839 ac0cd457 Frédéric Péters
        client_dir = patient.get_client_side_directory(self.service.name)
840 577ecc05 Jérôme Schneider
        event.convocation_sent = True
841
        event.save()
842 ac0cd457 Frédéric Péters
        if not client_dir:
843 364eecbe Mikaël Ates
            content = File(file(filename))
844
            response = HttpResponse(content,'text/rtf')
845
            response['Content-Length'] = content.size
846 b1bac2e0 Mikaël Ates
            response['Content-Disposition'] = 'attachment; filename="%s"' \
847
                % dest_filename.encode('utf-8')
848 ac0cd457 Frédéric Péters
            return response
849
        else:
850 02f39251 Frédéric Péters
            class LocalFileHttpResponseRedirect(HttpResponseRedirect):
851
                allowed_schemes = ['file']
852 ac0cd457 Frédéric Péters
            client_filepath = os.path.join(client_dir, dest_filename)
853 02f39251 Frédéric Péters
            return LocalFileHttpResponseRedirect('file://' + client_filepath)
854 23937808 Frédéric Péters
855
generate_rtf_form = GenerateRtfFormView.as_view()
856 17e36a37 Frédéric Péters
857
858
class PatientRecordsQuotationsView(cbv.ListView):
859
    model = PatientRecord
860
    template_name = 'dossiers/quotations.html'
861
862 e16b3817 Jérôme Schneider
    def _get_search_result(self, paginate_patient_records):
863
        patient_records = []
864
        for patient_record in paginate_patient_records:
865 584b363f Mikaël Ates
            current_state = patient_record.get_current_state() or patient_record.get_state()
866 feffc421 Serghei MIHAI
            deficiencies = [getattr(patient_record, field) \
867 3fa5579e Serghei MIHAI
                            for field in self.model.DEFICIENCY_FIELDS]
868
            anap = any(deficiencies)
869
            mises = reduce(lambda m1, m2: m1+m2, [list(getattr(patient_record, field).all()) for field in self.model.MISES_FIELDS])
870 748e8d64 Serghei MIHAI
            next_rdv = get_next_rdv(patient_record)
871
            last_rdv = get_last_rdv(patient_record)
872
873
            if next_rdv:
874
                next_rdv_datetime = next_rdv.start_datetime
875
            else:
876
                next_rdv_datetime = None
877
            if last_rdv:
878
                last_rdv_datetime = last_rdv['start_datetime']
879
            else:
880
                last_rdv_datetime = None
881 e16b3817 Jérôme Schneider
            patient_records.append(
882
                    {
883
                        'object': patient_record,
884 97fbc132 Mikaël Ates
                        'state': current_state,
885 748e8d64 Serghei MIHAI
                        'anap': anap,
886
                        'mises': mises,
887
                        'next_rdv_date': next_rdv_datetime,
888
                        'last_rdv_date': last_rdv_datetime
889 e16b3817 Jérôme Schneider
                        }
890
                    )
891
        return patient_records
892
893 17e36a37 Frédéric Péters
    def get_queryset(self):
894
        form = forms.QuotationsForm(data=self.request.GET or None)
895
        qs = super(PatientRecordsQuotationsView, self).get_queryset()
896
        without_quotations = self.request.GET.get('without_quotations')
897 feffc421 Serghei MIHAI
        without_anap_quotations = self.request.GET.get('without_anap_quotations')
898 17e36a37 Frédéric Péters
        if without_quotations:
899 3fa5579e Serghei MIHAI
            for field in self.model.MISES_FIELDS:
900 748e8d64 Serghei MIHAI
                mise_field = {'%s__isnull' % field: True}
901
                qs = qs.filter(**mise_field)
902 feffc421 Serghei MIHAI
903
        if without_anap_quotations:
904 3fa5579e Serghei MIHAI
            for field in self.model.DEFICIENCY_FIELDS:
905 feffc421 Serghei MIHAI
                anap_field = {field: 0}
906
                qs = qs.filter(**anap_field)
907
908 17e36a37 Frédéric Péters
        states = self.request.GET.getlist('states')
909 e30c9bdb Jérôme Schneider
        qs = qs.filter(last_state__status__id__in=states)
910 17e36a37 Frédéric Péters
911
        try:
912
            date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
913 64839f29 Mikaël Ates
            qs = qs.filter(act__date__gte=date_actes_start.date()).distinct()
914 17e36a37 Frédéric Péters
        except (ValueError, KeyError):
915 76974b6f Benjamin Dauvergne
            pass
916 17e36a37 Frédéric Péters
        try:
917
            date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
918 64839f29 Mikaël Ates
            qs = qs.filter(act__date__lte=date_actes_end.date()).distinct()
919 17e36a37 Frédéric Péters
        except (ValueError, KeyError):
920 76974b6f Benjamin Dauvergne
            pass
921 e16b3817 Jérôme Schneider
        qs = qs.filter(service=self.service).order_by('last_name').prefetch_related()
922 17e36a37 Frédéric Péters
        return qs
923
924
    def get_context_data(self, **kwargs):
925
        ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
926 f6be0c7d Jérôme Schneider
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
927
                service=self.service)
928 43a5b181 Frédéric Péters
        patient_records = []
929
        page = self.request.GET.get('page')
930 2c6641c8 Serghei MIHAI
        all = 'all' in self.request.GET
931
        if all:
932
            patient_records = ctx['object_list']
933
            ctx['all'] = all
934
            self.template_name = 'dossiers/quotations_print.html'
935
        else:
936 affeff87 Mikaël Ates
            paginator = Paginator(ctx['object_list'].filter(), 25)
937 2c6641c8 Serghei MIHAI
            try:
938
                patient_records = paginator.page(page)
939
            except PageNotAnInteger:
940
                patient_records = paginator.page(1)
941
            except EmptyPage:
942
                patient_records = paginator.page(paginator.num_pages)
943
            ctx['paginate_patient_records'] = patient_records
944
945
        ctx['patient_records'] = self._get_search_result(patient_records)
946 43a5b181 Frédéric Péters
947
        query = self.request.GET.copy()
948
        if 'page' in query:
949
            del query['page']
950
        ctx['query'] = query.urlencode()
951
952 17e36a37 Frédéric Péters
        return ctx
953
954
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
955 7bc87b6f Frédéric Péters
956 5497fedd Mikaël Ates
class NewProtectionStateView(cbv.CreateView):
957
    model = ProtectionState
958
    template_name = 'dossiers/generic_form.html'
959
    success_url = '../view#tab=1'
960
    form_class = forms.ProtectionStateForm
961
962
    def form_valid(self, form):
963
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
964
        form.instance.patient = self.patient
965
        return super(NewProtectionStateView, self).form_valid(form)
966
967
new_protection = NewProtectionStateView.as_view()
968
969
class UpdateProtectionStateView(cbv.UpdateView):
970
    model = ProtectionState
971
    template_name = 'dossiers/generic_form.html'
972
    success_url = '../../view#tab=1'
973
    form_class = forms.ProtectionStateForm
974
975
    def form_valid(self, form):
976
        self.patient = get_object_or_404(PatientRecord, id=self.kwargs.get('patientrecord_id',None))
977
        form.instance.patient = self.patient
978
        return super(UpdateProtectionStateView, self).form_valid(form)
979
980
update_protection = UpdateProtectionStateView.as_view()
981
982
class DeleteProtectionStateView(cbv.DeleteView):
983
    model = ProtectionState
984
    template_name = 'dossiers/protection_confirm_delete.html'
985
    success_url = '../../view#tab=1'
986
987
delete_protection = DeleteProtectionStateView.as_view()
988
989 c5f8a919 Mikaël Ates
class PatientRecordsWaitingQueueView(cbv.ListView):
990
    model = PatientRecord
991
    template_name = 'dossiers/waiting_queue.html'
992
993
    def _get_search_result(self, paginate_patient_records,
994
            all_patient_records):
995
        patient_records = []
996
        if paginate_patient_records:
997
            position = 1
998
            for patient_record in paginate_patient_records:
999
                while patient_record.id != all_patient_records[position - 1].id:
1000
                    position += 1
1001
                patient_records.append(
1002
                        {
1003
                            'object': patient_record,
1004
                            'position': position,
1005
                            }
1006
                        )
1007
        return patient_records
1008
1009
    def get_queryset(self):
1010
        form = forms.QuotationsForm(data=self.request.GET or None)
1011
        qs = super(PatientRecordsWaitingQueueView, self).get_queryset()
1012
        first_name = self.request.GET.get('first_name')
1013
        last_name = self.request.GET.get('last_name')
1014
        paper_id = self.request.GET.get('paper_id')
1015
        id = self.request.GET.get('id')
1016
        social_security_id = self.request.GET.get('social_security_id')
1017
        qs = qs.filter(service=self.service,
1018
            last_state__status__type='ACCUEIL')
1019
        if last_name:
1020
            qs = qs.filter(last_name__istartswith=last_name)
1021
        if first_name:
1022
            qs = qs.filter(first_name__istartswith=first_name)
1023
        if paper_id:
1024
            qs = qs.filter(paper_id__startswith=paper_id)
1025
        if id:
1026
            qs = qs.filter(id__startswith=id)
1027
        if social_security_id:
1028
            qs = qs.filter(models.Q(
1029
                social_security_id__startswith=social_security_id)
1030
                | models.Q(
1031
                contacts__social_security_id__startswith=social_security_id))
1032
        qs = qs.order_by('last_state__date_selected', 'created')
1033
        return qs
1034
1035
    def get_context_data(self, **kwargs):
1036
        ctx = super(PatientRecordsWaitingQueueView, self).get_context_data(**kwargs)
1037
        ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None,
1038
                service=self.service)
1039
        patient_records = []
1040
        page = self.request.GET.get('page')
1041 affeff87 Mikaël Ates
1042
        all = 'all' in self.request.GET
1043
        if all:
1044
            paginate_patient_records = ctx['object_list']
1045
            ctx['all'] = all
1046
            self.template_name = 'dossiers/waiting_queue_print.html'
1047
        else:
1048
            paginator = Paginator(ctx['object_list'].filter(), 25)
1049
            try:
1050
                paginate_patient_records = paginator.page(page)
1051
            except PageNotAnInteger:
1052
                paginate_patient_records = paginator.page(1)
1053
            except EmptyPage:
1054
                paginate_patient_records = paginator.page(paginator.num_pages)
1055
            ctx['paginate_patient_records'] = paginate_patient_records
1056 c5f8a919 Mikaël Ates
1057
        all_patient_records = PatientRecord.objects.filter(
1058
                service=self.service,
1059
                last_state__status__type='ACCUEIL').order_by(
1060
                'last_state__date_selected', 'created')
1061
        ctx['patient_records'] = self._get_search_result(
1062
            paginate_patient_records, all_patient_records)
1063
        ctx['len_patient_records'] = all_patient_records.count()
1064
1065
        query = self.request.GET.copy()
1066
        if 'page' in query:
1067
            del query['page']
1068
        ctx['query'] = query.urlencode()
1069
1070
        return ctx
1071
1072
patientrecord_waiting_queue = PatientRecordsWaitingQueueView.as_view()
1073 7bc87b6f Frédéric Péters
1074
class CreateDirectoryView(View, cbv.ServiceViewMixin):
1075
    def post(self, request, *args, **kwargs):
1076
        patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
1077
        service = Service.objects.get(slug=kwargs['service'])
1078
        patient.get_ondisk_directory(service.name)
1079
        messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
1080
        return HttpResponseRedirect('view')
1081
1082
create_directory = CreateDirectoryView.as_view()
1083 cda02476 Mikaël Ates
1084
class GenerateTransportPrescriptionFormView(cbv.FormView):
1085
    template_name = 'dossiers/generate_transport_prescription_form.html'
1086
    form_class = Form
1087
    success_url = './view#tab=1'
1088
1089
    def get_context_data(self, **kwargs):
1090
        ctx = super(GenerateTransportPrescriptionFormView, self).get_context_data(**kwargs)
1091 07b0577e Mikaël Ates
        ctx['lieu'] = 'Saint-Etienne'
1092
        ctx['date'] = formats.date_format(datetime.today(), "SHORT_DATE_FORMAT")
1093
        ctx['id_etab'] = '''%s SAINT ETIENNE
1094
66/68, RUE MARENGO
1095
42000 SAINT ETIENNE''' % ctx['service'].upper()
1096
        try:
1097
            patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1098
            ctx['object'] = patient
1099
            last_log = TransportPrescriptionLog.objects.filter(patient=patient).latest('created')
1100
            if last_log:
1101
                ctx['choices'] = last_log.get_choices()
1102
                if 'lieu' in ctx['choices'] and ctx['choices']['lieu']:
1103
                    ctx['lieu'] = ctx['choices']['lieu']
1104
                if 'date' in ctx['choices'] and ctx['choices']['date']:
1105
                    ctx['date'] = ctx['choices']['date']
1106
                if 'id_etab' in ctx['choices'] and ctx['choices']['id_etab']:
1107
                    ctx['id_etab'] = ctx['choices']['id_etab']
1108
        except:
1109
            pass
1110 cda02476 Mikaël Ates
        return ctx
1111
1112
    def form_valid(self, form):
1113
        patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
1114
        address = PatientAddress.objects.get(id=form.data['address_id'])
1115 07b0577e Mikaël Ates
        path = render_transport(patient, address, form.data)
1116 cda02476 Mikaël Ates
        content = File(file(path))
1117 07b0577e Mikaël Ates
        log = TransportPrescriptionLog(patient=patient)
1118
        log.set_choices(form.data)
1119
        log.save()
1120 cda02476 Mikaël Ates
        response = HttpResponse(content,'application/pdf')
1121
        response['Content-Length'] = content.size
1122 b9039913 Mikaël Ates
        dest_filename = "%s--prescription-transport-%s-%s.pdf" \
1123 71d239fc Mikaël Ates
            % (datetime.now().strftime('%Y-%m-%d--%H:%M:%S'),
1124 b9039913 Mikaël Ates
            patient.last_name.upper().encode('utf-8'),
1125
            patient.first_name.encode('utf-8'))
1126
        response['Content-Disposition'] = \
1127
            'attachment; filename="%s"' % dest_filename
1128 cda02476 Mikaël Ates
        return response
1129
1130
prescription_transport = GenerateTransportPrescriptionFormView.as_view()