Rapports: trie dans postes et petit helper pour afficher le header du tableau
authorJean-Philippe Caissy <jean-philippe.caissy@auf.org>
Fri, 27 Jan 2012 19:04:52 +0000 (13:04 -0600)
committerJean-Philippe Caissy <jean-philippe.caissy@auf.org>
Fri, 27 Jan 2012 19:04:52 +0000 (13:04 -0600)
project/rh/templates/admin/table_header.html [deleted file]
project/rh/templates/rh/rapports/table_header.html [new file with mode: 0644]
project/rh/templatetags/rapports.py
project/rh/views.py

diff --git a/project/rh/templates/admin/table_header.html b/project/rh/templates/admin/table_header.html
deleted file mode 100644 (file)
index dad0517..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-{% for header in headers %}<th class="{{ header.class_attr }}">
-{% if header.sortable %}<a href="{{ header.url|escape }}">{% endif %}
-{{ header.text }}
-  {% if header.sortable %}</a>{% endif %}
-</th>{% endfor %}
diff --git a/project/rh/templates/rh/rapports/table_header.html b/project/rh/templates/rh/rapports/table_header.html
new file mode 100644 (file)
index 0000000..dad0517
--- /dev/null
@@ -0,0 +1,5 @@
+{% for header in headers %}<th class="{{ header.class_attr }}">
+{% if header.sortable %}<a href="{{ header.url|escape }}">{% endif %}
+{{ header.text }}
+  {% if header.sortable %}</a>{% endif %}
+</th>{% endfor %}
index 016d184..8ea7d48 100644 (file)
@@ -121,7 +121,7 @@ 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('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}
 
@@ -170,126 +170,40 @@ def prepare_choices_date(field_name, context, links, remove=[]):
                        '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]
             }
 
-    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
+
+
index c97e2de..6ac5724 100644 (file)
@@ -143,22 +143,23 @@ def rapports_poste(request):
 
     if 'o' in request.GET:
         try:
-            out = multikeysort(out, [request.GET['o']])
+            out = multikeysort(out, ["%s%s" % ('-' if 'ot' in request.GET and request.GET['ot'] == "desc" else '', request.GET['o'])])
         except KeyError:
             raise Http404
-
+    headers = [
+        ("id", u"# du poste"),
+        ("nom", u"Nom du poste"),
+        ("implantation", u"Implantation"),
+        ("employe_id", u"# de l'employé"),
+        ("employe_nom", u"Nom"),
+        ("employe_prenom", u"Prénom"),
+    ]
+    h = SortHeaders(request, headers, order_field_type="ot", order_field="o")
     c = {
         'title': 'Rapport des postes',
         'postes': out,
         'count': len(out),
-        'headers': list(SortHeaders(request, (
-                (u"# de l'employé", "id"),
-                (u"Nom", "nom"),
-                (u"Implantation", "implantation"),
-                (u"# de l'employé", "employe_id"),
-                (u"Nom", "employe_nom"),
-                (u"Prénom", "employe_prenom"),
-            )).headers())
+        'headers': list(h.headers())
     }
 
     return render_to_response('rh/rapports/postes.html', c, RequestContext(request))