region_protected niveau project
[auf_rh_dae.git] / project / rh / views.py
1 # -*- encoding: utf-8 -*-
2
3 import urllib
4 from datetime import date
5 from itertools import izip
6 import StringIO
7
8 import pygraphviz as pgv
9
10 from django import forms
11 from django.conf import settings
12 from django.contrib.auth.decorators import login_required
13 from django.core.servers.basehttp import FileWrapper
14 from django.core.urlresolvers import reverse
15 from django.db.models import Q
16 from django.http import HttpResponse
17 from django.shortcuts import render, get_object_or_404
18 from django.utils.encoding import smart_str
19
20 from auf.django.references import models as ref
21
22 from project.decorators import redirect_interdiction
23 from project.decorators import drh_or_admin_required
24 from project.decorators import region_protected
25 from project.utils import get_employe_from_user
26
27 from project.rh import models as rh
28 from project.rh import graph as rh_graph
29 from project.rh.change_list import RechercheTemporelle
30 from project.rh.lib import calc_remun
31 from project.rh.masse_salariale import MasseSalariale
32 from project.rh.templatetags.rapports import SortHeaders
33
34 # pas de reference a DAE devrait etre refactorisé
35 from project.dae.workflow import grp_drh, grp_correspondants_rh
36
37
38 @login_required
39 def profil(request):
40 """Profil personnel de l'employé - éditable"""
41 employe = get_employe_from_user(user)
42 c = {
43 'user' = request.user,
44 'employe' = employe,
45 }
46 return render(request, 'rh/profil.html', c)
47
48
49 @login_required
50 def employes_liste(request):
51 """Liste des employés."""
52 today = date.today()
53 employes = rh.Employe.objects \
54 .exclude(dossiers__date_debut__gt=today) \
55 .exclude(dossiers__date_fin__lt=today) \
56 .order_by('nom')
57 c = {
58 'user': request.user,
59 'employes': employes,
60 }
61 return render(request, 'rh/employes_liste.html', c)
62
63
64 @login_required
65 def employe(request, id):
66 """Information publique sur un employé."""
67 try:
68 employe = rh.Employe.objects.get(pk=id)
69 except:
70 employe = rh.Employe.objects.none()
71 c = {
72 'user': request.user,
73 'employe': employe,
74 }
75 return render(request, 'rh/employe.html', c)
76
77
78 @login_required
79 @drh_or_admin_required
80 def rapports_poste(request):
81
82 lookup_params = dict(request.GET.items())
83
84 for key, value in lookup_params.items():
85 if key == 'o' or key == 'ot':
86 del lookup_params[key]
87 continue
88 if not isinstance(key, str):
89 # 'key' will be used as a keyword argument later, so Python
90 # requires it to be a string.
91 del lookup_params[key]
92 lookup_params[smart_str(key)] = value
93
94 if key == 'comble':
95 del lookup_params[key]
96
97 sort_order = 'ASC' if request.GET.get('ot') == 'asc' else 'DESC'
98
99 postes = rh.Poste.objects.select_related('implantation') \
100 .extra(select={
101 'employe_id':
102 'SELECT GROUP_CONCAT(employe SEPARATOR "|") '
103 'FROM rh_dossier '
104 'WHERE poste = rh_poste.id '
105 'AND rh_dossier.date_fin IS NULL ' + (
106 'ORDER BY employe ' + sort_order
107 if request.GET.get('o') == 'employe_id' else ''
108 )
109 }) \
110 .extra(select={
111 'employe_nom':
112 'SELECT GROUP_CONCAT(rh_employe.nom SEPARATOR "|") '
113 'FROM rh_dossier INNER JOIN rh_employe '
114 'ON rh_dossier.employe = rh_employe.id '
115 'WHERE poste = rh_poste.id '
116 'AND rh_dossier.date_fin IS NULL ' + (
117 'ORDER BY rh_employe.nom ' + sort_order
118 if request.GET.get('o') == 'employe_nom' else ''
119 )
120 }) \
121 .extra(select={
122 'employe_prenom':
123 'SELECT GROUP_CONCAT(rh_employe.prenom SEPARATOR "|") '
124 'FROM rh_dossier INNER JOIN rh_employe '
125 'ON rh_dossier.employe = rh_employe.id '
126 'WHERE poste = rh_poste.id '
127 'AND rh_dossier.date_fin IS NULL ' + (
128 'ORDER BY rh_employe.prenom ' + sort_order
129 if request.GET.get('o') == 'employe_prenom' else ''
130 )
131 })
132
133 postes = postes.filter(**lookup_params)
134 if 'o' in request.GET:
135 postes = postes.order_by(
136 ('-' if sort_order == "DESC" else '') + request.GET['o']
137 )
138
139 out = []
140 for p in postes:
141 out.append({
142 'id': p.id,
143 'nom': p.nom,
144 'implantation': p.implantation,
145 'employes': [] if not p.employe_id else [
146 {'id': id, 'nom': nom, 'prenom': prenom}
147 for id, nom, prenom in izip(
148 p.employe_id.split('|'),
149 p.employe_nom.split('|'),
150 p.employe_prenom.split('|')
151 )
152 ]
153 })
154
155 headers = [
156 ("id", u"# du poste"),
157 ("nom", u"Nom du poste"),
158 ("implantation__id", u"Implantation"),
159 ("employe_nom", u"Nom"),
160 ]
161 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
162 c = {
163 'title': 'Rapport des postes',
164 'postes': out,
165 'count': len(out),
166 'headers': list(h.headers()),
167 }
168
169 return render(request, 'rh/rapports/postes.html', c)
170
171
172 @login_required
173 @drh_or_admin_required
174 def rapports_contrat(request):
175 if 'HTTP_REFERER' in request.META.keys():
176 referer = request.META['HTTP_REFERER']
177 referer = "/".join(referer.split('/')[3:])
178 referer = "/%s" % referer.split('?')[0]
179 if referer != reverse('rhr_contrats'):
180 params = request.GET.copy()
181 params.update({'statut': 'Actif'})
182 request.GET = params
183
184 lookup_params = dict(request.GET.items())
185 if 'ot' in lookup_params:
186 del lookup_params['ot']
187 if 'o' in lookup_params:
188 del lookup_params['o']
189
190 for key, value in lookup_params.items():
191 if not isinstance(key, str):
192 # 'key' will be used as a keyword argument later, so Python
193 # requires it to be a string.
194 del lookup_params[key]
195 lookup_params[smart_str(key)] = value
196
197 contrats = rh.Contrat.objects.select_related(
198 'dossier', 'dossier__poste', 'dossier__poste__implantation',
199 'type_contrat', 'dossier__employe'
200 )
201
202 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
203 lookup_params = cl.purge_params(lookup_params)
204 q_temporel = cl.get_q_temporel(contrats)
205 q = Q(**lookup_params) & q_temporel
206 contrats = contrats.filter(q).exclude(dossier__employe__supprime=1)
207
208 if 'o' in request.GET:
209 contrats = contrats.order_by(
210 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
211 )
212
213 employes = set([c.dossier.employe_id for c in contrats])
214
215 headers = [
216 ("dossier__employe__id", u"# de l'employé"),
217 ("dossier__employe__nom", u"Employé"),
218 ("type_contrat__nom", u"Poste"),
219 ("dossier__poste__implantation__region", u"Région"),
220 ("dossier__poste__implantation", u"Implantation"),
221 ("type_contrat__nom", u"Type de contrat"),
222 ("date_debut", u"Date début"),
223 ("date_fin", u"Date fin"),
224 ]
225 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
226
227 c = {
228 'cl': cl,
229 'title': 'Rapport des contrats',
230 'contrats': contrats,
231 'count': len(contrats),
232 'count_employe': len(employes),
233 'headers': list(h.headers()),
234 }
235
236 return render(request, 'rh/rapports/contrats.html', c)
237
238
239 @login_required
240 @drh_or_admin_required
241 def rapports_masse_salariale(request):
242
243 class RechercheTemporelle(forms.Form):
244 CHOICE_ANNEES = range(
245 rh.Remuneration.objects.exclude(date_debut=None)
246 .order_by('date_debut')[0].date_debut.year,
247 date.today().year + 1
248 )
249
250 annee = forms.CharField(
251 initial=date.today().year,
252 widget=forms.Select(
253 choices=((a, a) for a in reversed(CHOICE_ANNEES))
254 )
255 )
256
257 region = forms.CharField(
258 widget=forms.Select(choices=[('', '')] +
259 [(i.id, i) for i in ref.Region.objects.all()]
260 )
261 )
262
263 implantation = forms.CharField(
264 widget=forms.Select(choices=[('', '')] +
265 [(i.id, i) for i in ref.Implantation.objects.all()]
266 )
267 )
268
269 #date_debut = forms.DateField(widget=adminwidgets.AdminDateWidget)
270 #date_fin = forms.DateField(widget=adminwidgets.AdminDateWidget)
271
272 form = RechercheTemporelle(request.GET)
273 get_filtre = [
274 (k, v) for k, v in request.GET.items()
275 if k not in ('date_debut', 'date_fin', 'implantation')
276 ]
277 query_string = urllib.urlencode(get_filtre)
278
279 date_debut = None
280 date_fin = None
281 if request.GET.get('annee', None):
282 date_debut = "01-01-%s" % request.GET.get('annee', None)
283 date_fin = "31-12-%s" % request.GET.get('annee', None)
284
285 implantation = request.GET.get('implantation')
286 region = request.GET.get('region')
287
288 custom_filter = {}
289 if implantation:
290 custom_filter['dossier__poste__implantation'] = implantation
291 if region:
292 custom_filter['dossier__poste__implantation__region'] = region
293
294 c = {
295 'title': 'Rapport de masse salariale',
296 'form': form,
297 'headers': [],
298 'query_string': query_string,
299 }
300 if date_debut or date_fin:
301 masse = MasseSalariale(date_debut, date_fin, custom_filter,
302 request.GET.get('ne_pas_grouper', False))
303 if masse.rapport:
304 if request.GET.get('ods'):
305 for h in (
306 h for h in masse.headers if 'background-color' in h[2]
307 ):
308 del h[2]['background-color']
309 masse.ods()
310 output = StringIO.StringIO()
311 masse.doc.save(output)
312 output.seek(0)
313
314 response = HttpResponse(
315 FileWrapper(output),
316 content_type=(
317 'application/vnd.oasis.opendocument.spreadsheet'
318 )
319 )
320 response['Content-Disposition'] = \
321 'attachment; filename=Masse Salariale %s.ods' % \
322 masse.annee
323 return response
324 else:
325 c['rapport'] = masse.rapport
326 c['header_keys'] = [h[0] for h in masse.headers]
327 #on enleve le background pour le header
328 for h in (
329 h for h in masse.headers if 'background-color' in h[2]
330 ):
331 h[2]['background'] = 'none'
332 h = SortHeaders(request, masse.headers, order_field_type="ot",
333 not_sortable=c['header_keys'], order_field="o")
334 c['headers'] = list(h.headers())
335 for key, nom, opts in masse.headers:
336 c['headers']
337 c['total'] = masse.grand_totaux[0]
338 c['total_euro'] = masse.grand_totaux[1]
339 c['colspan'] = len(c['header_keys']) - 1
340 get_filtre.append(('ods', True))
341 query_string = urllib.urlencode(get_filtre)
342 c['url_ods'] = "%s?%s" % (
343 reverse('rhr_masse_salariale'), query_string)
344
345 return render(request, 'rh/rapports/masse_salariale.html', c)
346
347
348 @login_required
349 @drh_or_admin_required
350 def rapports_remuneration(request):
351
352 lookup_params = dict(request.GET.items())
353 if 'ot' in lookup_params:
354 del lookup_params['ot']
355 if 'o' in lookup_params:
356 del lookup_params['o']
357
358 for key, value in lookup_params.items():
359 if not isinstance(key, str):
360 # 'key' will be used as a keyword argument later, so Python
361 # requires it to be a string.
362 del lookup_params[key]
363 lookup_params[smart_str(key)] = value
364
365 employes = rh.Employe.objects.all()
366 if 'o' in request.GET:
367 employes = employes.order_by(
368 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
369 )
370
371 employes = employes.filter(**lookup_params)
372
373 output = []
374 headers = [
375 ("id", u"# de l'employé"),
376 ("nom", u"Nom"),
377 ("prenom", u"Prénom"),
378 ("", u"Salaire"),
379 ("", u"RAS"),
380 ("", u"Indemnités"),
381 ("", u"Accessoire"),
382 ("", u"Charges patronales"),
383 ("", u"Total"),
384 ]
385 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
386
387 for employe in employes:
388 line = {}
389 output.append(line)
390
391 dossiers = employe.rh_dossiers.all()
392
393 remun = {}
394 remun_sum_euro = 0
395
396 for dossier in dossiers:
397 this_remun, this_remun_sum, this_remun_sum_euro = \
398 calc_remun(dossier)
399
400 for item in this_remun:
401 if item not in remun:
402 remun[item] = this_remun[item]
403 else:
404 remun[item][0] += this_remun[item][0]
405 remun[item][1] += this_remun[item][1]
406
407 remun_sum_euro += this_remun_sum_euro
408
409 line['remun_sum_euro'] = remun_sum_euro
410
411 for r in remun:
412 if r == u'Indemnité':
413 line['Indemnite'] = remun[r][1]
414 else:
415 line[r] = remun[r][1]
416
417 line['id'] = employe.id
418 line['nom'] = employe.nom
419 line['prenom'] = employe.prenom
420
421 c = {
422 'title': 'Rapport de remuneration',
423 'employes': output,
424 'headers': list(h.headers()),
425 }
426
427 return render(request, 'rh/rapports/remuneration.html', c)
428
429
430 @login_required
431 @drh_or_admin_required
432 def rapports_employe_sans_contrat(request):
433
434 lookup_params = dict(request.GET.items())
435 if 'ot' in lookup_params:
436 del lookup_params['ot']
437 if 'o' in lookup_params:
438 del lookup_params['o']
439
440 for key, value in lookup_params.items():
441 if not isinstance(key, str):
442 # 'key' will be used as a keyword argument later, so Python
443 # requires it to be a string.
444 del lookup_params[key]
445 lookup_params[smart_str(key)] = value
446
447 employes_query = rh.Employe.objects
448 if 'o' in request.GET:
449 employes_query = employes_query.order_by(
450 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
451 )
452
453 employes = {}
454
455 dossiers_en_cours = rh.Dossier.objects.filter(
456 Q(date_fin=None) | Q(date_fin__gt=date.today())
457 )
458 tous_contrats_echus = rh.Contrat.objects.filter(
459 date_fin__lt=date.today(), dossier__in=dossiers_en_cours
460 )
461 contrats = tous_contrats_echus.filter(**lookup_params).all()
462 for c in contrats:
463 if c.dossier.employe.id not in employes.keys():
464 employes[c.dossier.employe.id] = {
465 'employe': c.dossier.employe,
466 'dossiers': []
467 }
468 employes[c.dossier.employe.id]['dossiers'] += [c.dossier]
469
470 headers = [
471 ("id", u"# de l'employé"),
472 ("nom", u"Nom"),
473 ("prenom", u"Prénom"),
474 ("dossier", u"Dossiers"),
475 ]
476 h = SortHeaders(
477 request, headers, order_field_type="ot", order_field="o",
478 not_sortable=('dossier',)
479 )
480
481 c = {
482 'title': u'Rapport des employés sans contrat',
483 'employes': employes,
484 'count': len(employes),
485 'headers': list(h.headers()),
486 }
487
488 return render(request, 'rh/rapports/employes_sans_contrat.html', c)
489
490
491 @login_required
492 @drh_or_admin_required
493 def rapports_postes_modelisation(request):
494 c = {}
495 data = []
496
497 for categorie in rh.CategorieEmploi.objects.all():
498 types = rh.TypePoste.objects.filter(categorie_emploi=categorie)
499 data_types = []
500 for t in types.all():
501 postes = rh.Poste.objects.filter(type_poste=t)
502 data_types.append({
503 'num_postes': postes.count(),
504 'postes': postes.all(),
505 'type': categorie,
506 })
507
508 data.append({
509 'categorie': categorie,
510 'nb_types': types.count(),
511 'types': data_types
512 })
513
514 c['data'] = data
515
516 return render(request, 'rh/rapports/postes_modelisation.html', c)
517
518
519 @login_required
520 @drh_or_admin_required
521 def rapports_postes_implantation(request):
522 c = {}
523 data = []
524 for r in ref.Region.objects.all():
525 implantations = []
526 for i in ref.Implantation.objects.filter(region=r):
527 implantations.append({
528 'implantation': i,
529 'postes': rh.Poste.objects.filter(implantation=i),
530 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
531 })
532 data.append({
533 'region': r,
534 'implantations': implantations
535 })
536
537 c['data'] = data
538
539 return render(request, 'rh/rapports/postes_implantation.html', c)
540
541
542 @login_required
543 @drh_or_admin_required
544 def rapports_postes_service(request):
545 c = {}
546 data = []
547 for s in rh.Service.objects.all():
548 postes = rh.Poste.objects.filter(service=s).all()
549 num_postes = rh.Poste.objects.filter(service=s).count()
550 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
551
552 c['data'] = data
553 return render(request, 'rh/rapports/postes_service.html', c)
554
555 @region_protected(rh.Dossier)
556 def dossier_apercu(request, dossier_id):
557 d = get_object_or_404(rh.Dossier, pk=dossier_id)
558 c = {
559 'title': u"Dossier %s" % (d, ),
560 'is_popup': request.GET.get('_popup', False),
561 'dossier': d,
562 'pieces': rh.DossierPiece.objects.filter(dossier__exact=d),
563 'contrats': rh.Contrat.objects.filter(dossier__exact=d),
564 'commentaires': rh.DossierCommentaire.objects.filter(dossier=d).all(),
565 'media_url': settings.PRIVE_MEDIA_URL,
566 }
567 return render(request, 'admin/rh/dossier/apercu.html', c)
568
569
570 @region_protected(rh.Poste)
571 def poste_apercu(request, poste_id):
572 p = get_object_or_404(rh.Poste, pk=poste_id)
573 c = {
574 'title': u"Poste %s" % (p, ),
575 'is_popup': request.GET.get('_popup', False),
576 'poste': p,
577 'financements': (
578 rh.PosteFinancement.objects.filter(poste=poste_id).all()
579 ),
580 'pieces': rh.PostePiece.objects.filter(poste=poste_id).all(),
581 'dossiers': (
582 rh.Dossier.objects.filter(poste=poste_id)
583 .order_by("-date_debut").all()
584 ),
585 'comparaisons': (
586 rh.PosteComparaison.objects.filter(poste=poste_id).all()
587 ),
588 'commentaires': (
589 rh.PosteCommentaire.objects.filter(poste=poste_id).all()
590 ),
591 'media_url': settings.PRIVE_MEDIA_URL,
592 }
593 return render(request, 'admin/rh/poste/apercu.html', c)
594
595
596 def employe_apercu(request, employe_id):
597 employe = get_object_or_404(rh.Employe, pk=employe_id)
598 user_groups = request.user.groups.all()
599 dossiers = None
600
601 if request.user.is_superuser or \
602 grp_drh in user_groups:
603 q = Q(employe=employe)
604 if grp_correspondants_rh in user_groups:
605 regions = [
606 d.poste.implantation.region for d in employe.rh_dossiers.all()
607 ]
608 q = Q(employe=employe) & Q(implantation__region__in=regions)
609
610 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
611
612 c = {
613 'title': u"Employe %s" % (employe, ),
614 'is_popup': request.GET.get('_popup', False),
615 'employe': employe,
616 'dossiers': dossiers,
617 'media_url': settings.PRIVE_MEDIA_URL,
618 }
619 return render(request, 'admin/rh/employe/apercu.html', c)
620
621
622 @login_required
623 @drh_or_admin_required
624 def organigrammes_employe(request, id, level="all"):
625
626 poste = get_object_or_404(rh.Poste, pk=id)
627 dossiers_by_poste = dict(
628 (d.poste_id, d)
629 for d in rh.Dossier.objects.select_related('employe', 'poste').all()
630 )
631 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
632
633 e = dossiers_by_poste[poste.id].employe
634 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
635 graph = pgv.AGraph()
636
637 if rh.Poste.objects.filter(responsable=poste).count() > 0:
638 postes_handle = [poste]
639 while postes_handle:
640 postes_handle = rh.Poste.objects.select_related('implantation') \
641 .filter(
642 Q(date_fin__gt=date.today()) | Q(date_fin=None),
643 Q(date_debut__lt=date.today()) | Q(date_debut=None),
644 responsable__in=postes_handle
645 ).exclude(supprime=True).exclude(responsable=None).all()
646
647 for p in postes_handle:
648 if p.responsable_id != p.id:
649 graph.add_edge(
650 dossiers_by_poste[p.responsable_id].poste_id, p.id
651 )
652
653 else:
654 graph.add_node(poste.id)
655
656 if level != "all":
657 postes_niveau = [poste.id]
658 for niveau in range(int(level)):
659 postes_niveau = [
660 p.id for p in
661 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
662 ]
663
664 while postes_niveau:
665 postes_niveau = [
666 p.id for p in
667 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
668 ]
669 if postes_niveau:
670 for p in postes_niveau:
671 if graph.has_node(p):
672 graph.delete_node(p)
673
674 a = graph
675 a.name = name.encode('ascii', 'xmlcharrefreplace')
676
677 poste_remontant = poste
678 while poste_remontant.responsable_id:
679 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
680 poste_remontant = poste_remontant.responsable
681
682 rh_graph.bind_poste_to_graph(a, postes_by_id)
683 #a.graph_attr['normalize'] = True
684 #a.graph_attr['level'] = 2
685 a.layout(prog='dot')
686
687 svg = a.draw(format='svg')
688
689 c = {
690 'svg': svg
691 }
692
693 if 'forcer' in request.GET:
694 response = HttpResponse(svg, content_type='image/svg+xml')
695 response['Content-Disposition'] = \
696 'attachment; filename=organigramme.svg'
697 return response
698
699 return render(request, 'rh/organigrammes/employe.html', c,
700 content_type="image/svg+xml"
701 )
702
703
704 @login_required
705 @drh_or_admin_required
706 def organigrammes_service(request, id):
707
708 service = get_object_or_404(rh.Service, pk=id)
709 svg = rh_graph.organigramme_postes_cluster( \
710 cluster_filter={"service": service}, \
711 titre=u"Organigramme du service %s" % service.nom,
712 cluster_titre=service.nom)
713
714 c = {
715 'svg': svg
716 }
717
718 return render(request, 'rh/organigrammes/vide.html', c,
719 content_type="image/svg+xml"
720 )
721
722
723 @login_required
724 @drh_or_admin_required
725 def organigrammes_implantation(request, id):
726
727 implantation = get_object_or_404(ref.Implantation, pk=id)
728 svg = rh_graph.organigramme_postes_cluster( \
729 cluster_filter={"implantation": implantation}, \
730 titre=u"Organigramme de l'implantation %s" % implantation.nom,
731 cluster_titre=implantation.nom)
732
733 c = {
734 'svg': svg
735 }
736
737 return render(request, 'rh/organigrammes/vide.html', c,
738 content_type="image/svg+xml"
739 )
740
741
742 @login_required
743 @drh_or_admin_required
744 def organigrammes_region(request, id):
745
746 region = get_object_or_404(ref.Region, pk=id)
747 svg = rh_graph.organigramme_postes_cluster( \
748 cluster_filter={"implantation__region": region}, \
749 titre=u"Organigramme du bureau de %s" % region.nom,
750 cluster_titre=region.nom)
751
752 c = {
753 'svg': svg
754 }
755
756 return render(request,
757 'rh/organigrammes/vide.html', c,
758 content_type="image/svg+xml"
759 )