Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ 477e1b65

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
        meeting_type = EventType.objects.get(id=2)
80
        occurrences = Occurrence.objects.daily_occurrences(context['date'],
81
                services=[self.service],
82
                event_type=[appoinment_type, meeting_type])
83
        for occurrence in occurrences:
84
            start_time = occurrence.start_time.strftime("%H:%M")
85
            if not appointments_times.has_key(start_time):
86
                appointments_times[start_time] = dict()
87
                appointments_times[start_time]['row'] = 0
88
                appointments_times[start_time]['appointments'] = []
89
            appointment = dict()
90
            length = occurrence.end_time - occurrence.start_time
91
            if length.seconds:
92
                length = length.seconds / 60
93
                appointment['length'] = "%sm" % length
94
            if occurrence.event.event_type == EventType.objects.get(id=1):
95
                appointment['type'] = 1
96
                event_act = occurrence.event.eventact
97
                appointment['label'] = event_act.patient.display_name
98
                appointment['act'] = event_act.act_type.name
99
            elif occurrence.event.event_type == EventType.objects.get(id=2):
100
                appointment['type'] = 2
101
                appointment['label'] = '%s - %s' % (occurrence.event.event_type.label,
102
                                                    occurrence.event.title)
103
            else:
104
                appointment['type'] = 0
105
                appointment['label'] = '???'
106
            appointment['therapists'] = ""
107
            for participant in occurrence.event.participants.all():
108
                appointment['therapists'] += participant.display_name + "; "
109
            if appointment['therapists']:
110
                appointment['therapists'] = appointment['therapists'][:-2]
111
            appointments_times[start_time]['row'] += 1
112
            appointments_times[start_time]['appointments'].append(appointment)
113
        context['appointments_times'] = sorted(appointments_times.items())
114
        return context
115

    
116

    
117
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
118
    model = EventAct
119
    form_class = NewAppointmentForm
120
    template_name = 'agenda/nouveau-rdv.html'
121
    success_url = '..'
122

    
123
    def get_initial(self):
124
        initial = super(NewAppointmentView, self).get_initial()
125
        initial['date'] = self.date
126
        initial['participants'] = self.request.GET.getlist('participants')
127
        initial['time'] = self.request.GET.get('time')
128
        return initial
129

    
130

    
131
class UpdateAppointmentView(UpdateView):
132
    model = EventAct
133
    form_class = UpdateAppointmentForm
134
    template_name = 'agenda/update-rdv.html'
135
    success_url = '..'
136

    
137
    def get_object(self, queryset=None):
138
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
139
        if self.occurrence.event.eventact:
140
            return self.occurrence.event.eventact
141

    
142
    def get_initial(self):
143
        initial = super(UpdateView, self).get_initial()
144
        initial['date'] = self.object.date
145
        initial['time'] = self.occurrence.start_time.strftime("%H:%M")
146
        time = self.occurrence.end_time - self.occurrence.start_time
147
        if time:
148
            time = time.seconds / 60
149
        else:
150
            time = 0
151
        initial['duration'] = time
152
        initial['participants'] = self.object.participants.values_list('id', flat=True)
153
        return initial
154

    
155
    def get_form_kwargs(self):
156
        kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
157
        kwargs['occurrence'] = self.occurrence
158
        return kwargs
159

    
160

    
161
class NewEventView(CreateView):
162
    model = Event
163
    form_class = NewEventForm
164
    template_name = 'agenda/new-event.html'
165
    success_url = '..'
166

    
167
    def get_initial(self):
168
        initial = super(NewEventView, self).get_initial()
169
        initial['date'] = self.date
170
        initial['participants'] = self.request.GET.getlist('participants')
171
        initial['time'] = self.request.GET.get('time')
172
        initial['services'] = [self.service]
173
        initial['event_type'] = 2
174
        return initial
175

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

    
182
    def get_object(self, queryset=None):
183
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
184
        return self.occurrence.event
185

    
186
    def get_initial(self):
187
        initial = super(UpdateEventView, self).get_initial()
188
        initial['date'] = self.occurrence.start_time.strftime("%Y-%m-%d")
189
        initial['time'] = self.occurrence.start_time.strftime("%H:%M")
190
        time = self.occurrence.end_time - self.occurrence.start_time
191
        if time:
192
            time = time.seconds / 60
193
        else:
194
            time = 0
195
        initial['duration'] = time
196
        initial['participants'] = self.object.participants.values_list('id', flat=True)
197
        return initial
198

    
199
    def get_form_kwargs(self):
200
        kwargs = super(UpdateEventView, self).get_form_kwargs()
201
        kwargs['occurrence'] = self.occurrence
202
        return kwargs
203

    
204
def new_appointment(request):
205
    pass
206

    
207
class AgendaServiceActValidationView(TemplateView):
208

    
209
    template_name = 'agenda/act-validation.html'
210

    
211
    def acts_of_the_day(self):
212
        return get_acts_of_the_day(self.date, self.service)
213

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

    
237
    def get_context_data(self, **kwargs):
238
        context = super(AgendaServiceActValidationView, self).get_context_data(**kwargs)
239
        authorized_lock = True # is_authorized_for_locking(get_request().user)
240
        validation_msg = ValidationMessage.objects.\
241
            filter(validation_date=self.date, service=self.service).\
242
            order_by('-when')[:3]
243
        acts_of_the_day = self.acts_of_the_day()
244
        actes = list()
245
        for act in acts_of_the_day:
246
            state = act.get_state()
247
            display_name = VALIDATION_STATES[state.state_name]
248
            if not state.previous_state:
249
                state = None
250
            act.date = act.date.strftime("%H:%M")
251
            actes.append((act, state, display_name))
252
        context['validation_states'] = VALIDATION_STATES
253
        context['actes'] = actes
254
        context['validation_msg'] = validation_msg
255
        context['authorized_lock'] = authorized_lock
256
        return context
257

    
258

    
259
class AutomatedValidationView(TemplateView):
260
    template_name = 'agenda/automated-validation.html'
261

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

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

    
280
        nb_acts_not_validated = nb_acts_double + \
281
            nb_acts_abs_non_exc + \
282
            nb_acts_abs_exc + \
283
            nb_acts_annul_nous + \
284
            nb_acts_annul_famille + \
285
            nb_acts_abs_ess_pps + \
286
            nb_acts_enf_hosp
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_annul_nous': nb_acts_annul_nous,
295
            'nb_acts_annul_famille': nb_acts_annul_famille,
296
            'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
297
            'nb_acts_enf_hosp': nb_acts_enf_hosp})
298
        return context
299

    
300
class UnlockAllView(CreateView):
301
    pass
302

    
303

    
304
class AgendasTherapeutesView(AgendaHomepageView):
305

    
306
    template_name = 'agenda/agendas-therapeutes.html'
307

    
308
    def get_context_data(self, **kwargs):
309
        context = super(AgendasTherapeutesView, self).get_context_data(**kwargs)
310
        for worker_agenda in context.get('workers_agenda', []):
311
            patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
312
            worker_agenda['summary'] = {
313
              'rdv': len(patient_appointments),
314
              'presence': len([x for x in patient_appointments if x.act_absence is None]),
315
              'absence': len([x for x in patient_appointments if x.act_absence is not None]),
316
              'doubles': len([x for x in patient_appointments if x.act_type == 'ACT_DOUBLE']),
317
              'valides': len([x for x in patient_appointments if x.act_type == 'ACT_VALIDE']),
318
            }
319

    
320
        return context
321

    
322
class JoursNonVerrouillesView(TemplateView):
323

    
324
    template_name = 'agenda/days-not-locked.html'
325

    
326
    def get_context_data(self, **kwargs):
327
        context = super(JoursNonVerrouillesView, self).get_context_data(**kwargs)
328
        acts = EventAct.objects.filter(is_billed=False,
329
            patient__service=self.service).order_by('date')
330
        days_not_locked = []
331
        for act in acts:
332
            current_day = datetime.datetime(act.date.year, act.date.month, act.date.day)
333
            if not current_day in days_not_locked:
334
                locked = are_all_acts_of_the_day_locked(current_day, self.service)
335
                if not locked:
336
                    days_not_locked.append(current_day)
337
        context['days_not_locked'] = days_not_locked
338
        return context
339

    
(10-10/10)