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