Project

General

Profile

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

calebasse / calebasse / personnes / views.py @ 53647eb3

1
# -*- coding: utf-8 -*-
2
from collections import defaultdict
3
from datetime import date
4
from interval import IntervalSet
5

    
6
from dateutil.relativedelta import relativedelta
7

    
8
from django.http import HttpResponseRedirect, Http404, HttpResponse
9
from django.db.models import Q
10
from django.contrib.auth.models import User
11
from django.contrib import messages
12
from django.core.urlresolvers import reverse
13
from django.utils.dateformat import format as date_format
14
from django.views.decorators.csrf import csrf_exempt
15

    
16
from calebasse import cbv, models as cb_models
17
from calebasse.ressources.models import Service
18

    
19
import json
20

    
21
from calebasse.decorators import super_user_only
22

    
23
import forms
24
import models
25

    
26

    
27
FILTER_CRITERIA = (
28
        'username',
29
        'first_name',
30
        'last_name',
31
        'email',
32
        'userworker__worker__display_name',
33
)
34

    
35
class AccessView(cbv.ListView):
36
    model = User
37
    template_name = 'personnes/acces.html'
38

    
39
    def get_queryset(self):
40
        qs = super(AccessView, self).get_queryset()
41
        identifier = self.request.GET.get('identifier')
42
        if identifier:
43
            for part in identifier.split():
44
                filters = []
45
                for criteria in FILTER_CRITERIA:
46
                    q = Q(**{criteria+'__contains': part})
47
                    filters.append(q)
48
                qs = qs.filter(reduce(Q.__or__, filters))
49
        qs = qs.prefetch_related('userworker__worker')
50
        return qs
51

    
52
    def get_context_data(self, **kwargs):
53
        ctx = super(AccessView, self).get_context_data(**kwargs)
54
        ctx['active_list'] = ctx['object_list'].filter(is_active=True)
55
        ctx['inactive_list'] = ctx['object_list'].filter(is_active=False)
56
        return ctx
57

    
58

    
59
class AccessUpdateView(cbv.ServiceFormMixin, cbv.UpdateView):
60
    model = User
61
    template_name = 'personnes/acces-update.html'
62
    form_class = forms.UserForm
63
    success_url = '../'
64

    
65

    
66
class WorkerView(cbv.ListView):
67
    model = models.Worker
68
    template_name = 'personnes/workers.html'
69

    
70
    def get_form(self):
71
        return forms.WorkerSearchForm(data=self.request.GET or None)
72

    
73
    def get_queryset(self):
74
        qs = super(WorkerView, self).get_queryset()
75
        qs = qs.select_related()
76
        qs = qs.prefetch_related('services')
77
        form = self.get_form()
78
        if form.is_valid():
79
            cleaned_data = form.cleaned_data
80
            last_name = cleaned_data.get('last_name')
81
            first_name = cleaned_data.get('first_name')
82
            profession = cleaned_data.get('profession')
83
            intervene_status = cleaned_data.get('intervene_status')
84
            if last_name:
85
                qs = qs.filter(last_name__icontains=last_name)
86
            if first_name:
87
                qs = qs.filter(first_name__icontains=first_name)
88
            if profession:
89
                qs = qs.filter(type=profession)
90
            if intervene_status and 0 < len(intervene_status) < 2:
91
                qs = qs.filter(enabled=intervene_status[0] == 'a')
92
        else:
93
            # only display current workers by default
94
            qs = qs.filter(enabled=True)
95
        today = date.today()
96
        if models.Holiday.objects.for_service(self.service).future() \
97
                .filter(start_date__lte=today).exists():
98
            for worker in qs:
99
                worker.holiday = True
100
        else:
101
            qs2 = models.Holiday.objects.today()
102
            worker_dict = dict(((w.id, w) for w in qs))
103
            for worker in qs:
104
                worker.holiday = False
105
            for holiday in qs2:
106
                if holiday.worker.id in worker_dict:
107
                    worker_dict[holiday.worker.id].holiday = True
108
        return qs
109

    
110
    def get_context_data(self, **kwargs):
111
        ctx = super(WorkerView, self).get_context_data(**kwargs)
112
        ctx['search_form'] = self.get_form()
113
        return ctx
114

    
115
homepage = cbv.TemplateView.as_view(template_name='personnes/index.html')
116

    
117

    
118
user_listing = super_user_only(AccessView.as_view())
119

    
120

    
121
class UserCreateView(cbv.ServiceFormMixin, cbv.CreateView):
122
    model=User
123
    success_url='../'
124
    form_class=forms.UserForm
125
    template_name='calebasse/simple-form.html'
126
    template_name_suffix='_new.html'
127

    
128
class UserDeleteView(cbv.DeleteView):
129
    model = User
130
    success_url = "../../"
131
    template_name = 'calebasse/generic_confirm_delete.html'
132

    
133

    
134
user_new = super_user_only(UserCreateView.as_view())
135
user_update = super_user_only(AccessUpdateView.as_view())
136
user_delete = super_user_only(UserDeleteView.as_view())
137

    
138

    
139
class WorkerUpdateView(cbv.MultiUpdateView):
140
    model = models.Worker
141
    forms_classes = {
142
            'id': forms.WorkerIdForm,
143
            'services': forms.WorkerServiceForm
144
    }
145
    template_name = 'personnes/worker_update.html'
146
    success_url = './'
147

    
148
    def get_context_data(self, **kwargs):
149
        ctx = super(WorkerUpdateView, self).get_context_data(**kwargs)
150
        _timetables = defaultdict(lambda: [])
151
        for timetable in self.object.timetable_set.order_by('start_time'):
152
            _timetables[timetable.weekday].append(timetable)
153
        timetable = []
154
        for weekday, name in models.TimeTable.WEEKDAYS:
155
            timetable.append({
156
                'weekday': name,
157
                'schedules': _timetables[weekday]})
158
        ctx['weekdays'] = list(models.TimeTable.WEEKDAYS)
159
        ctx['timetables'] = timetable
160
        ctx['holidays'] = models.Holiday.objects \
161
                            .for_worker(self.object) \
162
                            .future() \
163
                            .order_by('start_date')
164
        try:
165
            holiday = models.Holiday.objects \
166
                    .for_worker(self.object) \
167
                    .today()[0]
168
        except IndexError:
169
            holiday = None
170
        ctx['holiday'] = holiday
171
        return ctx
172

    
173
    def form_valid(self, form):
174
        messages.add_message(self.request, messages.INFO, u'Modification enregistrée avec succès.')
175
        return super(WorkerUpdateView, self).form_valid(form)
176

    
177

    
178
class WorkerScheduleUpdateView(cbv.UpdateView):
179
    model = models.Worker
180
    form_class = forms.TimetableFormSet
181
    success_url = '../'
182
    template_name = 'personnes/worker_schedule_update.html'
183

    
184
    def get_form_kwargs(self):
185
        kwargs = super(WorkerScheduleUpdateView, self).get_form_kwargs()
186
        kwargs['queryset'] = models.TimeTable.objects.filter(weekday=self.weekday).prefetch_related('services')
187
        kwargs['initial'] = [{ 'services': Service.objects.all().values_list('pk', flat=True) }] * 3
188
        return kwargs
189

    
190
    def get_context_data(self, **kwargs):
191
        ctx = super(WorkerScheduleUpdateView, self).get_context_data(**kwargs)
192
        ctx['weekday'] = models.TimeTable.WEEKDAYS[self.weekday][1]
193
        return ctx
194

    
195
    def dispatch(self, *args, **kwargs):
196
        self.weekday = int(kwargs['weekday'])
197
        if self.weekday > 6:
198
            raise Http404()
199
        return super(WorkerScheduleUpdateView, self).dispatch(*args, **kwargs)
200

    
201
    def form_valid(self, form):
202
        instances = form.save(commit=False)
203
        for instance in instances:
204
            instance.weekday = self.weekday
205
            instance.save()
206
        form.save_m2m()
207
        return HttpResponseRedirect('')
208

    
209

    
210
class WorkerHolidaysUpdateView(cbv.UpdateView):
211
    model = models.Worker
212
    form_class = forms.HolidayFormSet
213
    success_url = '../'
214
    template_name = 'personnes/worker_holidays_update.html'
215

    
216
    def get_success_url(self):
217
        return self.success_url
218

    
219

    
220
worker_listing = WorkerView.as_view()
221
worker_new = cbv.CreateView.as_view(model=models.Worker,
222
        template_name='calebasse/simple-form.html',
223
        success_url='../')
224
worker_update = WorkerUpdateView.as_view()
225
worker_schedule_update = WorkerScheduleUpdateView.as_view()
226
worker_holidays_update = WorkerHolidaysUpdateView.as_view()
227
worker_delete = cbv.DeleteView.as_view(model=models.Worker,
228
        template_name='calebasse/simple-form.html',
229
        success_url='../../')
230

    
231

    
232
class HolidayView(cbv.TemplateView):
233
    months = 3
234
    template_name='personnes/holidays.html'
235

    
236
    def get_form(self):
237
        return forms.HolidaySearchForm(data=self.request.GET)
238

    
239
    def get_context_data(self, **kwargs):
240
        ctx = super(HolidayView, self).get_context_data(**kwargs)
241
        form = forms.HolidaySearchForm(data=self.request.GET)
242

    
243
        today = date.today()
244
        filter_start_date = today
245
        filter_end_date = date.today() + relativedelta(months=self.months)
246

    
247
        if form.is_valid():
248
            if form.cleaned_data.get('start_date'):
249
                filter_start_date = form.cleaned_data.get('start_date')
250
            if form.cleaned_data.get('end_date'):
251
                filter_end_date = form.cleaned_data.get('end_date')
252

    
253
        workers = models.Worker.objects.filter(enabled=True)
254
        holidays = models.Holiday.objects \
255
                .filter(end_date__gte=filter_start_date,
256
                        start_date__lte=filter_end_date) \
257
                .select_related('worker', 'service')
258
        holiday_by_worker = defaultdict(lambda: [])
259
        all_holidays = holidays.filter(worker__isnull=True)
260

    
261
        for worker in workers:
262
            holiday_by_worker[worker] = list(all_holidays)
263

    
264
        for holiday in holidays.filter(worker__isnull=False):
265
            holiday_by_worker[holiday.worker].append(holiday)
266

    
267
        def holiday_url(holiday):
268
            if holiday.worker:
269
                return reverse('worker-holidays-update', kwargs=dict(
270
                    service=self.service.slug, pk=holiday.worker.pk))
271
            else:
272
                slug = holiday.service.slug if holiday.service else self.service.slug
273
                return reverse('group-holiday-update', kwargs=dict(
274
                    service=slug))
275

    
276
        currents = []
277
        futures = defaultdict(lambda: [])
278
        for worker, holidays in holiday_by_worker.iteritems():
279
            for holiday in holidays:
280
                url = holiday_url(holiday)
281
                holiday_tpl = dict(worker=worker.display_name, holiday=holiday, url=url)
282
                if holiday.start_date <= today <= holiday.end_date:
283
                    currents.append(holiday_tpl)
284
                start_date = max(holiday.start_date, filter_start_date)
285
                month_name = date_format(start_date, 'F')
286
                key = start_date.year, start_date.month, month_name
287
                futures[key].append(holiday_tpl)
288

    
289
        future_holidays = []
290
        for key in sorted(futures.keys()):
291
            future_holidays.append(dict(
292
                month=key[2],
293
                holidays=futures[key]))
294
        future_holidays2 = []
295
        for i in range(0, len(future_holidays), 2):
296
            future_holidays2.append(future_holidays[i:i+2])
297

    
298
        ctx['end_date'] = filter_end_date
299
        ctx['current_holidays'] = currents
300
        ctx['future_holidays'] = future_holidays2
301
        ctx['group_holidays'] = all_holidays.order_by('-start_date')
302
        ctx['search_form'] = form
303
        return ctx
304

    
305

    
306
holiday_listing = HolidayView.as_view()
307

    
308

    
309
class GroupHolidayUpdateView(cbv.FormView):
310
    form_class = forms.GroupHolidayFormSet
311
    template_name = 'personnes/group_holiday_update.html'
312
    success_url = '.'
313

    
314
    def get_form_kwargs(self):
315
        kwargs = super(GroupHolidayUpdateView, self).get_form_kwargs()
316
        qs = models.Holiday.objects.for_service(self.service)
317
        kwargs['queryset'] = qs
318
        kwargs['service'] = self.service
319
        return kwargs
320

    
321
    def form_valid(self, form):
322
        form.save()
323
        return super(GroupHolidayUpdateView, self).form_valid(form)
324

    
325

    
326
group_holiday_update = GroupHolidayUpdateView.as_view()
327

    
328
class HolidayManagement(object):
329
    def render_to_json(self, id, context, err = 0, **kwargs):
330
        data = {'err': err, 'id': id, 'content': context}
331
        response = json.dumps(data)
332
        kwargs['content_type'] = 'application/json'
333
        return HttpResponse(response, **kwargs)
334

    
335
    def form_valid(self, form):
336
        form.save()
337
        if self.request.is_ajax:
338
            instance = form.instance
339
            status = ''
340
            if instance.is_current() and instance.service:
341
                status = u'congés annuels, en cours'
342
            elif instance.is_current():
343
                status = u'en cours'
344
            elif instance.service:
345
                status = u'congés annuels'
346

    
347
            context = (('period', '%s' % instance),
348
                       ('status', status),
349
                       ('type', '%s' % instance.holiday_type),
350
                       ('comment', instance.comment)
351
                       )
352
            return self.render_to_json(instance.id, context)
353
        return super(HolidayManagement, self).form_valid(form)
354

    
355
class HolidayCreateView(HolidayManagement, cbv.ServiceFormMixin,
356
                        cbv.CreateView):
357
    model = models.Holiday
358
    form_class = forms.HolidayForm
359

    
360
    def get_form_kwargs(self, *args, **kwargs):
361
        kwargs = super(HolidayCreateView, self).get_form_kwargs(*args, **kwargs)
362
        worker = models.Worker.objects.get(pk = self.kwargs['worker_pk'])
363
        kwargs['initial'] = {'service': self.service, 'worker': worker}
364
        del kwargs['service']
365
        return kwargs
366

    
367
create_holiday = HolidayCreateView.as_view()
368

    
369
class EditHolidayView(HolidayManagement, cbv.FormView):
370
    template_name = 'personnes/holiday_update_form.html'
371
    form_class = forms.HolidayForm
372
    model = models.Holiday
373

    
374
    def get_form_kwargs(self):
375
        kwargs = super(EditHolidayView, self).get_form_kwargs()
376
        kwargs['instance'] = self.model.objects.get(pk = self.kwargs['pk'])
377
        return kwargs
378

    
379
    def post(self, request, *args, **kwargs):
380
        worker = models.Worker.objects.get(pk = self.kwargs['worker_pk'])
381
        obj = self.model.objects.for_worker(worker).get(pk = self.kwargs['pk'])
382
        form = self.form_class(request.POST, instance = obj)
383
        if form.is_valid():
384
            return self.form_valid(form)
385
        else:
386
            return self.form_invalid(form)
387

    
388

    
389
edit_holiday = EditHolidayView.as_view()
390

    
391
class DeleteHolidayView(cbv.DeleteView):
392
    model = models.Holiday
393
    template_name = 'personnes/holiday_update_form.html'
394

    
395
    def post(self, request, *args, **kwargs):
396
        response = HttpResponse('', content_type = 'application/json')
397
        context = {'err': 0, }
398
        try:
399
            worker = models.Worker.objects.get(pk = self.kwargs['worker_pk'])
400
            self.model.objects.for_worker(worker).get(pk = self.kwargs['pk']).delete()
401
        except Exception, e:
402
            context['error': e.message]
403
        response.content = json.dumps(context)
404
        return response
405

    
406
delete_holiday = DeleteHolidayView.as_view()
407

    
408
#user_delete = UserCreateView.as_view()
409

    
(8-8/8)