looks like this has been copy/paste/modified from https://github.com/dimagi/commcare-hq/blob/master/corehq/apps/reports/generic.py#L836

could it be refactored so that the two functions were able to share most of the code?