rapports fixes
[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 .exclude(dossiers__date_debut__gt=today) \
72 .exclude(dossiers__date_fin__lt=today) \
73 .order_by('nom')
74 c = {
75 'user':request.user,
76 'employes':employes,
77 }
78 return render_to_response('rh/employes_liste.html', c, RequestContext(request))
79
80 @login_required
81 def employe(request, id):
82 """Information publique sur un employé."""
83 try:
84 employe = rh.Employe.objects.get(pk=id)
85 except:
86 employe = rh.Employe.objects.none()
87 c = {
88 'user':request.user,
89 'employe':employe,
90 }
91 return render_to_response('rh/employe.html', c, RequestContext(request))
92
93
94 # Rapports
95
96 @login_required
97 @drh_or_admin_required
98 def rapports_poste(request):
99
100 lookup_params = dict(request.GET.items())
101
102 comble = 'all'
103
104 for key, value in lookup_params.items():
105 if key == 'o' or key == 'ot':
106 del lookup_params[key]
107 continue
108 if not isinstance(key, str):
109 # 'key' will be used as a keyword argument later, so Python
110 # requires it to be a string.
111 del lookup_params[key]
112 lookup_params[smart_str(key)] = value
113
114 if key == 'comble':
115 comble = value
116 del lookup_params[key]
117
118 postes = rh.Poste.objects.select_related('implantation') \
119 .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' % \
120 ("%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 "") \
121 }) \
122 .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' % \
123 ("%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 "") \
124 }) \
125 .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' % \
126 ("%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 "") \
127 })
128
129 postes = postes.filter(**lookup_params)
130 if 'o' in request.GET:
131 postes = postes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
132
133 out = []
134 for p in postes:
135 out.append({
136 'id': p.id,
137 'nom': p.nom,
138 'implantation': p.implantation,
139 '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('|'))] })
140
141
142 headers = [
143 ("id", u"# du poste"),
144 ("nom", u"Nom du poste"),
145 ("implantation__id", u"Implantation"),
146 ("employe_nom", u"Nom"),
147 ]
148 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
149 c = {
150 'title': 'Rapport des postes',
151 'postes': out,
152 'count': len(out),
153 'headers': list(h.headers()),
154 }
155
156 return render_to_response('rh/rapports/postes.html', c, RequestContext(request))
157
158 @login_required
159 @drh_or_admin_required
160 def rapports_contrat(request):
161
162 lookup_params = dict(request.GET.items())
163 if 'ot' in lookup_params:
164 del lookup_params['ot']
165 if 'o' in lookup_params:
166 del lookup_params['o']
167
168 for key, value in lookup_params.items():
169 if not isinstance(key, str):
170 # 'key' will be used as a keyword argument later, so Python
171 # requires it to be a string.
172 del lookup_params[key]
173 lookup_params[smart_str(key)] = value
174
175 contrats = rh.Contrat.objects.select_related('dossier', 'dossier__poste', 'dossier__poste__implantation', 'type_contrat', 'dossier__employe')
176 contrats = contrats.filter(**lookup_params).exclude(dossier__employe__supprime=1)
177 if 'o' in request.GET:
178 contrats = contrats.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
179
180 employes = set([c.dossier.employe_id for c in contrats])
181
182 headers = [
183 ("dossier__employe__id", u"# de l'employé"),
184 ("dossier__employe__nom", u"Nom"),
185 ("dossier__employe__prenom", u"Prénom"),
186 ("type_contrat__nom", u"Poste"),
187 ("type_contrat__nom", u"Type de contrat"),
188 ("date_debut", u"Date début"),
189 ("date_fin", u"Date fin"),
190 ]
191 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
192
193 c = {
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 def region_protected(model):
284 def wrapper(func):
285 def wrapped(request, id):
286 if request.user.is_superuser:
287 return func(request, id)
288 user_groups = request.user.groups.all()
289 if grp_drh in user_groups:
290 return func(request, id)
291 if grp_correspondants_rh in user_groups:
292 employe = get_employe_from_user(request.user)
293 q = Q(**{model.prefix_implantation: employe.implantation.region})
294 qs = model.objects.filter(q)
295 if int(id) in [o.id for o in qs]:
296 return func(request, id)
297 return redirect_interdiction(request)
298 return wrapped
299 return wrapper
300
301
302 @region_protected(rh.Dossier)
303 def dossier_apercu(request, dossier_id):
304 d = get_object_or_404(rh.Dossier, pk=dossier_id)
305 c = {
306 'is_popup' : request.GET.get('_popup', False),
307 'dossier' : d,
308 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
309 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
310 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
311 'media_url': settings.PRIVE_MEDIA_URL,
312 }
313 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
314
315 @region_protected(rh.Poste)
316 def poste_apercu(request, poste_id):
317 c = {
318 'is_popup' : request.GET.get('_popup', False),
319 'poste' : get_object_or_404(rh.Poste, pk=poste_id),
320 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
321 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
322 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
323 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
324 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
325 'media_url': settings.PRIVE_MEDIA_URL,
326 }
327 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
328
329 def employe_apercu(request, employe_id):
330 from dae.workflow import grp_drh, grp_correspondants_rh
331 employe = get_object_or_404(rh.Employe, pk=employe_id)
332 user_groups = request.user.groups.all()
333
334 dernier_dossier = None
335 dossiers = None
336
337 if request.user.is_superuser or \
338 grp_drh in user_groups:
339 q = Q(employe=employe)
340 if grp_correspondants_rh in user_groups:
341 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
342 q = Q(employe=employe) & Q(implantation__region__in=regions)
343
344 dossiers = rh.Dossier.objects.filter(employe=employe).order_by('-date_debut')
345
346 c = {
347 'is_popup' : request.GET.get('_popup', False),
348 'employe' : employe,
349 'dossiers' : dossiers,
350 'media_url': settings.PRIVE_MEDIA_URL,
351 }
352 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
353
354