From 5a0958d52ce191af279aeb37e587aa2146623484 Mon Sep 17 00:00:00 2001 From: "Edgar P. Burkhart" Date: Wed, 19 Apr 2023 21:43:43 +0200 Subject: [PATCH] Fill empty months in history --- nummi/main/views.py | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/nummi/main/views.py b/nummi/main/views.py index 806b473..552d6a5 100644 --- a/nummi/main/views.py +++ b/nummi/main/views.py @@ -34,18 +34,37 @@ from .forms import ( from .models import Account, Category, Invoice, Snapshot, Transaction +class GenerateMonth(models.Func): + function = "generate_series" + template = "%(function)s(%(expressions)s, '1 month')::date" + + def history(transaction_set): - _history = ( - transaction_set.values(month=models.functions.TruncMonth("date")) - .annotate( - sum_p=models.Sum("value", filter=models.Q(value__gt=0)), - sum_m=models.Sum("value", filter=models.Q(value__lt=0)), - sum=models.Sum("value"), + _transaction_month = transaction_set.values( + month=models.functions.TruncMonth("date") + ).order_by("-date") + _months = ( + transaction_set.values( + month=GenerateMonth( + _transaction_month.last()["month"], + models.functions.Now(output_field=models.DateField()), + ) + ) + .annotate(sum_m=models.Value(0), sum_p=models.Value(0), sum=models.Value(0)) + .difference( + _transaction_month.annotate( + sum_m=models.Value(0), sum_p=models.Value(0), sum=models.Value(0) + ) ) - .order_by("-month") ) + _history = _transaction_month.annotate( + sum_p=models.Sum("value", filter=models.Q(value__gt=0)), + sum_m=models.Sum("value", filter=models.Q(value__lt=0)), + sum=models.Sum("value"), + ).order_by("-month") + return { - "data": _history, + "data": _history.union(_months).order_by("-month"), "max": max( _history.aggregate( max=models.Max("sum_p", default=0),