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