PEP8
[auf_rh_dae.git] / project / rh / templatetags / rapports.py
index 016d184..08045fa 100644 (file)
@@ -6,9 +6,12 @@ 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 rh.models import TypeContrat
+from auf.django.references.models import \
+        Implantation, Region, ZoneAdministrative
 
+from project import groups
+
+from project.rh.models import TypeContrat
 
 register = Library()
 
@@ -18,116 +21,238 @@ 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)}
+    return {
+        'title': 'comblé',
+        'choices': prepare_choices(COMBLE_CHOICES, 'comble', context)
+    }
 
 
-@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'])}
+@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_select.html', takes_context=True)
-def filter_implantation(context):
-    return {'title': u"implantation",
-            'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'implantation', context)}
+@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_select.html', takes_context=True)
-def filter_region_contrat(context):
-    return {'title': u"région",
-            'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'dossier__poste__implantation__region', 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_select.html', takes_context=True)
+@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):
-    return {'title': u"implantation",
-            'choices': prepare_choices(Implantation.objects.values_list('id', 'nom'), 'dossier__poste__implantation', 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_select.html', takes_context=True)
+@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)}
+    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)
 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)
+    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')}),
+                ('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)
 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)
+    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', {}),
-                ('anées à venirs', {'%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')}),
-                ('ans passés', {'%s__lte' % field_name: last_year.strftime('%Y-%m-%d')}),
+                ('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)
+    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')}),
+                ('à 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_region_remun(context):
-    return {'title': u"région",
-            'choices': prepare_choices(Region.objects.values_list('id', 'nom'), 'dossiers__poste__implantation__region', context, remove=['pays', 'nord_sud'])}
+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)}
+    return {
+        'title': u"implantation",
+        'choices': prepare_choices(
+            Implantation.objects.values_list('id', 'nom'),
+            'dossiers__poste__implantation', context
+        )
+    }
+
 
-@register.inclusion_tag('admin/table_header.html', takes_context=True)
+@register.inclusion_tag('rh/rapports/table_header.html', takes_context=True)
 def table_header(context, headers):
-        return {'headers': headers}
+    return {'headers': headers}
+
 
 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():
@@ -145,13 +270,19 @@ 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)
-    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:
-        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
 
 
@@ -159,137 +290,90 @@ 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)])
+    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})
+        result.append({
+            'selected': date_params == param_dict,
+            'query_string': get_query_string(
+                request, param_dict, [field_generic]
+            ),
+            'display': title
+        })
     return result
 
-ORDER_VAR = 'o'
-ORDER_TYPE_VAR = 'ot'
 
 class SortHeaders:
-    """
-    Handles generation of an argument for the Django ORM's
-    ``order_by`` method and generation of table headers which reflect
-    the currently selected sort, based on defined table headers with
-    matching sort criteria.
-
-    Based in part on the Django Admin application's ``ChangeList``
-    functionality.
-
-    http://djangosnippets.org/snippets/308/
-    """
-    def __init__(self, request, headers, default_order_field=None,
-            default_order_type='asc', additional_params=None):
-        """
-        request
-            The request currently being processed - the current sort
-            order field and type are determined based on GET
-            parameters.
-
-        headers
-            A list of two-tuples of header text and matching ordering
-            criteria for use with the Django ORM's ``order_by``
-            method. A criterion of ``None`` indicates that a header
-            is not sortable.
-
-        default_order_field
-            The index of the header definition to be used for default
-            ordering and when an invalid or non-sortable header is
-            specified in GET parameters. If not specified, the index
-            of the first sortable header will be used.
-
-        default_order_type
-            The default type of ordering used - must be one of
-            ``'asc`` or ``'desc'``.
-
-        additional_params:
-            Query parameters which should always appear in sort links,
-            specified as a dictionary mapping parameter names to
-            values. For example, this might contain the current page
-            number if you're sorting a paginated list of items.
-        """
-        if default_order_field is None:
-            for i, (header, query_lookup) in enumerate(headers):
-                if query_lookup is not None:
-                    default_order_field = i
-                    break
-        if default_order_field is None:
-            raise AttributeError('No default_order_field was specified and none of the header definitions given were sortable.')
-        if default_order_type not in ('asc', 'desc'):
-            raise AttributeError('If given, default_order_type must be one of \'asc\' or \'desc\'.')
-        if additional_params is None: additional_params = {}
-
+    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.additional_params = additional_params
-        self.order_field, self.order_type = default_order_field, default_order_type
-
-        # Determine order field and order type for the current request
-        params = dict(request.GET.items())
-        if ORDER_VAR in params:
-            try:
-                new_order_field = int(params[ORDER_VAR])
-                if headers[new_order_field][1] is not None:
-                    import pdb
-                    pdb.set_trace()
-                    self.order_field = params[ORDER_VAR]
-            except (IndexError, ValueError):
-                pass # Use the default
-        if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
-            self.order_type = params[ORDER_TYPE_VAR]
-        try:
-            del params[ORDER_VAR]
-        except KeyError:
-            pass
-        try:
-            del params[ORDER_TYPE_VAR]
-        except KeyError:
-            pass
-        self.additional_params = params
+        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):
-        """
-        Generates dicts containing header and sort link details for
-        all defined headers.
-        """
-        for i, (header, order_criterion) in enumerate(self.header_defs):
-            th_classes = []
-            new_order_type = 'asc'
-            if i == self.order_field:
-                th_classes.append('sorted %sending' % self.order_type)
-                new_order_type = {'asc': 'desc', 'desc': 'asc'}[self.order_type]
+        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 {
-                'text': header,
-                'sortable': order_criterion is not None,
-                'url': self.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}),
-                'class_attr': (th_classes and ' '.join(th_classes) or ''),
+                    "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 get_query_string(self, params):
-        """
-        Creates a query string from the given dictionary of
-        parameters, including any additonal parameters which should
-        always be present.
-        """
-        params.update(self.additional_params)
-        if self.order_type == params[ORDER_TYPE_VAR] and self.order_field == params[ORDER_VAR]:
-            params[ORDER_TYPE_VAR] = 'asc' if params[ORDER_TYPE_VAR] == "desc" else "desc"
-        return '?%s' % '&'.join(['%s=%s' % (param, value) \
-                                     for param, value in params.items()])
-
-    def get_order_by(self):
-        """
-        Creates an ordering criterion based on the current order
-        field and order type, for use with the Django ORM's
-        ``order_by`` method.
-        """
-        return '%s%s' % (
-            self.order_type == 'desc' and '-' or '',
-            self.header_defs[self.order_field][1],
-        )
+    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