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