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