debut affichage masse salariale dans les rapports
[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 from rh.models import TypeContrat
11
12
13 register = Library()
14
15
16 COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
17
18
19 @register.inclusion_tag('admin/filter.html', takes_context=True)
20 def filter_comble(context):
21 return {'title': 'comblé',
22 'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)}
23
24
25 @register.inclusion_tag('admin/filter.html', takes_context=True)
26 def filter_region(context, prefix=None):
27
28 label = "".join([prefix or "", "implantation__region"])
29 return {'title': u"région",
30 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), label, context, remove=['pays', 'nord_sud'])}
31
32
33 @register.inclusion_tag('admin/filter.html', takes_context=True)
34 def filter_implantation(context, prefix=None):
35
36 label = "".join([prefix or "", "implantation"])
37 return {'title': u"implantation",
38 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), label, context)}
39
40
41 @register.inclusion_tag('admin/filter.html', takes_context=True)
42 def filter_region_contrat(context):
43 return {'title': u"région",
44 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'dossier__poste__implantation__region', context, remove=['pays', 'nord_sud'])}
45
46 @register.inclusion_tag('admin/filter.html', takes_context=True)
47 def filter_region_dossier(context):
48 return {'title': u"région",
49 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'poste__implantation__region', context, remove=['pays', 'nord_sud'])}
50
51 @register.inclusion_tag('admin/filter.html', takes_context=True)
52 def filter_implantation_dossier(context):
53 return {'title': u"implantation",
54 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'poste__implantation', context)}
55
56
57 @register.inclusion_tag('admin/filter.html', takes_context=True)
58 def filter_implantation_contrat(context):
59 return {'title': u"implantation",
60 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'dossier__poste__implantation', context)}
61
62
63 @register.inclusion_tag('admin/filter.html', takes_context=True)
64 def filter_type_contrat(context):
65 return {'title': u"type de contrat",
66 'choices': prepare_choices(TypeContrat.objects.values_list('id', 'nom'), 'type_contrat', context)}
67
68 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
69 def filter_echeance_contrat(context):
70 today = datetime.date.today()
71 three_months = today + datetime.timedelta(days=3*30)
72 six_months = today + datetime.timedelta(days=6*30)
73 twelve_months = today + datetime.timedelta(days=12*30)
74
75 field_name = 'date_fin'
76 return {'title': u"échéance",
77 'choices': prepare_choices_date(field_name, context, links=(
78 ('Tous', {}),
79 ('échus', {'%s__lt' % field_name: today.strftime('%Y-%m-%d'),}),
80 ('moins de 3 mois', {'%s__gte' % field_name: today.strftime('%Y-%m-%d'),
81 '%s__lte' % field_name: three_months.strftime('%Y-%m-%d')}),
82 ('3 à 6 mois', {'%s__gte' % field_name: three_months.strftime('%Y-%m-%d'),
83 '%s__lte' % field_name: six_months.strftime('%Y-%m-%d')}),
84 ('6 à 12 mois', {'%s__gte' % field_name: six_months.strftime('%Y-%m-%d'),
85 '%s__lte' % field_name: twelve_months.strftime('%Y-%m-%d')}),
86 )
87 )}
88
89 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
90 def filter_debut_contrat(context):
91 year = datetime.date.today().timetuple()[0]
92 this_year = datetime.date(year, 1, 1)
93 next_year = datetime.date(year + 1, 1, 1)
94 last_year = datetime.date(year - 1, 12,31)
95
96 field_name = 'date_debut'
97 return {'title': u"date début",
98 'choices': prepare_choices_date(field_name, context, links=(
99 ('Tous', {}),
100 ('années à venir', {'%s__gte' % field_name: next_year.strftime('%Y-%m-%d')}),
101 ('cette anneée', {'%s__gte' % field_name: this_year.strftime('%Y-%m-%d'),
102 '%s__lt' % field_name: next_year.strftime('%Y-%m-%d')}),
103 ('années passées', {'%s__lte' % field_name: last_year.strftime('%Y-%m-%d')}),
104 )
105 )}
106
107 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
108 def filter_a_venir(context):
109 today = datetime.date.today()
110 year, month, day = datetime.date.today().timetuple()[:3]
111 mois_prochain = datetime.date(year+((month+1)/13), (month+1)%12, 1)
112 this_month = datetime.date(year, month, 1)
113
114 field_name = 'date_debut'
115 return {'title': u"à venir",
116 'choices': prepare_choices_date(field_name, context, links=(
117 ('Tous', {}),
118 ('à venir', {'%s__gt' % field_name: today.strftime('%Y-%m-%d')}),
119 ('à venir mois prochain', {'%s__gte' % field_name: mois_prochain.strftime('%Y-%m-%d')}),
120 ('à venir ce mois', {'%s__gte' % field_name: this_month.strftime('%Y-%m-%d'),
121 '%s__lt' % field_name: mois_prochain.strftime('%Y-%m-%d')}),
122 )
123 )}
124
125
126
127
128 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
129 def filter_region_remun(context):
130 return {'title': u"région",
131 'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'dossiers__poste__implantation__region', context, remove=['pays', 'nord_sud'])}
132
133
134 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
135 def filter_implantation_remun(context):
136 return {'title': u"implantation",
137 'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'dossiers__poste__implantation', context)}
138
139 @register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
140 def table_header(context, headers):
141 return {'headers': headers}
142
143 def get_query_string(request, new_params=None, remove=None):
144 if new_params is None: new_params = {}
145 if remove is None: remove = []
146 p = dict(request.GET.items())
147 for r in remove:
148 for k in p.keys():
149 if k.startswith(r):
150 del p[k]
151 for k, v in new_params.items():
152 if v is None:
153 if k in p:
154 del p[k]
155 else:
156 p[k] = v
157 return '?%s' % urlencode(p)
158
159
160 def prepare_choices(choices, query_param, context, remove=[]):
161 request = context['request']
162 query_val = request.GET.get(query_param)
163 result = [{'selected': query_val is None,
164 'query_string': get_query_string(request, {}, [query_param] + remove),
165 'display': 'Tout'}]
166 for k, v in choices:
167 result.append({'selected': smart_unicode(k) == query_val,
168 'query_string': get_query_string(request, {query_param: k}, remove),
169 'display': v})
170 return result
171
172
173 def prepare_choices_date(field_name, context, links, remove=[]):
174 request = context['request']
175 params = request.GET
176 field_generic = '%s__' % field_name
177 date_params = dict([(k, v) for k, v in params.items() if k.startswith(field_generic)])
178
179
180
181 result = []
182 for title, param_dict in links:
183 result.append({'selected': date_params == param_dict,
184 'query_string': get_query_string(request, param_dict, [field_generic]),
185 'display': title})
186 return result
187
188 class SortHeaders:
189 def __init__(self, request, headers, order_field_type, order_field, default_order_type="asc", not_sortable=[]):
190 self.request = request
191 self.order_field_type = order_field_type
192 self.order_field = order_field
193 self.header_defs = headers
194 self.params = dict(request.GET)
195 if default_order_type not in ('asc', 'desc'):
196 raise AttributeError(u"L'ordre par défaut n'est pas valide")
197 self.default_order_type = default_order_type
198 self.current_order_field = self.params[self.order_field][0] if self.order_field in self.params else None
199 self.current_order_field_type = self.params[self.order_field_type][0] if self.order_field_type in self.params else None
200 self.not_sortable = not_sortable
201
202 def headers(self):
203 for h in self.header_defs:
204 params = self.params
205 if h[0] == self.current_order_field:
206 order_type = {'asc': 'desc', 'desc': 'asc'}[self.current_order_field_type]
207 class_order = "%sending" % self.current_order_field_type
208 else:
209 order_type = self.default_order_type
210 class_order = ""
211 params[self.order_field_type] = [order_type]
212 params[self.order_field] = [h[0]]
213 url = "?%s" % "&".join(['%s=%s' % (param, value[0]) for param, value in params.items()])
214 yield {
215 "class_attr": "sorted %s" % class_order if self.field_sorted(h[0]) else "",
216 "sortable": self.field_sorted(h[0]),
217 "url": url,
218 "text": h[1]
219 }
220
221 def field_sorted(self, field):
222 return True if field not in self.not_sortable else False
223
224 @register.filter
225 def split(str, splitter):
226 return str.split(splitter)