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