Merge branch 'dev' of ssh://git.auf.org/auf_rh_dae into dev
[auf_rh_dae.git] / project / rh / views.py
1 # -*- encoding: utf-8 -*-
2 from datetime import date
3 from itertools import izip
4 import networkx as nx
5
6 from django.db.models import Q
7 from django.contrib.auth.decorators import login_required
8 from django.utils.encoding import smart_str
9 from django.shortcuts import redirect, render_to_response, get_object_or_404
10 from django.template import RequestContext
11 from django.http import Http404
12
13 from datamaster_modeles import models as ref
14 from project.lib import get_employe_from_id
15
16 from rh import models as rh
17 from rh.lib import calc_remun
18 from rh.decorators import drh_or_admin_required
19 from rh.templatetags.rapports import SortHeaders
20 from rh.change_list import RechercheTemporelle
21
22 # pas de reference a DAE devrait etre refactorisé
23 from dae.utils import get_employe_from_user
24 from dae.decorators import redirect_interdiction
25 from dae.workflow import grp_drh, grp_correspondants_rh
26 from django.conf import settings
27
28 # homes
29 @login_required
30 def profil(request):
31 """Profil personnel de l'employé - éditable"""
32 rc = RequestContext(request)
33 c = {}
34
35 employe = rc['this_employe']
36
37 c['user'] = request.user
38 c['employe'] = employe
39 return render_to_response('rh/profil.html', c, rc)
40
41 # employes
42 @login_required
43 def employes_liste(request):
44 """Liste des employés."""
45 today = date.today()
46 employes = rh.Employe.objects \
47 .exclude(dossiers__date_debut__gt=today) \
48 .exclude(dossiers__date_fin__lt=today) \
49 .order_by('nom')
50 c = {
51 'user':request.user,
52 'employes':employes,
53 }
54 return render_to_response('rh/employes_liste.html', c, RequestContext(request))
55
56 @login_required
57 def employe(request, id):
58 """Information publique sur un employé."""
59 try:
60 employe = rh.Employe.objects.get(pk=id)
61 except:
62 employe = rh.Employe.objects.none()
63 c = {
64 'user':request.user,
65 'employe':employe,
66 }
67 return render_to_response('rh/employe.html', c, RequestContext(request))
68
69
70 # Rapports
71
72 @login_required
73 @drh_or_admin_required
74 def rapports_postes_hierarchie(request):
75
76 c = {}
77 graph = nx.Graph()
78 postes = rh.Poste.objects.all()
79 postes_id = dict((p.id, p) for p in postes)
80 graph.add_node(p.id for p in postes)
81
82 for p in postes:
83 if p.responsable_id != p.id:
84 graph.add_edge(postes_id[p.responsable_id].id, p.id)
85
86 c['postes'] = nx.to_dict_of_lists(graph)
87
88 return render_to_response('rh/rapports/postes_hierarchie.html', c, RequestContext(request))
89
90 @login_required
91 @drh_or_admin_required
92 def rapports_poste(request):
93
94 lookup_params = dict(request.GET.items())
95
96 comble = 'all'
97
98 for key, value in lookup_params.items():
99 if key == 'o' or key == 'ot':
100 del lookup_params[key]
101 continue
102 if not isinstance(key, str):
103 # 'key' will be used as a keyword argument later, so Python
104 # requires it to be a string.
105 del lookup_params[key]
106 lookup_params[smart_str(key)] = value
107
108 if key == 'comble':
109 comble = value
110 del lookup_params[key]
111
112 postes = rh.Poste.objects.select_related('implantation') \
113 .extra(select={'employe_id':'select group_concat(employe separator "|") from rh_dossier where poste=rh_poste.id and rh_dossier.date_fin is null %s' % \
114 ("%s" % (('order by employe %s' % ('asc' if 'ot' in request.GET and request.GET['ot'] == "asc" else "desc"))) if 'o' in request.GET and request.GET['o'] == "employe_id" else "") \
115 }) \
116 .extra(select={'employe_nom':'select group_concat(rh_employe.nom separator "|") from rh_dossier inner join rh_employe on rh_dossier.employe = rh_employe.id where poste=rh_poste.id and rh_dossier.date_fin is null %s' % \
117 ("%s" % (('order by rh_employe.nom %s' % ('asc' if 'ot' in request.GET and request.GET['ot'] == "asc" else "desc"))) if 'o' in request.GET and request.GET['o'] == "employe_nom" else "") \
118 }) \
119 .extra(select={'employe_prenom':'select group_concat(rh_employe.prenom separator "|") from rh_dossier inner join rh_employe on rh_dossier.employe = rh_employe.id where poste=rh_poste.id and rh_dossier.date_fin is null %s' % \
120 ("%s" % (('order by rh_employe.prenom %s' % ('asc' if 'ot' in request.GET and request.GET['ot'] == "asc" else "desc"))) if 'o' in request.GET and request.GET['o'] == "employe_prenom" else "") \
121 })
122
123 postes = postes.filter(**lookup_params)
124 if 'o' in request.GET:
125 postes = postes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
126
127 out = []
128 for p in postes:
129 out.append({
130 'id': p.id,
131 'nom': p.nom,
132 'implantation': p.implantation,
133 'employes': [] if not p.employe_id else [{'id': id, 'nom': nom, 'prenom': prenom} for id, nom, prenom in izip(p.employe_id.split('|'), p.employe_nom.split('|'), p.employe_prenom.split('|'))] })
134
135
136 headers = [
137 ("id", u"# du poste"),
138 ("nom", u"Nom du poste"),
139 ("implantation__id", u"Implantation"),
140 ("employe_nom", u"Nom"),
141 ]
142 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
143 c = {
144 'title': 'Rapport des postes',
145 'postes': out,
146 'count': len(out),
147 'headers': list(h.headers()),
148 }
149
150 return render_to_response('rh/rapports/postes.html', c, RequestContext(request))
151
152 @login_required
153 @drh_or_admin_required
154 def rapports_contrat(request):
155
156 lookup_params = dict(request.GET.items())
157 if 'ot' in lookup_params:
158 del lookup_params['ot']
159 if 'o' in lookup_params:
160 del lookup_params['o']
161
162 for key, value in lookup_params.items():
163 if not isinstance(key, str):
164 # 'key' will be used as a keyword argument later, so Python
165 # requires it to be a string.
166 del lookup_params[key]
167 lookup_params[smart_str(key)] = value
168
169 contrats = rh.Contrat.objects.select_related('dossier', 'dossier__poste', 'dossier__poste__implantation', 'type_contrat', 'dossier__employe')
170
171 cl = RechercheTemporelle(request, rh.Contrat)
172 lookup_params = cl.purge_params(lookup_params)
173 contrats = contrats.filter(**lookup_params).exclude(dossier__employe__supprime=1)
174 contrats = cl.filter_temporel(contrats)
175
176 if 'o' in request.GET:
177 contrats = contrats.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
178
179 employes = set([c.dossier.employe_id for c in contrats])
180
181 headers = [
182 ("dossier__employe__id", u"# de l'employé"),
183 ("dossier__employe__nom", u"Nom"),
184 ("dossier__employe__prenom", u"Prénom"),
185 ("type_contrat__nom", u"Poste"),
186 ("type_contrat__nom", u"Type de contrat"),
187 ("date_debut", u"Date début"),
188 ("date_fin", u"Date fin"),
189 ]
190 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
191
192 c = {
193 'cl' : cl,
194 'title': 'Rapport des contrats',
195 'contrats': contrats,
196 'count': len(contrats),
197 'count_employe' : len(employes),
198 'headers': list(h.headers()),
199 }
200
201 return render_to_response('rh/rapports/contrats.html', c, RequestContext(request))
202
203
204 @login_required
205 @drh_or_admin_required
206 def rapports_remuneration(request):
207
208 lookup_params = dict(request.GET.items())
209 if 'ot' in lookup_params:
210 del lookup_params['ot']
211 if 'o' in lookup_params:
212 del lookup_params['o']
213
214 for key, value in lookup_params.items():
215 if not isinstance(key, str):
216 # 'key' will be used as a keyword argument later, so Python
217 # requires it to be a string.
218 del lookup_params[key]
219 lookup_params[smart_str(key)] = value
220
221 employes = rh.Employe.objects.all()
222 if 'o' in request.GET:
223 employes = employes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
224
225 employes = employes.filter(**lookup_params)
226
227 output = []
228 headers = [
229 ("id", u"# de l'employé"),
230 ("nom", u"Nom"),
231 ("prenom", u"Prénom"),
232 ("", u"Salaire"),
233 ("", u"RAS"),
234 ("", u"Indemnités"),
235 ("", u"Accessoire"),
236 ("", u"Charges patronales"),
237 ("", u"Total"),
238 ]
239 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
240
241 for employe in employes:
242 line = {}
243 output.append(line)
244
245 dossiers = employe.rh_dossiers.all()
246
247 remun = {}
248 remun_sum_euro = 0
249
250 for dossier in dossiers:
251 this_remun, this_remun_sum, this_remun_sum_euro = calc_remun(dossier)
252
253 for item in this_remun:
254 if item not in remun:
255 remun[item] = this_remun[item]
256 else:
257 remun[item][0] += this_remun[item][0]
258 remun[item][1] += this_remun[item][1]
259
260 remun_sum_euro += this_remun_sum_euro
261
262 line['remun_sum_euro'] = remun_sum_euro
263
264 for r in remun:
265 if r == u'Indemnité':
266 line['Indemnite'] = remun[r][1]
267 else:
268 line[r] = remun[r][1]
269
270 line['id'] = employe.id
271 line['nom'] = employe.nom
272 line['prenom'] = employe.prenom
273
274
275 c = {
276 'title': 'Rapport de remuneration',
277 'employes': output,
278 'headers': list(h.headers()),
279 }
280
281 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
282
283 @login_required
284 @drh_or_admin_required
285 def rapports_employe_sans_contrat(request):
286
287 lookup_params = dict(request.GET.items())
288 if 'ot' in lookup_params:
289 del lookup_params['ot']
290 if 'o' in lookup_params:
291 del lookup_params['o']
292
293 for key, value in lookup_params.items():
294 if not isinstance(key, str):
295 # 'key' will be used as a keyword argument later, so Python
296 # requires it to be a string.
297 del lookup_params[key]
298 lookup_params[smart_str(key)] = value
299
300 employes_query = rh.Employe.objects
301 if 'o' in request.GET:
302 employes_query = employes_query.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
303
304 employes = {}
305 for e in employes_query.all():
306 dossiers = rh.Dossier.objects.filter(employe=e). \
307 filter(Q(date_fin=None) | Q(date_fin__gt=date.today())). \
308 filter(**lookup_params).all()
309 for d in dossiers:
310 contrats = rh.Contrat.objects.filter(Q(dossier=d) & Q(date_fin__lt=date.today())).all()
311 if contrats:
312 if e.id not in employes:
313 employes[e.id] = {'employe': e, 'dossiers': set([d])}
314 else:
315 employes[e.id]['dossiers'].add(d)
316
317 headers = [
318 ("id", u"# de l'employé"),
319 ("nom", u"Nom"),
320 ("prenom", u"Prénom"),
321 ("dossier", u"Dossiers"),
322 ]
323 h = SortHeaders(request, headers, order_field_type="ot", order_field="o", not_sortable=('dossier',))
324
325 c = {
326 'title': u'Rapport des employés sans contrat',
327 'employes': employes,
328 'count': len(employes),
329 'headers': list(h.headers()),
330 }
331
332 return render_to_response('rh/rapports/employes_sans_contrat.html', c, RequestContext(request))
333
334 @login_required
335 @drh_or_admin_required
336 def rapports_postes_modelisation(request):
337 c = {}
338 data = []
339
340 for f in rh.FamilleEmploi.objects.all():
341 types = rh.TypePoste.objects.filter(famille_emploi=f)
342 data_types = []
343 for t in types.all():
344 postes = rh.Poste.objects.filter(type_poste=t)
345 data_types.append({
346 'num_postes': postes.count(),
347 'postes': postes.all(),
348 'type': f,
349 })
350
351 data.append({
352 'famille': f,
353 'nb_types': types.count(),
354 'types' : data_types
355 })
356
357 c['data'] = data
358
359
360 return render_to_response('rh/rapports/postes_modelisation.html', c, RequestContext(request))
361
362
363 @login_required
364 @drh_or_admin_required
365 def rapports_postes_implantation(request):
366 c = {}
367 data = []
368 for r in ref.Region.objects.all():
369 implantations = []
370 for i in ref.Implantation.objects.filter(region=r):
371 implantations.append({
372 'implantation': i,
373 'postes': rh.Poste.objects.filter(implantation=i),
374 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
375 })
376 data.append({
377 'region': r,
378 'implantations': implantations
379 })
380
381 c['data'] = data
382
383
384 return render_to_response('rh/rapports/postes_implantation.html', c, RequestContext(request))
385
386
387 @login_required
388 @drh_or_admin_required
389 def rapports_postes_service(request):
390 c = {}
391 data = []
392 for s in rh.Service.objects.all():
393 postes = rh.Poste.objects.filter(service=s).all()
394 num_postes = rh.Poste.objects.filter(service=s).count()
395 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
396
397 c['data'] = data
398 return render_to_response('rh/rapports/postes_service.html', c, RequestContext(request))
399
400
401 def region_protected(model):
402 def wrapper(func):
403 def wrapped(request, id):
404 if request.user.is_superuser:
405 return func(request, id)
406 user_groups = request.user.groups.all()
407 if grp_drh in user_groups:
408 return func(request, id)
409 if grp_correspondants_rh in user_groups:
410 employe = get_employe_from_user(request.user)
411 q = Q(**{model.prefix_implantation: employe.implantation.region})
412 qs = model.objects.filter(q)
413 if int(id) in [o.id for o in qs]:
414 return func(request, id)
415 return redirect_interdiction(request)
416 return wrapped
417 return wrapper
418
419
420 @region_protected(rh.Dossier)
421 def dossier_apercu(request, dossier_id):
422 d = get_object_or_404(rh.Dossier, pk=dossier_id)
423 c = {
424 'is_popup' : request.GET.get('_popup', False),
425 'dossier' : d,
426 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
427 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
428 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
429 'media_url': settings.PRIVE_MEDIA_URL,
430 }
431 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
432
433 @region_protected(rh.Poste)
434 def poste_apercu(request, poste_id):
435 c = {
436 'is_popup' : request.GET.get('_popup', False),
437 'poste' : get_object_or_404(rh.Poste, pk=poste_id),
438 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
439 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
440 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
441 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
442 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
443 'media_url': settings.PRIVE_MEDIA_URL,
444 }
445 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
446
447 def employe_apercu(request, employe_id):
448 from dae.workflow import grp_drh, grp_correspondants_rh
449 employe = get_object_or_404(rh.Employe, pk=employe_id)
450 user_groups = request.user.groups.all()
451
452 dernier_dossier = None
453 dossiers = None
454
455 if request.user.is_superuser or \
456 grp_drh in user_groups:
457 q = Q(employe=employe)
458 if grp_correspondants_rh in user_groups:
459 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
460 q = Q(employe=employe) & Q(implantation__region__in=regions)
461
462 dossiers = rh.Dossier.objects.filter(employe=employe).order_by('-date_debut')
463
464 c = {
465 'is_popup' : request.GET.get('_popup', False),
466 'employe' : employe,
467 'dossiers' : dossiers,
468 'media_url': settings.PRIVE_MEDIA_URL,
469 }
470 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
471
472