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