Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ 15a79142

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
            state = act.get_state()
266
            display_name = VALIDATION_STATES[state.state_name]
267
            if not state.previous_state and state.state_name == 'NON_VALIDE':
268
                state = None
269
            actes.append((act, state, display_name))
270
            if not act.id:
271
                act.save()
272
        validation_states = dict(VALIDATION_STATES)
273
        if self.service.name != 'CMPP' and \
274
                'ACT_DOUBLE' in validation_states:
275
            validation_states.pop('ACT_DOUBLE')
276
        vs = [('VALIDE', 'Présent')]
277
        validation_states.pop('VALIDE')
278
        validation_states = vs + sorted(validation_states.items(), key=lambda tup: tup[0])
279
        context['validation_states'] = validation_states
280
        context['actes'] = actes
281
        context['validation_msg'] = validation_msg
282
        context['authorized_lock'] = authorized_lock
283
        return context
284

    
285

    
286
class AutomatedValidationView(TemplateView):
287
    template_name = 'agenda/automated-validation.html'
288

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

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

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

    
333
class UnlockAllView(CreateView):
334
    pass
335

    
336

    
337
class AgendasTherapeutesView(AgendaHomepageView):
338
    template_name = 'agenda/agendas-therapeutes.html'
339

    
340
    def get_context_data(self, **kwargs):
341
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
342

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

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

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

    
402
        return context
403

    
404
class JoursNonVerrouillesView(TemplateView):
405
    template_name = 'agenda/days-not-locked.html'
406

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

    
421
class RessourcesView(TemplateView):
422

    
423
    template_name = 'agenda/ressources.html'
424

    
425
    def get_context_data(self, **kwargs):
426
        context = super(RessourcesView, self).get_context_data(**kwargs)
427

    
428
        plain_events = Event.objects.for_today(self.date) \
429
                .order_by('start_datetime').select_subclasses()
430
        events = [ e.today_occurrence(self.date) for e in plain_events ]
431

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

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

    
448
        return context
449

    
450
class AjaxWorkerTabView(TemplateView):
451

    
452
    template_name = 'agenda/ajax-worker-tab.html'
453

    
454
    def get_context_data(self, worker_id, **kwargs):
455
        context = super(AjaxWorkerTabView, self).get_context_data(**kwargs)
456
        worker = Worker.objects.get(id=worker_id)
457

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

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

    
493
class AjaxWorkerDisponibilityColumnView(TemplateView):
494

    
495
    template_name = 'agenda/ajax-worker-disponibility-column.html'
496

    
497
    def get_context_data(self, worker_id, **kwargs):
498
        context = super(AjaxWorkerDisponibilityColumnView, self).get_context_data(**kwargs)
499
        worker = Worker.objects.get(pk=worker_id)
500

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

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

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