Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ de502147

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 Occurrence, Event, EventType
11
from calebasse.personnes.models import TimeTable, Holiday
12
from calebasse.actes.models import EventAct
13
from calebasse.agenda.appointments import get_daily_appointments
14
from calebasse.personnes.models import Worker
15
from calebasse.ressources.models import WorkerType
16
from calebasse.actes.validation import get_acts_of_the_day
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,
20
    unlock_all_acts_of_the_day, are_all_acts_of_the_day_locked)
21
from calebasse import cbv
22

    
23
from forms import (NewAppointmentForm, NewEventForm,
24
        UpdateAppointmentForm, UpdateEventForm)
25

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

    
31
class AgendaHomepageView(TemplateView):
32

    
33
    template_name = 'agenda/index.html'
34

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

    
46
    def get_context_data(self, **kwargs):
47
        context = super(AgendaHomepageView, self).get_context_data(**kwargs)
48

    
49
        time_tables = TimeTable.objects.select_related('worker'). \
50
                filter(services=self.service). \
51
                for_today(self.date). \
52
                order_by('start_date')
53
        holidays = Holiday.objects.select_related('worker'). \
54
                for_period(self.date, self.date). \
55
                order_by('start_date')
56
        occurrences = Occurrence.objects.daily_occurrences(context['date']).order_by('start_time')
57

    
58
        context['workers_types'] = []
59
        context['workers_agenda'] = []
60
        context['disponibility'] = {}
61
        workers = []
62
        for worker_type in WorkerType.objects.all():
63
            workers_type = Worker.objects.filter(type=worker_type)
64
            if workers_type:
65
                data = {'type': worker_type.name, 'workers': workers_type }
66
                context['workers_types'].append(data)
67
                workers.extend(data['workers'])
68

    
69
        occurrences_workers = {}
70
        time_tables_workers = {}
71
        holidays_workers = {}
72
        for worker in workers:
73
            time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
74
            occurrences_worker = [o for o in occurrences if worker.id in o.event.participants.values_list('id', flat=True)]
75
            holidays_worker = [h for h in holidays if h.worker_id in (None, worker.id)]
76
            occurrences_workers[worker.id] = occurrences_worker
77
            time_tables_workers[worker.id] = time_tables_worker
78
            holidays_workers[worker.id] = holidays_worker
79
            context['workers_agenda'].append({'worker': worker,
80
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
81
                        time_tables_worker, occurrences_worker, holidays_worker)})
82

    
83
        context['disponibility'] = Occurrence.objects.daily_disponiblity(context['date'],
84
                occurrences_workers, workers, time_tables_workers, holidays_workers)
85
        return context
86

    
87
class AgendaServiceActivityView(TemplateView):
88

    
89
    template_name = 'agenda/service-activity.html'
90

    
91
    def get_context_data(self, **kwargs):
92
        context = super(AgendaServiceActivityView, self).get_context_data(**kwargs)
93

    
94
        appointments_times = dict()
95
        appoinment_type = EventType.objects.get(id=1)
96
        meeting_type = EventType.objects.get(id=2)
97
        occurrences = Occurrence.objects.daily_occurrences(context['date'],
98
                services=[self.service],
99
                event_type=[appoinment_type, meeting_type])
100
        for occurrence in occurrences:
101
            start_time = occurrence.start_time.strftime("%H:%M")
102
            if not appointments_times.has_key(start_time):
103
                appointments_times[start_time] = dict()
104
                appointments_times[start_time]['row'] = 0
105
                appointments_times[start_time]['appointments'] = []
106
            appointment = dict()
107
            length = occurrence.end_time - occurrence.start_time
108
            if length.seconds:
109
                length = length.seconds / 60
110
                appointment['length'] = "%sm" % length
111
            if occurrence.event.event_type == EventType.objects.get(id=1):
112
                appointment['type'] = 1
113
                event_act = occurrence.event.eventact
114
                appointment['label'] = event_act.patient.display_name
115
                appointment['act'] = event_act.act_type.name
116
            elif occurrence.event.event_type == EventType.objects.get(id=2):
117
                appointment['type'] = 2
118
                appointment['label'] = '%s - %s' % (occurrence.event.event_type.label,
119
                                                    occurrence.event.title)
120
            else:
121
                appointment['type'] = 0
122
                appointment['label'] = '???'
123
            appointment['participants'] = occurrence.event.participants.all()
124
            appointments_times[start_time]['row'] += 1
125
            appointments_times[start_time]['appointments'].append(appointment)
126
        context['appointments_times'] = sorted(appointments_times.items())
127
        return context
128

    
129

    
130
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
131
    model = EventAct
132
    form_class = NewAppointmentForm
133
    template_name = 'agenda/nouveau-rdv.html'
134
    success_url = '..'
135

    
136
    def get_initial(self):
137
        initial = super(NewAppointmentView, self).get_initial()
138
        initial['date'] = self.date
139
        initial['participants'] = self.request.GET.getlist('participants')
140
        initial['time'] = self.request.GET.get('time')
141
        return initial
142

    
143

    
144
class UpdateAppointmentView(UpdateView):
145
    model = EventAct
146
    form_class = UpdateAppointmentForm
147
    template_name = 'agenda/update-rdv.html'
148
    success_url = '..'
149

    
150
    def get_object(self, queryset=None):
151
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
152
        if self.occurrence.event.eventact:
153
            return self.occurrence.event.eventact
154

    
155
    def get_initial(self):
156
        initial = super(UpdateView, self).get_initial()
157
        initial['date'] = self.object.date
158
        initial['time'] = self.occurrence.start_time.strftime("%H:%M")
159
        time = self.occurrence.end_time - self.occurrence.start_time
160
        if time:
161
            time = time.seconds / 60
162
        else:
163
            time = 0
164
        initial['duration'] = time
165
        initial['participants'] = self.object.participants.values_list('id', flat=True)
166
        return initial
167

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

    
174

    
175
class NewEventView(CreateView):
176
    model = Event
177
    form_class = NewEventForm
178
    template_name = 'agenda/new-event.html'
179
    success_url = '..'
180

    
181
    def get_initial(self):
182
        initial = super(NewEventView, self).get_initial()
183
        initial['date'] = self.date
184
        initial['participants'] = self.request.GET.getlist('participants')
185
        initial['time'] = self.request.GET.get('time')
186
        initial['services'] = [self.service]
187
        initial['event_type'] = 2
188
        return initial
189

    
190
class UpdateEventView(UpdateView):
191
    model = Event
192
    form_class = UpdateEventForm
193
    template_name = 'agenda/update-event.html'
194
    success_url = '..'
195

    
196
    def get_object(self, queryset=None):
197
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
198
        return self.occurrence.event
199

    
200
    def get_initial(self):
201
        initial = super(UpdateEventView, self).get_initial()
202
        initial['date'] = self.occurrence.start_time.strftime("%Y-%m-%d")
203
        initial['time'] = self.occurrence.start_time.strftime("%H:%M")
204
        time = self.occurrence.end_time - self.occurrence.start_time
205
        if time:
206
            time = time.seconds / 60
207
        else:
208
            time = 0
209
        initial['duration'] = time
210
        initial['participants'] = self.object.participants.values_list('id', flat=True)
211
        return initial
212

    
213
    def get_form_kwargs(self):
214
        kwargs = super(UpdateEventView, self).get_form_kwargs()
215
        kwargs['occurrence'] = self.occurrence
216
        return kwargs
217

    
218
def new_appointment(request):
219
    pass
220

    
221
class AgendaServiceActValidationView(TemplateView):
222

    
223
    template_name = 'agenda/act-validation.html'
224

    
225
    def acts_of_the_day(self):
226
        return get_acts_of_the_day(self.date, self.service)
227

    
228
    def post(self, request, *args, **kwargs):
229
        if 'unlock-all' in request.POST:
230
            #TODO: check that the user is authorized
231
            unlock_all_acts_of_the_day(self.date, self.service)
232
            ValidationMessage(validation_date=self.date,
233
                who=request.user, what='Déverrouillage',
234
                service=self.service).save()
235
        else:
236
            acte_id = request.POST.get('acte-id')
237
            try:
238
                act = Act.objects.get(id=acte_id)
239
                if 'lock' in request.POST or 'unlock' in request.POST:
240
                    #TODO: check that the user is authorized
241
                    act.validation_locked = 'lock' in request.POST
242
                    act.save()
243
                else:
244
                    state_name = request.POST.get('act_state')
245
                    act.set_state(state_name, request.user)
246
            except Act.DoesNotExist:
247
                pass
248
            return HttpResponseRedirect('#acte-frame-'+acte_id)
249
        return HttpResponseRedirect('')
250

    
251
    def get_context_data(self, **kwargs):
252
        context = super(AgendaServiceActValidationView, self).get_context_data(**kwargs)
253
        authorized_lock = True # is_authorized_for_locking(get_request().user)
254
        validation_msg = ValidationMessage.objects.\
255
            filter(validation_date=self.date, service=self.service).\
256
            order_by('-when')[:3]
257
        acts_of_the_day = self.acts_of_the_day()
258
        actes = list()
259
        for act in acts_of_the_day:
260
            state = act.get_state()
261
            display_name = VALIDATION_STATES[state.state_name]
262
            if not state.previous_state:
263
                state = None
264
            act.date = act.date.strftime("%H:%M")
265
            actes.append((act, state, display_name))
266
        context['validation_states'] = dict(VALIDATION_STATES)
267
        if self.service.name != 'CMPP' and \
268
                'ACT_DOUBLE' in context['validation_states']:
269
            context['validation_states'].pop('ACT_DOUBLE')
270
        context['actes'] = actes
271
        context['validation_msg'] = validation_msg
272
        context['authorized_lock'] = authorized_lock
273
        return context
274

    
275

    
276
class AutomatedValidationView(TemplateView):
277
    template_name = 'agenda/automated-validation.html'
278

    
279
    def post(self, request, *args, **kwargs):
280
        automated_validation(self.date, self.service,
281
            request.user)
282
        ValidationMessage(validation_date=self.date,
283
            who=request.user, what='Validation automatique',
284
            service=self.service).save()
285
        return HttpResponseRedirect('..')
286

    
287
    def get_context_data(self, **kwargs):
288
        context = super(AutomatedValidationView, self).get_context_data(**kwargs)
289
        request = self.request
290
        (nb_acts_total, nb_acts_validated, nb_acts_double,
291
            nb_acts_abs_non_exc, nb_acts_abs_exc, nb_acts_annul_nous,
292
            nb_acts_annul_famille, nb_acts_reporte, nb_acts_abs_ess_pps,
293
            nb_acts_enf_hosp) = \
294
            automated_validation(self.date, self.service,
295
                request.user, commit = False)
296

    
297
        nb_acts_not_validated = nb_acts_double + \
298
            nb_acts_abs_non_exc + \
299
            nb_acts_abs_exc + \
300
            nb_acts_annul_nous + \
301
            nb_acts_annul_famille + \
302
            nb_acts_reporte + \
303
            nb_acts_abs_ess_pps + \
304
            nb_acts_enf_hosp
305
        context.update({
306
            'nb_acts_total': nb_acts_total,
307
            'nb_acts_validated': nb_acts_validated,
308
            'nb_acts_not_validated': nb_acts_not_validated,
309
            'nb_acts_double': nb_acts_double,
310
            'nb_acts_abs_non_exc': nb_acts_abs_non_exc,
311
            'nb_acts_abs_exc': nb_acts_abs_exc,
312
            'nb_acts_annul_nous': nb_acts_annul_nous,
313
            'nb_acts_annul_famille': nb_acts_annul_famille,
314
            'nb_acts_reporte': nb_acts_reporte,
315
            'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
316
            'nb_acts_enf_hosp': nb_acts_enf_hosp})
317
        return context
318

    
319
class UnlockAllView(CreateView):
320
    pass
321

    
322

    
323
class AgendasTherapeutesView(AgendaHomepageView):
324

    
325
    template_name = 'agenda/agendas-therapeutes.html'
326

    
327
    def get_context_data(self, **kwargs):
328
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
329
        for worker_agenda in context.get('workers_agenda', []):
330
            patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
331
            worker_agenda['summary'] = {
332
              'rdv': len(patient_appointments),
333
              'presence': len([x for x in patient_appointments if x.act_absence is None]),
334
              'absence': len([x for x in patient_appointments if x.act_absence is not None]),
335
              'doubles': len([x for x in patient_appointments if x.act_type == 'ACT_DOUBLE']),
336
              'valides': len([x for x in patient_appointments if x.act_type == 'ACT_VALIDE']),
337
            }
338

    
339
        return context
340

    
341
class JoursNonVerrouillesView(TemplateView):
342

    
343
    template_name = 'agenda/days-not-locked.html'
344

    
345
    def get_context_data(self, **kwargs):
346
        context = super(JoursNonVerrouillesView, self).get_context_data(**kwargs)
347
        acts = EventAct.objects.filter(is_billed=False,
348
            patient__service=self.service).order_by('date')
349
        days_not_locked = []
350
        for act in acts:
351
            current_day = datetime.datetime(act.date.year, act.date.month, act.date.day)
352
            if not current_day in days_not_locked:
353
                locked = are_all_acts_of_the_day_locked(current_day, self.service)
354
                if not locked:
355
                    days_not_locked.append(current_day)
356
        context['days_not_locked'] = days_not_locked
357
        return context
(10-10/10)