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