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, cbv.ServiceViewMixin):
|
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_update', kwargs=dict(
|
270
|
service = ctx['service'], pk=holiday.worker.pk))
|
271
|
else:
|
272
|
slug = ctx['service']
|
273
|
return reverse('group-holidays', 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
|
"""
|
330
|
A class providing some methods for handling the absences management
|
331
|
"""
|
332
|
|
333
|
def render_to_json(self, id, context, err = 0, **kwargs):
|
334
|
data = {'err': err, 'id': id, 'content': context}
|
335
|
response = json.dumps(data)
|
336
|
kwargs['content_type'] = 'application/json'
|
337
|
return HttpResponse(response, **kwargs)
|
338
|
|
339
|
def update_post_data(self, request):
|
340
|
worker = models.Worker.objects.get(pk = self.kwargs['worker_pk'])
|
341
|
post = request.POST.copy()
|
342
|
post.update({'worker': worker.id})
|
343
|
return worker, post
|
344
|
|
345
|
def form_valid(self, form):
|
346
|
form.save()
|
347
|
if self.request.is_ajax:
|
348
|
instance = form.instance
|
349
|
status = ''
|
350
|
if instance.is_current() and instance.services.count():
|
351
|
status = u'congés annuels, en cours'
|
352
|
elif instance.is_current():
|
353
|
status = u'en cours'
|
354
|
elif instance.services.count():
|
355
|
status = u'congés annuels'
|
356
|
|
357
|
context = (('period', '%s' % instance),
|
358
|
('status', status),
|
359
|
('type', '%s' % instance.holiday_type),
|
360
|
('comment', instance.comment)
|
361
|
)
|
362
|
return self.render_to_json(instance.id, context)
|
363
|
return super(HolidayManagement, self).form_valid(form)
|
364
|
|
365
|
def group_form_valid(self, form):
|
366
|
"""
|
367
|
Method handling the saving of group absences form
|
368
|
"""
|
369
|
form.save()
|
370
|
form.save_m2m()
|
371
|
if self.request.is_ajax:
|
372
|
instance = form.instance
|
373
|
context = (('start_date', '%s' % instance.start_date),
|
374
|
('end_date', '%s' % instance.end_date),
|
375
|
('start_time',
|
376
|
instance.start_time and '%s' % instance.start_time or '---'),
|
377
|
('end_time',
|
378
|
instance.end_time and '%s' % instance.end_time or '---'),
|
379
|
('type', '%s' % instance.holiday_type),
|
380
|
('all',
|
381
|
instance.for_all_services() and '<span class="icon-ok"></span>' or ''),
|
382
|
('comment',
|
383
|
instance.comment)
|
384
|
)
|
385
|
return self.render_to_json(instance.id, context)
|
386
|
return super(EditGroupHolidayView, self).form_valid(form)
|
387
|
|
388
|
class GroupHolidaysList(cbv.ListView):
|
389
|
model = models.Holiday
|
390
|
template_name = 'personnes/group_holidays_list.html'
|
391
|
queryset = model.objects.future()
|
392
|
|
393
|
def get_queryset(self, *args, **kwargs):
|
394
|
qs = super(GroupHolidaysList, self).get_queryset(*args, **kwargs)
|
395
|
qs = qs.for_service(self.service)
|
396
|
return qs
|
397
|
|
398
|
group_holidays = GroupHolidaysList.as_view()
|
399
|
|
400
|
class CreateGroupHolidayView(HolidayManagement, cbv.CreateView):
|
401
|
form_class = forms.GroupHolidayForm
|
402
|
model = models.Holiday
|
403
|
template_name_suffix = '_group_form'
|
404
|
|
405
|
def get_form_kwargs(self):
|
406
|
return {'initial': {'services': Service.objects.all()}}
|
407
|
|
408
|
def post(self, request, *args, **kwargs):
|
409
|
form = self.form_class(request.POST)
|
410
|
if form.is_valid():
|
411
|
return self.group_form_valid(form)
|
412
|
|
413
|
return self.form_invalid(form)
|
414
|
|
415
|
|
416
|
create_group_holiday = CreateGroupHolidayView.as_view()
|
417
|
|
418
|
class EditGroupHolidayView(HolidayManagement, cbv.FormView):
|
419
|
template_name = 'personnes/group_holiday_update_form.html'
|
420
|
form_class = forms.GroupHolidayForm
|
421
|
model = models.Holiday
|
422
|
|
423
|
def get_form_kwargs(self):
|
424
|
kwargs = super(EditGroupHolidayView, self).get_form_kwargs()
|
425
|
kwargs['instance'] = self.model.objects.get(pk = self.kwargs['pk'])
|
426
|
return kwargs
|
427
|
|
428
|
def post(self, request, *args, **kwargs):
|
429
|
obj = self.model.objects.get(pk = self.kwargs['pk'])
|
430
|
form = self.form_class(request.POST, instance = obj)
|
431
|
if form.is_valid():
|
432
|
return self.group_form_valid(form)
|
433
|
|
434
|
return self.form_invalid(form)
|
435
|
|
436
|
edit_group_holiday = EditGroupHolidayView.as_view()
|
437
|
|
438
|
class DeleteGroupHolidayView(cbv.DeleteView):
|
439
|
model = models.Holiday
|
440
|
template_name = 'personnes/group_holiday_update_form.html'
|
441
|
success_url = '.'
|
442
|
|
443
|
def delete(self, request, *args, **kwargs):
|
444
|
response = HttpResponse('', content_type = 'application/json')
|
445
|
context = {'err': 0, 'message': ''}
|
446
|
try:
|
447
|
super(DeleteGroupHolidayView, self).delete(request, *args, **kwargs)
|
448
|
except Exception, e:
|
449
|
context['message'] = '%s' % e
|
450
|
response.content = json.dumps(context)
|
451
|
return response
|
452
|
|
453
|
delete_group_holiday = DeleteGroupHolidayView.as_view()
|
454
|
|
455
|
class HolidayCreateView(HolidayManagement, cbv.CreateView):
|
456
|
model = models.Holiday
|
457
|
form_class = forms.HolidayForm
|
458
|
|
459
|
def post(self, request, *args, **kwargs):
|
460
|
worker, post = self.update_post_data(request)
|
461
|
form = self.form_class(post)
|
462
|
if form.is_valid():
|
463
|
return self.form_valid(form)
|
464
|
else:
|
465
|
return super(HolidayCreateView, self).post(request, *args, **kwargs)
|
466
|
|
467
|
create_holiday = HolidayCreateView.as_view()
|
468
|
|
469
|
class EditHolidayView(HolidayManagement, cbv.FormView):
|
470
|
template_name = 'personnes/holiday_update_form.html'
|
471
|
form_class = forms.HolidayForm
|
472
|
model = models.Holiday
|
473
|
|
474
|
def get_form_kwargs(self):
|
475
|
kwargs = super(EditHolidayView, self).get_form_kwargs()
|
476
|
kwargs['instance'] = self.model.objects.get(pk = self.kwargs['pk'])
|
477
|
return kwargs
|
478
|
|
479
|
def post(self, request, *args, **kwargs):
|
480
|
worker, post = self.update_post_data(request)
|
481
|
obj = self.model.objects.for_worker(worker).get(pk = kwargs['pk'])
|
482
|
form = self.form_class(post, instance = obj)
|
483
|
if form.is_valid():
|
484
|
return self.form_valid(form)
|
485
|
else:
|
486
|
return self.form_invalid(form)
|
487
|
|
488
|
|
489
|
edit_holiday = EditHolidayView.as_view()
|
490
|
|
491
|
class DeleteHolidayView(cbv.DeleteView):
|
492
|
model = models.Holiday
|
493
|
template_name = 'personnes/holiday_update_form.html'
|
494
|
|
495
|
def post(self, request, *args, **kwargs):
|
496
|
response = HttpResponse('', content_type = 'application/json')
|
497
|
context = {'err': 0, 'message': ''}
|
498
|
try:
|
499
|
#worker = models.Worker.objects.get(pk = self.kwargs['worker_pk'])
|
500
|
super(DeleteHolidayView, self).post(request, *args, **kwargs)
|
501
|
#self.model.objects.for_worker(worker).get(pk = self.kwargs['pk']).delete()
|
502
|
except Exception, e:
|
503
|
context['message'] = '%s' % e.message
|
504
|
response.content = json.dumps(context)
|
505
|
return response
|
506
|
|
507
|
delete_holiday = DeleteHolidayView.as_view()
|
508
|
|
509
|
#user_delete = UserCreateView.as_view()
|
510
|
|