Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ 759daffe

1
# -*- coding: utf-8 -*-
2

    
3
import datetime
4

    
5
from django.db.models import Q
6
from django.shortcuts import redirect
7
from django.http import HttpResponseRedirect
8

    
9
from calebasse.cbv import TemplateView, CreateView, UpdateView
10
from calebasse.agenda.models import Event, EventType, EventWithAct
11
from calebasse.personnes.models import TimeTable, Holiday
12
from calebasse.agenda.appointments import get_daily_appointments, get_daily_usage
13
from calebasse.personnes.models import Worker
14
from calebasse.ressources.models import WorkerType, Room
15
from calebasse.actes.validation import (get_acts_of_the_day,
16
        get_days_with_acts_not_locked)
17
from calebasse.actes.validation_states import VALIDATION_STATES
18
from calebasse.actes.models import Act, ValidationMessage
19
from calebasse.actes.validation import (automated_validation, unlock_all_acts_of_the_day)
20
from calebasse import cbv
21

    
22
from forms import (NewAppointmentForm, NewEventForm, UpdateAppointmentForm)
23

    
24
def redirect_today(request, service):
25
    '''If not date is given we redirect on the agenda for today'''
26
    return redirect('agenda', date=datetime.date.today().strftime('%Y-%m-%d'),
27
            service=service)
28

    
29
class AgendaHomepageView(TemplateView):
30

    
31
    template_name = 'agenda/index.html'
32

    
33
    def post(self, request, *args, **kwargs):
34
        acte_id = request.POST.get('acte-id')
35
        try:
36
            act = Act.objects.get(id=acte_id)
37
            if not act.validation_locked:
38
                state_name = request.POST.get('act_state')
39
                act.set_state(state_name, request.user)
40
        except Act.DoesNotExist:
41
            pass
42
        return HttpResponseRedirect('#acte-frame-'+acte_id)
43

    
44
    def get_context_data(self, **kwargs):
45
        context = super(AgendaHomepageView, self).get_context_data(**kwargs)
46

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

    
59
        return context
60

    
61
class AgendaServiceActivityView(TemplateView):
62

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

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

    
68
        appointments_times = dict()
69
        appoinment_type = EventType.objects.get(id=1)
70
        meeting_type = EventType.objects.get(id=2)
71
        plain_events = Event.objects.for_today(self.date) \
72
                .filter(services=self.service,
73
                        event_type__in=[appoinment_type, meeting_type])
74
        events = [ e.today_occurrence(self.date) for e in plain_events ]
75
        for event in events:
76
            start_datetime = event.start_datetime.strftime("%H:%M")
77
            if not appointments_times.has_key(start_datetime):
78
                appointments_times[start_datetime] = dict()
79
                appointments_times[start_datetime]['row'] = 0
80
                appointments_times[start_datetime]['appointments'] = []
81
            appointment = dict()
82
            length = event.end_datetime - event.start_datetime
83
            if length.seconds:
84
                length = length.seconds / 60
85
                appointment['length'] = "%sm" % length
86
            if event.event_type == EventType.objects.get(id=1):
87
                appointment['type'] = 1
88
                event_act = event.eventwithact
89
                appointment['label'] = event_act.patient.display_name
90
                appointment['act'] = event_act.act_type.name
91
            elif event.event_type == EventType.objects.get(id=2):
92
                appointment['type'] = 2
93
                appointment['label'] = '%s - %s' % (event.event_type.label,
94
                                                    event.title)
95
            else:
96
                appointment['type'] = 0
97
                appointment['label'] = '???'
98
            appointment['participants'] = event.participants.all()
99
            appointments_times[start_datetime]['row'] += 1
100
            appointments_times[start_datetime]['appointments'].append(appointment)
101
        context['appointments_times'] = sorted(appointments_times.items())
102
        return context
103

    
104

    
105
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
106
    model = EventWithAct
107
    form_class = NewAppointmentForm
108
    template_name = 'agenda/nouveau-rdv.html'
109
    success_url = '..'
110

    
111
    def get_initial(self):
112
        initial = super(NewAppointmentView, self).get_initial()
113
        initial['start_datetime'] = self.date
114
        initial['date'] = self.date
115
        initial['participants'] = self.request.GET.getlist('participants')
116
        initial['time'] = self.request.GET.get('time')
117
        initial['room'] = self.request.GET.get('room')
118
        return initial
119

    
120
    def get_form_kwargs(self):
121
        kwargs = super(NewAppointmentView, self).get_form_kwargs()
122
        kwargs['service'] = self.service
123
        return kwargs
124

    
125
class TodayOccurrenceMixin(object):
126
    def get_object(self, queryset=None):
127
        o = super(TodayOccurrenceMixin, self).get_object(queryset)
128
        return o.today_occurrence(self.date)
129

    
130
class UpdateAppointmentView(TodayOccurrenceMixin, UpdateView):
131
    model = EventWithAct
132
    form_class = UpdateAppointmentForm
133
    template_name = 'agenda/update-rdv.html'
134
    success_url = '..'
135

    
136
    def get_initial(self):
137
        initial = super(UpdateView, self).get_initial()
138
        initial['start_datetime'] = self.date
139
        initial['date'] = self.object.start_datetime.date()
140
        initial['time'] = self.object.start_datetime.time()
141
        time = self.object.end_datetime - self.object.start_datetime
142
        if time:
143
            time = time.seconds / 60
144
        else:
145
            time = 0
146
        initial['duration'] = time
147
        initial['participants'] = self.object.participants.values_list('id', flat=True)
148
        return initial
149

    
150
    def get_form_kwargs(self):
151
        kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
152
        kwargs['service'] = self.service
153
        return kwargs
154

    
155

    
156
class NewEventView(CreateView):
157
    model = Event
158
    form_class = NewEventForm
159
    template_name = 'agenda/new-event.html'
160
    success_url = '..'
161

    
162
    def get_initial(self):
163
        initial = super(NewEventView, self).get_initial()
164
        initial['start_datetime'] = self.date
165
        initial['date'] = self.date
166
        initial['participants'] = self.request.GET.getlist('participants')
167
        initial['time'] = self.request.GET.get('time')
168
        initial['event_type'] = 2
169
        initial['room'] = self.request.GET.get('room')
170
        return initial
171

    
172
    def get_form_kwargs(self):
173
        kwargs = super(NewEventView, self).get_form_kwargs()
174
        kwargs['service'] = self.service
175
        return kwargs
176

    
177

    
178
class UpdateEventView(TodayOccurrenceMixin, UpdateView):
179
    model = Event
180
    form_class = NewEventForm
181
    template_name = 'agenda/update-event.html'
182
    success_url = '..'
183

    
184
    def get_initial(self):
185
        initial = super(UpdateEventView, self).get_initial()
186
        initial['start_datetime'] = self.date
187
        initial['date'] = self.object.start_datetime.date()
188
        initial['time'] = self.object.start_datetime.time()
189
        time = self.object.end_datetime - self.object.start_datetime
190
        if time:
191
            time = time.seconds / 60
192
        else:
193
            time = 0
194
        initial['duration'] = time
195
        initial['participants'] = self.object.participants.values_list('id', flat=True)
196
        return initial
197

    
198
    def get_form_kwargs(self):
199
        kwargs = super(UpdateEventView, self).get_form_kwargs()
200
        kwargs['service'] = self.service
201
        return kwargs
202

    
203

    
204
class AgendaServiceActValidationView(TemplateView):
205
    template_name = 'agenda/act-validation.html'
206

    
207
    def acts_of_the_day(self):
208
        return [e.act for e in EventWithAct.objects.filter(patient__service=self.service)
209
                .today_occurrences(self.date)]
210

    
211
    def post(self, request, *args, **kwargs):
212
        if 'unlock-all' in request.POST:
213
            #TODO: check that the user is authorized
214
            unlock_all_acts_of_the_day(self.date, self.service)
215
            ValidationMessage(validation_date=self.date,
216
                who=request.user, what='Déverrouillage',
217
                service=self.service).save()
218
        else:
219
            acte_id = request.POST.get('acte-id')
220
            try:
221
                act = Act.objects.get(id=acte_id)
222
                if 'lock' in request.POST or 'unlock' in request.POST:
223
                    #TODO: check that the user is authorized
224
                    act.validation_locked = 'lock' in request.POST
225
                    act.save()
226
                else:
227
                    state_name = request.POST.get('act_state')
228
                    act.set_state(state_name, request.user)
229
            except Act.DoesNotExist:
230
                pass
231
            return HttpResponseRedirect('#acte-frame-'+acte_id)
232
        return HttpResponseRedirect('')
233

    
234
    def get_context_data(self, **kwargs):
235
        context = super(AgendaServiceActValidationView, self).get_context_data(**kwargs)
236
        authorized_lock = True # is_authorized_for_locking(get_request().user)
237
        validation_msg = ValidationMessage.objects.\
238
            filter(validation_date=self.date, service=self.service).\
239
            order_by('-when')[:3]
240
        acts_of_the_day = self.acts_of_the_day()
241
        actes = list()
242
        for act in acts_of_the_day:
243
            state = act.get_state()
244
            display_name = VALIDATION_STATES[state.state_name]
245
            if not state.previous_state:
246
                state = None
247
            actes.append((act, state, display_name))
248
        context['validation_states'] = dict(VALIDATION_STATES)
249
        if self.service.name != 'CMPP' and \
250
                'ACT_DOUBLE' in context['validation_states']:
251
            context['validation_states'].pop('ACT_DOUBLE')
252
        context['actes'] = actes
253
        context['validation_msg'] = validation_msg
254
        context['authorized_lock'] = authorized_lock
255
        return context
256

    
257

    
258
class AutomatedValidationView(TemplateView):
259
    template_name = 'agenda/automated-validation.html'
260

    
261
    def post(self, request, *args, **kwargs):
262
        automated_validation(self.date, self.service,
263
            request.user)
264
        ValidationMessage(validation_date=self.date,
265
            who=request.user, what='Validation automatique',
266
            service=self.service).save()
267
        return HttpResponseRedirect('..')
268

    
269
    def get_context_data(self, **kwargs):
270
        context = super(AutomatedValidationView, self).get_context_data(**kwargs)
271
        request = self.request
272
        (nb_acts_total, nb_acts_validated, nb_acts_double,
273
        nb_acts_abs_non_exc, nb_acts_abs_exc, nb_acts_abs_inter, nb_acts_annul_nous,
274
        nb_acts_annul_famille, nb_acts_reporte, nb_acts_abs_ess_pps,
275
        nb_acts_enf_hosp, nb_acts_losts) = \
276
            automated_validation(self.date, self.service,
277
                request.user, commit = False)
278

    
279
        nb_acts_not_validated = nb_acts_double + \
280
            nb_acts_abs_non_exc + \
281
            nb_acts_abs_exc + \
282
            nb_acts_abs_inter + \
283
            nb_acts_annul_nous + \
284
            nb_acts_annul_famille + \
285
            nb_acts_reporte + \
286
            nb_acts_abs_ess_pps + \
287
            nb_acts_enf_hosp + \
288
            nb_acts_losts
289
        context.update({
290
            'nb_acts_total': nb_acts_total,
291
            'nb_acts_validated': nb_acts_validated,
292
            'nb_acts_not_validated': nb_acts_not_validated,
293
            'nb_acts_double': nb_acts_double,
294
            'nb_acts_abs_non_exc': nb_acts_abs_non_exc,
295
            'nb_acts_abs_exc': nb_acts_abs_exc,
296
            'nb_acts_abs_inter': nb_acts_abs_inter,
297
            'nb_acts_annul_nous': nb_acts_annul_nous,
298
            'nb_acts_annul_famille': nb_acts_annul_famille,
299
            'nb_acts_reporte': nb_acts_reporte,
300
            'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
301
            'nb_acts_enf_hosp': nb_acts_enf_hosp,
302
            'nb_acts_losts': nb_acts_losts})
303
        return context
304

    
305
class UnlockAllView(CreateView):
306
    pass
307

    
308

    
309
class AgendasTherapeutesView(AgendaHomepageView):
310
    template_name = 'agenda/agendas-therapeutes.html'
311

    
312
    def get_context_data(self, **kwargs):
313
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
314

    
315
        time_tables = TimeTable.objects.select_related('worker'). \
316
                filter(services=self.service). \
317
                for_today(self.date). \
318
                order_by('start_date')
319
        holidays = Holiday.objects.select_related('worker'). \
320
                for_period(self.date, self.date). \
321
                order_by('start_date')
322
        plain_events = Event.objects.for_today(self.date) \
323
                .filter(services=self.service) \
324
                .order_by('start_datetime').select_subclasses()
325
        events = [ e.today_occurrence(self.date) for e in plain_events ]
326

    
327
        events_workers = {}
328
        time_tables_workers = {}
329
        holidays_workers = {}
330
        context['workers_agenda'] = []
331
        for worker in context['workers']:
332
            time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
333
            events_worker = [o for o in events if worker.id in o.participants.values_list('id', flat=True)]
334
            holidays_worker = [h for h in holidays if h.worker_id in (None, worker.id)]
335
            events_workers[worker.id] = events_worker
336
            time_tables_workers[worker.id] = time_tables_worker
337
            holidays_workers[worker.id] = holidays_worker
338
            context['workers_agenda'].append({'worker': worker,
339
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
340
                        time_tables_worker, events_worker, holidays_worker)})
341

    
342
        for worker_agenda in context.get('workers_agenda', []):
343
            patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
344
            worker_agenda['summary'] = {
345
              'rdv': len(patient_appointments),
346
              'presence': len([x for x in patient_appointments if x.act_absence is None]),
347
              'absence': len([x for x in patient_appointments if x.act_absence is not None]),
348
              'doubles': len([x for x in patient_appointments if x.act_type == 'ACT_DOUBLE']),
349
              'valides': len([x for x in patient_appointments if x.act_type == 'ACT_VALIDE']),
350
            }
351

    
352
        return context
353

    
354
class JoursNonVerrouillesView(TemplateView):
355
    template_name = 'agenda/days-not-locked.html'
356

    
357
    def get_context_data(self, **kwargs):
358
        context = super(JoursNonVerrouillesView, self).get_context_data(**kwargs)
359
        acts = Act.objects.filter(is_billed=False,
360
            patient__service=self.service).order_by('date')
361
        days = set(acts.values_list('date', flat=True))
362
        if days:
363
            max_day, min_day = max(days), min(days)
364
            today = datetime.datetime.today().date()
365
            if max_day > today:
366
                max_day = today
367
            days &= set(get_days_with_acts_not_locked(min_day, max_day, self.service))
368
        context['days_not_locked'] = days
369
        return context
370

    
371
class RessourcesView(TemplateView):
372

    
373
    template_name = 'agenda/ressources.html'
374

    
375
    def get_context_data(self, **kwargs):
376
        context = super(RessourcesView, self).get_context_data(**kwargs)
377

    
378
        plain_events = Event.objects.for_today(self.date) \
379
                .order_by('start_datetime').select_subclasses()
380
        events = [ e.today_occurrence(self.date) for e in plain_events ]
381

    
382
        context['ressources_types'] = []
383
        context['ressources_agenda'] = []
384
        context['disponibility'] = {}
385
        ressources = []
386
        data = {'type': Room._meta.verbose_name_plural, 'ressources': Room.objects.all() }
387
        context['ressources_types'].append(data)
388
        ressources.extend(data['ressources'])
389

    
390
        events_ressources = {}
391
        for ressource in ressources:
392
            events_ressource = [e for e in events if ressource == e.room]
393
            events_ressources[ressource.id] = events_ressource
394
            context['ressources_agenda'].append({'ressource': ressource,
395
                    'appointments': get_daily_usage(context['date'], ressource,
396
                        self.service, events_ressource)})
397

    
398
        return context
399

    
400
class AjaxWorkerTabView(TemplateView):
401

    
402
    template_name = 'agenda/ajax-worker-tab.html'
403

    
404
    def get_context_data(self, worker_id, **kwargs):
405
        context = super(AjaxWorkerTabView, self).get_context_data(**kwargs)
406
        worker_id = int(worker_id)
407

    
408
        time_tables_worker = TimeTable.objects.select_related('worker'). \
409
                filter(services=self.service, worker_id=worker_id). \
410
                for_today(self.date). \
411
                order_by('start_date')
412
        holidays_worker = Holiday.objects.for_worker_id(worker_id). \
413
                for_period(self.date, self.date). \
414
                order_by('start_date')
415
        plain_events = Event.objects.for_today(self.date) \
416
                .order_by('start_datetime').select_subclasses()
417
        events = [ e.today_occurrence(self.date) for e in plain_events ]
418
        events_worker = [e for e in events if worker_id in e.participants.values_list('id', flat=True)]
419

    
420
        worker = Worker.objects.get(pk=worker_id)
421
        context['worker_agenda'] = {'worker': worker,
422
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
423
                        time_tables_worker, events_worker, holidays_worker)}
424
        return context
425

    
426
class AjaxWorkerDisponibilityColumnView(TemplateView):
427

    
428
    template_name = 'agenda/ajax-worker-disponibility-column.html'
429

    
430
    def get_context_data(self, worker_id, **kwargs):
431
        context = super(AjaxWorkerDisponibilityColumnView, self).get_context_data(**kwargs)
432
        worker_id = int(worker_id)
433

    
434
        time_tables_worker = TimeTable.objects.select_related('worker'). \
435
                filter(services=self.service, worker_id=worker_id). \
436
                for_today(self.date). \
437
                order_by('start_date')
438
        holidays_worker = Holiday.objects.for_worker_id(worker_id). \
439
                for_period(self.date, self.date). \
440
                order_by('start_date')
441
        events = Event.objects.today_occurrences(self.date)
442
        events_worker = [e for e in events if worker_id in e.participants.values_list('id', flat=True)]
443

    
444
        worker = Worker.objects.get(pk=worker_id)
445
        time_tables_workers = {worker.id: time_tables_worker}
446
        events_workers = {worker.id: events_worker}
447
        holidays_workers = {worker.id: holidays_worker}
448

    
449
        context['initials'] = worker.get_initials()
450
        context['worker_id'] = worker.id
451
        context['disponibility'] = Event.objects.daily_disponibilities(self.date,
452
                events_workers, [worker], time_tables_workers, holidays_workers)
453
        return context
(10-10/10)