bgneal@621: """donations_report.py bgneal@621: bgneal@621: A management command to display donation statistics for a given year. bgneal@621: bgneal@621: """ bgneal@621: import datetime bgneal@621: import decimal bgneal@621: bgneal@621: from django.core.management.base import LabelCommand, CommandError bgneal@621: from django.db.models import Sum bgneal@621: bgneal@621: from donations.models import Donation bgneal@621: bgneal@621: ROW_FMT = '%10s %7s %7s' bgneal@621: bgneal@621: bgneal@621: class Command(LabelCommand): bgneal@621: help = "Display donation statistics for a given year" bgneal@621: args = "" bgneal@621: bgneal@621: def handle_label(self, year, **kwargs): bgneal@621: """Display donation statistics for a given year""" bgneal@621: bgneal@621: try: bgneal@621: year = int(year) bgneal@621: except ValueError: bgneal@621: raise CommandError("invalid year") bgneal@621: bgneal@621: today = datetime.date.today() bgneal@621: if year < 2011 or year > today.year: bgneal@621: raise CommandError("invalid year") bgneal@621: bgneal@621: max_month = 12 if year != today.year else today.month bgneal@621: bgneal@621: print ROW_FMT % ('Month', 'Gross', 'Net') bgneal@621: sep = ROW_FMT % ('-' * 10, '-' * 7, '-' * 7) bgneal@621: print sep bgneal@621: bgneal@621: total_gross = decimal.Decimal() bgneal@621: total_net = decimal.Decimal() bgneal@621: bgneal@621: for month in range(1, max_month + 1): bgneal@621: r = Donation.objects.filter( bgneal@621: payment_date__year=year, bgneal@621: payment_date__month=month).aggregate( bgneal@621: Sum('mc_gross'), Sum('mc_fee')) bgneal@621: bgneal@621: gross, fee = r['mc_gross__sum'], r['mc_fee__sum'] bgneal@621: bgneal@621: gross = gross if gross else decimal.Decimal() bgneal@621: fee = fee if fee else decimal.Decimal() bgneal@621: bgneal@621: net = gross - fee bgneal@621: bgneal@621: d = datetime.date(year=year, month=month, day=1) bgneal@621: bgneal@621: print ROW_FMT % (d.strftime('%b %Y'), gross, net) bgneal@621: bgneal@621: total_gross += gross bgneal@621: total_net += net bgneal@621: bgneal@621: print sep bgneal@621: print ROW_FMT % ('Total:', total_gross, total_net)