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