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