484326c1e720a40d58e191968d540120f3471465
[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, context,
49 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 {'title': u"implantation",
125 'choices': prepare_choices(implantations.values_list('id', 'nom'), 'dossier__poste__implantation', context)}
126
127
128 @register.inclusion_tag('admin/filter.html', takes_context=True)
129 def filter_type_contrat(context):
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
138
139 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
140 def filter_echeance_contrat(context):
141 today = datetime.date.today()
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)
145
146 field_name = 'date_fin'
147 return {'title': u"échéance",
148 'choices': prepare_choices_date(field_name, context, links=(
149 ('Tous', {}),
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 }),
162 )
163 )}
164
165
166 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
167 def 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)
171 last_year = datetime.date(year - 1, 12, 31)
172
173 field_name = 'date_debut'
174 return {'title': u"date début",
175 'choices': prepare_choices_date(field_name, context, links=(
176 ('Tous', {}),
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 }),
187 )
188 )}
189
190
191 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
192 def filter_a_venir(context):
193 today = datetime.date.today()
194 year, month, day = datetime.date.today().timetuple()[:3]
195 mois_prochain = datetime.date(
196 year + (month + 1) / 13, (month + 1) % 12, 1
197 )
198 this_month = datetime.date(year, month, 1)
199
200 field_name = 'date_debut'
201 return {'title': u"à venir",
202 'choices': prepare_choices_date(field_name, context, links=(
203 ('Tous', {}),
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 }),
214 )
215 )}
216
217
218 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
219 def filter_zone_administrative_remun(context):
220 return {
221 'title': u"région",
222 'choices': prepare_choices(
223 ZoneAdministrative.objects.values_list('code', 'nom'),
224 'dossiers__poste__implantation__zone_administrative', context,
225 remove=['pays', 'nord_sud']
226 )
227 }
228
229
230 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
231 def filter_implantation_remun(context):
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
240
241 @register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
242 def table_header(context, headers):
243 return {'headers': headers}
244
245
246 def get_query_string(request, new_params=None, remove=None):
247 if new_params is None:
248 new_params = {}
249 if remove is None:
250 remove = []
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
265 def prepare_choices(choices, query_param, context, remove=[]):
266 request = context['request']
267 query_val = request.GET.get(query_param)
268 result = [{
269 'selected': query_val is None,
270 'query_string': get_query_string(request, {}, [query_param] + remove),
271 'display': 'Tout'
272 }]
273 for k, v in choices:
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 })
281 return result
282
283
284 def prepare_choices_date(field_name, context, links, remove=[]):
285 request = context['request']
286 params = request.GET
287 field_generic = '%s__' % field_name
288 date_params = dict([
289 (k, v) for k, v in params.items() if k.startswith(field_generic)
290 ])
291
292 result = []
293 for title, param_dict in links:
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 })
301 return result
302
303
304 class SortHeaders:
305 def __init__(self, request, headers, order_field_type, order_field,
306 default_order_type="asc", not_sortable=[]):
307 self.request = request
308 self.order_field_type = order_field_type
309 self.order_field = order_field
310 self.header_defs = headers
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
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
320 self.not_sortable = not_sortable
321
322 def headers(self):
323 for h in self.header_defs:
324 params = self.params
325 if h[0] == self.current_order_field:
326 order_type = {
327 'asc': 'desc', 'desc': 'asc'
328 }[self.current_order_field_type]
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]]
335 url = "?%s" % "&".join([
336 '%s=%s' % (param, value[0]) for param, value in params.items()
337 ])
338 yield {
339 "class_attr": (
340 "sorted %s" % class_order
341 if self.field_sorted(h[0]) else ""
342 ),
343 "sortable": self.field_sorted(h[0]),
344 "url": url,
345 "text": h[1],
346 "style_attr": h[2] if len(h) > 2 else "",
347 }
348
349 def field_sorted(self, field):
350 return True if field not in self.not_sortable else False
351
352
353 @register.filter
354 def split(str, splitter):
355 return str.split(splitter)
356
357
358 @register.filter
359 def hash(h, key):
360 if key in h:
361 return h[key]
362 else:
363 raise Exception("%s does not exist" % key)
364
365
366 @register.filter
367 def is_float(v):
368 if type(v) == type(float()):
369 return True
370
371
372 @register.filter()
373 def contains(value, arg):
374 return arg in value