[#4713] Bugfix
[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
b0cf30b8
EMS
9from auf.django.references.models import \
10 Implantation, Region, ZoneAdministrative
75f0e87b 11
82c5e37d 12from project import groups
fd009814 13
82c5e37d 14from project.rh.models import TypeContrat
fd009814
PP
15
16register = Library()
17
18
549830eb 19COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
7821915f
PP
20
21
22@register.inclusion_tag('admin/filter.html', takes_context=True)
23def filter_comble(context):
b31ce2d7
EMS
24 return {
25 'title': 'comblé',
26 'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)
27 }
7821915f
PP
28
29
f0f6b03e 30@register.inclusion_tag('admin/filter.html', takes_context=True)
df37184c 31def filter_region(context, prefix=None):
df37184c 32 label = "".join([prefix or "", "implantation__region"])
b31ce2d7
EMS
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 }
fd009814
PP
40
41
f0f6b03e 42@register.inclusion_tag('admin/filter.html', takes_context=True)
b0cf30b8
EMS
43def 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(
9e3db2e5
EMS
48 ZoneAdministrative.objects.values_list('code', 'nom'), label,
49 context, remove=['pays', 'nord_sud']
b0cf30b8
EMS
50 )
51 }
52
53
54@register.inclusion_tag('admin/filter.html', takes_context=True)
df37184c 55def filter_implantation(context, prefix=None):
df37184c 56 label = "".join([prefix or "", "implantation"])
b31ce2d7
EMS
57 return {
58 'title': u"implantation",
59 'choices': prepare_choices(
60 Implantation.objects.values_list('id', 'nom'), label, context
61 )
62 }
fd009814
PP
63
64
f0f6b03e 65@register.inclusion_tag('admin/filter.html', takes_context=True)
b0cf30b8 66def filter_zone_administrative_contrat(context):
f96ec25c 67 request = context['request']
3383b2d1
OL
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)
b0cf30b8
EMS
73 zones = ZoneAdministrative.objects.filter(
74 code=employe.implantation.zone_administrative.code
75 )
f96ec25c 76 else:
9e3db2e5 77 zones = ZoneAdministrative.objects.all()
b0cf30b8
EMS
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 }
23e749e1 86
23e749e1 87
80518280 88@register.inclusion_tag('admin/filter.html', takes_context=True)
b0cf30b8 89def filter_zone_administrative_dossier(context):
b31ce2d7
EMS
90 return {
91 'title': u"région",
92 'choices': prepare_choices(
b0cf30b8
EMS
93 ZoneAdministrative.objects.values_list('code', 'nom'),
94 'poste__implantation__zone_administrative', context,
b31ce2d7
EMS
95 remove=['pays', 'nord_sud']
96 )
97 }
98
80518280
JPC
99
100@register.inclusion_tag('admin/filter.html', takes_context=True)
101def filter_implantation_dossier(context):
b31ce2d7
EMS
102 return {
103 'title': u"implantation",
104 'choices': prepare_choices(
105 Implantation.objects.values_list('id', 'nom'),
106 'poste__implantation', context
107 )
108 }
80518280 109
23e749e1 110
f0f6b03e 111@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 112def filter_implantation_contrat(context):
f96ec25c 113 request = context['request']
3383b2d1
OL
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)
b0cf30b8
EMS
119 implantations = Implantation.objects.filter(
120 zone_administrative=employe.implantation.zone_administrative
121 )
f96ec25c 122 else:
9e3db2e5
EMS
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 }
23e749e1
PP
131
132
f0f6b03e 133@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 134def filter_type_contrat(context):
b31ce2d7
EMS
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
23e749e1 143
72ac5e55
PP
144@register.inclusion_tag('admin/filter_select.html', takes_context=True)
145def filter_echeance_contrat(context):
eb204143 146 today = datetime.date.today()
b31ce2d7
EMS
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)
eb204143
JPC
150
151 field_name = 'date_fin'
72ac5e55 152 return {'title': u"échéance",
eb204143
JPC
153 'choices': prepare_choices_date(field_name, context, links=(
154 ('Tous', {}),
b31ce2d7
EMS
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 }),
eb204143
JPC
167 )
168 )}
169
b31ce2d7 170
eb204143
JPC
171@register.inclusion_tag('admin/filter_select.html', takes_context=True)
172def 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)
b31ce2d7 176 last_year = datetime.date(year - 1, 12, 31)
eb204143
JPC
177
178 field_name = 'date_debut'
179 return {'title': u"date début",
180 'choices': prepare_choices_date(field_name, context, links=(
181 ('Tous', {}),
b31ce2d7
EMS
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 }),
eb204143
JPC
192 )
193 )}
194
b31ce2d7 195
35beb92c
JPC
196@register.inclusion_tag('admin/filter_select.html', takes_context=True)
197def filter_a_venir(context):
198 today = datetime.date.today()
f8365137
EMS
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)
35beb92c
JPC
203
204 field_name = 'date_debut'
205 return {'title': u"à venir",
206 'choices': prepare_choices_date(field_name, context, links=(
207 ('Tous', {}),
b31ce2d7
EMS
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 }),
35beb92c
JPC
218 )
219 )}
220
221
af5073aa 222@register.inclusion_tag('admin/filter_select.html', takes_context=True)
b0cf30b8 223def filter_zone_administrative_remun(context):
b31ce2d7
EMS
224 return {
225 'title': u"région",
226 'choices': prepare_choices(
b0cf30b8
EMS
227 ZoneAdministrative.objects.values_list('code', 'nom'),
228 'dossiers__poste__implantation__zone_administrative', context,
b31ce2d7
EMS
229 remove=['pays', 'nord_sud']
230 )
231 }
af5073aa
PP
232
233
234@register.inclusion_tag('admin/filter_select.html', takes_context=True)
235def filter_implantation_remun(context):
b31ce2d7
EMS
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
af5073aa 244
4dade240 245@register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
9d53bc73 246def table_header(context, headers):
9fd09bdc 247 return {'headers': headers}
af5073aa 248
b31ce2d7 249
fd009814 250def get_query_string(request, new_params=None, remove=None):
b31ce2d7
EMS
251 if new_params is None:
252 new_params = {}
253 if remove is None:
254 remove = []
fd009814
PP
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
269def prepare_choices(choices, query_param, context, remove=[]):
270 request = context['request']
271 query_val = request.GET.get(query_param)
b31ce2d7
EMS
272 result = [{
273 'selected': query_val is None,
274 'query_string': get_query_string(request, {}, [query_param] + remove),
275 'display': 'Tout'
276 }]
fd009814 277 for k, v in choices:
b31ce2d7
EMS
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 })
fd009814 285 return result
72ac5e55
PP
286
287
eb204143 288def prepare_choices_date(field_name, context, links, remove=[]):
72ac5e55
PP
289 request = context['request']
290 params = request.GET
291 field_generic = '%s__' % field_name
b31ce2d7
EMS
292 date_params = dict([
293 (k, v) for k, v in params.items() if k.startswith(field_generic)
294 ])
72ac5e55 295
72ac5e55
PP
296 result = []
297 for title, param_dict in links:
b31ce2d7
EMS
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 })
72ac5e55 305 return result
9d53bc73 306
b31ce2d7 307
9d53bc73 308class SortHeaders:
b31ce2d7
EMS
309 def __init__(self, request, headers, order_field_type, order_field,
310 default_order_type="asc", not_sortable=[]):
4dade240
JPC
311 self.request = request
312 self.order_field_type = order_field_type
313 self.order_field = order_field
9d53bc73 314 self.header_defs = headers
4dade240
JPC
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
b31ce2d7
EMS
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
4dade240 324 self.not_sortable = not_sortable
9d53bc73
JPC
325
326 def headers(self):
4dade240
JPC
327 for h in self.header_defs:
328 params = self.params
329 if h[0] == self.current_order_field:
b31ce2d7
EMS
330 order_type = {
331 'asc': 'desc', 'desc': 'asc'
332 }[self.current_order_field_type]
4dade240
JPC
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]]
b31ce2d7
EMS
339 url = "?%s" % "&".join([
340 '%s=%s' % (param, value[0]) for param, value in params.items()
341 ])
9d53bc73 342 yield {
b31ce2d7
EMS
343 "class_attr": (
344 "sorted %s" % class_order
345 if self.field_sorted(h[0]) else ""
346 ),
4dade240
JPC
347 "sortable": self.field_sorted(h[0]),
348 "url": url,
9fd09bdc
JPC
349 "text": h[1],
350 "style_attr": h[2] if len(h) > 2 else "",
9d53bc73
JPC
351 }
352
4dade240
JPC
353 def field_sorted(self, field):
354 return True if field not in self.not_sortable else False
355
b31ce2d7 356
9202c5db
JPC
357@register.filter
358def split(str, splitter):
359 return str.split(splitter)
57e2b793 360
b31ce2d7 361
57e2b793 362@register.filter
3244a3c2 363def hash(h, key):
57e2b793
JPC
364 if key in h:
365 return h[key]
366 else:
367 raise Exception("%s does not exist" % key)
3244a3c2 368
b31ce2d7 369
3244a3c2
JPC
370@register.filter
371def is_float(v):
372 if type(v) == type(float()):
373 return True
a6927189 374
b31ce2d7 375
a6927189
JPC
376@register.filter()
377def contains(value, arg):
b31ce2d7 378 return arg in value