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