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