feature complete.. now need a bit of testing
[auf_rh_dae.git] / project / dae / forms.py
1 # -*- encoding: utf-8 -*-
2
3 import datetime
4 from ordereddict import OrderedDict
5 from dateutil.relativedelta import relativedelta
6 from django import forms
7 from django.core.urlresolvers import reverse
8 from django.core.exceptions import MultipleObjectsReturned
9 from django.forms.models import BaseInlineFormSet
10 from django.forms.models import (
11 inlineformset_factory,
12 modelformset_factory,
13 _get_foreign_key,
14 )
15 from django.db.models import Q, Max, Count
16 from django.shortcuts import redirect
17 from django.contrib.admin import widgets as admin_widgets
18
19 from ajax_select.fields import AutoCompleteSelectField
20
21 from auf.django.references import models as ref
22 from auf.django.workflow.forms import WorkflowFormMixin
23 from auf.django.workflow.models import WorkflowCommentaire
24
25 from project import groups
26 from project.rh import models as rh
27 from project.dae import models as dae
28 from .widgets import ReadOnlyChoiceWidget, ReadOnlyWidget
29 from project.dae.workflow import POSTE_ETATS_BOUTONS, POSTE_ETAT_FINALISE
30
31
32 class BaseInlineFormSetWithInitial(BaseInlineFormSet):
33 """
34 Cette classe permet de fournir l'option initial aux inlineformsets.
35 Elle devient désuette en django 1.4.
36 """
37 def __init__(self, data=None, files=None, instance=None,
38 save_as_new=False, prefix=None, queryset=None, **kwargs):
39
40 self.initial_extra = kwargs.pop('initial', None)
41
42 from django.db.models.fields.related import RelatedObject
43 if instance is None:
44 self.instance = self.fk.rel.to()
45 else:
46 self.instance = instance
47 self.save_as_new = save_as_new
48 # is there a better way to get the object descriptor?
49 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
50 if queryset is None:
51 queryset = self.model._default_manager
52 qs = queryset.filter(**{self.fk.name: self.instance})
53 super(BaseInlineFormSetWithInitial, self).__init__(data, files, prefix=prefix,
54 queryset=qs, **kwargs)
55
56 def _construct_form(self, i, **kwargs):
57 if self.is_bound and i < self.initial_form_count():
58 # Import goes here instead of module-level because importing
59 # django.db has side effects.
60 from django.db import connections
61 pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name)
62 pk = self.data[pk_key]
63 pk_field = self.model._meta.pk
64 pk = pk_field.get_db_prep_lookup('exact', pk,
65 connection=connections[self.get_queryset().db])
66 if isinstance(pk, list):
67 pk = pk[0]
68 kwargs['instance'] = self._existing_object(pk)
69 if i < self.initial_form_count() and not kwargs.get('instance'):
70 kwargs['instance'] = self.get_queryset()[i]
71 if i >= self.initial_form_count() and self.initial_extra:
72 # Set initial values for extra forms
73 try:
74 kwargs['initial'] = self.initial_extra[i-self.initial_form_count()]
75 except IndexError:
76 pass
77
78 defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
79 if self.is_bound:
80 defaults['data'] = self.data
81 defaults['files'] = self.files
82 if self.initial:
83 try:
84 defaults['initial'] = self.initial[i]
85 except IndexError:
86 pass
87 # Allow extra forms to be empty.
88 if i >= self.initial_form_count():
89 defaults['empty_permitted'] = True
90 defaults.update(kwargs)
91 form = self.form(**defaults)
92 self.add_fields(form, i)
93 return form
94
95
96 def _implantation_choices(obj, request):
97 # TRAITEMENT NORMAL
98 employe = groups.get_employe_from_user(request.user)
99 q = Q(**{'zone_administrative': employe.implantation.zone_administrative})
100
101 # TRAITEMENT DRH
102 user_groupes = [g.name for g in request.user.groups.all()]
103 if groups.DRH_NIVEAU_1 in user_groupes or \
104 groups.DRH_NIVEAU_2 in user_groupes:
105 q = Q()
106 return [('', '----------')] + \
107 [(i.id, unicode(i), )for i in ref.Implantation.objects.filter(q)]
108
109
110 def _employe_choices(obj, request):
111 # TRAITEMENT NORMAL
112 employe = groups.get_employe_from_user(request.user)
113 q_dae_region_service = Q(
114 poste__implantation__zone_administrative=(
115 employe.implantation.zone_administrative
116 )
117 )
118 q_rh_region_service = Q(
119 poste__implantation__zone_administrative=(
120 employe.implantation.zone_administrative
121 )
122 )
123 # TRAITEMENT DRH
124 user_groupes = [g.name for g in request.user.groups.all()]
125 if groups.DRH_NIVEAU_1 in user_groupes or \
126 groups.DRH_NIVEAU_2 in user_groupes:
127 q_dae_region_service = Q()
128 q_rh_region_service = Q()
129
130 # On filtre les employes avec les droits régionaux et on s'assure que
131 # c'est bien le dernier dossier en date pour sortir l'employe. On retient
132 # un employé qui travaille présentement dans la même région que le user
133 # connecté.
134 dossiers_regionaux_ids = [
135 d.id for d in dae.Dossier.objects.filter(q_dae_region_service)
136 ]
137 employes_ids = [
138 d['employe']
139 for d in dae.Dossier.objects
140 .values('employe')
141 .annotate(dernier_dossier=Max('id'))
142 if d['dernier_dossier'] in dossiers_regionaux_ids
143 ]
144 dae_employe = dae.Employe.objects.filter(id__in=employes_ids)
145 dae_ = dae_employe.filter(id_rh__isnull=True)
146 copies = dae_employe.filter(Q(id_rh__isnull=False))
147 id_copies = [p.id_rh_id for p in copies.all()]
148
149 dossiers_regionaux_ids = [
150 d.id for d in rh.Dossier.objects.filter(q_rh_region_service)
151 ]
152 employes_ids = [
153 d['employe']
154 for d in rh.Dossier.objects
155 .values('employe')
156 .annotate(dernier_dossier=Max('id'))
157 if d['dernier_dossier'] in dossiers_regionaux_ids
158 ]
159 rhv1 = rh.Employe.objects \
160 .filter(id__in=employes_ids) \
161 .exclude(id__in=id_copies)
162
163 # On ajoute les nouveaux Employés DAE qui ont été crées, mais qui n'ont
164 # pas de Dossier associés
165 employes_avec_dae = [d.employe_id for d in dae.Dossier.objects.all()]
166 employes_orphelins = dae.Employe.objects.exclude(id__in=employes_avec_dae)
167
168 def option_label(employe, extra=""):
169 if extra:
170 extra = " [%s]" % extra
171 return "%s %s %s" % (employe.nom.upper(), employe.prenom.title(), extra)
172
173 lbl_rh = sorted([('rh-%s' % p.id, option_label(p, "existant dans rh")) for p in rhv1],
174 key=lambda t: t[1])
175 lbl_dae = sorted([('dae-%s' % p.id, option_label(p)) for p in dae_ | copies | employes_orphelins],
176 key=lambda t: t[1])
177 return [('', 'Nouvel employé')] + lbl_rh + lbl_dae
178
179
180 def label_poste_display(poste):
181 """Formate un visuel pour un poste dans une liste déroulante"""
182 annee = ""
183 if poste.date_debut:
184 annee = poste.date_debut.year
185
186 nom = poste.nom
187 label = u"%s (%s) %s [%s]" % (
188 annee,
189 poste.implantation.nom_court,
190 nom,
191 #poste.type_poste.categorie_emploi.nom,
192 poste.id,
193 )
194 return label
195
196
197 PostePieceFormSet = inlineformset_factory(dae.Poste, dae.PostePiece,)
198 DossierPieceForm = inlineformset_factory(dae.Dossier, dae.DossierPiece)
199
200 # Ce formset est utilisé dans le cas de la création de poste prépopulé avec les
201 # données de RH
202 FinancementFormSetInitial = inlineformset_factory(
203 dae.Poste,
204 dae.PosteFinancement,
205 formset=BaseInlineFormSetWithInitial,
206 extra=2
207 )
208 FinancementFormSet = inlineformset_factory(
209 dae.Poste,
210 dae.PosteFinancement,
211 extra=2
212 )
213
214
215 class DossierComparaisonForm(forms.ModelForm):
216
217 recherche = AutoCompleteSelectField('dossiers', required=False)
218 poste = forms.CharField(
219 max_length=255, widget=forms.TextInput(attrs={'size': '60'})
220 )
221 cmp_dossier = forms.IntegerField(
222 widget=forms.widgets.HiddenInput,
223 required=False
224 )
225
226 class Meta:
227 model = dae.DossierComparaison
228 exclude = ('dossier',)
229
230 DossierComparaisonFormSet = modelformset_factory(
231 dae.DossierComparaison, extra=3, max_num=3, form=DossierComparaisonForm
232 )
233
234
235 class PosteComparaisonForm(forms.ModelForm):
236
237 recherche = AutoCompleteSelectField('dae_postes', required=False)
238
239 cmp_poste = forms.IntegerField(
240 widget=forms.widgets.HiddenInput,
241 required=False,
242 )
243
244 class Meta:
245 model = dae.PosteComparaison
246 exclude = ('poste',)
247
248 # Ce formset est utilisé dans le cas de la création de poste prépopulé avec les
249 # données de RH
250 PosteComparaisonFormSetInitial = inlineformset_factory(
251 dae.Poste,
252 dae.PosteComparaison,
253 extra=3,
254 max_num=3,
255 form=PosteComparaisonForm,
256 formset=BaseInlineFormSetWithInitial,
257 )
258 PosteComparaisonFormSet = inlineformset_factory(
259 dae.Poste,
260 dae.PosteComparaison,
261 extra=3,
262 max_num=3,
263 form=PosteComparaisonForm,
264 )
265
266
267 class FlexibleRemunForm(forms.ModelForm):
268 # Utilisé dans templats.
269 montant_mensuel = forms.DecimalField(required=False)
270 montant = forms.DecimalField(required=True, label='Montant annuel')
271
272 class Meta:
273 model = dae.Remuneration
274
275 def __init__(self, *a, **kw):
276 super(FlexibleRemunForm, self).__init__(*a, **kw)
277 # self.fields['type'].widget = ReadOnlyChoiceWidget(choices=self.fields['type'].choices)
278
279 def clean_devise(self):
280 devise = self.cleaned_data['devise']
281 if devise.code == 'EUR':
282 return devise
283 implantation = ref.Implantation.objects.get(
284 id=self.data['implantation']
285 )
286 liste_taux = devise.tauxchange_set.order_by('-annee')
287 if len(liste_taux) == 0:
288 raise forms.ValidationError(
289 u"La devise %s n'a pas de taux pour l'implantation %s" %
290 (devise, implantation)
291 )
292 else:
293 return devise
294
295 def has_changed(self):
296 """
297 Modification de has_changed pour qu'il ignore les montant a 0
298 et les 'types'.
299 """
300
301 changed_data = self.changed_data
302
303 # Type is set in hidden fields, it shouldn't be changed by the
304 # user; ignore when checking if data has changed.
305 if 'type' in changed_data:
306 changed_data.pop(changed_data.index('type'))
307
308 # Montant is set to 0 in javascript, ifnore 'montant' data if
309 # its value is 0.
310
311 # Generer le key tel qu'identifié dans self.data:
312 montant_key = '-'.join((self.prefix, 'montant'))
313
314 if ('montant' in changed_data and
315 self.data.get(montant_key, '0') == '0'):
316 changed_data.pop(changed_data.index('montant'))
317
318 return bool(changed_data)
319
320
321 class ReadOnlyRemunForm(FlexibleRemunForm):
322 # Utilisé dans templats.
323
324 def __init__(self, *a, **kw):
325 super (ReadOnlyRemunForm, self).__init__(*a, **kw)
326 for field in self.fields:
327 field = self.fields[field]
328 if not isinstance(field.widget, (
329 forms.widgets.HiddenInput,
330 forms.widgets.Select)):
331 field.widget = ReadOnlyWidget()
332 elif isinstance(field.widget, forms.widgets.Select):
333 field.widget = ReadOnlyChoiceWidget(choices=field.choices)
334
335
336 class GroupedInlineFormset(BaseInlineFormSet):
337
338 def set_groups(self,
339 groups,
340 group_accessor,
341 choice_overrides=[]):
342
343
344 # Create pre-defined groups.
345 self.groups = OrderedDict()
346 for group in groups:
347 self.groups[group[0]] = {
348 'name': group[1],
349 'key': group[0],
350 'forms': [],
351 }
352
353 # Assign each form to a group.
354 for form in self.forms:
355 if bool(form.initial):
356 grp = group_accessor(form)
357 if grp[0] not in self.groups:
358 self.groups[grp[0]] = {
359 'name': grp[1],
360 'key': grp[0],
361 'forms': [],
362 }
363 self.groups[grp[0]]['forms'].append(form)
364
365 # Add extra forms (n extra for each grop).
366 tmp_extras = []
367 for i in xrange(len(self.groups) * self.extra):
368 tmp_extras.insert(0,
369 self._construct_form(self.initial_form_count() + i))
370
371 for g in self.groups:
372 for i in xrange(self.extra):
373 self.groups[g]['forms'].append(tmp_extras.pop())
374
375
376 # Override form choices with the data provided in
377 # choice_overrides
378 for key in choice_overrides:
379 for form in self.groups.get(key, {'forms': []})['forms']:
380 for field_key in choice_overrides[key]:
381 form.fields[field_key].choices = choice_overrides[
382 key][field_key]
383
384
385 # Create an iterable for easier access in template.
386 self.group_list = self.groups.values()
387
388 # def set_groups(self, group_accessor, groups, group_order=[]):
389 # """
390 # group_accessor: A function that will get the key and name from
391 # each form.
392 # group_order: list the group keys here in a list and
393 # GroupedInlineFormset.groups will be ordered (ordereddict) by
394 # the key sequence provided here. Any missing key from the
395 # sequence will
396 # """
397
398 # # Build group list.
399 # self.groups = OrderedDict()
400 # temp_groups = {}
401 # # self.groups_and_forms = []
402 # for form in self.forms:
403 # group_key, group_name = group_accessor(form)
404 # if not temp_groups.has_key(group_key):
405 # temp_groups[group_key] = {
406 # 'name': group_name,
407 # 'key': group_key,
408 # 'forms': [],
409 # }
410 # temp_groups[group_key]['forms'].append(form)
411
412 # for order_key in group_order:
413 # if temp_groups.has_key(order_key):
414 # self.groups[order_key] = temp_groups.pop(order_key)
415
416 # for key in temp_groups:
417 # self.groups[key] = temp_groups[key]
418
419 # del temp_groups
420
421 # self.group_list = self.groups.values()
422
423
424 def remun_formset_factory(parent_model,
425 model,
426 form=forms.ModelForm,
427 formset=GroupedInlineFormset,
428 fk_name=None,
429 fields=None,
430 exclude=None,
431 can_order=False,
432 can_delete=True,
433 read_only=False,
434 extra=2,
435 max_num=None,
436 formfield_callback=None,
437 groups=None,
438 choice_overrides=[]):
439 trs = rh.TypeRemuneration.objects.all()
440 # extra = max_num = trs.count()
441 fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
442 # enforce a max_num=1 when the foreign key to the parent model is unique.
443 if fk.unique:
444 max_num = 1
445 kwargs = {
446 'form': form,
447 'formfield_callback': formfield_callback,
448 'formset': formset,
449 'extra': extra,
450 'can_delete': can_delete,
451 'can_order': can_order,
452 'fields': fields,
453 'exclude': exclude,
454 'max_num': max_num,
455 }
456 FormSet = modelformset_factory(model, **kwargs)
457 FormSet.fk = fk
458 FormSet.read_only = read_only
459
460 def grouper(form):
461 rtype = form.initial['type']
462 if not isinstance(rtype, rh.TypeRemuneration):
463 rtype = rh.TypeRemuneration.objects.get(id=rtype)
464 return (rtype.nature_remuneration,
465 rtype.nature_remuneration
466 )
467
468
469
470 # Monkey patch FormSet.
471 def __init__(inst, *a, **kw):
472 super(inst.__class__, inst).__init__(*a, **kw)
473 inst.set_groups(groups, grouper, choice_overrides)
474
475 FormSet.__init__ = __init__
476
477 return FormSet
478
479
480 def remun_formset_factory_factory(read_only=False, parent_model=dae.Dossier, model=dae.Remuneration):
481 """
482 Don't we love factory factories?
483 """
484
485 null_choice = ('', '-' * 10)
486 extras = 2 if not read_only else 0
487 can_delete = False if read_only else True
488 form_class = ReadOnlyRemunForm if read_only else FlexibleRemunForm
489
490 return remun_formset_factory(
491 parent_model,
492 model,
493 form=form_class,
494 extra=extras,
495 can_delete=can_delete,
496 read_only=read_only,
497 groups = [
498 (u'Traitement', u'Traitement',),
499 (u'Indemnité', u'Indemnité',),
500 (u'Charges', u'Charges',),
501 (u'Accessoire', u'Accessoire',),
502 (u'RAS', u'Rémunération autre source',),
503 ],
504 choice_overrides = {
505 u'Traitement': {
506 'type': [null_choice] + list(
507 rh.TypeRemuneration.objects.filter(
508 nature_remuneration=u'Traitement').values_list(
509 'id', 'nom')
510 )
511 },
512 u'Indemnité': {
513 'type': [null_choice] + list(
514 rh.TypeRemuneration.objects.filter(
515 nature_remuneration=u'Indemnité').values_list(
516 'id', 'nom')
517 )
518 },
519 u'Charges': {
520 'type': [null_choice] + list(
521 rh.TypeRemuneration.objects.filter(
522 nature_remuneration=u'Charges').values_list(
523 'id', 'nom')
524 )
525 },
526 u'Accessoire': {
527 'type': [null_choice] + list(
528 rh.TypeRemuneration.objects.filter(
529 nature_remuneration=u'Accessoire').values_list(
530 'id', 'nom')
531 )
532 },
533 u'RAS': {
534 'type': [null_choice] + list(
535 rh.TypeRemuneration.objects.filter(
536 nature_remuneration=u'RAS').values_list(
537 'id', 'nom')
538 )
539 },
540 }
541 )
542
543 RemunForm = remun_formset_factory_factory(
544 read_only=False,
545 parent_model=dae.Dossier,
546 model=dae.Remuneration,
547 )
548
549 ReadOnlyRemunFormSet = remun_formset_factory_factory(
550 read_only=True,
551 parent_model=dae.Dossier,
552 model=dae.Remuneration,
553 )
554
555 PosteCompReadOnlyRemunFormSet = remun_formset_factory_factory(
556 read_only=True,
557 parent_model=dae.PosteComparaison,
558 model=dae.PosteComparaisonRemuneration,
559 )
560
561 DossierCompReadOnlyRemunFormSet = remun_formset_factory_factory(
562 read_only=True,
563 parent_model=dae.DossierComparaison,
564 model=dae.DossierComparaisonRemuneration,
565 )
566
567
568 class PosteForm(forms.ModelForm):
569 """ Formulaire des postes. """
570
571 # On ne propose que les services actifs
572 service = forms.ModelChoiceField(
573 queryset=rh.Service.objects.all(), required=True
574 )
575
576 responsable = AutoCompleteSelectField('responsables', required=True)
577 #responsable = forms.ModelChoiceField(
578 # queryset=rh.Poste.objects.select_related(depth=1))
579
580 # La liste des choix est laissée vide. Voir __init__ pour la raison.
581 poste = forms.ChoiceField(label="Nouveau poste ou évolution du poste",
582 choices=(), required=False)
583
584 valeur_point_min = forms.ModelChoiceField(
585 queryset=rh.ValeurPoint.actuelles.all(), required=False
586 )
587 valeur_point_max = forms.ModelChoiceField(
588 queryset=rh.ValeurPoint.actuelles.all(), required=False
589 )
590
591 class Meta:
592 model = dae.Poste
593 fields = ('type_intervention',
594 'poste', 'implantation', 'type_poste', 'service', 'nom',
595 'responsable', 'local', 'expatrie', 'mise_a_disposition',
596 'appel', 'date_debut', 'date_fin',
597 'regime_travail', 'regime_travail_nb_heure_semaine',
598 'classement_min', 'classement_max',
599 'valeur_point_min', 'valeur_point_max',
600 'devise_min', 'devise_max',
601 'salaire_min', 'salaire_max',
602 'indemn_expat_min', 'indemn_expat_max',
603 'indemn_fct_min', 'indemn_fct_max',
604 'charges_patronales_min', 'charges_patronales_max',
605 'autre_min', 'autre_max', 'devise_comparaison',
606 'comp_locale_min', 'comp_locale_max',
607 'comp_universite_min', 'comp_universite_max',
608 'comp_fonctionpub_min', 'comp_fonctionpub_max',
609 'comp_ong_min', 'comp_ong_max',
610 'comp_autre_min', 'comp_autre_max',
611 'justification',
612 )
613 widgets = dict(type_intervention=forms.RadioSelect(),
614 appel=forms.RadioSelect(),
615 nom=forms.TextInput(attrs={'size': 60},),
616 date_debut=admin_widgets.AdminDateWidget(),
617 date_fin=admin_widgets.AdminDateWidget(),
618 justification=forms.Textarea(attrs={'cols': 80},),
619 #devise_min=forms.Select(attrs={'disabled':'disabled'}),
620 #devise_max=forms.Select(attrs={'disabled':'disabled'}),
621 )
622
623 def __init__(self, *args, **kwargs):
624 """ Mise à jour dynamique du contenu du menu des postes.
625
626 Si on ne met le menu à jour de cette façon, à chaque instantiation du
627 formulaire, son contenu est mis en cache par le système et il ne
628 reflète pas les changements apportés par les ajouts, modifications,
629 etc...
630
631 Aussi, dans ce cas-ci, on ne peut pas utiliser un ModelChoiceField
632 car le "id" de chaque choix est spécial (voir _poste_choices).
633
634 """
635 request = kwargs.pop('request')
636 super(PosteForm, self).__init__(*args, **kwargs)
637 self.fields['poste'].choices = self._poste_choices(request)
638
639 self.fields['implantation'].choices = \
640 _implantation_choices(self, request)
641
642 # Quand le dae.Poste n'existe pas, on recherche dans les dossiers rhv1
643 if self.instance and self.instance.id is None:
644 dossiers = self.instance.get_dossiers()
645 if len(dossiers) > 0:
646 self.initial['service'] = dossiers[0].poste.service
647
648 def _poste_choices(self, request):
649 """ Menu déroulant pour les postes.
650 Constitué des postes de RH
651 """
652 postes_rh = rh.Poste.objects.ma_region_ou_service(request.user).all()
653 postes_rh = postes_rh.select_related(depth=1)
654
655 return [('', 'Nouveau poste')] + \
656 sorted([('rh-%s' % p.id, label_poste_display(p)) for p in
657 postes_rh],
658 key=lambda t: t[1])
659
660 def clean(self):
661 """
662 Validation conditionnelles de certains champs.
663 """
664 cleaned_data = self.cleaned_data
665
666 if cleaned_data.get("local") is False \
667 and cleaned_data.get("expatrie") is False:
668 msg = "Le poste doit au moins être ouvert localement " \
669 "ou aux expatriés"
670 self._errors["local"] = self.error_class([msg])
671 self._errors["expatrie"] = ''
672 raise forms.ValidationError(msg)
673
674 return cleaned_data
675
676
677 class ChoosePosteForm(forms.Form):
678 class Meta:
679 fields = ('poste',)
680
681 # La liste des choix est laissée vide. Voir PosteForm.__init__.
682 postes_dae = forms.ChoiceField(choices=(), required=False)
683 postes_rh = forms.ChoiceField(choices=(), required=False)
684
685 def __init__(self, request=None, *args, **kwargs):
686 super(ChoosePosteForm, self).__init__(*args, **kwargs)
687 self.fields['postes_dae'].choices = self._poste_dae_choices(request)
688 self.fields['postes_rh'].choices = self._poste_rh_choices(request)
689
690 def _poste_dae_choices(self, request):
691 """ Menu déroulant pour les postes."""
692 postes_dae = dae.Poste.objects.ma_region_ou_service(request.user) \
693 .exclude(etat__in=(POSTE_ETAT_FINALISE, )) \
694 .annotate(num_dae=Count('dae_dossiers')) \
695 .filter(num_dae=0) \
696 .order_by('implantation', '-date_debut', )
697
698 return [('', '----------')] + \
699 [('dae-%s' % p.id, label_poste_display(p)) for p in postes_dae]
700
701 def _poste_rh_choices(self, request):
702 """ Menu déroulant pour les postes."""
703 postes_dae = dae.Poste.objects.exclude(etat__in=(POSTE_ETAT_FINALISE, ))
704 today = datetime.date.today()
705 id_poste_dae_commences = [p.id_rh_id for p in postes_dae if p.id_rh is not None]
706 postes_rh = rh.Poste.objects.ma_region_ou_service(request.user) \
707 .exclude(id__in=id_poste_dae_commences) \
708 .filter(Q(date_debut__lte=today) &
709 (Q(date_fin__gte=today) |
710 Q(date_fin__isnull=True))
711 ) \
712 .order_by('implantation', '-date_debut', )
713
714 return [('', '----------')] + \
715 [('rh-%s' % p.id, label_poste_display(p)) for p in postes_rh]
716
717 def clean(self):
718 cleaned_data = super(ChoosePosteForm, self).clean()
719 postes_dae = cleaned_data.get("postes_dae")
720 postes_rh = cleaned_data.get("postes_rh")
721 if (postes_dae is u"" and postes_rh is u"") or \
722 (postes_dae is not u"" and postes_rh is not u""):
723 raise forms.ValidationError("Choisissez un poste DAE ou un poste RH")
724 return cleaned_data
725
726 def redirect(self):
727 poste_dae_key = self.cleaned_data.get("postes_dae")
728 if poste_dae_key is not u"":
729 return redirect(reverse('embauche', args=(poste_dae_key,)))
730 poste_rh_key = self.cleaned_data.get("postes_rh")
731 if poste_rh_key is not u"":
732 return redirect("%s?creer_dossier_dae='M'" % reverse('poste', args=(poste_rh_key,)))
733
734 class EmployeForm(forms.ModelForm):
735 """ Formulaire des employés. """
736 class Meta:
737 model = dae.Employe
738 fields = ('employe', 'nom', 'prenom', 'genre')
739
740 # La liste des choix est laissée vide. Voir Poste.__init__ pour la raison.
741 employe = forms.ChoiceField(choices=(), required=False)
742
743 def __init__(self, *args, **kwargs):
744 """ Mise à jour dynamique du contenu du menu des employés. """
745 request = kwargs.pop('request', None)
746 super(EmployeForm, self).__init__(*args, **kwargs)
747 self.fields['employe'].choices = _employe_choices(self, request)
748
749
750 class DossierForm(forms.ModelForm):
751 """ Formulaire des dossiers. """
752 class Meta:
753 exclude = ('etat', 'employe', 'poste', 'date_debut',)
754 model = dae.Dossier
755 widgets = dict(statut_residence=forms.RadioSelect(),
756 contrat_date_debut=admin_widgets.AdminDateWidget(),
757 contrat_date_fin=admin_widgets.AdminDateWidget(),
758 )
759
760 WF_HELP_TEXT = ""
761
762
763 class PosteWorkflowForm(WorkflowFormMixin):
764 bouton_libelles = POSTE_ETATS_BOUTONS
765
766 class Meta:
767 fields = ('etat', )
768 model = dae.Poste
769
770 def __init__(self, *args, **kwargs):
771 super(PosteWorkflowForm, self).__init__(*args, **kwargs)
772 self.fields['etat'].help_text = WF_HELP_TEXT
773
774
775 class DossierWorkflowForm(WorkflowFormMixin):
776 bouton_libelles = POSTE_ETATS_BOUTONS # meme workflow que poste...
777
778 class Meta:
779 fields = ('etat', )
780 model = dae.Dossier
781
782 def __init__(self, *args, **kwargs):
783 super(DossierWorkflowForm, self).__init__(*args, **kwargs)
784 self.fields['etat'].help_text = WF_HELP_TEXT
785 self._etat_initial = self.instance.etat
786
787 def save(self):
788 super(DossierWorkflowForm, self).save()
789 poste = self.instance.poste
790
791 # créer le commentaire automatique pour le poste associé
792 commentaire = WorkflowCommentaire()
793 commentaire.content_object = poste
794 texte = u"Validation automatique à travers le dossier [%s] de %s\n%s" %(
795 self.instance.id,
796 self.instance,
797 self.data.get('commentaire', ''),
798 )
799 commentaire.texte = texte
800 commentaire.etat_initial = self.instance._etat_courant
801 commentaire.etat_final = self.instance.etat
802 commentaire.owner = self.request.user
803 commentaire.save()
804
805 # force l'état du poste
806 poste.etat = self.instance.etat
807 poste.save()
808
809
810 class ContratForm(forms.ModelForm):
811
812 class Meta:
813 fields = ('type_contrat', 'fichier', )
814 model = dae.Contrat
815
816
817 class DAENumeriseeForm(forms.ModelForm):
818
819 class Meta:
820 model = dae.Dossier
821 fields = ('dae_numerisee',)
822
823
824 class DAEFinaliseesSearchForm(forms.Form):
825 q = forms.CharField(
826 label='Recherche', required=False,
827 widget=forms.TextInput(attrs={'size': 40})
828 )
829 importees = forms.ChoiceField(
830 label='Importation', required=False, choices=(
831 ('', ''),
832 ('oui', 'DAE importées seulement'),
833 ('non', 'DAE non-importées seulement'),
834 )
835 )