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