Open-source personal finance manager. Self-hosted, privacy-first.
fix(accounts): keep a closed account's history in period reports (#1133)
Rogerio Camorim5093fbbc45c8
diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex bf4e4cc8..0f07d7e7 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -345,10 +345,8 @@ async def get_summary(func.sum(case((Transaction.type == "credit", Transaction.amount), else_=0)),func.sum(case((Transaction.type == "debit", Transaction.amount), else_=0)),)- .join(Account, Transaction.account_id == Account.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,report_date >= month_start,report_date < month_end,report_date <= today,@@ -490,10 +488,8 @@ async def get_summary(func.sum(case((Transaction.type == "credit", Transaction.amount_primary), else_=0)),func.sum(case((Transaction.type == "debit", Transaction.amount_primary), else_=0)),)- .join(Account, Transaction.account_id == Account.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,report_date >= month_start,report_date < month_end,report_date <= today,@@ -742,11 +738,9 @@ async def get_spending_by_category(func.sum(_primary_amount_expr()),).select_from(Transaction)- .join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,Transaction.type == "debit",report_date >= month_start,report_date < month_end,@@ -948,10 +942,8 @@ async def get_monthly_trend(func.sum(case((Transaction.type == "credit", primary_amt), else_=0)),func.sum(case((Transaction.type == "debit", primary_amt), else_=0)),)- .join(Account, Transaction.account_id == Account.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,Transaction.source != "opening_balance",report_date <= today,Transaction.status == "posted",diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 1ffe47bb..90663eb7 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -466,10 +466,8 @@ async def get_income_expenses_report(func.sum(case((Transaction.type == "credit", amount_expr), else_=0)),func.sum(case((Transaction.type == "debit", amount_expr), else_=0)),)- .join(Account, Transaction.account_id == Account.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,report_date >= start,report_date <= axis_end,Transaction.source != "opening_balance",@@ -802,11 +800,9 @@ async def get_income_expenses_report(func.sum(amount_expr),).select_from(Transaction)- .join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,report_date >= start,report_date <= axis_end,Transaction.source != "opening_balance",@@ -866,11 +862,9 @@ async def get_income_expenses_report(func.sum(amount_expr),).select_from(Transaction)- .join(Account, Transaction.account_id == Account.id).join(Category, Transaction.category_id == Category.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,report_date >= start,report_date <= axis_end,Transaction.source != "opening_balance",@@ -906,11 +900,9 @@ async def get_income_expenses_report(func.sum(amount_expr),).select_from(Transaction)- .join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,report_date >= start,report_date <= axis_end,Transaction.source != "opening_balance",diff --git a/backend/app/services/transaction_calendar_service.py b/backend/app/services/transaction_calendar_service.pyindex 982673de..17a895d4 100644--- a/backend/app/services/transaction_calendar_service.py+++ b/backend/app/services/transaction_calendar_service.py@@ -290,11 +290,9 @@ async def _load_actual_transactions() -> list[Transaction]:stmt = (select(Transaction)- .join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.workspace_id == workspace_id,- Account.is_closed == False,Transaction.date >= start,Transaction.date < end,Transaction.date <= app_today(),diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex ba15cd3e..8de7a072 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -265,7 +265,9 @@ async def get_transactions(if exclude_transfers:base_query = base_query.where(Transaction.transfer_pair_id.is_(None))if user_pnl_only:- base_query = base_query.where(Account.is_closed == False, counts_as_user_pnl())+ # Closed accounts are not excluded here: their history stays in the+ # period totals this list drills into (issue #1112).+ base_query = base_query.where(counts_as_user_pnl())if exclude_ignored:# Only drops rows; the summary below keeps computing over the same# filtered set, so the totals a hidden list shows stay the totals ofdiff --git a/backend/tests/test_dashboard_service.py b/backend/tests/test_dashboard_service.pyindex 7b5a786a..8b985906 100644--- a/backend/tests/test_dashboard_service.py+++ b/backend/tests/test_dashboard_service.py@@ -18,6 +18,7 @@ from app.services.dashboard_service import (_account_balance_at,_total_balance_by_currency,get_balance_history,+ get_monthly_trend,get_summary,get_spending_by_category,get_projected_transactions,@@ -378,9 +379,14 @@ async def test_get_summary_basic(session: AsyncSession, test_user, test_workspac@pytest.mark.asyncio-async def test_summary_matches_drilldown_and_excludes_closed_accounts(+async def test_summary_keeps_closed_account_history_and_matches_drilldown(session: AsyncSession, test_user, test_workspace):+ """Closing an account stops it counting as current money, not as history.++ Past income and expenses of a closed account stay in the month's totals+ (issue #1112), and the drill-down behind those totals lists the same rows.+ """month = (date.today().replace(day=1) - timedelta(days=1)).replace(day=1)month_start, month_end = _month_range(month)open_account = await _make_account(session, test_user.id, "Open")@@ -404,7 +410,9 @@ async def test_summary_matches_drilldown_and_excludes_closed_accounts(user_pnl_only=True,)- assert {row.account_id for row in rows} == {open_account.id}+ assert {row.account_id for row in rows} == {open_account.id, closed_account.id}+ assert summary.monthly_income == pytest.approx(1000.0)+ assert summary.monthly_expenses == pytest.approx(840.0)assert summary.monthly_income == pytest.approx(sum(float(row.amount) for row in rows if row.type == "credit"))@@ -413,6 +421,46 @@ async def test_summary_matches_drilldown_and_excludes_closed_accounts()+async def test_closed_account_balance_stays_out_of_current_totals(+ session: AsyncSession, test_user, test_workspace+):+ """History of a closed account counts; its balance does not."""+ month = date.today().replace(day=1)+ open_account = await _make_account(session, test_user.id, "Open")+ closed_account = await _make_account(+ session, test_user.id, "Closed", is_closed=True+ )+ await _add_txn(session, test_user.id, open_account.id, 100, "credit", month)+ await _add_txn(session, test_user.id, closed_account.id, 250, "credit", month)++ summary = await get_summary(session, test_workspace.id, test_user.id, month=month)++ assert summary.monthly_income == pytest.approx(350.0)+ assert summary.total_balance.get("BRL", 0.0) == pytest.approx(100.0)+ accounts = await _get_open_accounts(session, test_workspace.id)+ assert {a.id for a in accounts} == {open_account.id}+++async def test_spending_and_trend_keep_closed_account_history(+ session: AsyncSession, test_user, test_workspace+):+ cat = await _make_category(session, test_user.id, "Savings fees")+ closed_account = await _make_account(+ session, test_user.id, "Closed saver", is_closed=True+ )+ today = date.today()+ await _add_txn(session, test_user.id, closed_account.id, 60, "debit", today, category_id=cat.id)++ spending = await get_spending_by_category(session, test_workspace.id, test_user.id)+ fees = next((s for s in spending if s.category_id == str(cat.id)), None)+ assert fees is not None and fees.total == pytest.approx(60.0)++ trend = await get_monthly_trend(session, test_workspace.id, test_user.id, months=1)+ assert sum(point.expenses for point in trend) == pytest.approx(60.0)++@pytest.mark.asyncioasync def test_get_summary_excludes_opening_balance_from_income(session: AsyncSession, test_user, test_workspace):"""Opening balance does not count as monthly income."""diff --git a/backend/tests/test_report_service_coverage.py b/backend/tests/test_report_service_coverage.pyindex f4ddb00c..c32f1c22 100644--- a/backend/tests/test_report_service_coverage.py+++ b/backend/tests/test_report_service_coverage.py@@ -272,11 +272,14 @@ async def test_income_expenses_yearly_interval(session, test_user, test_workspacassert bd["income"] == pytest.approx(2000.0)-async def test_income_expenses_excludes_opening_and_closed(session, test_user, test_workspace):- """opening_balance source and closed accounts contribute nothing."""+async def test_income_expenses_excludes_opening_but_keeps_closed_history(+ session, test_user, test_workspace+):+ """opening_balance rows contribute nothing; a closed account's history still counts."""closed = await _make_account(session, test_user.id, "IE Closed", is_closed=True)today = date.today()await _add_txn(session, test_user.id, closed.id, 1000, "credit", today)+ await _add_txn(session, test_user.id, closed.id, 300, "debit", today)open_acct = await _make_account(session, test_user.id, "IE Open")await _add_txn(session, test_user.id, open_acct.id, 7000, "credit", today, source="opening_balance")@@ -285,8 +288,8 @@ async def test_income_expenses_excludes_opening_and_closed(session, test_user, tsession, test_workspace.id, test_user.id, months=2, interval="monthly")bd = {b.key: b.value for b in report.summary.breakdowns}- assert bd["income"] == 0.0- assert bd["expenses"] == 0.0+ assert bd["income"] == 1000.0+ assert bd["expenses"] == 300.0async def test_income_expenses_with_recurring_projection(session, test_user, test_workspace):diff --git a/backend/tests/test_transaction_calendar_service.py b/backend/tests/test_transaction_calendar_service.pyindex 14d3caf1..d11327bd 100644--- a/backend/tests/test_transaction_calendar_service.py+++ b/backend/tests/test_transaction_calendar_service.py@@ -924,3 +924,46 @@ async def test_transaction_calendar_ignored_actual_is_consistent_across_months(assert august_september_1.ending_balance == 1000.0assert september_september_1.ending_balance == 1000.0assert august_september_1.ending_balance == september_september_1.ending_balance+++async def test_transaction_calendar_shows_closed_account_history_but_not_its_balance(+ session: AsyncSession, test_user, test_workspace+):+ """A closed account's past rows stay on the calendar (issue #1112), while the+ running balance keeps counting only accounts that are still open."""+ open_account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Open", type="checking", balance=Decimal("0"), currency="BRL",+ )+ closed_account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Closed", type="savings", balance=Decimal("0"), currency="BRL",+ is_closed=True,+ )+ session.add_all([open_account, closed_account])+ await session.flush()+ session.add_all([+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=open_account.id, description="Salary", amount=Decimal("1000"),+ currency="BRL", date=date(2026, 7, 2), type="credit", source="manual",+ ),+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=closed_account.id, description="Old fee", amount=Decimal("400"),+ currency="BRL", date=date(2026, 7, 3), type="debit", source="manual",+ ),+ ])+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )++ july_3 = next(day for day in calendar.days if day.date == date(2026, 7, 3))+ assert july_3.actual_count == 1+ assert july_3.actual_expense == 400.0+ assert july_3.items[0].description == "Old fee"+ # The balance is what the open accounts hold; the closed account is not part of it.+ assert july_3.ending_balance == 1000.0