Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ a50df9c4

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, UpdateEventForm)
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('event-id')
35
        try:
36
            event = EventWithAct.objects.get(id=acte_id)
37
            event = event.today_occurrence(self.date)
38
            act = event.act
39
            if not act.validation_locked:
40
                state_name = request.POST.get('act_state')
41
                act.save()
42
                act.set_state(state_name, request.user)
43
        except Act.DoesNotExist:
44
            pass
45
        return HttpResponseRedirect('#acte-frame-'+acte_id)
46

    
47
    def get_context_data(self, **kwargs):
48
        context = super(AgendaHomepageView, self).get_context_data(**kwargs)
49

    
50
        context['workers_types'] = []
51
        workers = Worker.objects.filter(enabled=True).select_related() \
52
                .prefetch_related('services')
53
        worker_by_type = {}
54
        for worker in workers:
55
            workers_for_type = worker_by_type.setdefault(worker.type, [])
56
            workers_for_type.append(worker)
57
        for worker_type, workers_for_type in worker_by_type.iteritems():
58
            context['workers_types'].append(
59
                    {'type': worker_type.name, 'workers': workers_for_type })
60
        context['workers'] = workers
61
        context['disponibility_start_times'] = range(8, 20)
62

    
63
        return context
64

    
65
class AgendaServiceActivityView(TemplateView):
66

    
67
    template_name = 'agenda/service-activity.html'
68

    
69
    def get_context_data(self, **kwargs):
70
        context = super(AgendaServiceActivityView, self).get_context_data(**kwargs)
71

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

    
118

    
119
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
120
    model = EventWithAct
121
    form_class = NewAppointmentForm
122
    template_name = 'agenda/nouveau-rdv.html'
123
    success_url = '..'
124

    
125
    def get_initial(self):
126
        initial = super(NewAppointmentView, self).get_initial()
127
        initial['start_datetime'] = self.date
128
        initial['date'] = self.date
129
        initial['participants'] = self.request.GET.getlist('participants')
130
        initial['time'] = self.request.GET.get('time')
131
        initial['room'] = self.request.GET.get('room')
132
        return initial
133

    
134
    def get_form_kwargs(self):
135
        kwargs = super(NewAppointmentView, self).get_form_kwargs()
136
        kwargs['service'] = self.service
137
        return kwargs
138

    
139
class TodayOccurrenceMixin(object):
140
    def get_object(self, queryset=None):
141
        o = super(TodayOccurrenceMixin, self).get_object(queryset)
142
        return o.today_occurrence(self.date)
143

    
144
class UpdateAppointmentView(TodayOccurrenceMixin, UpdateView):
145
    model = EventWithAct
146
    form_class = UpdateAppointmentForm
147
    template_name = 'agenda/update-rdv.html'
148
    success_url = '..'
149

    
150
    def get_initial(self):
151
        initial = super(UpdateView, self).get_initial()
152
        initial['start_datetime'] = self.date
153
        initial['date'] = self.object.start_datetime.date()
154
        initial['time'] = self.object.start_datetime.time()
155
        time = self.object.end_datetime - self.object.start_datetime
156
        if time:
157
            time = time.seconds / 60
158
        else:
159
            time = 0
160
        initial['duration'] = time
161
        initial['participants'] = self.object.participants.values_list('id', flat=True)
162
        return initial
163

    
164
    def get_form_kwargs(self):
165
        kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
166
        kwargs['service'] = self.service
167
        return kwargs
168

    
169

    
170
class NewEventView(CreateView):
171
    model = Event
172
    form_class = NewEventForm
173
    template_name = 'agenda/new-event.html'
174
    success_url = '..'
175

    
176
    def get_initial(self):
177
        initial = super(NewEventView, self).get_initial()
178
        initial['start_datetime'] = self.date
179
        initial['date'] = self.date
180
        initial['participants'] = self.request.GET.getlist('participants')
181
        initial['time'] = self.request.GET.get('time')
182
        initial['event_type'] = 2
183
        initial['room'] = self.request.GET.get('room')
184
        return initial
185

    
186
    def get_form_kwargs(self):
187
        kwargs = super(NewEventView, self).get_form_kwargs()
188
        kwargs['service'] = self.service
189
        return kwargs
190

    
191

    
192
class UpdateEventView(TodayOccurrenceMixin, UpdateView):
193
    model = Event
194
    form_class = UpdateEventForm
195
    template_name = 'agenda/update-event.html'
196
    success_url = '..'
197

    
198
    def get_initial(self):
199
        initial = super(UpdateEventView, self).get_initial()
200
        initial['start_datetime'] = self.date
201
        initial['date'] = self.object.start_datetime.date()
202
        initial['time'] = self.object.start_datetime.time()
203
        time = self.object.end_datetime - self.object.start_datetime
204
        if time:
205
            time = time.seconds / 60
206
        else:
207
            time = 0
208
        initial['duration'] = time
209
        initial['participants'] = self.object.participants.values_list('id', flat=True)
210
        return initial
211

    
212
    def get_form_kwargs(self):
213
        kwargs = super(UpdateEventView, self).get_form_kwargs()
214
        kwargs['service'] = self.service
215
        return kwargs
216

    
217
class DeleteEventView(TodayOccurrenceMixin, cbv.DeleteView):
218
    model = Event
219
    success_url = '..'
220

    
221
    def delete(self, request, *args, **kwargs):
222
        super(DeleteEventView, self).delete(request, *args, **kwargs)
223
        return HttpResponse(status=204)
224

    
225
class AgendaServiceActValidationView(TemplateView):
226
    template_name = 'agenda/act-validation.html'
227

    
228
    def acts_of_the_day(self):
229
        acts = [e.act for e in EventWithAct.objects.filter(patient__service=self.service)
230
                .today_occurrences(self.date)] + list(Act.objects.filter(date=self.date, parent_event__isnull=True))
231
        return sorted(acts, key=lambda a: a.time or datetime.time.min)
232

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

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

    
288

    
289
class AutomatedValidationView(TemplateView):
290
    template_name = 'agenda/automated-validation.html'
291

    
292
    def post(self, request, *args, **kwargs):
293
        automated_validation(self.date, self.service,
294
            request.user)
295
        ValidationMessage(validation_date=self.date,
296
            who=request.user, what='Validation automatique',
297
            service=self.service).save()
298
        return HttpResponseRedirect('..')
299

    
300
    def get_context_data(self, **kwargs):
301
        context = super(AutomatedValidationView, self).get_context_data(**kwargs)
302
        request = self.request
303
        (nb_acts_total, nb_acts_validated, nb_acts_double,
304
        nb_acts_abs_non_exc, nb_acts_abs_exc, nb_acts_abs_inter, nb_acts_annul_nous,
305
        nb_acts_annul_famille, nb_acts_reporte, nb_acts_abs_ess_pps,
306
        nb_acts_enf_hosp, nb_acts_losts) = \
307
            automated_validation(self.date, self.service,
308
                request.user, commit = False)
309

    
310
        nb_acts_not_validated = nb_acts_double + \
311
            nb_acts_abs_non_exc + \
312
            nb_acts_abs_exc + \
313
            nb_acts_abs_inter + \
314
            nb_acts_annul_nous + \
315
            nb_acts_annul_famille + \
316
            nb_acts_reporte + \
317
            nb_acts_abs_ess_pps + \
318
            nb_acts_enf_hosp + \
319
            nb_acts_losts
320
        context.update({
321
            'nb_acts_total': nb_acts_total,
322
            'nb_acts_validated': nb_acts_validated,
323
            'nb_acts_not_validated': nb_acts_not_validated,
324
            'nb_acts_double': nb_acts_double,
325
            'nb_acts_abs_non_exc': nb_acts_abs_non_exc,
326
            'nb_acts_abs_exc': nb_acts_abs_exc,
327
            'nb_acts_abs_inter': nb_acts_abs_inter,
328
            'nb_acts_annul_nous': nb_acts_annul_nous,
329
            'nb_acts_annul_famille': nb_acts_annul_famille,
330
            'nb_acts_reporte': nb_acts_reporte,
331
            'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
332
            'nb_acts_enf_hosp': nb_acts_enf_hosp,
333
            'nb_acts_losts': nb_acts_losts})
334
        return context
335

    
336
class UnlockAllView(CreateView):
337
    pass
338

    
339

    
340
class AgendasTherapeutesView(AgendaHomepageView):
341
    template_name = 'agenda/agendas-therapeutes.html'
342

    
343
    def get_context_data(self, **kwargs):
344
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
345

    
346
        time_tables = TimeTable.objects.select_related('worker'). \
347
                filter(services=self.service). \
348
                for_today(self.date). \
349
                order_by('start_date')
350
        holidays = Holiday.objects.select_related('worker') \
351
                .for_period(self.date, self.date) \
352
                .order_by('start_date') \
353
                .select_related()
354
        events = Event.objects.for_today(self.date) \
355
                .exclude(event_type_id=1) \
356
                .filter(services=self.service) \
357
                .order_by('start_datetime') \
358
                .select_related() \
359
                .prefetch_related('services',
360
                        'exceptions',
361
                        'participants')
362
        eventswithact = EventWithAct.objects.for_today(self.date) \
363
                .filter(services=self.service) \
364
                .order_by('start_datetime') \
365
                .select_related() \
366
                .prefetch_related(
367
                        'services',
368
                        'patient__service',
369
                        'act_set__actvalidationstate_set',
370
                        'exceptions', 'participants')
371
        events = [ e.today_occurrence(self.date) for e in events ] \
372
             + [ e.today_occurrence(self.date) for e in eventswithact ]
373
        for e in events:
374
            e.workers_ids = set(p.id for p in e.participants.all())
375

    
376
        events_workers = {}
377
        time_tables_workers = {}
378
        holidays_workers = {}
379
        context['workers_agenda'] = []
380
        context['workers'] = context['workers'].filter(services=self.service)
381
        for worker in context['workers']:
382
            time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
383
            events_worker = [o for o in events if worker.id in o.workers_ids ]
384
            holidays_worker = [h for h in holidays if h.worker_id in (None, worker.id)]
385
            events_workers[worker.id] = events_worker
386
            time_tables_workers[worker.id] = time_tables_worker
387
            holidays_workers[worker.id] = holidays_worker
388
            daily_appointments = get_daily_appointments(context['date'], worker, self.service,
389
                        time_tables_worker, events_worker, holidays_worker)
390
            if all(map(lambda x: x.holiday, daily_appointments)):
391
                continue
392
            context['workers_agenda'].append({'worker': worker,
393
                    'appointments': daily_appointments})
394

    
395
        for worker_agenda in context.get('workers_agenda', []):
396
            patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
397
            worker_agenda['summary'] = {
398
              'rdv': len(patient_appointments),
399
              'presence': len([x for x in patient_appointments if x.act_absence is None]),
400
              'absence': len([x for x in patient_appointments if x.act_absence is not None]),
401
              'doubles': len([x for x in patient_appointments if x.act_type == 'ACT_DOUBLE']),
402
              'valides': len([x for x in patient_appointments if x.act_type == 'ACT_VALIDE']),
403
            }
404

    
405
        return context
406

    
407
class JoursNonVerrouillesView(TemplateView):
408
    template_name = 'agenda/days-not-locked.html'
409

    
410
    def get_context_data(self, **kwargs):
411
        context = super(JoursNonVerrouillesView, self).get_context_data(**kwargs)
412
        acts = Act.objects.filter(is_billed=False,
413
            patient__service=self.service).order_by('date')
414
        days = set(acts.values_list('date', flat=True))
415
        if days:
416
            max_day, min_day = max(days), min(days)
417
            today = datetime.datetime.today().date()
418
            if max_day > today:
419
                max_day = today
420
            days &= set(get_days_with_acts_not_locked(min_day, max_day, self.service))
421
        context['days_not_locked'] = sorted(days)
422
        return context
423

    
424
class RessourcesView(TemplateView):
425

    
426
    template_name = 'agenda/ressources.html'
427

    
428
    def get_context_data(self, **kwargs):
429
        context = super(RessourcesView, self).get_context_data(**kwargs)
430

    
431
        plain_events = Event.objects.for_today(self.date) \
432
                .order_by('start_datetime').select_subclasses()
433
        events = [ e.today_occurrence(self.date) for e in plain_events ]
434

    
435
        context['ressources_types'] = []
436
        context['ressources_agenda'] = []
437
        context['disponibility'] = {}
438
        ressources = []
439
        data = {'type': Room._meta.verbose_name_plural, 'ressources': Room.objects.all() }
440
        context['ressources_types'].append(data)
441
        ressources.extend(data['ressources'])
442

    
443
        events_ressources = {}
444
        for ressource in ressources:
445
            events_ressource = [e for e in events if ressource == e.room]
446
            events_ressources[ressource.id] = events_ressource
447
            context['ressources_agenda'].append({'ressource': ressource,
448
                    'appointments': get_daily_usage(context['date'], ressource,
449
                        self.service, events_ressource)})
450

    
451
        return context
452

    
453
class AjaxWorkerTabView(TemplateView):
454

    
455
    template_name = 'agenda/ajax-worker-tab.html'
456

    
457
    def get_context_data(self, worker_id, **kwargs):
458
        context = super(AjaxWorkerTabView, self).get_context_data(**kwargs)
459
        worker = Worker.objects.get(id=worker_id)
460

    
461
        time_tables_worker = TimeTable.objects.select_related('worker'). \
462
                filter(services=self.service, worker=worker) \
463
                .for_today(self.date) \
464
                .order_by('start_date') \
465
                .select_related()
466
        holidays_worker = Holiday.objects.for_worker(worker) \
467
                .for_period(self.date, self.date) \
468
                .order_by('start_date') \
469
                .select_related()
470
        events = Event.objects.for_today(self.date) \
471
                .exclude(event_type_id=1) \
472
                .filter(participants=worker) \
473
                .order_by('start_datetime') \
474
                .select_related() \
475
                .prefetch_related('services',
476
                        'exceptions',
477
                        'participants')
478
        eventswithact = EventWithAct.objects.for_today(self.date) \
479
                .filter(participants=worker) \
480
                .order_by('start_datetime') \
481
                .select_related() \
482
                .prefetch_related('patient__addresses',
483
                        'patient__addresses__patientcontact_set',
484
                        'services',
485
                        'patient__service',
486
                        'act_set__actvalidationstate_set',
487
                        'exceptions', 'participants')
488
        events = [ e.today_occurrence(self.date) for e in events ] \
489
             + [ e.today_occurrence(self.date) for e in eventswithact ]
490

    
491
        context['worker_agenda'] = {'worker': worker,
492
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
493
                        time_tables_worker, events, holidays_worker)}
494
        return context
495

    
496
class AjaxWorkerDisponibilityColumnView(TemplateView):
497

    
498
    template_name = 'agenda/ajax-worker-disponibility-column.html'
499

    
500
    def get_context_data(self, worker_id, **kwargs):
501
        context = super(AjaxWorkerDisponibilityColumnView, self).get_context_data(**kwargs)
502
        worker = Worker.objects.get(pk=worker_id)
503

    
504
        time_tables_worker = TimeTable.objects.select_related('worker'). \
505
                filter(services=self.service, worker=worker). \
506
                for_today(self.date). \
507
                order_by('start_date')
508
        holidays_worker = Holiday.objects.for_worker(worker). \
509
                for_period(self.date, self.date). \
510
                order_by('start_date')
511
        events = Event.objects.for_today(self.date) \
512
                .exclude(event_type_id=1) \
513
                .filter(participants=worker) \
514
                .order_by('start_datetime') \
515
                .select_related() \
516
                .prefetch_related('participants', 'exceptions')
517
        eventswithact = EventWithAct.objects.for_today(self.date) \
518
                .filter(participants=worker) \
519
                .order_by('start_datetime') \
520
                .select_related() \
521
                .prefetch_related('participants', 'exceptions',
522
                        'act_set__actvalidationstate_set')
523

    
524
        events = list(events) + list(eventswithact)
525
        events = [ e.today_occurrence(self.date) for e in events ]
526
        time_tables_workers = {worker.id: time_tables_worker}
527
        events_workers = {worker.id: events}
528
        holidays_workers = {worker.id: holidays_worker}
529

    
530
        context['initials'] = worker.get_initials()
531
        context['worker_id'] = worker.id
532
        context['disponibility'] = Event.objects.daily_disponibilities(self.date,
533
                events_workers, [worker], time_tables_workers, holidays_workers)
534
        return context
(10-10/10)