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