Exemple #1
0
    def config_options(self):
        if self.config:
            options = json.loads(self.config)
            output = []
            for opt_key, opt_val in options.items():
                if opt_key in CONFIG_OPTIONS:
                    config_option = CONFIG_OPTIONS[opt_key]
                    config_dict = {
                        'label': config_option['label'],
                        'value': config_option['options'][opt_val]['label']
                    }
                    output.append(config_dict)

                elif opt_key == "invoice_object_type":
                    value = ", ".join(sorted([get_ct_nice_name(i) for i in opt_val]))
                    if sorted(opt_val) == sorted([str(i['object_type']) for i in Invoice.objects.values('object_type').distinct()]):
                        value = "All Apps"
                    config_dict = {
                        'label': "Which Apps",
                        'value': value
                    }
                    output.append(config_dict)

                elif opt_key == "invoice_membership_filter":
                    try:
                        item = MembershipType.objects.get(pk=opt_val)
                        output.append({
                            'label': 'Membership Filter',
                            'value': '%s members only' % item.name
                        })
                    except:
                        pass

            return output
        return u''
Exemple #2
0
    def config_options(self):
        if self.config:
            options = json.loads(self.config)
            output = []
            for opt_key, opt_val in options.items():
                if opt_key in CONFIG_OPTIONS:
                    config_option = CONFIG_OPTIONS[opt_key]
                    config_dict = {
                        'label': config_option['label'],
                        'value': config_option['options'][opt_val]['label']
                    }
                    output.append(config_dict)

                elif opt_key == "invoice_object_type":
                    value = ", ".join(
                        sorted([get_ct_nice_name(i) for i in opt_val]))
                    if sorted(opt_val) == sorted([
                            unicode(i['object_type']) for i in
                            Invoice.objects.values('object_type').distinct()
                    ]):
                        value = "All Apps"
                    config_dict = {'label': "Which Apps", 'value': value}
                    output.append(config_dict)

            return output
        return u''
Exemple #3
0
    def config_options(self):
        if self.config:
            options = json.loads(self.config)
            output = []
            for opt_key, opt_val in options.items():
                if opt_key in CONFIG_OPTIONS:
                    config_option = CONFIG_OPTIONS[opt_key]
                    config_dict = {
                        'label': config_option['label'],
                        'value': config_option['options'][opt_val]['label']
                    }
                    output.append(config_dict)

                elif opt_key == "invoice_object_type":
                    value = ", ".join(sorted([get_ct_nice_name(i) for i in opt_val]))
                    if sorted(opt_val) == sorted([unicode(i['object_type']) for i in Invoice.objects.values('object_type').distinct()]):
                        value = "All Apps"
                    config_dict = {
                        'label': "Which Apps",
                        'value': value
                    }
                    output.append(config_dict)

                elif opt_key == "invoice_membership_filter":
                    try:
                        item = MembershipType.objects.get(pk=opt_val)
                        output.append({
                            'label': 'Membership Filter',
                            'value': '%s members only' % item.name
                        })
                    except:
                        pass

            return output
        return u''
Exemple #4
0
    def report_output_invoices(self, run):
        from tendenci.apps.invoices.models import Invoice
        from tendenci.apps.reports.models import CONFIG_OPTIONS
        results = []
        totals = {'total': 0, 'payments_credits': 0, 'balance': 0, 'count': 0}
        filters = Q()
        filters = (filters & Q(create_dt__gte=run.range_start_dt)
                   & Q(create_dt__lte=run.range_end_dt))

        if run.report.config:
            for k, v in run.report.config_options_dict().items():
                if k in CONFIG_OPTIONS:
                    filter_kwarg = CONFIG_OPTIONS[k]['options'][v]['filter']
                    if filter_kwarg:
                        filters = (filters & Q(**filter_kwarg))
                elif k == "invoice_object_type":
                    if "None" in v:
                        v.pop(v.index("None"))
                        filters = (filters & (Q(object_type__in=v)
                                              | Q(object_type__isnull=True)))
                    else:
                        filters = (filters & Q(object_type__in=v))

        distinct_object_types = Invoice.objects.filter(filters).values(
            'object_type').distinct()

        for ot in distinct_object_types:
            ot_dict = {}
            invoices = Invoice.objects.filter(filters).filter(
                object_type=ot['object_type'])
            ot_dict['invoices'] = invoices.order_by('create_dt')
            ot_dict['object_type'] = get_ct_nice_name(ot['object_type'])
            ot_dict['count'] = invoices.count()
            aggregates = invoices.aggregate(Sum('total'),
                                            Sum('payments_credits'),
                                            Sum('balance'))
            ot_dict.update(aggregates)
            results.append(ot_dict)
            totals['count'] = totals['count'] + ot_dict['count']
            totals['total'] = totals['total'] + aggregates['total__sum']
            totals['payments_credits'] = totals[
                'payments_credits'] + aggregates['payments_credits__sum']
            totals['balance'] = totals['balance'] + aggregates['balance__sum']

        results = sorted(results, key=lambda k: k['object_type'])

        try:
            if run.output_type == 'html-extended':
                t = get_template("reports/invoices/results-extended.html")
            else:
                t = get_template("reports/invoices/results.html")
        except TemplateDoesNotExist:
            self.end_with_error(run)
            raise CommandError('The template for this report is missing.')
        return t.render(
            Context({
                'results': results,
                'totals': totals,
                'run': run
            }))
Exemple #5
0
    def __init__(self, *args, **kwargs):
        super(ReportForm, self).__init__(*args, **kwargs)

        fields_to_append = ['invoice_display', 'invoice_status']

        for item in fields_to_append:
            self.fields[item] = forms.ChoiceField(
                choices=[(k, v['label'])
                         for k, v in CONFIG_OPTIONS[item]['options'].items()],
                label=CONFIG_OPTIONS[item]['label'])

        if 'invoice_status' in self.fields:
            self.fields['invoice_status'].initial = 'has-balance'

        self.fields['invoice_membership_filter'] = forms.ChoiceField(
            label=
            "Filter results based on membership type (if membership is selected)",
            choices=[('', '--- Membership type filter ---')] +
            sorted([(i['pk'], i['name'])
                    for i in MembershipType.objects.values('pk', 'name')],
                   key=lambda t: t[0]),
            required=False)

        self.fields['invoice_object_type'] = forms.MultipleChoiceField(
            label="Which apps to include?",
            choices=sorted(
                [(i['object_type'], get_ct_nice_name(i['object_type']))
                 for i in Invoice.objects.values('object_type').distinct()],
                key=lambda t: t[1]),
            widget=forms.widgets.CheckboxSelectMultiple(),
            initial=[
                i['object_type']
                for i in Invoice.objects.values('object_type').distinct()
            ])
Exemple #6
0
    def config_options(self):
        if self.config:
            options = json.loads(self.config)
            output = []
            for opt_key, opt_val in options.items():
                if opt_key in CONFIG_OPTIONS:
                    config_option = CONFIG_OPTIONS[opt_key]
                    config_dict = {
                        'label': config_option['label'],
                        'value': config_option['options'][opt_val]['label']
                    }
                    output.append(config_dict)

                elif opt_key == "invoice_object_type":
                    value = ", ".join(sorted([get_ct_nice_name(i) for i in opt_val]))
                    if sorted(opt_val) == sorted([unicode(i['object_type']) for i in Invoice.objects.values('object_type').distinct()]):
                        value = "All Apps"
                    config_dict = {
                        'label': "Which Apps",
                        'value': value
                    }
                    output.append(config_dict)

            return output
        return u''
Exemple #7
0
    def __init__(self, *args, **kwargs):
        super(ReportForm, self).__init__(*args, **kwargs)

        fields_to_append = ['invoice_display', 'invoice_status']

        for item in fields_to_append:
            self.fields[item] = forms.ChoiceField(
                choices=[(k, v['label'])
                         for k, v in CONFIG_OPTIONS[item]['options'].items()],
                label=CONFIG_OPTIONS[item]['label'])

        if 'invoice_status' in self.fields:
            self.fields['invoice_status'].initial = 'has-balance'

        self.fields['invoice_object_type'] = forms.MultipleChoiceField(
            label="Which apps to include?",
            choices=sorted(
                [(i['object_type'], get_ct_nice_name(i['object_type']))
                 for i in Invoice.objects.values('object_type').distinct()],
                key=lambda t: t[1]),
            widget=forms.widgets.CheckboxSelectMultiple(),
            initial=[
                i['object_type']
                for i in Invoice.objects.values('object_type').distinct()
            ])
    def report_output_invoices(self, run):
        from tendenci.apps.invoices.models import Invoice
        from tendenci.apps.reports.models import CONFIG_OPTIONS
        results = []
        totals = {'total': 0, 'payments_credits': 0, 'balance': 0, 'count': 0}
        filters = Q()
        filters = (filters & Q(create_dt__gte=run.range_start_dt) & Q(create_dt__lte=run.range_end_dt))

        if run.report.config:
            for k, v in run.report.config_options_dict().items():
                if k in CONFIG_OPTIONS:
                    filter_kwarg = CONFIG_OPTIONS[k]['options'][v]['filter']
                    if filter_kwarg:
                        filters = (filters & Q(**filter_kwarg))
                elif k == "invoice_object_type":
                    if "None" in v:
                        v.pop(v.index("None"))
                        filters = (filters & (Q(object_type__in=v) | Q(object_type__isnull=True)))
                    else:
                        filters = (filters & Q(object_type__in=v))

        distinct_object_types = Invoice.objects.filter(filters).values('object_type').distinct()

        for ot in distinct_object_types:
            ot_dict = {}
            invoices = Invoice.objects.filter(filters).filter(
                object_type=ot['object_type'])
            ot_dict['invoices'] = invoices.order_by('create_dt')
            ot_dict['object_type'] = get_ct_nice_name(ot['object_type'])
            ot_dict['count'] = invoices.count()
            aggregates = invoices.aggregate(Sum('total'), Sum('payments_credits'), Sum('balance'))
            ot_dict.update(aggregates)
            results.append(ot_dict)
            totals['count'] = totals['count'] + ot_dict['count']
            totals['total'] = totals['total'] + aggregates['total__sum']
            totals['payments_credits'] = totals['payments_credits'] + aggregates['payments_credits__sum']
            totals['balance'] = totals['balance'] + aggregates['balance__sum']

        results = sorted(results, key=lambda k: k['object_type'])

        try:
            if run.output_type == 'html-extended':
                t = get_template("reports/invoices/results-extended.html")
            else:
                t = get_template("reports/invoices/results.html")
        except TemplateDoesNotExist:
            self.end_with_error(run)
            raise CommandError('The template for this report is missing.')
        return t.render(Context({
            'results': results,
            'totals': totals,
            'run': run}))
Exemple #9
0
    def __init__(self, *args, **kwargs):
        super(ReportForm, self).__init__(*args, **kwargs)

        fields_to_append = ['invoice_display', 'invoice_status']

        for item in fields_to_append:
            self.fields[item] = forms.ChoiceField(choices=[
                (k, v['label']) for k, v in CONFIG_OPTIONS[item]['options'].items()],
                label=CONFIG_OPTIONS[item]['label'])

        self.fields['invoice_object_type'] = forms.MultipleChoiceField(
            label="Which apps to include?",
            choices=sorted([(i['object_type'], get_ct_nice_name(i['object_type'])) for i in Invoice.objects.values('object_type').distinct()], key=lambda t: t[1]),
            widget=forms.widgets.CheckboxSelectMultiple(),
            initial=[i['object_type'] for i in Invoice.objects.values('object_type').distinct()])
Exemple #10
0
    def __init__(self, *args, **kwargs):
        super(ReportForm, self).__init__(*args, **kwargs)

        fields_to_append = ['invoice_display', 'invoice_status']

        for item in fields_to_append:
            self.fields[item] = forms.ChoiceField(choices=[
                (k, v['label']) for k, v in CONFIG_OPTIONS[item]['options'].items()],
                label=CONFIG_OPTIONS[item]['label'])

        if 'invoice_status' in self.fields:
            self.fields['invoice_status'].initial = 'has-balance'

        self.fields['invoice_membership_filter'] = forms.ChoiceField(
            label="Filter results based on membership type (if membership is selected)",
            choices=[('', '--- Membership type filter ---')] + sorted([(i['pk'], i['name']) for i in MembershipType.objects.values('pk', 'name')], key=lambda t: t[0]),
            required=False)

        self.fields['invoice_object_type'] = forms.MultipleChoiceField(
            label="Which apps to include?",
            choices=sorted([(i['object_type'], get_ct_nice_name(i['object_type'])) for i in Invoice.objects.values('object_type').distinct()], key=lambda t: t[1]),
            widget=forms.widgets.CheckboxSelectMultiple(),
            initial=[i['object_type'] for i in Invoice.objects.values('object_type').distinct()])
Exemple #11
0
    def report_output_invoices(self, run):
        from tendenci.apps.corporate_memberships.models import CorpMembership
        try:
            from tendenci.apps.donations.models import Donation
        except:
            Donation = None
        from tendenci.apps.memberships.models import (MembershipType,
                                                      MembershipSet,
                                                      MembershipDefault)
        from tendenci.apps.invoices.models import Invoice
        from tendenci.apps.reports.models import CONFIG_OPTIONS
        is_summary_mode = (run.output_type == 'html-summary')
        results = []
        totals = {'total': 0, 'payments_credits': 0, 'balance': 0, 'count': 0}
        filters = Q()
        filters = (filters & Q(create_dt__gte=run.range_start_dt)
                   & Q(create_dt__lte=run.range_end_dt))

        membership_filter = None

        if run.report.config:
            for k, v in run.report.config_options_dict().items():
                if k in CONFIG_OPTIONS:
                    filter_kwarg = CONFIG_OPTIONS[k]['options'][v]['filter']
                    if filter_kwarg:
                        filters = (filters & Q(**filter_kwarg))
                elif k == "invoice_object_type":
                    if "None" in v:
                        v.pop(v.index("None"))
                        filters = (filters & (Q(object_type__in=v)
                                              | Q(object_type__isnull=True)))
                    else:
                        filters = (filters & Q(object_type__in=v))
                elif k == "invoice_membership_filter":
                    try:
                        item = MembershipType.objects.get(pk=v)
                        membership_filter = item
                    except:
                        pass

        distinct_object_types = Invoice.objects.filter(filters).values(
            'object_type').distinct()

        for ot in distinct_object_types:
            ot_dict = {}
            invoices = Invoice.objects.filter(filters).filter(
                object_type=ot['object_type'])

            try:
                if membership_filter:
                    invoice_object = invoices[0].get_object()

                    if isinstance(invoice_object, MembershipDefault):
                        members_pk = MembershipDefault.objects.filter(membership_type=membership_filter) \
                            .values_list('pk', flat=True)
                        invoices = invoices.filter(
                            object_id__in=set(members_pk))
                    elif isinstance(invoice_object, MembershipSet):
                        members_pk = MembershipSet.objects.filter(membershipdefault__membership_type=membership_filter) \
                            .values_list('pk', flat=True)
                        invoices = invoices.filter(
                            object_id__in=set(members_pk))
                    elif isinstance(invoice_object, CorpMembership):
                        members_pk = CorpMembership.objects.filter(corporate_membership_type__membership_type=membership_filter) \
                            .values_list('pk', flat=True)
                        invoices = invoices.filter(
                            object_id__in=set(members_pk))
            except:
                pass

            # generate summary mode data
            if is_summary_mode:
                sm_dict = {}
                for invoice in invoices:
                    key = str(invoice.get_object())
                    if key not in sm_dict:
                        sm_dict[key] = {
                            'invoices': [],
                            'count': 0,
                            'total': 0,
                            'payments_credits': 0,
                            'balance': 0,
                        }
                    invoice_dict = sm_dict[key]
                    invoice_dict['count'] += 1
                    invoice_dict['invoices'].append(invoice)
                    invoice_dict['total'] += invoice.total
                    invoice_dict[
                        'payments_credits'] += invoice.payments_credits
                    invoice_dict['balance'] += invoice.balance
                ot_dict['summary'] = [v for k, v in sm_dict.items()]

            ot_dict['invoices'] = invoices.order_by('create_dt')
            ot_dict['object_type'] = get_ct_nice_name(ot['object_type'])
            ot_dict['count'] = invoices.count()
            ot_dict.update({
                'is_membership':
                'membership' in ot_dict['object_type'].lower(),
                'is_donation':
                'donation' in ot_dict['object_type'].lower(),
            })

            aggregates = invoices.aggregate(Sum('total'),
                                            Sum('payments_credits'),
                                            Sum('balance'))
            for k, v in aggregates.items():
                if not v: aggregates[k] = v or 0

            ot_dict.update(aggregates)
            results.append(ot_dict)
            totals['count'] = totals['count'] + ot_dict['count']
            totals['total'] = totals['total'] + aggregates['total__sum']
            totals['payments_credits'] = totals[
                'payments_credits'] + aggregates['payments_credits__sum']
            totals['balance'] = totals['balance'] + aggregates['balance__sum']

        results = sorted(results, key=lambda k: k['object_type'])

        try:
            if run.output_type == 'html-extended':
                t = get_template("reports/invoices/results-extended.html")
            elif is_summary_mode:
                t = get_template("reports/invoices/results-summary.html")
            else:
                t = get_template("reports/invoices/results.html")
        except TemplateDoesNotExist:
            self.end_with_error(run)
            raise CommandError('The template for this report is missing.')
        return t.render(
            Context({
                'results': results,
                'totals': totals,
                'run': run
            }))
Exemple #12
0
    def report_output_invoices(self, run):
        from tendenci.apps.corporate_memberships.models import CorpMembership
        try:
            from tendenci.apps.donations.models import Donation
        except:
            Donation = None
        from tendenci.apps.memberships.models import (MembershipType,
            MembershipSet, MembershipDefault)
        from tendenci.apps.invoices.models import Invoice
        from tendenci.apps.reports.models import CONFIG_OPTIONS
        is_summary_mode = (run.output_type == 'html-summary')
        results = []
        totals = {'total': 0, 'payments_credits': 0, 'balance': 0, 'count': 0}
        filters = Q()
        filters = (filters & Q(create_dt__gte=run.range_start_dt) & Q(create_dt__lte=run.range_end_dt))

        membership_filter = None

        if run.report.config:
            for k, v in run.report.config_options_dict().items():
                if k in CONFIG_OPTIONS:
                    filter_kwarg = CONFIG_OPTIONS[k]['options'][v]['filter']
                    if filter_kwarg:
                        filters = (filters & Q(**filter_kwarg))
                elif k == "invoice_object_type":
                    if "None" in v:
                        v.pop(v.index("None"))
                        filters = (filters & (Q(object_type__in=v) | Q(object_type__isnull=True)))
                    else:
                        filters = (filters & Q(object_type__in=v))
                elif k == "invoice_membership_filter":
                    try:
                        item = MembershipType.objects.get(pk=v)
                        membership_filter = item
                    except:
                        pass

        distinct_object_types = Invoice.objects.filter(filters).values('object_type').distinct()

        for ot in distinct_object_types:
            ot_dict = {}
            invoices = Invoice.objects.filter(filters).filter(
                object_type=ot['object_type'])

            try:
                if membership_filter:
                    invoice_object = invoices[0].get_object()

                    if isinstance(invoice_object, MembershipDefault):
                        members_pk = MembershipDefault.objects.filter(membership_type=membership_filter) \
                            .values_list('pk', flat=True)
                        invoices = invoices.filter(object_id__in=set(members_pk))
                    elif isinstance(invoice_object, MembershipSet):
                        members_pk = MembershipSet.objects.filter(membershipdefault__membership_type=membership_filter) \
                            .values_list('pk', flat=True)
                        invoices = invoices.filter(object_id__in=set(members_pk))
                    elif isinstance(invoice_object, CorpMembership):
                        members_pk = CorpMembership.objects.filter(corporate_membership_type__membership_type=membership_filter) \
                            .values_list('pk', flat=True)
                        invoices = invoices.filter(object_id__in=set(members_pk))
            except:
                pass

            # generate summary mode data
            if is_summary_mode:
                sm_dict = {}
                for invoice in invoices:
                    key = str(invoice.get_object())
                    if key not in sm_dict:
                        sm_dict[key] = {
                            'invoices': [],
                            'count': 0,
                            'total': 0,
                            'payments_credits': 0,
                            'balance': 0,
                        }
                    invoice_dict = sm_dict[key]
                    invoice_dict['count'] += 1
                    invoice_dict['invoices'].append(invoice)
                    invoice_dict['total'] += invoice.total
                    invoice_dict['payments_credits'] += invoice.payments_credits
                    invoice_dict['balance'] += invoice.balance
                ot_dict['summary'] = [v for k,v in sm_dict.items()]

            ot_dict['invoices'] = invoices.order_by('create_dt')
            ot_dict['object_type'] = get_ct_nice_name(ot['object_type'])
            ot_dict['count'] = invoices.count()
            ot_dict.update({
                'is_membership': 'membership' in ot_dict['object_type'].lower(),
                'is_donation': 'donation' in ot_dict['object_type'].lower(),
                })

            aggregates = invoices.aggregate(Sum('total'), Sum('payments_credits'), Sum('balance'))
            for k, v in aggregates.items():
                if not v: aggregates[k] = v or 0

            ot_dict.update(aggregates)
            results.append(ot_dict)
            totals['count'] = totals['count'] + ot_dict['count']
            totals['total'] = totals['total'] + aggregates['total__sum']
            totals['payments_credits'] = totals['payments_credits'] + aggregates['payments_credits__sum']
            totals['balance'] = totals['balance'] + aggregates['balance__sum']

        results = sorted(results, key=lambda k: k['object_type'])

        try:
            if run.output_type == 'html-extended':
                t = get_template("reports/invoices/results-extended.html")
            elif is_summary_mode:
                t = get_template("reports/invoices/results-summary.html")
            else:
                t = get_template("reports/invoices/results.html")
        except TemplateDoesNotExist:
            self.end_with_error(run)
            raise CommandError('The template for this report is missing.')
        return t.render(Context({
            'results': results,
            'totals': totals,
            'run': run}))
Exemple #13
0
    def report_output_invoices(self, run):
        from tendenci.apps.corporate_memberships.models import CorpMembership

        try:
            from donations.models import Donation
        except:
            Donation = None
        from tendenci.apps.memberships.models import MembershipType, MembershipSet, MembershipDefault
        from tendenci.apps.invoices.models import Invoice
        from tendenci.apps.reports.models import CONFIG_OPTIONS

        is_summary_mode = run.output_type == "html-summary"
        results = []
        totals = {"total": 0, "payments_credits": 0, "balance": 0, "count": 0}
        filters = Q()
        filters = filters & Q(create_dt__gte=run.range_start_dt) & Q(create_dt__lte=run.range_end_dt)

        membership_filter = None

        if run.report.config:
            for k, v in run.report.config_options_dict().items():
                if k in CONFIG_OPTIONS:
                    filter_kwarg = CONFIG_OPTIONS[k]["options"][v]["filter"]
                    if filter_kwarg:
                        filters = filters & Q(**filter_kwarg)
                elif k == "invoice_object_type":
                    if "None" in v:
                        v.pop(v.index("None"))
                        filters = filters & (Q(object_type__in=v) | Q(object_type__isnull=True))
                    else:
                        filters = filters & Q(object_type__in=v)
                elif k == "invoice_membership_filter":
                    try:
                        item = MembershipType.objects.get(pk=v)
                        membership_filter = item
                    except:
                        pass

        distinct_object_types = Invoice.objects.filter(filters).values("object_type").distinct()

        for ot in distinct_object_types:
            ot_dict = {}
            invoices = Invoice.objects.filter(filters).filter(object_type=ot["object_type"])

            try:
                if membership_filter:
                    invoice_object = invoices[0].get_object()

                    if isinstance(invoice_object, MembershipDefault):
                        members_pk = MembershipDefault.objects.filter(membership_type=membership_filter).values_list(
                            "pk", flat=True
                        )
                        invoices = invoices.filter(object_id__in=set(members_pk))
                    elif isinstance(invoice_object, MembershipSet):
                        members_pk = MembershipSet.objects.filter(
                            membershipdefault__membership_type=membership_filter
                        ).values_list("pk", flat=True)
                        invoices = invoices.filter(object_id__in=set(members_pk))
                    elif isinstance(invoice_object, CorpMembership):
                        members_pk = CorpMembership.objects.filter(
                            corporate_membership_type__membership_type=membership_filter
                        ).values_list("pk", flat=True)
                        invoices = invoices.filter(object_id__in=set(members_pk))
            except:
                pass

            # generate summary mode data
            if is_summary_mode:
                sm_dict = {}
                for invoice in invoices:
                    key = str(invoice.get_object())
                    if key not in sm_dict:
                        sm_dict[key] = {"invoices": [], "count": 0, "total": 0, "payments_credits": 0, "balance": 0}
                    invoice_dict = sm_dict[key]
                    invoice_dict["count"] += 1
                    invoice_dict["invoices"].append(invoice)
                    invoice_dict["total"] += invoice.total
                    invoice_dict["payments_credits"] += invoice.payments_credits
                    invoice_dict["balance"] += invoice.balance
                ot_dict["summary"] = [v for k, v in sm_dict.items()]

            ot_dict["invoices"] = invoices.order_by("create_dt")
            ot_dict["object_type"] = get_ct_nice_name(ot["object_type"])
            ot_dict["count"] = invoices.count()
            ot_dict.update(
                {
                    "is_membership": "membership" in ot_dict["object_type"].lower(),
                    "is_donation": "donation" in ot_dict["object_type"].lower(),
                }
            )

            aggregates = invoices.aggregate(Sum("total"), Sum("payments_credits"), Sum("balance"))
            for k, v in aggregates.items():
                if not v:
                    aggregates[k] = v or 0

            ot_dict.update(aggregates)
            results.append(ot_dict)
            totals["count"] = totals["count"] + ot_dict["count"]
            totals["total"] = totals["total"] + aggregates["total__sum"]
            totals["payments_credits"] = totals["payments_credits"] + aggregates["payments_credits__sum"]
            totals["balance"] = totals["balance"] + aggregates["balance__sum"]

        results = sorted(results, key=lambda k: k["object_type"])

        try:
            if run.output_type == "html-extended":
                t = get_template("reports/invoices/results-extended.html")
            elif is_summary_mode:
                t = get_template("reports/invoices/results-summary.html")
            else:
                t = get_template("reports/invoices/results.html")
        except TemplateDoesNotExist:
            self.end_with_error(run)
            raise CommandError("The template for this report is missing.")
        return t.render(Context({"results": results, "totals": totals, "run": run}))