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