Project

General

Profile

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

calebasse / calebasse / agenda / views.py @ c8d74e1a

1
import datetime
2

    
3
from django.db.models import Q
4
from django.shortcuts import redirect
5
from django.http import HttpResponseRedirect
6

    
7
from calebasse.cbv import TemplateView, CreateView, UpdateView
8
from calebasse.agenda.models import Occurrence, Event, EventType
9
from calebasse.personnes.models import TimeTable
10
from calebasse.actes.models import EventAct
11
from calebasse.agenda.appointments import get_daily_appointments
12
from calebasse.personnes.models import Worker
13
from calebasse.ressources.models import WorkerType
14
from calebasse.actes.validation import (are_all_acts_of_the_day_locked,
15
    get_acts_of_the_day)
16
from calebasse.actes.validation_states import VALIDATION_STATES, VALIDE
17
from calebasse.actes.models import Act
18
from calebasse.actes.validation import (automated_validation,
19
    unlock_all_acts_of_the_day)
20

    
21
from forms import (NewAppointmentForm, NewEventForm,
22
        UpdateAppointmentForm, UpdateEventForm)
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 get_context_data(self, **kwargs):
34
        context = super(AgendaHomepageView, self).get_context_data(**kwargs)
35

    
36
        weekday_mapping = {
37
                '0': u'dimanche',
38
                '1': u'lundi',
39
                '2': u'mardi',
40
                '3': u'mercredi',
41
                '4': u'jeudi',
42
                '5': u'vendredi',
43
                '6': u'samedi'
44
                }
45
        weekday = weekday_mapping[context['date'].strftime("%w")]
46
        time_tables = TimeTable.objects.select_related('worker').\
47
                filter(service=self.service).\
48
                filter(weekday=weekday).\
49
                filter(start_date__lte=context['date']).\
50
                filter(Q(end_date=None) |Q(end_date__gte=context['date'])).\
51
                order_by('start_date')
52
        occurrences = Occurrence.objects.daily_occurrences(context['date']).order_by('start_time')
53

    
54
        context['workers_types'] = []
55
        context['workers_agenda'] = []
56
        context['disponnibility'] = {}
57
        workers = []
58
        for worker_type in WorkerType.objects.all():
59
            workers_type = Worker.objects.for_service(self.service, worker_type)
60
            if workers_type:
61
                data = {'type': worker_type.name, 'workers': workers_type }
62
                context['workers_types'].append(data)
63
                workers.extend(data['workers'])
64

    
65
        occurrences_workers = {}
66
        time_tables_workers = {}
67
        for worker in workers:
68
            time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
69
            occurrences_worker = [o for o in occurrences if worker.id in o.event.participants.values_list('id', flat=True)]
70
            occurrences_workers[worker.id] = occurrences_worker
71
            time_tables_workers[worker.id] = time_tables_worker
72
            context['workers_agenda'].append({'worker': worker,
73
                    'appointments': get_daily_appointments(context['date'], worker, self.service,
74
                        time_tables_worker, occurrences_worker)})
75

    
76
        context['disponibility'] = Occurrence.objects.daily_disponiblity(context['date'],
77
                occurrences_workers, workers, time_tables_workers)
78
        return context
79

    
80
class AgendaServiceActivityView(TemplateView):
81

    
82
    template_name = 'agenda/service-activity.html'
83

    
84
    def get_context_data(self, **kwargs):
85
        context = super(AgendaServiceActivityView, self).get_context_data(**kwargs)
86

    
87
        appointments_times = dict()
88
        appoinment_type = EventType.objects.get(id=1)
89
        occurrences = Occurrence.objects.daily_occurrences(context['date'],
90
                services=[self.service],
91
                event_type=appoinment_type)
92
        for occurrence in occurrences:
93
            start_time = occurrence.start_time.strftime("%H:%M")
94
            if not appointments_times.has_key(start_time):
95
                appointments_times[start_time] = dict()
96
                appointments_times[start_time]['row'] = 0
97
                appointments_times[start_time]['appointments'] = []
98
            appointment = dict()
99
            length = occurrence.end_time - occurrence.start_time
100
            if length.seconds:
101
                length = length.seconds / 60
102
                appointment['length'] = "%sm" % length
103
            event_act = occurrence.event.eventact
104
            appointment['patient'] = event_act.patient.display_name
105
            appointment['therapists'] = ""
106
            for participant in occurrence.event.participants.all():
107
                appointment['therapists'] += participant.display_name + "; "
108
            if appointment['therapists']:
109
                appointment['therapists'] = appointment['therapists'][:-2]
110
            appointment['act'] = event_act.act_type.name
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(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.kwargs.get('date')
126
        initial['participants'] = self.request.GET.getlist('participants')
127
        initial['time'] = self.request.GET.get('time')
128
        return initial
129

    
130
    def get_form_kwargs(self):
131
        kwargs = super(NewAppointmentView, self).get_form_kwargs()
132
        kwargs['service'] = self.service
133
        return kwargs
134

    
135
class UpdateAppointmentView(UpdateView):
136
    model = EventAct
137
    form_class = UpdateAppointmentForm
138
    template_name = 'agenda/update-rdv.html'
139
    success_url = '..'
140

    
141
    def get_object(self, queryset=None):
142
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
143
        if self.occurrence.event.eventact:
144
            return self.occurrence.event.eventact
145

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

    
159
    def get_form_kwargs(self):
160
        kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
161
        kwargs['occurrence'] = self.occurrence
162
        return kwargs
163

    
164

    
165
class NewEventView(CreateView):
166
    model = Event
167
    form_class = NewEventForm
168
    template_name = 'agenda/new-event.html'
169
    success_url = '..'
170

    
171
    def get_initial(self):
172
        initial = super(NewEventView, self).get_initial()
173
        initial['date'] = self.kwargs.get('date')
174
        initial['participants'] = self.request.GET.getlist('participants')
175
        initial['time'] = self.request.GET.get('time')
176
        initial['services'] = [self.service]
177
        initial['event_type'] = 2
178
        return initial
179

    
180
class UpdateEventView(UpdateView):
181
    model = Event
182
    form_class = UpdateEventForm
183
    template_name = 'agenda/update-event.html'
184
    success_url = '..'
185

    
186
    def get_object(self, queryset=None):
187
        self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
188
        return self.occurrence.event
189

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

    
203
    def get_form_kwargs(self):
204
        kwargs = super(UpdateEventView, self).get_form_kwargs()
205
        kwargs['occurrence'] = self.occurrence
206
        return kwargs
207

    
208
def new_appointment(request):
209
    pass
210

    
211
class AgendaServiceActValidationView(TemplateView):
212

    
213
    template_name = 'agenda/act-validation.html'
214

    
215
    def acts_of_the_day(self):
216
        return get_acts_of_the_day(self.date)
217

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

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

    
257

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

    
261
    def post(self, request, *args, **kwargs):
262
        automated_validation(self.date, self.service,
263
            request.user)
264
        return HttpResponseRedirect('..')
265

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

    
276
        nb_acts_not_validated = nb_acts_double + \
277
            nb_acts_abs_non_exc + \
278
            nb_acts_abs_exc + \
279
            nb_acts_annul_nous + \
280
            nb_acts_annul_famille + \
281
            nb_acts_abs_ess_pps + \
282
            nb_acts_enf_hosp
283
        context.update({
284
            'nb_acts_total': nb_acts_total,
285
            'nb_acts_validated': nb_acts_validated,
286
            'nb_acts_not_validated': nb_acts_not_validated,
287
            'nb_acts_double': nb_acts_double,
288
            'nb_acts_abs_non_exc': nb_acts_abs_non_exc,
289
            'nb_acts_abs_exc': nb_acts_abs_exc,
290
            'nb_acts_annul_nous': nb_acts_annul_nous,
291
            'nb_acts_annul_famille': nb_acts_annul_famille,
292
            'nb_acts_abs_ess_pps': nb_acts_abs_ess_pps,
293
            'nb_acts_enf_hosp': nb_acts_enf_hosp})
294
        return context
295

    
296
class UnlockAllView(CreateView):
297
    pass
(10-10/10)