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