Instantly share code, notes, and snippets.

Embed
What would you like to do?
from functools import reduce
from django.contrib.postgres.fields.jsonb import KeyTransform
from accounts.models import StripeEvent
def accumulate_tax(start_date, end_date):
"""
Can't aggregate KeyTransformed objects directly, so summing manually
Reference: https://code.djangoproject.com/ticket/29139
"""
events = StripeEvent.objects.filter(
created__range=(start_date, end_date),
type='invoice.payment_succeeded'
).annotate(
tax=KeyTransform('tax', KeyTransform('object', KeyTransform('data', 'data'))),
).values('tax')
if events:
tax_total = reduce(lambda x, y: dict((k, (v or 0) + (y[k] or 0),)
for k, v in x.items()), events)
else:
tax_total = {'tax': 0}
for key, value in tax_total.items():
tax_total[key] = '${:,.2f}'.format(value / 100)
return {'start': start_date, 'end': end_date, 'totals': tax_total}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment