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