Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix(budgets): offset positive refund transactions in category budget calculation (#757)

Vijay Misal14e66371c200
diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.py
index c1360a1a..2e874909 100644
--- a/backend/app/services/budget_service.py
+++ b/backend/app/services/budget_service.py
@@ -3,7 +3,7 @@ from datetime import date
from decimal import Decimal
from typing import Optional
-from sqlalchemy import select, func, and_
+from sqlalchemy import select, func, and_, case
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.app_clock import app_today
@@ -266,15 +266,21 @@ async def get_budget_vs_actual(
report_date = reporting_date_col(accounting_mode)
# Get actual spending by category for this month (exclude transfer pairs)
+ # Net spending = Debits - Credits (refunds offset expenses)
# Use amount_primary for multi-currency support
spending_result = await session.execute(
select(
Transaction.category_id,
- func.sum(_primary_amount_expr()),
+ func.sum(
+ case(
+ (Transaction.type == "debit", _primary_amount_expr()),
+ (Transaction.type == "credit", -_primary_amount_expr()),
+ else_=0,
+ )
+ ),
)
.where(
Transaction.workspace_id == workspace_id,
- Transaction.type == "debit",
report_date >= month_start,
report_date < month_end,
Transaction.category_id.isnot(None),
@@ -286,7 +292,9 @@ async def get_budget_vs_actual(
)
spending_map: dict[str, Decimal] = {}
for row in spending_result.all():
- spending_map[str(row[0])] = abs(row[1] or Decimal("0"))
+ net = row[1] or Decimal("0")
+ if net > 0:
+ spending_map[str(row[0])] = net
# Subtract non-owner shares of own splits — only the user's share counts.
own_offset = await owner_split_offset_by_category(
@@ -352,15 +360,21 @@ async def get_budget_vs_actual(
projected_spending_map[cat_id] = projected_spending_map.get(cat_id, Decimal("0")) + converted
# Get previous month spending by category (exclude transfer pairs)
+ # Net spending = Debits - Credits (refunds offset expenses)
# Use amount_primary for multi-currency support
prev_spending_result = await session.execute(
select(
Transaction.category_id,
- func.sum(_primary_amount_expr()),
+ func.sum(
+ case(
+ (Transaction.type == "debit", _primary_amount_expr()),
+ (Transaction.type == "credit", -_primary_amount_expr()),
+ else_=0,
+ )
+ ),
)
.where(
Transaction.workspace_id == workspace_id,
- Transaction.type == "debit",
report_date >= prev_month_start,
report_date < prev_month_end,
Transaction.category_id.isnot(None),
@@ -372,7 +386,9 @@ async def get_budget_vs_actual(
)
prev_spending_map: dict[str, Decimal] = {}
for row in prev_spending_result.all():
- prev_spending_map[str(row[0])] = abs(row[1] or Decimal("0"))
+ net = row[1] or Decimal("0")
+ if net > 0:
+ prev_spending_map[str(row[0])] = net
prev_own_offset = await owner_split_offset_by_category(
session, user_id, prev_month_start, prev_month_end,
diff --git a/backend/tests/test_budget_service.py b/backend/tests/test_budget_service.py
index 7e919742..96d51e5c 100644
--- a/backend/tests/test_budget_service.py
+++ b/backend/tests/test_budget_service.py
@@ -401,7 +401,7 @@ async def test_budget_vs_actual_includes_prev_month(
session.add(account)
await session.commit()
- # Spending in Feb (prev month)
+ # Spending and a refund in Feb (prev month)
txn_prev = Transaction(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -414,6 +414,18 @@ async def test_budget_vs_actual_includes_prev_month(
source="manual",
created_at=datetime.now(timezone.utc),
)
+ txn_prev_refund = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Feb refund",
+ amount=Decimal("30"),
+ date=date(2025, 2, 20),
+ type="credit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
# Spending in March (current)
txn_curr = Transaction(
id=uuid.uuid4(),
@@ -427,10 +439,115 @@ async def test_budget_vs_actual_includes_prev_month(
source="manual",
created_at=datetime.now(timezone.utc),
)
- session.add_all([txn_prev, txn_curr])
+ session.add_all([txn_prev, txn_prev_refund, txn_curr])
await session.commit()
comparisons = await get_budget_vs_actual(session, test_workspace.id, test_user.id, month=date(2025, 3, 1))
cat0 = [c for c in comparisons if c.category_id == test_categories[0].id]
- if cat0:
- assert cat0[0].prev_month_amount == Decimal("75")
+ assert len(cat0) == 1
+ assert cat0[0].prev_month_amount == Decimal("45")
+
+
+async def test_budget_vs_actual_offsets_refunds(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="RefundAccount",
+ type="checking",
+ balance=Decimal("5000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+
+ # Budget of 200 for April 2025
+ await create_budget(
+ session,
+ test_workspace.id,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("200"),
+ month=date(2025, 4, 1),
+ ),
+ )
+
+ # 2 expenses: 100 and 50 (total 150)
+ # 1 refund (credit): 30
+ # Net actual should be: 150 - 30 = 120
+ txns = [
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Previous month expense",
+ amount=Decimal("80"),
+ date=date(2025, 3, 10),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ ),
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Previous month refund",
+ amount=Decimal("25"),
+ date=date(2025, 3, 12),
+ type="credit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ ),
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Expense 1",
+ amount=Decimal("100"),
+ date=date(2025, 4, 10),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ ),
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Expense 2",
+ amount=Decimal("50"),
+ date=date(2025, 4, 12),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ ),
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Refund",
+ amount=Decimal("30"),
+ date=date(2025, 4, 15),
+ type="credit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ ),
+ ]
+ session.add_all(txns)
+ await session.commit()
+
+ comparisons = await get_budget_vs_actual(
+ session, test_workspace.id, test_user.id, month=date(2025, 4, 1)
+ )
+ cat0 = [c for c in comparisons if c.category_id == test_categories[0].id]
+ assert len(cat0) == 1
+ assert cat0[0].actual_amount == Decimal("120")
+ assert cat0[0].prev_month_amount == Decimal("55")
+