[#3125] Recherche dans les embauches 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."""
476 embauches = dae.Dossier.objects.ma_region_ou_service(request.user) \
477 .filter(etat=DOSSIER_ETAT_FINALISE)
478
cbfd7bd4
EMS
479 # Recherche
480 search_form = DAEFinaliseesSearchForm(request.GET)
481 if search_form.is_valid():
482 q = search_form.cleaned_data.get('q').strip()
483 importees = search_form.cleaned_data.get('importees')
484 if q:
485 criteria = [
486 Q(poste__implantation__region__nom__icontains=word) |
487 Q(poste__implantation__region__code=word) |
488 Q(poste__implantation__nom__icontains=word) |
489 Q(poste__nom__icontains=word) |
490 Q(employe__nom__icontains=word) |
491 Q(employe__prenom__icontains=word)
492 for word in q.split()
493 ]
494 embauches = embauches.filter(*criteria)
495 if importees == 'oui':
496 embauches = embauches.exclude(dossier_rh=None)
497 elif importees == 'non':
498 embauches = embauches.filter(dossier_rh=None)
499
44055779
EMS
500 # Tri
501 tri = request.GET.get('tri', None)
7652a4c3 502 if tri and tri.startswith('-'):
44055779
EMS
503 dir = '-'
504 tri = tri[1:]
505 else:
506 dir = ''
507 if tri == 'region':
5a1f75cb
EMS
508 embauches = embauches.order_by(
509 dir + 'poste__implantation__region__nom'
510 )
44055779
EMS
511 elif tri == 'implantation':
512 embauches = embauches.order_by(dir + 'poste__implantation__nom')
513 elif tri == 'poste':
514 embauches = embauches.order_by(dir + 'poste__nom')
515 elif tri == 'personne':
8684fcaa
EMS
516 embauches = embauches.order_by(dir + 'employe__nom',
517 dir + 'employe__prenom')
44055779
EMS
518 elif tri == 'date_debut':
519 embauches = embauches.order_by(dir + 'debut_contrat')
520 elif tri == 'date_fin':
521 embauches = embauches.order_by(dir + 'fin_contrat')
522
523 # Pagination
524 paginator = Paginator(embauches, 20)
525 try:
526 page = paginator.page(request.GET.get('page', 1))
527 except InvalidPage:
528 page = paginator.page(1)
529
530 return render_to_response('dae/embauches_finalisees.html', {
cbfd7bd4
EMS
531 'embauches': page,
532 'search_form': search_form
44055779
EMS
533 }, RequestContext(request))
534
5a1f75cb 535
139686f2
NC
536def employe(request, key):
537 """ Récupération AJAX de l'employé pour la page d'embauche. """
538 data = dict(employe=key)
539
540 if key == '':
541 # Nouvel employé
542 employe = dae.Employe()
543 else:
544 # Employé existant
545 source, id = key.split('-')
546
547 if source == 'dae':
548 employe = get_object_or_404(dae.Employe, pk=id)
549 elif source == 'rh':
550 e = get_object_or_404(rh.Employe, id=id)
551 # Initialisation avec les valeurs de l'employé de rh_v1
552 employe = dae.Employe(id_rh=e)
553 for field in ('prenom', 'nom', 'genre'):
554 setattr(employe, field, getattr(e, field))
555
5a1f75cb
EMS
556 return HttpResponse(
557 EmployeForm(initial=data, instance=employe, request=request).as_table()
558 )
559
139686f2 560
9536ea21
EMS
561### CONTRATS
562
563@dae_groupe_requis
564@get_contrat
67a94eaf
EMS
565def contrat(request, contrat, filename):
566 return sendfile(request, contrat.fichier.path)
9536ea21 567
5a1f75cb 568
9536ea21
EMS
569@dae_groupe_requis
570@get_contrat
571def contrat_supprimer(request, contrat):
572 if request.method == 'POST':
573 if 'oui' in request.POST:
574 contrat.delete()
575 return redirect('embauche_consulter', dossier_id=contrat.dossier.id)
576 return render_to_response('dae/contrat-supprimer.html', {
577 'contrat': contrat
578 }, RequestContext(request))
579
5a1f75cb 580
9536ea21
EMS
581@dae_groupe_requis
582@dossier_dans_ma_region_ou_service
583def embauche_ajouter_contrat(request, dossier_id=None):
584 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
585 if request.method == 'POST':
586 form = ContratForm(request.POST, request.FILES)
587 if form.is_valid():
588 contrat = form.save(commit=False)
589 contrat.dossier = dossier
9dfa4296
OL
590 contrat.date_debut = dossier.contrat_date_debut
591 contrat.date_fin = dossier.contrat_date_fin
9536ea21
EMS
592 contrat.save()
593 return redirect('embauche_consulter', dossier_id=dossier.id)
594 else:
595 form = ContratForm()
596 return render_to_response('dae/embauche-ajouter-contrat.html', {
597 'form': form
598 }, RequestContext(request))
599
5a1f75cb 600
c3f0b49f
EMS
601### DAE NUMERISEE
602
603@get_object(dae.Dossier, 'consulter')
604def dae_numerisee(request, dossier):
605 return sendfile(request, dossier.dae_numerisee.path)
606
5a1f75cb 607
c3f0b49f
EMS
608@get_object(dae.Dossier, 'modifier_dae_numerisee')
609def dae_numerisee_modifier(request, dossier):
610 if request.method == 'POST':
611 form = DAENumeriseeForm(request.POST, request.FILES, instance=dossier)
612 if form.is_valid():
613 form.save()
614 return redirect('embauche_consulter', dossier_id=dossier.id)
615 else:
616 form = DAENumeriseeForm(instance=dossier)
617 return render_to_response('dae/dae_numerisee_modifier.html', {
618 'form': form
619 }, RequestContext(request))
620
5a1f75cb 621
c3f0b49f
EMS
622@get_object(dae.Dossier, 'modifier_dae_numerisee')
623def dae_numerisee_supprimer(request, dossier):
624 if request.method == 'POST':
625 if 'oui' in request.POST:
626 dossier.dae_numerisee = None
627 dossier.save()
628 return redirect('embauche_consulter', dossier_id=dossier.id)
5a1f75cb
EMS
629 return render_to_response(
630 'dae/dae_numerisee_supprimer.html', {}, RequestContext(request)
631 )
632
c3f0b49f 633
04380fba 634# AJAX SECURISE
5a1f75cb 635
04380fba
OL
636@dae_groupe_requis
637@employe_dans_ma_region_ou_service
139686f2
NC
638def dossier(request, poste_key, employe_key):
639 """ Récupération AJAX du dossier pour la page d'embauche. """
640 data = dict()
641
642 poste_source, poste_id = poste_key.split('-')
643 poste = get_object_or_404(dae.Poste, pk=poste_id)
179f6b49
OL
644
645 # Récupérer la devise de l'implantation lié au poste
646 implantation_devise = poste.get_default_devise()
5a1f75cb 647 data.update({'devise': implantation_devise})
9536ea21 648
e27db04c
OL
649 if poste.id_rh_id is not None:
650 poste_rh = get_object_or_404(rh.Poste, pk=poste.id_rh_id)
651 else:
652 poste_rh = None
139686f2 653
eabaed81 654 # NOUVEL EMPLOYE
139686f2
NC
655 if employe_key == '':
656 employe_source = 'new'
eabaed81 657 employe = None
139686f2 658 dossier_rh = rh.Dossier()
ed1982f3 659 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
139686f2 660
eabaed81 661 # EMPLOYE DAE
eabaed81 662 if employe_key.startswith('dae'):
5a1f75cb
EMS
663 employe_source, employe_id = employe_key.split('-')
664 employe_dae = get_object_or_404(dae.Employe, pk=employe_id)
665
666 # récupération de l'ancien dossier rh v1 pour l'employe DAE
667 try:
668 dossier_rh = rh.Dossier.objects.get(
669 employe=employe_dae.id_rh_id, date_fin=None
670 )
671 except (rh.Dossier.DoesNotExist):
672 dossier_rh = rh.Dossier()
673
674 # on tente de récupérer le dossier DAE, au pire on le contruit en le
675 # prépoluant avec son dossier rh v1.
676 try:
677 dossier = dae.Dossier.objects.get(employe=employe_dae, poste=poste)
678 except (dae.Dossier.DoesNotExist):
679 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
680 employe = employe_dae.id_rh
681
eabaed81 682 # EMPLOYE RH v1
eabaed81 683 if employe_key.startswith('rh'):
5a1f75cb
EMS
684 employe_source, employe_id = employe_key.split('-')
685 employe_rh = get_object_or_404(rh.Employe, pk=employe_id)
686
687 # récupération de l'ancien dossier rh v1 pour l'employe rh v1, s'il
688 # n'en a pas, on en fournit un nouveau qui servira uniquement un
689 # créer un nouveau dossier DAE.
690 try:
691 dossier_rh = rh.Dossier.objects.get(
692 employe=employe_rh, date_fin=None
693 )
694 except (rh.Dossier.DoesNotExist):
695 dossier_rh = rh.Dossier()
696 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
697 employe = employe_rh
da3ca955 698
eabaed81
OL
699 dossier_form = DossierForm(initial=data, instance=dossier)
700 vars = dict(form=dossier_form, poste=poste, employe=employe)
da3ca955 701 return render_to_response('dae/embauche-dossier.html', vars,
702 RequestContext(request))
139686f2 703
5a1f75cb
EMS
704
705# Cette fonction est appelée à partir de fonctions déjà sécurisée
ed1982f3
NC
706def pre_filled_dossier(dossier_rh, employe_source, poste_rh):
707 dossier = dae.Dossier()
708
709 if employe_source != 'new' and dossier_rh.id:
710 dossier.statut_anterieur = dossier_rh.statut
711
712 # Certains dossiers ont un classement à zéro
713 if dossier_rh.classement_id > 0:
714 dossier.classement_anterieur = dossier_rh.classement
715
716 # Récupération du salaire de base
5a1f75cb
EMS
717 remun = dossier_rh.remunerations() \
718 .filter(type=1).order_by('-date_debut')
ed1982f3
NC
719 if remun:
720 dossier.salaire_anterieur = remun[0].montant
80bcc96b 721 dossier.devise_anterieur = remun[0].devise
ed1982f3
NC
722
723 # Récupération du titulaire précédent
724 try:
09aa8374 725 dossiers = rh.Dossier.objects.order_by('-date_debut')
32f26ff3 726 if poste_rh:
09aa8374 727 dossiers = dossiers.filter(poste=poste_rh)
32f26ff3
AJ
728 else:
729 dossiers = rh.Dossier.objects.none()
ed1982f3
NC
730 if len(dossiers):
731 # Ce bloc ignore toutes les erreurs, car les données de rh
732 # manquantes peuvent en générer
733 d = dossiers[0]
734 try:
735 titulaire = d.employe
736 dossier.employe_anterieur = titulaire
737 dossier.classement_titulaire_anterieur = d.classement
738 dossier.statut_titulaire_anterieur = d.statut
5a1f75cb
EMS
739 remun = d.remunerations().filter(type=1) \
740 .order_by('-date_debut')[0]
80bcc96b
OL
741 dossier.salaire_titulaire_anterieur = remun.montant
742 dossier.devise_titulaire_anterieur = remun.devise
ed1982f3
NC
743 except:
744 pass
745 # TODO: afficher l'info, les champs ne sont pas dans le
746 # modèle dae.Dossier: nom, prenom, classement, salaire
747 pass
748
749 except (rh.Dossier.DoesNotExist):
750 dossier_rh = rh.Dossier()
751
752 return dossier
753
5a1f75cb 754
04380fba 755@dae_groupe_requis
c0492570 756@vieux_dossier_dans_ma_region_ou_service
04380fba 757def dossier_resume(request, dossier_id=None):
04380fba
OL
758 try:
759 dossier = rh.Dossier.objects.get(id=dossier_id)
760 except:
761 return HttpResponseGone("Ce dossier n'est pas accessible")
f87fe1a1 762
04380fba
OL
763 data = {}
764 data['personne'] = unicode(dossier.employe)
0ebb99b3 765 data['classement'] = dossier.classement.id
09aa8374
OL
766 if dossier.statut is not None:
767 data['statut'] = dossier.statut.id
768 data['implantation'] = dossier.poste.implantation.id
5a1f75cb
EMS
769 data['poste'] = u"%s %s" % (
770 dossier.poste.type_poste.nom, dossier.poste.nom
771 )
09aa8374 772 salaire = dossier.get_salaire()
a4125771 773 if salaire is not None:
5a64aab4 774 data['montant'] = float(salaire.montant)
a4125771
OL
775 else:
776 data['montant'] = None
777 if salaire is not None and salaire.devise is not None:
10b6780c 778 data['devise'] = salaire.devise.id
e84c8ef1 779 data['montant_euros'] = salaire.montant_euros()
f87fe1a1 780 else:
04380fba
OL
781 data['devise'] = None
782 data['montant_euros'] = 0
85668061 783 return HttpResponse(dumps(data))
f87fe1a1 784
5a1f75cb 785
068d1462
OL
786@dae_groupe_requis
787@vieux_dossier_dans_ma_region_ou_service
788def poste_resume(request, dossier_id=None):
789 """
790 On travaille, en réalité sur le dossier mais on cache
791 l'identité de la personne.
792 """
793 try:
794 dossier = rh.Dossier.objects.get(id=dossier_id)
795 except:
796 return HttpResponseGone("Ce dossier n'est pas accessible")
797
3f5cbabe 798 salaire = dossier.get_salaire()
068d1462 799 data = {}
09aa8374 800 data['implantation'] = dossier.poste.implantation.id
5a1f75cb
EMS
801 data['poste'] = u"%s %s" % (
802 dossier.poste.type_poste.nom, dossier.poste.nom
803 )
068d1462
OL
804 if salaire is not None:
805 data['devise'] = salaire.devise.id
e503e64d 806 data['montant'] = float(salaire.montant)
e84c8ef1 807 data['montant_euros'] = salaire.montant_euros()
068d1462
OL
808 else:
809 data['devise'] = None
e503e64d
OL
810 data['montant'] = ""
811 data['montant_euros'] = ""
5d84008f
OL
812 data['statut'] = dossier.statut_id
813 data['classement'] = dossier.classement_id
068d1462
OL
814 return HttpResponse(dumps(data))
815
5a1f75cb 816
6d047148 817def liste_postes(request):
8684fcaa 818 """ Appel AJAX :
6d047148
OL
819 input : implantation_id
820 output : JSON liste de valeur point
821 """
822 method = request.method
823 params = getattr(request, method, [])
824 data = []
825
826 # Voir le code de _poste_choices dans forms.py
5a1f75cb
EMS
827 copies = dae.Poste.objects.exclude(id_rh__isnull=True) \
828 .filter(etat=POSTE_ETAT_FINALISE)
aa512122 829 rh_postes_actifs = rh.Poste.objects.all()
6d047148 830
5a1f75cb
EMS
831 if 'implantation_id' in params \
832 and params.get('implantation_id') is not u"":
6d047148 833 implantation_id = params.get('implantation_id')
6d047148 834 copies = copies.filter(implantation__id=implantation_id)
5a1f75cb
EMS
835 rh_postes_actifs = rh_postes_actifs.filter(
836 implantation__id=implantation_id
837 )
9536ea21 838
6d047148
OL
839 id_copies = [p.id_rh_id for p in copies.all()]
840 rhv1 = rh_postes_actifs.exclude(id__in=id_copies)
841 rhv1 = rhv1.select_related(depth=1)
4bce4d24 842
5a1f75cb
EMS
843 data = [('', 'Nouveau poste')] + \
844 sorted([('rh-%s' % p.id, label_poste_display(p)) for p in rhv1],
845 key=lambda t: t[1])
6d047148
OL
846 return HttpResponse(dumps(data))
847
5a1f75cb 848
e3563bcf 849@login_required
67a94eaf 850def dossier_piece(request, id, filename):
e3563bcf
EMS
851 """Téléchargement d'une pièce jointe à un poste."""
852 piece = get_object_or_404(dae.DossierPiece, pk=id)
5a1f75cb
EMS
853 if dae.Dossier.objects.ma_region_ou_service(request.user) \
854 .filter(id=piece.dossier_id).exists():
67a94eaf 855 return sendfile(request, piece.fichier.path)
e3563bcf
EMS
856 else:
857 return redirect_interdiction(request)
858
5a1f75cb 859
04380fba 860# AJAX SECURITE non nécessaire
5a1f75cb 861
04380fba 862def coefficient(request):
9536ea21 863 """ Appel AJAX :
04380fba
OL
864 input : classement
865 output : coefficient
866 """
867 method = request.method
868 params = getattr(request, method, [])
869 data = dict()
870 if 'classement' in params and params.get('classement') is not u"":
871 classement = params.get('classement')
872 classement = rh.Classement.objects.get(pk=classement)
873 data['coefficient'] = classement.coefficient
874 else:
875 data['coefficient'] = 0
876 return HttpResponse(dumps(data))
877
878
3d627bfd 879def devise(request):
8684fcaa 880 """ Appel AJAX :
3d627bfd 881 input : valeur_point
8e30e17f 882 output : devise, devise_code, taux_euro
3d627bfd 883 """
f87fe1a1
OL
884 method = request.method
885 params = getattr(request, method, [])
3d627bfd 886 data = dict()
8684fcaa 887 if 'valeur_point' in params and params.get('valeur_point') is not u"":
f87fe1a1 888 valeur_point = params.get('valeur_point')
3d627bfd 889 valeur_point = rh.ValeurPoint.objects.get(pk=valeur_point)
890 annee = valeur_point.annee
3f5cbabe 891 try:
5a1f75cb
EMS
892 taux = rh.TauxChange.objects.get(
893 annee=annee, devise=valeur_point.devise
894 )
3f5cbabe 895 except MultipleObjectsReturned:
5a1f75cb
EMS
896 return HttpResponseGone(
897 u"Il existe plusieurs taux pour la devise %s "
898 u"cette année-là : %s" % (valeur_point.devise.code, annee)
899 )
3f5cbabe 900
3d627bfd 901 data['devise'] = taux.devise.id
f87fe1a1 902 data['valeur'] = valeur_point.valeur
3d627bfd 903 data['devise_code'] = taux.devise.code
8e30e17f 904 data['taux_euro'] = taux.taux
be3c51e9
OL
905 else:
906 return HttpResponseGone("Vous devez choisir une valeur de point")
3d627bfd 907 return HttpResponse(dumps(data))
9536ea21 908
5a1f75cb 909
3d627bfd 910def devise_code(request):
8684fcaa 911 """ Appel AJAX :
3d627bfd 912 input : devise
8e30e17f 913 output : devise_code, taux_euro
3d627bfd 914 """
f87fe1a1
OL
915 method = request.method
916 params = getattr(request, method, [])
3d627bfd 917 data = dict()
f87fe1a1
OL
918 if 'devise' in params:
919 devise = params.get('devise')
3d627bfd 920 devise = rh.Devise.objects.get(pk=devise)
8e30e17f 921 annee = date.today().year
922 taux = rh.TauxChange.objects.filter(annee=annee, devise=devise)
86f1e48d
OL
923 if len(taux) == 0:
924 return HttpResponseGone("Le taux n'est pas disponible")
3d627bfd 925 data['devise_code'] = devise.code
8e30e17f 926 data['taux_euro'] = taux[0].taux
3d627bfd 927 return HttpResponse(dumps(data))
85668061 928
5a1f75cb 929
cb1d62b5
NC
930def add_remun(request, dossier, type_remun):
931 dossier = get_object_or_404(dae.Dossier, pk=dossier)
932 type_remun = get_object_or_404(rh.TypeRemuneration, pk=type_remun)
933 dae.Remuneration(dossier=dossier, devise=dossier.devise,
934 type=type_remun).save()
935
936 return render_to_response('dae/embauche-remun.html', dict(dossier=dossier),
937 RequestContext(request))
03b395db 938
5a1f75cb 939
04380fba
OL
940def salaire(request, implantation, devise, classement):
941 if not devise or not classement:
942 raise Http404
943
04380fba 944 taux = rh.TauxChange.objects.filter(devise=devise).order_by('-annee')
5a1f75cb
EMS
945 vp = rh.ValeurPoint.objects \
946 .filter(implantation=implantation, devise=devise) \
947 .order_by('-annee')
aa512122
OL
948
949 if vp.count() == 0:
950 raise Exception(u"pas de valeur de point pour le couple\
951 implantation/devise (%s/%s)" % (implantation, devise))
952
953 if taux.count() == 0:
954 raise Exception(u"Pas de taux pour la devise %s" % devise)
04380fba
OL
955
956 classement = get_object_or_404(rh.Classement, pk=classement)
90716392 957 taux, vp = taux[0].taux, vp[0].valeur
04380fba 958
90716392 959 salaire_euro = round(vp * classement.coefficient * taux, 2)
04380fba
OL
960 data = dict(salaire_euro=salaire_euro, taux=taux,
961 salaire_devise=round(salaire_euro / taux, 2))
962
963 return HttpResponse(dumps(data))
964
5a1f75cb 965
04380fba 966def liste_valeurs_point(request):
8684fcaa 967 """ Appel AJAX :
04380fba
OL
968 input : implantation_id
969 output : JSON liste de valeur point
03b395db 970 """
04380fba
OL
971 method = request.method
972 params = getattr(request, method, [])
973 data = []
974 annee_courante = datetime.datetime.now().year
5a1f75cb
EMS
975 if 'implantation_id' in params \
976 and params.get('implantation_id') is not u"":
04380fba 977 implantation_id = params.get('implantation_id')
5a1f75cb
EMS
978 preselectionne = rh.ValeurPoint.objects \
979 .filter(implantation=implantation_id, annee=annee_courante) \
980 .order_by("-annee")
7ad0549c 981 for o in preselectionne:
5a1f75cb
EMS
982 data.append({
983 'id': o.id,
984 'label': o.__unicode__(),
985 'devise': o.devise_id,
986 'suggestion': True
987 })
b1f7765e 988 else:
7ad0549c
OL
989 preselectionne = rh.ValeurPoint.objects.none()
990
5a1f75cb
EMS
991 liste_complete = rh.ValeurPoint.objects \
992 .filter(annee__in=(annee_courante,)) \
993 .order_by("-annee")
7ad0549c 994 for o in liste_complete.exclude(id__in=[p.id for p in preselectionne]):
5a1f75cb
EMS
995 data.append({
996 'id': o.id,
997 'label': o.__unicode__(),
998 'devise': o.devise_id,
999 'suggestion': False
1000 })
3f5cbabe 1001 return HttpResponse(dumps(data, indent=4))