Fixed function monthly_balance #11

Merged
jkuijperm merged 1 commits from dev into main 2026-06-16 08:38:06 +00:00
Showing only changes of commit bb9f13a031 - Show all commits

View File

@ -68,10 +68,8 @@ class Account(models.Model):
def monthly_balance(self, year=None): def monthly_balance(self, year=None):
year = year or date.today().year year = year or date.today().year
today = date.today()
# -------------------------
# Previous accumulated balance
# -------------------------
previous_income = ( previous_income = (
self.incomes.filter(date__year__lt=year) self.incomes.filter(date__year__lt=year)
.aggregate(total=Sum('amount'))['total'] .aggregate(total=Sum('amount'))['total']
@ -84,11 +82,7 @@ class Account(models.Model):
or Decimal('0') or Decimal('0')
) )
balance = (self.initial_balance + previous_income - previous_income) balance = self.initial_balance + previous_income - previous_expenses
# -------------------------
# Current year data
# -------------------------
incomes = ( incomes = (
self.incomes.filter(date__year=year) self.incomes.filter(date__year=year)
@ -104,8 +98,8 @@ class Account(models.Model):
.annotate(total=Sum("amount")) .annotate(total=Sum("amount"))
) )
income_map = {i["month"]: i["total"] for i in incomes} income_map = {i["month"]: Decimal(str(i["total"] or 0)) for i in incomes}
expenses_map = {e["month"]: e["total"] for e in expenses} expenses_map = {e["month"]: Decimal(str(e["total"] or 0)) for e in expenses}
data = [] data = []
@ -116,11 +110,18 @@ class Account(models.Model):
data.append( data.append(
{ {
"month": month, "month": month,
"balance": float(balance), "balance": float(balance)
} }
) )
if year == today.year:
current_month_idx = today.month - 1
if 0 <= current_month_idx < len(data):
data[current_month_idx]["balance"] = float(self.current_balance())
return data return data
def balance_until(self, date): def balance_until(self, date):
incomes_total = self.incomes.filter(date__lte=date).aggregate( incomes_total = self.incomes.filter(date__lte=date).aggregate(
total=Sum("amount") total=Sum("amount")