trad
[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
JPC
8import pygraphviz as pgv
9
dcd1b959 10from django.core.urlresolvers import reverse
fbe60a9d 11from django.db.models import Q
fd009814 12from django.utils.encoding import smart_str
22343fe7 13from django.shortcuts import render_to_response, get_object_or_404
e9bbd6ba 14from django.template import RequestContext
a251ac8d 15from django.http import HttpResponse
e90b19fd
OL
16from django import forms
17from django.contrib.auth.decorators import login_required
18from django.contrib.admin import widgets as adminwidgets
eabb27fd 19from django.core.servers.basehttp import FileWrapper
e9bbd6ba 20
d04d084c 21from datamaster_modeles import models as ref
ae936f8d 22
d04d084c 23from rh import models as rh
e2c0b1ac 24from rh.lib import calc_remun
02c1b3dc 25from rh.decorators import drh_or_admin_required
9d53bc73 26from rh.templatetags.rapports import SortHeaders
f0f6b03e 27from rh.change_list import RechercheTemporelle
5c0f1778 28from rh import graph as rh_graph
df37184c 29from rh.masse_salariale import MasseSalariale
a9faef67 30
9817fed5
OL
31# pas de reference a DAE devrait etre refactorisé
32from dae.utils import get_employe_from_user
33from dae.decorators import redirect_interdiction
34from dae.workflow import grp_drh, grp_correspondants_rh
baf9b78c 35from django.conf import settings
9817fed5 36
22343fe7 37
c9122f1d 38@login_required
39def profil(request):
40 """Profil personnel de l'employé - éditable"""
41 rc = RequestContext(request)
42 c = {}
22343fe7 43
c9122f1d 44 employe = rc['this_employe']
22343fe7 45
c9122f1d 46 c['user'] = request.user
47 c['employe'] = employe
c9122f1d 48 return render_to_response('rh/profil.html', c, rc)
22343fe7
OL
49
50
3411ac33 51@login_required
a9faef67 52def employes_liste(request):
53 """Liste des employés."""
5ea6b5bb 54 today = date.today()
55 employes = rh.Employe.objects \
5ea6b5bb 56 .exclude(dossiers__date_debut__gt=today) \
57 .exclude(dossiers__date_fin__lt=today) \
58 .order_by('nom')
a9faef67 59 c = {
22343fe7
OL
60 'user': request.user,
61 'employes': employes,
a9faef67 62 }
22343fe7
OL
63 return render_to_response('rh/employes_liste.html',
64 c,
65 RequestContext(request))
66
67
3411ac33 68@login_required
a9faef67 69def employe(request, id):
70 """Information publique sur un employé."""
71 try:
72 employe = rh.Employe.objects.get(pk=id)
73 except:
74 employe = rh.Employe.objects.none()
75 c = {
22343fe7
OL
76 'user': request.user,
77 'employe': employe,
a9faef67 78 }
79 return render_to_response('rh/employe.html', c, RequestContext(request))
63e17dff
PP
80
81
08faf06e
JPC
82@login_required
83@drh_or_admin_required
63e17dff
PP
84def rapports_poste(request):
85
fd009814
PP
86 lookup_params = dict(request.GET.items())
87
88 for key, value in lookup_params.items():
9d53bc73
JPC
89 if key == 'o' or key == 'ot':
90 del lookup_params[key]
91 continue
fd009814
PP
92 if not isinstance(key, str):
93 # 'key' will be used as a keyword argument later, so Python
94 # requires it to be a string.
95 del lookup_params[key]
96 lookup_params[smart_str(key)] = value
97
7821915f 98 if key == 'comble':
7821915f
PP
99 del lookup_params[key]
100
ed3cbb32
OL
101 postes = rh.Poste.objects.select_related('implantation') \
102 .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' % \
9202c5db
JPC
103 ("%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 "") \
104 }) \
ed3cbb32 105 .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' % \
9202c5db
JPC
106 ("%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 "") \
107 }) \
ed3cbb32 108 .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' % \
9202c5db
JPC
109 ("%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 "") \
110 })
9d53bc73 111
65e02621 112 postes = postes.filter(**lookup_params)
9d53bc73 113 if 'o' in request.GET:
65e02621
JPC
114 postes = postes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
115
a7de62d7
JPC
116 out = []
117 for p in postes:
118 out.append({
119 'id': p.id,
120 'nom': p.nom,
121 'implantation': p.implantation,
122 '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('|'))] })
123
124
4dade240
JPC
125 headers = [
126 ("id", u"# du poste"),
127 ("nom", u"Nom du poste"),
65e02621 128 ("implantation__id", u"Implantation"),
4dade240 129 ("employe_nom", u"Nom"),
4dade240
JPC
130 ]
131 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
63e17dff
PP
132 c = {
133 'title': 'Rapport des postes',
a7de62d7
JPC
134 'postes': out,
135 'count': len(out),
65e02621 136 'headers': list(h.headers()),
63e17dff
PP
137 }
138
139 return render_to_response('rh/rapports/postes.html', c, RequestContext(request))
f2d65e83 140
02c1b3dc
JPC
141@login_required
142@drh_or_admin_required
f2d65e83 143def rapports_contrat(request):
dcd1b959
OL
144 if 'HTTP_REFERER' in request.META.keys():
145 referer = request.META['HTTP_REFERER']
146 referer = "/".join(referer.split('/')[3:])
147 referer = "/%s" % referer.split('?')[0]
148 if referer != reverse('rhr_contrats'):
149 params = request.GET.copy()
150 params.update({'statut': 'Actif'})
151 request.GET = params
f2d65e83
PP
152
153 lookup_params = dict(request.GET.items())
65e02621
JPC
154 if 'ot' in lookup_params:
155 del lookup_params['ot']
156 if 'o' in lookup_params:
157 del lookup_params['o']
f2d65e83
PP
158
159 for key, value in lookup_params.items():
160 if not isinstance(key, str):
161 # 'key' will be used as a keyword argument later, so Python
162 # requires it to be a string.
163 del lookup_params[key]
164 lookup_params[smart_str(key)] = value
165
65e02621 166 contrats = rh.Contrat.objects.select_related('dossier', 'dossier__poste', 'dossier__poste__implantation', 'type_contrat', 'dossier__employe')
22343fe7 167
6bee05ff 168 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
f0f6b03e 169 lookup_params = cl.purge_params(lookup_params)
dcd1b959
OL
170 q_temporel = cl.get_q_temporel(contrats)
171 q = Q(**lookup_params) & q_temporel
172 contrats = contrats.filter(q).exclude(dossier__employe__supprime=1)
f0f6b03e 173
65e02621
JPC
174 if 'o' in request.GET:
175 contrats = contrats.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
f2d65e83 176
8ee135b7
JPC
177 employes = set([c.dossier.employe_id for c in contrats])
178
65e02621
JPC
179 headers = [
180 ("dossier__employe__id", u"# de l'employé"),
181 ("dossier__employe__nom", u"Nom"),
182 ("dossier__employe__prenom", u"Prénom"),
183 ("type_contrat__nom", u"Poste"),
184 ("type_contrat__nom", u"Type de contrat"),
185 ("date_debut", u"Date début"),
186 ("date_fin", u"Date fin"),
187 ]
188 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
189
f2d65e83 190 c = {
f0f6b03e 191 'cl' : cl,
f2d65e83
PP
192 'title': 'Rapport des contrats',
193 'contrats': contrats,
8ee135b7
JPC
194 'count': len(contrats),
195 'count_employe' : len(employes),
65e02621 196 'headers': list(h.headers()),
f2d65e83
PP
197 }
198
199 return render_to_response('rh/rapports/contrats.html', c, RequestContext(request))
e2c0b1ac
PP
200
201
02c1b3dc
JPC
202@login_required
203@drh_or_admin_required
98d6eb6c 204def rapports_masse_salariale(request):
df37184c 205
e90b19fd 206 class RechercheTemporelle(forms.Form):
aecb222b
JPC
207 CHOICE_ANNEES = range(
208 rh.Remuneration.objects.exclude(date_debut=None) \
209 .order_by('date_debut')[0].date_debut.year
210 , date.today().year + 1)
aecb222b 211
444f3223
JPC
212 annee = forms.CharField(initial=date.today().year,
213 widget=forms.Select(choices=
aecb222b 214 ((a, a) for a in reversed(CHOICE_ANNEES)
444f3223
JPC
215 ))
216 )
aecb222b 217
48c0abfe
JPC
218 region = forms.CharField(
219 widget=forms.Select(choices=[('', '')] +
220 [(i.id, i) for i in ref.Region.objects.all()]
221 )
222 )
223
224 implantation = forms.CharField(
225 widget=forms.Select(choices=[('', '')] +
226 [(i.id, i) for i in ref.Implantation.objects.all()]
227 )
228 )
229
aecb222b
JPC
230 #date_debut = forms.DateField(widget=adminwidgets.AdminDateWidget)
231 #date_fin = forms.DateField(widget=adminwidgets.AdminDateWidget)
e90b19fd
OL
232
233
234 form = RechercheTemporelle(request.GET)
235 get_filtre = [(k, v) for k,v in request.GET.items() \
236 if k not in ('date_debut', 'date_fin', 'implantation', )]
237 query_string = urllib.urlencode(get_filtre)
238
aecb222b
JPC
239 date_debut = None
240 date_fin = None
444f3223
JPC
241 if request.GET.get('annee', None):
242 date_debut = "01-01-%s" % request.GET.get('annee', None)
243 date_fin = "31-12-%s" % request.GET.get('annee', None)
df37184c 244
48c0abfe
JPC
245 implantation = request.GET.get('implantation')
246 region = request.GET.get('region')
df37184c
JPC
247
248 custom_filter = {}
249 if implantation:
250 custom_filter['dossier__poste__implantation'] = implantation
251 if region:
252 custom_filter['dossier__poste__implantation__region'] = region
253
df37184c 254 c = {
e90b19fd
OL
255 'title': 'Rapport de masse salariale',
256 'form': form,
df37184c 257 'headers': [],
e90b19fd 258 'query_string': query_string,
df37184c 259 }
22b53270 260 if date_debut or date_fin:
c99116c3
JPC
261 masse = MasseSalariale(date_debut, date_fin, custom_filter,
262 request.GET.get('ne_pas_grouper', False))
515b83c3 263 if masse.rapport:
eabb27fd
JPC
264 if request.GET.get('ods'):
265 for h in (h for h in masse.headers if 'background-color' in h[2]):
266 del h[2]['background-color']
267 masse.ods()
268 output = StringIO.StringIO()
269 masse.doc.save(output)
270 output.seek(0)
271
272 response = HttpResponse(FileWrapper(output), content_type=
273 'application/vnd.oasis.opendocument.spreadsheet')
274 response['Content-Disposition'] = \
275 'attachment; filename=Masse Salariale %s.ods' % \
276 masse.annee
277 return response
278 else:
279 c['rapport'] = masse.rapport
280 c['header_keys'] = [h[0] for h in masse.headers]
281 #on enleve le background pour le header
282 for h in (h for h in masse.headers if 'background-color' in h[2]):
283 h[2]['background'] = 'none'
284 h = SortHeaders(request, masse.headers, order_field_type="ot",
285 not_sortable=c['header_keys'], order_field="o")
286 c['headers'] = list(h.headers())
287 for key, nom, opts in masse.headers:
288 c['headers']
289 c['total'] = masse.grand_totaux[0]
290 c['total_euro'] = masse.grand_totaux[1]
291 c['colspan'] = len(c['header_keys']) - 1
292 get_filtre.append(('ods', True))
293 query_string = urllib.urlencode(get_filtre)
294 c['url_ods'] = "%s?%s" % (
295 reverse('rhr_masse_salariale'), query_string)
22b53270 296
df37184c 297 return render_to_response('rh/rapports/masse_salariale.html', c, RequestContext(request))
98d6eb6c
JPC
298
299
300@login_required
301@drh_or_admin_required
e2c0b1ac
PP
302def rapports_remuneration(request):
303
304 lookup_params = dict(request.GET.items())
9202c5db
JPC
305 if 'ot' in lookup_params:
306 del lookup_params['ot']
307 if 'o' in lookup_params:
308 del lookup_params['o']
e2c0b1ac
PP
309
310 for key, value in lookup_params.items():
311 if not isinstance(key, str):
312 # 'key' will be used as a keyword argument later, so Python
313 # requires it to be a string.
314 del lookup_params[key]
315 lookup_params[smart_str(key)] = value
316
317 employes = rh.Employe.objects.all()
9202c5db
JPC
318 if 'o' in request.GET:
319 employes = employes.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
320
e2c0b1ac
PP
321 employes = employes.filter(**lookup_params)
322
323 output = []
9202c5db
JPC
324 headers = [
325 ("id", u"# de l'employé"),
326 ("nom", u"Nom"),
327 ("prenom", u"Prénom"),
328 ("", u"Salaire"),
329 ("", u"RAS"),
330 ("", u"Indemnités"),
331 ("", u"Accessoire"),
332 ("", u"Charges patronales"),
333 ("", u"Total"),
334 ]
335 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
e2c0b1ac
PP
336
337 for employe in employes:
338 line = {}
339 output.append(line)
340
da6c523f 341 dossiers = employe.rh_dossiers.all()
e2c0b1ac
PP
342
343 remun = {}
344 remun_sum_euro = 0
345
346 for dossier in dossiers:
347 this_remun, this_remun_sum, this_remun_sum_euro = calc_remun(dossier)
348
349 for item in this_remun:
350 if item not in remun:
351 remun[item] = this_remun[item]
352 else:
353 remun[item][0] += this_remun[item][0]
354 remun[item][1] += this_remun[item][1]
355
356 remun_sum_euro += this_remun_sum_euro
357
358 line['remun_sum_euro'] = remun_sum_euro
359
360 for r in remun:
361 if r == u'Indemnité':
e2c0b1ac
PP
362 line['Indemnite'] = remun[r][1]
363 else:
364 line[r] = remun[r][1]
365
366 line['id'] = employe.id
367 line['nom'] = employe.nom
368 line['prenom'] = employe.prenom
369
370
371 c = {
372 'title': 'Rapport de remuneration',
373 'employes': output,
9202c5db 374 'headers': list(h.headers()),
e2c0b1ac
PP
375 }
376
377 return render_to_response('rh/rapports/remuneration.html', c, RequestContext(request))
3ebc0952 378
783e077a
JPC
379@login_required
380@drh_or_admin_required
c8b22fd1
JPC
381def rapports_employe_sans_contrat(request):
382
383 lookup_params = dict(request.GET.items())
384 if 'ot' in lookup_params:
385 del lookup_params['ot']
386 if 'o' in lookup_params:
387 del lookup_params['o']
388
389 for key, value in lookup_params.items():
390 if not isinstance(key, str):
391 # 'key' will be used as a keyword argument later, so Python
392 # requires it to be a string.
393 del lookup_params[key]
394 lookup_params[smart_str(key)] = value
395
396 employes_query = rh.Employe.objects
397 if 'o' in request.GET:
398 employes_query = employes_query.order_by("%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o']))
399
7c5645f0 400 employes = {}
22343fe7 401
00c9d7c2
OL
402 dossiers_en_cours = rh.Dossier.objects.filter(Q(date_fin=None) | Q(date_fin__gt=date.today()))
403 tous_contrats_echus = rh.Contrat.objects.filter(date_fin__lt=date.today(), dossier__in=dossiers_en_cours)
404 contrats = tous_contrats_echus.filter(**lookup_params).all()
405 for c in contrats:
406 if c.dossier.employe.id not in employes.keys():
407 employes[c.dossier.employe.id] = {'employe': c.dossier.employe, 'dossiers': []}
408 employes[c.dossier.employe.id]['dossiers'] += [c.dossier,]
22343fe7 409
00c9d7c2 410
c8b22fd1
JPC
411
412 headers = [
1d2d4dc2
JPC
413 ("id", u"# de l'employé"),
414 ("nom", u"Nom"),
415 ("prenom", u"Prénom"),
80518280 416 ("dossier", u"Dossiers"),
c8b22fd1 417 ]
80518280 418 h = SortHeaders(request, headers, order_field_type="ot", order_field="o", not_sortable=('dossier',))
c8b22fd1
JPC
419
420 c = {
421 'title': u'Rapport des employés sans contrat',
422 'employes': employes,
423 'count': len(employes),
424 'headers': list(h.headers()),
425 }
426
427 return render_to_response('rh/rapports/employes_sans_contrat.html', c, RequestContext(request))
428
429@login_required
430@drh_or_admin_required
857b5c24
JPC
431def rapports_postes_modelisation(request):
432 c = {}
433 data = []
3c1ba807
JPC
434
435 for f in rh.FamilleEmploi.objects.all():
436 types = rh.TypePoste.objects.filter(famille_emploi=f)
437 data_types = []
438 for t in types.all():
439 postes = rh.Poste.objects.filter(type_poste=t)
440 data_types.append({
441 'num_postes': postes.count(),
442 'postes': postes.all(),
443 'type': f,
857b5c24 444 })
3c1ba807 445
857b5c24 446 data.append({
3c1ba807
JPC
447 'famille': f,
448 'nb_types': types.count(),
449 'types' : data_types
857b5c24
JPC
450 })
451
452 c['data'] = data
453
454
455 return render_to_response('rh/rapports/postes_modelisation.html', c, RequestContext(request))
456
457
458@login_required
459@drh_or_admin_required
783e077a
JPC
460def rapports_postes_implantation(request):
461 c = {}
462 data = []
463 for r in ref.Region.objects.all():
464 implantations = []
465 for i in ref.Implantation.objects.filter(region=r):
466 implantations.append({
467 'implantation': i,
468 'postes': rh.Poste.objects.filter(implantation=i),
469 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
470 })
471 data.append({
472 'region': r,
473 'implantations': implantations
474 })
475
476 c['data'] = data
477
478
479 return render_to_response('rh/rapports/postes_implantation.html', c, RequestContext(request))
480
481
482@login_required
483@drh_or_admin_required
484def rapports_postes_service(request):
485 c = {}
9988aafb
JPC
486 data = []
487 for s in rh.Service.objects.all():
488 postes = rh.Poste.objects.filter(service=s).all()
489 num_postes = rh.Poste.objects.filter(service=s).count()
22343fe7 490 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
783e077a 491
9988aafb
JPC
492 c['data'] = data
493 return render_to_response('rh/rapports/postes_service.html', c, RequestContext(request))
783e077a
JPC
494
495
32373f2e
OL
496def region_protected(model):
497 def wrapper(func):
498 def wrapped(request, id):
32373f2e
OL
499 if request.user.is_superuser:
500 return func(request, id)
501 user_groups = request.user.groups.all()
502 if grp_drh in user_groups:
503 return func(request, id)
504 if grp_correspondants_rh in user_groups:
505 employe = get_employe_from_user(request.user)
506 q = Q(**{model.prefix_implantation: employe.implantation.region})
507 qs = model.objects.filter(q)
718abc4d 508 if int(id) in [o.id for o in qs]:
32373f2e
OL
509 return func(request, id)
510 return redirect_interdiction(request)
511 return wrapped
512 return wrapper
513
514
515@region_protected(rh.Dossier)
3ebc0952 516def dossier_apercu(request, dossier_id):
baf9b78c 517 d = get_object_or_404(rh.Dossier, pk=dossier_id)
3ebc0952 518 c = {
838bc59d 519 'title': u"Dossier %s" % (d, ),
3ebc0952 520 'is_popup' : request.GET.get('_popup', False),
baf9b78c 521 'dossier' : d,
520ab455
JPC
522 'pieces' : rh.DossierPiece.objects.filter(dossier__exact=d),
523 'contrats' : rh.Contrat.objects.filter(dossier__exact=d),
2a36598b 524 'commentaires' : rh.DossierCommentaire.objects.filter(dossier__exact=d).all(),
abf91905 525 'media_url': settings.PRIVE_MEDIA_URL,
3ebc0952
OL
526 }
527 return render_to_response('admin/rh/dossier/apercu.html', c, RequestContext(request))
4a1f2ece 528
fbe60a9d
OL
529@region_protected(rh.Poste)
530def poste_apercu(request, poste_id):
c8cb18e3 531 p = get_object_or_404(rh.Poste, pk=poste_id)
fbe60a9d 532 c = {
c8cb18e3 533 'title': u"Poste %s" % (p, ),
fbe60a9d 534 'is_popup' : request.GET.get('_popup', False),
c8cb18e3 535 'poste' : p,
0dcfc806
JPC
536 'financements' : rh.PosteFinancement.objects.filter(poste=poste_id).all(),
537 'pieces' : rh.PostePiece.objects.filter(poste=poste_id).all(),
538 'dossiers' : rh.Dossier.objects.filter(poste=poste_id).order_by("-date_debut").all(),
539 'comparaisons' : rh.PosteComparaison.objects.filter(poste=poste_id).all(),
540 'commentaires' : rh.PosteCommentaire.objects.filter(poste=poste_id).all(),
abf91905 541 'media_url': settings.PRIVE_MEDIA_URL,
fbe60a9d
OL
542 }
543 return render_to_response('admin/rh/poste/apercu.html', c, RequestContext(request))
544
4a1f2ece
OL
545def employe_apercu(request, employe_id):
546 employe = get_object_or_404(rh.Employe, pk=employe_id)
fbe60a9d 547 user_groups = request.user.groups.all()
fbe60a9d
OL
548 dossiers = None
549
550 if request.user.is_superuser or \
551 grp_drh in user_groups:
552 q = Q(employe=employe)
553 if grp_correspondants_rh in user_groups:
7eeafa57 554 regions = [d.poste.implantation.region for d in employe.rh_dossiers.all()]
fbe60a9d 555 q = Q(employe=employe) & Q(implantation__region__in=regions)
22343fe7
OL
556
557 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
558
4a1f2ece 559 c = {
ce740bb5 560 'title': u"Employe %s" % (employe, ),
4a1f2ece
OL
561 'is_popup' : request.GET.get('_popup', False),
562 'employe' : employe,
fbe60a9d 563 'dossiers' : dossiers,
abf91905 564 'media_url': settings.PRIVE_MEDIA_URL,
4a1f2ece
OL
565 }
566 return render_to_response('admin/rh/employe/apercu.html', c, RequestContext(request))
150d83ec 567
77bd83d1
JPC
568@login_required
569@drh_or_admin_required
56264a85 570def organigrammes_employe(request, id, level="all"):
08faf06e
JPC
571
572 poste = get_object_or_404(rh.Poste, pk=id)
5c0f1778
JPC
573 dossiers_by_poste = dict((d.poste_id, d) for d in rh.Dossier.objects.select_related('employe', 'poste').all())
574 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
575
576 e = dossiers_by_poste[poste.id].employe
577 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
58014aec 578 graph = pgv.AGraph()
5c0f1778 579
f187a10f 580 if rh.Poste.objects.filter(responsable=poste).count() > 0:
58014aec
JPC
581 postes_handle = [poste]
582 while postes_handle:
583 postes_handle = rh.Poste.objects.select_related('implantation').filter((Q(date_fin__gt=date.today()) | Q(date_fin=None)) & (Q(date_debut__lt=date.today()) | Q(date_debut=None)) ).filter(responsable__in=postes_handle).exclude(supprime=True).exclude(responsable=None).all()
32373f2e 584
58014aec
JPC
585 for p in postes_handle:
586 if p.responsable_id != p.id:
587 graph.add_edge(dossiers_by_poste[p.responsable_id].poste_id, p.id)
13ad5ad5 588
f187a10f 589 else:
5c0f1778
JPC
590 graph.add_node(poste.id)
591
4afec2e1
JPC
592 if level != "all":
593 postes_niveau = [poste.id]
594 for niveau in range(int(level)):
595 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
596
597 while postes_niveau:
598 postes_niveau = [p.id for p in rh.Poste.objects.filter(responsable__in=postes_niveau).all()]
599 if postes_niveau:
600 for p in postes_niveau:
601 if graph.has_node(p):
4cc81304 602 graph.delete_node(p)
4afec2e1 603
58014aec 604 a = graph
4afec2e1 605 a.name = name.encode('ascii', 'xmlcharrefreplace')
5c0f1778
JPC
606
607 poste_remontant = poste
608 while poste_remontant.responsable_id:
609 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
610 poste_remontant = poste_remontant.responsable
611
612 rh_graph.bind_poste_to_graph(a, postes_by_id)
613 #a.graph_attr['normalize'] = True
614 #a.graph_attr['level'] = 2
615 a.layout(prog='dot')
616
617 svg = a.draw(format='svg')
618
619 c = {
620 'svg': svg
621 }
a251ac8d
JPC
622
623 if 'forcer' in request.GET:
624 response = HttpResponse(svg, mimetype='image/svg+xml')
625 response['Content-Disposition'] = 'attachment; filename=organigramme.svg'
626 return response
627
c548bef6 628 return render_to_response('rh/organigrammes/employe.html', c, RequestContext(request), mimetype="image/svg+xml")
5c0f1778
JPC
629
630
631@login_required
632@drh_or_admin_required
633def organigrammes_service(request, id):
634
635 service = get_object_or_404(rh.Service, pk=id)
82af5c19
JPC
636 svg = rh_graph.organigramme_postes_cluster( \
637 cluster_filter={"service": service}, \
638 titre=u"Organigramme du service %s" % service.nom,
639 cluster_titre=service.nom)
5c0f1778 640
82af5c19
JPC
641 c = {
642 'svg': svg
643 }
5c0f1778 644
6dec02db 645 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
5c0f1778 646
82af5c19
JPC
647@login_required
648@drh_or_admin_required
649def organigrammes_implantation(request, id):
5c0f1778 650
82af5c19
JPC
651 implantation = get_object_or_404(ref.Implantation, pk=id)
652 svg = rh_graph.organigramme_postes_cluster( \
653 cluster_filter={"implantation": implantation}, \
654 titre=u"Organigramme de l'implantation %s" % implantation.nom,
655 cluster_titre=implantation.nom)
5c0f1778
JPC
656
657 c = {
658 'svg': svg
659 }
660
6dec02db 661 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")
5c0f1778 662
9da4c195
JPC
663@login_required
664@drh_or_admin_required
665def organigrammes_region(request, id):
666
667 region = get_object_or_404(ref.Region, pk=id)
668 svg = rh_graph.organigramme_postes_cluster( \
669 cluster_filter={"implantation__region": region}, \
670 titre=u"Organigramme du bureau de %s" % region.nom,
671 cluster_titre=region.nom)
672
673 c = {
674 'svg': svg
675 }
676
677 return render_to_response('rh/organigrammes/vide.html', c, RequestContext(request), mimetype="image/svg+xml")