Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ fcfb4f5b

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
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 get_context_data(self, **kwargs):
36
        context = super(AgendaHomepageView, self).get_context_data(**kwargs)
37

    
38
        time_tables = TimeTable.objects.select_related('worker'). \
39
                filter(services=self.service). \
40
                for_today(self.date). \
41
                order_by('start_date')
42
        occurrences = Occurrence.objects.daily_occurrences(context['date']).order_by('start_time')
43

    
44
        context['workers_types'] = []
45
        context['workers_agenda'] = []
46
        context['disponibility'] = {}
47
        workers = []
48
        for worker_type in WorkerType.objects.all():
49
            workers_type = Worker.objects.for_service(self.service, worker_type)
50
            if workers_type:
51
                data = {'type': worker_type.name, 'workers': workers_type }
52
                context['workers_types'].append(data)
53
                workers.extend(data['workers'])
54

    
55
        occurrences_workers = {}
56
        time_tables_workers = {}
57
        for worker in workers:
58
            time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
59
            occurrences_worker = [o for o in occurrences if worker.id in o.event.participants.values_list('id', flat=True)]
60
            occurrences_workers[worker.id] = occurrences_worker
61
            time_tables_workers[worker.id] = time_tables_worker
62
            context['workers_agenda'].append({'worker': worker,
63
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
64
                        time_tables_worker, occurrences_worker)})
65

    
66
        context['disponibility'] = Occurrence.objects.daily_disponiblity(context['date'],
67
                occurrences_workers, workers, time_tables_workers)
68
        return context
69

    
70
class AgendaServiceActivityView(TemplateView):
71

    
72
    template_name = 'agenda/service-activity.html'
73

    
74
    def get_context_data(self, **kwargs):
75
        context = super(AgendaServiceActivityView, self).get_context_data(**kwargs)
76

    
77
        appointments_times = dict()
78
        appoinment_type = EventType.objects.get(id=1)
79
        occurrences = Occurrence.objects.daily_occurrences(context['date'],
80
                services=[self.service],
81
                event_type=appoinment_type)
82
        for occurrence in occurrences:
83
            start_time = occurrence.start_time.strftime("%H:%M")
84
            if not appointments_times.has_key(start_time):
85
                appointments_times[start_time] = dict()
86
                appointments_times[start_time]['row'] = 0
87
                appointments_times[start_time]['appointments'] = []
88
            appointment = dict()
89
            length = occurrence.end_time - occurrence.start_time
90
            if length.seconds:
91
                length = length.seconds / 60
92
                appointment['length'] = "%sm" % length
93
            event_act = occurrence.event.eventact
94
            appointment['patient'] = event_act.patient.display_name
95
            appointment['therapists'] = ""
96
            for participant in occurrence.event.participants.all():
97
                appointment['therapists'] += participant.display_name + "; "
98
            if appointment['therapists']:
99
                appointment['therapists'] = appointment['therapists'][:-2]
100
            appointment['act'] = event_act.act_type.name
101
            appointments_times[start_time]['row'] += 1
102
            appointments_times[start_time]['appointments'].append(appointment)
103
        context['appointments_times'] = sorted(appointments_times.items())
104
        return context
105

    
106

    
107
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
108
    model = EventAct
109
    form_class = NewAppointmentForm
110
    template_name = 'agenda/nouveau-rdv.html'
111
    success_url = '..'
112

    
113
    def get_initial(self):
114
        initial = super(NewAppointmentView, self).get_initial()
115
        initial['date'] = self.date
116
        initial['participants'] = self.request.GET.getlist('participants')
117
        initial['time'] = self.request.GET.get('time')
118
        return initial
119

    
120

    
121
class UpdateAppointmentView(UpdateView):
122
    model = EventAct
123
    form_class = UpdateAppointmentForm
124
    template_name = 'agenda/update-rdv.html'
125
    success_url = '..'
126

    
127
    def get_object(self, queryset=None):
128
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
129
        if self.occurrence.event.eventact:
130
            return self.occurrence.event.eventact
131

    
132
    def get_initial(self):
133
        initial = super(UpdateView, self).get_initial()
134
        initial['date'] = self.object.date
135
        initial['time'] = self.occurrence.start_time.strftime("%H:%M")
136
        time = self.occurrence.end_time - self.occurrence.start_time
137
        if time:
138
            time = time.seconds / 60
139
        else:
140
            time = 0
141
        initial['duration'] = time
142
        initial['participants'] = self.object.participants.values_list('id', flat=True)
143
        return initial
144

    
145
    def get_form_kwargs(self):
146
        kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
147
        kwargs['occurrence'] = self.occurrence
148
        return kwargs
149

    
150

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

    
157
    def get_initial(self):
158
        initial = super(NewEventView, self).get_initial()
159
        initial['date'] = self.date
160
        initial['participants'] = self.request.GET.getlist('participants')
161
        initial['time'] = self.request.GET.get('time')
162
        initial['services'] = [self.service]
163
        initial['event_type'] = 2
164
        return initial
165

    
166
class UpdateEventView(UpdateView):
167
    model = Event
168
    form_class = UpdateEventForm
169
    template_name = 'agenda/update-event.html'
170
    success_url = '..'
171

    
172
    def get_object(self, queryset=None):
173
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
174
        return self.occurrence.event
175

    
176
    def get_initial(self):
177
        initial = super(UpdateEventView, self).get_initial()
178
        initial['date'] = self.occurrence.start_time.strftime("%Y-%m-%d")
179
        initial['time'] = self.occurrence.start_time.strftime("%H:%M")
180
        time = self.occurrence.end_time - self.occurrence.start_time
181
        if time:
182
            time = time.seconds / 60
183
        else:
184
            time = 0
185
        initial['duration'] = time
186
        initial['participants'] = self.object.participants.values_list('id', flat=True)
187
        return initial
188

    
189
    def get_form_kwargs(self):
190
        kwargs = super(UpdateEventView, self).get_form_kwargs()
191
        kwargs['occurrence'] = self.occurrence
192
        return kwargs
193

    
194
def new_appointment(request):
195
    pass
196

    
197
class AgendaServiceActValidationView(TemplateView):
198

    
199
    template_name = 'agenda/act-validation.html'
200

    
201
    def acts_of_the_day(self):
202
        return get_acts_of_the_day(self.date, self.service)
203

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

    
227
    def get_context_data(self, **kwargs):
228
        context = super(AgendaServiceActValidationView, self).get_context_data(**kwargs)
229
        authorized_lock = True # is_authorized_for_locking(get_request().user)
230
        validation_msg = ValidationMessage.objects.\
231
            filter(validation_date=self.date, service=self.service).\
232
            order_by('-when')[:3]
233
        acts_of_the_day = self.acts_of_the_day()
234
        actes = list()
235
        for act in acts_of_the_day:
236
            state = act.get_state()
237
            display_name = VALIDATION_STATES[state.state_name]
238
            if not state.previous_state:
239
                state = None
240
            act.date = act.date.strftime("%H:%M")
241
            actes.append((act, state, display_name))
242
        context['validation_states'] = VALIDATION_STATES
243
        context['actes'] = actes
244
        context['validation_msg'] = validation_msg
245
        context['authorized_lock'] = authorized_lock
246
        return context
247

    
248

    
249
class AutomatedValidationView(TemplateView):
250
    template_name = 'agenda/automated-validation.html'
251

    
252
    def post(self, request, *args, **kwargs):
253
        automated_validation(self.date, self.service,
254
            request.user)
255
        ValidationMessage(validation_date=self.date,
256
            who=request.user, what='Validation automatique',
257
            service=self.service).save()
258
        return HttpResponseRedirect('..')
259

    
260
    def get_context_data(self, **kwargs):
261
        context = super(AutomatedValidationView, self).get_context_data(**kwargs)
262
        request = self.request
263
        (nb_acts_total, nb_acts_validated, nb_acts_double,
264
            nb_acts_abs_non_exc, nb_acts_abs_exc, nb_acts_annul_nous,
265
            nb_acts_annul_famille, nb_acts_abs_ess_pps,
266
            nb_acts_enf_hosp) = \
267
            automated_validation(self.date, self.service,
268
                request.user, commit = False)
269

    
270
        nb_acts_not_validated = nb_acts_double + \
271
            nb_acts_abs_non_exc + \
272
            nb_acts_abs_exc + \
273
            nb_acts_annul_nous + \
274
            nb_acts_annul_famille + \
275
            nb_acts_abs_ess_pps + \
276
            nb_acts_enf_hosp
277
        context.update({
278
            'nb_acts_total': nb_acts_total,
279
            'nb_acts_validated': nb_acts_validated,
280
            'nb_acts_not_validated': nb_acts_not_validated,
281
            'nb_acts_double': nb_acts_double,
282
            'nb_acts_abs_non_exc': nb_acts_abs_non_exc,
283
            'nb_acts_abs_exc': nb_acts_abs_exc,
284
            'nb_acts_annul_nous': nb_acts_annul_nous,
285
            'nb_acts_annul_famille': nb_acts_annul_famille,
286
            'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
287
            'nb_acts_enf_hosp': nb_acts_enf_hosp})
288
        return context
289

    
290
class UnlockAllView(CreateView):
291
    pass
292

    
293

    
294
class AgendasTherapeutesView(AgendaHomepageView):
295

    
296
    template_name = 'agenda/agendas-therapeutes.html'
297

    
298
    def get_context_data(self, **kwargs):
299
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
300
        for worker_agenda in context.get('workers_agenda', []):
301
            patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
302
            worker_agenda['summary'] = {
303
              'rdv': len(patient_appointments),
304
              'presence': len([x for x in patient_appointments if x.act_absence is None]),
305
              'absence': len([x for x in patient_appointments if x.act_absence is not None]),
306
              'doubles': len([x for x in patient_appointments if x.act_type == 'ACT_DOUBLE']),
307
              'valides': len([x for x in patient_appointments if x.act_type == 'ACT_VALIDE']),
308
            }
309

    
310
        return context
311

    
312
class JoursNonVerouillesView(TemplateView):
313

    
314
    template_name = 'agenda/days-not-locked.html'
315

    
316
    def get_context_data(self, **kwargs):
317
        context = super(JoursNonVerouillesView, self).get_context_data(**kwargs)
318
        acts = EventAct.objects.filter(is_billed=False,
319
            patient__service=self.service).order_by('date')
320
        days_not_locked = []
321
        for act in acts:
322
            current_day = datetime.datetime(act.date.year, act.date.month, act.date.day)
323
            if not current_day in days_not_locked:
324
                locked = are_all_acts_of_the_day_locked(current_day, self.service)
325
                if not locked:
326
                    days_not_locked.append(current_day)
327
        context['days_not_locked'] = days_not_locked
328
        return context
(10-10/10)