[#2658] Intégration de reversion à l'app rh
[auf_rh_dae.git] / project / rh / views.py
1 # -*- encoding: utf-8 -*-
2
3 import urllib
4 from datetime import date
5 import StringIO
6
7 import pygraphviz as pgv
8 from auf.django.references import models as ref
9 from django import forms
10 from django.conf import settings
11 from django.contrib.auth.decorators import login_required
12 from django.core.servers.basehttp import FileWrapper
13 from django.core.urlresolvers import reverse
14 from django.db.models import Q
15 from django.http import HttpResponse
16 from django.shortcuts import render, get_object_or_404
17
18 from project.decorators import drh_or_admin_required
19 from project.decorators import region_protected
20 from project.groups import get_employe_from_user
21 from project.groups import grp_drh, grp_correspondants_rh
22 from project.rh import models as rh
23 from project.rh import graph as rh_graph
24 from project.rh.change_list import RechercheTemporelle
25 from project.rh.lib import get_lookup_params
26 from project.rh.masse_salariale import MasseSalariale
27 from project.rh.templatetags.rapports import SortHeaders
28
29
30 @login_required
31 def profil(request):
32 """Profil personnel de l'employé - éditable"""
33 employe = get_employe_from_user(request.user)
34 c = {
35 'user': request.user,
36 'employe': employe,
37 }
38 return render(request, 'rh/profil.html', c)
39
40
41 @login_required
42 def employes_liste(request):
43 """Liste des employés."""
44 today = date.today()
45 employes = rh.Employe.objects \
46 .exclude(dossiers__date_debut__gt=today) \
47 .exclude(dossiers__date_fin__lt=today) \
48 .order_by('nom')
49 c = {
50 'user': request.user,
51 'employes': employes,
52 }
53 return render(request, 'rh/employes_liste.html', c)
54
55
56 @login_required
57 def 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 = {
64 'user': request.user,
65 'employe': employe,
66 }
67 return render(request, 'rh/employe.html', c)
68
69
70 @login_required
71 @drh_or_admin_required
72 def rapports_contrat(request):
73 # statut default = actif?
74 if 'HTTP_REFERER' in request.META.keys():
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
82
83 contrats = rh.Contrat.objects.select_related(
84 'dossier', 'dossier__poste', 'dossier__poste__implantation',
85 'type_contrat', 'dossier__employe'
86 )
87
88 # filters et recherche temporelle
89 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
90 lookup_params = get_lookup_params(request)
91 lookup_params = cl.purge_params(lookup_params)
92 q_temporel = cl.get_q_temporel(contrats)
93 q = Q(**lookup_params) & q_temporel
94 contrats = contrats.filter(q)
95
96 # tri
97 if 'o' in request.GET:
98 contrats = contrats.order_by(
99 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
100 )
101
102 # affichage
103 employes = set([c.dossier.employe_id for c in contrats])
104
105 headers = [
106 ("dossier__employe__id", u"#"),
107 ("dossier__employe__nom", u"Employé"),
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"),
113 ("dossier__poste__implantation__region", u"Région"),
114 ("dossier__poste__implantation", u"Implantation"),
115 ]
116 h = SortHeaders(
117 request, headers, order_field_type="ot", order_field="o",
118 not_sortable=('dossier',)
119 )
120
121 c = {
122 'cl': cl,
123 'title': 'Rapport des contrats',
124 'contrats': contrats,
125 'count_employe': len(employes),
126 'headers': list(h.headers()),
127 }
128 return render(request, 'rh/rapports/contrats.html', c)
129
130
131 @login_required
132 @drh_or_admin_required
133 def rapports_masse_salariale(request):
134
135 class RechercheTemporelle(forms.Form):
136 CHOICE_ANNEES = range(
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 )
147 )
148
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
161 #date_debut = forms.DateField(widget=adminwidgets.AdminDateWidget)
162 #date_fin = forms.DateField(widget=adminwidgets.AdminDateWidget)
163
164 form = RechercheTemporelle(request.GET)
165 get_filtre = [
166 (k, v) for k, v in request.GET.items()
167 if k not in ('date_debut', 'date_fin', 'implantation')
168 ]
169 query_string = urllib.urlencode(get_filtre)
170
171 date_debut = None
172 date_fin = None
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)
176
177 implantation = request.GET.get('implantation')
178 region = request.GET.get('region')
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
186 c = {
187 'title': 'Rapport de masse salariale',
188 'form': form,
189 'headers': [],
190 'query_string': query_string,
191 }
192 if date_debut or date_fin:
193 masse = MasseSalariale(date_debut, date_fin, custom_filter,
194 request.GET.get('ne_pas_grouper', False))
195 if masse.rapport:
196 if request.GET.get('ods'):
197 for h in (
198 h for h in masse.headers if 'background-color' in h[2]
199 ):
200 del h[2]['background-color']
201 masse.ods()
202 output = StringIO.StringIO()
203 masse.doc.save(output)
204 output.seek(0)
205
206 response = HttpResponse(
207 FileWrapper(output),
208 content_type=(
209 'application/vnd.oasis.opendocument.spreadsheet'
210 )
211 )
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
220 for h in (
221 h for h in masse.headers if 'background-color' in h[2]
222 ):
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)
236
237 return render(request, 'rh/rapports/masse_salariale.html', c)
238
239
240 @login_required
241 @drh_or_admin_required
242 def rapports_employes_sans_contrat(request):
243 lookup_params = get_lookup_params(request)
244
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 )
260
261 # employés sans contrat
262 employes = rh.Employe.objects.filter(
263 rh_dossiers__in=dossiers_sans_contrat
264 ).distinct()
265 if 'o' in request.GET:
266 employes = employes.order_by(
267 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
268 )
269
270 # affichage
271 headers = [
272 ("id", u"#"),
273 ("nom", u"Employé"),
274 ("dossier", u"Dossier : Poste"),
275 ("dossier_date_debut", u"Début dossier"),
276 ("dossier_date_fin", u"Fin dossier"),
277 ]
278 h = SortHeaders(
279 request, headers, order_field_type="ot", order_field="o",
280 not_sortable=('dossier', 'dossier_date_debut', 'dossier_date_fin',)
281 )
282
283 c = {
284 'title': u'Rapport des employés sans contrat',
285 'employes': employes,
286 'dossiers_sans_contrat': dossiers_sans_contrat,
287 'headers': list(h.headers()),
288 }
289
290 return render(request, 'rh/rapports/employes_sans_contrat.html', c)
291
292
293 @login_required
294 @drh_or_admin_required
295 def rapports_postes_modelisation(request):
296 c = {}
297 data = []
298
299 for categorie in rh.CategorieEmploi.objects.all():
300 types = rh.TypePoste.objects.filter(categorie_emploi=categorie)
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(),
307 'type': categorie,
308 })
309
310 data.append({
311 'categorie': categorie,
312 'nb_types': types.count(),
313 'types': data_types
314 })
315
316 c['data'] = data
317
318 return render(request, 'rh/rapports/postes_modelisation.html', c)
319
320
321 @login_required
322 @drh_or_admin_required
323 def 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
341 return render(request, 'rh/rapports/postes_implantation.html', c)
342
343
344 @login_required
345 @drh_or_admin_required
346 def rapports_postes_service(request):
347 c = {}
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()
352 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
353
354 c['data'] = data
355 return render(request, 'rh/rapports/postes_service.html', c)
356
357
358 @region_protected(rh.Dossier)
359 def dossier_apercu(request, dossier_id):
360 d = get_object_or_404(rh.Dossier, pk=dossier_id)
361 c = {
362 'title': u"Dossier %s" % (d, ),
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(),
368 'media_url': settings.PRIVE_MEDIA_URL,
369 }
370 return render(request, 'admin/rh/dossier/apercu.html', c)
371
372
373 @region_protected(rh.Poste)
374 def poste_apercu(request, poste_id):
375 p = get_object_or_404(rh.Poste, pk=poste_id)
376 c = {
377 'title': u"Poste %s" % (p, ),
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 ),
394 'media_url': settings.PRIVE_MEDIA_URL,
395 }
396 return render(request, 'admin/rh/poste/apercu.html', c)
397
398
399 def employe_apercu(request, employe_id):
400 employe = get_object_or_404(rh.Employe, pk=employe_id)
401 user_groups = request.user.groups.all()
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:
408 regions = [
409 d.poste.implantation.region for d in employe.rh_dossiers.all()
410 ]
411 q = Q(employe=employe) & Q(implantation__region__in=regions)
412
413 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
414
415 c = {
416 'title': u"Employe %s" % (employe, ),
417 'is_popup': request.GET.get('_popup', False),
418 'employe': employe,
419 'dossiers': dossiers,
420 'media_url': settings.PRIVE_MEDIA_URL,
421 }
422 return render(request, 'admin/rh/employe/apercu.html', c)
423
424
425 @login_required
426 @drh_or_admin_required
427 def organigrammes_employe(request, id, level="all"):
428 poste = get_object_or_404(rh.Poste, pk=id)
429 dossiers_by_poste = dict(
430 (d.poste_id, d)
431 for d in rh.Dossier.objects.select_related('employe', 'poste').all()
432 )
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)
437 graph = pgv.AGraph()
438
439 if rh.Poste.objects.filter(responsable=poste).count() > 0:
440 postes_handle = [poste]
441 while postes_handle:
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()
448
449 for p in postes_handle:
450 if p.responsable_id != p.id:
451 graph.add_edge(
452 dossiers_by_poste[p.responsable_id].poste_id, p.id
453 )
454
455 else:
456 graph.add_node(poste.id)
457
458 if level != "all":
459 postes_niveau = [poste.id]
460 for niveau in range(int(level)):
461 postes_niveau = [
462 p.id for p in
463 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
464 ]
465
466 while postes_niveau:
467 postes_niveau = [
468 p.id for p in
469 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
470 ]
471 if postes_niveau:
472 for p in postes_niveau:
473 if graph.has_node(p):
474 graph.delete_node(p)
475
476 a = graph
477 a.name = name.encode('ascii', 'xmlcharrefreplace')
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 }
494
495 if 'forcer' in request.GET:
496 response = HttpResponse(svg, content_type='image/svg+xml')
497 response['Content-Disposition'] = \
498 'attachment; filename=organigramme.svg'
499 return response
500
501 return render(request, 'rh/organigrammes/employe.html', c,
502 content_type="image/svg+xml"
503 )
504
505
506 @login_required
507 @drh_or_admin_required
508 def organigrammes_service(request, id):
509 service = get_object_or_404(rh.Service, pk=id)
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)
514
515 return render(request, 'rh/organigrammes/vide.html', {
516 'svg': svg
517 }, content_type="image/svg+xml")
518
519
520 @login_required
521 @drh_or_admin_required
522 def organigrammes_implantation(request, id):
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)
528 return render(request, 'rh/organigrammes/vide.html', {
529 'svg': svg
530 }, content_type="image/svg+xml")
531
532
533 @login_required
534 @drh_or_admin_required
535 def organigrammes_region(request, id):
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
542 return render(request, 'rh/organigrammes/vide.html', {
543 'svg': svg
544 }, content_type="image/svg+xml")