Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ d0b8cfab

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 = 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
        plain_events = Event.objects.for_today(self.date) \
70
                .filter(services=self.service) \
71
                .select_subclasses()
72
        events = [ e.today_occurrence(self.date) for e in plain_events ]
73
        for event in events:
74
            start_datetime = event.start_datetime.strftime("%H:%M")
75
            if not appointments_times.has_key(start_datetime):
76
                appointments_times[start_datetime] = dict()
77
                appointments_times[start_datetime]['row'] = 0
78
                appointments_times[start_datetime]['appointments'] = []
79
            appointment = dict()
80
            length = event.end_datetime - event.start_datetime
81
            if length.seconds:
82
                length = length.seconds / 60
83
                appointment['length'] = "%sm" % length
84
            if event.event_type_id == 1:
85
                appointment['type'] = 1
86
                appointment['label'] = event.patient.display_name
87
                appointment['act'] = event.act_type.name
88
            else:
89
                appointment['type'] = 2
90
                if event.event_type.label == 'Autre' and event.title:
91
                    appointment['label'] = event.title
92
                else:
93
                    appointment['label'] = '%s - %s' % (event.event_type.label,
94
                                                        event.title)
95
            appointment['participants'] = event.participants.all()
96
            appointments_times[start_datetime]['row'] += 1
97
            appointments_times[start_datetime]['appointments'].append(appointment)
98
        context['appointments_times'] = sorted(appointments_times.items())
99
        return context
100

    
101

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

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

    
117
    def get_form_kwargs(self):
118
        kwargs = super(NewAppointmentView, self).get_form_kwargs()
119
        kwargs['service'] = self.service
120
        return kwargs
121

    
122
class TodayOccurrenceMixin(object):
123
    def get_object(self, queryset=None):
124
        o = super(TodayOccurrenceMixin, self).get_object(queryset)
125
        return o.today_occurrence(self.date)
126

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

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

    
147
    def get_form_kwargs(self):
148
        kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
149
        kwargs['service'] = self.service
150
        return kwargs
151

    
152

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

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

    
169
    def get_form_kwargs(self):
170
        kwargs = super(NewEventView, self).get_form_kwargs()
171
        kwargs['service'] = self.service
172
        return kwargs
173

    
174

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

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

    
195
    def get_form_kwargs(self):
196
        kwargs = super(UpdateEventView, self).get_form_kwargs()
197
        kwargs['service'] = self.service
198
        return kwargs
199

    
200

    
201
class AgendaServiceActValidationView(TemplateView):
202
    template_name = 'agenda/act-validation.html'
203

    
204
    def acts_of_the_day(self):
205
        return [e.act for e in EventWithAct.objects.filter(patient__service=self.service)
206
                .today_occurrences(self.date)]
207

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

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

    
254

    
255
class AutomatedValidationView(TemplateView):
256
    template_name = 'agenda/automated-validation.html'
257

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

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

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

    
302
class UnlockAllView(CreateView):
303
    pass
304

    
305

    
306
class AgendasTherapeutesView(AgendaHomepageView):
307
    template_name = 'agenda/agendas-therapeutes.html'
308

    
309
    def get_context_data(self, **kwargs):
310
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
311

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

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

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

    
349
        return context
350

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

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

    
368
class RessourcesView(TemplateView):
369

    
370
    template_name = 'agenda/ressources.html'
371

    
372
    def get_context_data(self, **kwargs):
373
        context = super(RessourcesView, self).get_context_data(**kwargs)
374

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

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

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

    
395
        return context
396

    
397
class AjaxWorkerTabView(TemplateView):
398

    
399
    template_name = 'agenda/ajax-worker-tab.html'
400

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

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

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

    
423
class AjaxWorkerDisponibilityColumnView(TemplateView):
424

    
425
    template_name = 'agenda/ajax-worker-disponibility-column.html'
426

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

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

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

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