Code layout change.
[wolnelektury.git] / src / reporting / templatetags / reporting_stats.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from functools import wraps
6 from django import template
7 from catalogue.models import Book
8
9
10 register = template.Library()
11
12 class StatsNode(template.Node):
13     def __init__(self, value, varname=None):
14         self.value = value
15         self.varname = varname
16
17     def render(self, context):
18         if self.varname:
19             context[self.varname] = self.value
20             return ''
21         else:
22             return self.value
23
24
25 def register_counter(f):
26     """Turns a simple counting function into a registered counter tag.
27
28     You can run a counter tag as a simple {% tag_name %} tag, or
29     as {% tag_name var_name %} to store the result in a variable.
30
31     """
32     @wraps(f)
33     def wrapped(parser, token):
34         try:
35             tag_name, args = token.contents.split(None, 1)
36         except ValueError:
37             args = None
38         return StatsNode(f(), args)
39
40     return register.tag(wrapped)
41
42
43 @register_counter
44 def count_books_all():
45     return Book.objects.all().count()
46
47 @register_counter
48 def count_books():
49     return Book.objects.filter(children=None).count()
50
51 @register_counter
52 def count_books_parent():
53     return Book.objects.exclude(children=None).count()
54
55 @register_counter
56 def count_books_root():
57     return Book.objects.filter(parent=None).count()