Fix django ajax selects
[auf_rh_dae.git] / project / rh / templatetags / rapports.py
CommitLineData
fd009814
PP
1# -*- coding: utf-8 -*-
2
72ac5e55
PP
3import datetime
4
fd009814
PP
5from django.utils.encoding import smart_unicode
6from django.template import Library
7from django.utils.http import urlencode
8
9from datamaster_modeles.models import Implantation, Region
23e749e1 10from rh.models import TypeContrat
f96ec25c
OL
11from project.rh import groups
12# pas de reference a DAE devrait etre refactorisé
13from dae.utils import get_employe_from_user
fd009814
PP
14
15register = Library()
16
17
549830eb 18COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
7821915f
PP
19
20
21@register.inclusion_tag('admin/filter.html', takes_context=True)
22def filter_comble(context):
23 return {'title': 'comblé',
24 'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)}
25
26
f0f6b03e 27@register.inclusion_tag('admin/filter.html', takes_context=True)
df37184c 28def filter_region(context, prefix=None):
df37184c 29 label = "".join([prefix or "", "implantation__region"])
fd009814 30 return {'title': u"région",
df37184c 31 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), label, context, remove=['pays', 'nord_sud'])}
fd009814
PP
32
33
f0f6b03e 34@register.inclusion_tag('admin/filter.html', takes_context=True)
df37184c 35def filter_implantation(context, prefix=None):
df37184c 36 label = "".join([prefix or "", "implantation"])
fd009814 37 return {'title': u"implantation",
df37184c 38 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), label, context)}
fd009814
PP
39
40
f0f6b03e 41@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 42def filter_region_contrat(context):
f96ec25c
OL
43 request = context['request']
44 user_groups = request.user.groups.all()
45 if groups.grp_correspondants_rh in user_groups or\
46 groups.grp_administrateurs in user_groups or\
47 groups.grp_directeurs_bureau in user_groups:
48 employe = get_employe_from_user(request.user)
49 regions = Region.objects.filter(id=employe.implantation.region.id)
50 else:
51 regions = Region.objects.all()
23e749e1 52 return {'title': u"région",
f96ec25c 53 'choices': prepare_choices(regions.values_list('id', 'nom'), 'dossier__poste__implantation__region', context, remove=['pays', 'nord_sud'])}
23e749e1 54
80518280
JPC
55@register.inclusion_tag('admin/filter.html', takes_context=True)
56def filter_region_dossier(context):
57 return {'title': u"région",
58 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'poste__implantation__region', context, remove=['pays', 'nord_sud'])}
59
60@register.inclusion_tag('admin/filter.html', takes_context=True)
61def filter_implantation_dossier(context):
62 return {'title': u"implantation",
63 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'poste__implantation', context)}
64
23e749e1 65
f0f6b03e 66@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 67def filter_implantation_contrat(context):
f96ec25c
OL
68 request = context['request']
69 user_groups = request.user.groups.all()
70 if groups.grp_correspondants_rh in user_groups or\
71 groups.grp_administrateurs in user_groups or\
72 groups.grp_directeurs_bureau in user_groups:
73 employe = get_employe_from_user(request.user)
74 implantations = Implantation.objects.filter(region=employe.implantation.region)
75 else:
76 implantations = Implantation.objects.all()
23e749e1 77 return {'title': u"implantation",
f96ec25c 78 'choices': prepare_choices(implantations.values_list('id', 'nom'), 'dossier__poste__implantation', context)}
23e749e1
PP
79
80
f0f6b03e 81@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1
PP
82def filter_type_contrat(context):
83 return {'title': u"type de contrat",
84 'choices': prepare_choices(TypeContrat.objects.values_list('id', 'nom'), 'type_contrat', context)}
85
72ac5e55
PP
86@register.inclusion_tag('admin/filter_select.html', takes_context=True)
87def filter_echeance_contrat(context):
eb204143
JPC
88 today = datetime.date.today()
89 three_months = today + datetime.timedelta(days=3*30)
90 six_months = today + datetime.timedelta(days=6*30)
91 twelve_months = today + datetime.timedelta(days=12*30)
92
93 field_name = 'date_fin'
72ac5e55 94 return {'title': u"échéance",
eb204143
JPC
95 'choices': prepare_choices_date(field_name, context, links=(
96 ('Tous', {}),
97 ('moins de 3 mois', {'%s__gte' % field_name: today.strftime('%Y-%m-%d'),
98 '%s__lte' % field_name: three_months.strftime('%Y-%m-%d')}),
99 ('3 à 6 mois', {'%s__gte' % field_name: three_months.strftime('%Y-%m-%d'),
100 '%s__lte' % field_name: six_months.strftime('%Y-%m-%d')}),
101 ('6 à 12 mois', {'%s__gte' % field_name: six_months.strftime('%Y-%m-%d'),
102 '%s__lte' % field_name: twelve_months.strftime('%Y-%m-%d')}),
103 )
104 )}
105
106@register.inclusion_tag('admin/filter_select.html', takes_context=True)
107def filter_debut_contrat(context):
108 year = datetime.date.today().timetuple()[0]
109 this_year = datetime.date(year, 1, 1)
110 next_year = datetime.date(year + 1, 1, 1)
111 last_year = datetime.date(year - 1, 12,31)
112
113 field_name = 'date_debut'
114 return {'title': u"date début",
115 'choices': prepare_choices_date(field_name, context, links=(
116 ('Tous', {}),
2953bb4d 117 ('années à venir', {'%s__gte' % field_name: next_year.strftime('%Y-%m-%d')}),
eb204143
JPC
118 ('cette anneée', {'%s__gte' % field_name: this_year.strftime('%Y-%m-%d'),
119 '%s__lt' % field_name: next_year.strftime('%Y-%m-%d')}),
02d63d23 120 ('années passées', {'%s__lte' % field_name: last_year.strftime('%Y-%m-%d')}),
eb204143
JPC
121 )
122 )}
123
35beb92c
JPC
124@register.inclusion_tag('admin/filter_select.html', takes_context=True)
125def filter_a_venir(context):
126 today = datetime.date.today()
127 year, month, day = datetime.date.today().timetuple()[:3]
128 mois_prochain = datetime.date(year+((month+1)/13), (month+1)%12, 1)
129 this_month = datetime.date(year, month, 1)
130
131 field_name = 'date_debut'
132 return {'title': u"à venir",
133 'choices': prepare_choices_date(field_name, context, links=(
134 ('Tous', {}),
135 ('à venir', {'%s__gt' % field_name: today.strftime('%Y-%m-%d')}),
136 ('à venir mois prochain', {'%s__gte' % field_name: mois_prochain.strftime('%Y-%m-%d')}),
137 ('à venir ce mois', {'%s__gte' % field_name: this_month.strftime('%Y-%m-%d'),
138 '%s__lt' % field_name: mois_prochain.strftime('%Y-%m-%d')}),
139 )
140 )}
141
142
72ac5e55
PP
143
144
af5073aa
PP
145@register.inclusion_tag('admin/filter_select.html', takes_context=True)
146def filter_region_remun(context):
147 return {'title': u"région",
148 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'dossiers__poste__implantation__region', context, remove=['pays', 'nord_sud'])}
149
150
151@register.inclusion_tag('admin/filter_select.html', takes_context=True)
152def filter_implantation_remun(context):
153 return {'title': u"implantation",
154 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'dossiers__poste__implantation', context)}
155
4dade240 156@register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
9d53bc73 157def table_header(context, headers):
9fd09bdc 158 return {'headers': headers}
af5073aa 159
fd009814
PP
160def get_query_string(request, new_params=None, remove=None):
161 if new_params is None: new_params = {}
162 if remove is None: remove = []
163 p = dict(request.GET.items())
164 for r in remove:
165 for k in p.keys():
166 if k.startswith(r):
167 del p[k]
168 for k, v in new_params.items():
169 if v is None:
170 if k in p:
171 del p[k]
172 else:
173 p[k] = v
174 return '?%s' % urlencode(p)
175
176
177def prepare_choices(choices, query_param, context, remove=[]):
178 request = context['request']
179 query_val = request.GET.get(query_param)
180 result = [{'selected': query_val is None,
181 'query_string': get_query_string(request, {}, [query_param] + remove),
182 'display': 'Tout'}]
183 for k, v in choices:
184 result.append({'selected': smart_unicode(k) == query_val,
185 'query_string': get_query_string(request, {query_param: k}, remove),
186 'display': v})
187 return result
72ac5e55
PP
188
189
eb204143 190def prepare_choices_date(field_name, context, links, remove=[]):
72ac5e55
PP
191 request = context['request']
192 params = request.GET
193 field_generic = '%s__' % field_name
194 date_params = dict([(k, v) for k, v in params.items() if k.startswith(field_generic)])
195
196
eb204143 197
72ac5e55
PP
198 result = []
199 for title, param_dict in links:
200 result.append({'selected': date_params == param_dict,
201 'query_string': get_query_string(request, param_dict, [field_generic]),
202 'display': title})
203 return result
9d53bc73 204
9d53bc73 205class SortHeaders:
4dade240
JPC
206 def __init__(self, request, headers, order_field_type, order_field, default_order_type="asc", not_sortable=[]):
207 self.request = request
208 self.order_field_type = order_field_type
209 self.order_field = order_field
9d53bc73 210 self.header_defs = headers
4dade240
JPC
211 self.params = dict(request.GET)
212 if default_order_type not in ('asc', 'desc'):
213 raise AttributeError(u"L'ordre par défaut n'est pas valide")
214 self.default_order_type = default_order_type
215 self.current_order_field = self.params[self.order_field][0] if self.order_field in self.params else None
216 self.current_order_field_type = self.params[self.order_field_type][0] if self.order_field_type in self.params else None
217 self.not_sortable = not_sortable
9d53bc73
JPC
218
219 def headers(self):
4dade240
JPC
220 for h in self.header_defs:
221 params = self.params
222 if h[0] == self.current_order_field:
223 order_type = {'asc': 'desc', 'desc': 'asc'}[self.current_order_field_type]
224 class_order = "%sending" % self.current_order_field_type
225 else:
226 order_type = self.default_order_type
227 class_order = ""
228 params[self.order_field_type] = [order_type]
229 params[self.order_field] = [h[0]]
230 url = "?%s" % "&".join(['%s=%s' % (param, value[0]) for param, value in params.items()])
9d53bc73 231 yield {
4dade240
JPC
232 "class_attr": "sorted %s" % class_order if self.field_sorted(h[0]) else "",
233 "sortable": self.field_sorted(h[0]),
234 "url": url,
9fd09bdc
JPC
235 "text": h[1],
236 "style_attr": h[2] if len(h) > 2 else "",
9d53bc73
JPC
237 }
238
4dade240
JPC
239 def field_sorted(self, field):
240 return True if field not in self.not_sortable else False
241
9202c5db
JPC
242@register.filter
243def split(str, splitter):
244 return str.split(splitter)
57e2b793
JPC
245
246@register.filter
3244a3c2 247def hash(h, key):
57e2b793
JPC
248 if key in h:
249 return h[key]
250 else:
251 raise Exception("%s does not exist" % key)
3244a3c2
JPC
252
253@register.filter
254def is_float(v):
255 if type(v) == type(float()):
256 return True
a6927189
JPC
257
258@register.filter()
259def contains(value, arg):
260 return arg in value