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