import avec project.
[auf_rh_dae.git] / project / dae / views.py
CommitLineData
5d680e84 1# -*- encoding: utf-8 -*-
f87fe1a1
OL
2
3import datetime
8e30e17f 4from datetime import date
3feae3c6 5from simplejson import dumps
139686f2 6
5a1f75cb
EMS
7from django.contrib import messages
8from django.contrib.auth.decorators import login_required
9from django.contrib.contenttypes.models import ContentType
3f5cbabe 10from django.core.exceptions import MultipleObjectsReturned
44055779 11from django.core.paginator import Paginator, InvalidPage
5a1f75cb 12from django.db.models import Q
86f1e48d 13from django.http import Http404, HttpResponse, HttpResponseGone
5d680e84 14from django.shortcuts import redirect, render_to_response, get_object_or_404
90716392 15from django.template import RequestContext
75f0e87b 16
e3563bcf
EMS
17from sendfile import sendfile
18
75f0e87b
DB
19from auf.django.permissions.decorators import get_object
20
5a1f75cb
EMS
21from project.dae import models as dae
22from project.dae.decorators import \
23 redirect_interdiction, dae_groupe_requis, \
8684fcaa
EMS
24 poste_dans_ma_region_ou_service, \
25 dossier_dans_ma_region_ou_service, \
26 vieux_dossier_dans_ma_region_ou_service, \
27 employe_dans_ma_region_ou_service, \
28 dossier_est_modifiable, \
29 poste_est_modifiable, get_contrat
5a1f75cb
EMS
30from project.dae.forms import \
31 PosteWorkflowForm, PosteForm, FinancementForm, PostePieceForm, \
32 PosteComparaisonFormSet, DossierWorkflowForm, ChoosePosteForm, \
33 EmployeForm, DossierForm, DossierPieceForm, \
34 DossierComparaisonFormSet, RemunForm, ContratForm, DAENumeriseeForm, \
cbfd7bd4 35 label_poste_display, DAEFinaliseesSearchForm
5a1f75cb
EMS
36from project.dae.mail import send_drh_finalisation_mail
37from project.dae.workflow import \
38 DOSSIER_ETAT_FINALISE, DOSSIER_ETAT_REGION_FINALISATION, \
39 DOSSIER_ETAT_DRH_FINALISATION, POSTE_ETAT_FINALISE
40from project.rh import models as rh
8684fcaa 41
ed1982f3 42
0a085c42
OL
43def devises():
44 liste = []
45 for d in rh.Devise.objects.all():
46 annee = date.today().year
47 taux = rh.TauxChange.objects.filter(annee=annee, devise=d)
48 data = {}
49 if len(taux) == 0:
50 data['taux_euro'] = 0
51 else:
52 data['taux_euro'] = taux[0].taux
378ffe6c 53 data['devise_code'] = d.id
0a085c42
OL
54 liste.append(data)
55 return liste
56
5a1f75cb 57
5633fa41 58@dae_groupe_requis
5d680e84
NC
59def index(request):
60 return render_to_response('dae/index.html', {}, RequestContext(request))
61
e3563bcf
EMS
62
63### POSTE
64
5633fa41
OL
65@dae_groupe_requis
66@poste_dans_ma_region_ou_service
c0413a6f
OL
67def poste_consulter(request, key):
68 source, id = key.split('-')
69 poste = get_object_or_404(dae.Poste, pk=id)
8684fcaa 70
e6f52402 71 if request.POST:
5a1f75cb
EMS
72 validationForm = PosteWorkflowForm(
73 request.POST, instance=poste, request=request
74 )
e6f52402
OL
75 if validationForm.is_valid():
76 validationForm.save()
5a1f75cb
EMS
77 messages.add_message(
78 request, messages.SUCCESS, "La validation a été enregistrée."
79 )
18c6d4c0 80 return redirect('dae_postes_liste')
e6f52402
OL
81 else:
82 validationForm = PosteWorkflowForm(instance=poste, request=request)
8684fcaa 83
5a1f75cb
EMS
84 comparaisons_internes = \
85 poste.dae_comparaisons_internes.ma_region_ou_service(request.user)
1de3da13
EMS
86 vars = {
87 'poste': poste,
88 'validationForm': validationForm,
89 'comparaisons_internes': comparaisons_internes
90 }
868a9322 91
5a1f75cb
EMS
92 return render_to_response(
93 'dae/poste_consulter.html', vars, RequestContext(request)
94 )
95
c0413a6f 96
6fcc7644
EMS
97def poste_importer(request, id):
98 poste_dae = get_object_or_404(dae.Poste, id=id)
99 if request.method == 'POST':
100 if 'confirmer' in request.POST:
101 poste_rh = poste_dae.importer_dans_rh()
102 return redirect('admin:rh_poste_change', poste_rh.id)
103 else:
104 return redirect('poste_consulter', 'dae-' + id)
105 else:
106 return render_to_response('dae/poste_importer.html', {
107 'poste': poste_dae
108 }, RequestContext(request))
109
110
5633fa41 111@dae_groupe_requis
1b217058 112@poste_dans_ma_region_ou_service
6e80b20c 113@poste_est_modifiable
3ed49093 114def poste(request, key=None):
5d680e84
NC
115 """ Formulaire pour un poste.
116
117 Permet de créer ou modifier un poste. Si le poste n'existe que dans rh_v1
118 il est automatiquement copié dans dae.
119
120 """
121 poste, data, vars = None, dict(), dict()
122
3ed49093 123 if key:
5d680e84 124 # Poste existant
3ed49093 125 data['poste'] = key
139686f2 126 source, id = key.split('-')
5d680e84 127
139686f2 128 if source == 'dae':
5d680e84 129 poste = get_object_or_404(dae.Poste, pk=id)
139686f2
NC
130 elif source == 'rh':
131 p = get_object_or_404(rh.Poste, pk=id)
5d680e84
NC
132 # Initialisation avec les valeurs du poste de rh_v1
133 poste = dae.Poste(id_rh=p, nom=p.type_poste.nom)
f614ca5c 134 for field in ('implantation', 'type_poste', ):
5d680e84 135 setattr(poste, field, getattr(p, field))
3ed49093
NC
136 else:
137 # Nouveau poste
138 vars['new'] = True
5d680e84
NC
139
140 if request.POST:
3ed49093 141 data.update(dict(request.POST.items()))
f258e4e7 142 form = PosteForm(data, instance=poste, request=request)
151e7bd0 143 financementForm = FinancementForm(request.POST, instance=poste)
5a1f75cb
EMS
144 piecesForm = PostePieceForm(
145 request.POST, request.FILES, instance=poste
146 )
c4bfc2a0
EMS
147 if isinstance(poste, dae.Poste):
148 comparaisons_formset = PosteComparaisonFormSet(
149 request.POST,
5a1f75cb
EMS
150 queryset=poste.dae_comparaisons_internes.ma_region_ou_service(
151 request.user
152 )
c4bfc2a0
EMS
153 )
154 else:
155 comparaisons_formset = PosteComparaisonFormSet(
156 request.POST,
157 queryset=dae.PosteComparaison.objects.none()
158 )
5a1f75cb
EMS
159 if form.is_valid() and piecesForm.is_valid() and \
160 financementForm.is_valid() and comparaisons_formset.is_valid():
5d680e84 161 poste = form.save()
eb8c3edb
OL
162 piecesForm.instance = poste
163 piecesForm.save()
151e7bd0
OL
164 financementForm.instance = poste
165 financementForm.save()
320d7584
EMS
166
167 # Ne remplacer que les comparaisons de ma région
168 comparaisons = comparaisons_formset.save(commit=False)
169 for comparaison in comparaisons:
170 comparaison.poste = poste
171 comparaison.save()
172
5a1f75cb
EMS
173 messages.add_message(
174 request, messages.SUCCESS,
175 "Le poste %s a été sauvegardé." % poste
176 )
177 if 'save' in request.POST:
5bc760f9
OL
178 return redirect('poste_consulter', key='dae-%s' % poste.id)
179 else:
180 return redirect('poste', key='dae-%s' % poste.id)
8684fcaa 181
9cb4de55 182 else:
5a1f75cb
EMS
183 messages.add_message(
184 request, messages.ERROR,
185 'Il y a des erreurs dans le formulaire.'
186 )
8684fcaa 187
5d680e84
NC
188 else:
189 # 'initial' évite la validation prémature lors d'une copie de poste de
190 # rh_v1 vers dae.
f258e4e7 191 form = PosteForm(initial=data, instance=poste, request=request)
36341125 192 piecesForm = PostePieceForm(instance=poste)
151e7bd0 193 financementForm = FinancementForm(instance=poste)
829eb351
EMS
194 if isinstance(poste, dae.Poste):
195 comparaisons_formset = PosteComparaisonFormSet(
5a1f75cb
EMS
196 queryset=poste.dae_comparaisons_internes.ma_region_ou_service(
197 request.user
198 )
829eb351
EMS
199 )
200 else:
201 comparaisons_formset = PosteComparaisonFormSet(
202 queryset=dae.PosteComparaison.objects.none()
203 )
5d680e84 204
320d7584
EMS
205 vars.update(dict(
206 form=form, poste=poste, poste_key=key, piecesForm=piecesForm,
207 financementForm=financementForm,
208 comparaisons_formset=comparaisons_formset
209 ))
5d680e84
NC
210
211 return render_to_response('dae/poste.html', vars, RequestContext(request))
3ed49093 212
5a1f75cb 213
5633fa41 214@dae_groupe_requis
498881f4 215def postes_liste(request):
0f23302a 216 """ Liste des postes. """
92741270
EMS
217 content_type = ContentType.objects.get_for_model(dae.Poste)
218 extra_select = {'derniere_validation': (
219 "SELECT MAX(date) FROM workflow_workflowcommentaire "
5a1f75cb
EMS
220 "WHERE content_type_id = '%s' AND object_id = dae_poste.id" %
221 content_type.id
92741270
EMS
222 )}
223 postes_a_traiter = dae.Poste.objects.mes_choses_a_faire(request.user) \
224 .extra(select=extra_select).order_by('-date_creation')
225 postes_en_cours = dae.Poste.objects.ma_region_ou_service(request.user) \
5a1f75cb
EMS
226 .extra(select=extra_select) \
227 .filter(~Q(etat=POSTE_ETAT_FINALISE)) \
228 .order_by('-date_creation')
92741270
EMS
229 return render_to_response('dae/postes_liste.html', {
230 'postes_a_traiter': postes_a_traiter,
231 'postes_en_cours': postes_en_cours,
232 }, RequestContext(request))
98d51b59 233
5a1f75cb 234
e3563bcf 235@login_required
67a94eaf 236def poste_piece(request, id, filename):
e3563bcf
EMS
237 """Téléchargement d'une pièce jointe à un poste."""
238 piece = get_object_or_404(dae.PostePiece, pk=id)
5a1f75cb
EMS
239 if dae.Poste.objects.ma_region_ou_service(request.user) \
240 .filter(id=piece.poste_id).exists():
67a94eaf 241 return sendfile(request, piece.fichier.path)
e3563bcf
EMS
242 else:
243 return redirect_interdiction(request)
244
245
246### DOSSIER
247
cb1d62b5 248def filtered_type_remun():
5a1f75cb
EMS
249 defaut = (2, 3, 8, 17) # salaire de base, indemnité de fonction,
250 # charges patronales
0a085c42 251 return rh.TypeRemuneration.objects.filter(pk__in=defaut)
cb1d62b5 252
5a1f75cb 253
5633fa41 254@dae_groupe_requis
62d3903d 255@dossier_dans_ma_region_ou_service
5d5a57a4
OL
256def embauche_consulter(request, dossier_id):
257 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
8684fcaa 258 etat_precedent = dossier.etat
e6f52402
OL
259
260 if request.POST:
5a1f75cb
EMS
261 validationForm = DossierWorkflowForm(
262 request.POST, instance=dossier, request=request
263 )
e6f52402 264 if validationForm.is_valid():
8684fcaa 265 if etat_precedent == DOSSIER_ETAT_REGION_FINALISATION and \
5a1f75cb
EMS
266 validationForm.cleaned_data['etat'] == \
267 DOSSIER_ETAT_DRH_FINALISATION:
8684fcaa 268 send_drh_finalisation_mail(request, dossier)
e6f52402 269 validationForm.save()
5a1f75cb
EMS
270 messages.add_message(
271 request, messages.SUCCESS, "La validation a été enregistrée."
272 )
18c6d4c0 273 return redirect('dae_embauches_liste')
e6f52402
OL
274 else:
275 validationForm = DossierWorkflowForm(instance=dossier, request=request)
9536ea21 276
5a1f75cb
EMS
277 comparaisons_internes = \
278 dossier.poste.dae_comparaisons_internes.ma_region_ou_service(
279 request.user
280 )
a4125771 281 comparaisons = dossier.dae_comparaisons.ma_region_ou_service(request.user)
5d5a57a4 282 vars = {
291bbfd9
EMS
283 'dossier': dossier,
284 'validationForm': validationForm,
320d7584
EMS
285 'comparaisons_internes': comparaisons_internes,
286 'comparaisons': comparaisons
287 }
3a33b1ce 288
5a1f75cb
EMS
289 return render_to_response(
290 'dae/embauche_consulter.html', vars, RequestContext(request)
291 )
292
5d5a57a4 293
5633fa41 294@dae_groupe_requis
fb0ed970
EMS
295@dossier_dans_ma_region_ou_service
296def embauche_importer(request, dossier_id=None):
297 dossier_dae = get_object_or_404(dae.Dossier, id=dossier_id)
47b60f16
EMS
298 if request.method == 'POST':
299 if 'confirmer' in request.POST:
300 dossier_rh = dossier_dae.importer_dans_rh()
301 return redirect('admin:rh_dossier_change', dossier_rh.id)
302 else:
303 return redirect('embauches_finalisees')
304 else:
305 return render_to_response('dae/embauche_importer.html', {
306 'dossier': dossier_dae
307 }, RequestContext(request))
fb0ed970
EMS
308
309
310@dae_groupe_requis
577dcb77
EMS
311def embauche_choisir_poste(request):
312 return render_to_response('dae/embauche-choisir-poste.html', {
313 'form': ChoosePosteForm(request=request)
314 }, RequestContext(request))
315
5a1f75cb 316
577dcb77 317@dae_groupe_requis
62d3903d 318@dossier_dans_ma_region_ou_service
62cfa562 319@dossier_est_modifiable
62d3903d 320def embauche(request, key=None, dossier_id=None):
139686f2 321 """ Formulaire d'autorisation d'embauche. """
139686f2 322
577dcb77
EMS
323 # Récupérer ou créer un poste et un dossier
324 source, id = key.split('-')
325 if source != 'dae':
326 return Http404
327 poste = get_object_or_404(dae.Poste, pk=id)
328
329 if request.POST:
330 if request.POST['employe'] == '':
331 # Nouvel employé
332 employe = dae.Employe()
333 else:
334 employe_source, id = request.POST['employe'].split('-')
335 if employe_source == 'dae':
336 # Employé DAE
337 employe = get_object_or_404(dae.Employe, pk=id)
338 elif employe_source == 'rh':
339 # Employé RH, on le copie dans DAE
340 e = get_object_or_404(rh.Employe, pk=id)
341 employe = dae.Employe(id_rh=e, prenom=e.prenom, nom=e.nom,
342 genre=e.genre)
139686f2 343 else:
577dcb77
EMS
344 raise Http404
345
5a1f75cb
EMS
346 employe_form = EmployeForm(
347 request.POST, instance=employe, request=request
348 )
577dcb77
EMS
349
350 if employe_form.is_valid():
351 data = dict(request.POST.items())
352 employe = employe_form.save()
353 data['employe'] = 'dae-%s' % employe.id
354 employe_form = EmployeForm(data, instance=employe, request=request)
355
356 if not dossier_id:
357 dossier = dae.Dossier(poste=poste, employe=employe)
358 else:
359 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
16b1454e 360 dossier.employe = employe_form.instance
577dcb77
EMS
361
362 dossier_form = DossierForm(request.POST, instance=dossier)
5a1f75cb
EMS
363 piecesForm = DossierPieceForm(
364 request.POST, request.FILES, instance=dossier
365 )
320d7584
EMS
366 comparaisons_formset = DossierComparaisonFormSet(
367 request.POST,
5a1f75cb
EMS
368 queryset=dossier.dae_comparaisons.ma_region_ou_service(
369 request.user
370 )
320d7584 371 )
577dcb77
EMS
372 remunForm = RemunForm(request.POST, instance=dossier)
373
55360d7d
EMS
374 if employe_form.is_valid() and \
375 dossier_form.is_valid() and \
577dcb77 376 piecesForm.is_valid() and \
320d7584 377 comparaisons_formset.is_valid() and \
577dcb77
EMS
378 remunForm.is_valid():
379 employe.save()
55360d7d 380 dossier_form.save()
577dcb77 381 piecesForm.save()
577dcb77 382 remunForm.save()
320d7584
EMS
383
384 # Ne remplacer que les comparaisons de ma région
385 comparaisons = comparaisons_formset.save(commit=False)
386 for comparaison in comparaisons:
387 comparaison.dossier = dossier
388 comparaison.save()
389
5a1f75cb
EMS
390 messages.success(
391 request, "Le dossier %s a été sauvegardé." % dossier
392 )
393 if 'save' in request.POST:
577dcb77 394 return redirect('embauche_consulter', dossier_id=dossier.id)
768d7e1b 395 else:
5a1f75cb
EMS
396 return redirect(
397 'embauche', key=dossier.poste.key, dossier_id=dossier.id
398 )
9536ea21 399
577dcb77 400 else:
5a1f75cb
EMS
401 messages.add_message(
402 request, messages.ERROR,
403 'Il y a des erreurs dans le formulaire.'
404 )
9536ea21 405
577dcb77
EMS
406 else:
407 # Initialisation d'un formulaire vide
408 if dossier_id:
409 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
410 employe = dossier.employe
411 data = dict(employe='dae-%s' % employe.id)
5a1f75cb
EMS
412 employe_form = EmployeForm(
413 initial=data, instance=employe, request=request
414 )
ed1982f3
NC
415 else:
416 dossier_rh = rh.Dossier()
417 poste_rh = poste.id_rh
577dcb77
EMS
418 dossier = pre_filled_dossier(dossier_rh, 'new', poste_rh)
419 employe_form = EmployeForm(request=request)
420
421 dossier_form = DossierForm(instance=dossier)
422 piecesForm = DossierPieceForm(instance=dossier)
320d7584 423 comparaisons_formset = DossierComparaisonFormSet(
5a1f75cb
EMS
424 queryset=dossier.dae_comparaisons.ma_region_ou_service(
425 request.user
426 )
320d7584 427 )
577dcb77
EMS
428 remunForm = RemunForm(instance=dossier)
429
829eb351 430 try:
5a1f75cb
EMS
431 comparaisons_internes = \
432 dossier.poste.dae_comparaisons_internes.ma_region_ou_service(
433 request.user
434 )
829eb351
EMS
435 except dae.Poste.DoesNotExist:
436 comparaisons_internes = []
437
577dcb77
EMS
438 return render_to_response('dae/embauche.html', {
439 'type_remun': filtered_type_remun(),
440 'devises': devises(),
441 'poste': poste,
442 'dossier': dossier,
443 'piecesForm': piecesForm,
444 'remunForm': remunForm,
320d7584 445 'comparaisons_formset': comparaisons_formset,
291bbfd9
EMS
446 'forms': dict(employe=employe_form, dossier=dossier_form, ),
447 'comparaisons_internes': comparaisons_internes
577dcb77 448 }, RequestContext(request))
139686f2 449
5a1f75cb 450
5633fa41 451@dae_groupe_requis
62d3903d 452@dossier_dans_ma_region_ou_service
0140cbd2 453def embauches_liste(request):
454 """ Liste des embauches. """
92741270
EMS
455 content_type = ContentType.objects.get_for_model(dae.Dossier)
456 extra_select = {'derniere_validation': (
457 "SELECT MAX(date) FROM workflow_workflowcommentaire "
5a1f75cb
EMS
458 "WHERE content_type_id = '%s' AND object_id = dae_dossier.id" %
459 content_type.id
92741270 460 )}
5a1f75cb
EMS
461 embauches_a_traiter = dae.Dossier.objects \
462 .mes_choses_a_faire(request.user) \
92741270 463 .extra(select=extra_select).order_by('-date_creation')
5a1f75cb
EMS
464 embauches_en_cours = dae.Dossier.objects \
465 .ma_region_ou_service(request.user) \
466 .extra(select=extra_select) \
467 .order_by('-date_creation') \
468 .exclude(etat=DOSSIER_ETAT_FINALISE)
92741270
EMS
469 return render_to_response('dae/embauches_liste.html', {
470 'embauches_a_traiter': embauches_a_traiter,
471 'embauches_en_cours': embauches_en_cours,
472 }, RequestContext(request))
355c80c8 473
5a1f75cb 474
44055779
EMS
475@dae_groupe_requis
476def embauches_finalisees(request):
477 """Liste des embauches finalisées."""
bed096fc
EMS
478
479 ### POST
480
481 if request.method == 'POST':
482 if 'supprimer' in request.POST:
483 ids = request.POST.getlist('ids')
484 dossiers = dae.Dossier.objects.filter(id__in=ids)
485 count = dossiers.count()
486 if count > 0:
487 dossiers.delete()
488 messages.success(request, u'%d dossiers supprimés' % count)
489 return redirect(request.get_full_path())
490
491 ### GET
492
44055779
EMS
493 embauches = dae.Dossier.objects.ma_region_ou_service(request.user) \
494 .filter(etat=DOSSIER_ETAT_FINALISE)
495
cbfd7bd4
EMS
496 # Recherche
497 search_form = DAEFinaliseesSearchForm(request.GET)
498 if search_form.is_valid():
499 q = search_form.cleaned_data.get('q').strip()
500 importees = search_form.cleaned_data.get('importees')
501 if q:
502 criteria = [
503 Q(poste__implantation__region__nom__icontains=word) |
504 Q(poste__implantation__region__code=word) |
505 Q(poste__implantation__nom__icontains=word) |
506 Q(poste__nom__icontains=word) |
507 Q(employe__nom__icontains=word) |
508 Q(employe__prenom__icontains=word)
509 for word in q.split()
510 ]
511 embauches = embauches.filter(*criteria)
512 if importees == 'oui':
513 embauches = embauches.exclude(dossier_rh=None)
514 elif importees == 'non':
515 embauches = embauches.filter(dossier_rh=None)
516
44055779
EMS
517 # Tri
518 tri = request.GET.get('tri', None)
7652a4c3 519 if tri and tri.startswith('-'):
44055779
EMS
520 dir = '-'
521 tri = tri[1:]
522 else:
523 dir = ''
524 if tri == 'region':
5a1f75cb
EMS
525 embauches = embauches.order_by(
526 dir + 'poste__implantation__region__nom'
527 )
44055779
EMS
528 elif tri == 'implantation':
529 embauches = embauches.order_by(dir + 'poste__implantation__nom')
530 elif tri == 'poste':
531 embauches = embauches.order_by(dir + 'poste__nom')
532 elif tri == 'personne':
8684fcaa
EMS
533 embauches = embauches.order_by(dir + 'employe__nom',
534 dir + 'employe__prenom')
44055779
EMS
535 elif tri == 'date_debut':
536 embauches = embauches.order_by(dir + 'debut_contrat')
537 elif tri == 'date_fin':
538 embauches = embauches.order_by(dir + 'fin_contrat')
539
540 # Pagination
541 paginator = Paginator(embauches, 20)
542 try:
543 page = paginator.page(request.GET.get('page', 1))
544 except InvalidPage:
545 page = paginator.page(1)
546
547 return render_to_response('dae/embauches_finalisees.html', {
cbfd7bd4
EMS
548 'embauches': page,
549 'search_form': search_form
44055779
EMS
550 }, RequestContext(request))
551
5a1f75cb 552
139686f2
NC
553def employe(request, key):
554 """ Récupération AJAX de l'employé pour la page d'embauche. """
555 data = dict(employe=key)
556
557 if key == '':
558 # Nouvel employé
559 employe = dae.Employe()
560 else:
561 # Employé existant
562 source, id = key.split('-')
563
564 if source == 'dae':
565 employe = get_object_or_404(dae.Employe, pk=id)
566 elif source == 'rh':
567 e = get_object_or_404(rh.Employe, id=id)
568 # Initialisation avec les valeurs de l'employé de rh_v1
569 employe = dae.Employe(id_rh=e)
570 for field in ('prenom', 'nom', 'genre'):
571 setattr(employe, field, getattr(e, field))
572
5a1f75cb
EMS
573 return HttpResponse(
574 EmployeForm(initial=data, instance=employe, request=request).as_table()
575 )
576
139686f2 577
9536ea21
EMS
578### CONTRATS
579
580@dae_groupe_requis
581@get_contrat
67a94eaf
EMS
582def contrat(request, contrat, filename):
583 return sendfile(request, contrat.fichier.path)
9536ea21 584
5a1f75cb 585
9536ea21
EMS
586@dae_groupe_requis
587@get_contrat
588def contrat_supprimer(request, contrat):
589 if request.method == 'POST':
590 if 'oui' in request.POST:
591 contrat.delete()
592 return redirect('embauche_consulter', dossier_id=contrat.dossier.id)
593 return render_to_response('dae/contrat-supprimer.html', {
594 'contrat': contrat
595 }, RequestContext(request))
596
5a1f75cb 597
9536ea21
EMS
598@dae_groupe_requis
599@dossier_dans_ma_region_ou_service
600def embauche_ajouter_contrat(request, dossier_id=None):
601 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
602 if request.method == 'POST':
603 form = ContratForm(request.POST, request.FILES)
604 if form.is_valid():
605 contrat = form.save(commit=False)
606 contrat.dossier = dossier
9dfa4296
OL
607 contrat.date_debut = dossier.contrat_date_debut
608 contrat.date_fin = dossier.contrat_date_fin
9536ea21
EMS
609 contrat.save()
610 return redirect('embauche_consulter', dossier_id=dossier.id)
611 else:
612 form = ContratForm()
613 return render_to_response('dae/embauche-ajouter-contrat.html', {
614 'form': form
615 }, RequestContext(request))
616
5a1f75cb 617
c3f0b49f
EMS
618### DAE NUMERISEE
619
620@get_object(dae.Dossier, 'consulter')
621def dae_numerisee(request, dossier):
622 return sendfile(request, dossier.dae_numerisee.path)
623
5a1f75cb 624
c3f0b49f
EMS
625@get_object(dae.Dossier, 'modifier_dae_numerisee')
626def dae_numerisee_modifier(request, dossier):
627 if request.method == 'POST':
628 form = DAENumeriseeForm(request.POST, request.FILES, instance=dossier)
629 if form.is_valid():
630 form.save()
631 return redirect('embauche_consulter', dossier_id=dossier.id)
632 else:
633 form = DAENumeriseeForm(instance=dossier)
634 return render_to_response('dae/dae_numerisee_modifier.html', {
635 'form': form
636 }, RequestContext(request))
637
5a1f75cb 638
c3f0b49f
EMS
639@get_object(dae.Dossier, 'modifier_dae_numerisee')
640def dae_numerisee_supprimer(request, dossier):
641 if request.method == 'POST':
642 if 'oui' in request.POST:
643 dossier.dae_numerisee = None
644 dossier.save()
645 return redirect('embauche_consulter', dossier_id=dossier.id)
5a1f75cb
EMS
646 return render_to_response(
647 'dae/dae_numerisee_supprimer.html', {}, RequestContext(request)
648 )
649
c3f0b49f 650
04380fba 651# AJAX SECURISE
5a1f75cb 652
04380fba
OL
653@dae_groupe_requis
654@employe_dans_ma_region_ou_service
139686f2
NC
655def dossier(request, poste_key, employe_key):
656 """ Récupération AJAX du dossier pour la page d'embauche. """
657 data = dict()
658
659 poste_source, poste_id = poste_key.split('-')
660 poste = get_object_or_404(dae.Poste, pk=poste_id)
179f6b49
OL
661
662 # Récupérer la devise de l'implantation lié au poste
663 implantation_devise = poste.get_default_devise()
5a1f75cb 664 data.update({'devise': implantation_devise})
9536ea21 665
e27db04c
OL
666 if poste.id_rh_id is not None:
667 poste_rh = get_object_or_404(rh.Poste, pk=poste.id_rh_id)
668 else:
669 poste_rh = None
139686f2 670
eabaed81 671 # NOUVEL EMPLOYE
139686f2
NC
672 if employe_key == '':
673 employe_source = 'new'
eabaed81 674 employe = None
139686f2 675 dossier_rh = rh.Dossier()
ed1982f3 676 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
139686f2 677
eabaed81 678 # EMPLOYE DAE
eabaed81 679 if employe_key.startswith('dae'):
5a1f75cb
EMS
680 employe_source, employe_id = employe_key.split('-')
681 employe_dae = get_object_or_404(dae.Employe, pk=employe_id)
682
683 # récupération de l'ancien dossier rh v1 pour l'employe DAE
684 try:
685 dossier_rh = rh.Dossier.objects.get(
686 employe=employe_dae.id_rh_id, date_fin=None
687 )
688 except (rh.Dossier.DoesNotExist):
689 dossier_rh = rh.Dossier()
690
691 # on tente de récupérer le dossier DAE, au pire on le contruit en le
692 # prépoluant avec son dossier rh v1.
693 try:
694 dossier = dae.Dossier.objects.get(employe=employe_dae, poste=poste)
695 except (dae.Dossier.DoesNotExist):
696 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
697 employe = employe_dae.id_rh
698
eabaed81 699 # EMPLOYE RH v1
eabaed81 700 if employe_key.startswith('rh'):
5a1f75cb
EMS
701 employe_source, employe_id = employe_key.split('-')
702 employe_rh = get_object_or_404(rh.Employe, pk=employe_id)
703
704 # récupération de l'ancien dossier rh v1 pour l'employe rh v1, s'il
705 # n'en a pas, on en fournit un nouveau qui servira uniquement un
706 # créer un nouveau dossier DAE.
707 try:
708 dossier_rh = rh.Dossier.objects.get(
709 employe=employe_rh, date_fin=None
710 )
711 except (rh.Dossier.DoesNotExist):
712 dossier_rh = rh.Dossier()
713 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
714 employe = employe_rh
da3ca955 715
eabaed81
OL
716 dossier_form = DossierForm(initial=data, instance=dossier)
717 vars = dict(form=dossier_form, poste=poste, employe=employe)
da3ca955 718 return render_to_response('dae/embauche-dossier.html', vars,
719 RequestContext(request))
139686f2 720
5a1f75cb
EMS
721
722# Cette fonction est appelée à partir de fonctions déjà sécurisée
ed1982f3
NC
723def pre_filled_dossier(dossier_rh, employe_source, poste_rh):
724 dossier = dae.Dossier()
725
726 if employe_source != 'new' and dossier_rh.id:
727 dossier.statut_anterieur = dossier_rh.statut
728
729 # Certains dossiers ont un classement à zéro
730 if dossier_rh.classement_id > 0:
731 dossier.classement_anterieur = dossier_rh.classement
732
733 # Récupération du salaire de base
5a1f75cb
EMS
734 remun = dossier_rh.remunerations() \
735 .filter(type=1).order_by('-date_debut')
ed1982f3
NC
736 if remun:
737 dossier.salaire_anterieur = remun[0].montant
80bcc96b 738 dossier.devise_anterieur = remun[0].devise
ed1982f3
NC
739
740 # Récupération du titulaire précédent
741 try:
09aa8374 742 dossiers = rh.Dossier.objects.order_by('-date_debut')
32f26ff3 743 if poste_rh:
09aa8374 744 dossiers = dossiers.filter(poste=poste_rh)
32f26ff3
AJ
745 else:
746 dossiers = rh.Dossier.objects.none()
ed1982f3
NC
747 if len(dossiers):
748 # Ce bloc ignore toutes les erreurs, car les données de rh
749 # manquantes peuvent en générer
750 d = dossiers[0]
751 try:
752 titulaire = d.employe
753 dossier.employe_anterieur = titulaire
754 dossier.classement_titulaire_anterieur = d.classement
755 dossier.statut_titulaire_anterieur = d.statut
5a1f75cb
EMS
756 remun = d.remunerations().filter(type=1) \
757 .order_by('-date_debut')[0]
80bcc96b
OL
758 dossier.salaire_titulaire_anterieur = remun.montant
759 dossier.devise_titulaire_anterieur = remun.devise
ed1982f3
NC
760 except:
761 pass
762 # TODO: afficher l'info, les champs ne sont pas dans le
763 # modèle dae.Dossier: nom, prenom, classement, salaire
764 pass
765
766 except (rh.Dossier.DoesNotExist):
767 dossier_rh = rh.Dossier()
768
769 return dossier
770
5a1f75cb 771
04380fba 772@dae_groupe_requis
c0492570 773@vieux_dossier_dans_ma_region_ou_service
04380fba 774def dossier_resume(request, dossier_id=None):
04380fba
OL
775 try:
776 dossier = rh.Dossier.objects.get(id=dossier_id)
777 except:
778 return HttpResponseGone("Ce dossier n'est pas accessible")
f87fe1a1 779
04380fba
OL
780 data = {}
781 data['personne'] = unicode(dossier.employe)
0ebb99b3 782 data['classement'] = dossier.classement.id
09aa8374
OL
783 if dossier.statut is not None:
784 data['statut'] = dossier.statut.id
785 data['implantation'] = dossier.poste.implantation.id
5a1f75cb
EMS
786 data['poste'] = u"%s %s" % (
787 dossier.poste.type_poste.nom, dossier.poste.nom
788 )
09aa8374 789 salaire = dossier.get_salaire()
a4125771 790 if salaire is not None:
5a64aab4 791 data['montant'] = float(salaire.montant)
a4125771
OL
792 else:
793 data['montant'] = None
794 if salaire is not None and salaire.devise is not None:
10b6780c 795 data['devise'] = salaire.devise.id
e84c8ef1 796 data['montant_euros'] = salaire.montant_euros()
f87fe1a1 797 else:
04380fba
OL
798 data['devise'] = None
799 data['montant_euros'] = 0
85668061 800 return HttpResponse(dumps(data))
f87fe1a1 801
5a1f75cb 802
068d1462
OL
803@dae_groupe_requis
804@vieux_dossier_dans_ma_region_ou_service
805def poste_resume(request, dossier_id=None):
806 """
807 On travaille, en réalité sur le dossier mais on cache
808 l'identité de la personne.
809 """
810 try:
811 dossier = rh.Dossier.objects.get(id=dossier_id)
812 except:
813 return HttpResponseGone("Ce dossier n'est pas accessible")
814
3f5cbabe 815 salaire = dossier.get_salaire()
068d1462 816 data = {}
09aa8374 817 data['implantation'] = dossier.poste.implantation.id
5a1f75cb
EMS
818 data['poste'] = u"%s %s" % (
819 dossier.poste.type_poste.nom, dossier.poste.nom
820 )
068d1462
OL
821 if salaire is not None:
822 data['devise'] = salaire.devise.id
e503e64d 823 data['montant'] = float(salaire.montant)
e84c8ef1 824 data['montant_euros'] = salaire.montant_euros()
068d1462
OL
825 else:
826 data['devise'] = None
e503e64d
OL
827 data['montant'] = ""
828 data['montant_euros'] = ""
5d84008f
OL
829 data['statut'] = dossier.statut_id
830 data['classement'] = dossier.classement_id
068d1462
OL
831 return HttpResponse(dumps(data))
832
5a1f75cb 833
6d047148 834def liste_postes(request):
8684fcaa 835 """ Appel AJAX :
6d047148
OL
836 input : implantation_id
837 output : JSON liste de valeur point
838 """
839 method = request.method
840 params = getattr(request, method, [])
841 data = []
842
843 # Voir le code de _poste_choices dans forms.py
5a1f75cb
EMS
844 copies = dae.Poste.objects.exclude(id_rh__isnull=True) \
845 .filter(etat=POSTE_ETAT_FINALISE)
aa512122 846 rh_postes_actifs = rh.Poste.objects.all()
6d047148 847
5a1f75cb
EMS
848 if 'implantation_id' in params \
849 and params.get('implantation_id') is not u"":
6d047148 850 implantation_id = params.get('implantation_id')
6d047148 851 copies = copies.filter(implantation__id=implantation_id)
5a1f75cb
EMS
852 rh_postes_actifs = rh_postes_actifs.filter(
853 implantation__id=implantation_id
854 )
9536ea21 855
6d047148
OL
856 id_copies = [p.id_rh_id for p in copies.all()]
857 rhv1 = rh_postes_actifs.exclude(id__in=id_copies)
858 rhv1 = rhv1.select_related(depth=1)
4bce4d24 859
5a1f75cb
EMS
860 data = [('', 'Nouveau poste')] + \
861 sorted([('rh-%s' % p.id, label_poste_display(p)) for p in rhv1],
862 key=lambda t: t[1])
6d047148
OL
863 return HttpResponse(dumps(data))
864
5a1f75cb 865
e3563bcf 866@login_required
67a94eaf 867def dossier_piece(request, id, filename):
e3563bcf
EMS
868 """Téléchargement d'une pièce jointe à un poste."""
869 piece = get_object_or_404(dae.DossierPiece, pk=id)
5a1f75cb
EMS
870 if dae.Dossier.objects.ma_region_ou_service(request.user) \
871 .filter(id=piece.dossier_id).exists():
67a94eaf 872 return sendfile(request, piece.fichier.path)
e3563bcf
EMS
873 else:
874 return redirect_interdiction(request)
875
5a1f75cb 876
04380fba 877# AJAX SECURITE non nécessaire
5a1f75cb 878
04380fba 879def coefficient(request):
9536ea21 880 """ Appel AJAX :
04380fba
OL
881 input : classement
882 output : coefficient
883 """
884 method = request.method
885 params = getattr(request, method, [])
886 data = dict()
887 if 'classement' in params and params.get('classement') is not u"":
888 classement = params.get('classement')
889 classement = rh.Classement.objects.get(pk=classement)
890 data['coefficient'] = classement.coefficient
891 else:
892 data['coefficient'] = 0
893 return HttpResponse(dumps(data))
894
895
3d627bfd 896def devise(request):
8684fcaa 897 """ Appel AJAX :
3d627bfd 898 input : valeur_point
8e30e17f 899 output : devise, devise_code, taux_euro
3d627bfd 900 """
f87fe1a1
OL
901 method = request.method
902 params = getattr(request, method, [])
3d627bfd 903 data = dict()
8684fcaa 904 if 'valeur_point' in params and params.get('valeur_point') is not u"":
f87fe1a1 905 valeur_point = params.get('valeur_point')
3d627bfd 906 valeur_point = rh.ValeurPoint.objects.get(pk=valeur_point)
907 annee = valeur_point.annee
3f5cbabe 908 try:
5a1f75cb
EMS
909 taux = rh.TauxChange.objects.get(
910 annee=annee, devise=valeur_point.devise
911 )
3f5cbabe 912 except MultipleObjectsReturned:
5a1f75cb
EMS
913 return HttpResponseGone(
914 u"Il existe plusieurs taux pour la devise %s "
915 u"cette année-là : %s" % (valeur_point.devise.code, annee)
916 )
3f5cbabe 917
3d627bfd 918 data['devise'] = taux.devise.id
f87fe1a1 919 data['valeur'] = valeur_point.valeur
3d627bfd 920 data['devise_code'] = taux.devise.code
8e30e17f 921 data['taux_euro'] = taux.taux
be3c51e9
OL
922 else:
923 return HttpResponseGone("Vous devez choisir une valeur de point")
3d627bfd 924 return HttpResponse(dumps(data))
9536ea21 925
5a1f75cb 926
3d627bfd 927def devise_code(request):
8684fcaa 928 """ Appel AJAX :
3d627bfd 929 input : devise
8e30e17f 930 output : devise_code, taux_euro
3d627bfd 931 """
f87fe1a1
OL
932 method = request.method
933 params = getattr(request, method, [])
3d627bfd 934 data = dict()
f87fe1a1
OL
935 if 'devise' in params:
936 devise = params.get('devise')
3d627bfd 937 devise = rh.Devise.objects.get(pk=devise)
8e30e17f 938 annee = date.today().year
939 taux = rh.TauxChange.objects.filter(annee=annee, devise=devise)
86f1e48d
OL
940 if len(taux) == 0:
941 return HttpResponseGone("Le taux n'est pas disponible")
3d627bfd 942 data['devise_code'] = devise.code
8e30e17f 943 data['taux_euro'] = taux[0].taux
3d627bfd 944 return HttpResponse(dumps(data))
85668061 945
5a1f75cb 946
cb1d62b5
NC
947def add_remun(request, dossier, type_remun):
948 dossier = get_object_or_404(dae.Dossier, pk=dossier)
949 type_remun = get_object_or_404(rh.TypeRemuneration, pk=type_remun)
950 dae.Remuneration(dossier=dossier, devise=dossier.devise,
951 type=type_remun).save()
952
953 return render_to_response('dae/embauche-remun.html', dict(dossier=dossier),
954 RequestContext(request))
03b395db 955
5a1f75cb 956
04380fba
OL
957def salaire(request, implantation, devise, classement):
958 if not devise or not classement:
959 raise Http404
960
04380fba 961 taux = rh.TauxChange.objects.filter(devise=devise).order_by('-annee')
5a1f75cb
EMS
962 vp = rh.ValeurPoint.objects \
963 .filter(implantation=implantation, devise=devise) \
964 .order_by('-annee')
aa512122
OL
965
966 if vp.count() == 0:
967 raise Exception(u"pas de valeur de point pour le couple\
968 implantation/devise (%s/%s)" % (implantation, devise))
969
970 if taux.count() == 0:
971 raise Exception(u"Pas de taux pour la devise %s" % devise)
04380fba
OL
972
973 classement = get_object_or_404(rh.Classement, pk=classement)
e2968ebb
EMS
974 if classement.coefficient is None:
975 raise Http404
90716392 976 taux, vp = taux[0].taux, vp[0].valeur
04380fba 977
90716392 978 salaire_euro = round(vp * classement.coefficient * taux, 2)
04380fba
OL
979 data = dict(salaire_euro=salaire_euro, taux=taux,
980 salaire_devise=round(salaire_euro / taux, 2))
981
982 return HttpResponse(dumps(data))
983
5a1f75cb 984
04380fba 985def liste_valeurs_point(request):
8684fcaa 986 """ Appel AJAX :
04380fba
OL
987 input : implantation_id
988 output : JSON liste de valeur point
03b395db 989 """
04380fba
OL
990 method = request.method
991 params = getattr(request, method, [])
992 data = []
993 annee_courante = datetime.datetime.now().year
5a1f75cb
EMS
994 if 'implantation_id' in params \
995 and params.get('implantation_id') is not u"":
04380fba 996 implantation_id = params.get('implantation_id')
5a1f75cb
EMS
997 preselectionne = rh.ValeurPoint.objects \
998 .filter(implantation=implantation_id, annee=annee_courante) \
999 .order_by("-annee")
7ad0549c 1000 for o in preselectionne:
5a1f75cb
EMS
1001 data.append({
1002 'id': o.id,
1003 'label': o.__unicode__(),
1004 'devise': o.devise_id,
1005 'suggestion': True
1006 })
b1f7765e 1007 else:
7ad0549c
OL
1008 preselectionne = rh.ValeurPoint.objects.none()
1009
5a1f75cb
EMS
1010 liste_complete = rh.ValeurPoint.objects \
1011 .filter(annee__in=(annee_courante,)) \
1012 .order_by("-annee")
7ad0549c 1013 for o in liste_complete.exclude(id__in=[p.id for p in preselectionne]):
5a1f75cb
EMS
1014 data.append({
1015 'id': o.id,
1016 'label': o.__unicode__(),
1017 'devise': o.devise_id,
1018 'suggestion': False
1019 })
3f5cbabe 1020 return HttpResponse(dumps(data, indent=4))