Masse salariale WIP et bugfix
[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(dict(request.GET.items()), 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 pass
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 'is_popup' : request.GET.get('_popup', False),
416 'dossier' : d,
417 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
418 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
419 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
420 'media_url': settings.PRIVE_MEDIA_URL,
421 }
422 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
423
424 @region_protected(rh.Poste)
425 def poste_apercu(request, poste_id):
426 c = {
427 'is_popup' : request.GET.get('_popup', False),
428 'poste' : get_object_or_404(rh.Poste, pk=poste_id),
429 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
430 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
431 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
432 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
433 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
434 'media_url': settings.PRIVE_MEDIA_URL,
435 }
436 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
437
438 def employe_apercu(request, employe_id):
439 employe = get_object_or_404(rh.Employe, pk=employe_id)
440 user_groups = request.user.groups.all()
441 dossiers = None
442
443 if request.user.is_superuser or \
444 grp_drh in user_groups:
445 q = Q(employe=employe)
446 if grp_correspondants_rh in user_groups:
447 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
448 q = Q(employe=employe) & Q(implantation__region__in=regions)
449
450 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
451
452 c = {
453 'is_popup' : request.GET.get('_popup', False),
454 'employe' : employe,
455 'dossiers' : dossiers,
456 'media_url': settings.PRIVE_MEDIA_URL,
457 }
458 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
459
460 @login_required
461 @drh_or_admin_required
462 def organigrammes_employe(request, id, level="all"):
463
464 poste = get_object_or_404(rh.Poste, pk=id)
465 dossiers_by_poste = dict((d.poste_id, d) for d in rh.Dossier.objects.select_related('employe', 'poste').all())
466 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
467
468 e = dossiers_by_poste[poste.id].employe
469 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
470 graph = pgv.AGraph()
471
472 if rh.Poste.objects.filter(responsable=poste).count() > 0:
473 postes_handle = [poste]
474 while postes_handle:
475 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()
476
477 for p in postes_handle:
478 if p.responsable_id != p.id:
479 graph.add_edge(dossiers_by_poste[p.responsable_id].poste_id, p.id)
480
481 else:
482 graph.add_node(poste.id)
483
484 if level != "all":
485 postes_niveau = [poste.id]
486 for niveau in range(int(level)):
487 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
488
489 while postes_niveau:
490 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
491 if postes_niveau:
492 for p in postes_niveau:
493 if graph.has_node(p):
494 graph.remove_node(p)
495
496 a = graph
497 a.name = name.encode('ascii', 'xmlcharrefreplace')
498
499 poste_remontant = poste
500 while poste_remontant.responsable_id:
501 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
502 poste_remontant = poste_remontant.responsable
503
504 rh_graph.bind_poste_to_graph(a, postes_by_id)
505 #a.graph_attr['normalize'] = True
506 #a.graph_attr['level'] = 2
507 a.layout(prog='dot')
508
509 svg = a.draw(format='svg')
510
511 c = {
512 'svg': svg
513 }
514
515 if 'forcer' in request.GET:
516 response = HttpResponse(svg, mimetype='image/svg+xml')
517 response['Content-Disposition'] = 'attachment; filename=organigramme.svg'
518 return response
519
520 return render_to_response('rh/organigrammes/employe.html', c, RequestContext(request), mimetype="image/svg+xml")
521
522
523 @login_required
524 @drh_or_admin_required
525 def organigrammes_service(request, id):
526
527 service = get_object_or_404(rh.Service, pk=id)
528 svg = rh_graph.organigramme_postes_cluster( \
529 cluster_filter={"service": service}, \
530 titre=u"Organigramme du service %s" % service.nom,
531 cluster_titre=service.nom)
532
533 c = {
534 'svg': svg
535 }
536
537 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
538
539 @login_required
540 @drh_or_admin_required
541 def organigrammes_implantation(request, id):
542
543 implantation = get_object_or_404(ref.Implantation, pk=id)
544 svg = rh_graph.organigramme_postes_cluster( \
545 cluster_filter={"implantation": implantation}, \
546 titre=u"Organigramme de l'implantation %s" % implantation.nom,
547 cluster_titre=implantation.nom)
548
549 c = {
550 'svg': svg
551 }
552
553 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
554
555 @login_required
556 @drh_or_admin_required
557 def organigrammes_region(request, id):
558
559 region = get_object_or_404(ref.Region, pk=id)
560 svg = rh_graph.organigramme_postes_cluster( \
561 cluster_filter={"implantation__region": region}, \
562 titre=u"Organigramme du bureau de %s" % region.nom,
563 cluster_titre=region.nom)
564
565 c = {
566 'svg': svg
567 }
568
569 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")