DRY sur les commentaires des apercus
[auf_rh_dae.git] / project / rh / views.py
1 # -*- encoding: utf-8 -*-
2 from datetime import date
3
4 from django.db.models import Q
5 from django.contrib.auth.decorators import login_required
6 from django.utils.encoding import smart_str
7 from django.shortcuts import redirect, render_to_response, get_object_or_404
8 from django.template import RequestContext
9 from django.http import Http404
10 from sendfile import sendfile
11
12 from datamaster_modeles import models as ref
13 from project.lib import get_employe_from_id
14
15 from rh import models as rh
16 from rh.lib import calc_remun
17 from rh.decorators import drh_or_admin_required
18 from rh.templatetags.rapports import SortHeaders
19
20 # pas de reference a DAE devrait etre refactorisé
21 from dae.utils import get_employe_from_user
22 from dae.decorators import redirect_interdiction
23 from dae.workflow import grp_drh, grp_correspondants_rh
24 from django.conf import settings
25
26 @login_required
27 def piece(request, filename):
28 """Téléchargement d'une pièce jointe à un poste."""
29 model, id, f = filename.split('/')
30 if model == 'contrat':
31 # TODO definir peut-être un controle d'accès
32 piece = get_object_or_404(rh.Contrat, fichier=filename)
33 return sendfile(request, piece.fichier.path)
34 if model == 'employe':
35 # TODO definir peut-être un controle d'accès
36 piece = get_object_or_404(rh.EmployePiece, fichier=filename)
37 return sendfile(request, piece.fichier.path)
38 if model == 'poste':
39 piece = get_object_or_404(rh.PostePiece, fichier=filename)
40 if rh.Poste.objects.ma_region_ou_service(request.user).filter(id=piece.poste_id).exists():
41 return sendfile(request, piece.fichier.path)
42 else:
43 return redirect_interdiction(request)
44 if model == 'dossier':
45 piece = get_object_or_404(rh.DossierPiece, fichier=filename)
46 if rh.Dossier.objects.ma_region_ou_service(request.user).filter(id=piece.dossier_id).exists():
47 return sendfile(request, piece.fichier.path)
48 else:
49 return redirect_interdiction(request)
50
51 # homes
52 @login_required
53 def profil(request):
54 """Profil personnel de l'employé - éditable"""
55 rc = RequestContext(request)
56 c = {}
57
58 employe = rc['this_employe']
59
60 c['user'] = request.user
61 c['employe'] = employe
62 return render_to_response('rh/profil.html', c, rc)
63
64 # employes
65 @login_required
66 def employes_liste(request):
67 """Liste des employés."""
68 today = date.today()
69 employes = rh.Employe.objects \
70 .filter(actif=True, supprime=False) \
71 .filter(dossiers__actif=True, dossiers__supprime=False) \
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.actifs.select_related('implantation', 'dossier').all()
120 postes = rh.Poste.actifs.select_related('implantation') \
121 .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' % \
122 ("%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 "") \
123 }) \
124 .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' % \
125 ("%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 "") \
126 }) \
127 .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' % \
128 ("%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 "") \
129 })
130
131 postes = postes.filter(**lookup_params)
132 if 'o' in request.GET:
133 postes = postes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
134
135 headers = [
136 ("id", u"# du poste"),
137 ("nom", u"Nom du poste"),
138 ("implantation__id", u"Implantation"),
139 ("employe_id", u"# de l'employé"),
140 ("employe_nom", u"Nom"),
141 ("employe_prenom", u"Prénom"),
142 ]
143 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
144 c = {
145 'title': 'Rapport des postes',
146 'postes': postes,
147 'count': len(postes),
148 'headers': list(h.headers()),
149 }
150
151 return render_to_response('rh/rapports/postes.html', c, RequestContext(request))
152
153 @login_required
154 @drh_or_admin_required
155 def rapports_contrat(request):
156
157 lookup_params = dict(request.GET.items())
158 if 'ot' in lookup_params:
159 del lookup_params['ot']
160 if 'o' in lookup_params:
161 del lookup_params['o']
162
163 for key, value in lookup_params.items():
164 if not isinstance(key, str):
165 # 'key' will be used as a keyword argument later, so Python
166 # requires it to be a string.
167 del lookup_params[key]
168 lookup_params[smart_str(key)] = value
169
170 contrats = rh.Contrat.objects.select_related('dossier', 'dossier__poste', 'dossier__poste__implantation', 'type_contrat', 'dossier__employe')
171 contrats = contrats.filter(**lookup_params)
172 if 'o' in request.GET:
173 contrats = contrats.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
174
175 employes = set([c.dossier.employe_id for c in contrats])
176
177 headers = [
178 ("dossier__employe__id", u"# de l'employé"),
179 ("dossier__employe__nom", u"Nom"),
180 ("dossier__employe__prenom", u"Prénom"),
181 ("type_contrat__nom", u"Poste"),
182 ("type_contrat__nom", u"Type de contrat"),
183 ("date_debut", u"Date début"),
184 ("date_fin", u"Date fin"),
185 ]
186 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
187
188 c = {
189 'title': 'Rapport des contrats',
190 'contrats': contrats,
191 'count': len(contrats),
192 'count_employe' : len(employes),
193 'headers': list(h.headers()),
194 }
195
196 return render_to_response('rh/rapports/contrats.html', c, RequestContext(request))
197
198
199 @login_required
200 @drh_or_admin_required
201 def rapports_remuneration(request):
202
203 lookup_params = dict(request.GET.items())
204 if 'ot' in lookup_params:
205 del lookup_params['ot']
206 if 'o' in lookup_params:
207 del lookup_params['o']
208
209 for key, value in lookup_params.items():
210 if not isinstance(key, str):
211 # 'key' will be used as a keyword argument later, so Python
212 # requires it to be a string.
213 del lookup_params[key]
214 lookup_params[smart_str(key)] = value
215
216 employes = rh.Employe.objects.all()
217 if 'o' in request.GET:
218 employes = employes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
219
220 employes = employes.filter(**lookup_params)
221
222 output = []
223 headers = [
224 ("id", u"# de l'employé"),
225 ("nom", u"Nom"),
226 ("prenom", u"Prénom"),
227 ("", u"Salaire"),
228 ("", u"RAS"),
229 ("", u"Indemnités"),
230 ("", u"Accessoire"),
231 ("", u"Charges patronales"),
232 ("", u"Total"),
233 ]
234 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
235
236 for employe in employes:
237 line = {}
238 output.append(line)
239
240 dossiers = employe.rh_dossiers.all()
241
242 remun = {}
243 remun_sum_euro = 0
244
245 for dossier in dossiers:
246 this_remun, this_remun_sum, this_remun_sum_euro = calc_remun(dossier)
247
248 for item in this_remun:
249 if item not in remun:
250 remun[item] = this_remun[item]
251 else:
252 remun[item][0] += this_remun[item][0]
253 remun[item][1] += this_remun[item][1]
254
255 remun_sum_euro += this_remun_sum_euro
256
257 line['remun_sum_euro'] = remun_sum_euro
258
259 for r in remun:
260 if r == u'Indemnité':
261 line['Indemnite'] = remun[r][1]
262 else:
263 line[r] = remun[r][1]
264
265 line['id'] = employe.id
266 line['nom'] = employe.nom
267 line['prenom'] = employe.prenom
268
269
270 c = {
271 'title': 'Rapport de remuneration',
272 'employes': output,
273 'headers': list(h.headers()),
274 }
275
276 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
277
278 def region_protected(model):
279 def wrapper(func):
280 def wrapped(request, id):
281 if request.user.is_superuser:
282 return func(request, id)
283 user_groups = request.user.groups.all()
284 if grp_drh in user_groups:
285 return func(request, id)
286 if grp_correspondants_rh in user_groups:
287 employe = get_employe_from_user(request.user)
288 q = Q(**{model.prefix_implantation: employe.implantation.region})
289 qs = model.objects.filter(q)
290 if int(id) in [o.id for o in qs]:
291 return func(request, id)
292 return redirect_interdiction(request)
293 return wrapped
294 return wrapper
295
296
297 @region_protected(rh.Dossier)
298 def dossier_apercu(request, dossier_id):
299 d = get_object_or_404(rh.Dossier, pk=dossier_id)
300 c = {
301 'is_popup' : request.GET.get('_popup', False),
302 'dossier' : d,
303 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
304 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
305 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
306 'media' : settings.PRIVE_MEDIA_URL
307 }
308 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
309
310 @region_protected(rh.Poste)
311 def poste_apercu(request, poste_id):
312 c = {
313 'is_popup' : request.GET.get('_popup', False),
314 'poste' : get_object_or_404(rh.Poste, pk=poste_id),
315 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
316 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
317 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
318 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
319 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
320 }
321 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
322
323 def employe_apercu(request, employe_id):
324 from dae.workflow import grp_drh, grp_correspondants_rh
325 employe = get_object_or_404(rh.Employe, pk=employe_id)
326 user_groups = request.user.groups.all()
327
328 dernier_dossier = None
329 dossiers = None
330
331 if request.user.is_superuser or \
332 grp_drh in user_groups:
333 q = Q(employe=employe)
334 if grp_correspondants_rh in user_groups:
335 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
336 q = Q(employe=employe) & Q(implantation__region__in=regions)
337
338 dossiers = rh.Dossier.objects.filter(employe=employe).order_by('-date_debut')
339
340 c = {
341 'is_popup' : request.GET.get('_popup', False),
342 'employe' : employe,
343 'dossiers' : dossiers,
344 }
345 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
346
347