Project

General

Profile

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

calebasse / calebasse / personnes / views.py @ 0d4bf0b4

1 c2f3ff62 Mikaël Ates
# -*- coding: utf-8 -*-
2 04022fee Benjamin Dauvergne
from collections import defaultdict
3
from datetime import date
4 84614733 Benjamin Dauvergne
from interval import IntervalSet
5 46f98e2c Serghei MIHAI
import logging
6 04022fee Benjamin Dauvergne
7 f69ae8a2 Benjamin Dauvergne
from dateutil.relativedelta import relativedelta
8
9 c029f285 Serghei MIHAI
from django.http import HttpResponseRedirect, Http404, HttpResponse
10 32486db7 Benjamin Dauvergne
from django.db.models import Q
11
from django.contrib.auth.models import User
12 c2f3ff62 Mikaël Ates
from django.contrib import messages
13 84614733 Benjamin Dauvergne
from django.core.urlresolvers import reverse
14 e6e5249f Benjamin Dauvergne
from django.utils.dateformat import format as date_format
15 c029f285 Serghei MIHAI
from django.views.decorators.csrf import csrf_exempt
16 32486db7 Benjamin Dauvergne
17 04022fee Benjamin Dauvergne
from calebasse import cbv, models as cb_models
18 f8f903c3 Benjamin Dauvergne
from calebasse.ressources.models import Service
19 32486db7 Benjamin Dauvergne
20 c029f285 Serghei MIHAI
import json
21
22 5c9faa2c Mikaël Ates
from calebasse.decorators import super_user_only
23
24 32486db7 Benjamin Dauvergne
import forms
25 957da834 Benjamin Dauvergne
import models
26 32486db7 Benjamin Dauvergne
27 46f98e2c Serghei MIHAI
logger = logging.getLogger(__name__)
28
29 32486db7 Benjamin Dauvergne
30
FILTER_CRITERIA = (
31
        'username',
32
        'first_name',
33
        'last_name',
34
        'email',
35
        'userworker__worker__display_name',
36
)
37
38 957da834 Benjamin Dauvergne
class AccessView(cbv.ListView):
39 32486db7 Benjamin Dauvergne
    model = User
40
    template_name = 'personnes/acces.html'
41
42
    def get_queryset(self):
43
        qs = super(AccessView, self).get_queryset()
44
        identifier = self.request.GET.get('identifier')
45
        if identifier:
46
            for part in identifier.split():
47
                filters = []
48
                for criteria in FILTER_CRITERIA:
49
                    q = Q(**{criteria+'__contains': part})
50
                    filters.append(q)
51
                qs = qs.filter(reduce(Q.__or__, filters))
52
        qs = qs.prefetch_related('userworker__worker')
53
        return qs
54
55 548f19f9 Benjamin Dauvergne
    def get_context_data(self, **kwargs):
56
        ctx = super(AccessView, self).get_context_data(**kwargs)
57
        ctx['active_list'] = ctx['object_list'].filter(is_active=True)
58
        return ctx
59
60 957da834 Benjamin Dauvergne
61
class AccessUpdateView(cbv.ServiceFormMixin, cbv.UpdateView):
62 32486db7 Benjamin Dauvergne
    model = User
63
    template_name = 'personnes/acces-update.html'
64
    form_class = forms.UserForm
65 957da834 Benjamin Dauvergne
    success_url = '../'
66
67
68
class WorkerView(cbv.ListView):
69
    model = models.Worker
70
    template_name = 'personnes/workers.html'
71
72
    def get_form(self):
73
        return forms.WorkerSearchForm(data=self.request.GET or None)
74
75
    def get_queryset(self):
76
        qs = super(WorkerView, self).get_queryset()
77 04022fee Benjamin Dauvergne
        qs = qs.select_related()
78
        qs = qs.prefetch_related('services')
79 a78c2263 Jérôme Schneider
        qs = qs.filter()
80 957da834 Benjamin Dauvergne
        form = self.get_form()
81
        if form.is_valid():
82
            cleaned_data = form.cleaned_data
83
            last_name = cleaned_data.get('last_name')
84
            first_name = cleaned_data.get('first_name')
85
            profession = cleaned_data.get('profession')
86
            intervene_status = cleaned_data.get('intervene_status')
87
            if last_name:
88
                qs = qs.filter(last_name__icontains=last_name)
89
            if first_name:
90
                qs = qs.filter(first_name__icontains=first_name)
91
            if profession:
92
                qs = qs.filter(type=profession)
93
            if intervene_status and 0 < len(intervene_status) < 2:
94 c5dd5b8a Mikaël Ates
                qs = qs.filter(enabled=intervene_status[0] == 'a')
95 937f1ad2 Frédéric Péters
        else:
96
            # only display current workers by default
97
            qs = qs.filter(enabled=True)
98 04022fee Benjamin Dauvergne
        today = date.today()
99 a5bdc8ec Benjamin Dauvergne
        if models.Holiday.objects.for_service(self.service).future() \
100 04022fee Benjamin Dauvergne
                .filter(start_date__lte=today).exists():
101
            for worker in qs:
102
                worker.holiday = True
103
        else:
104 672109c5 Serghei MIHAI
            qs2 = models.Holiday.objects.today().filter(worker__isnull=False)
105 04022fee Benjamin Dauvergne
            worker_dict = dict(((w.id, w) for w in qs))
106
            for worker in qs:
107
                worker.holiday = False
108
            for holiday in qs2:
109
                if holiday.worker.id in worker_dict:
110
                    worker_dict[holiday.worker.id].holiday = True
111 957da834 Benjamin Dauvergne
        return qs
112
113
    def get_context_data(self, **kwargs):
114
        ctx = super(WorkerView, self).get_context_data(**kwargs)
115
        ctx['search_form'] = self.get_form()
116
        return ctx
117
118
homepage = cbv.TemplateView.as_view(template_name='personnes/index.html')
119
120
121 5c9faa2c Mikaël Ates
user_listing = super_user_only(AccessView.as_view())
122 34029347 Benjamin Dauvergne
123
124
class UserCreateView(cbv.ServiceFormMixin, cbv.CreateView):
125 3396c6cb Jérôme Schneider
    model = User
126
    success_url = '../'
127
    form_class = forms.UserForm
128
    template_name = 'calebasse/simple-form.html'
129
    template_name_suffix = '_new.html'
130 34029347 Benjamin Dauvergne
131 a37b870f Jérôme Schneider
class UserDisactivateView(cbv.DeleteView):
132 7843b54f Jérôme Schneider
    model = User
133
    success_url = "../../"
134
    template_name = 'calebasse/generic_confirm_delete.html'
135
136 a37b870f Jérôme Schneider
    def delete(self, request, *args, **kwargs):
137
        self.object = self.get_object()
138
        self.object.is_active = False
139
        self.object.save()
140
        return HttpResponseRedirect(self.get_success_url())
141
142 34029347 Benjamin Dauvergne
143 5c9faa2c Mikaël Ates
user_new = super_user_only(UserCreateView.as_view())
144
user_update = super_user_only(AccessUpdateView.as_view())
145 a37b870f Jérôme Schneider
user_delete = super_user_only(UserDisactivateView.as_view())
146 957da834 Benjamin Dauvergne
147
148 5b88932c Mikaël Ates
class WorkerUpdateView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
149 04022fee Benjamin Dauvergne
    model = models.Worker
150
    forms_classes = {
151 c5dd5b8a Mikaël Ates
            'id': forms.WorkerIdForm,
152 04022fee Benjamin Dauvergne
            'services': forms.WorkerServiceForm
153
    }
154 4696b827 Benjamin Dauvergne
    template_name = 'personnes/worker_update.html'
155 04022fee Benjamin Dauvergne
    success_url = './'
156
157
    def get_context_data(self, **kwargs):
158
        ctx = super(WorkerUpdateView, self).get_context_data(**kwargs)
159
        _timetables = defaultdict(lambda: [])
160
        for timetable in self.object.timetable_set.order_by('start_time'):
161
            _timetables[timetable.weekday].append(timetable)
162
        timetable = []
163 f8f903c3 Benjamin Dauvergne
        for weekday, name in models.TimeTable.WEEKDAYS:
164 04022fee Benjamin Dauvergne
            timetable.append({
165 f8f903c3 Benjamin Dauvergne
                'weekday': name,
166 04022fee Benjamin Dauvergne
                'schedules': _timetables[weekday]})
167 f8f903c3 Benjamin Dauvergne
        ctx['weekdays'] = list(models.TimeTable.WEEKDAYS)
168 04022fee Benjamin Dauvergne
        ctx['timetables'] = timetable
169
        ctx['holidays'] = models.Holiday.objects \
170
                            .for_worker(self.object) \
171 f1db8cdd Serghei MIHAI
                            .order_by('-start_date')
172 04022fee Benjamin Dauvergne
        try:
173 a5bdc8ec Benjamin Dauvergne
            holiday = models.Holiday.objects \
174
                    .for_worker(self.object) \
175
                    .today()[0]
176 04022fee Benjamin Dauvergne
        except IndexError:
177
            holiday = None
178
        ctx['holiday'] = holiday
179
        return ctx
180
181 c2f3ff62 Mikaël Ates
    def form_valid(self, form):
182
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
183
        return super(WorkerUpdateView, self).form_valid(form)
184
185
186 04022fee Benjamin Dauvergne
class WorkerScheduleUpdateView(cbv.UpdateView):
187
    model = models.Worker
188
    form_class = forms.TimetableFormSet
189
    success_url = '../'
190
    template_name = 'personnes/worker_schedule_update.html'
191
192
    def get_form_kwargs(self):
193
        kwargs = super(WorkerScheduleUpdateView, self).get_form_kwargs()
194 f8f903c3 Benjamin Dauvergne
        kwargs['queryset'] = models.TimeTable.objects.filter(weekday=self.weekday).prefetch_related('services')
195
        kwargs['initial'] = [{ 'services': Service.objects.all().values_list('pk', flat=True) }] * 3
196 04022fee Benjamin Dauvergne
        return kwargs
197
198
    def get_context_data(self, **kwargs):
199
        ctx = super(WorkerScheduleUpdateView, self).get_context_data(**kwargs)
200 f8f903c3 Benjamin Dauvergne
        ctx['weekday'] = models.TimeTable.WEEKDAYS[self.weekday][1]
201 04022fee Benjamin Dauvergne
        return ctx
202
203
    def dispatch(self, *args, **kwargs):
204 f8f903c3 Benjamin Dauvergne
        self.weekday = int(kwargs['weekday'])
205
        if self.weekday > 6:
206 04022fee Benjamin Dauvergne
            raise Http404()
207
        return super(WorkerScheduleUpdateView, self).dispatch(*args, **kwargs)
208
209
    def form_valid(self, form):
210
        instances = form.save(commit=False)
211
        for instance in instances:
212 f8f903c3 Benjamin Dauvergne
            instance.weekday = self.weekday
213 04022fee Benjamin Dauvergne
            instance.save()
214 52d3b722 Benjamin Dauvergne
        form.save_m2m()
215 04022fee Benjamin Dauvergne
        return HttpResponseRedirect('')
216
217
218
class WorkerHolidaysUpdateView(cbv.UpdateView):
219
    model = models.Worker
220
    form_class = forms.HolidayFormSet
221
    success_url = '../'
222
    template_name = 'personnes/worker_holidays_update.html'
223
224 f69ae8a2 Benjamin Dauvergne
    def get_success_url(self):
225
        return self.success_url
226
227
228 957da834 Benjamin Dauvergne
worker_listing = WorkerView.as_view()
229
worker_new = cbv.CreateView.as_view(model=models.Worker,
230
        template_name='calebasse/simple-form.html',
231
        success_url='../')
232 04022fee Benjamin Dauvergne
worker_update = WorkerUpdateView.as_view()
233
worker_schedule_update = WorkerScheduleUpdateView.as_view()
234
worker_holidays_update = WorkerHolidaysUpdateView.as_view()
235 957da834 Benjamin Dauvergne
worker_delete = cbv.DeleteView.as_view(model=models.Worker,
236
        template_name='calebasse/simple-form.html',
237 cfbe06e8 Benjamin Dauvergne
        success_url='../../')
238 f69ae8a2 Benjamin Dauvergne
239
240 5b90c12e Serghei MIHAI
class HolidayView(cbv.TemplateView, cbv.ServiceViewMixin):
241 f69ae8a2 Benjamin Dauvergne
    months = 3
242
    template_name='personnes/holidays.html'
243
244
    def get_form(self):
245
        return forms.HolidaySearchForm(data=self.request.GET)
246
247
    def get_context_data(self, **kwargs):
248
        ctx = super(HolidayView, self).get_context_data(**kwargs)
249 84614733 Benjamin Dauvergne
        form = forms.HolidaySearchForm(data=self.request.GET)
250
251 f69ae8a2 Benjamin Dauvergne
        today = date.today()
252 84614733 Benjamin Dauvergne
        filter_start_date = today
253
        filter_end_date = date.today() + relativedelta(months=self.months)
254
255
        if form.is_valid():
256
            if form.cleaned_data.get('start_date'):
257
                filter_start_date = form.cleaned_data.get('start_date')
258
            if form.cleaned_data.get('end_date'):
259
                filter_end_date = form.cleaned_data.get('end_date')
260
261
        workers = models.Worker.objects.filter(enabled=True)
262
        holidays = models.Holiday.objects \
263
                .filter(end_date__gte=filter_start_date,
264
                        start_date__lte=filter_end_date) \
265
                .select_related('worker', 'service')
266
        holiday_by_worker = defaultdict(lambda: [])
267 b4e25157 Serghei MIHAI
        service = Service.objects.get(slug = ctx['service'])
268 14a6b60b Serghei MIHAI
        all_holidays = holidays.filter(services=service, worker__isnull=True)
269 84614733 Benjamin Dauvergne
270
        for worker in workers:
271
            holiday_by_worker[worker] = list(all_holidays)
272
273
        for holiday in holidays.filter(worker__isnull=False):
274
            holiday_by_worker[holiday.worker].append(holiday)
275
276
        def holiday_url(holiday):
277
            if holiday.worker:
278 e840a72b Serghei MIHAI
                return reverse('worker_update', kwargs=dict(
279 5b90c12e Serghei MIHAI
                    service = ctx['service'], pk=holiday.worker.pk))
280 84614733 Benjamin Dauvergne
            else:
281 5b90c12e Serghei MIHAI
                slug = ctx['service']
282 3ade90b9 Serghei MIHAI
                return reverse('group-holidays', kwargs=dict(
283 84614733 Benjamin Dauvergne
                    service=slug))
284
285
        currents = []
286
        futures = defaultdict(lambda: [])
287
        for worker, holidays in holiday_by_worker.iteritems():
288
            for holiday in holidays:
289
                url = holiday_url(holiday)
290
                holiday_tpl = dict(worker=worker.display_name, holiday=holiday, url=url)
291
                if holiday.start_date <= today <= holiday.end_date:
292
                    currents.append(holiday_tpl)
293
                start_date = max(holiday.start_date, filter_start_date)
294 e6e5249f Benjamin Dauvergne
                month_name = date_format(start_date, 'F')
295 84614733 Benjamin Dauvergne
                key = start_date.year, start_date.month, month_name
296
                futures[key].append(holiday_tpl)
297
298
        future_holidays = []
299
        for key in sorted(futures.keys()):
300
            future_holidays.append(dict(
301
                month=key[2],
302
                holidays=futures[key]))
303
        future_holidays2 = []
304
        for i in range(0, len(future_holidays), 2):
305
            future_holidays2.append(future_holidays[i:i+2])
306
307
        ctx['end_date'] = filter_end_date
308
        ctx['current_holidays'] = currents
309
        ctx['future_holidays'] = future_holidays2
310
        ctx['group_holidays'] = all_holidays.order_by('-start_date')
311 f69ae8a2 Benjamin Dauvergne
        ctx['search_form'] = form
312
        return ctx
313
314
315
holiday_listing = HolidayView.as_view()
316
317
318 9edb5f60 Mikaël Ates
class GroupHolidayUpdateView(cbv.FormView):
319
    form_class = forms.GroupHolidayFormSet
320
    template_name = 'personnes/group_holiday_update.html'
321 d964fe2f Benjamin Dauvergne
    success_url = '.'
322 f69ae8a2 Benjamin Dauvergne
323
    def get_form_kwargs(self):
324 9edb5f60 Mikaël Ates
        kwargs = super(GroupHolidayUpdateView, self).get_form_kwargs()
325 f69ae8a2 Benjamin Dauvergne
        qs = models.Holiday.objects.for_service(self.service)
326
        kwargs['queryset'] = qs
327 57212b18 Benjamin Dauvergne
        kwargs['service'] = self.service
328 f69ae8a2 Benjamin Dauvergne
        return kwargs
329
330 d964fe2f Benjamin Dauvergne
    def form_valid(self, form):
331
        form.save()
332 9edb5f60 Mikaël Ates
        return super(GroupHolidayUpdateView, self).form_valid(form)
333 d964fe2f Benjamin Dauvergne
334 f69ae8a2 Benjamin Dauvergne
335 9edb5f60 Mikaël Ates
group_holiday_update = GroupHolidayUpdateView.as_view()
336 7843b54f Jérôme Schneider
337 3ade90b9 Serghei MIHAI
class GroupHolidaysList(cbv.ListView):
338
    model = models.Holiday
339
    template_name = 'personnes/group_holidays_list.html'
340 8379904e Serghei MIHAI
    queryset = model.objects.future().filter(worker__isnull=True)
341 3ade90b9 Serghei MIHAI
342 5b90c12e Serghei MIHAI
    def get_queryset(self, *args, **kwargs):
343
        qs = super(GroupHolidaysList, self).get_queryset(*args, **kwargs)
344
        return qs
345
346 3ade90b9 Serghei MIHAI
group_holidays = GroupHolidaysList.as_view()
347
348 8e003db0 Serghei MIHAI
class HolidayManagement(object):
349
    """
350
    A class providing some methods for handling the absences management
351
    """
352 c029f285 Serghei MIHAI
    model = models.Holiday
353
    form_class = forms.HolidayForm
354
355 bc16b4d1 Serghei MIHAI
    def get_initial(self):
356
        worker = models.Worker.objects.get(pk=self.kwargs['worker_pk'])
357
        return {'services': worker.services.all()}
358
359 c2953462 Serghei MIHAI
    def form_valid(self, form):
360
        holiday = form.save()
361
        worker = models.Worker.objects.get(pk=self.kwargs['worker_pk'])
362
        holiday.worker = worker
363
        holiday.save()
364
365 8e003db0 Serghei MIHAI
    def render_to_json(self, location, err = 0, **kwargs):
366
        data = {'err': err, 'location': location}
367
        response = json.dumps(data)
368
        kwargs['content_type'] = 'application/json'
369
        return HttpResponse(response, **kwargs)
370
371
    def get_success_url(self):
372
        slug = self.service.slug
373
        return reverse('worker_update', kwargs={'pk': self.kwargs['worker_pk'],
374
                                                'service': slug})
375
376 9090fa1a Serghei MIHAI
class GroupHolidayManagement(HolidayManagement):
377
    form_class = forms.GroupHolidayForm
378
379 b1c329fc Serghei MIHAI
    def get_initial(self):
380
        return {'services': Service.objects.all()}
381
382 9090fa1a Serghei MIHAI
    def get_success_url(self):
383
        slug = self.service.slug
384
        return reverse('group-holidays', kwargs={'service': slug})
385
386
class CreateGroupHolidayView(GroupHolidayManagement, cbv.CreateView):
387
388
    template_name_suffix = '_group_form'
389
390
    def form_valid(self, form):
391
        try:
392
            form.save()
393
            messages.success(self.request, u'Absence ajoutée avec succès')
394 46f98e2c Serghei MIHAI
        except Exception, e:
395
            logger.debug('Error on creating a group holiday: %s' % e)
396 9090fa1a Serghei MIHAI
            messages.error(self.request, u'Une erreur est survenue lors de l\'ajout de l\'absence')
397
        return self.render_to_json(self.get_success_url())
398
399
create_group_holiday = CreateGroupHolidayView.as_view()
400
401
class EditGroupHolidayView(GroupHolidayManagement, cbv.FormView):
402
    template_name = 'personnes/group_holiday_update_form.html'
403
404 6fd0e5b8 Serghei MIHAI
    def get_initial(self):
405
        return
406
407 9090fa1a Serghei MIHAI
    def get_form_kwargs(self):
408
        kwargs = super(EditGroupHolidayView, self).get_form_kwargs()
409
        kwargs['instance'] = self.model.objects.get(pk = self.kwargs['pk'])
410
        return kwargs
411
412
    def form_valid(self, form):
413
        try:
414
            form.save()
415
            messages.success(self.request, u'Données mises à jour avec succès')
416 46f98e2c Serghei MIHAI
        except Exception, e:
417
            logger.debug('Error on updating a group holiday: %s' % e)
418 9090fa1a Serghei MIHAI
            messages.error(self.request, u'Une erreur est survenue lors de la mise à jour de l\'absence')
419
        return self.render_to_json(self.get_success_url())
420
421 c2953462 Serghei MIHAI
422 9090fa1a Serghei MIHAI
edit_group_holiday = EditGroupHolidayView.as_view()
423
424 8e003db0 Serghei MIHAI
class HolidayCreateView(HolidayManagement, cbv.CreateView):
425
426
    def form_valid(self, form):
427 9090fa1a Serghei MIHAI
        try:
428 c2953462 Serghei MIHAI
            super(HolidayCreateView, self).form_valid(form)
429 9090fa1a Serghei MIHAI
            messages.success(self.request, u'Absence ajoutée avec succès')
430 46f98e2c Serghei MIHAI
        except Exception, e:
431
            logger.debug('Error on creating a holiday: %s' % e)
432 c2953462 Serghei MIHAI
            messages.error(self.request, u'Une erreur est survenue lors de l\'ajout de l\'absence')
433 8e003db0 Serghei MIHAI
        return self.render_to_json(self.get_success_url())
434 cb647183 Serghei MIHAI
435 c029f285 Serghei MIHAI
create_holiday = HolidayCreateView.as_view()
436
437
class EditHolidayView(HolidayManagement, cbv.FormView):
438
    template_name = 'personnes/holiday_update_form.html'
439
440
    def get_form_kwargs(self):
441
        kwargs = super(EditHolidayView, self).get_form_kwargs()
442
        kwargs['instance'] = self.model.objects.get(pk = self.kwargs['pk'])
443
        return kwargs
444
445 8e003db0 Serghei MIHAI
    def form_valid(self, form):
446
        try:
447 c2953462 Serghei MIHAI
            super(EditHolidayView, self).form_valid(form)
448 8e003db0 Serghei MIHAI
            messages.success(self.request, u'Données mises à jour avec succès')
449 46f98e2c Serghei MIHAI
        except Exception, e:
450
            logger.debug('Error on updating a holiday: %s' % e)
451 8e003db0 Serghei MIHAI
            messages.error(self.request, u'Une erreur est survenue lors de la mise à jour de l\'absence')
452
        return self.render_to_json(self.get_success_url())
453 c029f285 Serghei MIHAI
454
edit_holiday = EditHolidayView.as_view()
455
456 8e003db0 Serghei MIHAI
class DeleteHolidayView(HolidayManagement, cbv.DeleteView):
457 c029f285 Serghei MIHAI
    template_name = 'personnes/holiday_update_form.html'
458
459 8e003db0 Serghei MIHAI
    def delete(self, request, *args, **kwargs):
460 c029f285 Serghei MIHAI
        try:
461 8e003db0 Serghei MIHAI
            super(DeleteHolidayView, self).delete(request, *args, **kwargs)
462
            messages.success(request, u'Absence supprimée avec succès')
463 46f98e2c Serghei MIHAI
        except Exception, e:
464
            logger.debug('Error on deleting a holiday: %s' % e)
465 8e003db0 Serghei MIHAI
            messages.error(request, u'Une erreur est survenue lors de la suppression de l\'absence')
466
467
        return self.render_to_json(self.get_success_url())
468 c029f285 Serghei MIHAI
469
delete_holiday = DeleteHolidayView.as_view()
470 7843b54f Jérôme Schneider
471 9090fa1a Serghei MIHAI
class DeleteGroupHolidayView(GroupHolidayManagement, DeleteHolidayView):
472
    template_name = 'personnes/group_holiday_update_form.html'
473
474
delete_group_holiday = DeleteGroupHolidayView.as_view()