PEP8
[auf_rh_dae.git] / project / rh / templatetags / rapports.py
1 # -*- coding: utf-8 -*-
2
3 import datetime
4
5 from datamaster_modeles.models import Implantation, Region
6 from django.utils.encoding import smart_unicode
7 from django.template import Library
8 from django.utils.http import urlencode
9
10 from project.rh.models import TypeContrat
11
12
13 register = Library()
14
15
16 COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
17
18
19 @register.inclusion_tag('admin/filter.html', takes_context=True)
20 def filter_comble(context):
21 return {
22 'title': 'comblé',
23 'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)
24 }
25
26
27 @register.inclusion_tag('admin/filter.html', takes_context=True)
28 def filter_region(context, prefix=None):
29 label = "".join([prefix or "", "implantation__region"])
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 }
37
38
39 @register.inclusion_tag('admin/filter.html', takes_context=True)
40 def filter_implantation(context, prefix=None):
41 label = "".join([prefix or "", "implantation"])
42 return {
43 'title': u"implantation",
44 'choices': prepare_choices(
45 Implantation.objects.values_list('id', 'nom'), label, context
46 )
47 }
48
49
50 @register.inclusion_tag('admin/filter.html', takes_context=True)
51 def filter_region_contrat(context):
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
61
62 @register.inclusion_tag('admin/filter.html', takes_context=True)
63 def filter_region_dossier(context):
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
73
74 @register.inclusion_tag('admin/filter.html', takes_context=True)
75 def filter_implantation_dossier(context):
76 return {
77 'title': u"implantation",
78 'choices': prepare_choices(
79 Implantation.objects.values_list('id', 'nom'),
80 'poste__implantation', context
81 )
82 }
83
84
85 @register.inclusion_tag('admin/filter.html', takes_context=True)
86 def filter_implantation_contrat(context):
87 return {
88 'title': u"implantation",
89 'choices': prepare_choices(
90 Implantation.objects.values_list('id', 'nom'),
91 'dossier__poste__implantation', context
92 )
93 }
94
95
96 @register.inclusion_tag('admin/filter.html', takes_context=True)
97 def filter_type_contrat(context):
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
106
107 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
108 def filter_echeance_contrat(context):
109 today = datetime.date.today()
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)
113
114 field_name = 'date_fin'
115 return {'title': u"échéance",
116 'choices': prepare_choices_date(field_name, context, links=(
117 ('Tous', {}),
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 }),
130 )
131 )}
132
133
134 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
135 def 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)
139 last_year = datetime.date(year - 1, 12, 31)
140
141 field_name = 'date_debut'
142 return {'title': u"date début",
143 'choices': prepare_choices_date(field_name, context, links=(
144 ('Tous', {}),
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 }),
155 )
156 )}
157
158
159 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
160 def filter_a_venir(context):
161 today = datetime.date.today()
162 year, month, day = datetime.date.today().timetuple()[:3]
163 mois_prochain = datetime.date(
164 year + (month + 1) / 13, (month + 1) % 12, 1
165 )
166 this_month = datetime.date(year, month, 1)
167
168 field_name = 'date_debut'
169 return {'title': u"à venir",
170 'choices': prepare_choices_date(field_name, context, links=(
171 ('Tous', {}),
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 }),
182 )
183 )}
184
185
186 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
187 def filter_region_remun(context):
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 }
196
197
198 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
199 def filter_implantation_remun(context):
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
208
209 @register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
210 def table_header(context, headers):
211 return {'headers': headers}
212
213
214 def get_query_string(request, new_params=None, remove=None):
215 if new_params is None:
216 new_params = {}
217 if remove is None:
218 remove = []
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
233 def prepare_choices(choices, query_param, context, remove=[]):
234 request = context['request']
235 query_val = request.GET.get(query_param)
236 result = [{
237 'selected': query_val is None,
238 'query_string': get_query_string(request, {}, [query_param] + remove),
239 'display': 'Tout'
240 }]
241 for k, v in choices:
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 })
249 return result
250
251
252 def prepare_choices_date(field_name, context, links, remove=[]):
253 request = context['request']
254 params = request.GET
255 field_generic = '%s__' % field_name
256 date_params = dict([
257 (k, v) for k, v in params.items() if k.startswith(field_generic)
258 ])
259
260 result = []
261 for title, param_dict in links:
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 })
269 return result
270
271
272 class SortHeaders:
273 def __init__(self, request, headers, order_field_type, order_field,
274 default_order_type="asc", not_sortable=[]):
275 self.request = request
276 self.order_field_type = order_field_type
277 self.order_field = order_field
278 self.header_defs = headers
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
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
288 self.not_sortable = not_sortable
289
290 def headers(self):
291 for h in self.header_defs:
292 params = self.params
293 if h[0] == self.current_order_field:
294 order_type = {
295 'asc': 'desc', 'desc': 'asc'
296 }[self.current_order_field_type]
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]]
303 url = "?%s" % "&".join([
304 '%s=%s' % (param, value[0]) for param, value in params.items()
305 ])
306 yield {
307 "class_attr": (
308 "sorted %s" % class_order
309 if self.field_sorted(h[0]) else ""
310 ),
311 "sortable": self.field_sorted(h[0]),
312 "url": url,
313 "text": h[1],
314 "style_attr": h[2] if len(h) > 2 else "",
315 }
316
317 def field_sorted(self, field):
318 return True if field not in self.not_sortable else False
319
320
321 @register.filter
322 def split(str, splitter):
323 return str.split(splitter)
324
325
326 @register.filter
327 def hash(h, key):
328 if key in h:
329 return h[key]
330 else:
331 raise Exception("%s does not exist" % key)
332
333
334 @register.filter
335 def is_float(v):
336 if type(v) == type(float()):
337 return True
338
339
340 @register.filter()
341 def contains(value, arg):
342 return arg in value