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