32dfa8f9f7b6960a8d50210ceba10b3c233a55e4
[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
21 # pas de reference a DAE devrait etre refactorisé
22 from dae.utils import get_employe_from_user
23 from dae.decorators import redirect_interdiction
24 from dae.workflow import grp_drh, grp_correspondants_rh
25 from django.conf import settings
26
27 @login_required
28 def piece(request, filename):
29 """Téléchargement d'une pièce jointe à un poste."""
30 model, id, f = filename.split('/')
31 if model == 'contrat':
32 # TODO definir peut-être un controle d'accès
33 piece = get_object_or_404(rh.Contrat, fichier=filename)
34 return sendfile(request, piece.fichier.path)
35 if model == 'employe':
36 # TODO definir peut-être un controle d'accès
37 piece = get_object_or_404(rh.EmployePiece, fichier=filename)
38 return sendfile(request, piece.fichier.path)
39 if model == 'poste':
40 piece = get_object_or_404(rh.PostePiece, fichier=filename)
41 if rh.Poste.objects.ma_region_ou_service(request.user).filter(id=piece.poste_id).exists():
42 return sendfile(request, piece.fichier.path)
43 else:
44 return redirect_interdiction(request)
45 if model == 'dossier':
46 piece = get_object_or_404(rh.DossierPiece, fichier=filename)
47 if rh.Dossier.objects.ma_region_ou_service(request.user).filter(id=piece.dossier_id).exists():
48 return sendfile(request, piece.fichier.path)
49 else:
50 return redirect_interdiction(request)
51
52 # homes
53 @login_required
54 def profil(request):
55 """Profil personnel de l'employé - éditable"""
56 rc = RequestContext(request)
57 c = {}
58
59 employe = rc['this_employe']
60
61 c['user'] = request.user
62 c['employe'] = employe
63 return render_to_response('rh/profil.html', c, rc)
64
65 # employes
66 @login_required
67 def employes_liste(request):
68 """Liste des employés."""
69 today = date.today()
70 employes = rh.Employe.objects \
71 .filter(actif=True, supprime=False) \
72 .filter(dossiers__actif=True, dossiers__supprime=False) \
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_poste(request):
101
102 lookup_params = dict(request.GET.items())
103
104 comble = 'all'
105
106 for key, value in lookup_params.items():
107 if key == 'o' or key == 'ot':
108 del lookup_params[key]
109 continue
110 if not isinstance(key, str):
111 # 'key' will be used as a keyword argument later, so Python
112 # requires it to be a string.
113 del lookup_params[key]
114 lookup_params[smart_str(key)] = value
115
116 if key == 'comble':
117 comble = value
118 del lookup_params[key]
119
120 #postes = rh.Poste.actifs.select_related('implantation', 'dossier').all()
121 postes = rh.Poste.actifs.select_related('implantation') \
122 .extra(select={'employe_id':'select group_concat(employe separator "|") from rh_dossier where poste=rh_poste.id and rh_dossier.actif = 1 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.actif = 1 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.actif = 1 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 contrats = contrats.filter(**lookup_params)
180 if 'o' in request.GET:
181 contrats = contrats.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
182
183 employes = set([c.dossier.employe_id for c in contrats])
184
185 headers = [
186 ("dossier__employe__id", u"# de l'employé"),
187 ("dossier__employe__nom", u"Nom"),
188 ("dossier__employe__prenom", u"Prénom"),
189 ("type_contrat__nom", u"Poste"),
190 ("type_contrat__nom", u"Type de contrat"),
191 ("date_debut", u"Date début"),
192 ("date_fin", u"Date fin"),
193 ]
194 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
195
196 c = {
197 'title': 'Rapport des contrats',
198 'contrats': contrats,
199 'count': len(contrats),
200 'count_employe' : len(employes),
201 'headers': list(h.headers()),
202 }
203
204 return render_to_response('rh/rapports/contrats.html', c, RequestContext(request))
205
206
207 @login_required
208 @drh_or_admin_required
209 def rapports_remuneration(request):
210
211 lookup_params = dict(request.GET.items())
212 if 'ot' in lookup_params:
213 del lookup_params['ot']
214 if 'o' in lookup_params:
215 del lookup_params['o']
216
217 for key, value in lookup_params.items():
218 if not isinstance(key, str):
219 # 'key' will be used as a keyword argument later, so Python
220 # requires it to be a string.
221 del lookup_params[key]
222 lookup_params[smart_str(key)] = value
223
224 employes = rh.Employe.objects.all()
225 if 'o' in request.GET:
226 employes = employes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
227
228 employes = employes.filter(**lookup_params)
229
230 output = []
231 headers = [
232 ("id", u"# de l'employé"),
233 ("nom", u"Nom"),
234 ("prenom", u"Prénom"),
235 ("", u"Salaire"),
236 ("", u"RAS"),
237 ("", u"Indemnités"),
238 ("", u"Accessoire"),
239 ("", u"Charges patronales"),
240 ("", u"Total"),
241 ]
242 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
243
244 for employe in employes:
245 line = {}
246 output.append(line)
247
248 dossiers = employe.rh_dossiers.all()
249
250 remun = {}
251 remun_sum_euro = 0
252
253 for dossier in dossiers:
254 this_remun, this_remun_sum, this_remun_sum_euro = calc_remun(dossier)
255
256 for item in this_remun:
257 if item not in remun:
258 remun[item] = this_remun[item]
259 else:
260 remun[item][0] += this_remun[item][0]
261 remun[item][1] += this_remun[item][1]
262
263 remun_sum_euro += this_remun_sum_euro
264
265 line['remun_sum_euro'] = remun_sum_euro
266
267 for r in remun:
268 if r == u'Indemnité':
269 line['Indemnite'] = remun[r][1]
270 else:
271 line[r] = remun[r][1]
272
273 line['id'] = employe.id
274 line['nom'] = employe.nom
275 line['prenom'] = employe.prenom
276
277
278 c = {
279 'title': 'Rapport de remuneration',
280 'employes': output,
281 'headers': list(h.headers()),
282 }
283
284 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
285
286 def region_protected(model):
287 def wrapper(func):
288 def wrapped(request, id):
289 if request.user.is_superuser:
290 return func(request, id)
291 user_groups = request.user.groups.all()
292 if grp_drh in user_groups:
293 return func(request, id)
294 if grp_correspondants_rh in user_groups:
295 employe = get_employe_from_user(request.user)
296 q = Q(**{model.prefix_implantation: employe.implantation.region})
297 qs = model.objects.filter(q)
298 if int(id) in [o.id for o in qs]:
299 return func(request, id)
300 return redirect_interdiction(request)
301 return wrapped
302 return wrapper
303
304
305 @region_protected(rh.Dossier)
306 def dossier_apercu(request, dossier_id):
307 d = get_object_or_404(rh.Dossier, pk=dossier_id)
308 c = {
309 'is_popup' : request.GET.get('_popup', False),
310 'dossier' : d,
311 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
312 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
313 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
314 'media_url': settings.PRIVE_MEDIA_URL,
315 }
316 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
317
318 @region_protected(rh.Poste)
319 def poste_apercu(request, poste_id):
320 c = {
321 'is_popup' : request.GET.get('_popup', False),
322 'poste' : get_object_or_404(rh.Poste, pk=poste_id),
323 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
324 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
325 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
326 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
327 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
328 'media_url': settings.PRIVE_MEDIA_URL,
329 }
330 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
331
332 def employe_apercu(request, employe_id):
333 from dae.workflow import grp_drh, grp_correspondants_rh
334 employe = get_object_or_404(rh.Employe, pk=employe_id)
335 user_groups = request.user.groups.all()
336
337 dernier_dossier = None
338 dossiers = None
339
340 if request.user.is_superuser or \
341 grp_drh in user_groups:
342 q = Q(employe=employe)
343 if grp_correspondants_rh in user_groups:
344 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
345 q = Q(employe=employe) & Q(implantation__region__in=regions)
346
347 dossiers = rh.Dossier.objects.filter(employe=employe).order_by('-date_debut')
348
349 c = {
350 'is_popup' : request.GET.get('_popup', False),
351 'employe' : employe,
352 'dossiers' : dossiers,
353 'media_url': settings.PRIVE_MEDIA_URL,
354 }
355 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
356
357