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