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