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