view donations/management/commands/donations_report.py @ 943:cf9918328c64

Haystack tweaks for Django 1.7.7. I had to upgrade to Haystack 2.3.1 to get it to work with Django 1.7.7. I also had to update the Xapian backend. But I ran into problems. On my laptop anyway (Ubuntu 14.0.4), xapian gets mad when search terms are greater than 245 chars (or something) when indexing. So I created a custom field that would simply omit terms greater than 64 chars and used this field everywhere I previously used a CharField. Secondly, the custom search form was broken now. Something changed in the Xapian backend and exact searches stopped working. Fortunately the auto_query (which I was using originally and broke during an upgrade) started working again. So I cut the search form back over to doing an auto_query. I kept the form the same (3 fields) because I didn't want to change the form and I think it's better that way.
author Brian Neal <bgneal@gmail.com>
date Wed, 13 May 2015 20:25:07 -0500
parents 161b56849114
children
line wrap: on
line source
"""donations_report.py

A management command to display donation statistics for a given year.

"""
import datetime
import decimal

from django.core.management.base import LabelCommand, CommandError
from django.db.models import Sum

from donations.models import Donation

ROW_FMT = '%10s %7s %7s'


class Command(LabelCommand):
    help = "Display donation statistics for a given year"
    args = "<year>"

    def handle_label(self, year, **kwargs):
        """Display donation statistics for a given year"""

        try:
            year = int(year)
        except ValueError:
            raise CommandError("invalid year")

        today = datetime.date.today()
        if year < 2011 or year > today.year:
            raise CommandError("invalid year")

        max_month = 12 if year != today.year else today.month

        self.stdout.write(ROW_FMT % ('Month', 'Gross', 'Net'))
        sep = ROW_FMT % ('-' * 10, '-' * 7, '-' * 7)
        self.stdout.write(sep)

        total_gross = decimal.Decimal()
        total_net = decimal.Decimal()

        for month in range(1, max_month + 1):
            r = Donation.objects.filter(
                    payment_date__year=year,
                    payment_date__month=month).aggregate(
                            Sum('mc_gross'), Sum('mc_fee'))

            gross, fee = r['mc_gross__sum'], r['mc_fee__sum']

            gross = gross if gross else decimal.Decimal()
            fee = fee if fee else decimal.Decimal()

            net = gross - fee

            d = datetime.date(year=year, month=month, day=1)

            self.stdout.write(ROW_FMT % (d.strftime('%b %Y'), gross, net))

            total_gross += gross
            total_net += net

        self.stdout.write(sep)
        self.stdout.write(ROW_FMT % ('Total:', total_gross, total_net))