1
|
# -*- coding: utf-8 -*-
|
2
|
|
3
|
import os
|
4
|
|
5
|
from datetime import datetime, date
|
6
|
|
7
|
from django.conf import settings
|
8
|
from django.core.urlresolvers import reverse_lazy
|
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, FormMixin
|
13
|
from django.contrib import messages
|
14
|
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
|
15
|
|
16
|
from calebasse import cbv
|
17
|
from calebasse.doc_templates import make_doc_from_template
|
18
|
from calebasse.dossiers import forms
|
19
|
from calebasse.agenda.models import Event, EventWithAct
|
20
|
from calebasse.actes.models import Act
|
21
|
from calebasse.agenda.appointments import Appointment
|
22
|
from calebasse.dossiers.models import (PatientRecord, PatientContact,
|
23
|
PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
|
24
|
CmppHealthCareDiagnostic, SessadHealthCareNotification, HealthCare)
|
25
|
from calebasse.dossiers.states import STATES_MAPPING, STATE_CHOICES_TYPE, STATES_BTN_MAPPER
|
26
|
from calebasse.ressources.models import (Service,
|
27
|
SocialisationDuration, MDPHRequest, MDPHResponse)
|
28
|
|
29
|
|
30
|
def get_next_rdv(patient_record):
|
31
|
next_rdv = {}
|
32
|
event = Event.objects.next_appointment(patient_record)
|
33
|
if event:
|
34
|
next_rdv['start_datetime'] = event.start_datetime
|
35
|
next_rdv['participants'] = event.participants.all()
|
36
|
next_rdv['act_type'] = event.eventwithact.act_type
|
37
|
return next_rdv
|
38
|
|
39
|
def get_last_rdv(patient_record):
|
40
|
last_rdv = {}
|
41
|
event = Event.objects.last_appointment(patient_record)
|
42
|
if event:
|
43
|
last_rdv['start_datetime'] = event.start_datetime
|
44
|
last_rdv['participants'] = event.participants.all()
|
45
|
last_rdv['act_type'] = event.eventwithact.act_type
|
46
|
return last_rdv
|
47
|
|
48
|
class NewPatientRecordView(cbv.FormView, cbv.ServiceViewMixin):
|
49
|
form_class = forms.NewPatientRecordForm
|
50
|
template_name = 'dossiers/patientrecord_new.html'
|
51
|
success_url = '..'
|
52
|
patient = None
|
53
|
|
54
|
def post(self, request, *args, **kwarg):
|
55
|
self.user = request.user
|
56
|
return super(NewPatientRecordView, self).post(request, *args, **kwarg)
|
57
|
|
58
|
def form_valid(self, form):
|
59
|
self.patient = create_patient(form.data['first_name'], form.data['last_name'], self.service,
|
60
|
self.user, date_selected=datetime.strptime(form.data['date_selected'], "%d/%m/%Y"))
|
61
|
return super(NewPatientRecordView, self).form_valid(form)
|
62
|
|
63
|
def get_success_url(self):
|
64
|
return '%s/view' % self.patient.id
|
65
|
|
66
|
new_patient_record = NewPatientRecordView.as_view()
|
67
|
|
68
|
class RecordPatientRecordIdMixing(object):
|
69
|
def dispatch(self, request, *args, **kwargs):
|
70
|
self.patientrecord_id = request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
71
|
return super(RecordPatientRecordIdMixing, self).dispatch(request, *args, **kwargs)
|
72
|
|
73
|
def get_form_kwargs(self):
|
74
|
kwargs = super(RecordPatientRecordIdMixing, self).get_form_kwargs()
|
75
|
kwargs['patient'] = PatientRecord.objects.get(id=self.patientrecord_id)
|
76
|
return kwargs
|
77
|
|
78
|
class NewPatientContactView(RecordPatientRecordIdMixing, cbv.CreateView):
|
79
|
model = PatientContact
|
80
|
form_class = forms.PatientContactForm
|
81
|
template_name = 'dossiers/patientcontact_new.html'
|
82
|
success_url = '../view#tab=2'
|
83
|
|
84
|
new_patient_contact = NewPatientContactView.as_view()
|
85
|
|
86
|
class UpdatePatientContactView(RecordPatientRecordIdMixing, cbv.UpdateView):
|
87
|
model = PatientContact
|
88
|
form_class = forms.PatientContactForm
|
89
|
template_name = 'dossiers/patientcontact_new.html'
|
90
|
success_url = '../../view#tab=2'
|
91
|
|
92
|
update_patient_contact = UpdatePatientContactView.as_view()
|
93
|
|
94
|
class DeletePatientContactView(cbv.DeleteView):
|
95
|
model = PatientContact
|
96
|
form_class = forms.PatientContactForm
|
97
|
template_name = 'dossiers/patientcontact_confirm_delete.html'
|
98
|
success_url = '../../view#tab=2'
|
99
|
|
100
|
def post(self, request, *args, **kwargs):
|
101
|
try:
|
102
|
patient = PatientRecord.objects.get(id=kwargs.get('pk'))
|
103
|
except PatientRecord.DoesNotExist:
|
104
|
return super(DeletePatientContactView, self).post(request, *args, **kwargs)
|
105
|
# the contact is also a patient record; it shouldn't be deleted; just
|
106
|
# altered to remove an address
|
107
|
patient.addresses.remove(self.request.GET['address'])
|
108
|
return HttpResponseRedirect(self.get_success_url())
|
109
|
|
110
|
delete_patient_contact = DeletePatientContactView.as_view()
|
111
|
|
112
|
class NewPatientAddressView(cbv.CreateView):
|
113
|
model = PatientAddress
|
114
|
form_class = forms.PatientAddressForm
|
115
|
template_name = 'dossiers/patientaddress_new.html'
|
116
|
success_url = '../view#tab=2'
|
117
|
|
118
|
def get_success_url(self):
|
119
|
return self.success_url
|
120
|
|
121
|
def form_valid(self, form):
|
122
|
patientaddress = form.save()
|
123
|
patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
|
124
|
patientrecord.addresses.add(patientaddress)
|
125
|
return HttpResponseRedirect(self.get_success_url())
|
126
|
|
127
|
new_patient_address = NewPatientAddressView.as_view()
|
128
|
|
129
|
class UpdatePatientAddressView(cbv.UpdateView):
|
130
|
model = PatientAddress
|
131
|
form_class = forms.PatientAddressForm
|
132
|
template_name = 'dossiers/patientaddress_new.html'
|
133
|
success_url = '../../view#tab=2'
|
134
|
|
135
|
update_patient_address = UpdatePatientAddressView.as_view()
|
136
|
|
137
|
class DeletePatientAddressView(cbv.DeleteView):
|
138
|
model = PatientAddress
|
139
|
form_class = forms.PatientAddressForm
|
140
|
template_name = 'dossiers/patientaddress_confirm_delete.html'
|
141
|
success_url = '../../view#tab=2'
|
142
|
|
143
|
delete_patient_address = DeletePatientAddressView.as_view()
|
144
|
|
145
|
|
146
|
class NewHealthCareView(cbv.CreateView):
|
147
|
|
148
|
def get_initial(self):
|
149
|
initial = super(NewHealthCareView, self).get_initial()
|
150
|
initial['author'] = self.request.user.id
|
151
|
initial['patient'] = self.kwargs['patientrecord_id']
|
152
|
return initial
|
153
|
|
154
|
new_healthcare_treatment = \
|
155
|
NewHealthCareView.as_view(model=CmppHealthCareTreatment,
|
156
|
template_name = 'dossiers/generic_form.html',
|
157
|
success_url = '../view#tab=3',
|
158
|
form_class=forms.CmppHealthCareTreatmentForm)
|
159
|
new_healthcare_diagnostic = \
|
160
|
NewHealthCareView.as_view(model=CmppHealthCareDiagnostic,
|
161
|
template_name = 'dossiers/generic_form.html',
|
162
|
success_url = '../view#tab=3',
|
163
|
form_class=forms.CmppHealthCareDiagnosticForm)
|
164
|
new_healthcare_notification = \
|
165
|
NewHealthCareView.as_view(model=SessadHealthCareNotification,
|
166
|
template_name = 'dossiers/generic_form.html',
|
167
|
success_url = '../view#tab=3',
|
168
|
form_class=forms.SessadHealthCareNotificationForm)
|
169
|
update_healthcare_treatment = \
|
170
|
cbv.UpdateView.as_view(model=CmppHealthCareTreatment,
|
171
|
template_name = 'dossiers/generic_form.html',
|
172
|
success_url = '../../view#tab=3',
|
173
|
form_class=forms.CmppHealthCareTreatmentForm)
|
174
|
update_healthcare_diagnostic = \
|
175
|
cbv.UpdateView.as_view(model=CmppHealthCareDiagnostic,
|
176
|
template_name = 'dossiers/generic_form.html',
|
177
|
success_url = '../../view#tab=3',
|
178
|
form_class=forms.CmppHealthCareDiagnosticForm)
|
179
|
update_healthcare_notification = \
|
180
|
cbv.UpdateView.as_view(model=SessadHealthCareNotification,
|
181
|
template_name = 'dossiers/generic_form.html',
|
182
|
success_url = '../../view#tab=3',
|
183
|
form_class=forms.SessadHealthCareNotificationForm)
|
184
|
delete_healthcare_treatment = \
|
185
|
cbv.DeleteView.as_view(model=CmppHealthCareTreatment,
|
186
|
template_name = 'dossiers/generic_confirm_delete.html',
|
187
|
success_url = '../../view#tab=3')
|
188
|
delete_healthcare_diagnostic = \
|
189
|
cbv.DeleteView.as_view(model=CmppHealthCareDiagnostic,
|
190
|
template_name = 'dossiers/generic_confirm_delete.html',
|
191
|
success_url = '../../view#tab=3')
|
192
|
delete_healthcare_notification = \
|
193
|
cbv.DeleteView.as_view(model=SessadHealthCareNotification,
|
194
|
template_name = 'dossiers/generic_confirm_delete.html',
|
195
|
success_url = '../../view#tab=3')
|
196
|
|
197
|
|
198
|
class StateFormView(cbv.FormView):
|
199
|
template_name = 'dossiers/state.html'
|
200
|
form_class = forms.StateForm
|
201
|
success_url = './view#tab=0'
|
202
|
|
203
|
def post(self, request, *args, **kwarg):
|
204
|
self.user = request.user
|
205
|
return super(StateFormView, self).post(request, *args, **kwarg)
|
206
|
|
207
|
def form_valid(self, form):
|
208
|
service = Service.objects.get(id=form.data['service_id'])
|
209
|
status = Status.objects.filter(services=service).filter(type=form.data['state_type'])
|
210
|
patient = PatientRecord.objects.get(id=form.data['patient_id'])
|
211
|
date_selected = datetime.strptime(form.data['date'], "%d/%m/%Y")
|
212
|
patient.set_state(status[0], self.user, date_selected, form.data['comment'])
|
213
|
return super(StateFormView, self).form_valid(form)
|
214
|
|
215
|
state_form = StateFormView.as_view()
|
216
|
|
217
|
|
218
|
class PatientRecordView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
|
219
|
model = PatientRecord
|
220
|
forms_classes = {
|
221
|
'general': forms.GeneralForm,
|
222
|
'id': forms.CivilStatusForm,
|
223
|
'physiology': forms.PhysiologyForm,
|
224
|
'inscription': forms.InscriptionForm,
|
225
|
'out': forms.OutForm,
|
226
|
'family': forms.FamilyForm,
|
227
|
'transport': forms.TransportFrom,
|
228
|
'followup': forms.FollowUpForm,
|
229
|
'policyholder': forms.PolicyHolderForm
|
230
|
}
|
231
|
template_name = 'dossiers/patientrecord_update.html'
|
232
|
success_url = './view'
|
233
|
|
234
|
def get_success_url(self):
|
235
|
if self.request.POST.has_key('tab'):
|
236
|
return self.success_url + '#tab=' + self.request.POST['tab']
|
237
|
else:
|
238
|
return self.success_url
|
239
|
|
240
|
def get_context_data(self, **kwargs):
|
241
|
ctx = super(PatientRecordView, self).get_context_data(**kwargs)
|
242
|
ctx['next_rdv'] = get_next_rdv(ctx['object'])
|
243
|
ctx['last_rdv'] = get_last_rdv(ctx['object'])
|
244
|
ctx['initial_state'] = ctx['object'].get_initial_state()
|
245
|
current_state = ctx['object'].get_current_state()
|
246
|
if STATES_MAPPING.has_key(current_state.status.type):
|
247
|
state = STATES_MAPPING[current_state.status.type]
|
248
|
else:
|
249
|
state = current_state.status.name
|
250
|
ctx['current_state'] = current_state
|
251
|
ctx['service_id'] = self.service.id
|
252
|
ctx['states'] = FileState.objects.filter(patient=self.object).filter(status__services=self.service)
|
253
|
ctx['next_rdvs'] = []
|
254
|
Q = models.Q
|
255
|
today = date.today()
|
256
|
qs = EventWithAct.objects.filter(patient=ctx['object']) \
|
257
|
.filter(exception_to__isnull=True) \
|
258
|
.filter(Q(start_datetime__gte=today)
|
259
|
| ( Q(recurrence_periodicity__isnull=False)
|
260
|
& (Q(recurrence_end_date__gte=today)
|
261
|
| Q(recurrence_end_date__isnull=True)))) \
|
262
|
.select_related() \
|
263
|
.prefetch_related('participants', 'exceptions__eventwithact', 'act_set__actvalidationstate_set')
|
264
|
occurrences = []
|
265
|
for event in qs:
|
266
|
occurrences.extend(filter(lambda e: e.start_datetime.date() > today, event.all_occurences(limit=180)))
|
267
|
occurrences = sorted(occurrences, key=lambda e: e.start_datetime)
|
268
|
acts = Act.objects.filter(date__gte=today, patient=ctx['object']) \
|
269
|
.prefetch_related('actvalidationstate_set')
|
270
|
acts_by_date = dict((act.date, act.time) for act in acts)
|
271
|
for event in occurrences:
|
272
|
state = None
|
273
|
act = acts_by_date.get((event.start_datetime.date, event.start_datetime.time))
|
274
|
if act:
|
275
|
state = act.actvalidationstate_set.all()[0]
|
276
|
if state and not state.previous_state and state.state_name == 'NON_VALIDE':
|
277
|
state = None
|
278
|
ctx['next_rdvs'].append((event, state))
|
279
|
ctx['last_rdvs'] = []
|
280
|
for act in Act.objects.last_acts(ctx['object']).prefetch_related('doctors'):
|
281
|
state = act.get_state()
|
282
|
if not state.previous_state and state.state_name == 'NON_VALIDE':
|
283
|
state = None
|
284
|
ctx['last_rdvs'].append((act, state))
|
285
|
ctx['status'] = []
|
286
|
if ctx['object'].service.name == "CMPP":
|
287
|
if ctx['object'].last_state.status.type == "ACCUEIL":
|
288
|
# Inscription automatique au premier acte facturable valide
|
289
|
ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
|
290
|
STATES_BTN_MAPPER['DIAGNOSTIC'],
|
291
|
STATES_BTN_MAPPER['TRAITEMENT']]
|
292
|
elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
|
293
|
# Passage automatique en diagnostic ou traitement
|
294
|
ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
|
295
|
STATES_BTN_MAPPER['DIAGNOSTIC'],
|
296
|
STATES_BTN_MAPPER['TRAITEMENT']]
|
297
|
elif ctx['object'].last_state.status.type == "DIAGNOSTIC":
|
298
|
# Passage automatique en traitement
|
299
|
ctx['status'] = [STATES_BTN_MAPPER['TRAITEMENT'],
|
300
|
STATES_BTN_MAPPER['CLOS'],
|
301
|
STATES_BTN_MAPPER['ACCUEIL']]
|
302
|
elif ctx['object'].last_state.status.type == "TRAITEMENT":
|
303
|
# Passage automatique en diagnostic si on ajoute une prise en charge diagnostic,
|
304
|
# ce qui est faisable dans l'onglet prise en charge par un bouton visible sous conditions
|
305
|
ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
|
306
|
STATES_BTN_MAPPER['CLOS'],
|
307
|
STATES_BTN_MAPPER['ACCUEIL']]
|
308
|
elif ctx['object'].last_state.status.type == "CLOS":
|
309
|
# Passage automatique en diagnostic ou traitement
|
310
|
ctx['status'] = [STATES_BTN_MAPPER['DIAGNOSTIC'],
|
311
|
STATES_BTN_MAPPER['TRAITEMENT'],
|
312
|
STATES_BTN_MAPPER['ACCUEIL']]
|
313
|
elif ctx['object'].service.name == "CAMSP":
|
314
|
if ctx['object'].last_state.status.type == "ACCUEIL":
|
315
|
ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
|
316
|
STATES_BTN_MAPPER['BILAN']]
|
317
|
elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
|
318
|
ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
|
319
|
STATES_BTN_MAPPER['BILAN'],
|
320
|
STATES_BTN_MAPPER['SURVEILLANCE'],
|
321
|
STATES_BTN_MAPPER['SUIVI'],
|
322
|
STATES_BTN_MAPPER['CLOS']]
|
323
|
elif ctx['object'].last_state.status.type == "BILAN":
|
324
|
ctx['status'] = [STATES_BTN_MAPPER['SURVEILLANCE'],
|
325
|
STATES_BTN_MAPPER['SUIVI'],
|
326
|
STATES_BTN_MAPPER['CLOS'],
|
327
|
STATES_BTN_MAPPER['ACCUEIL']]
|
328
|
elif ctx['object'].last_state.status.type == "SURVEILLANCE":
|
329
|
ctx['status'] = [STATES_BTN_MAPPER['SUIVI'],
|
330
|
STATES_BTN_MAPPER['CLOS'],
|
331
|
STATES_BTN_MAPPER['ACCUEIL'],
|
332
|
STATES_BTN_MAPPER['BILAN']]
|
333
|
elif ctx['object'].last_state.status.type == "SUIVI":
|
334
|
ctx['status'] = [STATES_BTN_MAPPER['CLOS'],
|
335
|
STATES_BTN_MAPPER['ACCUEIL'],
|
336
|
STATES_BTN_MAPPER['BILAN'],
|
337
|
STATES_BTN_MAPPER['SURVEILLANCE']]
|
338
|
elif ctx['object'].last_state.status.type == "CLOS":
|
339
|
ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
|
340
|
STATES_BTN_MAPPER['BILAN'],
|
341
|
STATES_BTN_MAPPER['SURVEILLANCE'],
|
342
|
STATES_BTN_MAPPER['SUIVI']]
|
343
|
elif ctx['object'].service.name == "SESSAD TED" or ctx['object'].service.name == "SESSAD DYS":
|
344
|
if ctx['object'].last_state.status.type == "ACCUEIL":
|
345
|
ctx['status'] = [STATES_BTN_MAPPER['FIN_ACCUEIL'],
|
346
|
STATES_BTN_MAPPER['TRAITEMENT']]
|
347
|
elif ctx['object'].last_state.status.type == "FIN_ACCUEIL":
|
348
|
ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
|
349
|
STATES_BTN_MAPPER['TRAITEMENT'],
|
350
|
STATES_BTN_MAPPER['CLOS']]
|
351
|
elif ctx['object'].last_state.status.type == "TRAITEMENT":
|
352
|
ctx['status'] = [STATES_BTN_MAPPER['CLOS'],
|
353
|
STATES_BTN_MAPPER['ACCUEIL']]
|
354
|
elif ctx['object'].last_state.status.type == "CLOS":
|
355
|
ctx['status'] = [STATES_BTN_MAPPER['ACCUEIL'],
|
356
|
STATES_BTN_MAPPER['TRAITEMENT']]
|
357
|
ctx['can_rediag'] = self.object.create_diag_healthcare(self.request.user)
|
358
|
ctx['hcs'] = HealthCare.objects.filter(patient=self.object).order_by('-start_date')
|
359
|
return ctx
|
360
|
|
361
|
def form_valid(self, form):
|
362
|
messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
|
363
|
return super(PatientRecordView, self).form_valid(form)
|
364
|
|
365
|
|
366
|
patient_record = PatientRecordView.as_view()
|
367
|
|
368
|
class PatientRecordsHomepageView(cbv.ListView):
|
369
|
model = PatientRecord
|
370
|
template_name = 'dossiers/index.html'
|
371
|
|
372
|
def get_queryset(self):
|
373
|
first_name = self.request.GET.get('first_name')
|
374
|
last_name = self.request.GET.get('last_name')
|
375
|
paper_id = self.request.GET.get('paper_id')
|
376
|
id = self.request.GET.get('id')
|
377
|
social_security_id = self.request.GET.get('social_security_id')
|
378
|
if not (first_name or last_name or paper_id or id or social_security_id):
|
379
|
return None
|
380
|
if (first_name and len(first_name) < 2) or (last_name and len(last_name) < 2):
|
381
|
return None
|
382
|
qs = super(PatientRecordsHomepageView, self).get_queryset()
|
383
|
states = self.request.GET.getlist('states')
|
384
|
if last_name:
|
385
|
qs = qs.filter(last_name__icontains=last_name)
|
386
|
if first_name:
|
387
|
qs = qs.filter(first_name__icontains=first_name)
|
388
|
if paper_id:
|
389
|
qs = qs.filter(paper_id__startswith=paper_id)
|
390
|
if id:
|
391
|
qs = qs.filter(id__startswith=id)
|
392
|
if social_security_id:
|
393
|
qs = qs.filter(models.Q(social_security_id__startswith=social_security_id) | \
|
394
|
models.Q(contacts__social_security_id__startswith=social_security_id))
|
395
|
if states:
|
396
|
status_types = ['BILAN', 'SURVEILLANCE', 'SUIVI']
|
397
|
for state in states:
|
398
|
status_types.append(STATE_CHOICES_TYPE[state])
|
399
|
qs = qs.filter(last_state__status__type__in=status_types)
|
400
|
else:
|
401
|
qs = qs.filter(last_state__status__type__in="")
|
402
|
qs = qs.filter(service=self.service).order_by('last_name')
|
403
|
return qs
|
404
|
|
405
|
def get_context_data(self, **kwargs):
|
406
|
ctx = super(PatientRecordsHomepageView, self).get_context_data(**kwargs)
|
407
|
ctx['search_form'] = forms.SearchForm(data=self.request.GET or None)
|
408
|
patient_records = []
|
409
|
ctx['stats'] = {"dossiers": 0,
|
410
|
"En_contact": 0,
|
411
|
"Fin_daccueil": 0,
|
412
|
"Diagnostic": 0,
|
413
|
"Traitement": 0,
|
414
|
"Clos": 0}
|
415
|
if self.request.GET:
|
416
|
if ctx['object_list']:
|
417
|
for patient_record in ctx['object_list'].filter():
|
418
|
ctx['stats']['dossiers'] += 1
|
419
|
next_rdv = get_next_rdv(patient_record)
|
420
|
last_rdv = get_last_rdv(patient_record)
|
421
|
current_state = patient_record.get_current_state()
|
422
|
if STATES_MAPPING.has_key(current_state.status.type):
|
423
|
state = STATES_MAPPING[current_state.status.type]
|
424
|
else:
|
425
|
state = current_state.status.name
|
426
|
state_class = current_state.status.type.lower()
|
427
|
patient_records.append(
|
428
|
{
|
429
|
'object': patient_record,
|
430
|
'next_rdv': next_rdv,
|
431
|
'last_rdv': last_rdv,
|
432
|
'state': state,
|
433
|
'state_class': state_class
|
434
|
}
|
435
|
)
|
436
|
state = state.replace(' ', '_')
|
437
|
state = state.replace("'", '')
|
438
|
if not ctx['stats'].has_key(state):
|
439
|
ctx['stats'][state] = 0
|
440
|
ctx['stats'][state] += 1
|
441
|
|
442
|
page = self.request.GET.get('page')
|
443
|
paginator = Paginator(patient_records, 50)
|
444
|
try:
|
445
|
patient_records = paginator.page(page)
|
446
|
except PageNotAnInteger:
|
447
|
patient_records = paginator.page(1)
|
448
|
except EmptyPage:
|
449
|
patient_records = paginator.page(paginator.num_pages)
|
450
|
|
451
|
query = self.request.GET.copy()
|
452
|
if 'page' in query:
|
453
|
del query['page']
|
454
|
ctx['query'] = query.urlencode()
|
455
|
|
456
|
ctx['patient_records'] = patient_records
|
457
|
return ctx
|
458
|
|
459
|
patientrecord_home = PatientRecordsHomepageView.as_view()
|
460
|
|
461
|
class PatientRecordDeleteView(DeleteView):
|
462
|
model = PatientRecord
|
463
|
success_url = ".."
|
464
|
template_name = 'dossiers/patientrecord_confirm_delete.html'
|
465
|
|
466
|
patientrecord_delete = PatientRecordDeleteView.as_view()
|
467
|
|
468
|
|
469
|
class PatientRecordPaperIDUpdateView(cbv.UpdateView):
|
470
|
model = PatientRecord
|
471
|
form_class = forms.PaperIDForm
|
472
|
template_name = 'dossiers/generic_form.html'
|
473
|
success_url = '../..'
|
474
|
|
475
|
update_paper_id = PatientRecordPaperIDUpdateView.as_view()
|
476
|
|
477
|
|
478
|
class NewSocialisationDurationView(cbv.CreateView):
|
479
|
model = SocialisationDuration
|
480
|
form_class = forms.SocialisationDurationForm
|
481
|
template_name = 'dossiers/generic_form.html'
|
482
|
success_url = '../view#tab=6'
|
483
|
|
484
|
def get_success_url(self):
|
485
|
return self.success_url
|
486
|
|
487
|
def get(self, request, *args, **kwargs):
|
488
|
if kwargs.has_key('patientrecord_id'):
|
489
|
request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
490
|
return super(NewSocialisationDurationView, self).get(request, *args, **kwargs)
|
491
|
|
492
|
def form_valid(self, form):
|
493
|
duration = form.save()
|
494
|
patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
|
495
|
patientrecord.socialisation_durations.add(duration)
|
496
|
return HttpResponseRedirect(self.get_success_url())
|
497
|
|
498
|
new_socialisation_duration = NewSocialisationDurationView.as_view()
|
499
|
|
500
|
class UpdateSocialisationDurationView(cbv.UpdateView):
|
501
|
model = SocialisationDuration
|
502
|
form_class = forms.SocialisationDurationForm
|
503
|
template_name = 'dossiers/generic_form.html'
|
504
|
success_url = '../../view#tab=6'
|
505
|
|
506
|
def get(self, request, *args, **kwargs):
|
507
|
if kwargs.has_key('patientrecord_id'):
|
508
|
request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
509
|
return super(UpdateSocialisationDurationView, self).get(request, *args, **kwargs)
|
510
|
|
511
|
update_socialisation_duration = UpdateSocialisationDurationView.as_view()
|
512
|
|
513
|
class DeleteSocialisationDurationView(cbv.DeleteView):
|
514
|
model = SocialisationDuration
|
515
|
form_class = forms.SocialisationDurationForm
|
516
|
template_name = 'dossiers/socialisationduration_confirm_delete.html'
|
517
|
success_url = '../../view#tab=6'
|
518
|
|
519
|
delete_socialisation_duration = DeleteSocialisationDurationView.as_view()
|
520
|
|
521
|
|
522
|
class NewMDPHRequestView(cbv.CreateView):
|
523
|
def get(self, request, *args, **kwargs):
|
524
|
if kwargs.has_key('patientrecord_id'):
|
525
|
request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
526
|
return super(NewMDPHRequestView, self).get(request, *args, **kwargs)
|
527
|
|
528
|
def form_valid(self, form):
|
529
|
request = form.save()
|
530
|
patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
|
531
|
patientrecord.mdph_requests.add(request)
|
532
|
return HttpResponseRedirect(self.success_url)
|
533
|
|
534
|
class UpdateMDPHRequestView(cbv.UpdateView):
|
535
|
def get(self, request, *args, **kwargs):
|
536
|
if kwargs.has_key('patientrecord_id'):
|
537
|
request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
538
|
return super(UpdateMDPHRequestView, self).get(request, *args, **kwargs)
|
539
|
|
540
|
|
541
|
new_mdph_request = \
|
542
|
NewMDPHRequestView.as_view(model=MDPHRequest,
|
543
|
template_name = 'dossiers/generic_form.html',
|
544
|
success_url = '../view#tab=6',
|
545
|
form_class=forms.MDPHRequestForm)
|
546
|
update_mdph_request = \
|
547
|
UpdateMDPHRequestView.as_view(model=MDPHRequest,
|
548
|
template_name = 'dossiers/generic_form.html',
|
549
|
success_url = '../../view#tab=6',
|
550
|
form_class=forms.MDPHRequestForm)
|
551
|
delete_mdph_request = \
|
552
|
cbv.DeleteView.as_view(model=MDPHRequest,
|
553
|
template_name = 'dossiers/generic_confirm_delete.html',
|
554
|
success_url = '../../view#tab=6')
|
555
|
|
556
|
class NewMDPHResponseView(cbv.CreateView):
|
557
|
def get(self, request, *args, **kwargs):
|
558
|
if kwargs.has_key('patientrecord_id'):
|
559
|
request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
560
|
return super(NewMDPHResponseView, self).get(request, *args, **kwargs)
|
561
|
|
562
|
def form_valid(self, form):
|
563
|
response = form.save()
|
564
|
patientrecord = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
|
565
|
patientrecord.mdph_responses.add(response)
|
566
|
return HttpResponseRedirect(self.success_url)
|
567
|
|
568
|
class UpdateMDPHResponseView(cbv.UpdateView):
|
569
|
def get(self, request, *args, **kwargs):
|
570
|
if kwargs.has_key('patientrecord_id'):
|
571
|
request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
572
|
return super(UpdateMDPHResponseView, self).get(request, *args, **kwargs)
|
573
|
|
574
|
|
575
|
new_mdph_response = \
|
576
|
NewMDPHResponseView.as_view(model=MDPHResponse,
|
577
|
template_name = 'dossiers/generic_form.html',
|
578
|
success_url = '../view#tab=6',
|
579
|
form_class=forms.MDPHResponseForm)
|
580
|
update_mdph_response = \
|
581
|
UpdateMDPHResponseView.as_view(model=MDPHResponse,
|
582
|
template_name = 'dossiers/generic_form.html',
|
583
|
success_url = '../../view#tab=6',
|
584
|
form_class=forms.MDPHResponseForm)
|
585
|
delete_mdph_response = \
|
586
|
cbv.DeleteView.as_view(model=MDPHResponse,
|
587
|
template_name = 'dossiers/generic_confirm_delete.html',
|
588
|
success_url = '../../view#tab=6')
|
589
|
|
590
|
|
591
|
class UpdatePatientStateView(cbv.UpdateView):
|
592
|
def get(self, request, *args, **kwargs):
|
593
|
if kwargs.has_key('patientrecord_id'):
|
594
|
request.session['patientrecord_id'] = kwargs['patientrecord_id']
|
595
|
return super(UpdatePatientStateView, self).get(request, *args, **kwargs)
|
596
|
|
597
|
update_patient_state = \
|
598
|
UpdatePatientStateView.as_view(model=FileState,
|
599
|
template_name = 'dossiers/generic_form.html',
|
600
|
success_url = '../../view#tab=0',
|
601
|
form_class=forms.PatientStateForm)
|
602
|
delete_patient_state = \
|
603
|
cbv.DeleteView.as_view(model=FileState,
|
604
|
template_name = 'dossiers/generic_confirm_delete.html',
|
605
|
success_url = '../../view#tab=0')
|
606
|
|
607
|
|
608
|
class GenerateRtfFormView(cbv.FormView):
|
609
|
template_name = 'dossiers/generate_rtf_form.html'
|
610
|
form_class = forms.GenerateRtfForm
|
611
|
success_url = './view#tab=0'
|
612
|
|
613
|
def get_context_data(self, **kwargs):
|
614
|
ctx = super(GenerateRtfFormView, self).get_context_data(**kwargs)
|
615
|
ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
|
616
|
ctx['service_id'] = self.service.id
|
617
|
if self.request.GET.get('event-id'):
|
618
|
date = self.request.GET.get('date')
|
619
|
date = datetime.strptime(date, '%Y-%m-%d').date()
|
620
|
appointment = Appointment()
|
621
|
event = EventWithAct.objects.get(id=self.request.GET.get('event-id'))
|
622
|
event = event.today_occurrence(date)
|
623
|
appointment.init_from_event(event, self.service)
|
624
|
ctx['appointment'] = appointment
|
625
|
return ctx
|
626
|
|
627
|
def form_valid(self, form):
|
628
|
patient = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
|
629
|
template_filename = form.cleaned_data.get('template_filename')
|
630
|
dest_filename = datetime.now().strftime('%Y-%m-%d--%H:%M') + '--' + template_filename
|
631
|
from_path = os.path.join(settings.RTF_TEMPLATES_DIRECTORY, template_filename)
|
632
|
to_path = os.path.join(patient.get_ondisk_directory(self.service.name), dest_filename)
|
633
|
vars = {'AD11': '', 'AD12': '', 'AD13': '', 'AD14': '', 'AD15': '',
|
634
|
'JOU1': datetime.today().strftime('%d/%m/%Y'),
|
635
|
'VIL1': u'Saint-Étienne',
|
636
|
'PRE1': form.cleaned_data.get('first_name'),
|
637
|
'NOM1': form.cleaned_data.get('last_name'),
|
638
|
'DPA1': form.cleaned_data.get('appointment_intervenants')
|
639
|
}
|
640
|
for i, line in enumerate(form.cleaned_data.get('address').splitlines()):
|
641
|
vars['AD%d' % (11+i)] = line
|
642
|
make_doc_from_template(from_path, to_path, vars)
|
643
|
|
644
|
client_dir = patient.get_client_side_directory(self.service.name)
|
645
|
if not client_dir:
|
646
|
response = HttpResponse(mimetype='text/rtf')
|
647
|
response['Content-Disposition'] = 'attachment; filename="%s"' % dest_filename
|
648
|
response.write(file(to_path).read())
|
649
|
return response
|
650
|
else:
|
651
|
class LocalFileHttpResponseRedirect(HttpResponseRedirect):
|
652
|
allowed_schemes = ['file']
|
653
|
client_filepath = os.path.join(client_dir, dest_filename)
|
654
|
return LocalFileHttpResponseRedirect('file://' + client_filepath)
|
655
|
|
656
|
generate_rtf_form = GenerateRtfFormView.as_view()
|
657
|
|
658
|
|
659
|
class PatientRecordsQuotationsView(cbv.ListView):
|
660
|
model = PatientRecord
|
661
|
template_name = 'dossiers/quotations.html'
|
662
|
|
663
|
def get_queryset(self):
|
664
|
form = forms.QuotationsForm(data=self.request.GET or None)
|
665
|
qs = super(PatientRecordsQuotationsView, self).get_queryset()
|
666
|
without_quotations = self.request.GET.get('without_quotations')
|
667
|
if without_quotations:
|
668
|
qs = qs.filter(mises_1=None).filter(mises_2=None).filter(mises_3=None)
|
669
|
states = self.request.GET.getlist('states')
|
670
|
if states:
|
671
|
status_types = ['BILAN', 'SURVEILLANCE', 'SUIVI']
|
672
|
for state in states:
|
673
|
status_types.append(STATE_CHOICES_TYPE[state])
|
674
|
qs = qs.filter(last_state__status__type__in=status_types)
|
675
|
else:
|
676
|
qs = qs.filter(last_state__status__type__in='')
|
677
|
|
678
|
try:
|
679
|
date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
|
680
|
qs = qs.filter(act_set__date__gte=date_actes_start.date())
|
681
|
except (ValueError, KeyError):
|
682
|
pass
|
683
|
try:
|
684
|
date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
|
685
|
qs = qs.filter(act_set__date__lte=date_actes_end.date())
|
686
|
except (ValueError, KeyError):
|
687
|
pass
|
688
|
qs = qs.filter(service=self.service).order_by('last_name')
|
689
|
return qs
|
690
|
|
691
|
def get_context_data(self, **kwargs):
|
692
|
ctx = super(PatientRecordsQuotationsView, self).get_context_data(**kwargs)
|
693
|
ctx['search_form'] = forms.QuotationsForm(data=self.request.GET or None)
|
694
|
patient_records = []
|
695
|
if self.request.GET:
|
696
|
for patient_record in ctx['object_list'].filter():
|
697
|
next_rdv = get_next_rdv(patient_record)
|
698
|
last_rdv = get_last_rdv(patient_record)
|
699
|
current_state = patient_record.get_current_state()
|
700
|
if STATES_MAPPING.has_key(current_state.status.type):
|
701
|
state = STATES_MAPPING[current_state.status.type]
|
702
|
else:
|
703
|
state = current_state.status.name
|
704
|
state_class = current_state.status.type.lower()
|
705
|
patient_records.append(
|
706
|
{
|
707
|
'object': patient_record,
|
708
|
'state': state,
|
709
|
'state_class': state_class
|
710
|
}
|
711
|
)
|
712
|
state = state.replace(' ', '_')
|
713
|
state = state.replace("'", '')
|
714
|
|
715
|
page = self.request.GET.get('page')
|
716
|
paginator = Paginator(patient_records, 50)
|
717
|
try:
|
718
|
patient_records = paginator.page(page)
|
719
|
except PageNotAnInteger:
|
720
|
patient_records = paginator.page(1)
|
721
|
except EmptyPage:
|
722
|
patient_records = paginator.page(paginator.num_pages)
|
723
|
|
724
|
ctx['patient_records'] = patient_records
|
725
|
|
726
|
query = self.request.GET.copy()
|
727
|
if 'page' in query:
|
728
|
del query['page']
|
729
|
ctx['query'] = query.urlencode()
|
730
|
|
731
|
return ctx
|
732
|
|
733
|
patientrecord_quotations = PatientRecordsQuotationsView.as_view()
|
734
|
|
735
|
|
736
|
class CreateDirectoryView(View, cbv.ServiceViewMixin):
|
737
|
def post(self, request, *args, **kwargs):
|
738
|
patient = PatientRecord.objects.get(id=kwargs['patientrecord_id'])
|
739
|
service = Service.objects.get(slug=kwargs['service'])
|
740
|
patient.get_ondisk_directory(service.name)
|
741
|
messages.add_message(self.request, messages.INFO, u'Répertoire patient créé.')
|
742
|
return HttpResponseRedirect('view')
|
743
|
|
744
|
create_directory = CreateDirectoryView.as_view()
|