Fix django ajax selects
[auf_rh_dae.git] / project / rh / views.py
CommitLineData
e9bbd6ba 1# -*- encoding: utf-8 -*-
22343fe7 2
e90b19fd 3import urllib
c9122f1d 4from datetime import date
a7de62d7 5from itertools import izip
eabb27fd 6import StringIO
9b0a8554 7
9f55f18a 8import pygraphviz as pgv
e949324b 9
e90b19fd 10from django import forms
4ba84959 11from django.conf import settings
e90b19fd 12from django.contrib.auth.decorators import login_required
eabb27fd 13from django.core.servers.basehttp import FileWrapper
dcd1b959 14from django.core.urlresolvers import reverse
fbe60a9d 15from django.db.models import Q
4ba84959 16from django.http import HttpResponse
890b80e7 17from django.shortcuts import render, get_object_or_404
e9bbd6ba 18
4c17e518 19from auf.django.references import models as ref
e9bbd6ba 20
acbc95a1 21from project.decorators import redirect_interdiction
018c8eaf 22from project.decorators import drh_or_admin_required
ae99002a 23from project.decorators import region_protected
afd3be54 24from project.groups import get_employe_from_user
a4198848 25from project.groups import grp_drh, grp_correspondants_rh
e9bbd6ba 26
4ba84959 27from project.rh import models as rh
4ba84959 28from project.rh import graph as rh_graph
890b80e7 29from project.rh.change_list import RechercheTemporelle
2cb9e555 30from project.rh.lib import calc_remun, get_lookup_params
4ba84959 31from project.rh.masse_salariale import MasseSalariale
890b80e7 32from project.rh.templatetags.rapports import SortHeaders
9817fed5 33
22343fe7 34
c9122f1d 35@login_required
36def profil(request):
37 """Profil personnel de l'employé - éditable"""
7d0c2206
DB
38 employe = get_employe_from_user(user)
39 c = {
8b3f6ff5
DB
40 'user': request.user,
41 'employe': employe,
7d0c2206 42 }
890b80e7 43 return render(request, 'rh/profil.html', c)
22343fe7
OL
44
45
3411ac33 46@login_required
a9faef67 47def employes_liste(request):
48 """Liste des employés."""
5ea6b5bb 49 today = date.today()
50 employes = rh.Employe.objects \
5ea6b5bb 51 .exclude(dossiers__date_debut__gt=today) \
52 .exclude(dossiers__date_fin__lt=today) \
53 .order_by('nom')
a9faef67 54 c = {
22343fe7
OL
55 'user': request.user,
56 'employes': employes,
a9faef67 57 }
890b80e7 58 return render(request, 'rh/employes_liste.html', c)
22343fe7
OL
59
60
3411ac33 61@login_required
a9faef67 62def employe(request, id):
63 """Information publique sur un employé."""
64 try:
65 employe = rh.Employe.objects.get(pk=id)
66 except:
67 employe = rh.Employe.objects.none()
68 c = {
22343fe7
OL
69 'user': request.user,
70 'employe': employe,
a9faef67 71 }
890b80e7 72 return render(request, 'rh/employe.html', c)
63e17dff
PP
73
74
08faf06e
JPC
75@login_required
76@drh_or_admin_required
f2d65e83 77def rapports_contrat(request):
dd18f6e3 78 # statut default = actif?
dcd1b959 79 if 'HTTP_REFERER' in request.META.keys():
58348377
EMS
80 referer = request.META['HTTP_REFERER']
81 referer = "/".join(referer.split('/')[3:])
82 referer = "/%s" % referer.split('?')[0]
83 if referer != reverse('rhr_contrats'):
84 params = request.GET.copy()
85 params.update({'statut': 'Actif'})
86 request.GET = params
f2d65e83 87
00ca4d9f
EMS
88 contrats = rh.Contrat.objects.select_related(
89 'dossier', 'dossier__poste', 'dossier__poste__implantation',
90 'type_contrat', 'dossier__employe'
91 )
22343fe7 92
dd18f6e3 93 # filters et recherche temporelle
6bee05ff 94 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
dd18f6e3 95 lookup_params = get_lookup_params(request)
f0f6b03e 96 lookup_params = cl.purge_params(lookup_params)
dcd1b959
OL
97 q_temporel = cl.get_q_temporel(contrats)
98 q = Q(**lookup_params) & q_temporel
99 contrats = contrats.filter(q).exclude(dossier__employe__supprime=1)
f0f6b03e 100
dd18f6e3 101 # tri
65e02621 102 if 'o' in request.GET:
00ca4d9f
EMS
103 contrats = contrats.order_by(
104 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
105 )
f2d65e83 106
dd18f6e3 107 # affichage
8ee135b7
JPC
108 employes = set([c.dossier.employe_id for c in contrats])
109
65e02621 110 headers = [
dd18f6e3 111 ("dossier__employe__id", u"#"),
d50a5e5d 112 ("dossier__employe__nom", u"Employé"),
dd18f6e3
DB
113 ("dossier", u"Dossier : Poste"),
114 ("type_contrat__nom", u"Contrat"),
115 ("date_debut", u"Début contrat"),
116 ("date_fin", u"Fin contrat"),
117 ("dossier__statut_residence", u"Statut"),
d50a5e5d
OL
118 ("dossier__poste__implantation__region", u"Région"),
119 ("dossier__poste__implantation", u"Implantation"),
65e02621 120 ]
dd18f6e3
DB
121 h = SortHeaders(
122 request, headers, order_field_type="ot", order_field="o",
123 not_sortable=('dossier',)
124 )
65e02621 125
f2d65e83 126 c = {
00ca4d9f 127 'cl': cl,
f2d65e83
PP
128 'title': 'Rapport des contrats',
129 'contrats': contrats,
00ca4d9f 130 'count_employe': len(employes),
65e02621 131 'headers': list(h.headers()),
f2d65e83 132 }
890b80e7 133 return render(request, 'rh/rapports/contrats.html', c)
e2c0b1ac
PP
134
135
02c1b3dc
JPC
136@login_required
137@drh_or_admin_required
98d6eb6c 138def rapports_masse_salariale(request):
df37184c 139
e90b19fd 140 class RechercheTemporelle(forms.Form):
aecb222b 141 CHOICE_ANNEES = range(
00ca4d9f
EMS
142 rh.Remuneration.objects.exclude(date_debut=None)
143 .order_by('date_debut')[0].date_debut.year,
144 date.today().year + 1
145 )
146
147 annee = forms.CharField(
148 initial=date.today().year,
149 widget=forms.Select(
150 choices=((a, a) for a in reversed(CHOICE_ANNEES))
151 )
444f3223 152 )
aecb222b 153
48c0abfe
JPC
154 region = forms.CharField(
155 widget=forms.Select(choices=[('', '')] +
156 [(i.id, i) for i in ref.Region.objects.all()]
157 )
158 )
159
160 implantation = forms.CharField(
161 widget=forms.Select(choices=[('', '')] +
162 [(i.id, i) for i in ref.Implantation.objects.all()]
163 )
164 )
165
aecb222b
JPC
166 #date_debut = forms.DateField(widget=adminwidgets.AdminDateWidget)
167 #date_fin = forms.DateField(widget=adminwidgets.AdminDateWidget)
e90b19fd 168
e90b19fd 169 form = RechercheTemporelle(request.GET)
00ca4d9f
EMS
170 get_filtre = [
171 (k, v) for k, v in request.GET.items()
172 if k not in ('date_debut', 'date_fin', 'implantation')
173 ]
e90b19fd
OL
174 query_string = urllib.urlencode(get_filtre)
175
aecb222b
JPC
176 date_debut = None
177 date_fin = None
444f3223
JPC
178 if request.GET.get('annee', None):
179 date_debut = "01-01-%s" % request.GET.get('annee', None)
180 date_fin = "31-12-%s" % request.GET.get('annee', None)
df37184c 181
48c0abfe
JPC
182 implantation = request.GET.get('implantation')
183 region = request.GET.get('region')
df37184c
JPC
184
185 custom_filter = {}
186 if implantation:
187 custom_filter['dossier__poste__implantation'] = implantation
188 if region:
189 custom_filter['dossier__poste__implantation__region'] = region
190
df37184c 191 c = {
e90b19fd
OL
192 'title': 'Rapport de masse salariale',
193 'form': form,
df37184c 194 'headers': [],
e90b19fd 195 'query_string': query_string,
df37184c 196 }
22b53270 197 if date_debut or date_fin:
c99116c3
JPC
198 masse = MasseSalariale(date_debut, date_fin, custom_filter,
199 request.GET.get('ne_pas_grouper', False))
515b83c3 200 if masse.rapport:
eabb27fd 201 if request.GET.get('ods'):
00ca4d9f
EMS
202 for h in (
203 h for h in masse.headers if 'background-color' in h[2]
204 ):
eabb27fd
JPC
205 del h[2]['background-color']
206 masse.ods()
207 output = StringIO.StringIO()
208 masse.doc.save(output)
209 output.seek(0)
210
00ca4d9f
EMS
211 response = HttpResponse(
212 FileWrapper(output),
213 content_type=(
214 'application/vnd.oasis.opendocument.spreadsheet'
215 )
216 )
eabb27fd
JPC
217 response['Content-Disposition'] = \
218 'attachment; filename=Masse Salariale %s.ods' % \
219 masse.annee
220 return response
221 else:
222 c['rapport'] = masse.rapport
223 c['header_keys'] = [h[0] for h in masse.headers]
224 #on enleve le background pour le header
00ca4d9f
EMS
225 for h in (
226 h for h in masse.headers if 'background-color' in h[2]
227 ):
eabb27fd
JPC
228 h[2]['background'] = 'none'
229 h = SortHeaders(request, masse.headers, order_field_type="ot",
230 not_sortable=c['header_keys'], order_field="o")
231 c['headers'] = list(h.headers())
232 for key, nom, opts in masse.headers:
233 c['headers']
234 c['total'] = masse.grand_totaux[0]
235 c['total_euro'] = masse.grand_totaux[1]
236 c['colspan'] = len(c['header_keys']) - 1
237 get_filtre.append(('ods', True))
238 query_string = urllib.urlencode(get_filtre)
239 c['url_ods'] = "%s?%s" % (
240 reverse('rhr_masse_salariale'), query_string)
22b53270 241
890b80e7 242 return render(request, 'rh/rapports/masse_salariale.html', c)
98d6eb6c
JPC
243
244
245@login_required
246@drh_or_admin_required
6b7cf654 247def rapports_employes_sans_contrat(request):
1a7b9e36 248 lookup_params = get_lookup_params(request)
c8b22fd1 249
1a7b9e36
DB
250 # contrats échus
251 contrats_echus = rh.Contrat.objects.filter(
252 date_fin__lt=date.today()
253 ).filter(
254 **lookup_params
255 )
256
257 # dossiers en cours sans contrat
258 dossiers_sans_contrat = rh.Dossier.objects.filter(
259 Q(date_fin=None) | Q(date_fin__gt=date.today()),
260 ).exclude(
261 date_debut__gt=date.today()
262 ).filter(
263 rh_contrats__in=contrats_echus
264 )
265
266 # employés sans contrat
dd18f6e3
DB
267 employes = rh.Employe.objects.filter(
268 rh_dossiers__in=dossiers_sans_contrat
269 ).distinct()
c8b22fd1 270 if 'o' in request.GET:
1a7b9e36 271 employes = employes.order_by(
00ca4d9f
EMS
272 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
273 )
c8b22fd1 274
6b7cf654 275 # affichage
c8b22fd1 276 headers = [
dd18f6e3 277 ("id", u"#"),
1a7b9e36
DB
278 ("nom", u"Employé"),
279 ("dossier", u"Dossier : Poste"),
dd18f6e3
DB
280 ("dossier_date_debut", u"Début dossier"),
281 ("dossier_date_fin", u"Fin dossier"),
c8b22fd1 282 ]
00ca4d9f
EMS
283 h = SortHeaders(
284 request, headers, order_field_type="ot", order_field="o",
1a7b9e36 285 not_sortable=('dossier','dossier_date_debut','dossier_date_fin',)
00ca4d9f 286 )
c8b22fd1
JPC
287
288 c = {
289 'title': u'Rapport des employés sans contrat',
290 'employes': employes,
1a7b9e36 291 'dossiers_sans_contrat':dossiers_sans_contrat,
c8b22fd1
JPC
292 'headers': list(h.headers()),
293 }
294
890b80e7 295 return render(request, 'rh/rapports/employes_sans_contrat.html', c)
00ca4d9f 296
c8b22fd1
JPC
297
298@login_required
299@drh_or_admin_required
857b5c24
JPC
300def rapports_postes_modelisation(request):
301 c = {}
302 data = []
3c1ba807 303
7bf28694
EMS
304 for categorie in rh.CategorieEmploi.objects.all():
305 types = rh.TypePoste.objects.filter(categorie_emploi=categorie)
3c1ba807
JPC
306 data_types = []
307 for t in types.all():
308 postes = rh.Poste.objects.filter(type_poste=t)
309 data_types.append({
310 'num_postes': postes.count(),
311 'postes': postes.all(),
7bf28694 312 'type': categorie,
857b5c24 313 })
3c1ba807 314
857b5c24 315 data.append({
7bf28694 316 'categorie': categorie,
3c1ba807 317 'nb_types': types.count(),
00ca4d9f
EMS
318 'types': data_types
319 })
857b5c24
JPC
320
321 c['data'] = data
322
890b80e7 323 return render(request, 'rh/rapports/postes_modelisation.html', c)
857b5c24
JPC
324
325
326@login_required
327@drh_or_admin_required
783e077a
JPC
328def rapports_postes_implantation(request):
329 c = {}
330 data = []
331 for r in ref.Region.objects.all():
332 implantations = []
333 for i in ref.Implantation.objects.filter(region=r):
334 implantations.append({
335 'implantation': i,
336 'postes': rh.Poste.objects.filter(implantation=i),
337 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
338 })
339 data.append({
340 'region': r,
341 'implantations': implantations
342 })
343
344 c['data'] = data
345
890b80e7 346 return render(request, 'rh/rapports/postes_implantation.html', c)
783e077a
JPC
347
348
349@login_required
350@drh_or_admin_required
351def rapports_postes_service(request):
352 c = {}
9988aafb
JPC
353 data = []
354 for s in rh.Service.objects.all():
355 postes = rh.Poste.objects.filter(service=s).all()
356 num_postes = rh.Poste.objects.filter(service=s).count()
22343fe7 357 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
783e077a 358
9988aafb 359 c['data'] = data
890b80e7 360 return render(request, 'rh/rapports/postes_service.html', c)
32373f2e
OL
361
362@region_protected(rh.Dossier)
3ebc0952 363def dossier_apercu(request, dossier_id):
baf9b78c 364 d = get_object_or_404(rh.Dossier, pk=dossier_id)
3ebc0952 365 c = {
838bc59d 366 'title': u"Dossier %s" % (d, ),
00ca4d9f
EMS
367 'is_popup': request.GET.get('_popup', False),
368 'dossier': d,
369 'pieces': rh.DossierPiece.objects.filter(dossier__exact=d),
370 'contrats': rh.Contrat.objects.filter(dossier__exact=d),
371 'commentaires': rh.DossierCommentaire.objects.filter(dossier=d).all(),
abf91905 372 'media_url': settings.PRIVE_MEDIA_URL,
3ebc0952 373 }
890b80e7 374 return render(request, 'admin/rh/dossier/apercu.html', c)
00ca4d9f 375
4a1f2ece 376
fbe60a9d
OL
377@region_protected(rh.Poste)
378def poste_apercu(request, poste_id):
c8cb18e3 379 p = get_object_or_404(rh.Poste, pk=poste_id)
fbe60a9d 380 c = {
c8cb18e3 381 'title': u"Poste %s" % (p, ),
00ca4d9f
EMS
382 'is_popup': request.GET.get('_popup', False),
383 'poste': p,
384 'financements': (
385 rh.PosteFinancement.objects.filter(poste=poste_id).all()
386 ),
387 'pieces': rh.PostePiece.objects.filter(poste=poste_id).all(),
388 'dossiers': (
389 rh.Dossier.objects.filter(poste=poste_id)
390 .order_by("-date_debut").all()
391 ),
392 'comparaisons': (
393 rh.PosteComparaison.objects.filter(poste=poste_id).all()
394 ),
395 'commentaires': (
396 rh.PosteCommentaire.objects.filter(poste=poste_id).all()
397 ),
abf91905 398 'media_url': settings.PRIVE_MEDIA_URL,
fbe60a9d 399 }
890b80e7 400 return render(request, 'admin/rh/poste/apercu.html', c)
00ca4d9f 401
fbe60a9d 402
4a1f2ece
OL
403def employe_apercu(request, employe_id):
404 employe = get_object_or_404(rh.Employe, pk=employe_id)
fbe60a9d 405 user_groups = request.user.groups.all()
fbe60a9d
OL
406 dossiers = None
407
408 if request.user.is_superuser or \
409 grp_drh in user_groups:
410 q = Q(employe=employe)
411 if grp_correspondants_rh in user_groups:
00ca4d9f
EMS
412 regions = [
413 d.poste.implantation.region for d in employe.rh_dossiers.all()
414 ]
fbe60a9d 415 q = Q(employe=employe) & Q(implantation__region__in=regions)
22343fe7
OL
416
417 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
418
4a1f2ece 419 c = {
ce740bb5 420 'title': u"Employe %s" % (employe, ),
00ca4d9f
EMS
421 'is_popup': request.GET.get('_popup', False),
422 'employe': employe,
423 'dossiers': dossiers,
abf91905 424 'media_url': settings.PRIVE_MEDIA_URL,
4a1f2ece 425 }
890b80e7 426 return render(request, 'admin/rh/employe/apercu.html', c)
00ca4d9f 427
150d83ec 428
77bd83d1
JPC
429@login_required
430@drh_or_admin_required
56264a85 431def organigrammes_employe(request, id, level="all"):
08faf06e
JPC
432
433 poste = get_object_or_404(rh.Poste, pk=id)
00ca4d9f
EMS
434 dossiers_by_poste = dict(
435 (d.poste_id, d)
436 for d in rh.Dossier.objects.select_related('employe', 'poste').all()
437 )
5c0f1778
JPC
438 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
439
440 e = dossiers_by_poste[poste.id].employe
441 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
58014aec 442 graph = pgv.AGraph()
5c0f1778 443
f187a10f 444 if rh.Poste.objects.filter(responsable=poste).count() > 0:
58014aec
JPC
445 postes_handle = [poste]
446 while postes_handle:
00ca4d9f
EMS
447 postes_handle = rh.Poste.objects.select_related('implantation') \
448 .filter(
449 Q(date_fin__gt=date.today()) | Q(date_fin=None),
450 Q(date_debut__lt=date.today()) | Q(date_debut=None),
451 responsable__in=postes_handle
452 ).exclude(supprime=True).exclude(responsable=None).all()
32373f2e 453
58014aec
JPC
454 for p in postes_handle:
455 if p.responsable_id != p.id:
00ca4d9f
EMS
456 graph.add_edge(
457 dossiers_by_poste[p.responsable_id].poste_id, p.id
458 )
13ad5ad5 459
f187a10f 460 else:
5c0f1778
JPC
461 graph.add_node(poste.id)
462
4afec2e1
JPC
463 if level != "all":
464 postes_niveau = [poste.id]
465 for niveau in range(int(level)):
00ca4d9f
EMS
466 postes_niveau = [
467 p.id for p in
468 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
469 ]
4afec2e1
JPC
470
471 while postes_niveau:
00ca4d9f
EMS
472 postes_niveau = [
473 p.id for p in
474 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
475 ]
4afec2e1
JPC
476 if postes_niveau:
477 for p in postes_niveau:
478 if graph.has_node(p):
4cc81304 479 graph.delete_node(p)
4afec2e1 480
58014aec 481 a = graph
4afec2e1 482 a.name = name.encode('ascii', 'xmlcharrefreplace')
5c0f1778
JPC
483
484 poste_remontant = poste
485 while poste_remontant.responsable_id:
486 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
487 poste_remontant = poste_remontant.responsable
488
489 rh_graph.bind_poste_to_graph(a, postes_by_id)
490 #a.graph_attr['normalize'] = True
491 #a.graph_attr['level'] = 2
492 a.layout(prog='dot')
493
494 svg = a.draw(format='svg')
495
496 c = {
497 'svg': svg
498 }
a251ac8d
JPC
499
500 if 'forcer' in request.GET:
890b80e7 501 response = HttpResponse(svg, content_type='image/svg+xml')
00ca4d9f
EMS
502 response['Content-Disposition'] = \
503 'attachment; filename=organigramme.svg'
a251ac8d
JPC
504 return response
505
890b80e7
DB
506 return render(request, 'rh/organigrammes/employe.html', c,
507 content_type="image/svg+xml"
00ca4d9f 508 )
5c0f1778
JPC
509
510
511@login_required
512@drh_or_admin_required
513def organigrammes_service(request, id):
514
515 service = get_object_or_404(rh.Service, pk=id)
82af5c19
JPC
516 svg = rh_graph.organigramme_postes_cluster( \
517 cluster_filter={"service": service}, \
518 titre=u"Organigramme du service %s" % service.nom,
519 cluster_titre=service.nom)
5c0f1778 520
82af5c19
JPC
521 c = {
522 'svg': svg
523 }
5c0f1778 524
890b80e7
DB
525 return render(request, 'rh/organigrammes/vide.html', c,
526 content_type="image/svg+xml"
00ca4d9f
EMS
527 )
528
5c0f1778 529
82af5c19
JPC
530@login_required
531@drh_or_admin_required
532def organigrammes_implantation(request, id):
5c0f1778 533
82af5c19
JPC
534 implantation = get_object_or_404(ref.Implantation, pk=id)
535 svg = rh_graph.organigramme_postes_cluster( \
536 cluster_filter={"implantation": implantation}, \
537 titre=u"Organigramme de l'implantation %s" % implantation.nom,
538 cluster_titre=implantation.nom)
5c0f1778
JPC
539
540 c = {
541 'svg': svg
542 }
543
890b80e7
DB
544 return render(request, 'rh/organigrammes/vide.html', c,
545 content_type="image/svg+xml"
00ca4d9f
EMS
546 )
547
5c0f1778 548
9da4c195
JPC
549@login_required
550@drh_or_admin_required
551def organigrammes_region(request, id):
552
553 region = get_object_or_404(ref.Region, pk=id)
554 svg = rh_graph.organigramme_postes_cluster( \
555 cluster_filter={"implantation__region": region}, \
556 titre=u"Organigramme du bureau de %s" % region.nom,
557 cluster_titre=region.nom)
558
559 c = {
560 'svg': svg
561 }
562
890b80e7
DB
563 return render(request,
564 'rh/organigrammes/vide.html', c,
565 content_type="image/svg+xml"
00ca4d9f 566 )