comparison donations/management/commands/donations_report.py @ 621:08d83015e15d

For issue #21, add a management command to display donation stats.
author Brian Neal <bgneal@gmail.com>
date Tue, 30 Oct 2012 18:55:16 -0500
parents
children 161b56849114
comparison
equal deleted inserted replaced
620:40ae28f33b3d 621:08d83015e15d
1 """donations_report.py
2
3 A management command to display donation statistics for a given year.
4
5 """
6 import datetime
7 import decimal
8
9 from django.core.management.base import LabelCommand, CommandError
10 from django.db.models import Sum
11
12 from donations.models import Donation
13
14 ROW_FMT = '%10s %7s %7s'
15
16
17 class Command(LabelCommand):
18 help = "Display donation statistics for a given year"
19 args = "<year>"
20
21 def handle_label(self, year, **kwargs):
22 """Display donation statistics for a given year"""
23
24 try:
25 year = int(year)
26 except ValueError:
27 raise CommandError("invalid year")
28
29 today = datetime.date.today()
30 if year < 2011 or year > today.year:
31 raise CommandError("invalid year")
32
33 max_month = 12 if year != today.year else today.month
34
35 print ROW_FMT % ('Month', 'Gross', 'Net')
36 sep = ROW_FMT % ('-' * 10, '-' * 7, '-' * 7)
37 print sep
38
39 total_gross = decimal.Decimal()
40 total_net = decimal.Decimal()
41
42 for month in range(1, max_month + 1):
43 r = Donation.objects.filter(
44 payment_date__year=year,
45 payment_date__month=month).aggregate(
46 Sum('mc_gross'), Sum('mc_fee'))
47
48 gross, fee = r['mc_gross__sum'], r['mc_fee__sum']
49
50 gross = gross if gross else decimal.Decimal()
51 fee = fee if fee else decimal.Decimal()
52
53 net = gross - fee
54
55 d = datetime.date(year=year, month=month, day=1)
56
57 print ROW_FMT % (d.strftime('%b %Y'), gross, net)
58
59 total_gross += gross
60 total_net += net
61
62 print sep
63 print ROW_FMT % ('Total:', total_gross, total_net)