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