Fix django ajax selects
[auf_rh_dae.git] / project / rh / templatetags / rapports.py
1 # -*- coding: utf-8 -*-
2
3 import datetime
4
5 from django.utils.encoding import smart_unicode
6 from django.template import Library
7 from django.utils.http import urlencode
8
9 from datamaster_modeles.models import Implantation, Region
10 from rh.models import TypeContrat
11 from project.rh import groups
12 # pas de reference a DAE devrait etre refactorisé
13 from dae.utils import get_employe_from_user
14
15 register = Library()
16
17
18 COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
19
20
21 @register.inclusion_tag('admin/filter.html', takes_context=True)
22 def filter_comble(context):
23 return {'title': 'comblé',
24 'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)}
25
26
27 @register.inclusion_tag('admin/filter.html', takes_context=True)
28 def filter_region(context, prefix=None):
29 label = "".join([prefix or "", "implantation__region"])
30 return {'title': u"région",
31 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), label, context, remove=['pays', 'nord_sud'])}
32
33
34 @register.inclusion_tag('admin/filter.html', takes_context=True)
35 def filter_implantation(context, prefix=None):
36 label = "".join([prefix or "", "implantation"])
37 return {'title': u"implantation",
38 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), label, context)}
39
40
41 @register.inclusion_tag('admin/filter.html', takes_context=True)
42 def filter_region_contrat(context):
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()
52 return {'title': u"région",
53 'choices': prepare_choices(regions.values_list('id', 'nom'), 'dossier__poste__implantation__region', context, remove=['pays', 'nord_sud'])}
54
55 @register.inclusion_tag('admin/filter.html', takes_context=True)
56 def 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)
61 def filter_implantation_dossier(context):
62 return {'title': u"implantation",
63 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'poste__implantation', context)}
64
65
66 @register.inclusion_tag('admin/filter.html', takes_context=True)
67 def filter_implantation_contrat(context):
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()
77 return {'title': u"implantation",
78 'choices': prepare_choices(implantations.values_list('id', 'nom'), 'dossier__poste__implantation', context)}
79
80
81 @register.inclusion_tag('admin/filter.html', takes_context=True)
82 def 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
86 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
87 def filter_echeance_contrat(context):
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'
94 return {'title': u"échéance",
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)
107 def 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', {}),
117 ('années à venir', {'%s__gte' % field_name: next_year.strftime('%Y-%m-%d')}),
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')}),
120 ('années passées', {'%s__lte' % field_name: last_year.strftime('%Y-%m-%d')}),
121 )
122 )}
123
124 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
125 def 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
143
144
145 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
146 def 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)
152 def filter_implantation_remun(context):
153 return {'title': u"implantation",
154 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'dossiers__poste__implantation', context)}
155
156 @register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
157 def table_header(context, headers):
158 return {'headers': headers}
159
160 def 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
177 def 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
188
189
190 def prepare_choices_date(field_name, context, links, remove=[]):
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
197
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
204
205 class SortHeaders:
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
210 self.header_defs = headers
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
218
219 def headers(self):
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()])
231 yield {
232 "class_attr": "sorted %s" % class_order if self.field_sorted(h[0]) else "",
233 "sortable": self.field_sorted(h[0]),
234 "url": url,
235 "text": h[1],
236 "style_attr": h[2] if len(h) > 2 else "",
237 }
238
239 def field_sorted(self, field):
240 return True if field not in self.not_sortable else False
241
242 @register.filter
243 def split(str, splitter):
244 return str.split(splitter)
245
246 @register.filter
247 def hash(h, key):
248 if key in h:
249 return h[key]
250 else:
251 raise Exception("%s does not exist" % key)
252
253 @register.filter
254 def is_float(v):
255 if type(v) == type(float()):
256 return True
257
258 @register.filter()
259 def contains(value, arg):
260 return arg in value