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