Organigramme des employés : ajout de téléchargement
[auf_rh_dae.git] / project / rh / views.py
CommitLineData
e9bbd6ba 1# -*- encoding: utf-8 -*-
a251ac8d 2from sendfile import sendfile
c9122f1d 3from datetime import date
a7de62d7 4from itertools import izip
08faf06e 5from base64 import b64encode
fa1624f6 6import networkx as nx
9b0a8554 7
fbe60a9d 8from django.db.models import Q
3411ac33 9from django.contrib.auth.decorators import login_required
fd009814 10from django.utils.encoding import smart_str
e9bbd6ba 11from django.shortcuts import redirect, render_to_response, get_object_or_404
12from django.template import RequestContext
9d53bc73 13from django.http import Http404
77bd83d1 14from django.core.urlresolvers import reverse
a251ac8d 15from django.http import HttpResponse
e9bbd6ba 16
d04d084c 17from datamaster_modeles import models as ref
d04d084c 18from project.lib import get_employe_from_id
ae936f8d 19
d04d084c 20from rh import models as rh
e2c0b1ac 21from rh.lib import calc_remun
02c1b3dc 22from rh.decorators import drh_or_admin_required
9d53bc73 23from rh.templatetags.rapports import SortHeaders
f0f6b03e 24from rh.change_list import RechercheTemporelle
a9faef67 25
9817fed5
OL
26# pas de reference a DAE devrait etre refactorisé
27from dae.utils import get_employe_from_user
28from dae.decorators import redirect_interdiction
29from dae.workflow import grp_drh, grp_correspondants_rh
baf9b78c 30from django.conf import settings
9817fed5 31
3411ac33 32# homes
c9122f1d 33@login_required
34def profil(request):
35 """Profil personnel de l'employé - éditable"""
36 rc = RequestContext(request)
37 c = {}
d04d084c 38
c9122f1d 39 employe = rc['this_employe']
65f9fac8 40
c9122f1d 41 c['user'] = request.user
42 c['employe'] = employe
c9122f1d 43 return render_to_response('rh/profil.html', c, rc)
a9faef67 44
45# employes
3411ac33 46@login_required
a9faef67 47def employes_liste(request):
48 """Liste des employés."""
5ea6b5bb 49 today = date.today()
50 employes = rh.Employe.objects \
5ea6b5bb 51 .exclude(dossiers__date_debut__gt=today) \
52 .exclude(dossiers__date_fin__lt=today) \
53 .order_by('nom')
a9faef67 54 c = {
55 'user':request.user,
56 'employes':employes,
57 }
58 return render_to_response('rh/employes_liste.html', c, RequestContext(request))
59
3411ac33 60@login_required
a9faef67 61def 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))
63e17dff
PP
72
73
74# Rapports
75
76@login_required
02c1b3dc 77@drh_or_admin_required
48487f09
JPC
78def rapports_postes_hierarchie(request):
79
80 c = {}
ce18dd0a 81 graph = nx.DiGraph()
fa1624f6
JPC
82 postes = rh.Poste.objects.all()
83 postes_id = dict((p.id, p) for p in postes)
ce18dd0a 84 graph.add_node(p for p in postes)
48487f09 85
fa1624f6
JPC
86 for p in postes:
87 if p.responsable_id != p.id:
ce18dd0a 88 graph.add_edge(postes_id[p.responsable_id], p)
48487f09 89
fa1624f6 90 c['postes'] = nx.to_dict_of_lists(graph)
48487f09
JPC
91
92 return render_to_response('rh/rapports/postes_hierarchie.html', c, RequestContext(request))
93
94@login_required
95@drh_or_admin_required
08faf06e
JPC
96def hierarchie_poste(request):
97 pass
98
99@login_required
100@drh_or_admin_required
63e17dff
PP
101def rapports_poste(request):
102
fd009814
PP
103 lookup_params = dict(request.GET.items())
104
7821915f
PP
105 comble = 'all'
106
fd009814 107 for key, value in lookup_params.items():
9d53bc73
JPC
108 if key == 'o' or key == 'ot':
109 del lookup_params[key]
110 continue
fd009814
PP
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
7821915f
PP
117 if key == 'comble':
118 comble = value
119 del lookup_params[key]
120
ed3cbb32
OL
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' % \
9202c5db
JPC
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 }) \
ed3cbb32 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' % \
9202c5db
JPC
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 }) \
ed3cbb32 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' % \
9202c5db
JPC
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 })
9d53bc73 131
65e02621 132 postes = postes.filter(**lookup_params)
9d53bc73 133 if 'o' in request.GET:
65e02621
JPC
134 postes = postes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
135
a7de62d7
JPC
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
4dade240
JPC
145 headers = [
146 ("id", u"# du poste"),
147 ("nom", u"Nom du poste"),
65e02621 148 ("implantation__id", u"Implantation"),
4dade240 149 ("employe_nom", u"Nom"),
4dade240
JPC
150 ]
151 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
63e17dff
PP
152 c = {
153 'title': 'Rapport des postes',
a7de62d7
JPC
154 'postes': out,
155 'count': len(out),
65e02621 156 'headers': list(h.headers()),
63e17dff
PP
157 }
158
159 return render_to_response('rh/rapports/postes.html', c, RequestContext(request))
f2d65e83 160
02c1b3dc
JPC
161@login_required
162@drh_or_admin_required
f2d65e83
PP
163def rapports_contrat(request):
164
165 lookup_params = dict(request.GET.items())
65e02621
JPC
166 if 'ot' in lookup_params:
167 del lookup_params['ot']
168 if 'o' in lookup_params:
169 del lookup_params['o']
f2d65e83
PP
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
65e02621 178 contrats = rh.Contrat.objects.select_related('dossier', 'dossier__poste', 'dossier__poste__implantation', 'type_contrat', 'dossier__employe')
f0f6b03e
OL
179
180 cl = RechercheTemporelle(request, rh.Contrat)
181 lookup_params = cl.purge_params(lookup_params)
821b9889 182 contrats = contrats.filter(**lookup_params).exclude(dossier__employe__supprime=1)
f0f6b03e
OL
183 contrats = cl.filter_temporel(contrats)
184
65e02621
JPC
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']))
f2d65e83 187
8ee135b7
JPC
188 employes = set([c.dossier.employe_id for c in contrats])
189
65e02621
JPC
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
f2d65e83 201 c = {
f0f6b03e 202 'cl' : cl,
f2d65e83
PP
203 'title': 'Rapport des contrats',
204 'contrats': contrats,
8ee135b7
JPC
205 'count': len(contrats),
206 'count_employe' : len(employes),
65e02621 207 'headers': list(h.headers()),
f2d65e83
PP
208 }
209
210 return render_to_response('rh/rapports/contrats.html', c, RequestContext(request))
e2c0b1ac
PP
211
212
02c1b3dc
JPC
213@login_required
214@drh_or_admin_required
e2c0b1ac
PP
215def rapports_remuneration(request):
216
217 lookup_params = dict(request.GET.items())
9202c5db
JPC
218 if 'ot' in lookup_params:
219 del lookup_params['ot']
220 if 'o' in lookup_params:
221 del lookup_params['o']
e2c0b1ac
PP
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()
9202c5db
JPC
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
e2c0b1ac
PP
234 employes = employes.filter(**lookup_params)
235
236 output = []
9202c5db
JPC
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")
e2c0b1ac
PP
249
250 for employe in employes:
251 line = {}
252 output.append(line)
253
da6c523f 254 dossiers = employe.rh_dossiers.all()
e2c0b1ac
PP
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é':
e2c0b1ac
PP
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,
9202c5db 287 'headers': list(h.headers()),
e2c0b1ac
PP
288 }
289
290 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
3ebc0952 291
783e077a
JPC
292@login_required
293@drh_or_admin_required
c8b22fd1
JPC
294def 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
7c5645f0 313 employes = {}
00c9d7c2
OL
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
c8b22fd1
JPC
324
325 headers = [
1d2d4dc2
JPC
326 ("id", u"# de l'employé"),
327 ("nom", u"Nom"),
328 ("prenom", u"Prénom"),
80518280 329 ("dossier", u"Dossiers"),
c8b22fd1 330 ]
80518280 331 h = SortHeaders(request, headers, order_field_type="ot", order_field="o", not_sortable=('dossier',))
c8b22fd1
JPC
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
857b5c24
JPC
344def rapports_postes_modelisation(request):
345 c = {}
346 data = []
3c1ba807
JPC
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,
857b5c24 357 })
3c1ba807 358
857b5c24 359 data.append({
3c1ba807
JPC
360 'famille': f,
361 'nb_types': types.count(),
362 'types' : data_types
857b5c24
JPC
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
783e077a
JPC
373def 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
397def rapports_postes_service(request):
398 c = {}
9988aafb
JPC
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})
783e077a 404
9988aafb
JPC
405 c['data'] = data
406 return render_to_response('rh/rapports/postes_service.html', c, RequestContext(request))
783e077a
JPC
407
408
32373f2e
OL
409def region_protected(model):
410 def wrapper(func):
411 def wrapped(request, id):
32373f2e
OL
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)
718abc4d 421 if int(id) in [o.id for o in qs]:
32373f2e
OL
422 return func(request, id)
423 return redirect_interdiction(request)
424 return wrapped
425 return wrapper
426
427
428@region_protected(rh.Dossier)
3ebc0952 429def dossier_apercu(request, dossier_id):
baf9b78c 430 d = get_object_or_404(rh.Dossier, pk=dossier_id)
3ebc0952
OL
431 c = {
432 'is_popup' : request.GET.get('_popup', False),
baf9b78c 433 'dossier' : d,
520ab455
JPC
434 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
435 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
2a36598b 436 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
abf91905 437 'media_url': settings.PRIVE_MEDIA_URL,
3ebc0952
OL
438 }
439 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
4a1f2ece 440
fbe60a9d
OL
441@region_protected(rh.Poste)
442def poste_apercu(request, poste_id):
443 c = {
444 'is_popup' : request.GET.get('_popup', False),
0dcfc806
JPC
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(),
abf91905 451 'media_url': settings.PRIVE_MEDIA_URL,
fbe60a9d
OL
452 }
453 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
454
4a1f2ece 455def employe_apercu(request, employe_id):
fbe60a9d 456 from dae.workflow import grp_drh, grp_correspondants_rh
4a1f2ece 457 employe = get_object_or_404(rh.Employe, pk=employe_id)
fbe60a9d
OL
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:
7eeafa57 467 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
fbe60a9d
OL
468 q = Q(employe=employe) & Q(implantation__region__in=regions)
469
470 dossiers = rh.Dossier.objects.filter(employe=employe).order_by('-date_debut')
471
4a1f2ece
OL
472 c = {
473 'is_popup' : request.GET.get('_popup', False),
474 'employe' : employe,
fbe60a9d 475 'dossiers' : dossiers,
abf91905 476 'media_url': settings.PRIVE_MEDIA_URL,
4a1f2ece
OL
477 }
478 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
150d83ec 479
77bd83d1
JPC
480@login_required
481@drh_or_admin_required
08faf06e
JPC
482def organigrammes_employe(request, id):
483
484 poste = get_object_or_404(rh.Poste, pk=id)
f187a10f
JPC
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())
08faf06e 490
f187a10f
JPC
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)
32373f2e 493
f187a10f
JPC
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)
13ad5ad5 497
f187a10f
JPC
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]
77bd83d1
JPC
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,))
08faf06e 506
f187a10f
JPC
507 a.graph_attr['normalize'] = True
508 a.graph_attr['level'] = 2
509 a.layout(prog='dot')
08faf06e 510
77bd83d1 511 svg = a.draw(format='svg')
08faf06e 512
f187a10f 513 c = {
77bd83d1 514 'svg': svg
f187a10f
JPC
515 }
516 else:
517 c = {}
a251ac8d
JPC
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
08faf06e 524 return render_to_response('rh/organigrammes/employe.html', c, RequestContext(request))