fix import
[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
3383b2d1
OL
80@in_one_of_group((groups.CORRESPONDANT_RH,
81 groups.ADMINISTRATEURS,
82 groups.DIRECTEUR_DE_BUREAU,
83 groups.DRH_NIVEAU_1,
84 groups.DRH_NIVEAU_2))
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)
3383b2d1
OL
108 user_groups = [g.name for g in request.user.groups.all()]
109 if groups.CORRESPONDANT_RH in user_groups or\
110 groups.ADMINISTRATEURS in user_groups or\
111 groups.DIRECTEUR_DE_BUREAU in user_groups:
f96ec25c
OL
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
3383b2d1
OL
152@in_one_of_group((groups.CORRESPONDANT_RH,
153 groups.ADMINISTRATEURS,
154 groups.DIRECTEUR_DE_BUREAU,
155 groups.DRH_NIVEAU_1,
156 groups.DRH_NIVEAU_2))
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
3383b2d1 166 user_groups = [g.name for g in request.user.groups.all()]
3383b2d1
OL
167 if groups.CORRESPONDANT_RH in user_groups or\
168 groups.ADMINISTRATEURS in user_groups or\
169 groups.DIRECTEUR_DE_BUREAU in user_groups:
219ae355 170 employe = get_employe_from_user(request.user)
a20fa2a4 171 lookup_params['poste__implantation__region'] = employe.implantation.region
219ae355 172
a20fa2a4
OL
173
174 dossiers = rh.Dossier.objects.sans_contrats_ou_echus(**lookup_params)
a20fa2a4
OL
175 dossiers_ids = [d.id for d in dossiers]
176 employes = rh.Employe.objects.filter(id__in=dossiers_ids).distinct().count()
a623d1b2 177
5db1c5a3 178 # tri
c8b22fd1 179 if 'o' in request.GET:
5db1c5a3 180 dossiers = dossiers.order_by(
00ca4d9f
EMS
181 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
182 )
c8b22fd1 183
6b7cf654 184 # affichage
c8b22fd1 185 headers = [
5db1c5a3
DB
186 ("employe__id", u"#"),
187 ("employe__nom", u"Employé"),
1a7b9e36 188 ("dossier", u"Dossier : Poste"),
5db1c5a3
DB
189 ("rh_contrats__type_contrat", u"Contrat"),
190 ("rh_contrats__date_debut", u"Début contrat"),
191 ("rh_contrats__date_fin", u"Fin contrat"),
192 ("statut_residence", u"Statut"),
193 ("poste__implantation__region__code", u"Région"),
194 ("poste__implantation__nom", u"Implantation"),
c8b22fd1 195 ]
00ca4d9f
EMS
196 h = SortHeaders(
197 request, headers, order_field_type="ot", order_field="o",
5db1c5a3 198 not_sortable=('dossier',)
00ca4d9f 199 )
c8b22fd1
JPC
200
201 c = {
5db1c5a3 202 'title': u'Rapport des employés sans contrat ou contrat échu',
c8b22fd1 203 'employes': employes,
5db1c5a3 204 'dossiers': dossiers,
c8b22fd1
JPC
205 'headers': list(h.headers()),
206 }
207
890b80e7 208 return render(request, 'rh/rapports/employes_sans_contrat.html', c)
00ca4d9f 209
c8b22fd1
JPC
210
211@login_required
3383b2d1
OL
212@in_one_of_group((groups.CORRESPONDANT_RH,
213 groups.ADMINISTRATEURS,
214 groups.DIRECTEUR_DE_BUREAU,
215 groups.DRH_NIVEAU_1,
216 groups.DRH_NIVEAU_2))
98d6eb6c 217def rapports_masse_salariale(request):
fc62be5d
EMS
218 form = MasseSalarialeForm(request.user, request.GET)
219 if 'annee' in request.GET and form.is_valid():
220 region = form.cleaned_data['region']
221 implantation = form.cleaned_data['implantation']
222 annee = form.cleaned_data['annee']
223 debut_annee = date(annee, 1, 1)
224 fin_annee = date(annee, 12, 31)
225 jours_annee = (fin_annee - debut_annee).days + 1
226 today = date.today()
227
228 # Récupérer les dossiers actifs
229 dossiers = rh.Dossier.objects \
230 .actifs(annee=annee) \
231 .select_related(
232 'poste', 'poste__implantation',
233 'poste__implantation__region',
234 'poste__implantation__adresse_physique_pays',
235 'employe', 'poste__type_poste', 'classement',
236 'statut', 'organisme_bstg'
237 ) \
238 .extra(
fc62be5d 239 select={
471fd30f
EMS
240 'valeur_point': (
241 'SELECT valeur FROM rh_valeurpoint '
242 'WHERE annee = %d '
243 'AND implantation = ref_implantation.id' % annee
244 ),
245 'valeur_point_devise': (
246 'SELECT d.code '
247 'FROM rh_valeurpoint vp '
248 'INNER JOIN rh_devise d ON d.id = vp.devise '
249 'WHERE annee = %d '
250 'AND implantation = ref_implantation.id' % annee
251 )
fc62be5d 252 }
48c0abfe 253 )
fc62be5d
EMS
254 if region:
255 dossiers = dossiers.filter(poste__implantation__region=region)
256 if implantation:
257 dossiers = dossiers.filter(poste__implantation=implantation)
258
259 # Récupérer les rémunérations actives
260 remuns = rh.Remuneration.objects \
261 .actifs(annee=annee) \
262 .select_related('devise', 'type') \
263 .extra(
264 tables=['rh_tauxchange'],
265 where=[
266 'rh_tauxchange.annee = %s',
267 'rh_tauxchange.devise = rh_devise.id'
268 ],
269 params=[annee],
270 select={
271 'taux_change': 'rh_tauxchange.taux'
272 }
273 )
471fd30f
EMS
274 if region:
275 remuns = remuns.filter(dossier__poste__implantation__region=region)
276 if implantation:
277 remuns = remuns.filter(dossier__poste__implantation=implantation)
fc62be5d 278 remuns_par_dossier = defaultdict(list)
471fd30f 279 types_remun = set()
fc62be5d 280 for remun in remuns:
471fd30f 281 types_remun.add(remun.type_id)
fc62be5d
EMS
282 remuns_par_dossier[remun.dossier_id].append(remun)
283
284 # Récupérer les types de rémunération par nature
285 types_remun_par_nature = defaultdict(list)
286 for type in rh.TypeRemuneration.objects.all():
471fd30f
EMS
287 if type.id in types_remun:
288 types_remun_par_nature[type.nature_remuneration].append(type)
fc62be5d
EMS
289 titres_traitements = [
290 t.nom for t in types_remun_par_nature[u'Traitement']
291 ]
292 titres_indemnites = [
293 t.nom for t in types_remun_par_nature[u'Indemnité']
294 ]
295 titres_primes = [
296 t.nom for t in types_remun_par_nature[u'Accessoire']
297 ]
298 titres_charges = [
299 t.nom for t in types_remun_par_nature[u'Charges']
300 ]
df37184c 301
fc62be5d
EMS
302 # Boucler sur les dossiers et préprarer les lignes du rapport
303 lignes = []
304 masse_salariale_totale = 0
305 for dossier in dossiers:
306 debut_cette_annee = \
307 max(dossier.date_debut or debut_annee, debut_annee)
308 fin_cette_annee = \
309 min(dossier.date_fin or fin_annee, fin_annee)
310 jours = (fin_cette_annee - debut_cette_annee).days + 1
311
312 remuns = remuns_par_dossier[dossier.id]
313 devises = set(remun.devise.code for remun in remuns)
314 if len(devises) == 1:
315 devise = remuns[0].devise.code
316 montant_remun = lambda r: r.montant
317 taux_change = Decimal(str(remuns[0].taux_change))
318 else:
319 devise = 'EUR'
320 montant_remun = lambda r: (
321 r.montant * Decimal(str(r.taux_change))
48c0abfe 322 )
fc62be5d
EMS
323 taux_change = Decimal(1)
324
325 remuns_par_type = defaultdict(lambda: 0)
326 for remun in remuns:
ff9bc43d
EMS
327 if remun.type.nature_remuneration == u'Accessoire':
328 remuns_par_type[remun.type_id] += montant_remun(remun)
329 else:
330 remuns_par_type[remun.type_id] += (
331 montant_remun(remun) * ((
332 min(remun.date_fin or fin_annee, fin_annee) -
333 max(remun.date_debut or debut_annee, debut_annee)
a81bde86
EMS
334 ).days + 1) / jours_annee *
335 dossier.regime_travail / 100
ff9bc43d 336 ).quantize(TWOPLACES)
fc62be5d
EMS
337 traitements = [
338 remuns_par_type[type.id]
339 for type in types_remun_par_nature[u'Traitement']
340 ]
341 indemnites = [
342 remuns_par_type[type.id]
343 for type in types_remun_par_nature[u'Indemnité']
344 ]
345 primes = [
346 remuns_par_type[type.id]
347 for type in types_remun_par_nature[u'Accessoire']
348 ]
349 charges = [
350 remuns_par_type[type.id]
351 for type in types_remun_par_nature[u'Charges']
352 ]
353 masse_salariale = sum(remuns_par_type.values())
354 masse_salariale_eur = (
355 masse_salariale * taux_change
356 ).quantize(TWOPLACES)
357 masse_salariale_totale += masse_salariale_eur
358
359 if dossier.valeur_point and dossier.classement \
360 and dossier.classement.coefficient and dossier.regime_travail:
361 salaire_theorique = (Decimal(str(
362 dossier.valeur_point * dossier.classement.coefficient
363 )) * dossier.regime_travail / 100).quantize(TWOPLACES)
364 else:
365 salaire_theorique = None
366
367 lignes.append({
368 'dossier': dossier,
369 'poste': dossier.poste,
370 'date_debut': (
371 dossier.date_debut
372 if dossier.date_debut and dossier.date_debut.year == annee
373 else None
374 ),
375 'date_fin': (
376 dossier.date_fin
377 if dossier.date_fin and dossier.date_fin.year == annee
378 else None
379 ),
380 'jours': jours,
381 'devise': devise,
382 'valeur_point': dossier.valeur_point,
383 'valeur_point_devise': dossier.valeur_point_devise,
384 'regime_travail': dossier.regime_travail,
385 'local_expatrie': {
386 'local': 'L', 'expat': 'E'
387 }.get(dossier.statut_residence),
388 'salaire_bstg': remuns_par_type[2],
389 'salaire_bstg_eur': (
390 (remuns_par_type[2] * taux_change).quantize(TWOPLACES)
391 ),
392 'salaire_theorique': salaire_theorique,
393 'traitements': traitements,
394 'total_traitements': sum(traitements),
395 'indemnites': indemnites,
396 'total_indemnites': sum(indemnites),
397 'primes': primes,
398 'total_primes': sum(primes),
399 'charges': charges,
400 'total_charges': sum(charges),
401 'masse_salariale': masse_salariale,
402 'masse_salariale_eur': masse_salariale_eur,
403 })
00ca4d9f 404
fc62be5d
EMS
405 # Récupérer les postes actifs pour déterminer le nombre de jours
406 # vacants.
50e2340a
EMS
407 postes = rh.Poste.objects.actifs(annee=annee) \
408 .select_related(
409 'devise_max', 'valeur_point_max', 'classement_max'
410 ) \
411 .extra(
412 tables=['rh_tauxchange'],
413 where=[
414 'rh_tauxchange.annee = %s',
415 'rh_tauxchange.devise = rh_devise.id'
416 ],
417 params=[annee],
418 select={
419 'taux_change': 'rh_tauxchange.taux'
420 }
421 )
422 if region:
423 postes = postes.filter(implantation__region=region)
424 if implantation:
425 postes = postes.filter(implantation=implantation)
426 postes = list(postes)
fc62be5d
EMS
427 postes_par_id = dict((poste.id, poste) for poste in postes)
428 jours_vacants_date = dict(
429 (poste.id, max(today, poste.date_debut or today))
430 for poste in postes
431 )
432 jours_vacants = defaultdict(lambda: 0)
433 for dossier in rh.Dossier.objects.actifs(annee=annee) \
434 .order_by('date_debut'):
435 if dossier.poste_id not in jours_vacants_date:
436 continue
437 derniere_date = jours_vacants_date[dossier.poste_id]
438 if dossier.date_debut is not None:
439 jours_vacants[dossier.poste_id] += max((
440 dossier.date_debut - derniere_date
441 ).days - 1, 0)
442 jours_vacants_date[dossier.poste_id] = max(
443 min(dossier.date_fin or fin_annee, fin_annee),
444 derniere_date
48c0abfe 445 )
24b5b57f
EMS
446 for poste_id, derniere_date in jours_vacants_date.iteritems():
447 jours_vacants[poste_id] += max((
448 min(postes_par_id[poste_id].date_fin or fin_annee, fin_annee) -
449 derniere_date
450 ).days, 0)
48c0abfe 451
fc62be5d
EMS
452 # Ajouter les lignes des postes vacants au rapport
453 for poste_id, jours in jours_vacants.iteritems():
454 if jours == 0:
455 continue
456 poste = postes_par_id[poste_id]
457 if poste.valeur_point_max and poste.classement_max \
458 and poste.classement_max.coefficient and poste.regime_travail:
459 salaire_theorique = (Decimal(str(
460 poste.valeur_point_max.valeur *
461 poste.classement_max.coefficient
462 )) * poste.regime_travail / 100).quantize(TWOPLACES)
463 else:
464 salaire_theorique = None
df37184c 465
fc62be5d
EMS
466 local_expatrie = '/'.join(
467 (['L'] if poste.local else []) +
468 (['E'] if poste.expatrie else [])
469 )
df37184c 470
fc62be5d
EMS
471 salaire = (
472 poste.salaire_max * jours / jours_annee *
473 poste.regime_travail / 100
474 ).quantize(TWOPLACES)
475 indemnites = (
476 poste.indemn_max * jours / jours_annee *
477 poste.regime_travail / 100
478 ).quantize(TWOPLACES)
479 charges = (
480 poste.autre_max * jours / jours_annee *
481 poste.regime_travail / 100
482 ).quantize(TWOPLACES)
483 masse_salariale = salaire + indemnites + charges
484 masse_salariale_eur = (
485 masse_salariale * Decimal(str(poste.taux_change))
486 ).quantize(TWOPLACES)
487 masse_salariale_totale += masse_salariale_eur
488
489 lignes.append({
490 'poste': poste,
491 'regime_travail': poste.regime_travail,
492 'local_expatrie': local_expatrie,
493 'jours': jours,
494 'devise': poste.devise_max and poste.devise_max.code,
495 'valeur_point': (
496 poste.valeur_point_max and poste.valeur_point_max.valeur
497 ),
498 'valeur_point_devise': (
499 poste.valeur_point_max and \
500 poste.valeur_point_max.devise.code
501 ),
502 'salaire_theorique': salaire_theorique,
24b5b57f
EMS
503 'traitements': [0] * len(titres_traitements),
504 'total_traitements': salaire,
505 'indemnites': [0] * len(titres_indemnites),
fc62be5d 506 'total_indemnites': indemnites,
24b5b57f
EMS
507 'primes': [0] * len(titres_primes),
508 'total_primes': 0,
509 'charges': [0] * len(titres_charges),
fc62be5d
EMS
510 'total_charges': charges,
511 'masse_salariale': masse_salariale,
512 'masse_salariale_eur': masse_salariale_eur
513 })
514 if 'ods' in request.GET:
515 doc = ods.masse_salariale(
516 lignes=lignes,
517 annee=annee,
518 titres_traitements=titres_traitements,
519 titres_indemnites=titres_indemnites,
520 titres_primes=titres_primes,
521 titres_charges=titres_charges,
522 masse_salariale_totale=masse_salariale_totale
523 )
524 response = HttpResponse(
525 mimetype='vnd.oasis.opendocument.spreadsheet'
526 )
527 response['Content-Disposition'] = 'filename=masse-salariale.ods'
528 doc.write(response)
529 return response
530 else:
531 return render(request, 'rh/rapports/masse_salariale.html', {
532 'form': form,
533 'titres_traitements': titres_traitements,
534 'titres_indemnites': titres_indemnites,
535 'titres_primes': titres_primes,
536 'titres_charges': titres_charges,
537 'masse_salariale_totale': masse_salariale_totale,
538 'lignes': lignes,
539 'annee': annee
540 })
541 return render(request, 'rh/rapports/masse_salariale.html', {
542 'form': form
543 })
98d6eb6c
JPC
544
545
546@login_required
547@drh_or_admin_required
857b5c24
JPC
548def rapports_postes_modelisation(request):
549 c = {}
550 data = []
3c1ba807 551
7bf28694
EMS
552 for categorie in rh.CategorieEmploi.objects.all():
553 types = rh.TypePoste.objects.filter(categorie_emploi=categorie)
3c1ba807
JPC
554 data_types = []
555 for t in types.all():
556 postes = rh.Poste.objects.filter(type_poste=t)
557 data_types.append({
558 'num_postes': postes.count(),
559 'postes': postes.all(),
7bf28694 560 'type': categorie,
857b5c24 561 })
3c1ba807 562
857b5c24 563 data.append({
7bf28694 564 'categorie': categorie,
3c1ba807 565 'nb_types': types.count(),
00ca4d9f
EMS
566 'types': data_types
567 })
857b5c24
JPC
568
569 c['data'] = data
570
890b80e7 571 return render(request, 'rh/rapports/postes_modelisation.html', c)
857b5c24
JPC
572
573
574@login_required
575@drh_or_admin_required
783e077a
JPC
576def rapports_postes_implantation(request):
577 c = {}
578 data = []
579 for r in ref.Region.objects.all():
580 implantations = []
581 for i in ref.Implantation.objects.filter(region=r):
582 implantations.append({
583 'implantation': i,
584 'postes': rh.Poste.objects.filter(implantation=i),
585 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
586 })
587 data.append({
588 'region': r,
589 'implantations': implantations
590 })
591
592 c['data'] = data
593
890b80e7 594 return render(request, 'rh/rapports/postes_implantation.html', c)
783e077a
JPC
595
596
597@login_required
598@drh_or_admin_required
599def rapports_postes_service(request):
600 c = {}
9988aafb
JPC
601 data = []
602 for s in rh.Service.objects.all():
603 postes = rh.Poste.objects.filter(service=s).all()
604 num_postes = rh.Poste.objects.filter(service=s).count()
22343fe7 605 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
783e077a 606
9988aafb 607 c['data'] = data
890b80e7 608 return render(request, 'rh/rapports/postes_service.html', c)
32373f2e 609
d104b0ae 610
32373f2e 611@region_protected(rh.Dossier)
3ebc0952 612def dossier_apercu(request, dossier_id):
baf9b78c 613 d = get_object_or_404(rh.Dossier, pk=dossier_id)
3ebc0952 614 c = {
838bc59d 615 'title': u"Dossier %s" % (d, ),
00ca4d9f
EMS
616 'is_popup': request.GET.get('_popup', False),
617 'dossier': d,
618 'pieces': rh.DossierPiece.objects.filter(dossier__exact=d),
619 'contrats': rh.Contrat.objects.filter(dossier__exact=d),
620 'commentaires': rh.DossierCommentaire.objects.filter(dossier=d).all(),
abf91905 621 'media_url': settings.PRIVE_MEDIA_URL,
3ebc0952 622 }
890b80e7 623 return render(request, 'admin/rh/dossier/apercu.html', c)
00ca4d9f 624
4a1f2ece 625
fbe60a9d
OL
626@region_protected(rh.Poste)
627def poste_apercu(request, poste_id):
c8cb18e3 628 p = get_object_or_404(rh.Poste, pk=poste_id)
fbe60a9d 629 c = {
c8cb18e3 630 'title': u"Poste %s" % (p, ),
00ca4d9f
EMS
631 'is_popup': request.GET.get('_popup', False),
632 'poste': p,
633 'financements': (
634 rh.PosteFinancement.objects.filter(poste=poste_id).all()
635 ),
636 'pieces': rh.PostePiece.objects.filter(poste=poste_id).all(),
637 'dossiers': (
638 rh.Dossier.objects.filter(poste=poste_id)
639 .order_by("-date_debut").all()
640 ),
641 'comparaisons': (
642 rh.PosteComparaison.objects.filter(poste=poste_id).all()
643 ),
644 'commentaires': (
645 rh.PosteCommentaire.objects.filter(poste=poste_id).all()
646 ),
abf91905 647 'media_url': settings.PRIVE_MEDIA_URL,
fbe60a9d 648 }
890b80e7 649 return render(request, 'admin/rh/poste/apercu.html', c)
00ca4d9f 650
3383b2d1
OL
651@login_required
652@in_one_of_group((groups.CORRESPONDANT_RH,
653 groups.ADMINISTRATEURS,
654 groups.DIRECTEUR_DE_BUREAU,
655 groups.DRH_NIVEAU_1,
656 groups.DRH_NIVEAU_2))
4a1f2ece
OL
657def employe_apercu(request, employe_id):
658 employe = get_object_or_404(rh.Employe, pk=employe_id)
3383b2d1 659 user_groups = [g.name for g in request.user.groups.all()]
fbe60a9d
OL
660 dossiers = None
661
cd4c1b65 662 if in_drh_or_admin(request.user):
fbe60a9d 663 q = Q(employe=employe)
22343fe7 664
3383b2d1
OL
665 if groups.CORRESPONDANT_RH in user_groups or\
666 groups.ADMINISTRATEURS in user_groups or\
667 groups.DIRECTEUR_DE_BUREAU in user_groups:
bcc0c52d
OL
668 employe_connecte = get_employe_from_user(request.user)
669 q = Q(employe=employe) & Q(poste__implantation__region=employe_connecte.implantation.region)
670
22343fe7
OL
671 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
672
4a1f2ece 673 c = {
ce740bb5 674 'title': u"Employe %s" % (employe, ),
00ca4d9f
EMS
675 'is_popup': request.GET.get('_popup', False),
676 'employe': employe,
677 'dossiers': dossiers,
abf91905 678 'media_url': settings.PRIVE_MEDIA_URL,
4a1f2ece 679 }
890b80e7 680 return render(request, 'admin/rh/employe/apercu.html', c)
00ca4d9f 681
150d83ec 682
77bd83d1 683@login_required
3383b2d1
OL
684@in_one_of_group((groups.CORRESPONDANT_RH,
685 groups.ADMINISTRATEURS,
686 groups.DIRECTEUR_DE_BUREAU,
687 groups.DRH_NIVEAU_1,
688 groups.DRH_NIVEAU_2))
56264a85 689def organigrammes_employe(request, id, level="all"):
08faf06e 690 poste = get_object_or_404(rh.Poste, pk=id)
00ca4d9f
EMS
691 dossiers_by_poste = dict(
692 (d.poste_id, d)
693 for d in rh.Dossier.objects.select_related('employe', 'poste').all()
694 )
5c0f1778
JPC
695 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
696
697 e = dossiers_by_poste[poste.id].employe
698 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
58014aec 699 graph = pgv.AGraph()
5c0f1778 700
f187a10f 701 if rh.Poste.objects.filter(responsable=poste).count() > 0:
58014aec
JPC
702 postes_handle = [poste]
703 while postes_handle:
00ca4d9f
EMS
704 postes_handle = rh.Poste.objects.select_related('implantation') \
705 .filter(
706 Q(date_fin__gt=date.today()) | Q(date_fin=None),
707 Q(date_debut__lt=date.today()) | Q(date_debut=None),
708 responsable__in=postes_handle
c3550a05 709 ).exclude(responsable=None).all()
32373f2e 710
58014aec
JPC
711 for p in postes_handle:
712 if p.responsable_id != p.id:
00ca4d9f
EMS
713 graph.add_edge(
714 dossiers_by_poste[p.responsable_id].poste_id, p.id
715 )
13ad5ad5 716
f187a10f 717 else:
5c0f1778
JPC
718 graph.add_node(poste.id)
719
4afec2e1
JPC
720 if level != "all":
721 postes_niveau = [poste.id]
722 for niveau in range(int(level)):
00ca4d9f
EMS
723 postes_niveau = [
724 p.id for p in
725 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
726 ]
4afec2e1
JPC
727
728 while postes_niveau:
00ca4d9f
EMS
729 postes_niveau = [
730 p.id for p in
731 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
732 ]
4afec2e1
JPC
733 if postes_niveau:
734 for p in postes_niveau:
735 if graph.has_node(p):
4cc81304 736 graph.delete_node(p)
4afec2e1 737
58014aec 738 a = graph
4afec2e1 739 a.name = name.encode('ascii', 'xmlcharrefreplace')
5c0f1778
JPC
740
741 poste_remontant = poste
742 while poste_remontant.responsable_id:
743 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
744 poste_remontant = poste_remontant.responsable
745
7000b7b3 746 rh_graph.bind_poste_to_graph(request.user, a, postes_by_id)
5c0f1778
JPC
747 #a.graph_attr['normalize'] = True
748 #a.graph_attr['level'] = 2
749 a.layout(prog='dot')
750
751 svg = a.draw(format='svg')
752
753 c = {
754 'svg': svg
755 }
a251ac8d
JPC
756
757 if 'forcer' in request.GET:
890b80e7 758 response = HttpResponse(svg, content_type='image/svg+xml')
00ca4d9f
EMS
759 response['Content-Disposition'] = \
760 'attachment; filename=organigramme.svg'
a251ac8d
JPC
761 return response
762
890b80e7
DB
763 return render(request, 'rh/organigrammes/employe.html', c,
764 content_type="image/svg+xml"
00ca4d9f 765 )
5c0f1778
JPC
766
767
768@login_required
3383b2d1
OL
769@in_one_of_group((groups.CORRESPONDANT_RH,
770 groups.ADMINISTRATEURS,
771 groups.DIRECTEUR_DE_BUREAU,
772 groups.DRH_NIVEAU_1,
773 groups.DRH_NIVEAU_2))
5c0f1778 774def organigrammes_service(request, id):
5c0f1778 775 service = get_object_or_404(rh.Service, pk=id)
82af5c19 776 svg = rh_graph.organigramme_postes_cluster( \
7000b7b3 777 request.user, \
82af5c19
JPC
778 cluster_filter={"service": service}, \
779 titre=u"Organigramme du service %s" % service.nom,
780 cluster_titre=service.nom)
5c0f1778 781
d104b0ae 782 return render(request, 'rh/organigrammes/vide.html', {
82af5c19 783 'svg': svg
d104b0ae 784 }, content_type="image/svg+xml")
00ca4d9f 785
5c0f1778 786
82af5c19 787@login_required
3383b2d1
OL
788@in_one_of_group((groups.CORRESPONDANT_RH,
789 groups.ADMINISTRATEURS,
790 groups.DIRECTEUR_DE_BUREAU,
791 groups.DRH_NIVEAU_1,
792 groups.DRH_NIVEAU_2))
82af5c19 793def organigrammes_implantation(request, id):
82af5c19
JPC
794 implantation = get_object_or_404(ref.Implantation, pk=id)
795 svg = rh_graph.organigramme_postes_cluster( \
7000b7b3 796 request.user, \
82af5c19
JPC
797 cluster_filter={"implantation": implantation}, \
798 titre=u"Organigramme de l'implantation %s" % implantation.nom,
799 cluster_titre=implantation.nom)
d104b0ae 800 return render(request, 'rh/organigrammes/vide.html', {
5c0f1778 801 'svg': svg
d104b0ae 802 }, content_type="image/svg+xml")
00ca4d9f 803
5c0f1778 804
9da4c195 805@login_required
3383b2d1
OL
806@in_one_of_group((groups.CORRESPONDANT_RH,
807 groups.ADMINISTRATEURS,
808 groups.DIRECTEUR_DE_BUREAU,
809 groups.DRH_NIVEAU_1,
810 groups.DRH_NIVEAU_2))
9da4c195 811def organigrammes_region(request, id):
9da4c195
JPC
812 region = get_object_or_404(ref.Region, pk=id)
813 svg = rh_graph.organigramme_postes_cluster( \
7000b7b3 814 request.user, \
9da4c195
JPC
815 cluster_filter={"implantation__region": region}, \
816 titre=u"Organigramme du bureau de %s" % region.nom,
817 cluster_titre=region.nom)
818
d104b0ae 819 return render(request, 'rh/organigrammes/vide.html', {
9da4c195 820 'svg': svg
d104b0ae 821 }, content_type="image/svg+xml")
8e26a99b
OL
822
823
824@login_required
825@drh_or_admin_required
826def historique_des_modifications(request,):
827
828 from django.core.paginator import Paginator
829
edbc9e37 830 revisions = get_active_revisions()
45c66f19 831 paginator = Paginator(revisions, 50)
8e26a99b
OL
832 page = request.GET.get('page')
833 try:
834 page_revisions = paginator.page(page)
835 except:
836 page_revisions = paginator.page(1)
837
edbc9e37
OL
838 results = page_revisions.object_list
839 if request.POST:
840 form = TodoForm(request.POST, revisions=results)
841 if form.is_valid():
842 for id in form.cleaned_data['items']:
843 revision = Revision.objects.get(id=id)
844 rh.ModificationTraite(revision=revision).save()
845 return redirect(reverse('rhr_historique_des_modifications'))
846 else:
8e26a99b 847
edbc9e37
OL
848 form = TodoForm(revisions=results)
849
8e26a99b 850 c = {
edbc9e37
OL
851 'headers': ('Date', 'Auteur', 'Type', 'Objet', 'Historique',
852 'Commentaire', 'Traité'),
8e26a99b
OL
853 'revisions': results,
854 'page': page_revisions,
edbc9e37 855 'form': form,
8e26a99b
OL
856 }
857
858 return render(request, 'rh/rapports/historique_des_modifications.html', c)