1
|
# -*- coding: utf-8 -*-
|
2
|
from collections import defaultdict
|
3
|
from datetime import date
|
4
|
from interval import IntervalSet
|
5
|
import logging
|
6
|
|
7
|
from dateutil.relativedelta import relativedelta
|
8
|
|
9
|
from django.http import HttpResponseRedirect, Http404, HttpResponse
|
10
|
from django.db.models import Q
|
11
|
from django.contrib.auth.models import User
|
12
|
from django.contrib import messages
|
13
|
from django.core.urlresolvers import reverse
|
14
|
from django.utils.dateformat import format as date_format
|
15
|
from django.views.decorators.csrf import csrf_exempt
|
16
|
|
17
|
from calebasse import cbv, models as cb_models
|
18
|
from calebasse.ressources.models import Service
|
19
|
|
20
|
import json
|
21
|
|
22
|
from calebasse.decorators import super_user_only
|
23
|
|
24
|
import forms
|
25
|
import models
|
26
|
|
27
|
logger = logging.getLogger(__name__)
|
28
|
|
29
|
|
30
|
FILTER_CRITERIA = (
|
31
|
'username',
|
32
|
'first_name',
|
33
|
'last_name',
|
34
|
'email',
|
35
|
'userworker__worker__display_name',
|
36
|
)
|
37
|
|
38
|
class AccessView(cbv.ListView):
|
39
|
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
|
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
|
|
61
|
class AccessUpdateView(cbv.ServiceFormMixin, cbv.UpdateView):
|
62
|
model = User
|
63
|
template_name = 'personnes/acces-update.html'
|
64
|
form_class = forms.UserForm
|
65
|
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
|
qs = qs.select_related()
|
78
|
qs = qs.prefetch_related('services')
|
79
|
qs = qs.filter()
|
80
|
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
|
qs = qs.filter(enabled=intervene_status[0] == 'a')
|
95
|
else:
|
96
|
# only display current workers by default
|
97
|
qs = qs.filter(enabled=True)
|
98
|
today = date.today()
|
99
|
if models.Holiday.objects.for_service(self.service).future() \
|
100
|
.filter(start_date__lte=today).exists():
|
101
|
for worker in qs:
|
102
|
worker.holiday = True
|
103
|
else:
|
104
|
qs2 = models.Holiday.objects.today().filter(worker__isnull=False)
|
105
|
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
|
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
|
user_listing = super_user_only(AccessView.as_view())
|
122
|
|
123
|
|
124
|
class UserCreateView(cbv.ServiceFormMixin, cbv.CreateView):
|
125
|
model = User
|
126
|
success_url = '../'
|
127
|
form_class = forms.UserForm
|
128
|
template_name = 'calebasse/simple-form.html'
|
129
|
template_name_suffix = '_new.html'
|
130
|
|
131
|
class UserDisactivateView(cbv.DeleteView):
|
132
|
model = User
|
133
|
success_url = "../../"
|
134
|
template_name = 'calebasse/generic_confirm_delete.html'
|
135
|
|
136
|
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
|
|
143
|
user_new = super_user_only(UserCreateView.as_view())
|
144
|
user_update = super_user_only(AccessUpdateView.as_view())
|
145
|
user_delete = super_user_only(UserDisactivateView.as_view())
|
146
|
|
147
|
|
148
|
class WorkerUpdateView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
|
149
|
model = models.Worker
|
150
|
forms_classes = {
|
151
|
'id': forms.WorkerIdForm,
|
152
|
'services': forms.WorkerServiceForm
|
153
|
}
|
154
|
template_name = 'personnes/worker_update.html'
|
155
|
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
|
for weekday, name in models.TimeTable.WEEKDAYS:
|
164
|
timetable.append({
|
165
|
'weekday': name,
|
166
|
'schedules': _timetables[weekday]})
|
167
|
ctx['weekdays'] = list(models.TimeTable.WEEKDAYS)
|
168
|
ctx['timetables'] = timetable
|
169
|
ctx['holidays'] = models.Holiday.objects \
|
170
|
.for_worker(self.object) \
|
171
|
.order_by('-start_date')
|
172
|
try:
|
173
|
holiday = models.Holiday.objects \
|
174
|
.for_worker(self.object) \
|
175
|
.today()[0]
|
176
|
except IndexError:
|
177
|
holiday = None
|
178
|
ctx['holiday'] = holiday
|
179
|
return ctx
|
180
|
|
181
|
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
|
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
|
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
|
return kwargs
|
197
|
|
198
|
def get_context_data(self, **kwargs):
|
199
|
ctx = super(WorkerScheduleUpdateView, self).get_context_data(**kwargs)
|
200
|
ctx['weekday'] = models.TimeTable.WEEKDAYS[self.weekday][1]
|
201
|
return ctx
|
202
|
|
203
|
def dispatch(self, *args, **kwargs):
|
204
|
self.weekday = int(kwargs['weekday'])
|
205
|
if self.weekday > 6:
|
206
|
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
|
instance.weekday = self.weekday
|
213
|
instance.save()
|
214
|
form.save_m2m()
|
215
|
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
|
def get_success_url(self):
|
225
|
return self.success_url
|
226
|
|
227
|
|
228
|
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
|
worker_update = WorkerUpdateView.as_view()
|
233
|
worker_schedule_update = WorkerScheduleUpdateView.as_view()
|
234
|
worker_holidays_update = WorkerHolidaysUpdateView.as_view()
|
235
|
worker_delete = cbv.DeleteView.as_view(model=models.Worker,
|
236
|
template_name='calebasse/simple-form.html',
|
237
|
success_url='../../')
|
238
|
|
239
|
|
240
|
class HolidayView(cbv.TemplateView, cbv.ServiceViewMixin):
|
241
|
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
|
form = forms.HolidaySearchForm(data=self.request.GET)
|
250
|
|
251
|
today = date.today()
|
252
|
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
|
service = Service.objects.get(slug = ctx['service'])
|
268
|
all_holidays = holidays.filter(services=service, worker__isnull=True)
|
269
|
|
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
|
return reverse('worker_update', kwargs=dict(
|
279
|
service = ctx['service'], pk=holiday.worker.pk))
|
280
|
else:
|
281
|
slug = ctx['service']
|
282
|
return reverse('group-holidays', kwargs=dict(
|
283
|
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
|
month_name = date_format(start_date, 'F')
|
295
|
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
|
ctx['search_form'] = form
|
312
|
return ctx
|
313
|
|
314
|
|
315
|
holiday_listing = HolidayView.as_view()
|
316
|
|
317
|
|
318
|
class GroupHolidayUpdateView(cbv.FormView):
|
319
|
form_class = forms.GroupHolidayFormSet
|
320
|
template_name = 'personnes/group_holiday_update.html'
|
321
|
success_url = '.'
|
322
|
|
323
|
def get_form_kwargs(self):
|
324
|
kwargs = super(GroupHolidayUpdateView, self).get_form_kwargs()
|
325
|
qs = models.Holiday.objects.for_service(self.service)
|
326
|
kwargs['queryset'] = qs
|
327
|
kwargs['service'] = self.service
|
328
|
return kwargs
|
329
|
|
330
|
def form_valid(self, form):
|
331
|
form.save()
|
332
|
return super(GroupHolidayUpdateView, self).form_valid(form)
|
333
|
|
334
|
|
335
|
group_holiday_update = GroupHolidayUpdateView.as_view()
|
336
|
|
337
|
class GroupHolidaysList(cbv.ListView):
|
338
|
model = models.Holiday
|
339
|
template_name = 'personnes/group_holidays_list.html'
|
340
|
queryset = model.objects.future().filter(worker__isnull=True)
|
341
|
|
342
|
def get_queryset(self, *args, **kwargs):
|
343
|
qs = super(GroupHolidaysList, self).get_queryset(*args, **kwargs)
|
344
|
return qs
|
345
|
|
346
|
group_holidays = GroupHolidaysList.as_view()
|
347
|
|
348
|
class HolidayManagement(object):
|
349
|
"""
|
350
|
A class providing some methods for handling the absences management
|
351
|
"""
|
352
|
model = models.Holiday
|
353
|
form_class = forms.HolidayForm
|
354
|
|
355
|
def get_initial(self):
|
356
|
worker = models.Worker.objects.get(pk=self.kwargs['worker_pk'])
|
357
|
return {'services': worker.services.all()}
|
358
|
|
359
|
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
|
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
|
class GroupHolidayManagement(HolidayManagement):
|
377
|
form_class = forms.GroupHolidayForm
|
378
|
|
379
|
def get_initial(self):
|
380
|
return {'services': Service.objects.all()}
|
381
|
|
382
|
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
|
except Exception, e:
|
395
|
logger.debug('Error on creating a group holiday: %s' % e)
|
396
|
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
|
def get_initial(self):
|
405
|
return
|
406
|
|
407
|
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
|
except Exception, e:
|
417
|
logger.debug('Error on updating a group holiday: %s' % e)
|
418
|
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
|
|
422
|
edit_group_holiday = EditGroupHolidayView.as_view()
|
423
|
|
424
|
class HolidayCreateView(HolidayManagement, cbv.CreateView):
|
425
|
|
426
|
def form_valid(self, form):
|
427
|
try:
|
428
|
super(HolidayCreateView, self).form_valid(form)
|
429
|
messages.success(self.request, u'Absence ajoutée avec succès')
|
430
|
except Exception, e:
|
431
|
logger.debug('Error on creating a holiday: %s' % e)
|
432
|
messages.error(self.request, u'Une erreur est survenue lors de l\'ajout de l\'absence')
|
433
|
return self.render_to_json(self.get_success_url())
|
434
|
|
435
|
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
|
def form_valid(self, form):
|
446
|
try:
|
447
|
super(EditHolidayView, self).form_valid(form)
|
448
|
messages.success(self.request, u'Données mises à jour avec succès')
|
449
|
except Exception, e:
|
450
|
logger.debug('Error on updating a holiday: %s' % e)
|
451
|
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
|
|
454
|
edit_holiday = EditHolidayView.as_view()
|
455
|
|
456
|
class DeleteHolidayView(HolidayManagement, cbv.DeleteView):
|
457
|
template_name = 'personnes/holiday_update_form.html'
|
458
|
|
459
|
def delete(self, request, *args, **kwargs):
|
460
|
try:
|
461
|
super(DeleteHolidayView, self).delete(request, *args, **kwargs)
|
462
|
messages.success(request, u'Absence supprimée avec succès')
|
463
|
except Exception, e:
|
464
|
logger.debug('Error on deleting a holiday: %s' % e)
|
465
|
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
|
|
469
|
delete_holiday = DeleteHolidayView.as_view()
|
470
|
|
471
|
class DeleteGroupHolidayView(GroupHolidayManagement, DeleteHolidayView):
|
472
|
template_name = 'personnes/group_holiday_update_form.html'
|
473
|
|
474
|
delete_group_holiday = DeleteGroupHolidayView.as_view()
|