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