Fill empty months in history

This commit is contained in:
Edgar P. Burkhart 2023-04-19 21:43:43 +02:00
parent 917531aa97
commit 5a0958d52c
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227

View file

@ -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),