Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ 08bf3477

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.act
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 get_acts_of_the_day(self.date, self.service)
209

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

    
233
    def get_context_data(self, **kwargs):
234
        context = super(AgendaServiceActValidationView, self).get_context_data(**kwargs)
235
        authorized_lock = True # is_authorized_for_locking(get_request().user)
236
        validation_msg = ValidationMessage.objects.\
237
            filter(validation_date=self.date, service=self.service).\
238
            order_by('-when')[:3]
239
        acts_of_the_day = self.acts_of_the_day()
240
        actes = list()
241
        for act in acts_of_the_day:
242
            state = act.get_state()
243
            display_name = VALIDATION_STATES[state.state_name]
244
            if not state.previous_state:
245
                state = None
246
            act.date = act.date.strftime("%H:%M")
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
                .order_by('start_datetime').select_subclasses()
324
        events = [ e.today_occurrence(self.date) for e in plain_events ]
325

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

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

    
351
        return context
352

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

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

    
366
class RessourcesView(TemplateView):
367

    
368
    template_name = 'agenda/ressources.html'
369

    
370
    def get_context_data(self, **kwargs):
371
        context = super(RessourcesView, self).get_context_data(**kwargs)
372

    
373
        plain_events = Event.objects.for_today(self.date) \
374
                .order_by('start_datetime').select_subclasses()
375
        events = [ e.today_occurrence(self.date) for e in plain_events ]
376

    
377
        context['ressources_types'] = []
378
        context['ressources_agenda'] = []
379
        context['disponibility'] = {}
380
        ressources = []
381
        data = {'type': Room._meta.verbose_name_plural, 'ressources': Room.objects.all() }
382
        context['ressources_types'].append(data)
383
        ressources.extend(data['ressources'])
384

    
385
        events_ressources = {}
386
        for ressource in ressources:
387
            events_ressource = [e for e in events if ressource == e.room]
388
            events_ressources[ressource.id] = events_ressource
389
            context['ressources_agenda'].append({'ressource': ressource,
390
                    'appointments': get_daily_usage(context['date'], ressource,
391
                        self.service, events_ressource)})
392

    
393
        return context
394

    
395
class AjaxWorkerTabView(TemplateView):
396

    
397
    template_name = 'agenda/ajax-worker-tab.html'
398

    
399
    def get_context_data(self, worker_id, **kwargs):
400
        context = super(AjaxWorkerTabView, self).get_context_data(**kwargs)
401
        worker_id = int(worker_id)
402

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

    
415
        worker = Worker.objects.get(pk=worker_id)
416
        context['worker_agenda'] = {'worker': worker,
417
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
418
                        time_tables_worker, events_worker, holidays_worker)}
419
        return context
420

    
421
class AjaxWorkerDisponibilityColumnView(TemplateView):
422

    
423
    template_name = 'agenda/ajax-worker-disponibility-column.html'
424

    
425
    def get_context_data(self, worker_id, **kwargs):
426
        context = super(AjaxWorkerDisponibilityColumnView, self).get_context_data(**kwargs)
427
        worker_id = int(worker_id)
428

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

    
439
        worker = Worker.objects.get(pk=worker_id)
440
        time_tables_workers = {worker.id: time_tables_worker}
441
        events_workers = {worker.id: events_worker}
442
        holidays_workers = {worker.id: holidays_worker}
443

    
444
        context['initials'] = worker.get_initials()
445
        context['worker_id'] = worker.id
446
        context['disponibility'] = Event.objects.daily_disponibilities(self.date,
447
                events_workers, [worker], time_tables_workers, holidays_workers)
448
        return context
(10-10/10)