[#3059] Page intermédiaire à l'importation d'une DAE
[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
fb0ed970
EMS
279@dossier_dans_ma_region_ou_service
280def embauche_importer(request, dossier_id=None):
281 dossier_dae = get_object_or_404(dae.Dossier, id=dossier_id)
47b60f16
EMS
282 if request.method == 'POST':
283 if 'confirmer' in request.POST:
284 dossier_rh = dossier_dae.importer_dans_rh()
285 return redirect('admin:rh_dossier_change', dossier_rh.id)
286 else:
287 return redirect('embauches_finalisees')
288 else:
289 return render_to_response('dae/embauche_importer.html', {
290 'dossier': dossier_dae
291 }, RequestContext(request))
fb0ed970
EMS
292
293
294@dae_groupe_requis
577dcb77
EMS
295def embauche_choisir_poste(request):
296 return render_to_response('dae/embauche-choisir-poste.html', {
297 'form': ChoosePosteForm(request=request)
298 }, RequestContext(request))
299
5a1f75cb 300
577dcb77 301@dae_groupe_requis
62d3903d 302@dossier_dans_ma_region_ou_service
62cfa562 303@dossier_est_modifiable
62d3903d 304def embauche(request, key=None, dossier_id=None):
139686f2 305 """ Formulaire d'autorisation d'embauche. """
139686f2 306
577dcb77
EMS
307 # Récupérer ou créer un poste et un dossier
308 source, id = key.split('-')
309 if source != 'dae':
310 return Http404
311 poste = get_object_or_404(dae.Poste, pk=id)
312
313 if request.POST:
314 if request.POST['employe'] == '':
315 # Nouvel employé
316 employe = dae.Employe()
317 else:
318 employe_source, id = request.POST['employe'].split('-')
319 if employe_source == 'dae':
320 # Employé DAE
321 employe = get_object_or_404(dae.Employe, pk=id)
322 elif employe_source == 'rh':
323 # Employé RH, on le copie dans DAE
324 e = get_object_or_404(rh.Employe, pk=id)
325 employe = dae.Employe(id_rh=e, prenom=e.prenom, nom=e.nom,
326 genre=e.genre)
139686f2 327 else:
577dcb77
EMS
328 raise Http404
329
5a1f75cb
EMS
330 employe_form = EmployeForm(
331 request.POST, instance=employe, request=request
332 )
577dcb77
EMS
333
334 if employe_form.is_valid():
335 data = dict(request.POST.items())
336 employe = employe_form.save()
337 data['employe'] = 'dae-%s' % employe.id
338 employe_form = EmployeForm(data, instance=employe, request=request)
339
340 if not dossier_id:
341 dossier = dae.Dossier(poste=poste, employe=employe)
342 else:
343 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
16b1454e 344 dossier.employe = employe_form.instance
577dcb77
EMS
345
346 dossier_form = DossierForm(request.POST, instance=dossier)
5a1f75cb
EMS
347 piecesForm = DossierPieceForm(
348 request.POST, request.FILES, instance=dossier
349 )
320d7584
EMS
350 comparaisons_formset = DossierComparaisonFormSet(
351 request.POST,
5a1f75cb
EMS
352 queryset=dossier.dae_comparaisons.ma_region_ou_service(
353 request.user
354 )
320d7584 355 )
577dcb77
EMS
356 remunForm = RemunForm(request.POST, instance=dossier)
357
55360d7d
EMS
358 if employe_form.is_valid() and \
359 dossier_form.is_valid() and \
577dcb77 360 piecesForm.is_valid() and \
320d7584 361 comparaisons_formset.is_valid() and \
577dcb77
EMS
362 remunForm.is_valid():
363 employe.save()
55360d7d 364 dossier_form.save()
577dcb77 365 piecesForm.save()
577dcb77 366 remunForm.save()
320d7584
EMS
367
368 # Ne remplacer que les comparaisons de ma région
369 comparaisons = comparaisons_formset.save(commit=False)
370 for comparaison in comparaisons:
371 comparaison.dossier = dossier
372 comparaison.save()
373
5a1f75cb
EMS
374 messages.success(
375 request, "Le dossier %s a été sauvegardé." % dossier
376 )
377 if 'save' in request.POST:
577dcb77 378 return redirect('embauche_consulter', dossier_id=dossier.id)
768d7e1b 379 else:
5a1f75cb
EMS
380 return redirect(
381 'embauche', key=dossier.poste.key, dossier_id=dossier.id
382 )
9536ea21 383
577dcb77 384 else:
5a1f75cb
EMS
385 messages.add_message(
386 request, messages.ERROR,
387 'Il y a des erreurs dans le formulaire.'
388 )
9536ea21 389
577dcb77
EMS
390 else:
391 # Initialisation d'un formulaire vide
392 if dossier_id:
393 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
394 employe = dossier.employe
395 data = dict(employe='dae-%s' % employe.id)
5a1f75cb
EMS
396 employe_form = EmployeForm(
397 initial=data, instance=employe, request=request
398 )
ed1982f3
NC
399 else:
400 dossier_rh = rh.Dossier()
401 poste_rh = poste.id_rh
577dcb77
EMS
402 dossier = pre_filled_dossier(dossier_rh, 'new', poste_rh)
403 employe_form = EmployeForm(request=request)
404
405 dossier_form = DossierForm(instance=dossier)
406 piecesForm = DossierPieceForm(instance=dossier)
320d7584 407 comparaisons_formset = DossierComparaisonFormSet(
5a1f75cb
EMS
408 queryset=dossier.dae_comparaisons.ma_region_ou_service(
409 request.user
410 )
320d7584 411 )
577dcb77
EMS
412 remunForm = RemunForm(instance=dossier)
413
829eb351 414 try:
5a1f75cb
EMS
415 comparaisons_internes = \
416 dossier.poste.dae_comparaisons_internes.ma_region_ou_service(
417 request.user
418 )
829eb351
EMS
419 except dae.Poste.DoesNotExist:
420 comparaisons_internes = []
421
577dcb77
EMS
422 return render_to_response('dae/embauche.html', {
423 'type_remun': filtered_type_remun(),
424 'devises': devises(),
425 'poste': poste,
426 'dossier': dossier,
427 'piecesForm': piecesForm,
428 'remunForm': remunForm,
320d7584 429 'comparaisons_formset': comparaisons_formset,
291bbfd9
EMS
430 'forms': dict(employe=employe_form, dossier=dossier_form, ),
431 'comparaisons_internes': comparaisons_internes
577dcb77 432 }, RequestContext(request))
139686f2 433
5a1f75cb 434
5633fa41 435@dae_groupe_requis
62d3903d 436@dossier_dans_ma_region_ou_service
0140cbd2 437def embauches_liste(request):
438 """ Liste des embauches. """
92741270
EMS
439 content_type = ContentType.objects.get_for_model(dae.Dossier)
440 extra_select = {'derniere_validation': (
441 "SELECT MAX(date) FROM workflow_workflowcommentaire "
5a1f75cb
EMS
442 "WHERE content_type_id = '%s' AND object_id = dae_dossier.id" %
443 content_type.id
92741270 444 )}
5a1f75cb
EMS
445 embauches_a_traiter = dae.Dossier.objects \
446 .mes_choses_a_faire(request.user) \
92741270 447 .extra(select=extra_select).order_by('-date_creation')
5a1f75cb
EMS
448 embauches_en_cours = dae.Dossier.objects \
449 .ma_region_ou_service(request.user) \
450 .extra(select=extra_select) \
451 .order_by('-date_creation') \
452 .exclude(etat=DOSSIER_ETAT_FINALISE)
92741270
EMS
453 return render_to_response('dae/embauches_liste.html', {
454 'embauches_a_traiter': embauches_a_traiter,
455 'embauches_en_cours': embauches_en_cours,
456 }, RequestContext(request))
355c80c8 457
5a1f75cb 458
44055779
EMS
459@dae_groupe_requis
460def embauches_finalisees(request):
461 """Liste des embauches finalisées."""
462 embauches = dae.Dossier.objects.ma_region_ou_service(request.user) \
463 .filter(etat=DOSSIER_ETAT_FINALISE)
464
465 # Tri
466 tri = request.GET.get('tri', None)
7652a4c3 467 if tri and tri.startswith('-'):
44055779
EMS
468 dir = '-'
469 tri = tri[1:]
470 else:
471 dir = ''
472 if tri == 'region':
5a1f75cb
EMS
473 embauches = embauches.order_by(
474 dir + 'poste__implantation__region__nom'
475 )
44055779
EMS
476 elif tri == 'implantation':
477 embauches = embauches.order_by(dir + 'poste__implantation__nom')
478 elif tri == 'poste':
479 embauches = embauches.order_by(dir + 'poste__nom')
480 elif tri == 'personne':
8684fcaa
EMS
481 embauches = embauches.order_by(dir + 'employe__nom',
482 dir + 'employe__prenom')
44055779
EMS
483 elif tri == 'date_debut':
484 embauches = embauches.order_by(dir + 'debut_contrat')
485 elif tri == 'date_fin':
486 embauches = embauches.order_by(dir + 'fin_contrat')
487
488 # Pagination
489 paginator = Paginator(embauches, 20)
490 try:
491 page = paginator.page(request.GET.get('page', 1))
492 except InvalidPage:
493 page = paginator.page(1)
494
495 return render_to_response('dae/embauches_finalisees.html', {
496 'embauches': page
497 }, RequestContext(request))
498
5a1f75cb 499
139686f2
NC
500def employe(request, key):
501 """ Récupération AJAX de l'employé pour la page d'embauche. """
502 data = dict(employe=key)
503
504 if key == '':
505 # Nouvel employé
506 employe = dae.Employe()
507 else:
508 # Employé existant
509 source, id = key.split('-')
510
511 if source == 'dae':
512 employe = get_object_or_404(dae.Employe, pk=id)
513 elif source == 'rh':
514 e = get_object_or_404(rh.Employe, id=id)
515 # Initialisation avec les valeurs de l'employé de rh_v1
516 employe = dae.Employe(id_rh=e)
517 for field in ('prenom', 'nom', 'genre'):
518 setattr(employe, field, getattr(e, field))
519
5a1f75cb
EMS
520 return HttpResponse(
521 EmployeForm(initial=data, instance=employe, request=request).as_table()
522 )
523
139686f2 524
9536ea21
EMS
525### CONTRATS
526
527@dae_groupe_requis
528@get_contrat
67a94eaf
EMS
529def contrat(request, contrat, filename):
530 return sendfile(request, contrat.fichier.path)
9536ea21 531
5a1f75cb 532
9536ea21
EMS
533@dae_groupe_requis
534@get_contrat
535def contrat_supprimer(request, contrat):
536 if request.method == 'POST':
537 if 'oui' in request.POST:
538 contrat.delete()
539 return redirect('embauche_consulter', dossier_id=contrat.dossier.id)
540 return render_to_response('dae/contrat-supprimer.html', {
541 'contrat': contrat
542 }, RequestContext(request))
543
5a1f75cb 544
9536ea21
EMS
545@dae_groupe_requis
546@dossier_dans_ma_region_ou_service
547def embauche_ajouter_contrat(request, dossier_id=None):
548 dossier = get_object_or_404(dae.Dossier, pk=dossier_id)
549 if request.method == 'POST':
550 form = ContratForm(request.POST, request.FILES)
551 if form.is_valid():
552 contrat = form.save(commit=False)
553 contrat.dossier = dossier
9dfa4296
OL
554 contrat.date_debut = dossier.contrat_date_debut
555 contrat.date_fin = dossier.contrat_date_fin
9536ea21
EMS
556 contrat.save()
557 return redirect('embauche_consulter', dossier_id=dossier.id)
558 else:
559 form = ContratForm()
560 return render_to_response('dae/embauche-ajouter-contrat.html', {
561 'form': form
562 }, RequestContext(request))
563
5a1f75cb 564
c3f0b49f
EMS
565### DAE NUMERISEE
566
567@get_object(dae.Dossier, 'consulter')
568def dae_numerisee(request, dossier):
569 return sendfile(request, dossier.dae_numerisee.path)
570
5a1f75cb 571
c3f0b49f
EMS
572@get_object(dae.Dossier, 'modifier_dae_numerisee')
573def dae_numerisee_modifier(request, dossier):
574 if request.method == 'POST':
575 form = DAENumeriseeForm(request.POST, request.FILES, instance=dossier)
576 if form.is_valid():
577 form.save()
578 return redirect('embauche_consulter', dossier_id=dossier.id)
579 else:
580 form = DAENumeriseeForm(instance=dossier)
581 return render_to_response('dae/dae_numerisee_modifier.html', {
582 'form': form
583 }, RequestContext(request))
584
5a1f75cb 585
c3f0b49f
EMS
586@get_object(dae.Dossier, 'modifier_dae_numerisee')
587def dae_numerisee_supprimer(request, dossier):
588 if request.method == 'POST':
589 if 'oui' in request.POST:
590 dossier.dae_numerisee = None
591 dossier.save()
592 return redirect('embauche_consulter', dossier_id=dossier.id)
5a1f75cb
EMS
593 return render_to_response(
594 'dae/dae_numerisee_supprimer.html', {}, RequestContext(request)
595 )
596
c3f0b49f 597
04380fba 598# AJAX SECURISE
5a1f75cb 599
04380fba
OL
600@dae_groupe_requis
601@employe_dans_ma_region_ou_service
139686f2
NC
602def dossier(request, poste_key, employe_key):
603 """ Récupération AJAX du dossier pour la page d'embauche. """
604 data = dict()
605
606 poste_source, poste_id = poste_key.split('-')
607 poste = get_object_or_404(dae.Poste, pk=poste_id)
179f6b49
OL
608
609 # Récupérer la devise de l'implantation lié au poste
610 implantation_devise = poste.get_default_devise()
5a1f75cb 611 data.update({'devise': implantation_devise})
9536ea21 612
e27db04c
OL
613 if poste.id_rh_id is not None:
614 poste_rh = get_object_or_404(rh.Poste, pk=poste.id_rh_id)
615 else:
616 poste_rh = None
139686f2 617
eabaed81 618 # NOUVEL EMPLOYE
139686f2
NC
619 if employe_key == '':
620 employe_source = 'new'
eabaed81 621 employe = None
139686f2 622 dossier_rh = rh.Dossier()
ed1982f3 623 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
139686f2 624
eabaed81 625 # EMPLOYE DAE
eabaed81 626 if employe_key.startswith('dae'):
5a1f75cb
EMS
627 employe_source, employe_id = employe_key.split('-')
628 employe_dae = get_object_or_404(dae.Employe, pk=employe_id)
629
630 # récupération de l'ancien dossier rh v1 pour l'employe DAE
631 try:
632 dossier_rh = rh.Dossier.objects.get(
633 employe=employe_dae.id_rh_id, date_fin=None
634 )
635 except (rh.Dossier.DoesNotExist):
636 dossier_rh = rh.Dossier()
637
638 # on tente de récupérer le dossier DAE, au pire on le contruit en le
639 # prépoluant avec son dossier rh v1.
640 try:
641 dossier = dae.Dossier.objects.get(employe=employe_dae, poste=poste)
642 except (dae.Dossier.DoesNotExist):
643 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
644 employe = employe_dae.id_rh
645
eabaed81 646 # EMPLOYE RH v1
eabaed81 647 if employe_key.startswith('rh'):
5a1f75cb
EMS
648 employe_source, employe_id = employe_key.split('-')
649 employe_rh = get_object_or_404(rh.Employe, pk=employe_id)
650
651 # récupération de l'ancien dossier rh v1 pour l'employe rh v1, s'il
652 # n'en a pas, on en fournit un nouveau qui servira uniquement un
653 # créer un nouveau dossier DAE.
654 try:
655 dossier_rh = rh.Dossier.objects.get(
656 employe=employe_rh, date_fin=None
657 )
658 except (rh.Dossier.DoesNotExist):
659 dossier_rh = rh.Dossier()
660 dossier = pre_filled_dossier(dossier_rh, employe_source, poste_rh)
661 employe = employe_rh
da3ca955 662
eabaed81
OL
663 dossier_form = DossierForm(initial=data, instance=dossier)
664 vars = dict(form=dossier_form, poste=poste, employe=employe)
da3ca955 665 return render_to_response('dae/embauche-dossier.html', vars,
666 RequestContext(request))
139686f2 667
5a1f75cb
EMS
668
669# Cette fonction est appelée à partir de fonctions déjà sécurisée
ed1982f3
NC
670def pre_filled_dossier(dossier_rh, employe_source, poste_rh):
671 dossier = dae.Dossier()
672
673 if employe_source != 'new' and dossier_rh.id:
674 dossier.statut_anterieur = dossier_rh.statut
675
676 # Certains dossiers ont un classement à zéro
677 if dossier_rh.classement_id > 0:
678 dossier.classement_anterieur = dossier_rh.classement
679
680 # Récupération du salaire de base
5a1f75cb
EMS
681 remun = dossier_rh.remunerations() \
682 .filter(type=1).order_by('-date_debut')
ed1982f3
NC
683 if remun:
684 dossier.salaire_anterieur = remun[0].montant
80bcc96b 685 dossier.devise_anterieur = remun[0].devise
ed1982f3
NC
686
687 # Récupération du titulaire précédent
688 try:
09aa8374 689 dossiers = rh.Dossier.objects.order_by('-date_debut')
32f26ff3 690 if poste_rh:
09aa8374 691 dossiers = dossiers.filter(poste=poste_rh)
32f26ff3
AJ
692 else:
693 dossiers = rh.Dossier.objects.none()
ed1982f3
NC
694 if len(dossiers):
695 # Ce bloc ignore toutes les erreurs, car les données de rh
696 # manquantes peuvent en générer
697 d = dossiers[0]
698 try:
699 titulaire = d.employe
700 dossier.employe_anterieur = titulaire
701 dossier.classement_titulaire_anterieur = d.classement
702 dossier.statut_titulaire_anterieur = d.statut
5a1f75cb
EMS
703 remun = d.remunerations().filter(type=1) \
704 .order_by('-date_debut')[0]
80bcc96b
OL
705 dossier.salaire_titulaire_anterieur = remun.montant
706 dossier.devise_titulaire_anterieur = remun.devise
ed1982f3
NC
707 except:
708 pass
709 # TODO: afficher l'info, les champs ne sont pas dans le
710 # modèle dae.Dossier: nom, prenom, classement, salaire
711 pass
712
713 except (rh.Dossier.DoesNotExist):
714 dossier_rh = rh.Dossier()
715
716 return dossier
717
5a1f75cb 718
04380fba 719@dae_groupe_requis
c0492570 720@vieux_dossier_dans_ma_region_ou_service
04380fba 721def dossier_resume(request, dossier_id=None):
04380fba
OL
722 try:
723 dossier = rh.Dossier.objects.get(id=dossier_id)
724 except:
725 return HttpResponseGone("Ce dossier n'est pas accessible")
f87fe1a1 726
04380fba
OL
727 data = {}
728 data['personne'] = unicode(dossier.employe)
0ebb99b3 729 data['classement'] = dossier.classement.id
09aa8374
OL
730 if dossier.statut is not None:
731 data['statut'] = dossier.statut.id
732 data['implantation'] = dossier.poste.implantation.id
5a1f75cb
EMS
733 data['poste'] = u"%s %s" % (
734 dossier.poste.type_poste.nom, dossier.poste.nom
735 )
09aa8374 736 salaire = dossier.get_salaire()
a4125771 737 if salaire is not None:
5a64aab4 738 data['montant'] = float(salaire.montant)
a4125771
OL
739 else:
740 data['montant'] = None
741 if salaire is not None and salaire.devise is not None:
10b6780c 742 data['devise'] = salaire.devise.id
e84c8ef1 743 data['montant_euros'] = salaire.montant_euros()
f87fe1a1 744 else:
04380fba
OL
745 data['devise'] = None
746 data['montant_euros'] = 0
85668061 747 return HttpResponse(dumps(data))
f87fe1a1 748
5a1f75cb 749
068d1462
OL
750@dae_groupe_requis
751@vieux_dossier_dans_ma_region_ou_service
752def poste_resume(request, dossier_id=None):
753 """
754 On travaille, en réalité sur le dossier mais on cache
755 l'identité de la personne.
756 """
757 try:
758 dossier = rh.Dossier.objects.get(id=dossier_id)
759 except:
760 return HttpResponseGone("Ce dossier n'est pas accessible")
761
3f5cbabe 762 salaire = dossier.get_salaire()
068d1462 763 data = {}
09aa8374 764 data['implantation'] = dossier.poste.implantation.id
5a1f75cb
EMS
765 data['poste'] = u"%s %s" % (
766 dossier.poste.type_poste.nom, dossier.poste.nom
767 )
068d1462
OL
768 if salaire is not None:
769 data['devise'] = salaire.devise.id
e503e64d 770 data['montant'] = float(salaire.montant)
e84c8ef1 771 data['montant_euros'] = salaire.montant_euros()
068d1462
OL
772 else:
773 data['devise'] = None
e503e64d
OL
774 data['montant'] = ""
775 data['montant_euros'] = ""
5d84008f
OL
776 data['statut'] = dossier.statut_id
777 data['classement'] = dossier.classement_id
068d1462
OL
778 return HttpResponse(dumps(data))
779
5a1f75cb 780
6d047148 781def liste_postes(request):
8684fcaa 782 """ Appel AJAX :
6d047148
OL
783 input : implantation_id
784 output : JSON liste de valeur point
785 """
786 method = request.method
787 params = getattr(request, method, [])
788 data = []
789
790 # Voir le code de _poste_choices dans forms.py
5a1f75cb
EMS
791 copies = dae.Poste.objects.exclude(id_rh__isnull=True) \
792 .filter(etat=POSTE_ETAT_FINALISE)
aa512122 793 rh_postes_actifs = rh.Poste.objects.all()
6d047148 794
5a1f75cb
EMS
795 if 'implantation_id' in params \
796 and params.get('implantation_id') is not u"":
6d047148 797 implantation_id = params.get('implantation_id')
6d047148 798 copies = copies.filter(implantation__id=implantation_id)
5a1f75cb
EMS
799 rh_postes_actifs = rh_postes_actifs.filter(
800 implantation__id=implantation_id
801 )
9536ea21 802
6d047148
OL
803 id_copies = [p.id_rh_id for p in copies.all()]
804 rhv1 = rh_postes_actifs.exclude(id__in=id_copies)
805 rhv1 = rhv1.select_related(depth=1)
4bce4d24 806
5a1f75cb
EMS
807 data = [('', 'Nouveau poste')] + \
808 sorted([('rh-%s' % p.id, label_poste_display(p)) for p in rhv1],
809 key=lambda t: t[1])
6d047148
OL
810 return HttpResponse(dumps(data))
811
5a1f75cb 812
e3563bcf 813@login_required
67a94eaf 814def dossier_piece(request, id, filename):
e3563bcf
EMS
815 """Téléchargement d'une pièce jointe à un poste."""
816 piece = get_object_or_404(dae.DossierPiece, pk=id)
5a1f75cb
EMS
817 if dae.Dossier.objects.ma_region_ou_service(request.user) \
818 .filter(id=piece.dossier_id).exists():
67a94eaf 819 return sendfile(request, piece.fichier.path)
e3563bcf
EMS
820 else:
821 return redirect_interdiction(request)
822
5a1f75cb 823
317ce433
OL
824@login_required
825def importer_choix_dossier(request):
826 method = request.method
827 params = getattr(request, method, None)
828 if params:
829 form = DAEImportableForm(params)
830 if form.is_valid():
831 form.importer_poste()
5a1f75cb
EMS
832 messages.add_message(
833 request, messages.SUCCESS, "L'importation a réussie."
834 )
317ce433
OL
835 else:
836 form = DAEImportableForm()
5a1f75cb 837
317ce433
OL
838 vars = dict(form=form, )
839 return render_to_response('admin/dae/importer_choix_dossier.html', vars,
840 RequestContext(request))
04380fba 841
5a1f75cb 842
04380fba 843# AJAX SECURITE non nécessaire
5a1f75cb 844
04380fba 845def coefficient(request):
9536ea21 846 """ Appel AJAX :
04380fba
OL
847 input : classement
848 output : coefficient
849 """
850 method = request.method
851 params = getattr(request, method, [])
852 data = dict()
853 if 'classement' in params and params.get('classement') is not u"":
854 classement = params.get('classement')
855 classement = rh.Classement.objects.get(pk=classement)
856 data['coefficient'] = classement.coefficient
857 else:
858 data['coefficient'] = 0
859 return HttpResponse(dumps(data))
860
861
3d627bfd 862def devise(request):
8684fcaa 863 """ Appel AJAX :
3d627bfd 864 input : valeur_point
8e30e17f 865 output : devise, devise_code, taux_euro
3d627bfd 866 """
f87fe1a1
OL
867 method = request.method
868 params = getattr(request, method, [])
3d627bfd 869 data = dict()
8684fcaa 870 if 'valeur_point' in params and params.get('valeur_point') is not u"":
f87fe1a1 871 valeur_point = params.get('valeur_point')
3d627bfd 872 valeur_point = rh.ValeurPoint.objects.get(pk=valeur_point)
873 annee = valeur_point.annee
3f5cbabe 874 try:
5a1f75cb
EMS
875 taux = rh.TauxChange.objects.get(
876 annee=annee, devise=valeur_point.devise
877 )
3f5cbabe 878 except MultipleObjectsReturned:
5a1f75cb
EMS
879 return HttpResponseGone(
880 u"Il existe plusieurs taux pour la devise %s "
881 u"cette année-là : %s" % (valeur_point.devise.code, annee)
882 )
3f5cbabe 883
3d627bfd 884 data['devise'] = taux.devise.id
f87fe1a1 885 data['valeur'] = valeur_point.valeur
3d627bfd 886 data['devise_code'] = taux.devise.code
8e30e17f 887 data['taux_euro'] = taux.taux
be3c51e9
OL
888 else:
889 return HttpResponseGone("Vous devez choisir une valeur de point")
3d627bfd 890 return HttpResponse(dumps(data))
9536ea21 891
5a1f75cb 892
3d627bfd 893def devise_code(request):
8684fcaa 894 """ Appel AJAX :
3d627bfd 895 input : devise
8e30e17f 896 output : devise_code, taux_euro
3d627bfd 897 """
f87fe1a1
OL
898 method = request.method
899 params = getattr(request, method, [])
3d627bfd 900 data = dict()
f87fe1a1
OL
901 if 'devise' in params:
902 devise = params.get('devise')
3d627bfd 903 devise = rh.Devise.objects.get(pk=devise)
8e30e17f 904 annee = date.today().year
905 taux = rh.TauxChange.objects.filter(annee=annee, devise=devise)
86f1e48d
OL
906 if len(taux) == 0:
907 return HttpResponseGone("Le taux n'est pas disponible")
3d627bfd 908 data['devise_code'] = devise.code
8e30e17f 909 data['taux_euro'] = taux[0].taux
3d627bfd 910 return HttpResponse(dumps(data))
85668061 911
5a1f75cb 912
cb1d62b5
NC
913def add_remun(request, dossier, type_remun):
914 dossier = get_object_or_404(dae.Dossier, pk=dossier)
915 type_remun = get_object_or_404(rh.TypeRemuneration, pk=type_remun)
916 dae.Remuneration(dossier=dossier, devise=dossier.devise,
917 type=type_remun).save()
918
919 return render_to_response('dae/embauche-remun.html', dict(dossier=dossier),
920 RequestContext(request))
03b395db 921
5a1f75cb 922
04380fba
OL
923def salaire(request, implantation, devise, classement):
924 if not devise or not classement:
925 raise Http404
926
04380fba 927 taux = rh.TauxChange.objects.filter(devise=devise).order_by('-annee')
5a1f75cb
EMS
928 vp = rh.ValeurPoint.objects \
929 .filter(implantation=implantation, devise=devise) \
930 .order_by('-annee')
aa512122
OL
931
932 if vp.count() == 0:
933 raise Exception(u"pas de valeur de point pour le couple\
934 implantation/devise (%s/%s)" % (implantation, devise))
935
936 if taux.count() == 0:
937 raise Exception(u"Pas de taux pour la devise %s" % devise)
04380fba
OL
938
939 classement = get_object_or_404(rh.Classement, pk=classement)
90716392 940 taux, vp = taux[0].taux, vp[0].valeur
04380fba 941
90716392 942 salaire_euro = round(vp * classement.coefficient * taux, 2)
04380fba
OL
943 data = dict(salaire_euro=salaire_euro, taux=taux,
944 salaire_devise=round(salaire_euro / taux, 2))
945
946 return HttpResponse(dumps(data))
947
5a1f75cb 948
04380fba 949def liste_valeurs_point(request):
8684fcaa 950 """ Appel AJAX :
04380fba
OL
951 input : implantation_id
952 output : JSON liste de valeur point
03b395db 953 """
04380fba
OL
954 method = request.method
955 params = getattr(request, method, [])
956 data = []
957 annee_courante = datetime.datetime.now().year
5a1f75cb
EMS
958 if 'implantation_id' in params \
959 and params.get('implantation_id') is not u"":
04380fba 960 implantation_id = params.get('implantation_id')
5a1f75cb
EMS
961 preselectionne = rh.ValeurPoint.objects \
962 .filter(implantation=implantation_id, annee=annee_courante) \
963 .order_by("-annee")
7ad0549c 964 for o in preselectionne:
5a1f75cb
EMS
965 data.append({
966 'id': o.id,
967 'label': o.__unicode__(),
968 'devise': o.devise_id,
969 'suggestion': True
970 })
b1f7765e 971 else:
7ad0549c
OL
972 preselectionne = rh.ValeurPoint.objects.none()
973
5a1f75cb
EMS
974 liste_complete = rh.ValeurPoint.objects \
975 .filter(annee__in=(annee_courante,)) \
976 .order_by("-annee")
7ad0549c 977 for o in liste_complete.exclude(id__in=[p.id for p in preselectionne]):
5a1f75cb
EMS
978 data.append({
979 'id': o.id,
980 'label': o.__unicode__(),
981 'devise': o.devise_id,
982 'suggestion': False
983 })
3f5cbabe 984 return HttpResponse(dumps(data, indent=4))