merge regionalisation
[auf_rh_dae.git] / project / rh / views.py
CommitLineData
e9bbd6ba 1# -*- encoding: utf-8 -*-
22343fe7 2
fc62be5d 3from collections import defaultdict
c9122f1d 4from datetime import date
fc62be5d 5from decimal import Decimal
9b0a8554 6
9f55f18a 7import pygraphviz as pgv
edbc9e37 8from reversion.models import Revision
f80b83c6 9
d104b0ae 10from auf.django.references import models as ref
4ba84959 11from django.conf import settings
e90b19fd 12from django.contrib.auth.decorators import login_required
dcd1b959 13from django.core.urlresolvers import reverse
fbe60a9d 14from django.db.models import Q
4ba84959 15from django.http import HttpResponse
edbc9e37 16from django.shortcuts import render, get_object_or_404, redirect
8e26a99b 17
018c8eaf 18from project.decorators import drh_or_admin_required
ae99002a 19from project.decorators import region_protected
afd3be54 20from project.groups import get_employe_from_user
c3550a05
OL
21from project import groups
22from project.decorators import in_one_of_group, in_drh_or_admin
e9bbd6ba 23
fc62be5d 24from project.rh import ods
4ba84959 25from project.rh import graph as rh_graph
fc62be5d 26from project.rh import models as rh
890b80e7 27from project.rh.change_list import RechercheTemporelle
fc62be5d 28from project.rh.forms import MasseSalarialeForm
d104b0ae 29from project.rh.lib import get_lookup_params
890b80e7 30from project.rh.templatetags.rapports import SortHeaders
edbc9e37 31from project.rh.historique import get_active_revisions, TodoForm
9817fed5 32
fc62be5d
EMS
33TWOPLACES = Decimal('0.01')
34
22343fe7 35
c9122f1d 36@login_required
d9a82745 37@drh_or_admin_required
c9122f1d 38def profil(request):
39 """Profil personnel de l'employé - éditable"""
d104b0ae 40 employe = get_employe_from_user(request.user)
7d0c2206 41 c = {
8b3f6ff5
DB
42 'user': request.user,
43 'employe': employe,
7d0c2206 44 }
890b80e7 45 return render(request, 'rh/profil.html', c)
22343fe7
OL
46
47
3411ac33 48@login_required
d9a82745 49@drh_or_admin_required
a9faef67 50def employes_liste(request):
51 """Liste des employés."""
5ea6b5bb 52 today = date.today()
53 employes = rh.Employe.objects \
5ea6b5bb 54 .exclude(dossiers__date_debut__gt=today) \
55 .exclude(dossiers__date_fin__lt=today) \
56 .order_by('nom')
a9faef67 57 c = {
22343fe7
OL
58 'user': request.user,
59 'employes': employes,
a9faef67 60 }
890b80e7 61 return render(request, 'rh/employes_liste.html', c)
22343fe7
OL
62
63
3411ac33 64@login_required
d9a82745 65@drh_or_admin_required
a9faef67 66def employe(request, id):
67 """Information publique sur un employé."""
68 try:
69 employe = rh.Employe.objects.get(pk=id)
70 except:
71 employe = rh.Employe.objects.none()
72 c = {
22343fe7
OL
73 'user': request.user,
74 'employe': employe,
a9faef67 75 }
890b80e7 76 return render(request, 'rh/employe.html', c)
63e17dff
PP
77
78
08faf06e 79@login_required
f96ec25c
OL
80@in_one_of_group((groups.grp_correspondants_rh,
81 groups.grp_administrateurs,
82 groups.grp_directeurs_bureau,
83 groups.grp_drh,
84 groups.grp_drh2))
f2d65e83 85def rapports_contrat(request):
dd18f6e3 86 # statut default = actif?
dcd1b959 87 if 'HTTP_REFERER' in request.META.keys():
58348377
EMS
88 referer = request.META['HTTP_REFERER']
89 referer = "/".join(referer.split('/')[3:])
90 referer = "/%s" % referer.split('?')[0]
91 if referer != reverse('rhr_contrats'):
92 params = request.GET.copy()
93 params.update({'statut': 'Actif'})
94 request.GET = params
f2d65e83 95
00ca4d9f
EMS
96 contrats = rh.Contrat.objects.select_related(
97 'dossier', 'dossier__poste', 'dossier__poste__implantation',
98 'type_contrat', 'dossier__employe'
99 )
22343fe7 100
dd18f6e3 101 # filters et recherche temporelle
6bee05ff 102 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
dd18f6e3 103 lookup_params = get_lookup_params(request)
f0f6b03e 104 lookup_params = cl.purge_params(lookup_params)
dcd1b959
OL
105 q_temporel = cl.get_q_temporel(contrats)
106 q = Q(**lookup_params) & q_temporel
45066657 107 contrats = contrats.filter(q)
f96ec25c
OL
108 user_groups = request.user.groups.all()
109 if groups.grp_correspondants_rh in user_groups or\
110 groups.grp_administrateurs in user_groups or\
111 groups.grp_directeurs_bureau in user_groups:
112 employe = get_employe_from_user(request.user)
113 q = q & Q(dossier__poste__implantation__region=employe.implantation.region)
114
c3550a05 115 contrats = contrats.filter(q)
f0f6b03e 116
dd18f6e3 117 # tri
65e02621 118 if 'o' in request.GET:
00ca4d9f
EMS
119 contrats = contrats.order_by(
120 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
121 )
f2d65e83 122
dd18f6e3 123 # affichage
8ee135b7 124 employes = set([c.dossier.employe_id for c in contrats])
65e02621 125 headers = [
dd18f6e3 126 ("dossier__employe__id", u"#"),
d50a5e5d 127 ("dossier__employe__nom", u"Employé"),
dd18f6e3
DB
128 ("dossier", u"Dossier : Poste"),
129 ("type_contrat__nom", u"Contrat"),
130 ("date_debut", u"Début contrat"),
131 ("date_fin", u"Fin contrat"),
132 ("dossier__statut_residence", u"Statut"),
d50a5e5d
OL
133 ("dossier__poste__implantation__region", u"Région"),
134 ("dossier__poste__implantation", u"Implantation"),
65e02621 135 ]
dd18f6e3
DB
136 h = SortHeaders(
137 request, headers, order_field_type="ot", order_field="o",
138 not_sortable=('dossier',)
139 )
65e02621 140
f2d65e83 141 c = {
00ca4d9f 142 'cl': cl,
f2d65e83
PP
143 'title': 'Rapport des contrats',
144 'contrats': contrats,
00ca4d9f 145 'count_employe': len(employes),
65e02621 146 'headers': list(h.headers()),
f2d65e83 147 }
890b80e7 148 return render(request, 'rh/rapports/contrats.html', c)
e2c0b1ac
PP
149
150
02c1b3dc 151@login_required
35069664
OL
152@in_one_of_group((groups.grp_correspondants_rh,
153 groups.grp_administrateurs,
154 groups.grp_directeurs_bureau,
155 groups.grp_drh,
156 groups.grp_drh2))
6b7cf654 157def rapports_employes_sans_contrat(request):
5db1c5a3
DB
158 """
159 Employé sans contrat = a un Dossier qui n'a pas de Contrat associé
160 Employé avec contrat échu = a un Dossier avec un Contrat se terminant hier
161 au plus tard... (aujourd'hui = ok, pas date de fin = illimité donc ok)
162 """
1a7b9e36 163 lookup_params = get_lookup_params(request)
c8b22fd1 164
82c5e37d 165 # régionalisation
219ae355
OL
166 user_groups = request.user.groups.all()
167 q_region = Q()
168 if groups.grp_correspondants_rh in user_groups or\
169 groups.grp_administrateurs in user_groups or\
170 groups.grp_directeurs_bureau in user_groups:
171 employe = get_employe_from_user(request.user)
172 q_region = Q(poste__implantation__region=employe.implantation.region)
173
1a7b9e36
DB
174 # contrats échus
175 contrats_echus = rh.Contrat.objects.filter(
176 date_fin__lt=date.today()
177 ).filter(
178 **lookup_params
179 )
180
181 # dossiers en cours sans contrat
c3550a05 182 dossiers = rh.Dossier.objects.filter(q_region & (
82c5e37d 183 Q(date_fin=None) | Q(date_fin__gt=date.today())),
1a7b9e36
DB
184 ).exclude(
185 date_debut__gt=date.today()
186 ).filter(
5db1c5a3
DB
187 # sans contrat | contrat échu
188 Q(rh_contrats=None) | Q(rh_contrats__in=contrats_echus)
dd18f6e3 189 ).distinct()
a623d1b2 190
5db1c5a3
DB
191 # employés sans contrat ou contrats échus
192 employes = rh.Employe.objects.filter(rh_dossiers__in=dossiers) \
193 .distinct().count()
a623d1b2 194
5db1c5a3 195 # tri
c8b22fd1 196 if 'o' in request.GET:
5db1c5a3 197 dossiers = dossiers.order_by(
00ca4d9f
EMS
198 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
199 )
c8b22fd1 200
6b7cf654 201 # affichage
c8b22fd1 202 headers = [
5db1c5a3
DB
203 ("employe__id", u"#"),
204 ("employe__nom", u"Employé"),
1a7b9e36 205 ("dossier", u"Dossier : Poste"),
5db1c5a3
DB
206 ("rh_contrats__type_contrat", u"Contrat"),
207 ("rh_contrats__date_debut", u"Début contrat"),
208 ("rh_contrats__date_fin", u"Fin contrat"),
209 ("statut_residence", u"Statut"),
210 ("poste__implantation__region__code", u"Région"),
211 ("poste__implantation__nom", u"Implantation"),
c8b22fd1 212 ]
00ca4d9f
EMS
213 h = SortHeaders(
214 request, headers, order_field_type="ot", order_field="o",
5db1c5a3 215 not_sortable=('dossier',)
00ca4d9f 216 )
c8b22fd1
JPC
217
218 c = {
5db1c5a3 219 'title': u'Rapport des employés sans contrat ou contrat échu',
c8b22fd1 220 'employes': employes,
5db1c5a3 221 'dossiers': dossiers,
c8b22fd1
JPC
222 'headers': list(h.headers()),
223 }
224
890b80e7 225 return render(request, 'rh/rapports/employes_sans_contrat.html', c)
00ca4d9f 226
c8b22fd1
JPC
227
228@login_required
c3550a05
OL
229@in_one_of_group((groups.grp_correspondants_rh,
230 groups.grp_administrateurs,
231 groups.grp_directeurs_bureau,
232 groups.grp_drh,
233 groups.grp_drh2))
98d6eb6c 234def rapports_masse_salariale(request):
fc62be5d
EMS
235 form = MasseSalarialeForm(request.user, request.GET)
236 if 'annee' in request.GET and form.is_valid():
237 region = form.cleaned_data['region']
238 implantation = form.cleaned_data['implantation']
239 annee = form.cleaned_data['annee']
240 debut_annee = date(annee, 1, 1)
241 fin_annee = date(annee, 12, 31)
242 jours_annee = (fin_annee - debut_annee).days + 1
243 today = date.today()
244
245 # Récupérer les dossiers actifs
246 dossiers = rh.Dossier.objects \
247 .actifs(annee=annee) \
248 .select_related(
249 'poste', 'poste__implantation',
250 'poste__implantation__region',
251 'poste__implantation__adresse_physique_pays',
252 'employe', 'poste__type_poste', 'classement',
253 'statut', 'organisme_bstg'
254 ) \
255 .extra(
fc62be5d 256 select={
471fd30f
EMS
257 'valeur_point': (
258 'SELECT valeur FROM rh_valeurpoint '
259 'WHERE annee = %d '
260 'AND implantation = ref_implantation.id' % annee
261 ),
262 'valeur_point_devise': (
263 'SELECT d.code '
264 'FROM rh_valeurpoint vp '
265 'INNER JOIN rh_devise d ON d.id = vp.devise '
266 'WHERE annee = %d '
267 'AND implantation = ref_implantation.id' % annee
268 )
fc62be5d 269 }
48c0abfe 270 )
fc62be5d
EMS
271 if region:
272 dossiers = dossiers.filter(poste__implantation__region=region)
273 if implantation:
274 dossiers = dossiers.filter(poste__implantation=implantation)
275
276 # Récupérer les rémunérations actives
277 remuns = rh.Remuneration.objects \
278 .actifs(annee=annee) \
279 .select_related('devise', 'type') \
280 .extra(
281 tables=['rh_tauxchange'],
282 where=[
283 'rh_tauxchange.annee = %s',
284 'rh_tauxchange.devise = rh_devise.id'
285 ],
286 params=[annee],
287 select={
288 'taux_change': 'rh_tauxchange.taux'
289 }
290 )
471fd30f
EMS
291 if region:
292 remuns = remuns.filter(dossier__poste__implantation__region=region)
293 if implantation:
294 remuns = remuns.filter(dossier__poste__implantation=implantation)
fc62be5d 295 remuns_par_dossier = defaultdict(list)
471fd30f 296 types_remun = set()
fc62be5d 297 for remun in remuns:
471fd30f 298 types_remun.add(remun.type_id)
fc62be5d
EMS
299 remuns_par_dossier[remun.dossier_id].append(remun)
300
301 # Récupérer les types de rémunération par nature
302 types_remun_par_nature = defaultdict(list)
303 for type in rh.TypeRemuneration.objects.all():
471fd30f
EMS
304 if type.id in types_remun:
305 types_remun_par_nature[type.nature_remuneration].append(type)
fc62be5d
EMS
306 titres_traitements = [
307 t.nom for t in types_remun_par_nature[u'Traitement']
308 ]
309 titres_indemnites = [
310 t.nom for t in types_remun_par_nature[u'Indemnité']
311 ]
312 titres_primes = [
313 t.nom for t in types_remun_par_nature[u'Accessoire']
314 ]
315 titres_charges = [
316 t.nom for t in types_remun_par_nature[u'Charges']
317 ]
df37184c 318
fc62be5d
EMS
319 # Boucler sur les dossiers et préprarer les lignes du rapport
320 lignes = []
321 masse_salariale_totale = 0
322 for dossier in dossiers:
323 debut_cette_annee = \
324 max(dossier.date_debut or debut_annee, debut_annee)
325 fin_cette_annee = \
326 min(dossier.date_fin or fin_annee, fin_annee)
327 jours = (fin_cette_annee - debut_cette_annee).days + 1
328
329 remuns = remuns_par_dossier[dossier.id]
330 devises = set(remun.devise.code for remun in remuns)
331 if len(devises) == 1:
332 devise = remuns[0].devise.code
333 montant_remun = lambda r: r.montant
334 taux_change = Decimal(str(remuns[0].taux_change))
335 else:
336 devise = 'EUR'
337 montant_remun = lambda r: (
338 r.montant * Decimal(str(r.taux_change))
48c0abfe 339 )
fc62be5d
EMS
340 taux_change = Decimal(1)
341
342 remuns_par_type = defaultdict(lambda: 0)
343 for remun in remuns:
ff9bc43d
EMS
344 if remun.type.nature_remuneration == u'Accessoire':
345 remuns_par_type[remun.type_id] += montant_remun(remun)
346 else:
347 remuns_par_type[remun.type_id] += (
348 montant_remun(remun) * ((
349 min(remun.date_fin or fin_annee, fin_annee) -
350 max(remun.date_debut or debut_annee, debut_annee)
a81bde86
EMS
351 ).days + 1) / jours_annee *
352 dossier.regime_travail / 100
ff9bc43d 353 ).quantize(TWOPLACES)
fc62be5d
EMS
354 traitements = [
355 remuns_par_type[type.id]
356 for type in types_remun_par_nature[u'Traitement']
357 ]
358 indemnites = [
359 remuns_par_type[type.id]
360 for type in types_remun_par_nature[u'Indemnité']
361 ]
362 primes = [
363 remuns_par_type[type.id]
364 for type in types_remun_par_nature[u'Accessoire']
365 ]
366 charges = [
367 remuns_par_type[type.id]
368 for type in types_remun_par_nature[u'Charges']
369 ]
370 masse_salariale = sum(remuns_par_type.values())
371 masse_salariale_eur = (
372 masse_salariale * taux_change
373 ).quantize(TWOPLACES)
374 masse_salariale_totale += masse_salariale_eur
375
376 if dossier.valeur_point and dossier.classement \
377 and dossier.classement.coefficient and dossier.regime_travail:
378 salaire_theorique = (Decimal(str(
379 dossier.valeur_point * dossier.classement.coefficient
380 )) * dossier.regime_travail / 100).quantize(TWOPLACES)
381 else:
382 salaire_theorique = None
383
384 lignes.append({
385 'dossier': dossier,
386 'poste': dossier.poste,
387 'date_debut': (
388 dossier.date_debut
389 if dossier.date_debut and dossier.date_debut.year == annee
390 else None
391 ),
392 'date_fin': (
393 dossier.date_fin
394 if dossier.date_fin and dossier.date_fin.year == annee
395 else None
396 ),
397 'jours': jours,
398 'devise': devise,
399 'valeur_point': dossier.valeur_point,
400 'valeur_point_devise': dossier.valeur_point_devise,
401 'regime_travail': dossier.regime_travail,
402 'local_expatrie': {
403 'local': 'L', 'expat': 'E'
404 }.get(dossier.statut_residence),
405 'salaire_bstg': remuns_par_type[2],
406 'salaire_bstg_eur': (
407 (remuns_par_type[2] * taux_change).quantize(TWOPLACES)
408 ),
409 'salaire_theorique': salaire_theorique,
410 'traitements': traitements,
411 'total_traitements': sum(traitements),
412 'indemnites': indemnites,
413 'total_indemnites': sum(indemnites),
414 'primes': primes,
415 'total_primes': sum(primes),
416 'charges': charges,
417 'total_charges': sum(charges),
418 'masse_salariale': masse_salariale,
419 'masse_salariale_eur': masse_salariale_eur,
420 })
00ca4d9f 421
fc62be5d
EMS
422 # Récupérer les postes actifs pour déterminer le nombre de jours
423 # vacants.
50e2340a
EMS
424 postes = rh.Poste.objects.actifs(annee=annee) \
425 .select_related(
426 'devise_max', 'valeur_point_max', 'classement_max'
427 ) \
428 .extra(
429 tables=['rh_tauxchange'],
430 where=[
431 'rh_tauxchange.annee = %s',
432 'rh_tauxchange.devise = rh_devise.id'
433 ],
434 params=[annee],
435 select={
436 'taux_change': 'rh_tauxchange.taux'
437 }
438 )
439 if region:
440 postes = postes.filter(implantation__region=region)
441 if implantation:
442 postes = postes.filter(implantation=implantation)
443 postes = list(postes)
fc62be5d
EMS
444 postes_par_id = dict((poste.id, poste) for poste in postes)
445 jours_vacants_date = dict(
446 (poste.id, max(today, poste.date_debut or today))
447 for poste in postes
448 )
449 jours_vacants = defaultdict(lambda: 0)
450 for dossier in rh.Dossier.objects.actifs(annee=annee) \
451 .order_by('date_debut'):
452 if dossier.poste_id not in jours_vacants_date:
453 continue
454 derniere_date = jours_vacants_date[dossier.poste_id]
455 if dossier.date_debut is not None:
456 jours_vacants[dossier.poste_id] += max((
457 dossier.date_debut - derniere_date
458 ).days - 1, 0)
459 jours_vacants_date[dossier.poste_id] = max(
460 min(dossier.date_fin or fin_annee, fin_annee),
461 derniere_date
48c0abfe 462 )
24b5b57f
EMS
463 for poste_id, derniere_date in jours_vacants_date.iteritems():
464 jours_vacants[poste_id] += max((
465 min(postes_par_id[poste_id].date_fin or fin_annee, fin_annee) -
466 derniere_date
467 ).days, 0)
48c0abfe 468
fc62be5d
EMS
469 # Ajouter les lignes des postes vacants au rapport
470 for poste_id, jours in jours_vacants.iteritems():
471 if jours == 0:
472 continue
473 poste = postes_par_id[poste_id]
474 if poste.valeur_point_max and poste.classement_max \
475 and poste.classement_max.coefficient and poste.regime_travail:
476 salaire_theorique = (Decimal(str(
477 poste.valeur_point_max.valeur *
478 poste.classement_max.coefficient
479 )) * poste.regime_travail / 100).quantize(TWOPLACES)
480 else:
481 salaire_theorique = None
df37184c 482
fc62be5d
EMS
483 local_expatrie = '/'.join(
484 (['L'] if poste.local else []) +
485 (['E'] if poste.expatrie else [])
486 )
df37184c 487
fc62be5d
EMS
488 salaire = (
489 poste.salaire_max * jours / jours_annee *
490 poste.regime_travail / 100
491 ).quantize(TWOPLACES)
492 indemnites = (
493 poste.indemn_max * jours / jours_annee *
494 poste.regime_travail / 100
495 ).quantize(TWOPLACES)
496 charges = (
497 poste.autre_max * jours / jours_annee *
498 poste.regime_travail / 100
499 ).quantize(TWOPLACES)
500 masse_salariale = salaire + indemnites + charges
501 masse_salariale_eur = (
502 masse_salariale * Decimal(str(poste.taux_change))
503 ).quantize(TWOPLACES)
504 masse_salariale_totale += masse_salariale_eur
505
506 lignes.append({
507 'poste': poste,
508 'regime_travail': poste.regime_travail,
509 'local_expatrie': local_expatrie,
510 'jours': jours,
511 'devise': poste.devise_max and poste.devise_max.code,
512 'valeur_point': (
513 poste.valeur_point_max and poste.valeur_point_max.valeur
514 ),
515 'valeur_point_devise': (
516 poste.valeur_point_max and \
517 poste.valeur_point_max.devise.code
518 ),
519 'salaire_theorique': salaire_theorique,
24b5b57f
EMS
520 'traitements': [0] * len(titres_traitements),
521 'total_traitements': salaire,
522 'indemnites': [0] * len(titres_indemnites),
fc62be5d 523 'total_indemnites': indemnites,
24b5b57f
EMS
524 'primes': [0] * len(titres_primes),
525 'total_primes': 0,
526 'charges': [0] * len(titres_charges),
fc62be5d
EMS
527 'total_charges': charges,
528 'masse_salariale': masse_salariale,
529 'masse_salariale_eur': masse_salariale_eur
530 })
531 if 'ods' in request.GET:
532 doc = ods.masse_salariale(
533 lignes=lignes,
534 annee=annee,
535 titres_traitements=titres_traitements,
536 titres_indemnites=titres_indemnites,
537 titres_primes=titres_primes,
538 titres_charges=titres_charges,
539 masse_salariale_totale=masse_salariale_totale
540 )
541 response = HttpResponse(
542 mimetype='vnd.oasis.opendocument.spreadsheet'
543 )
544 response['Content-Disposition'] = 'filename=masse-salariale.ods'
545 doc.write(response)
546 return response
547 else:
548 return render(request, 'rh/rapports/masse_salariale.html', {
549 'form': form,
550 'titres_traitements': titres_traitements,
551 'titres_indemnites': titres_indemnites,
552 'titres_primes': titres_primes,
553 'titres_charges': titres_charges,
554 'masse_salariale_totale': masse_salariale_totale,
555 'lignes': lignes,
556 'annee': annee
557 })
558 return render(request, 'rh/rapports/masse_salariale.html', {
559 'form': form
560 })
98d6eb6c
JPC
561
562
563@login_required
564@drh_or_admin_required
857b5c24
JPC
565def rapports_postes_modelisation(request):
566 c = {}
567 data = []
3c1ba807 568
7bf28694
EMS
569 for categorie in rh.CategorieEmploi.objects.all():
570 types = rh.TypePoste.objects.filter(categorie_emploi=categorie)
3c1ba807
JPC
571 data_types = []
572 for t in types.all():
573 postes = rh.Poste.objects.filter(type_poste=t)
574 data_types.append({
575 'num_postes': postes.count(),
576 'postes': postes.all(),
7bf28694 577 'type': categorie,
857b5c24 578 })
3c1ba807 579
857b5c24 580 data.append({
7bf28694 581 'categorie': categorie,
3c1ba807 582 'nb_types': types.count(),
00ca4d9f
EMS
583 'types': data_types
584 })
857b5c24
JPC
585
586 c['data'] = data
587
890b80e7 588 return render(request, 'rh/rapports/postes_modelisation.html', c)
857b5c24
JPC
589
590
591@login_required
592@drh_or_admin_required
783e077a
JPC
593def rapports_postes_implantation(request):
594 c = {}
595 data = []
596 for r in ref.Region.objects.all():
597 implantations = []
598 for i in ref.Implantation.objects.filter(region=r):
599 implantations.append({
600 'implantation': i,
601 'postes': rh.Poste.objects.filter(implantation=i),
602 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
603 })
604 data.append({
605 'region': r,
606 'implantations': implantations
607 })
608
609 c['data'] = data
610
890b80e7 611 return render(request, 'rh/rapports/postes_implantation.html', c)
783e077a
JPC
612
613
614@login_required
615@drh_or_admin_required
616def rapports_postes_service(request):
617 c = {}
9988aafb
JPC
618 data = []
619 for s in rh.Service.objects.all():
620 postes = rh.Poste.objects.filter(service=s).all()
621 num_postes = rh.Poste.objects.filter(service=s).count()
22343fe7 622 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
783e077a 623
9988aafb 624 c['data'] = data
890b80e7 625 return render(request, 'rh/rapports/postes_service.html', c)
32373f2e 626
d104b0ae 627
32373f2e 628@region_protected(rh.Dossier)
3ebc0952 629def dossier_apercu(request, dossier_id):
baf9b78c 630 d = get_object_or_404(rh.Dossier, pk=dossier_id)
3ebc0952 631 c = {
838bc59d 632 'title': u"Dossier %s" % (d, ),
00ca4d9f
EMS
633 'is_popup': request.GET.get('_popup', False),
634 'dossier': d,
635 'pieces': rh.DossierPiece.objects.filter(dossier__exact=d),
636 'contrats': rh.Contrat.objects.filter(dossier__exact=d),
637 'commentaires': rh.DossierCommentaire.objects.filter(dossier=d).all(),
abf91905 638 'media_url': settings.PRIVE_MEDIA_URL,
3ebc0952 639 }
890b80e7 640 return render(request, 'admin/rh/dossier/apercu.html', c)
00ca4d9f 641
4a1f2ece 642
fbe60a9d
OL
643@region_protected(rh.Poste)
644def poste_apercu(request, poste_id):
c8cb18e3 645 p = get_object_or_404(rh.Poste, pk=poste_id)
fbe60a9d 646 c = {
c8cb18e3 647 'title': u"Poste %s" % (p, ),
00ca4d9f
EMS
648 'is_popup': request.GET.get('_popup', False),
649 'poste': p,
650 'financements': (
651 rh.PosteFinancement.objects.filter(poste=poste_id).all()
652 ),
653 'pieces': rh.PostePiece.objects.filter(poste=poste_id).all(),
654 'dossiers': (
655 rh.Dossier.objects.filter(poste=poste_id)
656 .order_by("-date_debut").all()
657 ),
658 'comparaisons': (
659 rh.PosteComparaison.objects.filter(poste=poste_id).all()
660 ),
661 'commentaires': (
662 rh.PosteCommentaire.objects.filter(poste=poste_id).all()
663 ),
abf91905 664 'media_url': settings.PRIVE_MEDIA_URL,
fbe60a9d 665 }
890b80e7 666 return render(request, 'admin/rh/poste/apercu.html', c)
00ca4d9f 667
c3550a05
OL
668@in_one_of_group((groups.grp_correspondants_rh,
669 groups.grp_administrateurs,
670 groups.grp_directeurs_bureau,
671 groups.grp_drh,
672 groups.grp_drh2))
4a1f2ece
OL
673def employe_apercu(request, employe_id):
674 employe = get_object_or_404(rh.Employe, pk=employe_id)
fbe60a9d 675 user_groups = request.user.groups.all()
fbe60a9d
OL
676 dossiers = None
677
cd4c1b65 678 if in_drh_or_admin(request.user):
fbe60a9d 679 q = Q(employe=employe)
22343fe7 680
cd4c1b65
OL
681 if groups.grp_correspondants_rh in user_groups or\
682 groups.grp_administrateurs in user_groups or\
683 groups.grp_directeurs_bureau in user_groups:
bcc0c52d
OL
684 employe_connecte = get_employe_from_user(request.user)
685 q = Q(employe=employe) & Q(poste__implantation__region=employe_connecte.implantation.region)
686
22343fe7
OL
687 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
688
4a1f2ece 689 c = {
ce740bb5 690 'title': u"Employe %s" % (employe, ),
00ca4d9f
EMS
691 'is_popup': request.GET.get('_popup', False),
692 'employe': employe,
693 'dossiers': dossiers,
abf91905 694 'media_url': settings.PRIVE_MEDIA_URL,
4a1f2ece 695 }
890b80e7 696 return render(request, 'admin/rh/employe/apercu.html', c)
00ca4d9f 697
150d83ec 698
77bd83d1 699@login_required
c5dab350
OL
700@in_one_of_group((groups.grp_correspondants_rh,
701 groups.grp_administrateurs,
702 groups.grp_directeurs_bureau,
703 groups.grp_drh,
704 groups.grp_drh2))
56264a85 705def organigrammes_employe(request, id, level="all"):
08faf06e 706 poste = get_object_or_404(rh.Poste, pk=id)
00ca4d9f
EMS
707 dossiers_by_poste = dict(
708 (d.poste_id, d)
709 for d in rh.Dossier.objects.select_related('employe', 'poste').all()
710 )
5c0f1778
JPC
711 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
712
713 e = dossiers_by_poste[poste.id].employe
714 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
58014aec 715 graph = pgv.AGraph()
5c0f1778 716
f187a10f 717 if rh.Poste.objects.filter(responsable=poste).count() > 0:
58014aec
JPC
718 postes_handle = [poste]
719 while postes_handle:
00ca4d9f
EMS
720 postes_handle = rh.Poste.objects.select_related('implantation') \
721 .filter(
722 Q(date_fin__gt=date.today()) | Q(date_fin=None),
723 Q(date_debut__lt=date.today()) | Q(date_debut=None),
724 responsable__in=postes_handle
c3550a05 725 ).exclude(responsable=None).all()
32373f2e 726
58014aec
JPC
727 for p in postes_handle:
728 if p.responsable_id != p.id:
00ca4d9f
EMS
729 graph.add_edge(
730 dossiers_by_poste[p.responsable_id].poste_id, p.id
731 )
13ad5ad5 732
f187a10f 733 else:
5c0f1778
JPC
734 graph.add_node(poste.id)
735
4afec2e1
JPC
736 if level != "all":
737 postes_niveau = [poste.id]
738 for niveau in range(int(level)):
00ca4d9f
EMS
739 postes_niveau = [
740 p.id for p in
741 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
742 ]
4afec2e1
JPC
743
744 while postes_niveau:
00ca4d9f
EMS
745 postes_niveau = [
746 p.id for p in
747 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
748 ]
4afec2e1
JPC
749 if postes_niveau:
750 for p in postes_niveau:
751 if graph.has_node(p):
4cc81304 752 graph.delete_node(p)
4afec2e1 753
58014aec 754 a = graph
4afec2e1 755 a.name = name.encode('ascii', 'xmlcharrefreplace')
5c0f1778
JPC
756
757 poste_remontant = poste
758 while poste_remontant.responsable_id:
759 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
760 poste_remontant = poste_remontant.responsable
761
7000b7b3 762 rh_graph.bind_poste_to_graph(request.user, a, postes_by_id)
5c0f1778
JPC
763 #a.graph_attr['normalize'] = True
764 #a.graph_attr['level'] = 2
765 a.layout(prog='dot')
766
767 svg = a.draw(format='svg')
768
769 c = {
770 'svg': svg
771 }
a251ac8d
JPC
772
773 if 'forcer' in request.GET:
890b80e7 774 response = HttpResponse(svg, content_type='image/svg+xml')
00ca4d9f
EMS
775 response['Content-Disposition'] = \
776 'attachment; filename=organigramme.svg'
a251ac8d
JPC
777 return response
778
890b80e7
DB
779 return render(request, 'rh/organigrammes/employe.html', c,
780 content_type="image/svg+xml"
00ca4d9f 781 )
5c0f1778
JPC
782
783
784@login_required
aa85e40c
DB
785@in_one_of_group((groups.grp_correspondants_rh,
786 groups.grp_administrateurs,
787 groups.grp_directeurs_bureau,
788 groups.grp_drh,
789 groups.grp_drh2))
5c0f1778 790def organigrammes_service(request, id):
5c0f1778 791 service = get_object_or_404(rh.Service, pk=id)
82af5c19 792 svg = rh_graph.organigramme_postes_cluster( \
7000b7b3 793 request.user, \
82af5c19
JPC
794 cluster_filter={"service": service}, \
795 titre=u"Organigramme du service %s" % service.nom,
796 cluster_titre=service.nom)
5c0f1778 797
d104b0ae 798 return render(request, 'rh/organigrammes/vide.html', {
82af5c19 799 'svg': svg
d104b0ae 800 }, content_type="image/svg+xml")
00ca4d9f 801
5c0f1778 802
82af5c19 803@login_required
aa85e40c
DB
804@in_one_of_group((groups.grp_correspondants_rh,
805 groups.grp_administrateurs,
806 groups.grp_directeurs_bureau,
807 groups.grp_drh,
808 groups.grp_drh2))
82af5c19 809def organigrammes_implantation(request, id):
82af5c19
JPC
810 implantation = get_object_or_404(ref.Implantation, pk=id)
811 svg = rh_graph.organigramme_postes_cluster( \
7000b7b3 812 request.user, \
82af5c19
JPC
813 cluster_filter={"implantation": implantation}, \
814 titre=u"Organigramme de l'implantation %s" % implantation.nom,
815 cluster_titre=implantation.nom)
d104b0ae 816 return render(request, 'rh/organigrammes/vide.html', {
5c0f1778 817 'svg': svg
d104b0ae 818 }, content_type="image/svg+xml")
00ca4d9f 819
5c0f1778 820
9da4c195 821@login_required
aa85e40c
DB
822@in_one_of_group((groups.grp_correspondants_rh,
823 groups.grp_administrateurs,
824 groups.grp_directeurs_bureau,
825 groups.grp_drh,
826 groups.grp_drh2))
9da4c195 827def organigrammes_region(request, id):
9da4c195
JPC
828 region = get_object_or_404(ref.Region, pk=id)
829 svg = rh_graph.organigramme_postes_cluster( \
7000b7b3 830 request.user, \
9da4c195
JPC
831 cluster_filter={"implantation__region": region}, \
832 titre=u"Organigramme du bureau de %s" % region.nom,
833 cluster_titre=region.nom)
834
d104b0ae 835 return render(request, 'rh/organigrammes/vide.html', {
9da4c195 836 'svg': svg
d104b0ae 837 }, content_type="image/svg+xml")
8e26a99b
OL
838
839
840@login_required
841@drh_or_admin_required
842def historique_des_modifications(request,):
843
844 from django.core.paginator import Paginator
845
edbc9e37 846 revisions = get_active_revisions()
45c66f19 847 paginator = Paginator(revisions, 50)
8e26a99b
OL
848 page = request.GET.get('page')
849 try:
850 page_revisions = paginator.page(page)
851 except:
852 page_revisions = paginator.page(1)
853
edbc9e37
OL
854 results = page_revisions.object_list
855 if request.POST:
856 form = TodoForm(request.POST, revisions=results)
857 if form.is_valid():
858 for id in form.cleaned_data['items']:
859 revision = Revision.objects.get(id=id)
860 rh.ModificationTraite(revision=revision).save()
861 return redirect(reverse('rhr_historique_des_modifications'))
862 else:
8e26a99b 863
edbc9e37
OL
864 form = TodoForm(revisions=results)
865
8e26a99b 866 c = {
edbc9e37
OL
867 'headers': ('Date', 'Auteur', 'Type', 'Objet', 'Historique',
868 'Commentaire', 'Traité'),
8e26a99b
OL
869 'revisions': results,
870 'page': page_revisions,
edbc9e37 871 'form': form,
8e26a99b
OL
872 }
873
874 return render(request, 'rh/rapports/historique_des_modifications.html', c)