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