fix import
[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
4c17e518 9from auf.django.references.models import Implantation, Region
75f0e87b 10
82c5e37d 11from project import groups
fd009814 12
82c5e37d 13from project.rh.models import TypeContrat
fd009814
PP
14
15register = Library()
16
17
549830eb 18COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
7821915f
PP
19
20
21@register.inclusion_tag('admin/filter.html', takes_context=True)
22def filter_comble(context):
b31ce2d7
EMS
23 return {
24 'title': 'comblé',
25 'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)
26 }
7821915f
PP
27
28
f0f6b03e 29@register.inclusion_tag('admin/filter.html', takes_context=True)
df37184c 30def filter_region(context, prefix=None):
df37184c 31 label = "".join([prefix or "", "implantation__region"])
b31ce2d7
EMS
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 }
fd009814
PP
39
40
f0f6b03e 41@register.inclusion_tag('admin/filter.html', takes_context=True)
df37184c 42def filter_implantation(context, prefix=None):
df37184c 43 label = "".join([prefix or "", "implantation"])
b31ce2d7
EMS
44 return {
45 'title': u"implantation",
46 'choices': prepare_choices(
47 Implantation.objects.values_list('id', 'nom'), label, context
48 )
49 }
fd009814
PP
50
51
f0f6b03e 52@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 53def filter_region_contrat(context):
f96ec25c 54 request = context['request']
3383b2d1
OL
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)
f96ec25c
OL
60 regions = Region.objects.filter(id=employe.implantation.region.id)
61 else:
62 regions = Region.objects.all()
23e749e1 63 return {'title': u"région",
f96ec25c 64 'choices': prepare_choices(regions.values_list('id', 'nom'), 'dossier__poste__implantation__region', context, remove=['pays', 'nord_sud'])}
23e749e1 65
23e749e1 66
80518280
JPC
67@register.inclusion_tag('admin/filter.html', takes_context=True)
68def filter_region_dossier(context):
b31ce2d7
EMS
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
80518280
JPC
78
79@register.inclusion_tag('admin/filter.html', takes_context=True)
80def filter_implantation_dossier(context):
b31ce2d7
EMS
81 return {
82 'title': u"implantation",
83 'choices': prepare_choices(
84 Implantation.objects.values_list('id', 'nom'),
85 'poste__implantation', context
86 )
87 }
80518280 88
23e749e1 89
f0f6b03e 90@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 91def filter_implantation_contrat(context):
f96ec25c 92 request = context['request']
3383b2d1
OL
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)
f96ec25c
OL
98 implantations = Implantation.objects.filter(region=employe.implantation.region)
99 else:
100 implantations = Implantation.objects.all()
23e749e1 101 return {'title': u"implantation",
f96ec25c 102 'choices': prepare_choices(implantations.values_list('id', 'nom'), 'dossier__poste__implantation', context)}
23e749e1
PP
103
104
f0f6b03e 105@register.inclusion_tag('admin/filter.html', takes_context=True)
23e749e1 106def filter_type_contrat(context):
b31ce2d7
EMS
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
23e749e1 115
72ac5e55
PP
116@register.inclusion_tag('admin/filter_select.html', takes_context=True)
117def filter_echeance_contrat(context):
eb204143 118 today = datetime.date.today()
b31ce2d7
EMS
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)
eb204143
JPC
122
123 field_name = 'date_fin'
72ac5e55 124 return {'title': u"échéance",
eb204143
JPC
125 'choices': prepare_choices_date(field_name, context, links=(
126 ('Tous', {}),
b31ce2d7
EMS
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 }),
eb204143
JPC
139 )
140 )}
141
b31ce2d7 142
eb204143
JPC
143@register.inclusion_tag('admin/filter_select.html', takes_context=True)
144def 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)
b31ce2d7 148 last_year = datetime.date(year - 1, 12, 31)
eb204143
JPC
149
150 field_name = 'date_debut'
151 return {'title': u"date début",
152 'choices': prepare_choices_date(field_name, context, links=(
153 ('Tous', {}),
b31ce2d7
EMS
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 }),
eb204143
JPC
164 )
165 )}
166
b31ce2d7 167
35beb92c
JPC
168@register.inclusion_tag('admin/filter_select.html', takes_context=True)
169def filter_a_venir(context):
170 today = datetime.date.today()
171 year, month, day = datetime.date.today().timetuple()[:3]
b31ce2d7
EMS
172 mois_prochain = datetime.date(
173 year + (month + 1) / 13, (month + 1) % 12, 1
174 )
175 this_month = datetime.date(year, month, 1)
35beb92c
JPC
176
177 field_name = 'date_debut'
178 return {'title': u"à venir",
179 'choices': prepare_choices_date(field_name, context, links=(
180 ('Tous', {}),
b31ce2d7
EMS
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 }),
35beb92c
JPC
191 )
192 )}
193
194
af5073aa
PP
195@register.inclusion_tag('admin/filter_select.html', takes_context=True)
196def filter_region_remun(context):
b31ce2d7
EMS
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 }
af5073aa
PP
205
206
207@register.inclusion_tag('admin/filter_select.html', takes_context=True)
208def filter_implantation_remun(context):
b31ce2d7
EMS
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
af5073aa 217
4dade240 218@register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
9d53bc73 219def table_header(context, headers):
9fd09bdc 220 return {'headers': headers}
af5073aa 221
b31ce2d7 222
fd009814 223def get_query_string(request, new_params=None, remove=None):
b31ce2d7
EMS
224 if new_params is None:
225 new_params = {}
226 if remove is None:
227 remove = []
fd009814
PP
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
242def prepare_choices(choices, query_param, context, remove=[]):
243 request = context['request']
244 query_val = request.GET.get(query_param)
b31ce2d7
EMS
245 result = [{
246 'selected': query_val is None,
247 'query_string': get_query_string(request, {}, [query_param] + remove),
248 'display': 'Tout'
249 }]
fd009814 250 for k, v in choices:
b31ce2d7
EMS
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 })
fd009814 258 return result
72ac5e55
PP
259
260
eb204143 261def prepare_choices_date(field_name, context, links, remove=[]):
72ac5e55
PP
262 request = context['request']
263 params = request.GET
264 field_generic = '%s__' % field_name
b31ce2d7
EMS
265 date_params = dict([
266 (k, v) for k, v in params.items() if k.startswith(field_generic)
267 ])
72ac5e55 268
72ac5e55
PP
269 result = []
270 for title, param_dict in links:
b31ce2d7
EMS
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 })
72ac5e55 278 return result
9d53bc73 279
b31ce2d7 280
9d53bc73 281class SortHeaders:
b31ce2d7
EMS
282 def __init__(self, request, headers, order_field_type, order_field,
283 default_order_type="asc", not_sortable=[]):
4dade240
JPC
284 self.request = request
285 self.order_field_type = order_field_type
286 self.order_field = order_field
9d53bc73 287 self.header_defs = headers
4dade240
JPC
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
b31ce2d7
EMS
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
4dade240 297 self.not_sortable = not_sortable
9d53bc73
JPC
298
299 def headers(self):
4dade240
JPC
300 for h in self.header_defs:
301 params = self.params
302 if h[0] == self.current_order_field:
b31ce2d7
EMS
303 order_type = {
304 'asc': 'desc', 'desc': 'asc'
305 }[self.current_order_field_type]
4dade240
JPC
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]]
b31ce2d7
EMS
312 url = "?%s" % "&".join([
313 '%s=%s' % (param, value[0]) for param, value in params.items()
314 ])
9d53bc73 315 yield {
b31ce2d7
EMS
316 "class_attr": (
317 "sorted %s" % class_order
318 if self.field_sorted(h[0]) else ""
319 ),
4dade240
JPC
320 "sortable": self.field_sorted(h[0]),
321 "url": url,
9fd09bdc
JPC
322 "text": h[1],
323 "style_attr": h[2] if len(h) > 2 else "",
9d53bc73
JPC
324 }
325
4dade240
JPC
326 def field_sorted(self, field):
327 return True if field not in self.not_sortable else False
328
b31ce2d7 329
9202c5db
JPC
330@register.filter
331def split(str, splitter):
332 return str.split(splitter)
57e2b793 333
b31ce2d7 334
57e2b793 335@register.filter
3244a3c2 336def hash(h, key):
57e2b793
JPC
337 if key in h:
338 return h[key]
339 else:
340 raise Exception("%s does not exist" % key)
3244a3c2 341
b31ce2d7 342
3244a3c2
JPC
343@register.filter
344def is_float(v):
345 if type(v) == type(float()):
346 return True
a6927189 347
b31ce2d7 348
a6927189
JPC
349@register.filter()
350def contains(value, arg):
b31ce2d7 351 return arg in value