Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ 7db9b9ef

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
                appointment['state'] = event.act.get_state()
89
            else:
90
                appointment['type'] = 2
91
                if event.event_type.label == 'Autre' and event.title:
92
                    appointment['label'] = event.title
93
                else:
94
                    appointment['label'] = '%s - %s' % (event.event_type.label,
95
                                                        event.title)
96
            appointment['participants'] = event.participants.all()
97
            appointments_times[start_datetime]['row'] += 1
98
            appointments_times[start_datetime]['appointments'].append(appointment)
99
        context['appointments_times'] = sorted(appointments_times.items())
100
        return context
101

    
102

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

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

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

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

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

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

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

    
153

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

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

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

    
175

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

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

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

    
201

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

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

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

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

    
255

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

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

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

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

    
303
class UnlockAllView(CreateView):
304
    pass
305

    
306

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

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

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

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

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

    
350
        return context
351

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

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

    
369
class RessourcesView(TemplateView):
370

    
371
    template_name = 'agenda/ressources.html'
372

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

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

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

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

    
396
        return context
397

    
398
class AjaxWorkerTabView(TemplateView):
399

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

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

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

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

    
424
class AjaxWorkerDisponibilityColumnView(TemplateView):
425

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

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

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

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

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