Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ db33aecd

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, HttpResponse
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 = Worker.objects.filter(enabled=True).select_related() \
49
                .prefetch_related('services')
50
        worker_by_type = {}
51
        for worker in workers:
52
            workers_for_type = worker_by_type.setdefault(worker.type, [])
53
            workers_for_type.append(worker)
54
        for worker_type, workers_for_type in worker_by_type.iteritems():
55
            context['workers_types'].append(
56
                    {'type': worker_type.name, 'workers': workers_for_type })
57
        context['workers'] = workers
58
        context['disponibility_start_times'] = range(8, 20)
59

    
60
        return context
61

    
62
class AgendaServiceActivityView(TemplateView):
63

    
64
    template_name = 'agenda/service-activity.html'
65

    
66
    def get_context_data(self, **kwargs):
67
        context = super(AgendaServiceActivityView, self).get_context_data(**kwargs)
68

    
69
        appointments_times = dict()
70
        events = Event.objects.for_today(self.date) \
71
                .exclude(event_type_id=1) \
72
                .filter(services=self.service) \
73
                .order_by('start_datetime') \
74
                .select_related() \
75
                .prefetch_related('participants', 'exceptions')
76
        eventswithact = EventWithAct.objects.for_today(self.date) \
77
                .filter(services=self.service) \
78
                .order_by('start_datetime') \
79
                .select_related() \
80
                .prefetch_related('participants', 'exceptions')
81
        events = [ e.today_occurrence(self.date) for e in events ] \
82
             + [ e.today_occurrence(self.date) for e in eventswithact ]
83
        for event in events:
84
            start_datetime = event.start_datetime.strftime("%H:%M")
85
            if not appointments_times.has_key(start_datetime):
86
                appointments_times[start_datetime] = dict()
87
                appointments_times[start_datetime]['row'] = 0
88
                appointments_times[start_datetime]['appointments'] = []
89
            appointment = dict()
90
            length = event.end_datetime - event.start_datetime
91
            if length.seconds:
92
                length = length.seconds / 60
93
                appointment['length'] = "%sm" % length
94
            if event.event_type_id == 1:
95
                appointment['type'] = 1
96
                appointment['label'] = event.patient.display_name
97
                appointment['act'] = event.act_type.name
98
                appointment['state'] = event.act.get_state()
99
            else:
100
                appointment['type'] = 2
101
                if event.event_type.label == 'Autre' and event.title:
102
                    appointment['label'] = event.title
103
                else:
104
                    appointment['label'] = '%s - %s' % (event.event_type.label,
105
                                                        event.title)
106
            appointment['participants'] = event.participants.all()
107
            appointments_times[start_datetime]['row'] += 1
108
            appointments_times[start_datetime]['appointments'].append(appointment)
109
        context['appointments_times'] = sorted(appointments_times.items())
110
        return context
111

    
112

    
113
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
114
    model = EventWithAct
115
    form_class = NewAppointmentForm
116
    template_name = 'agenda/nouveau-rdv.html'
117
    success_url = '..'
118

    
119
    def get_initial(self):
120
        initial = super(NewAppointmentView, self).get_initial()
121
        initial['start_datetime'] = self.date
122
        initial['date'] = self.date
123
        initial['participants'] = self.request.GET.getlist('participants')
124
        initial['time'] = self.request.GET.get('time')
125
        initial['room'] = self.request.GET.get('room')
126
        return initial
127

    
128
    def get_form_kwargs(self):
129
        kwargs = super(NewAppointmentView, self).get_form_kwargs()
130
        kwargs['service'] = self.service
131
        return kwargs
132

    
133
class TodayOccurrenceMixin(object):
134
    def get_object(self, queryset=None):
135
        o = super(TodayOccurrenceMixin, self).get_object(queryset)
136
        return o.today_occurrence(self.date)
137

    
138
class UpdateAppointmentView(TodayOccurrenceMixin, UpdateView):
139
    model = EventWithAct
140
    form_class = UpdateAppointmentForm
141
    template_name = 'agenda/update-rdv.html'
142
    success_url = '..'
143

    
144
    def get_initial(self):
145
        initial = super(UpdateView, self).get_initial()
146
        initial['start_datetime'] = self.date
147
        initial['date'] = self.object.start_datetime.date()
148
        initial['time'] = self.object.start_datetime.time()
149
        time = self.object.end_datetime - self.object.start_datetime
150
        if time:
151
            time = time.seconds / 60
152
        else:
153
            time = 0
154
        initial['duration'] = time
155
        initial['participants'] = self.object.participants.values_list('id', flat=True)
156
        return initial
157

    
158
    def get_form_kwargs(self):
159
        kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
160
        kwargs['service'] = self.service
161
        return kwargs
162

    
163

    
164
class NewEventView(CreateView):
165
    model = Event
166
    form_class = NewEventForm
167
    template_name = 'agenda/new-event.html'
168
    success_url = '..'
169

    
170
    def get_initial(self):
171
        initial = super(NewEventView, self).get_initial()
172
        initial['start_datetime'] = self.date
173
        initial['date'] = self.date
174
        initial['participants'] = self.request.GET.getlist('participants')
175
        initial['time'] = self.request.GET.get('time')
176
        initial['event_type'] = 2
177
        initial['room'] = self.request.GET.get('room')
178
        return initial
179

    
180
    def get_form_kwargs(self):
181
        kwargs = super(NewEventView, self).get_form_kwargs()
182
        kwargs['service'] = self.service
183
        return kwargs
184

    
185

    
186
class UpdateEventView(TodayOccurrenceMixin, UpdateView):
187
    model = Event
188
    form_class = NewEventForm
189
    template_name = 'agenda/update-event.html'
190
    success_url = '..'
191

    
192
    def get_initial(self):
193
        initial = super(UpdateEventView, self).get_initial()
194
        initial['start_datetime'] = self.date
195
        initial['date'] = self.object.start_datetime.date()
196
        initial['time'] = self.object.start_datetime.time()
197
        time = self.object.end_datetime - self.object.start_datetime
198
        if time:
199
            time = time.seconds / 60
200
        else:
201
            time = 0
202
        initial['duration'] = time
203
        initial['participants'] = self.object.participants.values_list('id', flat=True)
204
        return initial
205

    
206
    def get_form_kwargs(self):
207
        kwargs = super(UpdateEventView, self).get_form_kwargs()
208
        kwargs['service'] = self.service
209
        return kwargs
210

    
211
class DeleteEventView(TodayOccurrenceMixin, cbv.DeleteView):
212
    model = Event
213
    success_url = '..'
214

    
215
    def delete(self, request, *args, **kwargs):
216
        super(DeleteEventView, self).delete(request, *args, **kwargs)
217
        return HttpResponse(status=204)
218

    
219
class AgendaServiceActValidationView(TemplateView):
220
    template_name = 'agenda/act-validation.html'
221

    
222
    def acts_of_the_day(self):
223
        acts = [e.act for e in EventWithAct.objects.filter(patient__service=self.service)
224
                .today_occurrences(self.date)] + list(Act.objects.filter(date=self.date, parent_event__isnull=True))
225
        return sorted(acts, key=lambda a: a.time)
226

    
227
    def post(self, request, *args, **kwargs):
228
        if 'unlock-all' in request.POST:
229
            #TODO: check that the user is authorized
230
            unlock_all_acts_of_the_day(self.date, self.service)
231
            ValidationMessage(validation_date=self.date,
232
                who=request.user, what='Déverrouillage',
233
                service=self.service).save()
234
        else:
235
            acte_id = request.POST.get('acte-id')
236
            try:
237
                act = Act.objects.get(id=acte_id)
238
                if 'lock' in request.POST or 'unlock' in request.POST:
239
                    #TODO: check that the user is authorized
240
                    act.validation_locked = 'lock' in request.POST
241
                    act.save()
242
                else:
243
                    state_name = request.POST.get('act_state')
244
                    act.set_state(state_name, request.user)
245
            except Act.DoesNotExist:
246
                pass
247
            return HttpResponseRedirect('#acte-frame-'+acte_id)
248
        return HttpResponseRedirect('')
249

    
250
    def get_context_data(self, **kwargs):
251
        context = super(AgendaServiceActValidationView, self).get_context_data(**kwargs)
252
        authorized_lock = True # is_authorized_for_locking(get_request().user)
253
        validation_msg = ValidationMessage.objects.\
254
            filter(validation_date=self.date, service=self.service).\
255
            order_by('-when')[:3]
256
        acts_of_the_day = self.acts_of_the_day()
257
        actes = list()
258
        for act in acts_of_the_day:
259
            state = act.get_state()
260
            display_name = VALIDATION_STATES[state.state_name]
261
            if not state.previous_state and state.state_name == 'NON_VALIDE':
262
                state = None
263
            actes.append((act, state, display_name))
264
        validation_states = dict(VALIDATION_STATES)
265
        if self.service.name != 'CMPP' and \
266
                'ACT_DOUBLE' in validation_states:
267
            validation_states.pop('ACT_DOUBLE')
268
        vs = [('VALIDE', 'Présent')]
269
        validation_states.pop('VALIDE')
270
        validation_states = vs + sorted(validation_states.items(), key=lambda tup: tup[0])
271
        context['validation_states'] = validation_states
272
        context['actes'] = actes
273
        context['validation_msg'] = validation_msg
274
        context['authorized_lock'] = authorized_lock
275
        return context
276

    
277

    
278
class AutomatedValidationView(TemplateView):
279
    template_name = 'agenda/automated-validation.html'
280

    
281
    def post(self, request, *args, **kwargs):
282
        automated_validation(self.date, self.service,
283
            request.user)
284
        ValidationMessage(validation_date=self.date,
285
            who=request.user, what='Validation automatique',
286
            service=self.service).save()
287
        return HttpResponseRedirect('..')
288

    
289
    def get_context_data(self, **kwargs):
290
        context = super(AutomatedValidationView, self).get_context_data(**kwargs)
291
        request = self.request
292
        (nb_acts_total, nb_acts_validated, nb_acts_double,
293
        nb_acts_abs_non_exc, nb_acts_abs_exc, nb_acts_abs_inter, nb_acts_annul_nous,
294
        nb_acts_annul_famille, nb_acts_reporte, nb_acts_abs_ess_pps,
295
        nb_acts_enf_hosp, nb_acts_losts) = \
296
            automated_validation(self.date, self.service,
297
                request.user, commit = False)
298

    
299
        nb_acts_not_validated = nb_acts_double + \
300
            nb_acts_abs_non_exc + \
301
            nb_acts_abs_exc + \
302
            nb_acts_abs_inter + \
303
            nb_acts_annul_nous + \
304
            nb_acts_annul_famille + \
305
            nb_acts_reporte + \
306
            nb_acts_abs_ess_pps + \
307
            nb_acts_enf_hosp + \
308
            nb_acts_losts
309
        context.update({
310
            'nb_acts_total': nb_acts_total,
311
            'nb_acts_validated': nb_acts_validated,
312
            'nb_acts_not_validated': nb_acts_not_validated,
313
            'nb_acts_double': nb_acts_double,
314
            'nb_acts_abs_non_exc': nb_acts_abs_non_exc,
315
            'nb_acts_abs_exc': nb_acts_abs_exc,
316
            'nb_acts_abs_inter': nb_acts_abs_inter,
317
            'nb_acts_annul_nous': nb_acts_annul_nous,
318
            'nb_acts_annul_famille': nb_acts_annul_famille,
319
            'nb_acts_reporte': nb_acts_reporte,
320
            'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
321
            'nb_acts_enf_hosp': nb_acts_enf_hosp,
322
            'nb_acts_losts': nb_acts_losts})
323
        return context
324

    
325
class UnlockAllView(CreateView):
326
    pass
327

    
328

    
329
class AgendasTherapeutesView(AgendaHomepageView):
330
    template_name = 'agenda/agendas-therapeutes.html'
331

    
332
    def get_context_data(self, **kwargs):
333
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
334

    
335
        time_tables = TimeTable.objects.select_related('worker'). \
336
                filter(services=self.service). \
337
                for_today(self.date). \
338
                order_by('start_date')
339
        holidays = Holiday.objects.select_related('worker') \
340
                .for_period(self.date, self.date) \
341
                .order_by('start_date') \
342
                .select_related()
343
        events = Event.objects.for_today(self.date) \
344
                .exclude(event_type_id=1) \
345
                .filter(services=self.service) \
346
                .order_by('start_datetime') \
347
                .select_related() \
348
                .prefetch_related('services',
349
                        'exceptions',
350
                        'participants')
351
        eventswithact = EventWithAct.objects.for_today(self.date) \
352
                .filter(services=self.service) \
353
                .order_by('start_datetime') \
354
                .select_related() \
355
                .prefetch_related(
356
                        'services',
357
                        'patient__service',
358
                        'act_set__actvalidationstate_set', 
359
                        'exceptions', 'participants')
360
        events = [ e.today_occurrence(self.date) for e in events ] \
361
             + [ e.today_occurrence(self.date) for e in eventswithact ]
362
        for e in events:
363
            e.workers_ids = set(p.id for p in e.participants.all())
364

    
365
        events_workers = {}
366
        time_tables_workers = {}
367
        holidays_workers = {}
368
        context['workers_agenda'] = []
369
        context['workers'] = context['workers'].filter(services=self.service)
370
        for worker in context['workers']:
371
            time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
372
            events_worker = [o for o in events if worker.id in o.workers_ids ]
373
            holidays_worker = [h for h in holidays if h.worker_id in (None, worker.id)]
374
            events_workers[worker.id] = events_worker
375
            time_tables_workers[worker.id] = time_tables_worker
376
            holidays_workers[worker.id] = holidays_worker
377
            daily_appointments = get_daily_appointments(context['date'], worker, self.service,
378
                        time_tables_worker, events_worker, holidays_worker)
379
            if all(map(lambda x: x.holiday, daily_appointments)):
380
                continue
381
            context['workers_agenda'].append({'worker': worker,
382
                    'appointments': daily_appointments})
383

    
384
        for worker_agenda in context.get('workers_agenda', []):
385
            patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
386
            worker_agenda['summary'] = {
387
              'rdv': len(patient_appointments),
388
              'presence': len([x for x in patient_appointments if x.act_absence is None]),
389
              'absence': len([x for x in patient_appointments if x.act_absence is not None]),
390
              'doubles': len([x for x in patient_appointments if x.act_type == 'ACT_DOUBLE']),
391
              'valides': len([x for x in patient_appointments if x.act_type == 'ACT_VALIDE']),
392
            }
393

    
394
        return context
395

    
396
class JoursNonVerrouillesView(TemplateView):
397
    template_name = 'agenda/days-not-locked.html'
398

    
399
    def get_context_data(self, **kwargs):
400
        context = super(JoursNonVerrouillesView, self).get_context_data(**kwargs)
401
        acts = Act.objects.filter(is_billed=False,
402
            patient__service=self.service).order_by('date')
403
        days = set(acts.values_list('date', flat=True))
404
        if days:
405
            max_day, min_day = max(days), min(days)
406
            today = datetime.datetime.today().date()
407
            if max_day > today:
408
                max_day = today
409
            days &= set(get_days_with_acts_not_locked(min_day, max_day, self.service))
410
        context['days_not_locked'] = sorted(days)
411
        return context
412

    
413
class RessourcesView(TemplateView):
414

    
415
    template_name = 'agenda/ressources.html'
416

    
417
    def get_context_data(self, **kwargs):
418
        context = super(RessourcesView, self).get_context_data(**kwargs)
419

    
420
        plain_events = Event.objects.for_today(self.date) \
421
                .order_by('start_datetime').select_subclasses()
422
        events = [ e.today_occurrence(self.date) for e in plain_events ]
423

    
424
        context['ressources_types'] = []
425
        context['ressources_agenda'] = []
426
        context['disponibility'] = {}
427
        ressources = []
428
        data = {'type': Room._meta.verbose_name_plural, 'ressources': Room.objects.all() }
429
        context['ressources_types'].append(data)
430
        ressources.extend(data['ressources'])
431

    
432
        events_ressources = {}
433
        for ressource in ressources:
434
            events_ressource = [e for e in events if ressource == e.room]
435
            events_ressources[ressource.id] = events_ressource
436
            context['ressources_agenda'].append({'ressource': ressource,
437
                    'appointments': get_daily_usage(context['date'], ressource,
438
                        self.service, events_ressource)})
439

    
440
        return context
441

    
442
class AjaxWorkerTabView(TemplateView):
443

    
444
    template_name = 'agenda/ajax-worker-tab.html'
445

    
446
    def get_context_data(self, worker_id, **kwargs):
447
        context = super(AjaxWorkerTabView, self).get_context_data(**kwargs)
448
        worker = Worker.objects.get(id=worker_id)
449

    
450
        time_tables_worker = TimeTable.objects.select_related('worker'). \
451
                filter(services=self.service, worker=worker) \
452
                .for_today(self.date) \
453
                .order_by('start_date') \
454
                .select_related()
455
        holidays_worker = Holiday.objects.for_worker(worker) \
456
                .for_period(self.date, self.date) \
457
                .order_by('start_date') \
458
                .select_related()
459
        events = Event.objects.for_today(self.date) \
460
                .exclude(event_type_id=1) \
461
                .filter(participants=worker) \
462
                .order_by('start_datetime') \
463
                .select_related() \
464
                .prefetch_related('services',
465
                        'exceptions',
466
                        'participants')
467
        eventswithact = EventWithAct.objects.for_today(self.date) \
468
                .filter(participants=worker) \
469
                .order_by('start_datetime') \
470
                .select_related() \
471
                .prefetch_related('patient__addresses',
472
                        'patient__addresses__patientcontact_set',
473
                        'services',
474
                        'patient__service',
475
                        'act_set__actvalidationstate_set', 
476
                        'exceptions', 'participants')
477
        events = [ e.today_occurrence(self.date) for e in events ] \
478
             + [ e.today_occurrence(self.date) for e in eventswithact ]
479

    
480
        context['worker_agenda'] = {'worker': worker,
481
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
482
                        time_tables_worker, events, holidays_worker)}
483
        return context
484

    
485
class AjaxWorkerDisponibilityColumnView(TemplateView):
486

    
487
    template_name = 'agenda/ajax-worker-disponibility-column.html'
488

    
489
    def get_context_data(self, worker_id, **kwargs):
490
        context = super(AjaxWorkerDisponibilityColumnView, self).get_context_data(**kwargs)
491
        worker = Worker.objects.get(pk=worker_id)
492

    
493
        time_tables_worker = TimeTable.objects.select_related('worker'). \
494
                filter(services=self.service, worker=worker). \
495
                for_today(self.date). \
496
                order_by('start_date')
497
        holidays_worker = Holiday.objects.for_worker(worker). \
498
                for_period(self.date, self.date). \
499
                order_by('start_date')
500
        events = Event.objects.for_today(self.date) \
501
                .exclude(event_type_id=1) \
502
                .filter(participants=worker) \
503
                .order_by('start_datetime') \
504
                .select_related() \
505
                .prefetch_related('participants', 'exceptions')
506
        eventswithact = EventWithAct.objects.for_today(self.date) \
507
                .filter(participants=worker) \
508
                .order_by('start_datetime') \
509
                .select_related() \
510
                .prefetch_related('participants', 'exceptions',
511
                        'act_set__actvalidationstate_set')
512

    
513
        events = list(events) + list(eventswithact)
514
        events = [ e.today_occurrence(self.date) for e in events ]
515
        time_tables_workers = {worker.id: time_tables_worker}
516
        events_workers = {worker.id: events}
517
        holidays_workers = {worker.id: holidays_worker}
518

    
519
        context['initials'] = worker.get_initials()
520
        context['worker_id'] = worker.id
521
        context['disponibility'] = Event.objects.daily_disponibilities(self.date,
522
                events_workers, [worker], time_tables_workers, holidays_workers)
523
        return context
(10-10/10)