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