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