diff --git a/expenses_manager/expenses/models.py b/expenses_manager/expenses/models.py index 4f2b0a6..33b7b57 100644 --- a/expenses_manager/expenses/models.py +++ b/expenses_manager/expenses/models.py @@ -68,10 +68,8 @@ class Account(models.Model): def monthly_balance(self, year=None): year = year or date.today().year - - # ------------------------- - # Previous accumulated balance - # ------------------------- + today = date.today() + previous_income = ( self.incomes.filter(date__year__lt=year) .aggregate(total=Sum('amount'))['total'] @@ -84,11 +82,7 @@ class Account(models.Model): or Decimal('0') ) - balance = (self.initial_balance + previous_income - previous_income) - - # ------------------------- - # Current year data - # ------------------------- + balance = self.initial_balance + previous_income - previous_expenses incomes = ( self.incomes.filter(date__year=year) @@ -96,30 +90,37 @@ class Account(models.Model): .values("month") .annotate(total=Sum("amount")) ) - + expenses = ( self.expenses.filter(date__year=year) .annotate(month=ExtractMonth("date")) .values("month") .annotate(total=Sum("amount")) ) - - income_map = {i["month"]: i["total"] for i in incomes} - expenses_map = {e["month"]: e["total"] for e in expenses} - + + income_map = {i["month"]: Decimal(str(i["total"] or 0)) for i in incomes} + expenses_map = {e["month"]: Decimal(str(e["total"] or 0)) for e in expenses} + data = [] - + for month in range(1, 13): balance += income_map.get(month, Decimal("0")) balance -= expenses_map.get(month, Decimal("0")) - + data.append( { "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 + def balance_until(self, date): incomes_total = self.incomes.filter(date__lte=date).aggregate(