PEP8
[auf_rh_dae.git] / project / rh / templatetags / rapports.py
index fd6f936..08045fa 100644 (file)
 # -*- coding: utf-8 -*-
 
 # -*- coding: utf-8 -*-
 
+import datetime
+
 from django.utils.encoding import smart_unicode
 from django.template import Library
 from django.utils.http import urlencode
 
 from django.utils.encoding import smart_unicode
 from django.template import Library
 from django.utils.http import urlencode
 
-from datamaster_modeles.models import Implantation, Region
+from auf.django.references.models import \
+        Implantation, Region, ZoneAdministrative
+
+from project import groups
 
 
+from project.rh.models import TypeContrat
 
 register = Library()
 
 
 
 register = Library()
 
 
+COMBLE_CHOICES = (('c', 'Comblé'), ('n', 'Vacant'))
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_comble(context):
+    return {
+        'title': 'comblé',
+        'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_region(context, prefix=None):
+    label = "".join([prefix or "", "implantation__region"])
+    return {
+        'title': u"région",
+        'choices': prepare_choices(
+            Region.objects.values_list('id', 'nom'), label, context,
+            remove=['pays', 'nord_sud']
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_zone_administrative(context, prefix=None):
+    label = "".join([prefix or "", "implantation__zone_administrative"])
+    return {
+        'title': u"zone administrative",
+        'choices': prepare_choices(
+            ZoneAdministrative.objects.values_list('code', 'nom'), label,
+            context, remove=['pays', 'nord_sud']
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_implantation(context, prefix=None):
+    label = "".join([prefix or "", "implantation"])
+    return {
+        'title': u"implantation",
+        'choices': prepare_choices(
+            Implantation.objects.values_list('id', 'nom'), label, context
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_zone_administrative_contrat(context):
+    request = context['request']
+    user_groups = [g.name for g in request.user.groups.all()]
+    if groups.CORRESPONDANT_RH in user_groups or\
+         groups.ADMINISTRATEURS in user_groups or\
+         groups.DIRECTEUR_DE_BUREAU in user_groups:
+        employe = groups.get_employe_from_user(request.user)
+        zones = ZoneAdministrative.objects.filter(
+            code=employe.implantation.zone_administrative.code
+        )
+    else:
+        zones = ZoneAdministrative.objects.all()
+    return {
+        'title': u"région",
+        'choices': prepare_choices(
+            zones.values_list('code', 'nom'),
+            'dossier__poste__implantation__zone_administrative',
+            context, remove=['pays', 'nord_sud']
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_zone_administrative_dossier(context):
+    return {
+        'title': u"région",
+        'choices': prepare_choices(
+            ZoneAdministrative.objects.values_list('code', 'nom'),
+            'poste__implantation__zone_administrative', context,
+            remove=['pays', 'nord_sud']
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_implantation_dossier(context):
+    return {
+        'title': u"implantation",
+        'choices': prepare_choices(
+            Implantation.objects.values_list('id', 'nom'),
+            'poste__implantation', context
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_implantation_contrat(context):
+    request = context['request']
+    user_groups = [g.name for g in request.user.groups.all()]
+    if groups.CORRESPONDANT_RH in user_groups or\
+         groups.ADMINISTRATEURS in user_groups or\
+         groups.DIRECTEUR_DE_BUREAU in user_groups:
+        employe = groups.get_employe_from_user(request.user)
+        implantations = Implantation.objects.filter(
+            zone_administrative=employe.implantation.zone_administrative
+        )
+    else:
+        implantations = Implantation.objects.all()
+    return {
+        'title': u"implantation",
+        'choices': prepare_choices(
+            implantations.values_list('id', 'nom'),
+            'dossier__poste__implantation', context
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter.html', takes_context=True)
+def filter_type_contrat(context):
+    return {
+        'title': u"type de contrat",
+        'choices': prepare_choices(
+            TypeContrat.objects.values_list('id', 'nom'), 'type_contrat',
+            context
+        )
+    }
+
+
 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
-def filter_region(context):
-    return {'title': u"région",
-            'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'implantation__region', context, remove=['pays', 'nord_sud'])}
+def filter_echeance_contrat(context):
+    today = datetime.date.today()
+    three_months = today + datetime.timedelta(days=3 * 30)
+    six_months = today + datetime.timedelta(days=6 * 30)
+    twelve_months = today + datetime.timedelta(days=12 * 30)
+
+    field_name = 'date_fin'
+    return {'title': u"échéance",
+            'choices': prepare_choices_date(field_name, context, links=(
+                ('Tous', {}),
+                ('moins de 3 mois', {
+                    '%s__gte' % field_name: today.strftime('%Y-%m-%d'),
+                    '%s__lte' % field_name: three_months.strftime('%Y-%m-%d')
+                }),
+                ('3 à 6 mois', {
+                    '%s__gte' % field_name: three_months.strftime('%Y-%m-%d'),
+                    '%s__lte' % field_name: six_months.strftime('%Y-%m-%d')
+                }),
+                ('6 à 12 mois', {
+                    '%s__gte' % field_name: six_months.strftime('%Y-%m-%d'),
+                    '%s__lte' % field_name: twelve_months.strftime('%Y-%m-%d')
+                }),
+            )
+    )}
 
 
 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
 
 
 @register.inclusion_tag('admin/filter_select.html', takes_context=True)
-def filter_implantation(context):
-    return {'title': u"implantation",
-            'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'implantation', context)}
+def filter_debut_contrat(context):
+    year = datetime.date.today().timetuple()[0]
+    this_year = datetime.date(year, 1, 1)
+    next_year = datetime.date(year + 1, 1, 1)
+    last_year = datetime.date(year - 1, 12, 31)
+
+    field_name = 'date_debut'
+    return {'title': u"date début",
+            'choices': prepare_choices_date(field_name, context, links=(
+                ('Tous', {}),
+                ('années à venir', {
+                    '%s__gte' % field_name: next_year.strftime('%Y-%m-%d')
+                }),
+                ('cette anneée', {
+                    '%s__gte' % field_name: this_year.strftime('%Y-%m-%d'),
+                    '%s__lt' % field_name: next_year.strftime('%Y-%m-%d')
+                }),
+                ('années passées', {
+                    '%s__lte' % field_name: last_year.strftime('%Y-%m-%d')
+                }),
+            )
+    )}
+
+
+@register.inclusion_tag('admin/filter_select.html', takes_context=True)
+def filter_a_venir(context):
+    today = datetime.date.today()
+    year, month, day = datetime.date.today().timetuple()[:3]
+    mois_prochain = datetime.date(
+        year + (month + 1) / 13, (month + 1) % 12, 1
+    )
+    this_month = datetime.date(year, month, 1)
+
+    field_name = 'date_debut'
+    return {'title': u"à venir",
+            'choices': prepare_choices_date(field_name, context, links=(
+                ('Tous', {}),
+                ('à venir', {
+                    '%s__gt' % field_name: today.strftime('%Y-%m-%d')
+                }),
+                ('à venir mois prochain', {
+                    '%s__gte' % field_name: mois_prochain.strftime('%Y-%m-%d')
+                }),
+                ('à venir ce mois', {
+                    '%s__gte' % field_name: this_month.strftime('%Y-%m-%d'),
+                    '%s__lt' % field_name: mois_prochain.strftime('%Y-%m-%d')
+                }),
+            )
+    )}
+
+
+@register.inclusion_tag('admin/filter_select.html', takes_context=True)
+def filter_zone_administrative_remun(context):
+    return {
+        'title': u"région",
+        'choices': prepare_choices(
+            ZoneAdministrative.objects.values_list('code', 'nom'),
+            'dossiers__poste__implantation__zone_administrative', context,
+            remove=['pays', 'nord_sud']
+        )
+    }
+
+
+@register.inclusion_tag('admin/filter_select.html', takes_context=True)
+def filter_implantation_remun(context):
+    return {
+        'title': u"implantation",
+        'choices': prepare_choices(
+            Implantation.objects.values_list('id', 'nom'),
+            'dossiers__poste__implantation', context
+        )
+    }
+
+
+@register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
+def table_header(context, headers):
+    return {'headers': headers}
 
 
 def get_query_string(request, new_params=None, remove=None):
 
 
 def get_query_string(request, new_params=None, remove=None):
-    if new_params is None: new_params = {}
-    if remove is None: remove = []
+    if new_params is None:
+        new_params = {}
+    if remove is None:
+        remove = []
     p = dict(request.GET.items())
     for r in remove:
         for k in p.keys():
     p = dict(request.GET.items())
     for r in remove:
         for k in p.keys():
@@ -42,11 +270,110 @@ def get_query_string(request, new_params=None, remove=None):
 def prepare_choices(choices, query_param, context, remove=[]):
     request = context['request']
     query_val = request.GET.get(query_param)
 def prepare_choices(choices, query_param, context, remove=[]):
     request = context['request']
     query_val = request.GET.get(query_param)
-    result = [{'selected': query_val is None,
-               'query_string': get_query_string(request, {}, [query_param] + remove),
-               'display': 'Tout'}]
+    result = [{
+        'selected': query_val is None,
+        'query_string': get_query_string(request, {}, [query_param] + remove),
+        'display': 'Tout'
+    }]
     for k, v in choices:
     for k, v in choices:
-        result.append({'selected': smart_unicode(k) == query_val,
-                       'query_string': get_query_string(request, {query_param: k}, remove),
-                       'display': v})
+        result.append({
+            'selected': smart_unicode(k) == query_val,
+            'query_string': get_query_string(
+                request, {query_param: k}, remove
+            ),
+            'display': v
+        })
     return result
     return result
+
+
+def prepare_choices_date(field_name, context, links, remove=[]):
+    request = context['request']
+    params = request.GET
+    field_generic = '%s__' % field_name
+    date_params = dict([
+        (k, v) for k, v in params.items() if k.startswith(field_generic)
+    ])
+
+    result = []
+    for title, param_dict in links:
+        result.append({
+            'selected': date_params == param_dict,
+            'query_string': get_query_string(
+                request, param_dict, [field_generic]
+            ),
+            'display': title
+        })
+    return result
+
+
+class SortHeaders:
+    def __init__(self, request, headers, order_field_type, order_field,
+                 default_order_type="asc", not_sortable=[]):
+        self.request = request
+        self.order_field_type = order_field_type
+        self.order_field = order_field
+        self.header_defs = headers
+        self.params = dict(request.GET)
+        if default_order_type not in ('asc', 'desc'):
+            raise AttributeError(u"L'ordre par défaut n'est pas valide")
+        self.default_order_type = default_order_type
+        self.current_order_field = \
+                self.params[self.order_field][0] \
+                if self.order_field in self.params else None
+        self.current_order_field_type = self.params[self.order_field_type][0] \
+                if self.order_field_type in self.params else None
+        self.not_sortable = not_sortable
+
+    def headers(self):
+        for h in self.header_defs:
+            params = self.params
+            if h[0] == self.current_order_field:
+                order_type = {
+                    'asc': 'desc', 'desc': 'asc'
+                }[self.current_order_field_type]
+                class_order = "%sending" % self.current_order_field_type
+            else:
+                order_type = self.default_order_type
+                class_order = ""
+            params[self.order_field_type] = [order_type]
+            params[self.order_field] = [h[0]]
+            url = "?%s" % "&".join([
+                '%s=%s' % (param, value[0]) for param, value in params.items()
+            ])
+            yield {
+                    "class_attr": (
+                        "sorted %s" % class_order
+                        if self.field_sorted(h[0]) else ""
+                    ),
+                    "sortable": self.field_sorted(h[0]),
+                    "url": url,
+                    "text": h[1],
+                    "style_attr": h[2] if len(h) > 2 else "",
+            }
+
+    def field_sorted(self, field):
+        return True if field not in self.not_sortable else False
+
+
+@register.filter
+def split(str, splitter):
+    return str.split(splitter)
+
+
+@register.filter
+def hash(h, key):
+    if key in h:
+        return h[key]
+    else:
+        raise Exception("%s does not exist" % key)
+
+
+@register.filter
+def is_float(v):
+    if type(v) == type(float()):
+        return True
+
+
+@register.filter()
+def contains(value, arg):
+    return arg in value