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