1
|
# -*- coding: utf-8 -*-
|
2
|
|
3
|
import datetime
|
4
|
|
5
|
from django.db.models import Q
|
6
|
from django.shortcuts import redirect
|
7
|
from django.http import HttpResponseRedirect
|
8
|
|
9
|
from calebasse.cbv import TemplateView, CreateView, UpdateView
|
10
|
from calebasse.agenda.models import Event, EventType, EventWithAct
|
11
|
from calebasse.personnes.models import TimeTable, Holiday
|
12
|
from calebasse.agenda.appointments import get_daily_appointments, get_daily_usage
|
13
|
from calebasse.personnes.models import Worker
|
14
|
from calebasse.ressources.models import WorkerType, Room
|
15
|
from calebasse.actes.validation import (get_acts_of_the_day,
|
16
|
get_days_with_acts_not_locked)
|
17
|
from calebasse.actes.validation_states import VALIDATION_STATES
|
18
|
from calebasse.actes.models import Act, ValidationMessage
|
19
|
from calebasse.actes.validation import (automated_validation, unlock_all_acts_of_the_day)
|
20
|
from calebasse import cbv
|
21
|
|
22
|
from forms import (NewAppointmentForm, NewEventForm, UpdateAppointmentForm)
|
23
|
|
24
|
def redirect_today(request, service):
|
25
|
'''If not date is given we redirect on the agenda for today'''
|
26
|
return redirect('agenda', date=datetime.date.today().strftime('%Y-%m-%d'),
|
27
|
service=service)
|
28
|
|
29
|
class AgendaHomepageView(TemplateView):
|
30
|
|
31
|
template_name = 'agenda/index.html'
|
32
|
|
33
|
def post(self, request, *args, **kwargs):
|
34
|
acte_id = request.POST.get('acte-id')
|
35
|
try:
|
36
|
act = Act.objects.get(id=acte_id)
|
37
|
if not act.validation_locked:
|
38
|
state_name = request.POST.get('act_state')
|
39
|
act.set_state(state_name, request.user)
|
40
|
except Act.DoesNotExist:
|
41
|
pass
|
42
|
return HttpResponseRedirect('#acte-frame-'+acte_id)
|
43
|
|
44
|
def get_context_data(self, **kwargs):
|
45
|
context = super(AgendaHomepageView, self).get_context_data(**kwargs)
|
46
|
|
47
|
context['workers_types'] = []
|
48
|
workers = []
|
49
|
for worker_type in WorkerType.objects.all():
|
50
|
workers_type = Worker.objects.filter(enabled=True, type=worker_type)
|
51
|
if workers_type:
|
52
|
data = {'type': worker_type.name, 'workers': workers_type }
|
53
|
context['workers_types'].append(data)
|
54
|
workers.extend(data['workers'])
|
55
|
|
56
|
context['workers'] = workers
|
57
|
context['disponibility_start_times'] = range(8, 20)
|
58
|
|
59
|
return context
|
60
|
|
61
|
class AgendaServiceActivityView(TemplateView):
|
62
|
|
63
|
template_name = 'agenda/service-activity.html'
|
64
|
|
65
|
def get_context_data(self, **kwargs):
|
66
|
context = super(AgendaServiceActivityView, self).get_context_data(**kwargs)
|
67
|
|
68
|
appointments_times = dict()
|
69
|
appoinment_type = EventType.objects.get(id=1)
|
70
|
meeting_type = EventType.objects.get(id=2)
|
71
|
plain_events = Event.objects.for_today(self.date) \
|
72
|
.filter(services=self.service,
|
73
|
event_type__in=[appoinment_type, meeting_type])
|
74
|
events = [ e.today_occurence(self.date) for e in plain_events ]
|
75
|
for event in events:
|
76
|
start_datetime = event.start_datetime.strftime("%H:%M")
|
77
|
if not appointments_times.has_key(start_datetime):
|
78
|
appointments_times[start_datetime] = dict()
|
79
|
appointments_times[start_datetime]['row'] = 0
|
80
|
appointments_times[start_datetime]['appointments'] = []
|
81
|
appointment = dict()
|
82
|
length = event.end_datetime - event.start_datetime
|
83
|
if length.seconds:
|
84
|
length = length.seconds / 60
|
85
|
appointment['length'] = "%sm" % length
|
86
|
if event.event_type == EventType.objects.get(id=1):
|
87
|
appointment['type'] = 1
|
88
|
event_act = event.act
|
89
|
appointment['label'] = event_act.patient.display_name
|
90
|
appointment['act'] = event_act.act_type.name
|
91
|
elif event.event_type == EventType.objects.get(id=2):
|
92
|
appointment['type'] = 2
|
93
|
appointment['label'] = '%s - %s' % (event.event_type.label,
|
94
|
event.title)
|
95
|
else:
|
96
|
appointment['type'] = 0
|
97
|
appointment['label'] = '???'
|
98
|
appointment['participants'] = event.participants.all()
|
99
|
appointments_times[start_datetime]['row'] += 1
|
100
|
appointments_times[start_datetime]['appointments'].append(appointment)
|
101
|
context['appointments_times'] = sorted(appointments_times.items())
|
102
|
return context
|
103
|
|
104
|
|
105
|
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
|
106
|
model = EventWithAct
|
107
|
form_class = NewAppointmentForm
|
108
|
template_name = 'agenda/nouveau-rdv.html'
|
109
|
success_url = '..'
|
110
|
|
111
|
def get_initial(self):
|
112
|
initial = super(NewAppointmentView, self).get_initial()
|
113
|
initial['date'] = self.date
|
114
|
initial['participants'] = self.request.GET.getlist('participants')
|
115
|
initial['time'] = self.request.GET.get('time')
|
116
|
initial['room'] = self.request.GET.get('room')
|
117
|
return initial
|
118
|
|
119
|
|
120
|
class UpdateAppointmentView(UpdateView):
|
121
|
model = EventWithAct
|
122
|
form_class = UpdateAppointmentForm
|
123
|
template_name = 'agenda/update-rdv.html'
|
124
|
success_url = '..'
|
125
|
|
126
|
def get_initial(self):
|
127
|
initial = super(UpdateView, self).get_initial()
|
128
|
initial['date'] = self.object.start_datetime.strftime("%Y-%m-%d")
|
129
|
initial['time'] = self.object.start_datetime.strftime("%H:%M")
|
130
|
time = self.object.end_datetime - self.object.start_datetime
|
131
|
if time:
|
132
|
time = time.seconds / 60
|
133
|
else:
|
134
|
time = 0
|
135
|
initial['duration'] = time
|
136
|
initial['participants'] = self.object.participants.values_list('id', flat=True)
|
137
|
return initial
|
138
|
|
139
|
def get_form_kwargs(self):
|
140
|
kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
|
141
|
kwargs['service'] = self.service
|
142
|
return kwargs
|
143
|
|
144
|
|
145
|
class NewEventView(CreateView):
|
146
|
model = Event
|
147
|
form_class = NewEventForm
|
148
|
template_name = 'agenda/new-event.html'
|
149
|
success_url = '..'
|
150
|
|
151
|
def get_initial(self):
|
152
|
initial = super(NewEventView, self).get_initial()
|
153
|
initial['date'] = self.date
|
154
|
initial['participants'] = self.request.GET.getlist('participants')
|
155
|
initial['time'] = self.request.GET.get('time')
|
156
|
initial['services'] = [self.service]
|
157
|
initial['event_type'] = 2
|
158
|
initial['room'] = self.request.GET.get('room')
|
159
|
return initial
|
160
|
|
161
|
|
162
|
class UpdateEventView(UpdateView):
|
163
|
model = Event
|
164
|
form_class = NewEventForm
|
165
|
template_name = 'agenda/update-event.html'
|
166
|
success_url = '..'
|
167
|
|
168
|
def get_initial(self):
|
169
|
initial = super(UpdateEventView, self).get_initial()
|
170
|
initial['date'] = self.object.start_datetime.strftime("%Y-%m-%d")
|
171
|
initial['time'] = self.object.start_datetime.strftime("%H:%M")
|
172
|
time = self.object.end_datetime - self.object.start_datetime
|
173
|
if time:
|
174
|
time = time.seconds / 60
|
175
|
else:
|
176
|
time = 0
|
177
|
initial['duration'] = time
|
178
|
initial['participants'] = self.object.participants.values_list('id', flat=True)
|
179
|
return initial
|
180
|
|
181
|
|
182
|
class AgendaServiceActValidationView(TemplateView):
|
183
|
template_name = 'agenda/act-validation.html'
|
184
|
|
185
|
def acts_of_the_day(self):
|
186
|
return get_acts_of_the_day(self.date, self.service)
|
187
|
|
188
|
def post(self, request, *args, **kwargs):
|
189
|
if 'unlock-all' in request.POST:
|
190
|
#TODO: check that the user is authorized
|
191
|
unlock_all_acts_of_the_day(self.date, self.service)
|
192
|
ValidationMessage(validation_date=self.date,
|
193
|
who=request.user, what='Déverrouillage',
|
194
|
service=self.service).save()
|
195
|
else:
|
196
|
acte_id = request.POST.get('acte-id')
|
197
|
try:
|
198
|
act = Act.objects.get(id=acte_id)
|
199
|
if 'lock' in request.POST or 'unlock' in request.POST:
|
200
|
#TODO: check that the user is authorized
|
201
|
act.validation_locked = 'lock' in request.POST
|
202
|
act.save()
|
203
|
else:
|
204
|
state_name = request.POST.get('act_state')
|
205
|
act.set_state(state_name, request.user)
|
206
|
except Act.DoesNotExist:
|
207
|
pass
|
208
|
return HttpResponseRedirect('#acte-frame-'+acte_id)
|
209
|
return HttpResponseRedirect('')
|
210
|
|
211
|
def get_context_data(self, **kwargs):
|
212
|
context = super(AgendaServiceActValidationView, self).get_context_data(**kwargs)
|
213
|
authorized_lock = True # is_authorized_for_locking(get_request().user)
|
214
|
validation_msg = ValidationMessage.objects.\
|
215
|
filter(validation_date=self.date, service=self.service).\
|
216
|
order_by('-when')[:3]
|
217
|
acts_of_the_day = self.acts_of_the_day()
|
218
|
actes = list()
|
219
|
for act in acts_of_the_day:
|
220
|
state = act.get_state()
|
221
|
display_name = VALIDATION_STATES[state.state_name]
|
222
|
if not state.previous_state:
|
223
|
state = None
|
224
|
act.date = act.date.strftime("%H:%M")
|
225
|
actes.append((act, state, display_name))
|
226
|
context['validation_states'] = dict(VALIDATION_STATES)
|
227
|
if self.service.name != 'CMPP' and \
|
228
|
'ACT_DOUBLE' in context['validation_states']:
|
229
|
context['validation_states'].pop('ACT_DOUBLE')
|
230
|
context['actes'] = actes
|
231
|
context['validation_msg'] = validation_msg
|
232
|
context['authorized_lock'] = authorized_lock
|
233
|
return context
|
234
|
|
235
|
|
236
|
class AutomatedValidationView(TemplateView):
|
237
|
template_name = 'agenda/automated-validation.html'
|
238
|
|
239
|
def post(self, request, *args, **kwargs):
|
240
|
automated_validation(self.date, self.service,
|
241
|
request.user)
|
242
|
ValidationMessage(validation_date=self.date,
|
243
|
who=request.user, what='Validation automatique',
|
244
|
service=self.service).save()
|
245
|
return HttpResponseRedirect('..')
|
246
|
|
247
|
def get_context_data(self, **kwargs):
|
248
|
context = super(AutomatedValidationView, self).get_context_data(**kwargs)
|
249
|
request = self.request
|
250
|
(nb_acts_total, nb_acts_validated, nb_acts_double,
|
251
|
nb_acts_abs_non_exc, nb_acts_abs_exc, nb_acts_annul_nous,
|
252
|
nb_acts_annul_famille, nb_acts_reporte, nb_acts_abs_ess_pps,
|
253
|
nb_acts_enf_hosp) = \
|
254
|
automated_validation(self.date, self.service,
|
255
|
request.user, commit = False)
|
256
|
|
257
|
nb_acts_not_validated = nb_acts_double + \
|
258
|
nb_acts_abs_non_exc + \
|
259
|
nb_acts_abs_exc + \
|
260
|
nb_acts_annul_nous + \
|
261
|
nb_acts_annul_famille + \
|
262
|
nb_acts_reporte + \
|
263
|
nb_acts_abs_ess_pps + \
|
264
|
nb_acts_enf_hosp
|
265
|
context.update({
|
266
|
'nb_acts_total': nb_acts_total,
|
267
|
'nb_acts_validated': nb_acts_validated,
|
268
|
'nb_acts_not_validated': nb_acts_not_validated,
|
269
|
'nb_acts_double': nb_acts_double,
|
270
|
'nb_acts_abs_non_exc': nb_acts_abs_non_exc,
|
271
|
'nb_acts_abs_exc': nb_acts_abs_exc,
|
272
|
'nb_acts_annul_nous': nb_acts_annul_nous,
|
273
|
'nb_acts_annul_famille': nb_acts_annul_famille,
|
274
|
'nb_acts_reporte': nb_acts_reporte,
|
275
|
'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
|
276
|
'nb_acts_enf_hosp': nb_acts_enf_hosp})
|
277
|
return context
|
278
|
|
279
|
class UnlockAllView(CreateView):
|
280
|
pass
|
281
|
|
282
|
|
283
|
class AgendasTherapeutesView(AgendaHomepageView):
|
284
|
template_name = 'agenda/agendas-therapeutes.html'
|
285
|
|
286
|
def get_context_data(self, **kwargs):
|
287
|
context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
|
288
|
|
289
|
time_tables = TimeTable.objects.select_related('worker'). \
|
290
|
filter(services=self.service). \
|
291
|
for_today(self.date). \
|
292
|
order_by('start_date')
|
293
|
holidays = Holiday.objects.select_related('worker'). \
|
294
|
for_period(self.date, self.date). \
|
295
|
order_by('start_date')
|
296
|
plain_events = Event.objects.for_today(self.date) \
|
297
|
.order_by('start_datetime').select_subclasses()
|
298
|
events = [ e.today_occurence(self.date) for e in plain_events ]
|
299
|
|
300
|
events_workers = {}
|
301
|
time_tables_workers = {}
|
302
|
holidays_workers = {}
|
303
|
context['workers_agenda'] = []
|
304
|
for worker in context['workers']:
|
305
|
time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
|
306
|
events_worker = [o for o in events if worker.id in o.participants.values_list('id', flat=True)]
|
307
|
holidays_worker = [h for h in holidays if h.worker_id in (None, worker.id)]
|
308
|
events_workers[worker.id] = events_worker
|
309
|
time_tables_workers[worker.id] = time_tables_worker
|
310
|
holidays_workers[worker.id] = holidays_worker
|
311
|
context['workers_agenda'].append({'worker': worker,
|
312
|
'appointments': get_daily_appointments(context['date'], worker, self.service,
|
313
|
time_tables_worker, events_worker, holidays_worker)})
|
314
|
|
315
|
for worker_agenda in context.get('workers_agenda', []):
|
316
|
patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
|
317
|
worker_agenda['summary'] = {
|
318
|
'rdv': len(patient_appointments),
|
319
|
'presence': len([x for x in patient_appointments if x.act_absence is None]),
|
320
|
'absence': len([x for x in patient_appointments if x.act_absence is not None]),
|
321
|
'doubles': len([x for x in patient_appointments if x.act_type == 'ACT_DOUBLE']),
|
322
|
'valides': len([x for x in patient_appointments if x.act_type == 'ACT_VALIDE']),
|
323
|
}
|
324
|
|
325
|
return context
|
326
|
|
327
|
class JoursNonVerrouillesView(TemplateView):
|
328
|
template_name = 'agenda/days-not-locked.html'
|
329
|
|
330
|
def get_context_data(self, **kwargs):
|
331
|
context = super(JoursNonVerrouillesView, self).get_context_data(**kwargs)
|
332
|
acts = Act.objects.filter(is_billed=False,
|
333
|
patient__service=self.service).order_by('date')
|
334
|
days = set(acts.values_list('date', flat=True))
|
335
|
max_day, min_day = max(days), min(days)
|
336
|
days &= set(get_days_with_acts_not_locked(min_day, max_day, self.service))
|
337
|
context['days_not_locked'] = days
|
338
|
return context
|
339
|
|
340
|
class RessourcesView(TemplateView):
|
341
|
|
342
|
template_name = 'agenda/ressources.html'
|
343
|
|
344
|
def get_context_data(self, **kwargs):
|
345
|
context = super(RessourcesView, self).get_context_data(**kwargs)
|
346
|
|
347
|
plain_events = Event.objects.for_today(self.date) \
|
348
|
.order_by('start_datetime').select_subclasses()
|
349
|
events = [ e.today_occurence(self.date) for e in plain_events ]
|
350
|
|
351
|
context['ressources_types'] = []
|
352
|
context['ressources_agenda'] = []
|
353
|
context['disponibility'] = {}
|
354
|
ressources = []
|
355
|
data = {'type': Room._meta.verbose_name_plural, 'ressources': Room.objects.all() }
|
356
|
context['ressources_types'].append(data)
|
357
|
ressources.extend(data['ressources'])
|
358
|
|
359
|
events_ressources = {}
|
360
|
for ressource in ressources:
|
361
|
events_ressource = [e for e in events if ressource == e.room]
|
362
|
events_ressources[ressource.id] = events_ressource
|
363
|
context['ressources_agenda'].append({'ressource': ressource,
|
364
|
'appointments': get_daily_usage(context['date'], ressource,
|
365
|
self.service, events_ressource)})
|
366
|
|
367
|
return context
|
368
|
|
369
|
class AjaxWorkerTabView(TemplateView):
|
370
|
|
371
|
template_name = 'agenda/ajax-worker-tab.html'
|
372
|
|
373
|
def get_context_data(self, worker_id, **kwargs):
|
374
|
context = super(AjaxWorkerTabView, self).get_context_data(**kwargs)
|
375
|
worker_id = int(worker_id)
|
376
|
|
377
|
time_tables_worker = TimeTable.objects.select_related('worker'). \
|
378
|
filter(services=self.service, worker_id=worker_id). \
|
379
|
for_today(self.date). \
|
380
|
order_by('start_date')
|
381
|
holidays_worker = Holiday.objects.for_worker_id(worker_id). \
|
382
|
for_period(self.date, self.date). \
|
383
|
order_by('start_date')
|
384
|
plain_events = Event.objects.for_today(self.date) \
|
385
|
.order_by('start_datetime').select_subclasses()
|
386
|
events = [ e.today_occurence(self.date) for e in plain_events ]
|
387
|
events_worker = [e for e in events if worker_id in e.participants.values_list('id', flat=True)]
|
388
|
|
389
|
worker = Worker.objects.get(pk=worker_id)
|
390
|
context['worker_agenda'] = {'worker': worker,
|
391
|
'appointments': get_daily_appointments(context['date'], worker, self.service,
|
392
|
time_tables_worker, events_worker, holidays_worker)}
|
393
|
return context
|
394
|
|
395
|
class AjaxWorkerDisponibilityColumnView(TemplateView):
|
396
|
|
397
|
template_name = 'agenda/ajax-worker-disponibility-column.html'
|
398
|
|
399
|
def get_context_data(self, worker_id, **kwargs):
|
400
|
context = super(AjaxWorkerDisponibilityColumnView, self).get_context_data(**kwargs)
|
401
|
worker_id = int(worker_id)
|
402
|
|
403
|
time_tables_worker = TimeTable.objects.select_related('worker'). \
|
404
|
filter(services=self.service, worker_id=worker_id). \
|
405
|
for_today(self.date). \
|
406
|
order_by('start_date')
|
407
|
holidays_worker = Holiday.objects.for_worker_id(worker_id). \
|
408
|
for_period(self.date, self.date). \
|
409
|
order_by('start_date')
|
410
|
events = Event.objects.today_occurences(self.date)
|
411
|
events_worker = [e for e in events if worker_id in e.participants.values_list('id', flat=True)]
|
412
|
|
413
|
worker = Worker.objects.get(pk=worker_id)
|
414
|
time_tables_workers = {worker.id: time_tables_worker}
|
415
|
events_workers = {worker.id: events_worker}
|
416
|
holidays_workers = {worker.id: holidays_worker}
|
417
|
|
418
|
context['initials'] = worker.get_initials()
|
419
|
context['worker_id'] = worker.id
|
420
|
context['disponibility'] = Event.objects.daily_disponibilities(self.date,
|
421
|
events_workers, [worker], time_tables_workers, holidays_workers)
|
422
|
return context
|