Merge branch 'dev', remote-tracking branch 'origin' into masse_salariale_jp
[auf_rh_dae.git] / project / rh / views.py
1 # -*- encoding: utf-8 -*-
2
3 from datetime import date
4 from itertools import izip
5
6 import pygraphviz as pgv
7
8 from django.core.urlresolvers import reverse
9 from django.db.models import Q
10 from django.contrib.auth.decorators import login_required
11 from django.utils.encoding import smart_str
12 from django.shortcuts import render_to_response, get_object_or_404
13 from django.template import RequestContext
14 from django.http import HttpResponse
15
16 from datamaster_modeles import models as ref
17
18 from rh import models as rh
19 from rh.lib import calc_remun
20 from rh.decorators import drh_or_admin_required
21 from rh.templatetags.rapports import SortHeaders
22 from rh.change_list import RechercheTemporelle
23 from rh import graph as rh_graph
24
25 # pas de reference a DAE devrait etre refactorisé
26 from dae.utils import get_employe_from_user
27 from dae.decorators import redirect_interdiction
28 from dae.workflow import grp_drh, grp_correspondants_rh
29 from django.conf import settings
30
31
32 @login_required
33 def profil(request):
34 """Profil personnel de l'employé - éditable"""
35 rc = RequestContext(request)
36 c = {}
37
38 employe = rc['this_employe']
39
40 c['user'] = request.user
41 c['employe'] = employe
42 return render_to_response('rh/profil.html', c, rc)
43
44
45 @login_required
46 def employes_liste(request):
47 """Liste des employés."""
48 today = date.today()
49 employes = rh.Employe.objects \
50 .exclude(dossiers__date_debut__gt=today) \
51 .exclude(dossiers__date_fin__lt=today) \
52 .order_by('nom')
53 c = {
54 'user': request.user,
55 'employes': employes,
56 }
57 return render_to_response('rh/employes_liste.html',
58 c,
59 RequestContext(request))
60
61
62 @login_required
63 def employe(request, id):
64 """Information publique sur un employé."""
65 try:
66 employe = rh.Employe.objects.get(pk=id)
67 except:
68 employe = rh.Employe.objects.none()
69 c = {
70 'user': request.user,
71 'employe': employe,
72 }
73 return render_to_response('rh/employe.html', c, RequestContext(request))
74
75
76 @login_required
77 @drh_or_admin_required
78 def rapports_poste(request):
79
80 lookup_params = dict(request.GET.items())
81
82 for key, value in lookup_params.items():
83 if key == 'o' or key == 'ot':
84 del lookup_params[key]
85 continue
86 if not isinstance(key, str):
87 # 'key' will be used as a keyword argument later, so Python
88 # requires it to be a string.
89 del lookup_params[key]
90 lookup_params[smart_str(key)] = value
91
92 if key == 'comble':
93 del lookup_params[key]
94
95 postes = rh.Poste.objects.select_related('implantation') \
96 .extra(select={'employe_id':'select group_concat(employe separator "|") from rh_dossier where poste=rh_poste.id and rh_dossier.date_fin is null %s' % \
97 ("%s" % (('order by employe %s' % ('asc' if 'ot' in request.GET and request.GET['ot'] == "asc" else "desc"))) if 'o' in request.GET and request.GET['o'] == "employe_id" else "") \
98 }) \
99 .extra(select={'employe_nom':'select group_concat(rh_employe.nom separator "|") from rh_dossier inner join rh_employe on rh_dossier.employe = rh_employe.id where poste=rh_poste.id and rh_dossier.date_fin is null %s' % \
100 ("%s" % (('order by rh_employe.nom %s' % ('asc' if 'ot' in request.GET and request.GET['ot'] == "asc" else "desc"))) if 'o' in request.GET and request.GET['o'] == "employe_nom" else "") \
101 }) \
102 .extra(select={'employe_prenom':'select group_concat(rh_employe.prenom separator "|") from rh_dossier inner join rh_employe on rh_dossier.employe = rh_employe.id where poste=rh_poste.id and rh_dossier.date_fin is null %s' % \
103 ("%s" % (('order by rh_employe.prenom %s' % ('asc' if 'ot' in request.GET and request.GET['ot'] == "asc" else "desc"))) if 'o' in request.GET and request.GET['o'] == "employe_prenom" else "") \
104 })
105
106 postes = postes.filter(**lookup_params)
107 if 'o' in request.GET:
108 postes = postes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
109
110 out = []
111 for p in postes:
112 out.append({
113 'id': p.id,
114 'nom': p.nom,
115 'implantation': p.implantation,
116 'employes': [] if not p.employe_id else [{'id': id, 'nom': nom, 'prenom': prenom} for id, nom, prenom in izip(p.employe_id.split('|'), p.employe_nom.split('|'), p.employe_prenom.split('|'))] })
117
118
119 headers = [
120 ("id", u"# du poste"),
121 ("nom", u"Nom du poste"),
122 ("implantation__id", u"Implantation"),
123 ("employe_nom", u"Nom"),
124 ]
125 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
126 c = {
127 'title': 'Rapport des postes',
128 'postes': out,
129 'count': len(out),
130 'headers': list(h.headers()),
131 }
132
133 return render_to_response('rh/rapports/postes.html', c, RequestContext(request))
134
135 @login_required
136 @drh_or_admin_required
137 def rapports_contrat(request):
138 if 'HTTP_REFERER' in request.META.keys():
139 referer = request.META['HTTP_REFERER']
140 referer = "/".join(referer.split('/')[3:])
141 referer = "/%s" % referer.split('?')[0]
142 if referer != reverse('rhr_contrats'):
143 params = request.GET.copy()
144 params.update({'statut': 'Actif'})
145 request.GET = params
146
147 lookup_params = dict(request.GET.items())
148 if 'ot' in lookup_params:
149 del lookup_params['ot']
150 if 'o' in lookup_params:
151 del lookup_params['o']
152
153 for key, value in lookup_params.items():
154 if not isinstance(key, str):
155 # 'key' will be used as a keyword argument later, so Python
156 # requires it to be a string.
157 del lookup_params[key]
158 lookup_params[smart_str(key)] = value
159
160 contrats = rh.Contrat.objects.select_related('dossier', 'dossier__poste', 'dossier__poste__implantation', 'type_contrat', 'dossier__employe')
161
162 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
163 lookup_params = cl.purge_params(lookup_params)
164 q_temporel = cl.get_q_temporel(contrats)
165 q = Q(**lookup_params) & q_temporel
166 contrats = contrats.filter(q).exclude(dossier__employe__supprime=1)
167
168 if 'o' in request.GET:
169 contrats = contrats.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
170
171 employes = set([c.dossier.employe_id for c in contrats])
172
173 headers = [
174 ("dossier__employe__id", u"# de l'employé"),
175 ("dossier__employe__nom", u"Nom"),
176 ("dossier__employe__prenom", u"Prénom"),
177 ("type_contrat__nom", u"Poste"),
178 ("type_contrat__nom", u"Type de contrat"),
179 ("date_debut", u"Date début"),
180 ("date_fin", u"Date fin"),
181 ]
182 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
183
184 c = {
185 'cl' : cl,
186 'title': 'Rapport des contrats',
187 'contrats': contrats,
188 'count': len(contrats),
189 'count_employe' : len(employes),
190 'headers': list(h.headers()),
191 }
192
193 return render_to_response('rh/rapports/contrats.html', c, RequestContext(request))
194
195
196 @login_required
197 @drh_or_admin_required
198 def rapports_masse_salariale(request):
199 pass
200
201
202 @login_required
203 @drh_or_admin_required
204 def rapports_remuneration(request):
205
206 lookup_params = dict(request.GET.items())
207 if 'ot' in lookup_params:
208 del lookup_params['ot']
209 if 'o' in lookup_params:
210 del lookup_params['o']
211
212 for key, value in lookup_params.items():
213 if not isinstance(key, str):
214 # 'key' will be used as a keyword argument later, so Python
215 # requires it to be a string.
216 del lookup_params[key]
217 lookup_params[smart_str(key)] = value
218
219 employes = rh.Employe.objects.all()
220 if 'o' in request.GET:
221 employes = employes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
222
223 employes = employes.filter(**lookup_params)
224
225 output = []
226 headers = [
227 ("id", u"# de l'employé"),
228 ("nom", u"Nom"),
229 ("prenom", u"Prénom"),
230 ("", u"Salaire"),
231 ("", u"RAS"),
232 ("", u"Indemnités"),
233 ("", u"Accessoire"),
234 ("", u"Charges patronales"),
235 ("", u"Total"),
236 ]
237 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
238
239 for employe in employes:
240 line = {}
241 output.append(line)
242
243 dossiers = employe.rh_dossiers.all()
244
245 remun = {}
246 remun_sum_euro = 0
247
248 for dossier in dossiers:
249 this_remun, this_remun_sum, this_remun_sum_euro = calc_remun(dossier)
250
251 for item in this_remun:
252 if item not in remun:
253 remun[item] = this_remun[item]
254 else:
255 remun[item][0] += this_remun[item][0]
256 remun[item][1] += this_remun[item][1]
257
258 remun_sum_euro += this_remun_sum_euro
259
260 line['remun_sum_euro'] = remun_sum_euro
261
262 for r in remun:
263 if r == u'Indemnité':
264 line['Indemnite'] = remun[r][1]
265 else:
266 line[r] = remun[r][1]
267
268 line['id'] = employe.id
269 line['nom'] = employe.nom
270 line['prenom'] = employe.prenom
271
272
273 c = {
274 'title': 'Rapport de remuneration',
275 'employes': output,
276 'headers': list(h.headers()),
277 }
278
279 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
280
281 @login_required
282 @drh_or_admin_required
283 def rapports_employe_sans_contrat(request):
284
285 lookup_params = dict(request.GET.items())
286 if 'ot' in lookup_params:
287 del lookup_params['ot']
288 if 'o' in lookup_params:
289 del lookup_params['o']
290
291 for key, value in lookup_params.items():
292 if not isinstance(key, str):
293 # 'key' will be used as a keyword argument later, so Python
294 # requires it to be a string.
295 del lookup_params[key]
296 lookup_params[smart_str(key)] = value
297
298 employes_query = rh.Employe.objects
299 if 'o' in request.GET:
300 employes_query = employes_query.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
301
302 employes = {}
303
304 dossiers_en_cours = rh.Dossier.objects.filter(Q(date_fin=None) | Q(date_fin__gt=date.today()))
305 tous_contrats_echus = rh.Contrat.objects.filter(date_fin__lt=date.today(), dossier__in=dossiers_en_cours)
306 contrats = tous_contrats_echus.filter(**lookup_params).all()
307 for c in contrats:
308 if c.dossier.employe.id not in employes.keys():
309 employes[c.dossier.employe.id] = {'employe': c.dossier.employe, 'dossiers': []}
310 employes[c.dossier.employe.id]['dossiers'] += [c.dossier,]
311
312
313
314 headers = [
315 ("id", u"# de l'employé"),
316 ("nom", u"Nom"),
317 ("prenom", u"Prénom"),
318 ("dossier", u"Dossiers"),
319 ]
320 h = SortHeaders(request, headers, order_field_type="ot", order_field="o", not_sortable=('dossier',))
321
322 c = {
323 'title': u'Rapport des employés sans contrat',
324 'employes': employes,
325 'count': len(employes),
326 'headers': list(h.headers()),
327 }
328
329 return render_to_response('rh/rapports/employes_sans_contrat.html', c, RequestContext(request))
330
331 @login_required
332 @drh_or_admin_required
333 def rapports_postes_modelisation(request):
334 c = {}
335 data = []
336
337 for f in rh.FamilleEmploi.objects.all():
338 types = rh.TypePoste.objects.filter(famille_emploi=f)
339 data_types = []
340 for t in types.all():
341 postes = rh.Poste.objects.filter(type_poste=t)
342 data_types.append({
343 'num_postes': postes.count(),
344 'postes': postes.all(),
345 'type': f,
346 })
347
348 data.append({
349 'famille': f,
350 'nb_types': types.count(),
351 'types' : data_types
352 })
353
354 c['data'] = data
355
356
357 return render_to_response('rh/rapports/postes_modelisation.html', c, RequestContext(request))
358
359
360 @login_required
361 @drh_or_admin_required
362 def rapports_postes_implantation(request):
363 c = {}
364 data = []
365 for r in ref.Region.objects.all():
366 implantations = []
367 for i in ref.Implantation.objects.filter(region=r):
368 implantations.append({
369 'implantation': i,
370 'postes': rh.Poste.objects.filter(implantation=i),
371 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
372 })
373 data.append({
374 'region': r,
375 'implantations': implantations
376 })
377
378 c['data'] = data
379
380
381 return render_to_response('rh/rapports/postes_implantation.html', c, RequestContext(request))
382
383
384 @login_required
385 @drh_or_admin_required
386 def rapports_postes_service(request):
387 c = {}
388 data = []
389 for s in rh.Service.objects.all():
390 postes = rh.Poste.objects.filter(service=s).all()
391 num_postes = rh.Poste.objects.filter(service=s).count()
392 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
393
394 c['data'] = data
395 return render_to_response('rh/rapports/postes_service.html', c, RequestContext(request))
396
397
398 def region_protected(model):
399 def wrapper(func):
400 def wrapped(request, id):
401 if request.user.is_superuser:
402 return func(request, id)
403 user_groups = request.user.groups.all()
404 if grp_drh in user_groups:
405 return func(request, id)
406 if grp_correspondants_rh in user_groups:
407 employe = get_employe_from_user(request.user)
408 q = Q(**{model.prefix_implantation: employe.implantation.region})
409 qs = model.objects.filter(q)
410 if int(id) in [o.id for o in qs]:
411 return func(request, id)
412 return redirect_interdiction(request)
413 return wrapped
414 return wrapper
415
416
417 @region_protected(rh.Dossier)
418 def dossier_apercu(request, dossier_id):
419 d = get_object_or_404(rh.Dossier, pk=dossier_id)
420 c = {
421 'is_popup' : request.GET.get('_popup', False),
422 'dossier' : d,
423 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
424 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
425 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
426 'media_url': settings.PRIVE_MEDIA_URL,
427 }
428 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
429
430 @region_protected(rh.Poste)
431 def poste_apercu(request, poste_id):
432 c = {
433 'is_popup' : request.GET.get('_popup', False),
434 'poste' : get_object_or_404(rh.Poste, pk=poste_id),
435 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
436 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
437 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
438 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
439 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
440 'media_url': settings.PRIVE_MEDIA_URL,
441 }
442 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
443
444 def employe_apercu(request, employe_id):
445 employe = get_object_or_404(rh.Employe, pk=employe_id)
446 user_groups = request.user.groups.all()
447 dossiers = None
448
449 if request.user.is_superuser or \
450 grp_drh in user_groups:
451 q = Q(employe=employe)
452 if grp_correspondants_rh in user_groups:
453 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
454 q = Q(employe=employe) & Q(implantation__region__in=regions)
455
456 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
457
458 c = {
459 'is_popup' : request.GET.get('_popup', False),
460 'employe' : employe,
461 'dossiers' : dossiers,
462 'media_url': settings.PRIVE_MEDIA_URL,
463 }
464 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
465
466 @login_required
467 @drh_or_admin_required
468 def organigrammes_employe(request, id, level="all"):
469
470 poste = get_object_or_404(rh.Poste, pk=id)
471 dossiers_by_poste = dict((d.poste_id, d) for d in rh.Dossier.objects.select_related('employe', 'poste').all())
472 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
473
474 e = dossiers_by_poste[poste.id].employe
475 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
476 graph = pgv.AGraph()
477
478 if rh.Poste.objects.filter(responsable=poste).count() > 0:
479 postes_handle = [poste]
480 while postes_handle:
481 postes_handle = rh.Poste.objects.select_related('implantation').filter((Q(date_fin__gt=date.today()) | Q(date_fin=None)) & (Q(date_debut__lt=date.today()) | Q(date_debut=None)) ).filter(responsable__in=postes_handle).exclude(supprime=True).exclude(responsable=None).all()
482
483 for p in postes_handle:
484 if p.responsable_id != p.id:
485 graph.add_edge(dossiers_by_poste[p.responsable_id].poste_id, p.id)
486
487 else:
488 graph.add_node(poste.id)
489
490 if level != "all":
491 postes_niveau = [poste.id]
492 for niveau in range(int(level)):
493 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
494
495 while postes_niveau:
496 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
497 if postes_niveau:
498 for p in postes_niveau:
499 if graph.has_node(p):
500 graph.remove_node(p)
501
502 a = graph
503 a.name = name.encode('ascii', 'xmlcharrefreplace')
504
505 poste_remontant = poste
506 while poste_remontant.responsable_id:
507 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
508 poste_remontant = poste_remontant.responsable
509
510 rh_graph.bind_poste_to_graph(a, postes_by_id)
511 #a.graph_attr['normalize'] = True
512 #a.graph_attr['level'] = 2
513 a.layout(prog='dot')
514
515 svg = a.draw(format='svg')
516
517 c = {
518 'svg': svg
519 }
520
521 if 'forcer' in request.GET:
522 response = HttpResponse(svg, mimetype='image/svg+xml')
523 response['Content-Disposition'] = 'attachment; filename=organigramme.svg'
524 return response
525
526 return render_to_response('rh/organigrammes/employe.html', c, RequestContext(request), mimetype="image/svg+xml")
527
528
529 @login_required
530 @drh_or_admin_required
531 def organigrammes_service(request, id):
532
533 service = get_object_or_404(rh.Service, pk=id)
534 svg = rh_graph.organigramme_postes_cluster( \
535 cluster_filter={"service": service}, \
536 titre=u"Organigramme du service %s" % service.nom,
537 cluster_titre=service.nom)
538
539 c = {
540 'svg': svg
541 }
542
543 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
544
545 @login_required
546 @drh_or_admin_required
547 def organigrammes_implantation(request, id):
548
549 implantation = get_object_or_404(ref.Implantation, pk=id)
550 svg = rh_graph.organigramme_postes_cluster( \
551 cluster_filter={"implantation": implantation}, \
552 titre=u"Organigramme de l'implantation %s" % implantation.nom,
553 cluster_titre=implantation.nom)
554
555 c = {
556 'svg': svg
557 }
558
559 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
560
561 @login_required
562 @drh_or_admin_required
563 def organigrammes_region(request, id):
564
565 region = get_object_or_404(ref.Region, pk=id)
566 svg = rh_graph.organigramme_postes_cluster( \
567 cluster_filter={"implantation__region": region}, \
568 titre=u"Organigramme du bureau de %s" % region.nom,
569 cluster_titre=region.nom)
570
571 c = {
572 'svg': svg
573 }
574
575 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")