annotate donations/management/commands/donations_report.py @ 1191:cc4683870919

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