ergo UI : uniformiastion colonnes des changelists
[auf_rh_dae.git] / project / rh / views.py
CommitLineData
e9bbd6ba 1# -*- encoding: utf-8 -*-
22343fe7 2
e90b19fd 3import urllib
c9122f1d 4from datetime import date
a7de62d7 5from itertools import izip
eabb27fd 6import StringIO
9b0a8554 7
9f55f18a 8import pygraphviz as pgv
e949324b 9
e90b19fd 10from django import forms
4ba84959 11from django.conf import settings
e90b19fd 12from django.contrib.auth.decorators import login_required
eabb27fd 13from django.core.servers.basehttp import FileWrapper
dcd1b959 14from django.core.urlresolvers import reverse
fbe60a9d 15from django.db.models import Q
4ba84959 16from django.http import HttpResponse
890b80e7 17from django.shortcuts import render, get_object_or_404
e9bbd6ba 18
4c17e518 19from auf.django.references import models as ref
e9bbd6ba 20
acbc95a1 21from project.decorators import redirect_interdiction
018c8eaf 22from project.decorators import drh_or_admin_required
ae99002a 23from project.decorators import region_protected
afd3be54 24from project.groups import get_employe_from_user
a4198848 25from project.groups import grp_drh, grp_correspondants_rh
e9bbd6ba 26
4ba84959 27from project.rh import models as rh
4ba84959 28from project.rh import graph as rh_graph
890b80e7 29from project.rh.change_list import RechercheTemporelle
2cb9e555 30from project.rh.lib import calc_remun, get_lookup_params
4ba84959 31from project.rh.masse_salariale import MasseSalariale
890b80e7 32from project.rh.templatetags.rapports import SortHeaders
9817fed5 33
22343fe7 34
c9122f1d 35@login_required
36def profil(request):
37 """Profil personnel de l'employé - éditable"""
7d0c2206
DB
38 employe = get_employe_from_user(user)
39 c = {
8b3f6ff5
DB
40 'user': request.user,
41 'employe': employe,
7d0c2206 42 }
890b80e7 43 return render(request, 'rh/profil.html', c)
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 }
890b80e7 58 return render(request, 'rh/employes_liste.html', c)
22343fe7
OL
59
60
3411ac33 61@login_required
a9faef67 62def employe(request, id):
63 """Information publique sur un employé."""
64 try:
65 employe = rh.Employe.objects.get(pk=id)
66 except:
67 employe = rh.Employe.objects.none()
68 c = {
22343fe7
OL
69 'user': request.user,
70 'employe': employe,
a9faef67 71 }
890b80e7 72 return render(request, 'rh/employe.html', c)
63e17dff
PP
73
74
08faf06e
JPC
75@login_required
76@drh_or_admin_required
f2d65e83 77def rapports_contrat(request):
dd18f6e3 78 # statut default = actif?
dcd1b959 79 if 'HTTP_REFERER' in request.META.keys():
58348377
EMS
80 referer = request.META['HTTP_REFERER']
81 referer = "/".join(referer.split('/')[3:])
82 referer = "/%s" % referer.split('?')[0]
83 if referer != reverse('rhr_contrats'):
84 params = request.GET.copy()
85 params.update({'statut': 'Actif'})
86 request.GET = params
f2d65e83 87
00ca4d9f
EMS
88 contrats = rh.Contrat.objects.select_related(
89 'dossier', 'dossier__poste', 'dossier__poste__implantation',
90 'type_contrat', 'dossier__employe'
91 )
22343fe7 92
dd18f6e3 93 # filters et recherche temporelle
6bee05ff 94 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
dd18f6e3 95 lookup_params = get_lookup_params(request)
f0f6b03e 96 lookup_params = cl.purge_params(lookup_params)
dcd1b959
OL
97 q_temporel = cl.get_q_temporel(contrats)
98 q = Q(**lookup_params) & q_temporel
99 contrats = contrats.filter(q).exclude(dossier__employe__supprime=1)
f0f6b03e 100
dd18f6e3 101 # tri
65e02621 102 if 'o' in request.GET:
00ca4d9f
EMS
103 contrats = contrats.order_by(
104 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
105 )
f2d65e83 106
dd18f6e3 107 # affichage
8ee135b7
JPC
108 employes = set([c.dossier.employe_id for c in contrats])
109
65e02621 110 headers = [
dd18f6e3 111 ("dossier__employe__id", u"#"),
d50a5e5d 112 ("dossier__employe__nom", u"Employé"),
dd18f6e3
DB
113 ("dossier", u"Dossier : Poste"),
114 ("type_contrat__nom", u"Contrat"),
115 ("date_debut", u"Début contrat"),
116 ("date_fin", u"Fin contrat"),
117 ("dossier__statut_residence", u"Statut"),
d50a5e5d
OL
118 ("dossier__poste__implantation__region", u"Région"),
119 ("dossier__poste__implantation", u"Implantation"),
65e02621 120 ]
dd18f6e3
DB
121 h = SortHeaders(
122 request, headers, order_field_type="ot", order_field="o",
123 not_sortable=('dossier',)
124 )
65e02621 125
f2d65e83 126 c = {
00ca4d9f 127 'cl': cl,
f2d65e83
PP
128 'title': 'Rapport des contrats',
129 'contrats': contrats,
00ca4d9f 130 'count_employe': len(employes),
65e02621 131 'headers': list(h.headers()),
f2d65e83 132 }
890b80e7 133 return render(request, 'rh/rapports/contrats.html', c)
e2c0b1ac
PP
134
135
02c1b3dc
JPC
136@login_required
137@drh_or_admin_required
5db1c5a3
DB
138def rapports_employes_sans_contrat(request):
139 """
140 Employé sans contrat = a un Dossier qui n'a pas de Contrat associé
141 Employé avec contrat échu = a un Dossier avec un Contrat se terminant hier
142 au plus tard... (aujourd'hui = ok, pas date de fin = illimité donc ok)
143 """
144 lookup_params = get_lookup_params(request)
145
146 # contrats échus
147 contrats_echus = rh.Contrat.objects.filter(
148 date_fin__lt=date.today()
149 ).filter(
150 **lookup_params
151 )
152
153 # dossiers en cours sans contrat ou contrats échus
154 dossiers = rh.Dossier.objects.filter(
155 Q(date_debut=None) | Q(date_debut__lte=date.today()),
156 ).filter(
157 Q(date_fin=None) | Q(date_fin__gte=date.today()),
158 ).exclude(
159 date_debut__gt=date.today()
160 ).filter(
161 # sans contrat | contrat échu
162 Q(rh_contrats=None) | Q(rh_contrats__in=contrats_echus)
163 ).distinct()
164
165 # employés sans contrat ou contrats échus
166 employes = rh.Employe.objects.filter(rh_dossiers__in=dossiers) \
167 .distinct().count()
168
169 # tri
170 if 'o' in request.GET:
171 dossiers = dossiers.order_by(
172 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
173 )
174
175 # affichage
176 headers = [
177 ("employe__id", u"#"),
178 ("employe__nom", u"Employé"),
179 ("dossier", u"Dossier : Poste"),
180 ("rh_contrats__type_contrat", u"Contrat"),
181 ("rh_contrats__date_debut", u"Début contrat"),
182 ("rh_contrats__date_fin", u"Fin contrat"),
183 ("statut_residence", u"Statut"),
184 ("poste__implantation__region__code", u"Région"),
185 ("poste__implantation__nom", u"Implantation"),
186 ]
187 h = SortHeaders(
188 request, headers, order_field_type="ot", order_field="o",
189 not_sortable=('dossier',)
190 )
191
192 c = {
193 'title': u'Rapport des employés sans contrat ou contrat échu',
194 'employes': employes,
195 'dossiers': dossiers,
196 'headers': list(h.headers()),
197 }
198
199 return render(request, 'rh/rapports/employes_sans_contrat.html', c)
200
201
202@login_required
203@drh_or_admin_required
98d6eb6c 204def rapports_masse_salariale(request):
df37184c 205
e90b19fd 206 class RechercheTemporelle(forms.Form):
aecb222b 207 CHOICE_ANNEES = range(
00ca4d9f
EMS
208 rh.Remuneration.objects.exclude(date_debut=None)
209 .order_by('date_debut')[0].date_debut.year,
210 date.today().year + 1
211 )
212
213 annee = forms.CharField(
214 initial=date.today().year,
215 widget=forms.Select(
216 choices=((a, a) for a in reversed(CHOICE_ANNEES))
217 )
444f3223 218 )
aecb222b 219
48c0abfe
JPC
220 region = forms.CharField(
221 widget=forms.Select(choices=[('', '')] +
222 [(i.id, i) for i in ref.Region.objects.all()]
223 )
224 )
225
226 implantation = forms.CharField(
227 widget=forms.Select(choices=[('', '')] +
228 [(i.id, i) for i in ref.Implantation.objects.all()]
229 )
230 )
231
aecb222b
JPC
232 #date_debut = forms.DateField(widget=adminwidgets.AdminDateWidget)
233 #date_fin = forms.DateField(widget=adminwidgets.AdminDateWidget)
e90b19fd 234
e90b19fd 235 form = RechercheTemporelle(request.GET)
00ca4d9f
EMS
236 get_filtre = [
237 (k, v) for k, v in request.GET.items()
238 if k not in ('date_debut', 'date_fin', 'implantation')
239 ]
e90b19fd
OL
240 query_string = urllib.urlencode(get_filtre)
241
aecb222b
JPC
242 date_debut = None
243 date_fin = None
444f3223
JPC
244 if request.GET.get('annee', None):
245 date_debut = "01-01-%s" % request.GET.get('annee', None)
246 date_fin = "31-12-%s" % request.GET.get('annee', None)
df37184c 247
48c0abfe
JPC
248 implantation = request.GET.get('implantation')
249 region = request.GET.get('region')
df37184c
JPC
250
251 custom_filter = {}
252 if implantation:
253 custom_filter['dossier__poste__implantation'] = implantation
254 if region:
255 custom_filter['dossier__poste__implantation__region'] = region
256
df37184c 257 c = {
e90b19fd
OL
258 'title': 'Rapport de masse salariale',
259 'form': form,
df37184c 260 'headers': [],
e90b19fd 261 'query_string': query_string,
df37184c 262 }
22b53270 263 if date_debut or date_fin:
c99116c3
JPC
264 masse = MasseSalariale(date_debut, date_fin, custom_filter,
265 request.GET.get('ne_pas_grouper', False))
515b83c3 266 if masse.rapport:
eabb27fd 267 if request.GET.get('ods'):
00ca4d9f
EMS
268 for h in (
269 h for h in masse.headers if 'background-color' in h[2]
270 ):
eabb27fd
JPC
271 del h[2]['background-color']
272 masse.ods()
273 output = StringIO.StringIO()
274 masse.doc.save(output)
275 output.seek(0)
276
00ca4d9f
EMS
277 response = HttpResponse(
278 FileWrapper(output),
279 content_type=(
280 'application/vnd.oasis.opendocument.spreadsheet'
281 )
282 )
eabb27fd
JPC
283 response['Content-Disposition'] = \
284 'attachment; filename=Masse Salariale %s.ods' % \
285 masse.annee
286 return response
287 else:
288 c['rapport'] = masse.rapport
289 c['header_keys'] = [h[0] for h in masse.headers]
290 #on enleve le background pour le header
00ca4d9f
EMS
291 for h in (
292 h for h in masse.headers if 'background-color' in h[2]
293 ):
eabb27fd
JPC
294 h[2]['background'] = 'none'
295 h = SortHeaders(request, masse.headers, order_field_type="ot",
296 not_sortable=c['header_keys'], order_field="o")
297 c['headers'] = list(h.headers())
298 for key, nom, opts in masse.headers:
299 c['headers']
300 c['total'] = masse.grand_totaux[0]
301 c['total_euro'] = masse.grand_totaux[1]
302 c['colspan'] = len(c['header_keys']) - 1
303 get_filtre.append(('ods', True))
304 query_string = urllib.urlencode(get_filtre)
305 c['url_ods'] = "%s?%s" % (
306 reverse('rhr_masse_salariale'), query_string)
22b53270 307
890b80e7 308 return render(request, 'rh/rapports/masse_salariale.html', c)
98d6eb6c
JPC
309
310
311@login_required
312@drh_or_admin_required
857b5c24
JPC
313def rapports_postes_modelisation(request):
314 c = {}
315 data = []
3c1ba807 316
7bf28694
EMS
317 for categorie in rh.CategorieEmploi.objects.all():
318 types = rh.TypePoste.objects.filter(categorie_emploi=categorie)
3c1ba807
JPC
319 data_types = []
320 for t in types.all():
321 postes = rh.Poste.objects.filter(type_poste=t)
322 data_types.append({
323 'num_postes': postes.count(),
324 'postes': postes.all(),
7bf28694 325 'type': categorie,
857b5c24 326 })
3c1ba807 327
857b5c24 328 data.append({
7bf28694 329 'categorie': categorie,
3c1ba807 330 'nb_types': types.count(),
00ca4d9f
EMS
331 'types': data_types
332 })
857b5c24
JPC
333
334 c['data'] = data
335
890b80e7 336 return render(request, 'rh/rapports/postes_modelisation.html', c)
857b5c24
JPC
337
338
339@login_required
340@drh_or_admin_required
783e077a
JPC
341def rapports_postes_implantation(request):
342 c = {}
343 data = []
344 for r in ref.Region.objects.all():
345 implantations = []
346 for i in ref.Implantation.objects.filter(region=r):
347 implantations.append({
348 'implantation': i,
349 'postes': rh.Poste.objects.filter(implantation=i),
350 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
351 })
352 data.append({
353 'region': r,
354 'implantations': implantations
355 })
356
357 c['data'] = data
358
890b80e7 359 return render(request, 'rh/rapports/postes_implantation.html', c)
783e077a
JPC
360
361
362@login_required
363@drh_or_admin_required
364def rapports_postes_service(request):
365 c = {}
9988aafb
JPC
366 data = []
367 for s in rh.Service.objects.all():
368 postes = rh.Poste.objects.filter(service=s).all()
369 num_postes = rh.Poste.objects.filter(service=s).count()
22343fe7 370 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
783e077a 371
9988aafb 372 c['data'] = data
890b80e7 373 return render(request, 'rh/rapports/postes_service.html', c)
32373f2e
OL
374
375@region_protected(rh.Dossier)
3ebc0952 376def dossier_apercu(request, dossier_id):
baf9b78c 377 d = get_object_or_404(rh.Dossier, pk=dossier_id)
3ebc0952 378 c = {
838bc59d 379 'title': u"Dossier %s" % (d, ),
00ca4d9f
EMS
380 'is_popup': request.GET.get('_popup', False),
381 'dossier': d,
382 'pieces': rh.DossierPiece.objects.filter(dossier__exact=d),
383 'contrats': rh.Contrat.objects.filter(dossier__exact=d),
384 'commentaires': rh.DossierCommentaire.objects.filter(dossier=d).all(),
abf91905 385 'media_url': settings.PRIVE_MEDIA_URL,
3ebc0952 386 }
890b80e7 387 return render(request, 'admin/rh/dossier/apercu.html', c)
00ca4d9f 388
4a1f2ece 389
fbe60a9d
OL
390@region_protected(rh.Poste)
391def poste_apercu(request, poste_id):
c8cb18e3 392 p = get_object_or_404(rh.Poste, pk=poste_id)
fbe60a9d 393 c = {
c8cb18e3 394 'title': u"Poste %s" % (p, ),
00ca4d9f
EMS
395 'is_popup': request.GET.get('_popup', False),
396 'poste': p,
397 'financements': (
398 rh.PosteFinancement.objects.filter(poste=poste_id).all()
399 ),
400 'pieces': rh.PostePiece.objects.filter(poste=poste_id).all(),
401 'dossiers': (
402 rh.Dossier.objects.filter(poste=poste_id)
403 .order_by("-date_debut").all()
404 ),
405 'comparaisons': (
406 rh.PosteComparaison.objects.filter(poste=poste_id).all()
407 ),
408 'commentaires': (
409 rh.PosteCommentaire.objects.filter(poste=poste_id).all()
410 ),
abf91905 411 'media_url': settings.PRIVE_MEDIA_URL,
fbe60a9d 412 }
890b80e7 413 return render(request, 'admin/rh/poste/apercu.html', c)
00ca4d9f 414
fbe60a9d 415
4a1f2ece
OL
416def employe_apercu(request, employe_id):
417 employe = get_object_or_404(rh.Employe, pk=employe_id)
fbe60a9d 418 user_groups = request.user.groups.all()
fbe60a9d
OL
419 dossiers = None
420
421 if request.user.is_superuser or \
422 grp_drh in user_groups:
423 q = Q(employe=employe)
424 if grp_correspondants_rh in user_groups:
00ca4d9f
EMS
425 regions = [
426 d.poste.implantation.region for d in employe.rh_dossiers.all()
427 ]
fbe60a9d 428 q = Q(employe=employe) & Q(implantation__region__in=regions)
22343fe7
OL
429
430 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
431
4a1f2ece 432 c = {
ce740bb5 433 'title': u"Employe %s" % (employe, ),
00ca4d9f
EMS
434 'is_popup': request.GET.get('_popup', False),
435 'employe': employe,
436 'dossiers': dossiers,
abf91905 437 'media_url': settings.PRIVE_MEDIA_URL,
4a1f2ece 438 }
890b80e7 439 return render(request, 'admin/rh/employe/apercu.html', c)
00ca4d9f 440
150d83ec 441
77bd83d1
JPC
442@login_required
443@drh_or_admin_required
56264a85 444def organigrammes_employe(request, id, level="all"):
08faf06e
JPC
445
446 poste = get_object_or_404(rh.Poste, pk=id)
00ca4d9f
EMS
447 dossiers_by_poste = dict(
448 (d.poste_id, d)
449 for d in rh.Dossier.objects.select_related('employe', 'poste').all()
450 )
5c0f1778
JPC
451 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
452
453 e = dossiers_by_poste[poste.id].employe
454 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
58014aec 455 graph = pgv.AGraph()
5c0f1778 456
f187a10f 457 if rh.Poste.objects.filter(responsable=poste).count() > 0:
58014aec
JPC
458 postes_handle = [poste]
459 while postes_handle:
00ca4d9f
EMS
460 postes_handle = rh.Poste.objects.select_related('implantation') \
461 .filter(
462 Q(date_fin__gt=date.today()) | Q(date_fin=None),
463 Q(date_debut__lt=date.today()) | Q(date_debut=None),
464 responsable__in=postes_handle
465 ).exclude(supprime=True).exclude(responsable=None).all()
32373f2e 466
58014aec
JPC
467 for p in postes_handle:
468 if p.responsable_id != p.id:
00ca4d9f
EMS
469 graph.add_edge(
470 dossiers_by_poste[p.responsable_id].poste_id, p.id
471 )
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)):
00ca4d9f
EMS
479 postes_niveau = [
480 p.id for p in
481 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
482 ]
4afec2e1
JPC
483
484 while postes_niveau:
00ca4d9f
EMS
485 postes_niveau = [
486 p.id for p in
487 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
488 ]
4afec2e1
JPC
489 if postes_niveau:
490 for p in postes_niveau:
491 if graph.has_node(p):
4cc81304 492 graph.delete_node(p)
4afec2e1 493
58014aec 494 a = graph
4afec2e1 495 a.name = name.encode('ascii', 'xmlcharrefreplace')
5c0f1778
JPC
496
497 poste_remontant = poste
498 while poste_remontant.responsable_id:
499 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
500 poste_remontant = poste_remontant.responsable
501
502 rh_graph.bind_poste_to_graph(a, postes_by_id)
503 #a.graph_attr['normalize'] = True
504 #a.graph_attr['level'] = 2
505 a.layout(prog='dot')
506
507 svg = a.draw(format='svg')
508
509 c = {
510 'svg': svg
511 }
a251ac8d
JPC
512
513 if 'forcer' in request.GET:
890b80e7 514 response = HttpResponse(svg, content_type='image/svg+xml')
00ca4d9f
EMS
515 response['Content-Disposition'] = \
516 'attachment; filename=organigramme.svg'
a251ac8d
JPC
517 return response
518
890b80e7
DB
519 return render(request, 'rh/organigrammes/employe.html', c,
520 content_type="image/svg+xml"
00ca4d9f 521 )
5c0f1778
JPC
522
523
524@login_required
525@drh_or_admin_required
526def organigrammes_service(request, id):
527
528 service = get_object_or_404(rh.Service, pk=id)
82af5c19
JPC
529 svg = rh_graph.organigramme_postes_cluster( \
530 cluster_filter={"service": service}, \
531 titre=u"Organigramme du service %s" % service.nom,
532 cluster_titre=service.nom)
5c0f1778 533
82af5c19
JPC
534 c = {
535 'svg': svg
536 }
5c0f1778 537
890b80e7
DB
538 return render(request, 'rh/organigrammes/vide.html', c,
539 content_type="image/svg+xml"
00ca4d9f
EMS
540 )
541
5c0f1778 542
82af5c19
JPC
543@login_required
544@drh_or_admin_required
545def organigrammes_implantation(request, id):
5c0f1778 546
82af5c19
JPC
547 implantation = get_object_or_404(ref.Implantation, pk=id)
548 svg = rh_graph.organigramme_postes_cluster( \
549 cluster_filter={"implantation": implantation}, \
550 titre=u"Organigramme de l'implantation %s" % implantation.nom,
551 cluster_titre=implantation.nom)
5c0f1778
JPC
552
553 c = {
554 'svg': svg
555 }
556
890b80e7
DB
557 return render(request, 'rh/organigrammes/vide.html', c,
558 content_type="image/svg+xml"
00ca4d9f
EMS
559 )
560
5c0f1778 561
9da4c195
JPC
562@login_required
563@drh_or_admin_required
564def organigrammes_region(request, id):
565
566 region = get_object_or_404(ref.Region, pk=id)
567 svg = rh_graph.organigramme_postes_cluster( \
568 cluster_filter={"implantation__region": region}, \
569 titre=u"Organigramme du bureau de %s" % region.nom,
570 cluster_titre=region.nom)
571
572 c = {
573 'svg': svg
574 }
575
890b80e7
DB
576 return render(request,
577 'rh/organigrammes/vide.html', c,
578 content_type="image/svg+xml"
00ca4d9f 579 )