from decimal import Decimal from django.db.models import Sum from liveview import send from app.expenses.templatetags.money import format_money from app.monthly.models import Income, MonthlyFixedExpense, MonthlyNote from app.yearly.models import PlannedExpense def update_budget(consumer, year, month): """Recalculate and send budget to client.""" income_total = Income.objects.filter(date__year=year, date__month=month).aggregate( total=Sum("amount") )["total"] or Decimal("0") fe_total = MonthlyFixedExpense.objects.filter(year=year, month=month).aggregate( total=Sum("amount") )["total"] or Decimal("0") planned_total = PlannedExpense.objects.filter(year=year, month=month).aggregate( total=Sum("amount") )["total"] or Decimal("0") note, _ = MonthlyNote.objects.get_or_create(year=year, month=month) budget = income_total - fe_total - note.savings_target - planned_total send(consumer, {"target": "#budget-amount", "html": f"{format_money(budget)} €"})