PEP8
[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()
199 year, month, day = datetime.date.today().timetuple()[:3]
b31ce2d7
EMS
200 mois_prochain = datetime.date(
201 year + (month + 1) / 13, (month + 1) % 12, 1
202 )
203 this_month = datetime.date(year, month, 1)
35beb92c
JPC
204
205 field_name = 'date_debut'
206 return {'title': u"à venir",
207 'choices': prepare_choices_date(field_name, context, links=(
208 ('Tous', {}),
b31ce2d7
EMS
209 ('à venir', {
210 '%s__gt' % field_name: today.strftime('%Y-%m-%d')
211 }),
212 ('à venir mois prochain', {
213 '%s__gte' % field_name: mois_prochain.strftime('%Y-%m-%d')
214 }),
215 ('à venir ce mois', {
216 '%s__gte' % field_name: this_month.strftime('%Y-%m-%d'),
217 '%s__lt' % field_name: mois_prochain.strftime('%Y-%m-%d')
218 }),
35beb92c
JPC
219 )
220 )}
221
222
af5073aa 223@register.inclusion_tag('admin/filter_select.html', takes_context=True)
b0cf30b8 224def filter_zone_administrative_remun(context):
b31ce2d7
EMS
225 return {
226 'title': u"région",
227 'choices': prepare_choices(
b0cf30b8
EMS
228 ZoneAdministrative.objects.values_list('code', 'nom'),
229 'dossiers__poste__implantation__zone_administrative', context,
b31ce2d7
EMS
230 remove=['pays', 'nord_sud']
231 )
232 }
af5073aa
PP
233
234
235@register.inclusion_tag('admin/filter_select.html', takes_context=True)
236def filter_implantation_remun(context):
b31ce2d7
EMS
237 return {
238 'title': u"implantation",
239 'choices': prepare_choices(
240 Implantation.objects.values_list('id', 'nom'),
241 'dossiers__poste__implantation', context
242 )
243 }
244
af5073aa 245
4dade240 246@register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
9d53bc73 247def table_header(context, headers):
9fd09bdc 248 return {'headers': headers}
af5073aa 249
b31ce2d7 250
fd009814 251def get_query_string(request, new_params=None, remove=None):
b31ce2d7
EMS
252 if new_params is None:
253 new_params = {}
254 if remove is None:
255 remove = []
fd009814
PP
256 p = dict(request.GET.items())
257 for r in remove:
258 for k in p.keys():
259 if k.startswith(r):
260 del p[k]
261 for k, v in new_params.items():
262 if v is None:
263 if k in p:
264 del p[k]
265 else:
266 p[k] = v
267 return '?%s' % urlencode(p)
268
269
270def prepare_choices(choices, query_param, context, remove=[]):
271 request = context['request']
272 query_val = request.GET.get(query_param)
b31ce2d7
EMS
273 result = [{
274 'selected': query_val is None,
275 'query_string': get_query_string(request, {}, [query_param] + remove),
276 'display': 'Tout'
277 }]
fd009814 278 for k, v in choices:
b31ce2d7
EMS
279 result.append({
280 'selected': smart_unicode(k) == query_val,
281 'query_string': get_query_string(
282 request, {query_param: k}, remove
283 ),
284 'display': v
285 })
fd009814 286 return result
72ac5e55
PP
287
288
eb204143 289def prepare_choices_date(field_name, context, links, remove=[]):
72ac5e55
PP
290 request = context['request']
291 params = request.GET
292 field_generic = '%s__' % field_name
b31ce2d7
EMS
293 date_params = dict([
294 (k, v) for k, v in params.items() if k.startswith(field_generic)
295 ])
72ac5e55 296
72ac5e55
PP
297 result = []
298 for title, param_dict in links:
b31ce2d7
EMS
299 result.append({
300 'selected': date_params == param_dict,
301 'query_string': get_query_string(
302 request, param_dict, [field_generic]
303 ),
304 'display': title
305 })
72ac5e55 306 return result
9d53bc73 307
b31ce2d7 308
9d53bc73 309class SortHeaders:
b31ce2d7
EMS
310 def __init__(self, request, headers, order_field_type, order_field,
311 default_order_type="asc", not_sortable=[]):
4dade240
JPC
312 self.request = request
313 self.order_field_type = order_field_type
314 self.order_field = order_field
9d53bc73 315 self.header_defs = headers
4dade240
JPC
316 self.params = dict(request.GET)
317 if default_order_type not in ('asc', 'desc'):
318 raise AttributeError(u"L'ordre par défaut n'est pas valide")
319 self.default_order_type = default_order_type
b31ce2d7
EMS
320 self.current_order_field = \
321 self.params[self.order_field][0] \
322 if self.order_field in self.params else None
323 self.current_order_field_type = self.params[self.order_field_type][0] \
324 if self.order_field_type in self.params else None
4dade240 325 self.not_sortable = not_sortable
9d53bc73
JPC
326
327 def headers(self):
4dade240
JPC
328 for h in self.header_defs:
329 params = self.params
330 if h[0] == self.current_order_field:
b31ce2d7
EMS
331 order_type = {
332 'asc': 'desc', 'desc': 'asc'
333 }[self.current_order_field_type]
4dade240
JPC
334 class_order = "%sending" % self.current_order_field_type
335 else:
336 order_type = self.default_order_type
337 class_order = ""
338 params[self.order_field_type] = [order_type]
339 params[self.order_field] = [h[0]]
b31ce2d7
EMS
340 url = "?%s" % "&".join([
341 '%s=%s' % (param, value[0]) for param, value in params.items()
342 ])
9d53bc73 343 yield {
b31ce2d7
EMS
344 "class_attr": (
345 "sorted %s" % class_order
346 if self.field_sorted(h[0]) else ""
347 ),
4dade240
JPC
348 "sortable": self.field_sorted(h[0]),
349 "url": url,
9fd09bdc
JPC
350 "text": h[1],
351 "style_attr": h[2] if len(h) > 2 else "",
9d53bc73
JPC
352 }
353
4dade240
JPC
354 def field_sorted(self, field):
355 return True if field not in self.not_sortable else False
356
b31ce2d7 357
9202c5db
JPC
358@register.filter
359def split(str, splitter):
360 return str.split(splitter)
57e2b793 361
b31ce2d7 362
57e2b793 363@register.filter
3244a3c2 364def hash(h, key):
57e2b793
JPC
365 if key in h:
366 return h[key]
367 else:
368 raise Exception("%s does not exist" % key)
3244a3c2 369
b31ce2d7 370
3244a3c2
JPC
371@register.filter
372def is_float(v):
373 if type(v) == type(float()):
374 return True
a6927189 375
b31ce2d7 376
a6927189
JPC
377@register.filter()
378def contains(value, arg):
b31ce2d7 379 return arg in value