Fix django ajax selects
[auf_rh_dae.git] / project / rh / views.py
1 # -*- encoding: utf-8 -*-
2
3 import urllib
4 from datetime import date
5 from itertools import izip
6 import StringIO
7
8 import pygraphviz as pgv
9 from datamaster_modeles import models as ref
10 from django.core.urlresolvers import reverse
11 from django.db.models import Q
12 from django.utils.encoding import smart_str
13 from django.shortcuts import render_to_response, get_object_or_404
14 from django.template import RequestContext
15 from django.http import HttpResponse
16 from django import forms
17 from django.contrib.auth.decorators import login_required
18 from django.core.servers.basehttp import FileWrapper
19
20 from rh import models as rh
21 from rh.lib import calc_remun
22 from project.rh.decorators import drh_or_admin_required, in_one_of_group
23 from rh.templatetags.rapports import SortHeaders
24 from rh.change_list import RechercheTemporelle
25 from rh import graph as rh_graph
26 from rh.masse_salariale import MasseSalariale
27
28 # pas de reference a DAE devrait etre refactorisé
29 from dae.utils import get_employe_from_user
30 from dae.decorators import redirect_interdiction
31 from django.conf import settings
32 from project.rh.decorators import in_drh_or_admin
33 from project.rh import groups
34
35
36 @login_required
37 @drh_or_admin_required
38 def profil(request):
39 """Profil personnel de l'employé - éditable"""
40 rc = RequestContext(request)
41 c = {}
42
43 employe = rc['this_employe']
44
45 c['user'] = request.user
46 c['employe'] = employe
47 return render_to_response('rh/profil.html', c, rc)
48
49
50 @login_required
51 @drh_or_admin_required
52 def employes_liste(request):
53 """Liste des employés."""
54 today = date.today()
55 employes = rh.Employe.objects \
56 .exclude(dossiers__date_debut__gt=today) \
57 .exclude(dossiers__date_fin__lt=today) \
58 .order_by('nom')
59 c = {
60 'user': request.user,
61 'employes': employes,
62 }
63 return render_to_response('rh/employes_liste.html',
64 c,
65 RequestContext(request))
66
67
68 @login_required
69 @drh_or_admin_required
70 def employe(request, id):
71 """Information publique sur un employé."""
72 try:
73 employe = rh.Employe.objects.get(pk=id)
74 except:
75 employe = rh.Employe.objects.none()
76 c = {
77 'user': request.user,
78 'employe': employe,
79 }
80 return render_to_response('rh/employe.html', c, RequestContext(request))
81
82
83 @login_required
84 @drh_or_admin_required
85 def rapports_poste(request):
86
87 lookup_params = dict(request.GET.items())
88
89 for key, value in lookup_params.items():
90 if key == 'o' or key == 'ot':
91 del lookup_params[key]
92 continue
93 if not isinstance(key, str):
94 # 'key' will be used as a keyword argument later, so Python
95 # requires it to be a string.
96 del lookup_params[key]
97 lookup_params[smart_str(key)] = value
98
99 if key == 'comble':
100 del lookup_params[key]
101
102 sort_order = 'ASC' if request.GET.get('ot') == 'asc' else 'DESC'
103
104 postes = rh.Poste.objects.select_related('implantation') \
105 .extra(select={
106 'employe_id':
107 'SELECT GROUP_CONCAT(employe SEPARATOR "|") '
108 'FROM rh_dossier '
109 'WHERE poste = rh_poste.id '
110 'AND rh_dossier.date_fin IS NULL ' + (
111 'ORDER BY employe ' + sort_order
112 if request.GET.get('o') == 'employe_id' else ''
113 )
114 }) \
115 .extra(select={
116 'employe_nom':
117 'SELECT GROUP_CONCAT(rh_employe.nom SEPARATOR "|") '
118 'FROM rh_dossier INNER JOIN rh_employe '
119 'ON rh_dossier.employe = rh_employe.id '
120 'WHERE poste = rh_poste.id '
121 'AND rh_dossier.date_fin IS NULL ' + (
122 'ORDER BY rh_employe.nom ' + sort_order
123 if request.GET.get('o') == 'employe_nom' else ''
124 )
125 }) \
126 .extra(select={
127 'employe_prenom':
128 'SELECT GROUP_CONCAT(rh_employe.prenom SEPARATOR "|") '
129 'FROM rh_dossier INNER JOIN rh_employe '
130 'ON rh_dossier.employe = rh_employe.id '
131 'WHERE poste = rh_poste.id '
132 'AND rh_dossier.date_fin IS NULL ' + (
133 'ORDER BY rh_employe.prenom ' + sort_order
134 if request.GET.get('o') == 'employe_prenom' else ''
135 )
136 })
137
138 postes = postes.filter(**lookup_params)
139 if 'o' in request.GET:
140 postes = postes.order_by(
141 ('-' if sort_order == "DESC" else '') + request.GET['o']
142 )
143
144 out = []
145 for p in postes:
146 out.append({
147 'id': p.id,
148 'nom': p.nom,
149 'implantation': p.implantation,
150 'employes': [] if not p.employe_id else [
151 {'id': id, 'nom': nom, 'prenom': prenom}
152 for id, nom, prenom in izip(
153 p.employe_id.split('|'),
154 p.employe_nom.split('|'),
155 p.employe_prenom.split('|')
156 )
157 ]
158 })
159
160 headers = [
161 ("id", u"# du poste"),
162 ("nom", u"Nom du poste"),
163 ("implantation__id", u"Implantation"),
164 ("employe_nom", u"Nom"),
165 ]
166 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
167 c = {
168 'title': 'Rapport des postes',
169 'postes': out,
170 'count': len(out),
171 'headers': list(h.headers()),
172 }
173
174 return render_to_response(
175 'rh/rapports/postes.html', c, RequestContext(request)
176 )
177
178
179 @login_required
180 @in_one_of_group((groups.grp_correspondants_rh,
181 groups.grp_administrateurs,
182 groups.grp_directeurs_bureau,
183 groups.grp_drh,
184 groups.grp_drh2))
185 def rapports_contrat(request):
186 if 'HTTP_REFERER' in request.META.keys():
187 referer = request.META['HTTP_REFERER']
188 referer = "/".join(referer.split('/')[3:])
189 referer = "/%s" % referer.split('?')[0]
190 if referer != reverse('rhr_contrats'):
191 params = request.GET.copy()
192 params.update({'statut': 'Actif'})
193 request.GET = params
194
195 lookup_params = dict(request.GET.items())
196 if 'ot' in lookup_params:
197 del lookup_params['ot']
198 if 'o' in lookup_params:
199 del lookup_params['o']
200
201 for key, value in lookup_params.items():
202 if not isinstance(key, str):
203 # 'key' will be used as a keyword argument later, so Python
204 # requires it to be a string.
205 del lookup_params[key]
206 lookup_params[smart_str(key)] = value
207
208 contrats = rh.Contrat.objects.select_related(
209 'dossier', 'dossier__poste', 'dossier__poste__implantation',
210 'type_contrat', 'dossier__employe'
211 )
212
213 cl = RechercheTemporelle(dict(request.GET.items()), rh.Contrat)
214 lookup_params = cl.purge_params(lookup_params)
215 q_temporel = cl.get_q_temporel(contrats)
216 q = Q(**lookup_params) & q_temporel
217 user_groups = request.user.groups.all()
218 if groups.grp_correspondants_rh in user_groups or\
219 groups.grp_administrateurs in user_groups or\
220 groups.grp_directeurs_bureau in user_groups:
221 employe = get_employe_from_user(request.user)
222 q = q & Q(dossier__poste__implantation__region=employe.implantation.region)
223
224 contrats = contrats.filter(q).exclude(dossier__employe__supprime=1)
225
226 if 'o' in request.GET:
227 contrats = contrats.order_by(
228 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
229 )
230
231 employes = set([c.dossier.employe_id for c in contrats])
232
233 headers = [
234 ("dossier__employe__id", u"# de l'employé"),
235 ("dossier__employe__nom", u"Employé"),
236 ("type_contrat__nom", u"Poste"),
237 ("dossier__poste__implantation__region", u"Région"),
238 ("dossier__poste__implantation", u"Implantation"),
239 ("type_contrat__nom", u"Type de contrat"),
240 ("dossier__statut_residence", u"Statut de résidence"),
241 ("date_debut", u"Date début"),
242 ("date_fin", u"Date fin"),
243 ]
244 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
245
246 c = {
247 'cl': cl,
248 'title': 'Rapport des contrats',
249 'contrats': contrats,
250 'count': len(contrats),
251 'count_employe': len(employes),
252 'headers': list(h.headers()),
253 }
254
255 return render_to_response(
256 'rh/rapports/contrats.html', c, RequestContext(request)
257 )
258
259
260 @login_required
261 @in_one_of_group((groups.grp_correspondants_rh,
262 groups.grp_administrateurs,
263 groups.grp_directeurs_bureau,
264 groups.grp_drh,
265 groups.grp_drh2))
266 def rapports_masse_salariale(request):
267
268 class RechercheTemporelle(forms.Form):
269 remunerations = rh.Remuneration.objects.exclude(date_debut=None)
270 if len(remunerations) > 0:
271 annee_debut = remunerations.order_by('date_debut')[0].date_debut.year
272 else:
273 annee_debut = 1982
274 CHOICE_ANNEES = range(annee_debut, date.today().year + 1)
275
276 annee = forms.CharField(
277 initial=date.today().year,
278 widget=forms.Select(
279 choices=((a, a) for a in reversed(CHOICE_ANNEES))
280 )
281 )
282
283 user_groups = request.user.groups.all()
284 if groups.grp_correspondants_rh in user_groups or\
285 groups.grp_administrateurs in user_groups or\
286 groups.grp_directeurs_bureau in user_groups:
287 employe = get_employe_from_user(request.user)
288 regions = ref.Region.objects.filter(id=employe.implantation.region.id)
289 implantations = ref.Implantation.objects.filter(region=employe.implantation.region)
290 else:
291 regions = ref.Region.objects.all()
292 implantations = ref.Implantation.objects.all()
293
294 region = forms.CharField(
295 widget=forms.Select(choices=[('', '')] +
296 [(i.id, i) for i in regions]
297 )
298 )
299
300 implantation = forms.CharField(
301 widget=forms.Select(choices=[('', '')] +
302 [(i.id, i) for i in implantations]
303 )
304 )
305
306 #date_debut = forms.DateField(widget=adminwidgets.AdminDateWidget)
307 #date_fin = forms.DateField(widget=adminwidgets.AdminDateWidget)
308
309 form = RechercheTemporelle(request.GET)
310 get_filtre = [
311 (k, v) for k, v in request.GET.items()
312 if k not in ('date_debut', 'date_fin', 'implantation')
313 ]
314 query_string = urllib.urlencode(get_filtre)
315
316 date_debut = None
317 date_fin = None
318 if request.GET.get('annee', None):
319 date_debut = "01-01-%s" % request.GET.get('annee', None)
320 date_fin = "31-12-%s" % request.GET.get('annee', None)
321
322 implantation = request.GET.get('implantation')
323 region = request.GET.get('region')
324
325 custom_filter = {}
326 if implantation:
327 custom_filter['dossier__poste__implantation'] = implantation
328 if region:
329 custom_filter['dossier__poste__implantation__region'] = region
330
331 # on force la région dans tous les cas pour les membres de ce groupe
332 user_groups = request.user.groups.all()
333 if groups.grp_correspondants_rh in user_groups or\
334 groups.grp_administrateurs in user_groups or\
335 groups.grp_directeurs_bureau in user_groups:
336 employe = get_employe_from_user(request.user)
337 custom_filter['dossier__poste__implantation__region'] = employe.implantation.region.id
338
339
340 c = {
341 'title': 'Rapport de masse salariale',
342 'form': form,
343 'headers': [],
344 'query_string': query_string,
345 }
346 if date_debut or date_fin:
347 masse = MasseSalariale(date_debut, date_fin, custom_filter,
348 request.GET.get('ne_pas_grouper', False))
349 if masse.rapport:
350 if request.GET.get('ods'):
351 for h in (
352 h for h in masse.headers if 'background-color' in h[2]
353 ):
354 del h[2]['background-color']
355 masse.ods()
356 output = StringIO.StringIO()
357 masse.doc.save(output)
358 output.seek(0)
359
360 response = HttpResponse(
361 FileWrapper(output),
362 content_type=(
363 'application/vnd.oasis.opendocument.spreadsheet'
364 )
365 )
366 response['Content-Disposition'] = \
367 'attachment; filename=Masse Salariale %s.ods' % \
368 masse.annee
369 return response
370 else:
371 c['rapport'] = masse.rapport
372 c['header_keys'] = [h[0] for h in masse.headers]
373 #on enleve le background pour le header
374 for h in (
375 h for h in masse.headers if 'background-color' in h[2]
376 ):
377 h[2]['background'] = 'none'
378 h = SortHeaders(request, masse.headers, order_field_type="ot",
379 not_sortable=c['header_keys'], order_field="o")
380 c['headers'] = list(h.headers())
381 for key, nom, opts in masse.headers:
382 c['headers']
383 c['total'] = masse.grand_totaux[0]
384 c['total_euro'] = masse.grand_totaux[1]
385 c['colspan'] = len(c['header_keys']) - 1
386 get_filtre.append(('ods', True))
387 query_string = urllib.urlencode(get_filtre)
388 c['url_ods'] = "%s?%s" % (
389 reverse('rhr_masse_salariale'), query_string)
390
391 return render_to_response(
392 'rh/rapports/masse_salariale.html', c, RequestContext(request)
393 )
394
395
396 @login_required
397 @drh_or_admin_required
398 def rapports_remuneration(request):
399
400 lookup_params = dict(request.GET.items())
401 if 'ot' in lookup_params:
402 del lookup_params['ot']
403 if 'o' in lookup_params:
404 del lookup_params['o']
405
406 for key, value in lookup_params.items():
407 if not isinstance(key, str):
408 # 'key' will be used as a keyword argument later, so Python
409 # requires it to be a string.
410 del lookup_params[key]
411 lookup_params[smart_str(key)] = value
412
413 employes = rh.Employe.objects.all()
414 if 'o' in request.GET:
415 employes = employes.order_by(
416 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
417 )
418
419 employes = employes.filter(**lookup_params)
420
421 output = []
422 headers = [
423 ("id", u"# de l'employé"),
424 ("nom", u"Nom"),
425 ("prenom", u"Prénom"),
426 ("", u"Salaire"),
427 ("", u"RAS"),
428 ("", u"Indemnités"),
429 ("", u"Accessoire"),
430 ("", u"Charges patronales"),
431 ("", u"Total"),
432 ]
433 h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
434
435 for employe in employes:
436 line = {}
437 output.append(line)
438
439 dossiers = employe.rh_dossiers.all()
440
441 remun = {}
442 remun_sum_euro = 0
443
444 for dossier in dossiers:
445 this_remun, this_remun_sum, this_remun_sum_euro = \
446 calc_remun(dossier)
447
448 for item in this_remun:
449 if item not in remun:
450 remun[item] = this_remun[item]
451 else:
452 remun[item][0] += this_remun[item][0]
453 remun[item][1] += this_remun[item][1]
454
455 remun_sum_euro += this_remun_sum_euro
456
457 line['remun_sum_euro'] = remun_sum_euro
458
459 for r in remun:
460 if r == u'Indemnité':
461 line['Indemnite'] = remun[r][1]
462 else:
463 line[r] = remun[r][1]
464
465 line['id'] = employe.id
466 line['nom'] = employe.nom
467 line['prenom'] = employe.prenom
468
469 c = {
470 'title': 'Rapport de remuneration',
471 'employes': output,
472 'headers': list(h.headers()),
473 }
474
475 return render_to_response(
476 'rh/rapports/remuneration.html', c, RequestContext(request)
477 )
478
479
480 @login_required
481 @in_one_of_group((groups.grp_correspondants_rh,
482 groups.grp_administrateurs,
483 groups.grp_directeurs_bureau,
484 groups.grp_drh,
485 groups.grp_drh2))
486 def rapports_employe_sans_contrat(request):
487
488 lookup_params = dict(request.GET.items())
489 if 'ot' in lookup_params:
490 del lookup_params['ot']
491 if 'o' in lookup_params:
492 del lookup_params['o']
493
494 for key, value in lookup_params.items():
495 if not isinstance(key, str):
496 # 'key' will be used as a keyword argument later, so Python
497 # requires it to be a string.
498 del lookup_params[key]
499 lookup_params[smart_str(key)] = value
500
501 employes_query = rh.Employe.objects
502 if 'o' in request.GET:
503 employes_query = employes_query.order_by(
504 ('-' if request.GET.get('ot') == "desc" else '') + request.GET['o']
505 )
506
507 employes = {}
508
509 user_groups = request.user.groups.all()
510 q_region = Q()
511 if groups.grp_correspondants_rh in user_groups or\
512 groups.grp_administrateurs in user_groups or\
513 groups.grp_directeurs_bureau in user_groups:
514 employe = get_employe_from_user(request.user)
515 q_region = Q(poste__implantation__region=employe.implantation.region)
516
517 dossiers_en_cours = rh.Dossier.objects.filter(q_region & (
518 Q(date_fin=None) | Q(date_fin__gt=date.today()))
519 )
520 tous_contrats_echus = rh.Contrat.objects.filter(
521 date_fin__lt=date.today(), dossier__in=dossiers_en_cours
522 )
523 contrats = tous_contrats_echus.filter(**lookup_params).all()
524 for c in contrats:
525 if c.dossier.employe.id not in employes.keys():
526 employes[c.dossier.employe.id] = {
527 'employe': c.dossier.employe,
528 'dossiers': []
529 }
530 employes[c.dossier.employe.id]['dossiers'] += [c.dossier]
531
532 headers = [
533 ("id", u"# de l'employé"),
534 ("nom", u"Nom"),
535 ("prenom", u"Prénom"),
536 ("dossier", u"Dossiers"),
537 ]
538 h = SortHeaders(
539 request, headers, order_field_type="ot", order_field="o",
540 not_sortable=('dossier',)
541 )
542
543 c = {
544 'title': u'Rapport des employés sans contrat',
545 'employes': employes,
546 'count': len(employes),
547 'headers': list(h.headers()),
548 }
549
550 return render_to_response(
551 'rh/rapports/employes_sans_contrat.html', c, RequestContext(request)
552 )
553
554
555 @login_required
556 @drh_or_admin_required
557 def rapports_postes_modelisation(request):
558 c = {}
559 data = []
560
561 for categorie in rh.CategorieEmploi.objects.all():
562 types = rh.TypePoste.objects.filter(categorie_emploi=categorie)
563 data_types = []
564 for t in types.all():
565 postes = rh.Poste.objects.filter(type_poste=t)
566 data_types.append({
567 'num_postes': postes.count(),
568 'postes': postes.all(),
569 'type': categorie,
570 })
571
572 data.append({
573 'categorie': categorie,
574 'nb_types': types.count(),
575 'types': data_types
576 })
577
578 c['data'] = data
579
580 return render_to_response(
581 'rh/rapports/postes_modelisation.html', c, RequestContext(request)
582 )
583
584
585 @login_required
586 @drh_or_admin_required
587 def rapports_postes_implantation(request):
588 c = {}
589 data = []
590 for r in ref.Region.objects.all():
591 implantations = []
592 for i in ref.Implantation.objects.filter(region=r):
593 implantations.append({
594 'implantation': i,
595 'postes': rh.Poste.objects.filter(implantation=i),
596 'num_postes': rh.Poste.objects.filter(implantation=i).count(),
597 })
598 data.append({
599 'region': r,
600 'implantations': implantations
601 })
602
603 c['data'] = data
604
605 return render_to_response(
606 'rh/rapports/postes_implantation.html', c, RequestContext(request)
607 )
608
609
610 @login_required
611 @drh_or_admin_required
612 def rapports_postes_service(request):
613 c = {}
614 data = []
615 for s in rh.Service.objects.all():
616 postes = rh.Poste.objects.filter(service=s).all()
617 num_postes = rh.Poste.objects.filter(service=s).count()
618 data.append({'service': s, 'num_postes': num_postes, 'postes': postes})
619
620 c['data'] = data
621 return render_to_response(
622 'rh/rapports/postes_service.html', c, RequestContext(request)
623 )
624
625
626 def region_protected(model):
627 def wrapper(func):
628 def wrapped(request, id):
629 if request.user.is_superuser:
630 return func(request, id)
631 user_groups = request.user.groups.all()
632 if in_drh_or_admin(request.user):
633 return func(request, id)
634 if groups.grp_correspondants_rh in user_groups or\
635 groups.grp_administrateurs in user_groups or\
636 groups.grp_directeurs_bureau in user_groups:
637 employe = get_employe_from_user(request.user)
638 q = Q(**{
639 model.prefix_implantation: employe.implantation.region
640 })
641 qs = model.objects.filter(q)
642 if int(id) in [o.id for o in qs]:
643 return func(request, id)
644 return redirect_interdiction(request)
645 return wrapped
646 return wrapper
647
648
649 @region_protected(rh.Dossier)
650 def dossier_apercu(request, dossier_id):
651 d = get_object_or_404(rh.Dossier, pk=dossier_id)
652 c = {
653 'title': u"Dossier %s" % (d, ),
654 'is_popup': request.GET.get('_popup', False),
655 'dossier': d,
656 'pieces': rh.DossierPiece.objects.filter(dossier__exact=d),
657 'contrats': rh.Contrat.objects.filter(dossier__exact=d),
658 'commentaires': rh.DossierCommentaire.objects.filter(dossier=d).all(),
659 'media_url': settings.PRIVE_MEDIA_URL,
660 }
661 return render_to_response(
662 'admin/rh/dossier/apercu.html', c, RequestContext(request)
663 )
664
665
666 @region_protected(rh.Poste)
667 def poste_apercu(request, poste_id):
668 p = get_object_or_404(rh.Poste, pk=poste_id)
669 c = {
670 'title': u"Poste %s" % (p, ),
671 'is_popup': request.GET.get('_popup', False),
672 'poste': p,
673 'financements': (
674 rh.PosteFinancement.objects.filter(poste=poste_id).all()
675 ),
676 'pieces': rh.PostePiece.objects.filter(poste=poste_id).all(),
677 'dossiers': (
678 rh.Dossier.objects.filter(poste=poste_id)
679 .order_by("-date_debut").all()
680 ),
681 'comparaisons': (
682 rh.PosteComparaison.objects.filter(poste=poste_id).all()
683 ),
684 'commentaires': (
685 rh.PosteCommentaire.objects.filter(poste=poste_id).all()
686 ),
687 'media_url': settings.PRIVE_MEDIA_URL,
688 }
689 return render_to_response(
690 'admin/rh/poste/apercu.html', c, RequestContext(request)
691 )
692
693 @region_protected(rh.Employe)
694 def employe_apercu(request, employe_id):
695 employe = get_object_or_404(rh.Employe, pk=employe_id)
696 user_groups = request.user.groups.all()
697 dossiers = None
698
699 if in_drh_or_admin(request.user):
700 q = Q(employe=employe)
701
702 if groups.grp_correspondants_rh in user_groups or\
703 groups.grp_administrateurs in user_groups or\
704 groups.grp_directeurs_bureau in user_groups:
705 employe_connecte = get_employe_from_user(request.user)
706 q = Q(employe=employe) & Q(poste__implantation__region=employe_connecte.implantation.region)
707
708 dossiers = rh.Dossier.objects.filter(q).order_by('-date_debut')
709
710 c = {
711 'title': u"Employe %s" % (employe, ),
712 'is_popup': request.GET.get('_popup', False),
713 'employe': employe,
714 'dossiers': dossiers,
715 'media_url': settings.PRIVE_MEDIA_URL,
716 }
717 return render_to_response(
718 'admin/rh/employe/apercu.html', c, RequestContext(request)
719 )
720
721
722 @login_required
723 @in_one_of_group((groups.grp_correspondants_rh,
724 groups.grp_administrateurs,
725 groups.grp_directeurs_bureau,
726 groups.grp_drh,
727 groups.grp_drh2))
728 def organigrammes_employe(request, id, level="all"):
729
730 poste = get_object_or_404(rh.Poste, pk=id)
731 dossiers_by_poste = dict(
732 (d.poste_id, d)
733 for d in rh.Dossier.objects.select_related('employe', 'poste').all()
734 )
735 postes_by_id = dict((p.id, p) for p in rh.Poste.objects.all())
736
737 e = dossiers_by_poste[poste.id].employe
738 name = u"Organigramme de [%s] %s %s" % (e.id, e.nom.upper(), e.prenom)
739 graph = pgv.AGraph()
740
741 if rh.Poste.objects.filter(responsable=poste).count() > 0:
742 postes_handle = [poste]
743 while postes_handle:
744 postes_handle = rh.Poste.objects.select_related('implantation') \
745 .filter(
746 Q(date_fin__gt=date.today()) | Q(date_fin=None),
747 Q(date_debut__lt=date.today()) | Q(date_debut=None),
748 responsable__in=postes_handle
749 ).exclude(supprime=True).exclude(responsable=None).all()
750
751 for p in postes_handle:
752 if p.responsable_id != p.id:
753 graph.add_edge(
754 dossiers_by_poste[p.responsable_id].poste_id, p.id
755 )
756
757 else:
758 graph.add_node(poste.id)
759
760 if level != "all":
761 postes_niveau = [poste.id]
762 for niveau in range(int(level)):
763 postes_niveau = [
764 p.id for p in
765 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
766 ]
767
768 while postes_niveau:
769 postes_niveau = [
770 p.id for p in
771 rh.Poste.objects.filter(responsable__in=postes_niveau).all()
772 ]
773 if postes_niveau:
774 for p in postes_niveau:
775 if graph.has_node(p):
776 graph.delete_node(p)
777
778 a = graph
779 a.name = name.encode('ascii', 'xmlcharrefreplace')
780
781 poste_remontant = poste
782 while poste_remontant.responsable_id:
783 a.add_edge(poste_remontant.responsable_id, poste_remontant.id)
784 poste_remontant = poste_remontant.responsable
785
786 rh_graph.bind_poste_to_graph(a, postes_by_id)
787 #a.graph_attr['normalize'] = True
788 #a.graph_attr['level'] = 2
789 a.layout(prog='dot')
790
791 svg = a.draw(format='svg')
792
793 c = {
794 'svg': svg
795 }
796
797 if 'forcer' in request.GET:
798 response = HttpResponse(svg, mimetype='image/svg+xml')
799 response['Content-Disposition'] = \
800 'attachment; filename=organigramme.svg'
801 return response
802
803 return render_to_response(
804 'rh/organigrammes/employe.html', c, RequestContext(request),
805 mimetype="image/svg+xml"
806 )
807
808
809 @login_required
810 @in_one_of_group((groups.grp_correspondants_rh,
811 groups.grp_administrateurs,
812 groups.grp_directeurs_bureau,
813 groups.grp_drh,
814 groups.grp_drh2))
815 def organigrammes_service(request, id):
816
817 service = get_object_or_404(rh.Service, pk=id)
818 svg = rh_graph.organigramme_postes_cluster( \
819 cluster_filter={"service": service}, \
820 titre=u"Organigramme du service %s" % service.nom,
821 cluster_titre=service.nom)
822
823 c = {
824 'svg': svg
825 }
826
827 return render_to_response(
828 'rh/organigrammes/vide.html', c, RequestContext(request),
829 mimetype="image/svg+xml"
830 )
831
832
833 @login_required
834 @in_one_of_group((groups.grp_correspondants_rh,
835 groups.grp_administrateurs,
836 groups.grp_directeurs_bureau,
837 groups.grp_drh,
838 groups.grp_drh2))
839 def organigrammes_implantation(request, id):
840
841 implantation = get_object_or_404(ref.Implantation, pk=id)
842 svg = rh_graph.organigramme_postes_cluster( \
843 cluster_filter={"implantation": implantation}, \
844 titre=u"Organigramme de l'implantation %s" % implantation.nom,
845 cluster_titre=implantation.nom)
846
847 c = {
848 'svg': svg
849 }
850
851 return render_to_response(
852 'rh/organigrammes/vide.html', c, RequestContext(request),
853 mimetype="image/svg+xml"
854 )
855
856
857 @login_required
858 @in_one_of_group((groups.grp_correspondants_rh,
859 groups.grp_administrateurs,
860 groups.grp_directeurs_bureau,
861 groups.grp_drh,
862 groups.grp_drh2))
863 def organigrammes_region(request, id):
864
865 region = get_object_or_404(ref.Region, pk=id)
866 svg = rh_graph.organigramme_postes_cluster( \
867 cluster_filter={"implantation__region": region}, \
868 titre=u"Organigramme du bureau de %s" % region.nom,
869 cluster_titre=region.nom)
870
871 c = {
872 'svg': svg
873 }
874
875 return render_to_response(
876 'rh/organigrammes/vide.html', c, RequestContext(request),
877 mimetype="image/svg+xml"
878 )