Rapports trie, WIP et optimisation de requete SQL
[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
25 @login_required
26 def piece(request, filename):
27 """Téléchargement d'une pièce jointe à un poste."""
28 model, id, f = filename.split('/')
29 if model == 'employe':
30 # TODO definir peut-être un controle d'accès
31 piece = get_object_or_404(rh.EmployePiece, fichier=filename)
32 return sendfile(request, piece.fichier.path)
33 if model == 'poste':
34 piece = get_object_or_404(rh.PostePiece, fichier=filename)
35 if rh.Poste.objects.ma_region_ou_service(request.user).filter(id=piece.poste_id).exists():
36 return sendfile(request, piece.fichier.path)
37 else:
38 return redirect_interdiction(request)
39
40 # homes
41 @login_required
42 def profil(request):
43 """Profil personnel de l'employé - éditable"""
44 rc = RequestContext(request)
45 c = {}
46
47 employe = rc['this_employe']
48
49 c['user'] = request.user
50 c['employe'] = employe
51 return render_to_response('rh/profil.html', c, rc)
52
53 # employes
54 @login_required
55 def employes_liste(request):
56 """Liste des employés."""
57 today = date.today()
58 employes = rh.Employe.objects \
59 .filter(actif=True, supprime=False) \
60 .filter(dossiers__actif=True, dossiers__supprime=False) \
61 .exclude(dossiers__date_debut__gt=today) \
62 .exclude(dossiers__date_fin__lt=today) \
63 .order_by('nom')
64 c = {
65 'user':request.user,
66 'employes':employes,
67 }
68 return render_to_response('rh/employes_liste.html', c, RequestContext(request))
69
70 @login_required
71 def employe(request, id):
72 """Information publique sur un employé."""
73 try:
74 employe = rh.Employe.objects.get(pk=id)
75 except:
76 employe = rh.Employe.objects.none()
77 c = {
78 'user':request.user,
79 'employe':employe,
80 }
81 return render_to_response('rh/employe.html', c, RequestContext(request))
82
83
84 # Rapports
85
86 @login_required
87 @drh_or_admin_required
88 def rapports_poste(request):
89
90 lookup_params = dict(request.GET.items())
91
92 comble = 'all'
93
94 for key, value in lookup_params.items():
95 if key == 'o' or key == 'ot':
96 del lookup_params[key]
97 continue
98 if not isinstance(key, str):
99 # 'key' will be used as a keyword argument later, so Python
100 # requires it to be a string.
101 del lookup_params[key]
102 lookup_params[smart_str(key)] = value
103
104 if key == 'comble':
105 comble = value
106 del lookup_params[key]
107
108 #postes = rh.Poste.actifs.select_related('implantation', 'dossier').all()
109 postes = rh.Poste.actifs.select_related('implantation') \
110 .extra(select={'employe_id':'select group_concat(employe) from rh_dossier where poste=rh_poste.id and rh_dossier.actif = 1'}) \
111 .extra(select={'employe_nom':'select group_concat(rh_employe.nom) from rh_dossier inner join rh_employe on rh_dossier.employe = rh_employe.id where poste=rh_poste.id and rh_dossier.actif = 1'}) \
112 .extra(select={'employe_prenom':'select group_concat(rh_employe.prenom) from rh_dossier inner join rh_employe on rh_dossier.employe = rh_employe.id where poste=rh_poste.id and rh_dossier.actif = 1'})
113
114 postes = postes.filter(**lookup_params)
115 if 'o' in request.GET:
116 postes = postes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
117
118 headers = [
119 ("id", u"# du poste"),
120 ("nom", u"Nom du poste"),
121 ("implantation__id", u"Implantation"),
122 ("employe_id", u"# de l'employé"),
123 ("employe_nom", u"Nom"),
124 ("employe_prenom", u"Prénom"),
125 ]
126 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
127 c = {
128 'title': 'Rapport des postes',
129 'postes': postes,
130 'count': len(postes),
131 'headers': list(h.headers()),
132 }
133
134 return render_to_response('rh/rapports/postes.html', c, RequestContext(request))
135
136 @login_required
137 @drh_or_admin_required
138 def rapports_contrat(request):
139
140 lookup_params = dict(request.GET.items())
141 if 'ot' in lookup_params:
142 del lookup_params['ot']
143 if 'o' in lookup_params:
144 del lookup_params['o']
145
146 for key, value in lookup_params.items():
147 if not isinstance(key, str):
148 # 'key' will be used as a keyword argument later, so Python
149 # requires it to be a string.
150 del lookup_params[key]
151 lookup_params[smart_str(key)] = value
152
153 contrats = rh.Contrat.objects.select_related('dossier', 'dossier__poste', 'dossier__poste__implantation', 'type_contrat', 'dossier__employe')
154 contrats = contrats.filter(**lookup_params)
155 if 'o' in request.GET:
156 contrats = contrats.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
157
158 employes = set([c.dossier.employe_id for c in contrats])
159
160 headers = [
161 ("dossier__employe__id", u"# de l'employé"),
162 ("dossier__employe__nom", u"Nom"),
163 ("dossier__employe__prenom", u"Prénom"),
164 ("type_contrat__nom", u"Poste"),
165 ("type_contrat__nom", u"Type de contrat"),
166 ("date_debut", u"Date début"),
167 ("date_fin", u"Date fin"),
168 ]
169 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
170
171 c = {
172 'title': 'Rapport des contrats',
173 'contrats': contrats,
174 'count': len(contrats),
175 'count_employe' : len(employes),
176 'headers': list(h.headers()),
177 }
178
179 return render_to_response('rh/rapports/contrats.html', c, RequestContext(request))
180
181
182 @login_required
183 @drh_or_admin_required
184 def rapports_remuneration(request):
185
186 lookup_params = dict(request.GET.items())
187
188 for key, value in lookup_params.items():
189 if not isinstance(key, str):
190 # 'key' will be used as a keyword argument later, so Python
191 # requires it to be a string.
192 del lookup_params[key]
193 lookup_params[smart_str(key)] = value
194
195 employes = rh.Employe.objects.all()
196 employes = employes.filter(**lookup_params)
197
198 output = []
199
200 for employe in employes:
201 line = {}
202 output.append(line)
203
204 dossiers = employe.rh_dossiers.all()
205
206 remun = {}
207 remun_sum_euro = 0
208
209 for dossier in dossiers:
210 this_remun, this_remun_sum, this_remun_sum_euro = calc_remun(dossier)
211
212 for item in this_remun:
213 if item not in remun:
214 remun[item] = this_remun[item]
215 else:
216 remun[item][0] += this_remun[item][0]
217 remun[item][1] += this_remun[item][1]
218
219 remun_sum_euro += this_remun_sum_euro
220
221 line['remun_sum_euro'] = remun_sum_euro
222
223 for r in remun:
224 if r == u'Indemnité':
225 line['Indemnite'] = remun[r][1]
226 else:
227 line[r] = remun[r][1]
228
229 line['id'] = employe.id
230 line['nom'] = employe.nom
231 line['prenom'] = employe.prenom
232
233
234 c = {
235 'title': 'Rapport de remuneration',
236 'employes': output,
237 }
238
239 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
240
241 def region_protected(model):
242 def wrapper(func):
243 def wrapped(request, id):
244 if request.user.is_superuser:
245 return func(request, id)
246 user_groups = request.user.groups.all()
247 if grp_drh in user_groups:
248 return func(request, id)
249 if grp_correspondants_rh in user_groups:
250 employe = get_employe_from_user(request.user)
251 q = Q(**{model.prefix_implantation: employe.implantation.region})
252 qs = model.objects.filter(q)
253 if int(id) in [o.id for o in qs]:
254 return func(request, id)
255 return redirect_interdiction(request)
256 return wrapped
257 return wrapper
258
259
260 @region_protected(rh.Dossier)
261 def dossier_apercu(request, dossier_id):
262 c = {
263 'is_popup' : request.GET.get('_popup', False),
264 'dossier' : get_object_or_404(rh.Dossier, pk=dossier_id)
265
266 }
267 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
268
269 @region_protected(rh.Poste)
270 def poste_apercu(request, poste_id):
271 c = {
272 'is_popup' : request.GET.get('_popup', False),
273 'poste' : get_object_or_404(rh.Poste, pk=poste_id)
274
275 }
276 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
277
278 def employe_apercu(request, employe_id):
279 from dae.workflow import grp_drh, grp_correspondants_rh
280 employe = get_object_or_404(rh.Employe, pk=employe_id)
281 user_groups = request.user.groups.all()
282
283 dernier_dossier = None
284 dossiers = None
285
286 if request.user.is_superuser or \
287 grp_drh in user_groups:
288 q = Q(employe=employe)
289 if grp_correspondants_rh in user_groups:
290 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
291 q = Q(employe=employe) & Q(implantation__region__in=regions)
292
293 dossiers = rh.Dossier.objects.filter(employe=employe).order_by('-date_debut')
294
295 c = {
296 'is_popup' : request.GET.get('_popup', False),
297 'employe' : employe,
298 'dossiers' : dossiers,
299 }
300 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
301
302