upgrade modules
[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(
48 ZoneAdministrative.objects.values_list('code', 'nom'), label, context,
49 remove=['pays', 'nord_sud']
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:
b0cf30b8
EMS
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 }
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
OL
122 else:
123 implantations = Implantation.objects.all()
23e749e1 124 return {'title': u"implantation",
f96ec25c 125 'choices': prepare_choices(implantations.values_list('id', 'nom'), 'dossier__poste__implantation', context)}
23e749e1
PP
126
127
f0f6b03e 128@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 129def filter_type_contrat(context):
b31ce2d7
EMS
130 return {
131 'title': u"type de contrat",
132 'choices': prepare_choices(
133 TypeContrat.objects.values_list('id', 'nom'), 'type_contrat',
134 context
135 )
136 }
137
23e749e1 138
72ac5e55
PP
139@register.inclusion_tag('admin/filter_select.html', takes_context=True)
140def filter_echeance_contrat(context):
eb204143 141 today = datetime.date.today()
b31ce2d7
EMS
142 three_months = today + datetime.timedelta(days=3 * 30)
143 six_months = today + datetime.timedelta(days=6 * 30)
144 twelve_months = today + datetime.timedelta(days=12 * 30)
eb204143
JPC
145
146 field_name = 'date_fin'
72ac5e55 147 return {'title': u"échéance",
eb204143
JPC
148 'choices': prepare_choices_date(field_name, context, links=(
149 ('Tous', {}),
b31ce2d7
EMS
150 ('moins de 3 mois', {
151 '%s__gte' % field_name: today.strftime('%Y-%m-%d'),
152 '%s__lte' % field_name: three_months.strftime('%Y-%m-%d')
153 }),
154 ('3 à 6 mois', {
155 '%s__gte' % field_name: three_months.strftime('%Y-%m-%d'),
156 '%s__lte' % field_name: six_months.strftime('%Y-%m-%d')
157 }),
158 ('6 à 12 mois', {
159 '%s__gte' % field_name: six_months.strftime('%Y-%m-%d'),
160 '%s__lte' % field_name: twelve_months.strftime('%Y-%m-%d')
161 }),
eb204143
JPC
162 )
163 )}
164
b31ce2d7 165
eb204143
JPC
166@register.inclusion_tag('admin/filter_select.html', takes_context=True)
167def filter_debut_contrat(context):
168 year = datetime.date.today().timetuple()[0]
169 this_year = datetime.date(year, 1, 1)
170 next_year = datetime.date(year + 1, 1, 1)
b31ce2d7 171 last_year = datetime.date(year - 1, 12, 31)
eb204143
JPC
172
173 field_name = 'date_debut'
174 return {'title': u"date début",
175 'choices': prepare_choices_date(field_name, context, links=(
176 ('Tous', {}),
b31ce2d7
EMS
177 ('années à venir', {
178 '%s__gte' % field_name: next_year.strftime('%Y-%m-%d')
179 }),
180 ('cette anneée', {
181 '%s__gte' % field_name: this_year.strftime('%Y-%m-%d'),
182 '%s__lt' % field_name: next_year.strftime('%Y-%m-%d')
183 }),
184 ('années passées', {
185 '%s__lte' % field_name: last_year.strftime('%Y-%m-%d')
186 }),
eb204143
JPC
187 )
188 )}
189
b31ce2d7 190
35beb92c
JPC
191@register.inclusion_tag('admin/filter_select.html', takes_context=True)
192def filter_a_venir(context):
193 today = datetime.date.today()
194 year, month, day = datetime.date.today().timetuple()[:3]
b31ce2d7
EMS
195 mois_prochain = datetime.date(
196 year + (month + 1) / 13, (month + 1) % 12, 1
197 )
198 this_month = datetime.date(year, month, 1)
35beb92c
JPC
199
200 field_name = 'date_debut'
201 return {'title': u"à venir",
202 'choices': prepare_choices_date(field_name, context, links=(
203 ('Tous', {}),
b31ce2d7
EMS
204 ('à venir', {
205 '%s__gt' % field_name: today.strftime('%Y-%m-%d')
206 }),
207 ('à venir mois prochain', {
208 '%s__gte' % field_name: mois_prochain.strftime('%Y-%m-%d')
209 }),
210 ('à venir ce mois', {
211 '%s__gte' % field_name: this_month.strftime('%Y-%m-%d'),
212 '%s__lt' % field_name: mois_prochain.strftime('%Y-%m-%d')
213 }),
35beb92c
JPC
214 )
215 )}
216
217
af5073aa 218@register.inclusion_tag('admin/filter_select.html', takes_context=True)
b0cf30b8 219def filter_zone_administrative_remun(context):
b31ce2d7
EMS
220 return {
221 'title': u"région",
222 'choices': prepare_choices(
b0cf30b8
EMS
223 ZoneAdministrative.objects.values_list('code', 'nom'),
224 'dossiers__poste__implantation__zone_administrative', context,
b31ce2d7
EMS
225 remove=['pays', 'nord_sud']
226 )
227 }
af5073aa
PP
228
229
230@register.inclusion_tag('admin/filter_select.html', takes_context=True)
231def filter_implantation_remun(context):
b31ce2d7
EMS
232 return {
233 'title': u"implantation",
234 'choices': prepare_choices(
235 Implantation.objects.values_list('id', 'nom'),
236 'dossiers__poste__implantation', context
237 )
238 }
239
af5073aa 240
4dade240 241@register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
9d53bc73 242def table_header(context, headers):
9fd09bdc 243 return {'headers': headers}
af5073aa 244
b31ce2d7 245
fd009814 246def get_query_string(request, new_params=None, remove=None):
b31ce2d7
EMS
247 if new_params is None:
248 new_params = {}
249 if remove is None:
250 remove = []
fd009814
PP
251 p = dict(request.GET.items())
252 for r in remove:
253 for k in p.keys():
254 if k.startswith(r):
255 del p[k]
256 for k, v in new_params.items():
257 if v is None:
258 if k in p:
259 del p[k]
260 else:
261 p[k] = v
262 return '?%s' % urlencode(p)
263
264
265def prepare_choices(choices, query_param, context, remove=[]):
266 request = context['request']
267 query_val = request.GET.get(query_param)
b31ce2d7
EMS
268 result = [{
269 'selected': query_val is None,
270 'query_string': get_query_string(request, {}, [query_param] + remove),
271 'display': 'Tout'
272 }]
fd009814 273 for k, v in choices:
b31ce2d7
EMS
274 result.append({
275 'selected': smart_unicode(k) == query_val,
276 'query_string': get_query_string(
277 request, {query_param: k}, remove
278 ),
279 'display': v
280 })
fd009814 281 return result
72ac5e55
PP
282
283
eb204143 284def prepare_choices_date(field_name, context, links, remove=[]):
72ac5e55
PP
285 request = context['request']
286 params = request.GET
287 field_generic = '%s__' % field_name
b31ce2d7
EMS
288 date_params = dict([
289 (k, v) for k, v in params.items() if k.startswith(field_generic)
290 ])
72ac5e55 291
72ac5e55
PP
292 result = []
293 for title, param_dict in links:
b31ce2d7
EMS
294 result.append({
295 'selected': date_params == param_dict,
296 'query_string': get_query_string(
297 request, param_dict, [field_generic]
298 ),
299 'display': title
300 })
72ac5e55 301 return result
9d53bc73 302
b31ce2d7 303
9d53bc73 304class SortHeaders:
b31ce2d7
EMS
305 def __init__(self, request, headers, order_field_type, order_field,
306 default_order_type="asc", not_sortable=[]):
4dade240
JPC
307 self.request = request
308 self.order_field_type = order_field_type
309 self.order_field = order_field
9d53bc73 310 self.header_defs = headers
4dade240
JPC
311 self.params = dict(request.GET)
312 if default_order_type not in ('asc', 'desc'):
313 raise AttributeError(u"L'ordre par défaut n'est pas valide")
314 self.default_order_type = default_order_type
b31ce2d7
EMS
315 self.current_order_field = \
316 self.params[self.order_field][0] \
317 if self.order_field in self.params else None
318 self.current_order_field_type = self.params[self.order_field_type][0] \
319 if self.order_field_type in self.params else None
4dade240 320 self.not_sortable = not_sortable
9d53bc73
JPC
321
322 def headers(self):
4dade240
JPC
323 for h in self.header_defs:
324 params = self.params
325 if h[0] == self.current_order_field:
b31ce2d7
EMS
326 order_type = {
327 'asc': 'desc', 'desc': 'asc'
328 }[self.current_order_field_type]
4dade240
JPC
329 class_order = "%sending" % self.current_order_field_type
330 else:
331 order_type = self.default_order_type
332 class_order = ""
333 params[self.order_field_type] = [order_type]
334 params[self.order_field] = [h[0]]
b31ce2d7
EMS
335 url = "?%s" % "&".join([
336 '%s=%s' % (param, value[0]) for param, value in params.items()
337 ])
9d53bc73 338 yield {
b31ce2d7
EMS
339 "class_attr": (
340 "sorted %s" % class_order
341 if self.field_sorted(h[0]) else ""
342 ),
4dade240
JPC
343 "sortable": self.field_sorted(h[0]),
344 "url": url,
9fd09bdc
JPC
345 "text": h[1],
346 "style_attr": h[2] if len(h) > 2 else "",
9d53bc73
JPC
347 }
348
4dade240
JPC
349 def field_sorted(self, field):
350 return True if field not in self.not_sortable else False
351
b31ce2d7 352
9202c5db
JPC
353@register.filter
354def split(str, splitter):
355 return str.split(splitter)
57e2b793 356
b31ce2d7 357
57e2b793 358@register.filter
3244a3c2 359def hash(h, key):
57e2b793
JPC
360 if key in h:
361 return h[key]
362 else:
363 raise Exception("%s does not exist" % key)
3244a3c2 364
b31ce2d7 365
3244a3c2
JPC
366@register.filter
367def is_float(v):
368 if type(v) == type(float()):
369 return True
a6927189 370
b31ce2d7 371
a6927189
JPC
372@register.filter()
373def contains(value, arg):
b31ce2d7 374 return arg in value