Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ e3a19c55

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 = vs + sorted(validation_states.items(), key=lambda tup: tup[0])
281
        context['validation_states'] = validation_states
282
        context['actes'] = actes
283
        context['validation_msg'] = validation_msg
284
        context['authorized_lock'] = authorized_lock
285
        return context
286

    
287

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

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

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

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

    
335
class UnlockAllView(CreateView):
336
    pass
337

    
338

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

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

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

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

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

    
404
        return context
405

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

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

    
423
class RessourcesView(TemplateView):
424

    
425
    template_name = 'agenda/ressources.html'
426

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

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

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

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

    
450
        return context
451

    
452
class AjaxWorkerTabView(TemplateView):
453

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

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

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

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

    
495
class AjaxWorkerDisponibilityColumnView(TemplateView):
496

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

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

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

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

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