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