Fundraising in PDF.
[wolnelektury.git] / src / reporting / templatetags / reporting_stats.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from functools import wraps
5 from django import template
6 from catalogue.models import Book
7
8
9 register = template.Library()
10
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 str(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
48 @register_counter
49 def count_books():
50     return Book.objects.filter(children=None).count()
51
52
53 @register_counter
54 def count_books_parent():
55     return Book.objects.exclude(children=None).count()
56
57
58 @register_counter
59 def count_books_root():
60     return Book.objects.filter(parent=None).count()