Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ 1f9e881e

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)
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
class DeleteEventView(TodayOccurrenceMixin, cbv.DeleteView):
202
    model = Event
203
    success_url = '..'
204

    
205
    def delete(self, request, *args, **kwargs):
206
        super(DeleteEventView, self).delete(request, *args, **kwargs)
207
        return HttpResponse(status=204)
208

    
209
class AgendaServiceActValidationView(TemplateView):
210
    template_name = 'agenda/act-validation.html'
211

    
212
    def acts_of_the_day(self):
213
        return [e.act for e in EventWithAct.objects.filter(patient__service=self.service)
214
                .today_occurrences(self.date)]
215

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

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

    
262

    
263
class AutomatedValidationView(TemplateView):
264
    template_name = 'agenda/automated-validation.html'
265

    
266
    def post(self, request, *args, **kwargs):
267
        automated_validation(self.date, self.service,
268
            request.user)
269
        ValidationMessage(validation_date=self.date,
270
            who=request.user, what='Validation automatique',
271
            service=self.service).save()
272
        return HttpResponseRedirect('..')
273

    
274
    def get_context_data(self, **kwargs):
275
        context = super(AutomatedValidationView, self).get_context_data(**kwargs)
276
        request = self.request
277
        (nb_acts_total, nb_acts_validated, nb_acts_double,
278
        nb_acts_abs_non_exc, nb_acts_abs_exc, nb_acts_abs_inter, nb_acts_annul_nous,
279
        nb_acts_annul_famille, nb_acts_reporte, nb_acts_abs_ess_pps,
280
        nb_acts_enf_hosp, nb_acts_losts) = \
281
            automated_validation(self.date, self.service,
282
                request.user, commit = False)
283

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

    
310
class UnlockAllView(CreateView):
311
    pass
312

    
313

    
314
class AgendasTherapeutesView(AgendaHomepageView):
315
    template_name = 'agenda/agendas-therapeutes.html'
316

    
317
    def get_context_data(self, **kwargs):
318
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
319

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

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

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

    
357
        return context
358

    
359
class JoursNonVerrouillesView(TemplateView):
360
    template_name = 'agenda/days-not-locked.html'
361

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

    
376
class RessourcesView(TemplateView):
377

    
378
    template_name = 'agenda/ressources.html'
379

    
380
    def get_context_data(self, **kwargs):
381
        context = super(RessourcesView, self).get_context_data(**kwargs)
382

    
383
        plain_events = Event.objects.for_today(self.date) \
384
                .order_by('start_datetime').select_subclasses()
385
        events = [ e.today_occurrence(self.date) for e in plain_events ]
386

    
387
        context['ressources_types'] = []
388
        context['ressources_agenda'] = []
389
        context['disponibility'] = {}
390
        ressources = []
391
        data = {'type': Room._meta.verbose_name_plural, 'ressources': Room.objects.all() }
392
        context['ressources_types'].append(data)
393
        ressources.extend(data['ressources'])
394

    
395
        events_ressources = {}
396
        for ressource in ressources:
397
            events_ressource = [e for e in events if ressource == e.room]
398
            events_ressources[ressource.id] = events_ressource
399
            context['ressources_agenda'].append({'ressource': ressource,
400
                    'appointments': get_daily_usage(context['date'], ressource,
401
                        self.service, events_ressource)})
402

    
403
        return context
404

    
405
class AjaxWorkerTabView(TemplateView):
406

    
407
    template_name = 'agenda/ajax-worker-tab.html'
408

    
409
    def get_context_data(self, worker_id, **kwargs):
410
        context = super(AjaxWorkerTabView, self).get_context_data(**kwargs)
411
        worker_id = int(worker_id)
412

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

    
425
        worker = Worker.objects.get(pk=worker_id)
426
        context['worker_agenda'] = {'worker': worker,
427
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
428
                        time_tables_worker, events_worker, holidays_worker)}
429
        return context
430

    
431
class AjaxWorkerDisponibilityColumnView(TemplateView):
432

    
433
    template_name = 'agenda/ajax-worker-disponibility-column.html'
434

    
435
    def get_context_data(self, worker_id, **kwargs):
436
        context = super(AjaxWorkerDisponibilityColumnView, self).get_context_data(**kwargs)
437
        worker_id = int(worker_id)
438

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

    
449
        worker = Worker.objects.get(pk=worker_id)
450
        time_tables_workers = {worker.id: time_tables_worker}
451
        events_workers = {worker.id: events_worker}
452
        holidays_workers = {worker.id: holidays_worker}
453

    
454
        context['initials'] = worker.get_initials()
455
        context['worker_id'] = worker.id
456
        context['disponibility'] = Event.objects.daily_disponibilities(self.date,
457
                events_workers, [worker], time_tables_workers, holidays_workers)
458
        return context
(10-10/10)