Merge branch 'reflow'
[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
13 class StatsNode(template.Node):
14     def __init__(self, value, varname=None):
15         self.value = value
16         self.varname = varname
17
18     def render(self, context):
19         if self.varname:
20             context[self.varname] = self.value
21             return ''
22         else:
23             return self.value
24
25
26 def register_counter(f):
27     """Turns a simple counting function into a registered counter tag.
28
29     You can run a counter tag as a simple {% tag_name %} tag, or
30     as {% tag_name var_name %} to store the result in a variable.
31
32     """
33     @wraps(f)
34     def wrapped(parser, token):
35         try:
36             tag_name, args = token.contents.split(None, 1)
37         except ValueError:
38             args = None
39         return StatsNode(f(), args)
40
41     return register.tag(wrapped)
42
43
44 @register_counter
45 def count_books_all():
46     return Book.objects.all().count()
47
48
49 @register_counter
50 def count_books():
51     return Book.objects.filter(children=None).count()
52
53
54 @register_counter
55 def count_books_parent():
56     return Book.objects.exclude(children=None).count()
57
58
59 @register_counter
60 def count_books_root():
61     return Book.objects.filter(parent=None).count()