[#4713] Bugfix
[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 auf.django.references.models import \
10 Implantation, Region, ZoneAdministrative
11
12 from project import groups
13
14 from project.rh.models import TypeContrat
15
16 register = Library()
17
18
19 COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
20
21
22 @register.inclusion_tag('admin/filter.html', takes_context=True)
23 def filter_comble(context):
24 return {
25 'title': 'comblé',
26 'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)
27 }
28
29
30 @register.inclusion_tag('admin/filter.html', takes_context=True)
31 def filter_region(context, prefix=None):
32 label = "".join([prefix or "", "implantation__region"])
33 return {
34 'title': u"région",
35 'choices': prepare_choices(
36 Region.objects.values_list('id', 'nom'), label, context,
37 remove=['pays', 'nord_sud']
38 )
39 }
40
41
42 @register.inclusion_tag('admin/filter.html', takes_context=True)
43 def filter_zone_administrative(context, prefix=None):
44 label = "".join([prefix or "", "implantation__zone_administrative"])
45 return {
46 'title': u"zone administrative",
47 'choices': prepare_choices(
48 ZoneAdministrative.objects.values_list('code', 'nom'), label,
49 context, remove=['pays', 'nord_sud']
50 )
51 }
52
53
54 @register.inclusion_tag('admin/filter.html', takes_context=True)
55 def filter_implantation(context, prefix=None):
56 label = "".join([prefix or "", "implantation"])
57 return {
58 'title': u"implantation",
59 'choices': prepare_choices(
60 Implantation.objects.values_list('id', 'nom'), label, context
61 )
62 }
63
64
65 @register.inclusion_tag('admin/filter.html', takes_context=True)
66 def filter_zone_administrative_contrat(context):
67 request = context['request']
68 user_groups = [g.name for g in request.user.groups.all()]
69 if groups.CORRESPONDANT_RH in user_groups or\
70 groups.ADMINISTRATEURS in user_groups or\
71 groups.DIRECTEUR_DE_BUREAU in user_groups:
72 employe = groups.get_employe_from_user(request.user)
73 zones = ZoneAdministrative.objects.filter(
74 code=employe.implantation.zone_administrative.code
75 )
76 else:
77 zones = ZoneAdministrative.objects.all()
78 return {
79 'title': u"région",
80 'choices': prepare_choices(
81 zones.values_list('code', 'nom'),
82 'dossier__poste__implantation__zone_administrative',
83 context, remove=['pays', 'nord_sud']
84 )
85 }
86
87
88 @register.inclusion_tag('admin/filter.html', takes_context=True)
89 def filter_zone_administrative_dossier(context):
90 return {
91 'title': u"région",
92 'choices': prepare_choices(
93 ZoneAdministrative.objects.values_list('code', 'nom'),
94 'poste__implantation__zone_administrative', context,
95 remove=['pays', 'nord_sud']
96 )
97 }
98
99
100 @register.inclusion_tag('admin/filter.html', takes_context=True)
101 def filter_implantation_dossier(context):
102 return {
103 'title': u"implantation",
104 'choices': prepare_choices(
105 Implantation.objects.values_list('id', 'nom'),
106 'poste__implantation', context
107 )
108 }
109
110
111 @register.inclusion_tag('admin/filter.html', takes_context=True)
112 def filter_implantation_contrat(context):
113 request = context['request']
114 user_groups = [g.name for g in request.user.groups.all()]
115 if groups.CORRESPONDANT_RH in user_groups or\
116 groups.ADMINISTRATEURS in user_groups or\
117 groups.DIRECTEUR_DE_BUREAU in user_groups:
118 employe = groups.get_employe_from_user(request.user)
119 implantations = Implantation.objects.filter(
120 zone_administrative=employe.implantation.zone_administrative
121 )
122 else:
123 implantations = Implantation.objects.all()
124 return {
125 'title': u"implantation",
126 'choices': prepare_choices(
127 implantations.values_list('id', 'nom'),
128 'dossier__poste__implantation', context
129 )
130 }
131
132
133 @register.inclusion_tag('admin/filter.html', takes_context=True)
134 def filter_type_contrat(context):
135 return {
136 'title': u"type de contrat",
137 'choices': prepare_choices(
138 TypeContrat.objects.values_list('id', 'nom'), 'type_contrat',
139 context
140 )
141 }
142
143
144 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
145 def filter_echeance_contrat(context):
146 today = datetime.date.today()
147 three_months = today + datetime.timedelta(days=3 * 30)
148 six_months = today + datetime.timedelta(days=6 * 30)
149 twelve_months = today + datetime.timedelta(days=12 * 30)
150
151 field_name = 'date_fin'
152 return {'title': u"échéance",
153 'choices': prepare_choices_date(field_name, context, links=(
154 ('Tous', {}),
155 ('moins de 3 mois', {
156 '%s__gte' % field_name: today.strftime('%Y-%m-%d'),
157 '%s__lte' % field_name: three_months.strftime('%Y-%m-%d')
158 }),
159 ('3 à 6 mois', {
160 '%s__gte' % field_name: three_months.strftime('%Y-%m-%d'),
161 '%s__lte' % field_name: six_months.strftime('%Y-%m-%d')
162 }),
163 ('6 à 12 mois', {
164 '%s__gte' % field_name: six_months.strftime('%Y-%m-%d'),
165 '%s__lte' % field_name: twelve_months.strftime('%Y-%m-%d')
166 }),
167 )
168 )}
169
170
171 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
172 def filter_debut_contrat(context):
173 year = datetime.date.today().timetuple()[0]
174 this_year = datetime.date(year, 1, 1)
175 next_year = datetime.date(year + 1, 1, 1)
176 last_year = datetime.date(year - 1, 12, 31)
177
178 field_name = 'date_debut'
179 return {'title': u"date début",
180 'choices': prepare_choices_date(field_name, context, links=(
181 ('Tous', {}),
182 ('années à venir', {
183 '%s__gte' % field_name: next_year.strftime('%Y-%m-%d')
184 }),
185 ('cette anneée', {
186 '%s__gte' % field_name: this_year.strftime('%Y-%m-%d'),
187 '%s__lt' % field_name: next_year.strftime('%Y-%m-%d')
188 }),
189 ('années passées', {
190 '%s__lte' % field_name: last_year.strftime('%Y-%m-%d')
191 }),
192 )
193 )}
194
195
196 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
197 def filter_a_venir(context):
198 today = datetime.date.today()
199 mois_prochain = datetime.date(today.year, today.month + 1, 1) \
200 if today.month < 12 \
201 else datetime.date(today.year + 1, today.month, 1)
202 this_month = datetime.date(today.year, today.month, 1)
203
204 field_name = 'date_debut'
205 return {'title': u"à venir",
206 'choices': prepare_choices_date(field_name, context, links=(
207 ('Tous', {}),
208 ('à venir', {
209 '%s__gt' % field_name: today.strftime('%Y-%m-%d')
210 }),
211 ('à venir mois prochain', {
212 '%s__gte' % field_name: mois_prochain.strftime('%Y-%m-%d')
213 }),
214 ('à venir ce mois', {
215 '%s__gte' % field_name: this_month.strftime('%Y-%m-%d'),
216 '%s__lt' % field_name: mois_prochain.strftime('%Y-%m-%d')
217 }),
218 )
219 )}
220
221
222 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
223 def filter_zone_administrative_remun(context):
224 return {
225 'title': u"région",
226 'choices': prepare_choices(
227 ZoneAdministrative.objects.values_list('code', 'nom'),
228 'dossiers__poste__implantation__zone_administrative', context,
229 remove=['pays', 'nord_sud']
230 )
231 }
232
233
234 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
235 def filter_implantation_remun(context):
236 return {
237 'title': u"implantation",
238 'choices': prepare_choices(
239 Implantation.objects.values_list('id', 'nom'),
240 'dossiers__poste__implantation', context
241 )
242 }
243
244
245 @register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
246 def table_header(context, headers):
247 return {'headers': headers}
248
249
250 def get_query_string(request, new_params=None, remove=None):
251 if new_params is None:
252 new_params = {}
253 if remove is None:
254 remove = []
255 p = dict(request.GET.items())
256 for r in remove:
257 for k in p.keys():
258 if k.startswith(r):
259 del p[k]
260 for k, v in new_params.items():
261 if v is None:
262 if k in p:
263 del p[k]
264 else:
265 p[k] = v
266 return '?%s' % urlencode(p)
267
268
269 def prepare_choices(choices, query_param, context, remove=[]):
270 request = context['request']
271 query_val = request.GET.get(query_param)
272 result = [{
273 'selected': query_val is None,
274 'query_string': get_query_string(request, {}, [query_param] + remove),
275 'display': 'Tout'
276 }]
277 for k, v in choices:
278 result.append({
279 'selected': smart_unicode(k) == query_val,
280 'query_string': get_query_string(
281 request, {query_param: k}, remove
282 ),
283 'display': v
284 })
285 return result
286
287
288 def prepare_choices_date(field_name, context, links, remove=[]):
289 request = context['request']
290 params = request.GET
291 field_generic = '%s__' % field_name
292 date_params = dict([
293 (k, v) for k, v in params.items() if k.startswith(field_generic)
294 ])
295
296 result = []
297 for title, param_dict in links:
298 result.append({
299 'selected': date_params == param_dict,
300 'query_string': get_query_string(
301 request, param_dict, [field_generic]
302 ),
303 'display': title
304 })
305 return result
306
307
308 class SortHeaders:
309 def __init__(self, request, headers, order_field_type, order_field,
310 default_order_type="asc", not_sortable=[]):
311 self.request = request
312 self.order_field_type = order_field_type
313 self.order_field = order_field
314 self.header_defs = headers
315 self.params = dict(request.GET)
316 if default_order_type not in ('asc', 'desc'):
317 raise AttributeError(u"L'ordre par défaut n'est pas valide")
318 self.default_order_type = default_order_type
319 self.current_order_field = \
320 self.params[self.order_field][0] \
321 if self.order_field in self.params else None
322 self.current_order_field_type = self.params[self.order_field_type][0] \
323 if self.order_field_type in self.params else None
324 self.not_sortable = not_sortable
325
326 def headers(self):
327 for h in self.header_defs:
328 params = self.params
329 if h[0] == self.current_order_field:
330 order_type = {
331 'asc': 'desc', 'desc': 'asc'
332 }[self.current_order_field_type]
333 class_order = "%sending" % self.current_order_field_type
334 else:
335 order_type = self.default_order_type
336 class_order = ""
337 params[self.order_field_type] = [order_type]
338 params[self.order_field] = [h[0]]
339 url = "?%s" % "&".join([
340 '%s=%s' % (param, value[0]) for param, value in params.items()
341 ])
342 yield {
343 "class_attr": (
344 "sorted %s" % class_order
345 if self.field_sorted(h[0]) else ""
346 ),
347 "sortable": self.field_sorted(h[0]),
348 "url": url,
349 "text": h[1],
350 "style_attr": h[2] if len(h) > 2 else "",
351 }
352
353 def field_sorted(self, field):
354 return True if field not in self.not_sortable else False
355
356
357 @register.filter
358 def split(str, splitter):
359 return str.split(splitter)
360
361
362 @register.filter
363 def hash(h, key):
364 if key in h:
365 return h[key]
366 else:
367 raise Exception("%s does not exist" % key)
368
369
370 @register.filter
371 def is_float(v):
372 if type(v) == type(float()):
373 return True
374
375
376 @register.filter()
377 def contains(value, arg):
378 return arg in value