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