apercu
[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_remuneration(request):
199
200 lookup_params = dict(request.GET.items())
201 if 'ot' in lookup_params:
202 del lookup_params['ot']
203 if 'o' in lookup_params:
204 del lookup_params['o']
205
206 for key, value in lookup_params.items():
207 if not isinstance(key, str):
208 # 'key' will be used as a keyword argument later, so Python
209 # requires it to be a string.
210 del lookup_params[key]
211 lookup_params[smart_str(key)] = value
212
213 employes = rh.Employe.objects.all()
214 if 'o' in request.GET:
215 employes = employes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
216
217 employes = employes.filter(**lookup_params)
218
219 output = []
220 headers = [
221 ("id", u"# de l'employé"),
222 ("nom", u"Nom"),
223 ("prenom", u"Prénom"),
224 ("", u"Salaire"),
225 ("", u"RAS"),
226 ("", u"Indemnités"),
227 ("", u"Accessoire"),
228 ("", u"Charges patronales"),
229 ("", u"Total"),
230 ]
231 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
232
233 for employe in employes:
234 line = {}
235 output.append(line)
236
237 dossiers = employe.rh_dossiers.all()
238
239 remun = {}
240 remun_sum_euro = 0
241
242 for dossier in dossiers:
243 this_remun, this_remun_sum, this_remun_sum_euro = calc_remun(dossier)
244
245 for item in this_remun:
246 if item not in remun:
247 remun[item] = this_remun[item]
248 else:
249 remun[item][0] += this_remun[item][0]
250 remun[item][1] += this_remun[item][1]
251
252 remun_sum_euro += this_remun_sum_euro
253
254 line['remun_sum_euro'] = remun_sum_euro
255
256 for r in remun:
257 if r == u'Indemnité':
258 line['Indemnite'] = remun[r][1]
259 else:
260 line[r] = remun[r][1]
261
262 line['id'] = employe.id
263 line['nom'] = employe.nom
264 line['prenom'] = employe.prenom
265
266
267 c = {
268 'title': 'Rapport de remuneration',
269 'employes': output,
270 'headers': list(h.headers()),
271 }
272
273 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
274
275 @login_required
276 @drh_or_admin_required
277 def rapports_employe_sans_contrat(request):
278
279 lookup_params = dict(request.GET.items())
280 if 'ot' in lookup_params:
281 del lookup_params['ot']
282 if 'o' in lookup_params:
283 del lookup_params['o']
284
285 for key, value in lookup_params.items():
286 if not isinstance(key, str):
287 # 'key' will be used as a keyword argument later, so Python
288 # requires it to be a string.
289 del lookup_params[key]
290 lookup_params[smart_str(key)] = value
291
292 employes_query = rh.Employe.objects
293 if 'o' in request.GET:
294 employes_query = employes_query.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
295
296 employes = {}
297
298 dossiers_en_cours = rh.Dossier.objects.filter(Q(date_fin=None) | Q(date_fin__gt=date.today()))
299 tous_contrats_echus = rh.Contrat.objects.filter(date_fin__lt=date.today(), dossier__in=dossiers_en_cours)
300 contrats = tous_contrats_echus.filter(**lookup_params).all()
301 for c in contrats:
302 if c.dossier.employe.id not in employes.keys():
303 employes[c.dossier.employe.id] = {'employe': c.dossier.employe, 'dossiers': []}
304 employes[c.dossier.employe.id]['dossiers'] += [c.dossier,]
305
306
307
308 headers = [
309 ("id", u"# de l'employé"),
310 ("nom", u"Nom"),
311 ("prenom", u"Prénom"),
312 ("dossier", u"Dossiers"),
313 ]
314 h = SortHeaders(request, headers, order_field_type="ot", order_field="o", not_sortable=('dossier',))
315
316 c = {
317 'title': u'Rapport des employés sans contrat',
318 'employes': employes,
319 'count': len(employes),
320 'headers': list(h.headers()),
321 }
322
323 return render_to_response('rh/rapports/employes_sans_contrat.html', c, RequestContext(request))
324
325 @login_required
326 @drh_or_admin_required
327 def rapports_postes_modelisation(request):
328 c = {}
329 data = []
330
331 for f in rh.FamilleEmploi.objects.all():
332 types = rh.TypePoste.objects.filter(famille_emploi=f)
333 data_types = []
334 for t in types.all():
335 postes = rh.Poste.objects.filter(type_poste=t)
336 data_types.append({
337 'num_postes': postes.count(),
338 'postes': postes.all(),
339 'type': f,
340 })
341
342 data.append({
343 'famille': f,
344 'nb_types': types.count(),
345 'types' : data_types
346 })
347
348 c['data'] = data
349
350
351 return render_to_response('rh/rapports/postes_modelisation.html', c, RequestContext(request))
352
353
354 @login_required
355 @drh_or_admin_required
356 def rapports_postes_implantation(request):
357 c = {}
358 data = []
359 for r in ref.Region.objects.all():
360 implantations = []
361 for i in ref.Implantation.objects.filter(region=r):
362 implantations.append({
363 'implantation': i,
364 'postes': rh.Poste.objects.filter(implantation=i),
365 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
366 })
367 data.append({
368 'region': r,
369 'implantations': implantations
370 })
371
372 c['data'] = data
373
374
375 return render_to_response('rh/rapports/postes_implantation.html', c, RequestContext(request))
376
377
378 @login_required
379 @drh_or_admin_required
380 def rapports_postes_service(request):
381 c = {}
382 data = []
383 for s in rh.Service.objects.all():
384 postes = rh.Poste.objects.filter(service=s).all()
385 num_postes = rh.Poste.objects.filter(service=s).count()
386 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
387
388 c['data'] = data
389 return render_to_response('rh/rapports/postes_service.html', c, RequestContext(request))
390
391
392 def region_protected(model):
393 def wrapper(func):
394 def wrapped(request, id):
395 if request.user.is_superuser:
396 return func(request, id)
397 user_groups = request.user.groups.all()
398 if grp_drh in user_groups:
399 return func(request, id)
400 if grp_correspondants_rh in user_groups:
401 employe = get_employe_from_user(request.user)
402 q = Q(**{model.prefix_implantation: employe.implantation.region})
403 qs = model.objects.filter(q)
404 if int(id) in [o.id for o in qs]:
405 return func(request, id)
406 return redirect_interdiction(request)
407 return wrapped
408 return wrapper
409
410
411 @region_protected(rh.Dossier)
412 def dossier_apercu(request, dossier_id):
413 d = get_object_or_404(rh.Dossier, pk=dossier_id)
414 c = {
415 'title': u"Dossier %s" % (d, ),
416 'is_popup' : request.GET.get('_popup', False),
417 'dossier' : d,
418 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
419 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
420 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
421 'media_url': settings.PRIVE_MEDIA_URL,
422 }
423 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
424
425 @region_protected(rh.Poste)
426 def poste_apercu(request, poste_id):
427 c = {
428 'is_popup' : request.GET.get('_popup', False),
429 'poste' : get_object_or_404(rh.Poste, pk=poste_id),
430 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
431 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
432 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
433 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
434 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
435 'media_url': settings.PRIVE_MEDIA_URL,
436 }
437 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
438
439 def employe_apercu(request, employe_id):
440 employe = get_object_or_404(rh.Employe, pk=employe_id)
441 user_groups = request.user.groups.all()
442 dossiers = None
443
444 if request.user.is_superuser or \
445 grp_drh in user_groups:
446 q = Q(employe=employe)
447 if grp_correspondants_rh in user_groups:
448 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
449 q = Q(employe=employe) & Q(implantation__region__in=regions)
450
451 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
452
453 c = {
454 'is_popup' : request.GET.get('_popup', False),
455 'employe' : employe,
456 'dossiers' : dossiers,
457 'media_url': settings.PRIVE_MEDIA_URL,
458 }
459 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
460
461 @login_required
462 @drh_or_admin_required
463 def organigrammes_employe(request, id, level="all"):
464
465 poste = get_object_or_404(rh.Poste, pk=id)
466 dossiers_by_poste = dict((d.poste_id, d) for d in rh.Dossier.objects.select_related('employe', 'poste').all())
467 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
468
469 e = dossiers_by_poste[poste.id].employe
470 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
471 graph = pgv.AGraph()
472
473 if rh.Poste.objects.filter(responsable=poste).count() > 0:
474 postes_handle = [poste]
475 while postes_handle:
476 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()
477
478 for p in postes_handle:
479 if p.responsable_id != p.id:
480 graph.add_edge(dossiers_by_poste[p.responsable_id].poste_id, p.id)
481
482 else:
483 graph.add_node(poste.id)
484
485 if level != "all":
486 postes_niveau = [poste.id]
487 for niveau in range(int(level)):
488 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
489
490 while postes_niveau:
491 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
492 if postes_niveau:
493 for p in postes_niveau:
494 if graph.has_node(p):
495 graph.remove_node(p)
496
497 a = graph
498 a.name = name.encode('ascii', 'xmlcharrefreplace')
499
500 poste_remontant = poste
501 while poste_remontant.responsable_id:
502 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
503 poste_remontant = poste_remontant.responsable
504
505 rh_graph.bind_poste_to_graph(a, postes_by_id)
506 #a.graph_attr['normalize'] = True
507 #a.graph_attr['level'] = 2
508 a.layout(prog='dot')
509
510 svg = a.draw(format='svg')
511
512 c = {
513 'svg': svg
514 }
515
516 if 'forcer' in request.GET:
517 response = HttpResponse(svg, mimetype='image/svg+xml')
518 response['Content-Disposition'] = 'attachment; filename=organigramme.svg'
519 return response
520
521 return render_to_response('rh/organigrammes/employe.html', c, RequestContext(request), mimetype="image/svg+xml")
522
523
524 @login_required
525 @drh_or_admin_required
526 def organigrammes_service(request, id):
527
528 service = get_object_or_404(rh.Service, pk=id)
529 svg = rh_graph.organigramme_postes_cluster( \
530 cluster_filter={"service": service}, \
531 titre=u"Organigramme du service %s" % service.nom,
532 cluster_titre=service.nom)
533
534 c = {
535 'svg': svg
536 }
537
538 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
539
540 @login_required
541 @drh_or_admin_required
542 def organigrammes_implantation(request, id):
543
544 implantation = get_object_or_404(ref.Implantation, pk=id)
545 svg = rh_graph.organigramme_postes_cluster( \
546 cluster_filter={"implantation": implantation}, \
547 titre=u"Organigramme de l'implantation %s" % implantation.nom,
548 cluster_titre=implantation.nom)
549
550 c = {
551 'svg': svg
552 }
553
554 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
555
556 @login_required
557 @drh_or_admin_required
558 def organigrammes_region(request, id):
559
560 region = get_object_or_404(ref.Region, pk=id)
561 svg = rh_graph.organigramme_postes_cluster( \
562 cluster_filter={"implantation__region": region}, \
563 titre=u"Organigramme du bureau de %s" % region.nom,
564 cluster_titre=region.nom)
565
566 c = {
567 'svg': svg
568 }
569
570 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
571