Open-source personal finance manager. Self-hosted, privacy-first.
improve test stack and coverage
Tássio Noronha570e8d69bae5
diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex 47c36689..3fc9fee5 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -53,6 +53,10 @@ asyncio_default_test_loop_scope = "session"testpaths = ["tests"][tool.coverage.run]+# FastAPI/Starlette route handlers run on SQLAlchemy's greenlet, so coverage.py+# must track greenlet (and thread) execution contexts — otherwise async endpoint+# bodies execute but their lines are never attributed, under-reporting every API module.+concurrency = ["greenlet", "thread"]omit = ["app/cli.py","app/worker.py",diff --git a/backend/tests/test_accounts_api_coverage.py b/backend/tests/test_accounts_api_coverage.pynew file mode 100644index 00000000..b10bb32f--- /dev/null+++ b/backend/tests/test_accounts_api_coverage.py@@ -0,0 +1,282 @@+"""Coverage-focused tests for app/api/accounts.py.++Exercises list filters, get/create/update/delete, close/reopen, summary,+balance-history and bills endpoints, plus 404/400 error branches and the+non-primary-currency conversion path.+"""+import uuid+from decimal import Decimal++import pytest+from httpx import AsyncClient++from app.models.account import Account+++NONEXISTENT = "00000000-0000-0000-0000-000000000000"+++# ---------------------------------------------------------------------------+# list_accounts+# ---------------------------------------------------------------------------+++async def test_list_accounts_include_closed(client: AsyncClient, auth_headers):+ """A manually-closed account is hidden by default and shown with the flag."""+ create = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "Closeable", "type": "savings", "balance": "10.00"},+ )+ acc_id = create.json()["id"]+ await client.post(f"/api/accounts/{acc_id}/close", headers=auth_headers)++ default = await client.get("/api/accounts", headers=auth_headers)+ assert all(a["id"] != acc_id for a in default.json())++ with_closed = await client.get(+ "/api/accounts?include_closed=true", headers=auth_headers+ )+ assert any(a["id"] == acc_id for a in with_closed.json())+++async def test_list_accounts_foreign_currency_conversion(+ client: AsyncClient, auth_headers+):+ """A non-primary-currency account triggers the convert() balance_primary path."""+ await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "USD Wallet", "type": "checking", "balance": "100.00", "currency": "USD"},+ )+ resp = await client.get("/api/accounts", headers=auth_headers)+ assert resp.status_code == 200+ usd = next(a for a in resp.json() if a["name"] == "USD Wallet")+ assert "balance_primary" in usd+++# ---------------------------------------------------------------------------+# get_account+# ---------------------------------------------------------------------------+++async def test_get_account_found(client: AsyncClient, auth_headers, test_account: Account):+ resp = await client.get(f"/api/accounts/{test_account.id}", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.json()["name"] == "Conta Corrente"+++# ---------------------------------------------------------------------------+# create / update / delete+# ---------------------------------------------------------------------------+++async def test_create_credit_card_account(client: AsyncClient, auth_headers):+ resp = await client.post(+ "/api/accounts", headers=auth_headers,+ json={+ "name": "Visa", "type": "credit_card", "balance": "0.00",+ "credit_limit": "5000.00", "statement_close_day": 10,+ "payment_due_day": 18, "card_brand": "visa",+ },+ )+ assert resp.status_code == 201, resp.text+ data = resp.json()+ assert data["type"] == "credit_card"+ assert data["credit_limit"] == 5000.0+++async def test_update_account_name(client: AsyncClient, auth_headers):+ create = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "Old", "type": "checking", "balance": "0.00"},+ )+ acc_id = create.json()["id"]+ resp = await client.patch(+ f"/api/accounts/{acc_id}", headers=auth_headers, json={"name": "New"},+ )+ assert resp.status_code == 200+ assert resp.json()["name"] == "New"+++async def test_update_account_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.patch(+ f"/api/accounts/{NONEXISTENT}", headers=auth_headers, json={"name": "X"},+ )+ assert resp.status_code == 404+++async def test_update_bank_connected_account_rejected(+ client: AsyncClient, auth_headers, test_account: Account+):+ """test_account is connection-backed; editing the name must 400."""+ resp = await client.patch(+ f"/api/accounts/{test_account.id}", headers=auth_headers,+ json={"name": "Hacked"},+ )+ assert resp.status_code == 400+++async def test_delete_account(client: AsyncClient, auth_headers):+ create = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "Temp", "type": "checking", "balance": "0.00"},+ )+ acc_id = create.json()["id"]+ resp = await client.delete(f"/api/accounts/{acc_id}", headers=auth_headers)+ assert resp.status_code == 204+ # Gone now+ assert (await client.get(f"/api/accounts/{acc_id}", headers=auth_headers)).status_code == 404+++async def test_delete_account_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.delete(f"/api/accounts/{NONEXISTENT}", headers=auth_headers)+ assert resp.status_code == 404+++async def test_delete_bank_connected_account_rejected(+ client: AsyncClient, auth_headers, test_account: Account+):+ resp = await client.delete(f"/api/accounts/{test_account.id}", headers=auth_headers)+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# close / reopen+# ---------------------------------------------------------------------------+++async def test_close_then_reopen(client: AsyncClient, auth_headers):+ create = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "Lifecycle", "type": "checking", "balance": "0.00"},+ )+ acc_id = create.json()["id"]++ closed = await client.post(f"/api/accounts/{acc_id}/close", headers=auth_headers)+ assert closed.status_code == 200+ assert closed.json()["is_closed"] is True++ # Double-close is a 400+ again = await client.post(f"/api/accounts/{acc_id}/close", headers=auth_headers)+ assert again.status_code == 400++ reopened = await client.post(f"/api/accounts/{acc_id}/reopen", headers=auth_headers)+ assert reopened.status_code == 200+ assert reopened.json()["is_closed"] is False++ # Reopen an open account is a 400+ again2 = await client.post(f"/api/accounts/{acc_id}/reopen", headers=auth_headers)+ assert again2.status_code == 400+++async def test_close_account_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.post(f"/api/accounts/{NONEXISTENT}/close", headers=auth_headers)+ assert resp.status_code == 404+++async def test_reopen_account_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.post(f"/api/accounts/{NONEXISTENT}/reopen", headers=auth_headers)+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# summary+# ---------------------------------------------------------------------------+++async def test_account_summary(client: AsyncClient, auth_headers, test_transactions):+ account_id = test_transactions[0].account_id+ resp = await client.get(+ f"/api/accounts/{account_id}/summary", headers=auth_headers+ )+ assert resp.status_code == 200+ data = resp.json()+ assert "current_balance" in data+ assert "monthly_income" in data+ assert "monthly_expenses" in data+++async def test_account_summary_with_date_range(+ client: AsyncClient, auth_headers, test_transactions+):+ account_id = test_transactions[0].account_id+ resp = await client.get(+ f"/api/accounts/{account_id}/summary?from=2020-01-01&to=2020-12-31",+ headers=auth_headers,+ )+ assert resp.status_code == 200+++async def test_account_summary_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.get(f"/api/accounts/{NONEXISTENT}/summary", headers=auth_headers)+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# balance-history+# ---------------------------------------------------------------------------+++async def test_balance_history(client: AsyncClient, auth_headers, test_transactions):+ account_id = test_transactions[0].account_id+ resp = await client.get(+ f"/api/accounts/{account_id}/balance-history", headers=auth_headers+ )+ assert resp.status_code == 200+ assert isinstance(resp.json(), list)+++async def test_balance_history_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.get(+ f"/api/accounts/{NONEXISTENT}/balance-history", headers=auth_headers+ )+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# bills+# ---------------------------------------------------------------------------+++async def test_account_bills_empty_for_checking(+ client: AsyncClient, auth_headers, test_account: Account+):+ """Non-CC accounts return an empty bills list (not a 404)."""+ resp = await client.get(f"/api/accounts/{test_account.id}/bills", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_account_bills_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.get(f"/api/accounts/{NONEXISTENT}/bills", headers=auth_headers)+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# auth+# ---------------------------------------------------------------------------+++async def test_list_accounts_requires_auth(client: AsyncClient):+ resp = await client.get("/api/accounts")+ assert resp.status_code == 401diff --git a/backend/tests/test_asset_group_service_coverage.py b/backend/tests/test_asset_group_service_coverage.pynew file mode 100644index 00000000..4aa8a6a2--- /dev/null+++ b/backend/tests/test_asset_group_service_coverage.py@@ -0,0 +1,253 @@+"""Coverage-focused tests for asset_group_service.++Exercises the rollup math (incl. value-history fallback and FX conversion),+get/update/delete paths, position assignment, and the connection-sync+helpers (`ensure_group_for_connection`, `_unique_default_name`).+"""+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_group import AssetGroup+from app.models.asset_value import AssetValue+from app.models.bank_connection import BankConnection+from app.schemas.asset_group import AssetGroupCreate, AssetGroupUpdate+from app.services import asset_group_service as svc+++async def _add_asset(session, user_id, workspace_id, group_id, *, currency="BRL",+ purchase_price=None, value_amount=None, is_archived=False,+ sell_date=None):+ asset = Asset(+ id=uuid.uuid4(),+ user_id=user_id,+ workspace_id=workspace_id,+ name=f"Asset-{uuid.uuid4().hex[:5]}",+ type="investment",+ currency=currency,+ group_id=group_id,+ purchase_price=purchase_price,+ is_archived=is_archived,+ sell_date=sell_date,+ )+ session.add(asset)+ await session.flush()+ if value_amount is not None:+ session.add(AssetValue(+ id=uuid.uuid4(),+ asset_id=asset.id,+ workspace_id=workspace_id,+ amount=value_amount,+ date=date.today(),+ source="manual",+ ))+ await session.flush()+ return asset+++async def test_create_group_assigns_next_position(session: AsyncSession, test_user, test_workspace):+ g1 = await svc.create_group(+ session, test_workspace.id, test_user.id, AssetGroupCreate(name="W1")+ )+ g2 = await svc.create_group(+ session, test_workspace.id, test_user.id, AssetGroupCreate(name="W2")+ )+ # position defaulted to 0 -> _next_position appends.+ assert g2.position == g1.position + 1+ assert g1.source == "manual"+++async def test_create_group_honors_explicit_position(session: AsyncSession, test_user, test_workspace):+ g = await svc.create_group(+ session, test_workspace.id, test_user.id,+ AssetGroupCreate(name="Pinned", position=7),+ )+ assert g.position == 7+++async def test_get_groups_rolls_up_values_and_fallback(session: AsyncSession, test_user, test_workspace):+ g = await svc.create_group(+ session, test_workspace.id, test_user.id, AssetGroupCreate(name="Rollup")+ )+ # One asset with a value-history row (primary currency BRL).+ await _add_asset(session, test_user.id, test_workspace.id, g.id,+ currency="BRL", value_amount=Decimal("100"))+ # One asset with NO value history -> falls back to purchase_price.+ await _add_asset(session, test_user.id, test_workspace.id, g.id,+ currency="BRL", purchase_price=Decimal("50"))+ # Archived asset -> excluded.+ await _add_asset(session, test_user.id, test_workspace.id, g.id,+ currency="BRL", value_amount=Decimal("999"), is_archived=True)+ # Sold asset -> excluded.+ await _add_asset(session, test_user.id, test_workspace.id, g.id,+ currency="BRL", value_amount=Decimal("999"), sell_date=date.today())+ # Asset with neither value nor purchase_price -> skipped silently.+ await _add_asset(session, test_user.id, test_workspace.id, g.id, currency="BRL")+ await session.commit()++ groups = await svc.get_groups(session, test_workspace.id, test_user.id)+ by_name = {x.name: x for x in groups}+ assert "Rollup" in by_name+ read = by_name["Rollup"]+ # asset_count counts non-archived, non-sold assets (3: two valued + one+ # with no value/price that is still counted). Sold/archived excluded.+ assert read.asset_count == 3+ assert read.current_value == 150.0+ # Primary currency is BRL (test_user pref) -> matches without conversion.+ assert read.current_value_primary == 150.0+++async def test_get_groups_converts_foreign_currency(session: AsyncSession, test_user, test_workspace, monkeypatch):+ g = await svc.create_group(+ session, test_workspace.id, test_user.id, AssetGroupCreate(name="FX")+ )+ await _add_asset(session, test_user.id, test_workspace.id, g.id,+ currency="USD", value_amount=Decimal("10"))+ await session.commit()++ async def _fake_convert(session, amount, frm, to):+ return Decimal(amount) * Decimal("5"), Decimal("5")++ monkeypatch.setattr(svc, "convert", _fake_convert)++ groups = await svc.get_groups(session, test_workspace.id, test_user.id)+ read = {x.name: x for x in groups}["FX"]+ assert read.current_value == 10.0+ assert read.current_value_primary == 50.0+++async def test_get_groups_empty_returns_empty(session: AsyncSession, test_user, test_workspace):+ assert await svc.get_groups(session, test_workspace.id, test_user.id) == []+++async def test_get_groups_includes_institution_name(session: AsyncSession, test_user, test_workspace):+ conn = BankConnection(+ id=uuid.uuid4(),+ user_id=test_user.id,+ provider="pluggy",+ external_id="item-x",+ institution_name="Nubank",+ credentials={"t": "x"},+ status="active",+ created_at=datetime.now(timezone.utc),+ )+ session.add(conn)+ await session.flush()+ g = AssetGroup(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Synced",+ source="pluggy",+ connection_id=conn.id,+ )+ session.add(g)+ await session.flush()+ await _add_asset(session, test_user.id, test_workspace.id, g.id,+ currency="BRL", value_amount=Decimal("1"))+ await session.commit()++ groups = await svc.get_groups(session, test_workspace.id, test_user.id)+ read = {x.name: x for x in groups}["Synced"]+ assert read.institution_name == "Nubank"+++async def test_get_group_found_and_not_found(session: AsyncSession, test_user, test_workspace):+ g = await svc.create_group(+ session, test_workspace.id, test_user.id, AssetGroupCreate(name="One")+ )+ found = await svc.get_group(session, g.id, test_workspace.id, test_user.id)+ assert found is not None+ assert found.name == "One"++ missing = await svc.get_group(session, uuid.uuid4(), test_workspace.id, test_user.id)+ assert missing is None+++async def test_update_group(session: AsyncSession, test_user, test_workspace):+ g = await svc.create_group(+ session, test_workspace.id, test_user.id, AssetGroupCreate(name="Old")+ )+ updated = await svc.update_group(+ session, g.id, test_workspace.id, test_user.id,+ AssetGroupUpdate(name="New", color="#000000"),+ )+ assert updated is not None+ assert updated.name == "New"+ assert updated.color == "#000000"++ none = await svc.update_group(+ session, uuid.uuid4(), test_workspace.id, test_user.id,+ AssetGroupUpdate(name="X"),+ )+ assert none is None+++async def test_delete_group(session: AsyncSession, test_user, test_workspace):+ g = await svc.create_group(+ session, test_workspace.id, test_user.id, AssetGroupCreate(name="Doomed")+ )+ assert await svc.delete_group(session, g.id, test_workspace.id) is True+ assert await svc.delete_group(session, g.id, test_workspace.id) is False+++async def test_ensure_group_for_connection_creates_then_relinks(session: AsyncSession, test_user):+ conn_id = uuid.uuid4()+ g = await svc.ensure_group_for_connection(+ session, test_user.id, conn_id, "pluggy", "ext-1", "MeuPluggy"+ )+ assert g.name == "MeuPluggy"+ assert g.connection_id == conn_id+ assert g.source == "pluggy"++ # Same external_id, new connection -> relink, keep name.+ new_conn = uuid.uuid4()+ g2 = await svc.ensure_group_for_connection(+ session, test_user.id, new_conn, "pluggy", "ext-1", "Renamed"+ )+ assert g2.id == g.id+ assert g2.connection_id == new_conn+ assert g2.name == "MeuPluggy"+++async def test_ensure_group_for_connection_matches_by_connection_id(session: AsyncSession, test_user):+ conn_id = uuid.uuid4()+ g = await svc.ensure_group_for_connection(+ session, test_user.id, conn_id, "pluggy", None, "NoExtId"+ )+ g2 = await svc.ensure_group_for_connection(+ session, test_user.id, conn_id, "pluggy", None, "Other"+ )+ assert g2.id == g.id+++async def test_ensure_group_for_connection_disambiguates_name(session: AsyncSession, test_user):+ # Two distinct external ids, same default name -> " 2" suffix.+ g1 = await svc.ensure_group_for_connection(+ session, test_user.id, uuid.uuid4(), "pluggy", "ext-a", "MeuPluggy"+ )+ g2 = await svc.ensure_group_for_connection(+ session, test_user.id, uuid.uuid4(), "pluggy", "ext-b", "MeuPluggy"+ )+ g3 = await svc.ensure_group_for_connection(+ session, test_user.id, uuid.uuid4(), "pluggy", "ext-c", "MeuPluggy"+ )+ assert g1.name == "MeuPluggy"+ assert g2.name == "MeuPluggy 2"+ assert g3.name == "MeuPluggy 3"diff --git a/backend/tests/test_assets_api_coverage.py b/backend/tests/test_assets_api_coverage.pynew file mode 100644index 00000000..c7118bac--- /dev/null+++ b/backend/tests/test_assets_api_coverage.py@@ -0,0 +1,335 @@+"""Coverage-focused API tests for app/api/assets.py.++Covers the market search/quote proxy endpoints (with the provider mocked),+the single-asset price refresh branches, portfolio-trend, value-trend, and+the 404 branches on the value sub-resources.+"""+import uuid+from datetime import date+from decimal import Decimal+from unittest.mock import AsyncMock, patch++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_value import AssetValue+from app.models.user import User+from app.providers.market_price import MarketPriceRateLimitedError+from app.schemas.asset import MarketSymbolMatch, MarketSymbolQuote+++@pytest_asyncio.fixture+async def manual_asset(session: AsyncSession, test_user: User) -> Asset:+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Cov House",+ type="real_estate",+ currency="USD",+ valuation_method="manual",+ purchase_price=Decimal("100000.00"),+ purchase_date=date(2024, 1, 1),+ position=0,+ )+ session.add(asset)+ await session.flush()+ session.add(+ AssetValue(+ id=uuid.uuid4(),+ asset_id=asset.id,+ amount=Decimal("120000.00"),+ date=date(2025, 1, 1),+ source="manual",+ )+ )+ await session.commit()+ await session.refresh(asset)+ return asset+++@pytest_asyncio.fixture+async def market_asset(session: AsyncSession, test_user: User) -> Asset:+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="AAPL Holding",+ type="stock",+ currency="USD",+ valuation_method="market_price",+ ticker="AAPL",+ units=Decimal("10"),+ position=0,+ )+ session.add(asset)+ await session.commit()+ await session.refresh(asset)+ return asset+++# ---------------------------------------------------------------------------+# market search / quote+# ---------------------------------------------------------------------------+async def test_market_search_success(client: AsyncClient, auth_headers, test_user):+ fake = AsyncMock()+ fake.search = AsyncMock(+ return_value=[MarketSymbolMatch(symbol="AAPL", name="Apple Inc.", exchange="NMS")]+ )+ with patch("app.api.assets.get_market_price_provider", return_value=fake):+ resp = await client.get("/api/assets/market/search?q=apple", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body[0]["symbol"] == "AAPL"+++async def test_market_search_rate_limited_429(client: AsyncClient, auth_headers, test_user):+ fake = AsyncMock()+ fake.search = AsyncMock(side_effect=MarketPriceRateLimitedError("slow down"))+ with patch("app.api.assets.get_market_price_provider", return_value=fake):+ resp = await client.get("/api/assets/market/search?q=ab", headers=auth_headers)+ assert resp.status_code == 429+++async def test_market_search_generic_error_returns_empty(client: AsyncClient, auth_headers, test_user):+ fake = AsyncMock()+ fake.search = AsyncMock(side_effect=RuntimeError("boom"))+ with patch("app.api.assets.get_market_price_provider", return_value=fake):+ resp = await client.get("/api/assets/market/search?q=ab", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_market_search_validation_422(client: AsyncClient, auth_headers, test_user):+ # Missing required q param.+ resp = await client.get("/api/assets/market/search", headers=auth_headers)+ assert resp.status_code == 422+++async def test_market_quote_success(client: AsyncClient, auth_headers, test_user):+ fake = AsyncMock()+ fake.get_quote = AsyncMock(+ return_value=MarketSymbolQuote(symbol="AAPL", currency="USD", price=190.5)+ )+ with patch("app.api.assets.get_market_price_provider", return_value=fake):+ resp = await client.get("/api/assets/market/quote?symbol=AAPL", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ assert resp.json()["price"] == 190.5+++async def test_market_quote_not_found_404(client: AsyncClient, auth_headers, test_user):+ fake = AsyncMock()+ fake.get_quote = AsyncMock(return_value=None)+ with patch("app.api.assets.get_market_price_provider", return_value=fake):+ resp = await client.get("/api/assets/market/quote?symbol=NOPE", headers=auth_headers)+ assert resp.status_code == 404+++async def test_market_quote_rate_limited_429(client: AsyncClient, auth_headers, test_user):+ fake = AsyncMock()+ fake.get_quote = AsyncMock(side_effect=MarketPriceRateLimitedError("slow down"))+ with patch("app.api.assets.get_market_price_provider", return_value=fake):+ resp = await client.get("/api/assets/market/quote?symbol=AAPL", headers=auth_headers)+ assert resp.status_code == 429+++# ---------------------------------------------------------------------------+# refresh-price+# ---------------------------------------------------------------------------+async def test_refresh_price_asset_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.post(+ f"/api/assets/{uuid.uuid4()}/refresh-price", headers=auth_headers+ )+ assert resp.status_code == 404+++async def test_refresh_price_non_market_asset_422(client: AsyncClient, auth_headers, manual_asset):+ resp = await client.post(+ f"/api/assets/{manual_asset.id}/refresh-price", headers=auth_headers+ )+ assert resp.status_code == 422+++async def test_refresh_price_success(client: AsyncClient, auth_headers, market_asset):+ with patch(+ "app.services.asset_service.refresh_market_price_asset",+ new=AsyncMock(return_value=True),+ ):+ resp = await client.post(+ f"/api/assets/{market_asset.id}/refresh-price", headers=auth_headers+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["id"] == str(market_asset.id)+++async def test_refresh_price_provider_failure_502(client: AsyncClient, auth_headers, market_asset):+ with patch(+ "app.services.asset_service.refresh_market_price_asset",+ new=AsyncMock(return_value=False),+ ):+ resp = await client.post(+ f"/api/assets/{market_asset.id}/refresh-price", headers=auth_headers+ )+ assert resp.status_code == 502+++async def test_refresh_price_rate_limited_429(client: AsyncClient, auth_headers, market_asset):+ with patch(+ "app.services.asset_service.refresh_market_price_asset",+ new=AsyncMock(side_effect=MarketPriceRateLimitedError("slow down")),+ ):+ resp = await client.post(+ f"/api/assets/{market_asset.id}/refresh-price", headers=auth_headers+ )+ assert resp.status_code == 429+++# ---------------------------------------------------------------------------+# list / create / get / update / delete+# ---------------------------------------------------------------------------+async def test_list_assets_include_archived(client: AsyncClient, auth_headers, manual_asset):+ resp = await client.get("/api/assets?include_archived=true", headers=auth_headers)+ assert resp.status_code == 200+ assert any(a["id"] == str(manual_asset.id) for a in resp.json())+++async def test_create_then_update_then_delete_asset(client: AsyncClient, auth_headers, test_user):+ create = await client.post(+ "/api/assets",+ headers=auth_headers,+ json={"name": "Boat", "type": "other", "currency": "USD", "current_value": 5000},+ )+ assert create.status_code == 201, create.text+ asset_id = create.json()["id"]++ upd = await client.patch(+ f"/api/assets/{asset_id}",+ headers=auth_headers,+ json={"name": "Yacht", "is_archived": True},+ )+ assert upd.status_code == 200+ assert upd.json()["name"] == "Yacht"++ delete = await client.delete(f"/api/assets/{asset_id}", headers=auth_headers)+ assert delete.status_code == 204+++async def test_get_asset_success(client: AsyncClient, auth_headers, manual_asset):+ resp = await client.get(f"/api/assets/{manual_asset.id}", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ assert resp.json()["name"] == "Cov House"+++async def test_get_asset_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(f"/api/assets/{uuid.uuid4()}", headers=auth_headers)+ assert resp.status_code == 404+++async def test_refresh_price_fx_conversion(client: AsyncClient, auth_headers, market_asset, session):+ # Seed a USD value so the refreshed asset has a current_value the+ # endpoint converts into the BRL primary currency (FX branch).+ session.add(+ AssetValue(+ id=uuid.uuid4(),+ asset_id=market_asset.id,+ amount=Decimal("1905.00"),+ date=date(2026, 1, 1),+ source="market",+ )+ )+ await session.commit()+ with patch(+ "app.services.asset_service.refresh_market_price_asset",+ new=AsyncMock(return_value=True),+ ):+ resp = await client.post(+ f"/api/assets/{market_asset.id}/refresh-price", headers=auth_headers+ )+ assert resp.status_code == 200, resp.text+++async def test_update_asset_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.patch(+ f"/api/assets/{uuid.uuid4()}", headers=auth_headers, json={"name": "X"}+ )+ assert resp.status_code == 404+++async def test_delete_asset_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.delete(f"/api/assets/{uuid.uuid4()}", headers=auth_headers)+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# values + trends+# ---------------------------------------------------------------------------+async def test_list_values_unknown_asset_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(f"/api/assets/{uuid.uuid4()}/values", headers=auth_headers)+ assert resp.status_code == 404+++async def test_add_value_unknown_asset_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.post(+ f"/api/assets/{uuid.uuid4()}/values",+ headers=auth_headers,+ json={"amount": 100, "date": "2026-01-01"},+ )+ assert resp.status_code == 404+++async def test_value_trend_unknown_asset_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(+ f"/api/assets/{uuid.uuid4()}/value-trend?months=6", headers=auth_headers+ )+ assert resp.status_code == 404+++async def test_delete_value_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.delete(f"/api/assets/values/{uuid.uuid4()}", headers=auth_headers)+ assert resp.status_code == 404+++async def test_portfolio_trend(client: AsyncClient, auth_headers, manual_asset):+ resp = await client.get("/api/assets/portfolio-trend", headers=auth_headers)+ assert resp.status_code == 200+++async def test_add_value_then_value_trend(client: AsyncClient, auth_headers, manual_asset):+ add = await client.post(+ f"/api/assets/{manual_asset.id}/values",+ headers=auth_headers,+ json={"amount": 130000, "date": "2026-02-01"},+ )+ assert add.status_code == 201, add.text++ trend = await client.get(+ f"/api/assets/{manual_asset.id}/value-trend", headers=auth_headers+ )+ assert trend.status_code == 200+ assert isinstance(trend.json(), list)diff --git a/backend/tests/test_connection_service_coverage.py b/backend/tests/test_connection_service_coverage.pynew file mode 100644index 00000000..1c502e0f--- /dev/null+++ b/backend/tests/test_connection_service_coverage.py@@ -0,0 +1,557 @@+"""Coverage-focused tests for app/services/connection_service.py.++Targets branches not exercised by test_connection_service.py:+- get_oauth_url / get_reauth_url (state storage + provider delegation)+- list_provider_institutions (normalization)+- _sync_holdings (create / archive / withdrawn paths)+- sync_connection: trigger_refresh outcomes, fuzzy-match merge, SessionExpired+ and ProviderUserActionRequired error handling, status reset on generic error+- handle_oauth_callback: reconnect path + invalid-state guards+"""+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal+from unittest.mock import AsyncMock, patch++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset import Asset+from app.models.bank_connection import BankConnection+from app.models.transaction import Transaction+from app.providers.base import (+ AccountData,+ ConnectionData,+ HoldingData,+ InstitutionData,+ InstitutionListData,+ ProviderUserActionRequired,+ SessionExpiredError,+ TransactionData,+)+from app.services.connection_service import (+ _sync_holdings,+ get_oauth_url,+ get_reauth_url,+ handle_oauth_callback,+ list_provider_institutions,+ sync_connection,+)+++async def _make_connection(+ session: AsyncSession, user_id, name="Bank", settings=None,+) -> BankConnection:+ conn = BankConnection(+ id=uuid.uuid4(), user_id=user_id, provider="test",+ external_id=f"ext-{uuid.uuid4().hex[:8]}",+ institution_name=name, credentials={"token": "fake"},+ status="active", settings=settings,+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(conn)+ await session.commit()+ await session.refresh(conn)+ return conn+++def _patch_helpers():+ return (+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock),+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock),+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock),+ )+++# ---------------------------------------------------------------------------+# get_oauth_url / get_reauth_url+# ---------------------------------------------------------------------------+++async def test_get_oauth_url(test_user, test_workspace):+ mock_provider = AsyncMock()+ mock_provider.redirect_uri = "https://app/redirect"+ mock_provider.get_oauth_url = AsyncMock(return_value="https://bank/authorize?state=xyz")+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ patch("app.services.connection_service.oauth_state.store_state",+ new_callable=AsyncMock, return_value="state-token"):+ url = await get_oauth_url("pluggy", test_user.id, test_workspace.id, {"country": "BR"})+ assert url == "https://bank/authorize?state=xyz"+ mock_provider.get_oauth_url.assert_awaited_once()+++async def test_get_reauth_url(session: AsyncSession, test_user, test_workspace):+ conn = await _make_connection(session, test_user.id, settings={"flow_params": {"country": "DE"}})+ mock_provider = AsyncMock()+ mock_provider.redirect_uri = "https://app/redirect"+ mock_provider.reauth_url = AsyncMock(return_value="https://bank/reauth")+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ patch("app.services.connection_service.oauth_state.store_state",+ new_callable=AsyncMock, return_value="state-token"):+ url = await get_reauth_url(session, conn.id, test_workspace.id, test_user.id)+ assert url == "https://bank/reauth"+++async def test_get_reauth_url_not_found(session: AsyncSession, test_user, test_workspace):+ with pytest.raises(ValueError, match="not found"):+ await get_reauth_url(session, uuid.uuid4(), test_workspace.id, test_user.id)+++# ---------------------------------------------------------------------------+# list_provider_institutions+# ---------------------------------------------------------------------------+++async def test_list_provider_institutions():+ mock_provider = AsyncMock()+ mock_provider.list_institutions = AsyncMock(return_value=InstitutionListData(+ countries=["DE", "FR"],+ institutions=[+ InstitutionData(+ name="revolut_de", display_name="Revolut", country="DE",+ logo="logo.png", bic="REVODEB2", psu_types=["personal"],+ max_consent_days=90, max_history_days=730,+ ),+ ],+ ))+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ result = await list_provider_institutions("enable_banking", "DE")+ assert result["countries"] == ["DE", "FR"]+ assert len(result["institutions"]) == 1+ inst = result["institutions"][0]+ assert inst["name"] == "revolut_de"+ assert inst["display_name"] == "Revolut"+ assert inst["bic"] == "REVODEB2"+++# ---------------------------------------------------------------------------+# _sync_holdings+# ---------------------------------------------------------------------------+++async def test_sync_holdings_creates_asset(session: AsyncSession, test_user):+ conn = await _make_connection(session, test_user.id, "Broker")+ mock_provider = AsyncMock()+ mock_provider.get_holdings = AsyncMock(return_value=[+ HoldingData(+ external_id="hold-1", name="VWCE ETF", currency="EUR",+ current_value=Decimal("1200.00"), quantity=Decimal("10"),+ purchase_price=Decimal("1000.00"), purchase_date=date(2026, 1, 1),+ ),+ ])+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "t"})+ await session.commit()++ asset = (await session.execute(+ select(Asset).where(Asset.external_id == "hold-1")+ )).scalar_one()+ assert asset.name == "VWCE ETF"+ assert asset.type == "investment"+ assert asset.connection_id == conn.id+++async def test_sync_holdings_provider_error_swallowed(session: AsyncSession, test_user):+ """A failing get_holdings must not raise — investment data is best-effort."""+ conn = await _make_connection(session, test_user.id, "FlakyBroker")+ mock_provider = AsyncMock()+ mock_provider.get_holdings = AsyncMock(side_effect=RuntimeError("500"))+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "t"}) # no raise+++async def test_sync_holdings_withdrawn_new_skipped(session: AsyncSession, test_user):+ """A brand-new holding reported as withdrawn is skipped entirely."""+ conn = await _make_connection(session, test_user.id, "ClosedBroker")+ mock_provider = AsyncMock()+ mock_provider.get_holdings = AsyncMock(return_value=[+ HoldingData(+ external_id="dead-1", name="Closed Fund", currency="BRL",+ current_value=Decimal("0"), is_withdrawn=True,+ ),+ ])+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "t"})+ await session.commit()+ rows = (await session.execute(+ select(Asset).where(Asset.external_id == "dead-1")+ )).scalars().all()+ assert rows == []+++async def test_sync_holdings_archives_disappeared(session: AsyncSession, test_user):+ """A previously synced asset no longer in the provider response is archived."""+ conn = await _make_connection(session, test_user.id, "GoneBroker")+ existing = Asset(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ source="test", external_id="gone-1", name="Old", type="investment",+ currency="BRL", is_archived=False, valuation_method="manual",+ )+ session.add(existing)+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings = AsyncMock(return_value=[]) # nothing returned+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "t"})+ await session.commit()++ await session.refresh(existing)+ assert existing.is_archived is True+++# ---------------------------------------------------------------------------+# sync_connection: trigger_refresh outcomes+# ---------------------------------------------------------------------------+++async def test_sync_trigger_refresh_needs_user_action(session: AsyncSession, test_user, test_workspace):+ conn = await _make_connection(session, test_user.id, "RefreshBank")+ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock_provider.trigger_refresh = AsyncMock(return_value="needs_user_action")++ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ with pytest.raises(RuntimeError, match="reconnect"):+ await sync_connection(+ session, conn.id, test_workspace.id, test_user.id,+ trigger_provider_refresh=True,+ )+ # status marked error and committed+ refreshed = (await session.execute(+ select(BankConnection).where(BankConnection.id == conn.id)+ )).scalar_one()+ assert refreshed.status == "error"+++async def test_sync_trigger_refresh_refreshed_then_reads(session: AsyncSession, test_user, test_workspace):+ conn = await _make_connection(session, test_user.id, "RefreshOK")+ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock_provider.trigger_refresh = AsyncMock(return_value="refreshed")+ mock_provider.get_accounts = AsyncMock(return_value=[+ AccountData(external_id="ra-1", name="Checking", type="checking",+ balance=Decimal("10"), currency="BRL"),+ ])+ mock_provider.get_transactions = AsyncMock(return_value=[])++ p1, p2, p3 = _patch_helpers()+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ p1, p2, p3:+ result, _ = await sync_connection(+ session, conn.id, test_workspace.id, test_user.id,+ trigger_provider_refresh=True,+ )+ assert result.status == "active"+ mock_provider.trigger_refresh.assert_awaited_once()+++# ---------------------------------------------------------------------------+# sync_connection: fuzzy match merges a manual transaction+# ---------------------------------------------------------------------------+++async def test_sync_fuzzy_matches_manual_transaction(session: AsyncSession, test_user, test_workspace):+ """A synced tx that fuzzy-matches an existing manual tx merges into it+ (incrementing merged_count) rather than inserting a duplicate."""+ conn = await _make_connection(session, test_user.id, "FuzzyBank")+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ external_id="fz-acc-1", name="Checking", type="checking",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(account)+ await session.flush()+ manual = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=account.id,+ description="STARBUCKS COFFEE", amount=Decimal("25.00"),+ date=date(2026, 4, 10), type="debit", source="manual",+ external_id=None, created_at=datetime.now(timezone.utc),+ )+ session.add(manual)+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock_provider.get_accounts = AsyncMock(return_value=[+ AccountData(external_id="fz-acc-1", name="Checking", type="checking",+ balance=Decimal("0"), currency="BRL"),+ ])+ mock_provider.get_transactions = AsyncMock(return_value=[+ TransactionData(+ external_id="fz-tx-1", description="STARBUCKS COFFEE",+ amount=Decimal("25.00"), date=date(2026, 4, 10),+ type="debit", currency="BRL", payee="Starbucks",+ ),+ ])++ p1, p2, p3 = _patch_helpers()+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ p1, p2, p3:+ result, merged = await sync_connection(session, conn.id, test_workspace.id, test_user.id)++ assert result.status == "active"+ assert merged == 1+ await session.refresh(manual)+ assert manual.external_id == "fz-tx-1"+ assert manual.source == "sync"+ assert manual.payee == "Starbucks"+++# ---------------------------------------------------------------------------+# sync_connection: SessionExpired / ProviderUserActionRequired+# ---------------------------------------------------------------------------+++async def test_sync_session_expired_marks_expired(session: AsyncSession, test_user, test_workspace):+ conn = await _make_connection(session, test_user.id, "ExpiredBank")+ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(side_effect=SessionExpiredError("gone"))++ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ with pytest.raises(SessionExpiredError):+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)++ refreshed = (await session.execute(+ select(BankConnection).where(BankConnection.id == conn.id)+ )).scalar_one()+ assert refreshed.status == "expired"+++async def test_sync_user_action_required_propagates_without_error_status(+ session: AsyncSession, test_user, test_workspace,+):+ conn = await _make_connection(session, test_user.id, "ActionBank")+ conn_id = conn.id+ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(+ side_effect=ProviderUserActionRequired("link accounts", code="restricted_mode")+ )++ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ with pytest.raises(ProviderUserActionRequired):+ await sync_connection(session, conn_id, test_workspace.id, test_user.id)++ # Connection status NOT flipped to error for this case.+ refreshed = (await session.execute(+ select(BankConnection).where(BankConnection.id == conn_id)+ )).scalar_one()+ assert refreshed.status == "active"+++# ---------------------------------------------------------------------------+# handle_oauth_callback: state guards + reconnect path+# ---------------------------------------------------------------------------+++async def test_oauth_callback_invalid_state(session: AsyncSession, test_user, test_workspace):+ with patch("app.services.connection_service.oauth_state.consume_state",+ new_callable=AsyncMock, return_value=None):+ with pytest.raises(ValueError, match="invalid or expired"):+ await handle_oauth_callback(+ session, test_workspace.id, test_user.id, "code", state="bad-state",+ )+++async def test_oauth_callback_state_user_mismatch(session: AsyncSession, test_user, test_workspace):+ with patch("app.services.connection_service.oauth_state.consume_state",+ new_callable=AsyncMock,+ return_value={"user_id": str(uuid.uuid4()),+ "workspace_id": str(test_workspace.id),+ "provider": "test"}):+ with pytest.raises(ValueError, match="user does not match"):+ await handle_oauth_callback(+ session, test_workspace.id, test_user.id, "code", state="s",+ )+++async def test_oauth_callback_missing_provider(session: AsyncSession, test_user, test_workspace):+ with pytest.raises(ValueError, match="missing provider"):+ await handle_oauth_callback(session, test_workspace.id, test_user.id, "code")+++async def test_oauth_callback_reconnect_updates_existing(+ session: AsyncSession, test_user, test_workspace,+):+ """A callback carrying reconnect_connection_id updates the existing row in+ place instead of creating a new connection."""+ existing = await _make_connection(session, test_user.id, "OldName")++ mock_provider = AsyncMock()+ mock_provider.handle_oauth_callback = AsyncMock(return_value=ConnectionData(+ external_id="reconnected-ext",+ institution_name="NewName",+ credentials={"token": "fresh"},+ accounts=[],+ ))++ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ patch("app.services.connection_service.oauth_state.consume_state",+ new_callable=AsyncMock,+ return_value={+ "user_id": str(test_user.id),+ "workspace_id": str(test_workspace.id),+ "provider": "test",+ "reconnect_connection_id": str(existing.id),+ }):+ result = await handle_oauth_callback(+ session, test_workspace.id, test_user.id, "code", state="s",+ )++ assert result.id == existing.id+ assert result.external_id == "reconnected-ext"+ assert result.institution_name == "NewName"+ assert result.credentials == {"token": "fresh"}+ assert result.status == "active"+ assert result.last_sync_at is None+++# ---------------------------------------------------------------------------+# sync_connection: existing-tx update (pending -> posted) + new insert + FX+# ---------------------------------------------------------------------------+++async def test_sync_updates_existing_pending_to_posted(+ session: AsyncSession, test_user, test_workspace,+):+ """An already-synced tx matched by external_id flips pending->posted."""+ conn = await _make_connection(session, test_user.id, "PendingPostedBank")+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ external_id="pp-acc-1", name="Checking", type="checking",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(account)+ await session.flush()+ session.add(Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=account.id,+ external_id="pp-tx-1", description="PENDING CHARGE",+ amount=Decimal("60"), date=date(2026, 4, 12), type="debit",+ currency="BRL", source="sync", status="pending",+ created_at=datetime.now(timezone.utc),+ ))+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock_provider.get_accounts = AsyncMock(return_value=[+ AccountData(external_id="pp-acc-1", name="Checking", type="checking",+ balance=Decimal("0"), currency="BRL"),+ ])+ mock_provider.get_transactions = AsyncMock(return_value=[+ TransactionData(+ external_id="pp-tx-1", description="PENDING CHARGE",+ amount=Decimal("60"), date=date(2026, 4, 12), type="debit",+ currency="BRL", status="posted",+ ),+ ])++ p1, p2, p3 = _patch_helpers()+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ p1, p2, p3:+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)++ row = (await session.execute(+ select(Transaction).where(Transaction.external_id == "pp-tx-1")+ )).scalar_one()+ assert row.status == "posted"+++async def test_sync_new_transaction_with_payee_and_fx(+ session: AsyncSession, test_user, test_workspace,+):+ """New synced tx with a payee and a bank-provided FX conversion exercises+ the payee resolution + amount_primary/fx_rate_used branch (no fallback+ stamp_primary_amount call)."""+ conn = await _make_connection(session, test_user.id, "FxBank")+ # User primary currency is BRL (from conftest). Account in BRL, tx in USD+ # with bank-provided BRL amount -> fx branch.+ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock_provider.get_accounts = AsyncMock(return_value=[+ AccountData(external_id="fx-acc-1", name="Checking", type="checking",+ balance=Decimal("0"), currency="BRL"),+ ])+ mock_provider.get_transactions = AsyncMock(return_value=[+ TransactionData(+ external_id="fx-tx-1", description="AWS USD",+ amount=Decimal("10.00"), date=date(2026, 4, 1), type="debit",+ currency="USD", amount_in_account_currency=Decimal("52.00"),+ payee="Amazon Web Services",+ ),+ ])++ # Don't patch stamp_primary_amount here — the fx branch must bypass it.+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)++ row = (await session.execute(+ select(Transaction).where(Transaction.external_id == "fx-tx-1")+ )).scalar_one()+ assert row.payee == "Amazon Web Services"+ assert row.payee_id is not None+ assert row.amount_primary == Decimal("52.00")+ assert row.fx_rate_used == Decimal("5.2")+++# ---------------------------------------------------------------------------+# _sync_holdings: update an existing asset in place+# ---------------------------------------------------------------------------+++async def test_sync_holdings_updates_existing_asset(session: AsyncSession, test_user):+ """A holding matching an existing asset by external_id updates it in place+ (name/currency/units) rather than creating a duplicate."""+ conn = await _make_connection(session, test_user.id, "UpdBroker")+ existing = Asset(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ source="test", external_id="upd-1", name="Old Name", type="investment",+ currency="USD", units=Decimal("5"), is_archived=False,+ valuation_method="manual",+ )+ session.add(existing)+ await session.commit()++ mock_provider = AsyncMock()+ mock_provider.get_holdings = AsyncMock(return_value=[+ HoldingData(+ external_id="upd-1", name="New Name", currency="EUR",+ current_value=Decimal("999.00"), quantity=Decimal("8"),+ ),+ ])+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):+ await _sync_holdings(session, test_user.id, conn, {"token": "t"})+ await session.commit()++ rows = (await session.execute(+ select(Asset).where(Asset.external_id == "upd-1")+ )).scalars().all()+ assert len(rows) == 1 # updated, not duplicated+ assert rows[0].name == "New Name"+ assert rows[0].currency == "EUR"+ assert rows[0].units == Decimal("8")diff --git a/backend/tests/test_dashboard_service_coverage.py b/backend/tests/test_dashboard_service_coverage.pynew file mode 100644index 00000000..cc9ea99e--- /dev/null+++ b/backend/tests/test_dashboard_service_coverage.py@@ -0,0 +1,481 @@+"""Coverage-focused tests for app.services.dashboard_service.++Targets the multi-currency conversion branches, recurring-projection+balance adjustments, group-split (owner offset + viewer shared) paths,+pending-shares-net aggregation, and the daily-deltas / balance-history+projection branches that the existing suite doesn't reach.+"""+import uuid+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.category import Category+from app.models.fx_rate import FxRate+from app.models.group import Group, GroupMember+from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction+from app.models.transaction_split import TransactionSplit+from app.services.dashboard_service import (+ _balance_at,+ _compute_pending_shares_net,+ _daily_deltas,+ get_balance_history,+ get_monthly_trend,+ get_projected_transactions,+ get_spending_by_category,+ get_summary,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++async def _seed_fx(session, today=None):+ """USD->BRL=5.0, USD->EUR=0.9, USD->USD=1.0."""+ today = today or date.today()+ for quote, rate in [("BRL", "5.0"), ("EUR", "0.9"), ("USD", "1.0")]:+ session.add(FxRate(base_currency="USD", quote_currency=quote, date=today,+ rate=Decimal(rate), source="test"))+ await session.commit()+++async def _make_account(session, user_id, workspace_id, *, currency="BRL",+ balance="0.00", connection_id=None, acc_type="checking",+ is_closed=False, name="Acc"):+ acc = Account(+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id, name=name,+ type=acc_type, balance=Decimal(balance), currency=currency,+ connection_id=connection_id, is_closed=is_closed,+ )+ session.add(acc)+ await session.commit()+ await session.refresh(acc)+ return acc+++async def _add_txn(session, user_id, account_id, workspace_id, amount, typ, dt,+ *, currency="BRL", source="manual", category_id=None,+ amount_primary=None, transfer_pair_id=None):+ txn = Transaction(+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,+ workspace_id=workspace_id, description="t", amount=Decimal(str(amount)),+ date=dt, type=typ, source=source, currency=currency,+ category_id=category_id,+ amount_primary=Decimal(str(amount_primary)) if amount_primary is not None else None,+ transfer_pair_id=transfer_pair_id,+ created_at=datetime.now(timezone.utc),+ )+ session.add(txn)+ await session.commit()+ await session.refresh(txn)+ return txn+++async def _make_category(session, user_id, workspace_id, name):+ cat = Category(+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,+ name=name, icon="tag", color="#000", is_system=False,+ )+ session.add(cat)+ await session.commit()+ await session.refresh(cat)+ return cat+++# ---------------------------------------------------------------------------+# Multi-currency total balance + asset add (lines 224, 228-230) and primary+# income/expenses via amount_primary (257-258)+# ---------------------------------------------------------------------------+++async def test_summary_multi_currency_and_primary_amounts(session: AsyncSession, test_user, test_workspace):+ today = date.today()+ await _seed_fx(session, today)+ brl = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ usd = await _make_account(session, test_user.id, test_workspace.id, currency="USD")++ # Opening balances in two currencies -> multi-currency total -> convert loop+ await _add_txn(session, test_user.id, brl.id, test_workspace.id, 1000, "credit", today, source="opening_balance")+ await _add_txn(session, test_user.id, usd.id, test_workspace.id, 200, "credit", today, source="opening_balance", currency="USD")++ # Income/expense rows carrying amount_primary -> primary_row branch (257-258)+ await _add_txn(session, test_user.id, usd.id, test_workspace.id, 300, "credit", today,+ currency="USD", amount_primary=1500)+ await _add_txn(session, test_user.id, usd.id, test_workspace.id, 100, "debit", today,+ currency="USD", amount_primary=500)++ summary = await get_summary(session, test_workspace.id, test_user.id, month=today.replace(day=1))+ assert summary.total_balance.get("BRL") == pytest.approx(1000.0)+ assert summary.total_balance.get("USD") is not None+ assert summary.total_balance_primary > 0+ # amount_primary based primary income/expenses+ assert summary.monthly_income_primary == pytest.approx(1500.0, abs=1.0)+ assert summary.monthly_expenses_primary == pytest.approx(500.0, abs=1.0)+++# ---------------------------------------------------------------------------+# Balance projection for current month with recurring projections (123-124)+# ---------------------------------------------------------------------------+++async def test_summary_balance_projection_with_recurring(session, test_user, test_workspace):+ today = date.today()+ month_start = today.replace(day=1)+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL", balance="0")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1000, "credit", month_start, source="opening_balance")++ # Recurring that produces occurrences later this month (after today) so the+ # projection adjusts total_balance (lines 117-124). Use daily frequency.+ rec = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ description="Daily", amount=Decimal("10"), type="debit",+ frequency="daily", currency="BRL",+ start_date=month_start, next_occurrence=month_start,+ )+ session.add(rec)+ await session.commit()++ # Use a balance_date in the past so month_end > cutoff -> projection path runs+ summary = await get_summary(+ session, test_workspace.id, test_user.id, month=month_start,+ balance_date=month_start,+ )+ assert summary is not None+ assert "BRL" in summary.total_balance+++# ---------------------------------------------------------------------------+# Group splits: owner offset + viewer shared (summary 313-325, spending 496-535)+# ---------------------------------------------------------------------------+++async def _make_group_with_members(session, owner_id, workspace_id, *, viewer_user_id=None):+ """Create a group owned by owner_id with a self member and one other.+ If viewer_user_id given, that other member is linked to viewer (invitee)."""+ group = Group(+ id=uuid.uuid4(), user_id=owner_id, workspace_id=workspace_id,+ name="Trip", default_currency="BRL",+ )+ session.add(group)+ await session.flush()+ self_m = GroupMember(+ id=uuid.uuid4(), group_id=group.id, workspace_id=workspace_id,+ name="Me", linked_user_id=owner_id, is_self=True,+ )+ other_m = GroupMember(+ id=uuid.uuid4(), group_id=group.id, workspace_id=workspace_id,+ name="Friend", linked_user_id=viewer_user_id, is_self=False,+ )+ session.add_all([self_m, other_m])+ await session.commit()+ await session.refresh(group)+ await session.refresh(self_m)+ await session.refresh(other_m)+ return group, self_m, other_m+++async def test_summary_owner_split_offset(session, test_user, test_workspace):+ today = date.today()+ month_start = today.replace(day=1)+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ cat = await _make_category(session, test_user.id, test_workspace.id, "Dining")++ group, self_m, other_m = await _make_group_with_members(+ session, test_user.id, test_workspace.id+ )++ # Owner paid a 100 debit, split 50/50 with the friend (non-owner share = 50)+ txn = await _add_txn(session, test_user.id, acc.id, test_workspace.id, 100, "debit", today, category_id=cat.id)+ for member, amt in [(self_m, "50.00"), (other_m, "50.00")]:+ session.add(TransactionSplit(+ id=uuid.uuid4(), transaction_id=txn.id, workspace_id=test_workspace.id,+ group_member_id=member.id, share_amount=Decimal(amt), share_type="exact",+ ))+ await session.commit()++ summary = await get_summary(session, test_workspace.id, test_user.id, month=month_start)+ # Only the owner's 50 share should count as expense, not the full 100+ assert summary.monthly_expenses == pytest.approx(50.0, abs=0.01)++ spending = await get_spending_by_category(session, test_workspace.id, test_user.id, month=month_start)+ dining = next((s for s in spending if s.category_name == "Dining"), None)+ assert dining is not None+ assert dining.total == pytest.approx(50.0, abs=0.01)+++async def test_summary_viewer_shared_split(session, test_user, test_workspace, clean_db):+ """Viewer participates (linked, non-self) in another user's split tx."""+ today = date.today()+ month_start = today.replace(day=1)++ # Create the OWNER user (different from viewer test_user) and their workspace+ import bcrypt as _bcrypt+ from app.models.user import User as UserModel+ from app.models.workspace import Workspace, WorkspaceMember++ owner = UserModel(+ id=uuid.uuid4(), email="[email protected]",+ hashed_password=_bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode(),+ is_active=True, is_verified=True,+ preferences={"currency_display": "BRL"},+ )+ session.add(owner)+ await session.flush()+ owner_ws = Workspace(+ id=uuid.uuid4(), name="OwnerWS", kind="personal",+ created_by_user_id=owner.id, default_currency="BRL", locale="en",+ )+ session.add(owner_ws)+ await session.flush()+ session.add(WorkspaceMember(id=uuid.uuid4(), workspace_id=owner_ws.id, user_id=owner.id, role="owner"))+ await session.commit()++ owner_acc = await _make_account(session, owner.id, owner_ws.id, currency="BRL")++ # Group owned by `owner`; viewer (test_user) is a linked, non-self member.+ group, self_m, viewer_m = await _make_group_with_members(+ session, owner.id, owner_ws.id, viewer_user_id=test_user.id+ )++ # Owner's debit tx split: viewer owes 40 of a 100 expense+ txn = await _add_txn(session, owner.id, owner_acc.id, owner_ws.id, 100, "debit", today)+ cat = await _make_category(session, owner.id, owner_ws.id, "Shared")+ txn.category_id = cat.id+ await session.commit()+ for member, amt in [(self_m, "60.00"), (viewer_m, "40.00")]:+ session.add(TransactionSplit(+ id=uuid.uuid4(), transaction_id=txn.id, workspace_id=owner_ws.id,+ group_member_id=member.id, share_amount=Decimal(amt), share_type="exact",+ ))+ await session.commit()++ # Viewer's summary should pick up their 40 shared expense (viewer_shared paths)+ summary = await get_summary(session, test_workspace.id, test_user.id, month=month_start)+ assert summary.monthly_expenses == pytest.approx(40.0, abs=0.01)++ spending = await get_spending_by_category(session, test_workspace.id, test_user.id, month=month_start)+ shared = next((s for s in spending if s.category_name == "Shared"), None)+ assert shared is not None+ assert shared.total == pytest.approx(40.0, abs=0.01)+++# ---------------------------------------------------------------------------+# _compute_pending_shares_net (406-426)+# ---------------------------------------------------------------------------+++async def test_pending_shares_net_owned_group(session, test_user, test_workspace):+ today = date.today()+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ group, self_m, other_m = await _make_group_with_members(+ session, test_user.id, test_workspace.id+ )+ # Owner paid 100, friend owes 50 -> friend's line is +50 (asset to owner)+ txn = await _add_txn(session, test_user.id, acc.id, test_workspace.id, 100, "debit", today)+ for member, amt in [(self_m, "50.00"), (other_m, "50.00")]:+ session.add(TransactionSplit(+ id=uuid.uuid4(), transaction_id=txn.id, workspace_id=test_workspace.id,+ group_member_id=member.id, share_amount=Decimal(amt), share_type="exact",+ ))+ await session.commit()++ net = await _compute_pending_shares_net(session, test_workspace.id, test_user.id, "BRL")+ # Friend owes the owner -> positive net+ assert net == pytest.approx(50.0, abs=0.5)+++async def test_pending_shares_net_no_groups(session, test_user, test_workspace):+ net = await _compute_pending_shares_net(session, test_workspace.id, test_user.id, "BRL")+ assert net == pytest.approx(0.0)+++# ---------------------------------------------------------------------------+# get_projected_transactions currency conversion (718-721)+# ---------------------------------------------------------------------------+++async def test_projected_transactions_currency_conversion(session, test_user, test_workspace):+ today = date.today()+ month_start = today.replace(day=1)+ await _seed_fx(session, today)++ # Recurring in USD; user primary is BRL -> amount_primary conversion branch+ rec = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ description="USD Sub", amount=Decimal("10"), type="debit",+ frequency="monthly", currency="USD",+ start_date=month_start, next_occurrence=month_start,+ )+ session.add(rec)+ await session.commit()++ projections = await get_projected_transactions(session, test_workspace.id, test_user.id, month=month_start)+ assert len(projections) >= 1+ assert projections[0].currency == "USD"+ assert projections[0].amount_primary is not None+ # USD 10 * 5.0 = BRL 50+ assert projections[0].amount_primary == pytest.approx(50.0, abs=1.0)+++# ---------------------------------------------------------------------------+# _daily_deltas multi-currency (914-925) + balance_history projection (979-985)+# ---------------------------------------------------------------------------+++async def test_daily_deltas_multi_currency(session, test_user, test_workspace):+ today = date.today()+ month_start = today.replace(day=1)+ month_end = (month_start + timedelta(days=40)).replace(day=1)+ await _seed_fx(session, today)++ brl = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ usd = await _make_account(session, test_user.id, test_workspace.id, currency="USD")+ await _add_txn(session, test_user.id, brl.id, test_workspace.id, 100, "credit", month_start)+ await _add_txn(session, test_user.id, usd.id, test_workspace.id, 20, "credit", month_start,+ currency="USD", amount_primary=100)++ deltas = await _daily_deltas(+ session, test_workspace.id, month_start, month_end,+ primary_currency_hint="BRL",+ )+ # Day 1 should aggregate both currencies converted to BRL+ assert deltas.get(1, 0) > 100.0+++async def test_balance_history_with_future_projections(session, test_user, test_workspace):+ today = date.today()+ month_start = today.replace(day=1)+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1000, "credit", month_start, source="opening_balance")++ # Daily recurring whose next occurrence is in the future -> future days+ # get projection deltas (lines 979-985). Skip on the last day of the month+ # when no future days remain.+ next_day = today + timedelta(days=1)+ if next_day.month != today.month:+ pytest.skip("no future days left in current month")+ rec = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ description="Daily", amount=Decimal("5"), type="credit",+ frequency="daily", currency="BRL",+ start_date=month_start, next_occurrence=next_day,+ )+ session.add(rec)+ await session.commit()++ history = await get_balance_history(session, test_workspace.id, test_user.id, month=month_start)+ assert len(history.current) > 0+ assert len(history.previous) > 0+++def test_signed_expr_helpers_smoke():+ """The signed-amount SQL expression helpers compile without a bound query.+ Covers the empty-currency branch of _signed_balance_expr and+ _signed_primary_expr (used elsewhere / kept for reuse)."""+ from app.services.dashboard_service import (+ _signed_balance_expr,+ _signed_primary_expr,+ _primary_amount_expr,+ )++ # Empty currency arg -> simple effective=amount branch+ expr_empty = _signed_balance_expr("")+ expr_cur = _signed_balance_expr("BRL")+ expr_primary = _signed_primary_expr()+ expr_amt = _primary_amount_expr()+ # They should be SQLAlchemy ColumnElements that render to SQL strings+ assert all(str(e) for e in (expr_empty, expr_cur, expr_primary, expr_amt))+++async def _register_sqlite_to_char(session):+ """Register a SQLite UDF emulating Postgres to_char(date, 'YYYY-MM').++ get_monthly_trend uses func.to_char which only exists on Postgres in+ production. To exercise that code path under the SQLite test backend+ we install a matching scalar function on the underlying connection.+ """+ def _to_char(value, fmt):+ if value is None:+ return None+ # value comes through as an ISO date/datetime string+ s = str(value)+ return s[:7] # 'YYYY-MM'++ raw = await session.connection()++ def _install(dbapi_conn):+ dbapi_conn.create_function("to_char", 2, _to_char)++ await raw.run_sync(lambda conn: _install(conn.connection.dbapi_connection))+++async def test_monthly_trend(session, test_user, test_workspace):+ await _register_sqlite_to_char(session)+ today = date.today()+ month_start = today.replace(day=1)+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 3000, "credit", month_start, amount_primary=3000)+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 500, "debit", month_start, amount_primary=500)++ trends = await get_monthly_trend(session, test_workspace.id, test_user.id, months=6)+ assert len(trends) >= 1+ current = next((t for t in trends if t.month == month_start.strftime("%Y-%m")), None)+ assert current is not None+ assert current.income >= 3000.0+ assert current.expenses >= 500.0+++async def test_summary_current_month_projection_adjusts_balance(session, test_user, test_workspace):+ """When viewing the current month with no balance_date, month_end > today+ so recurring projections from today+1..month_end adjust total_balance."""+ today = date.today()+ month_start = today.replace(day=1)+ # Only run when there's at least one future day in the month.+ if (month_start + timedelta(days=40)).replace(day=1) - timedelta(days=1) <= today:+ pytest.skip("no future days left in current month")++ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1000, "credit", month_start, source="opening_balance")+ rec = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ description="DailyProj", amount=Decimal("10"), type="credit",+ frequency="daily", currency="BRL",+ start_date=month_start, next_occurrence=today + timedelta(days=1),+ )+ session.add(rec)+ await session.commit()++ summary = await get_summary(session, test_workspace.id, test_user.id, month=month_start)+ # Projected credits should push the BRL balance above the 1000 opening balance+ assert summary.total_balance.get("BRL", 0) > 1000.0+++async def test_balance_at_multi_currency_conversion(session, test_user, test_workspace):+ today = date.today()+ await _seed_fx(session, today)+ brl = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ usd = await _make_account(session, test_user.id, test_workspace.id, currency="USD")+ await _add_txn(session, test_user.id, brl.id, test_workspace.id, 500, "credit", today)+ await _add_txn(session, test_user.id, usd.id, test_workspace.id, 100, "credit", today, currency="USD")++ total = await _balance_at(session, test_workspace.id, today, primary_currency_hint="BRL")+ # 500 BRL + (100 USD * 5.0 = 500 BRL) = 1000+ assert total == pytest.approx(1000.0, abs=5.0)diff --git a/backend/tests/test_goal_service_coverage.py b/backend/tests/test_goal_service_coverage.pynew file mode 100644index 00000000..40d88916--- /dev/null+++ b/backend/tests/test_goal_service_coverage.py@@ -0,0 +1,566 @@+"""Coverage-focused unit tests for app.services.goal_service.++Exercises the pure helpers directly (cheap branch coverage) plus the+service functions against the SQLite test DB (resolve current amount for+each tracking_type, enrich currency conversion, get/update/delete/summary).+"""+import uuid+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset import Asset+from app.models.asset_value import AssetValue+from app.models.fx_rate import FxRate+from app.models.goal import Goal+from app.models.transaction import Transaction+from app.schemas.goal import GoalCreate, GoalUpdate+from app.services.goal_service import (+ _compute_monthly_contribution,+ _compute_on_track,+ _compute_percentage,+ _enrich_goal,+ _resolve_current_amount,+ create_goal,+ delete_goal,+ get_goal,+ get_goals,+ get_goal_summary,+ update_goal,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++async def _make_account(+ session, user_id, workspace_id, *, balance="0.00", currency="BRL",+ connection_id=None, acc_type="checking",+):+ acc = Account(+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,+ name="Goal Acct", type=acc_type, balance=Decimal(balance),+ currency=currency, connection_id=connection_id,+ )+ session.add(acc)+ await session.commit()+ await session.refresh(acc)+ return acc+++async def _add_txn(session, user_id, account_id, workspace_id, amount, typ, dt, currency="BRL"):+ txn = Transaction(+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,+ workspace_id=workspace_id, description="t", amount=Decimal(str(amount)),+ date=dt, type=typ, source="manual", currency=currency,+ created_at=datetime.now(timezone.utc),+ )+ session.add(txn)+ await session.commit()+++async def _make_asset(session, user_id, workspace_id, *, currency="BRL", price="0.00"):+ asset = Asset(+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,+ name="Goal Asset", type="investment", currency=currency,+ purchase_price=Decimal(price),+ )+ session.add(asset)+ await session.commit()+ await session.refresh(asset)+ return asset+++async def _make_goal(session, user_id, workspace_id, **kwargs):+ defaults = dict(+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id,+ name="G", target_amount=Decimal("1000"), current_amount=Decimal("100"),+ initial_amount=Decimal("0"), currency="BRL", tracking_type="manual",+ status="active",+ )+ defaults.update(kwargs)+ goal = Goal(**defaults)+ session.add(goal)+ await session.commit()+ await session.refresh(goal)+ return goal+++# ---------------------------------------------------------------------------+# Pure helpers — _compute_percentage+# ---------------------------------------------------------------------------+++def test_compute_percentage_normal():+ assert _compute_percentage(Decimal("250"), Decimal("1000")) == 25.0+++def test_compute_percentage_zero_target_with_current():+ assert _compute_percentage(Decimal("5"), Decimal("0")) == 100.0+++def test_compute_percentage_zero_target_no_current():+ assert _compute_percentage(Decimal("0"), Decimal("0")) == 0.0+++def test_compute_percentage_negative_target():+ assert _compute_percentage(Decimal("0"), Decimal("-10")) == 0.0+++# ---------------------------------------------------------------------------+# Pure helpers — _compute_monthly_contribution+# ---------------------------------------------------------------------------+++def test_monthly_contribution_no_target_date():+ assert _compute_monthly_contribution(Decimal("0"), Decimal("1000"), None) is None+++def test_monthly_contribution_target_in_past():+ past = date.today() - timedelta(days=5)+ assert _compute_monthly_contribution(Decimal("0"), Decimal("1000"), past) == 0.0+++def test_monthly_contribution_already_reached():+ future = date.today() + timedelta(days=365)+ assert _compute_monthly_contribution(Decimal("2000"), Decimal("1000"), future) == 0.0+++def test_monthly_contribution_normal():+ future = date.today() + timedelta(days=365)+ val = _compute_monthly_contribution(Decimal("0"), Decimal("1200"), future)+ assert val is not None and val > 0+++def test_monthly_contribution_months_clamped_to_one():+ # Target date in the same calendar month but a later day -> months == 0,+ # clamped to 1 (line 111). today < target_date so we don't hit the past branch.+ today = date.today()+ if today.day < 28:+ target = today.replace(day=28)+ val = _compute_monthly_contribution(Decimal("0"), Decimal("500"), target)+ assert val == 500.0 # remaining / 1 month+ else:+ # Last days of month: just assert it returns a value (same-month edge)+ target = today + timedelta(days=1)+ if target.month == today.month:+ val = _compute_monthly_contribution(Decimal("0"), Decimal("500"), target)+ assert val == 500.0+ else:+ pytest.skip("month boundary makes same-month clamp untestable today")+++# ---------------------------------------------------------------------------+# Pure helpers — _compute_on_track+# ---------------------------------------------------------------------------+++def test_on_track_no_target_date():+ assert _compute_on_track(Decimal("0"), Decimal("1000"), None) is None+++def test_on_track_achieved():+ future = date.today() + timedelta(days=100)+ assert _compute_on_track(Decimal("1000"), Decimal("1000"), future) == "achieved"+++def test_on_track_overdue():+ past = date.today() - timedelta(days=10)+ assert _compute_on_track(Decimal("10"), Decimal("1000"), past) == "overdue"+++def test_on_track_total_days_zero_returns_on_track():+ # created today, target today -> total_days <= 0 branch+ today = date.today()+ assert _compute_on_track(Decimal("100"), Decimal("1000"), today, today) == "on_track"+++def test_on_track_total_needed_non_positive():+ # initial_amount >= target -> total_needed <= 0 -> achieved+ start = date.today() - timedelta(days=10)+ future = date.today() + timedelta(days=10)+ result = _compute_on_track(+ Decimal("500"), Decimal("1000"), future, start, initial_amount=Decimal("1000")+ )+ assert result == "achieved"+++def test_on_track_ahead():+ start = date.today() - timedelta(days=50)+ future = date.today() + timedelta(days=50)+ # Halfway in time but already saved everything -> ahead+ result = _compute_on_track(+ Decimal("1000"), Decimal("1000"), future, start, initial_amount=Decimal("0")+ )+ # current >= target short-circuits to achieved, so use just below target+ result = _compute_on_track(+ Decimal("990"), Decimal("1000"), future, start, initial_amount=Decimal("0")+ )+ assert result == "ahead"+++def test_on_track_on_track():+ start = date.today() - timedelta(days=50)+ future = date.today() + timedelta(days=50)+ # ~halfway, saved ~half -> on_track+ result = _compute_on_track(+ Decimal("500"), Decimal("1000"), future, start, initial_amount=Decimal("0")+ )+ assert result == "on_track"+++def test_on_track_behind():+ start = date.today() - timedelta(days=80)+ future = date.today() + timedelta(days=20)+ # 80% through time but saved almost nothing -> behind+ result = _compute_on_track(+ Decimal("10"), Decimal("1000"), future, start, initial_amount=Decimal("0")+ )+ assert result == "behind"+++def test_on_track_created_at_none_uses_today():+ future = date.today() + timedelta(days=30)+ # created_at None -> start = today -> total_days > 0 path with no progress yet+ result = _compute_on_track(Decimal("0"), Decimal("1000"), future, None)+ assert result in ("on_track", "behind", "ahead")+++# ---------------------------------------------------------------------------+# _resolve_current_amount — manual fallback+# ---------------------------------------------------------------------------+++async def test_resolve_manual(session: AsyncSession, test_user, test_workspace):+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="manual", current_amount=Decimal("777"),+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == Decimal("777")+++# ---------------------------------------------------------------------------+# _resolve_current_amount — account tracking+# ---------------------------------------------------------------------------+++async def test_resolve_account_same_currency(session, test_user, test_workspace):+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1500, "credit", date.today())+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="account", account_id=acc.id, currency="BRL",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == pytest.approx(Decimal("1500"))+++async def test_resolve_account_cross_currency(session, test_user, test_workspace):+ today = date.today()+ for quote, rate in [("BRL", "5.0"), ("EUR", "0.9")]:+ session.add(FxRate(base_currency="USD", quote_currency=quote, date=today,+ rate=Decimal(rate), source="test"))+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1500, "credit", today)+ await session.commit()+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="account", account_id=acc.id, currency="EUR",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ # BRL 1500 / 5.0 * 0.9 = EUR 270+ assert float(val) == pytest.approx(270.0, abs=1.0)+++async def test_resolve_account_missing_account_fallback(session, test_user, test_workspace):+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="account", account_id=uuid.uuid4(),+ current_amount=Decimal("42"),+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == Decimal("42")+++async def test_resolve_account_no_account_id_fallback(session, test_user, test_workspace):+ # tracking_type account but no account_id -> falls through to else+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="account", account_id=None, current_amount=Decimal("13"),+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == Decimal("13")+++# ---------------------------------------------------------------------------+# _resolve_current_amount — asset tracking+# ---------------------------------------------------------------------------+++async def test_resolve_asset_same_currency(session, test_user, test_workspace):+ asset = await _make_asset(session, test_user.id, test_workspace.id, currency="BRL", price="5000")+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="asset", asset_id=asset.id, currency="BRL",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == pytest.approx(Decimal("5000"))+++async def test_resolve_asset_cross_currency(session, test_user, test_workspace):+ today = date.today()+ session.add(FxRate(base_currency="USD", quote_currency="EUR", date=today,+ rate=Decimal("0.9"), source="test"))+ asset = await _make_asset(session, test_user.id, test_workspace.id, currency="USD", price="8000")+ await session.commit()+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="asset", asset_id=asset.id, currency="EUR",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ # USD 8000 * 0.9 = EUR 7200+ assert float(val) == pytest.approx(7200.0, abs=1.0)+++async def test_resolve_asset_with_asset_value(session, test_user, test_workspace):+ asset = await _make_asset(session, test_user.id, test_workspace.id, currency="BRL", price="100")+ session.add(AssetValue(+ id=uuid.uuid4(), asset_id=asset.id, workspace_id=test_workspace.id,+ amount=Decimal("9999"), date=date.today(), source="manual",+ ))+ await session.commit()+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="asset", asset_id=asset.id, currency="BRL",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == pytest.approx(Decimal("9999"))+++async def test_resolve_asset_missing_fallback(session, test_user, test_workspace):+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="asset", asset_id=uuid.uuid4(), current_amount=Decimal("55"),+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == Decimal("55")+++# ---------------------------------------------------------------------------+# _resolve_current_amount — net_worth+# ---------------------------------------------------------------------------+++async def test_resolve_net_worth_same_currency(session, test_user, test_workspace):+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 2000, "credit", date.today())+ asset = await _make_asset(session, test_user.id, test_workspace.id, currency="BRL", price="3000")+ session.add(AssetValue(+ id=uuid.uuid4(), asset_id=asset.id, workspace_id=test_workspace.id,+ amount=Decimal("3000"), date=date.today(), source="manual",+ ))+ await session.commit()+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="net_worth", currency="BRL",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ # 2000 account + 3000 asset+ assert float(val) == pytest.approx(5000.0, abs=1.0)+++async def test_resolve_net_worth_cross_currency(session, test_user, test_workspace):+ today = date.today()+ for quote, rate in [("BRL", "5.0"), ("USD", "1.0")]:+ session.add(FxRate(base_currency="USD", quote_currency=quote, date=today,+ rate=Decimal(rate), source="test"))+ # USD account + USD asset, goal in BRL -> conversion branch for both+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="USD")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 100, "credit", today, currency="USD")+ asset = await _make_asset(session, test_user.id, test_workspace.id, currency="USD", price="200")+ session.add(AssetValue(+ id=uuid.uuid4(), asset_id=asset.id, workspace_id=test_workspace.id,+ amount=Decimal("200"), date=today, source="manual",+ ))+ await session.commit()+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="net_worth", currency="BRL",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ # (100 + 200) USD * 5.0 = 1500 BRL+ assert float(val) == pytest.approx(1500.0, abs=5.0)+++# ---------------------------------------------------------------------------+# _enrich_goal — names + primary-currency conversion+# ---------------------------------------------------------------------------+++async def test_enrich_goal_account_and_asset_names(session, test_user, test_workspace):+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ asset = await _make_asset(session, test_user.id, test_workspace.id, currency="BRL", price="0")+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="manual", account_id=acc.id, asset_id=asset.id,+ )+ enriched = await _enrich_goal(session, goal, test_user.id)+ assert enriched.account_name is not None+ assert enriched.asset_name == "Goal Asset"+++async def test_enrich_goal_primary_currency_conversion(session, test_user, test_workspace):+ # test_user primary currency is BRL; make goal in USD to hit conversion branch+ today = date.today()+ session.add(FxRate(base_currency="USD", quote_currency="BRL", date=today,+ rate=Decimal("5.0"), source="test"))+ await session.commit()+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="manual", currency="USD",+ target_amount=Decimal("100"), current_amount=Decimal("50"),+ )+ enriched = await _enrich_goal(session, goal, test_user.id)+ assert enriched.target_amount_primary is not None+ assert enriched.current_amount_primary is not None+ assert float(enriched.target_amount_primary) == pytest.approx(500.0, abs=1.0)+++async def test_enrich_goal_same_currency_no_conversion(session, test_user, test_workspace):+ goal = await _make_goal(+ session, test_user.id, test_workspace.id, currency="BRL",+ )+ enriched = await _enrich_goal(session, goal, test_user.id)+ assert enriched.target_amount_primary is None+ assert enriched.current_amount_primary is None+++# ---------------------------------------------------------------------------+# get_goal / update_goal / delete_goal / get_goal_summary+# ---------------------------------------------------------------------------+++async def test_get_goal_found(session, test_user, test_workspace):+ goal = await _make_goal(session, test_user.id, test_workspace.id, name="Findable")+ result = await get_goal(session, goal.id, test_workspace.id, test_user.id)+ assert result is not None+ assert result.name == "Findable"+++async def test_get_goal_not_found(session, test_user, test_workspace):+ result = await get_goal(session, uuid.uuid4(), test_workspace.id, test_user.id)+ assert result is None+++async def test_update_goal_found(session, test_user, test_workspace):+ goal = await _make_goal(session, test_user.id, test_workspace.id, name="Old")+ result = await update_goal(+ session, goal.id, test_workspace.id, test_user.id,+ GoalUpdate(name="New", target_amount=Decimal("2000")),+ )+ assert result is not None+ assert result.name == "New"+ assert float(result.target_amount) == 2000.0+++async def test_update_goal_not_found(session, test_user, test_workspace):+ result = await update_goal(+ session, uuid.uuid4(), test_workspace.id, test_user.id,+ GoalUpdate(name="Nope"),+ )+ assert result is None+++async def test_delete_goal_found(session, test_user, test_workspace):+ goal = await _make_goal(session, test_user.id, test_workspace.id)+ ok = await delete_goal(session, goal.id, test_workspace.id)+ assert ok is True+ assert await get_goal(session, goal.id, test_workspace.id, test_user.id) is None+++async def test_delete_goal_not_found(session, test_user, test_workspace):+ ok = await delete_goal(session, uuid.uuid4(), test_workspace.id)+ assert ok is False+++async def test_get_goal_summary(session, test_user, test_workspace):+ for i in range(4):+ await _make_goal(+ session, test_user.id, test_workspace.id, name=f"S{i}",+ target_amount=Decimal("1000"), current_amount=Decimal("250"),+ position=i,+ )+ summaries = await get_goal_summary(session, test_workspace.id, test_user.id, limit=3)+ assert len(summaries) == 3+ for s in summaries:+ assert s.percentage == 25.0+++async def test_get_goals_and_status_filter(session, test_user, test_workspace):+ await _make_goal(session, test_user.id, test_workspace.id, name="ActiveG", status="active")+ await _make_goal(session, test_user.id, test_workspace.id, name="PausedG", status="paused")++ all_goals = await get_goals(session, test_workspace.id, test_user.id)+ names = {g.name for g in all_goals}+ assert {"ActiveG", "PausedG"} <= names++ active_only = await get_goals(session, test_workspace.id, test_user.id, status="active")+ active_names = {g.name for g in active_only}+ assert "ActiveG" in active_names+ assert "PausedG" not in active_names+++async def test_create_goal(session, test_user, test_workspace):+ result = await create_goal(+ session, test_workspace.id, test_user.id,+ GoalCreate(+ name="Created", target_amount=Decimal("1000"),+ current_amount=Decimal("200"), currency="BRL", tracking_type="manual",+ ),+ )+ assert result.name == "Created"+ assert result.percentage == 20.0+++async def test_get_goal_summary_with_target_date(session, test_user, test_workspace):+ future = date.today() + timedelta(days=365)+ await _make_goal(+ session, test_user.id, test_workspace.id, name="Dated",+ target_amount=Decimal("1200"), current_amount=Decimal("100"),+ target_date=future, status="active",+ )+ summaries = await get_goal_summary(session, test_workspace.id, test_user.id, limit=5)+ dated = next((s for s in summaries if s.name == "Dated"), None)+ assert dated is not None+ assert dated.monthly_contribution is not None+ assert dated.on_track is not Nonediff --git a/backend/tests/test_group_service_coverage.py b/backend/tests/test_group_service_coverage.pynew file mode 100644index 00000000..3ad649a0--- /dev/null+++ b/backend/tests/test_group_service_coverage.py@@ -0,0 +1,369 @@+"""Coverage-focused tests for group_service.++Targets update_group name-clash, delete IntegrityError translation,+update_member (email re-resolve + name clash + self promotion), delete_member,+get_group_visible cross-workspace projection, and list_transactions.+"""+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import bcrypt as _bcrypt+import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.models.transaction_split import TransactionSplit+from app.models.user import User+from app.schemas.group import (+ GroupCreate,+ GroupMemberCreate,+ GroupMemberUpdate,+ GroupUpdate,+)+from app.services import group_service, workspace_service+++async def _make_user_with_workspace(session, email):+ hashed = _bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode()+ user = User(+ id=uuid.uuid4(),+ email=email,+ hashed_password=hashed,+ is_active=True,+ is_verified=True,+ preferences={"currency_display": "USD"},+ )+ session.add(user)+ await session.flush()+ ws = await workspace_service.create_personal_workspace_for_user(+ session, user, commit=True+ )+ return user, ws+++async def test_update_group_name_clash(session: AsyncSession, test_user, test_workspace):+ await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Alpha")+ )+ g2 = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Beta")+ )+ with pytest.raises(ValueError, match="already exists"):+ await group_service.update_group(+ session, g2.id, test_workspace.id, test_user.id,+ GroupUpdate(name="Alpha"),+ )+++async def test_update_group_not_found(session: AsyncSession, test_user, test_workspace):+ result = await group_service.update_group(+ session, uuid.uuid4(), test_workspace.id, test_user.id,+ GroupUpdate(name="X"),+ )+ assert result is None+++async def test_delete_group_integrity_error_translated(session: AsyncSession, test_user, test_workspace, monkeypatch):+ """A FK RESTRICT violation (member with active splits) surfaces as a+ friendly ValueError. SQLite doesn't enforce RESTRICT under test, so we+ simulate the commit raising IntegrityError to cover the translation."""+ from sqlalchemy.exc import IntegrityError++ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="HasSplits")+ )++ async def _boom():+ raise IntegrityError("DELETE", {}, Exception("FK RESTRICT"))++ monkeypatch.setattr(session, "commit", _boom)++ with pytest.raises(ValueError, match="referenced by transaction splits"):+ await group_service.delete_group(session, group.id, test_workspace.id)+++async def test_delete_group_not_found(session: AsyncSession, test_user, test_workspace):+ assert await group_service.delete_group(session, uuid.uuid4(), test_workspace.id) is False+++async def test_update_member_resolves_email_link(session: AsyncSession, test_user, test_workspace):+ other, _ws = await _make_user_with_workspace(session, "[email protected]")+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )+ m = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Friend")+ )+ assert m.linked_user_id is None++ updated = await group_service.update_member(+ session, group.id, m.id, test_workspace.id,+ GroupMemberUpdate(email="[email protected]"),+ )+ assert updated is not None+ assert updated.linked_user_id == other.id+++async def test_update_member_name_clash(session: AsyncSession, test_user, test_workspace):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )+ await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")+ )+ bob = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Bob")+ )+ with pytest.raises(ValueError, match="already exists"):+ await group_service.update_member(+ session, group.id, bob.id, test_workspace.id,+ GroupMemberUpdate(name="Alice"),+ )+++async def test_update_member_group_not_found(session: AsyncSession, test_user, test_workspace):+ result = await group_service.update_member(+ session, uuid.uuid4(), uuid.uuid4(), test_workspace.id,+ GroupMemberUpdate(name="X"),+ )+ assert result is None+++async def test_update_member_member_not_found(session: AsyncSession, test_user, test_workspace):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )+ result = await group_service.update_member(+ session, group.id, uuid.uuid4(), test_workspace.id,+ GroupMemberUpdate(name="X"),+ )+ assert result is None+++async def test_delete_member(session: AsyncSession, test_user, test_workspace):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )+ m = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Temp")+ )+ assert await group_service.delete_member(session, group.id, m.id, test_workspace.id) is True+ # Now gone.+ assert await group_service.delete_member(session, group.id, m.id, test_workspace.id) is False+++async def test_delete_member_group_not_found(session: AsyncSession, test_user, test_workspace):+ assert await group_service.delete_member(+ session, uuid.uuid4(), uuid.uuid4(), test_workspace.id+ ) is False+++async def test_delete_member_integrity_error_translated(session: AsyncSession, test_user, test_workspace, monkeypatch):+ """FK RESTRICT on a member with active splits surfaces as a friendly+ ValueError. Simulated via a commit that raises IntegrityError because+ SQLite doesn't enforce RESTRICT under test."""+ from sqlalchemy.exc import IntegrityError++ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )+ member = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")+ )++ async def _boom():+ raise IntegrityError("DELETE", {}, Exception("FK RESTRICT"))++ monkeypatch.setattr(session, "commit", _boom)++ with pytest.raises(ValueError, match="referenced by transaction splits"):+ await group_service.delete_member(session, group.id, member.id, test_workspace.id)+++async def test_get_group_visible_cross_workspace(session: AsyncSession, test_user, test_workspace):+ """A user linked as a non-self member from another workspace sees the group."""+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Shared")+ )+ await group_service.create_member(+ session, group.id, test_workspace.id,+ GroupMemberCreate(name="Cross", linked_user_id=other.id),+ )++ # The cross-workspace user sees it through their own workspace scope.+ visible = await group_service.get_group_visible(+ session, group.id, other_ws.id, other.id+ )+ assert visible is not None+ assert visible.is_owner is False # type: ignore[attr-defined]++ # And via list_groups too.+ listed = await group_service.list_groups(session, other_ws.id, other.id)+ assert group.id in {g.id for g in listed}+++async def test_list_transactions(session: AsyncSession, test_user, test_workspace, test_account):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="WithTx")+ )+ member = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")+ )+ tx = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=test_account.id,+ description="Group dinner",+ amount=Decimal("40.00"),+ date=date.today(),+ type="debit",+ source="manual",+ created_at=datetime.now(timezone.utc),+ )+ session.add(tx)+ await session.flush()+ session.add(TransactionSplit(+ id=uuid.uuid4(),+ transaction_id=tx.id,+ workspace_id=test_workspace.id,+ group_member_id=member.id,+ share_type="equal",+ share_amount=Decimal("40.00"),+ ))+ await session.commit()++ txs = await group_service.list_transactions(+ session, group.id, test_workspace.id, test_user.id+ )+ assert txs is not None+ assert len(txs) == 1+ assert txs[0].description == "Group dinner"+ assert txs[0].attachment_count == 0+++async def test_list_transactions_group_not_visible(session: AsyncSession, test_user, test_workspace):+ result = await group_service.list_transactions(+ session, uuid.uuid4(), test_workspace.id, test_user.id+ )+ assert result is None+++async def test_create_group_duplicate_name_rejected(session: AsyncSession, test_user, test_workspace):+ await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Dup")+ )+ with pytest.raises(ValueError, match="already exists"):+ await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="dup")+ )+++async def test_update_group_changes_fields(session: AsyncSession, test_user, test_workspace):+ g = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Editable")+ )+ updated = await group_service.update_group(+ session, g.id, test_workspace.id, test_user.id,+ GroupUpdate(name="Renamed", notes="hi", color="#abcdef"),+ )+ assert updated is not None+ assert updated.name == "Renamed"+ assert updated.notes == "hi"+ assert updated.color == "#abcdef"+++async def test_delete_group_success(session: AsyncSession, test_user, test_workspace):+ g = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Gone")+ )+ assert await group_service.delete_group(session, g.id, test_workspace.id) is True+++async def test_list_members_group_not_visible(session: AsyncSession, test_user, test_workspace):+ assert await group_service.list_members(+ session, uuid.uuid4(), test_workspace.id, test_user.id+ ) is None+++async def test_create_member_group_not_found(session: AsyncSession, test_user, test_workspace):+ assert await group_service.create_member(+ session, uuid.uuid4(), test_workspace.id, GroupMemberCreate(name="X")+ ) is None+++async def test_create_member_name_clash(session: AsyncSession, test_user, test_workspace):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="ClashG")+ )+ await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")+ )+ with pytest.raises(ValueError, match="already exists"):+ await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="alice")+ )+++async def test_create_member_self_demotes_prior_self(session: AsyncSession, test_user, test_workspace):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="SelfDemote")+ )+ m1 = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="A", is_self=True)+ )+ m2 = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="B", is_self=True)+ )+ members = await group_service.list_members(+ session, group.id, test_workspace.id, test_user.id+ )+ by_id = {m.id: m for m in members}+ assert by_id[m1.id].is_self is False+ assert by_id[m2.id].is_self is True+++async def test_update_member_promote_self_demotes_existing(session: AsyncSession, test_user, test_workspace):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="SelfSwap")+ )+ m1 = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="A", is_self=True)+ )+ m2 = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="B")+ )+ await group_service.update_member(+ session, group.id, m2.id, test_workspace.id, GroupMemberUpdate(is_self=True)+ )+ members = await group_service.list_members(+ session, group.id, test_workspace.id, test_user.id+ )+ by_id = {m.id: m for m in members}+ assert by_id[m1.id].is_self is False+ assert by_id[m2.id].is_self is Truediff --git a/backend/tests/test_groups_api_coverage.py b/backend/tests/test_groups_api_coverage.pynew file mode 100644index 00000000..1e10e340--- /dev/null+++ b/backend/tests/test_groups_api_coverage.py@@ -0,0 +1,278 @@+"""Coverage-focused API tests for app/api/groups.py.++Complements test_groups_api.py: exercises update/delete, transactions,+member 404 branches, settlement update + 404s, and the various not-found+paths across the router.+"""+import uuid++import pytest+from httpx import AsyncClient+++async def _create_group(client: AsyncClient, auth_headers: dict, **overrides) -> dict:+ payload = {"name": "Cov Group", "kind": "social", "default_currency": "USD"}+ payload.update(overrides)+ resp = await client.post("/api/groups", headers=auth_headers, json=payload)+ assert resp.status_code == 201, resp.text+ return resp.json()+++async def _add_member(client, auth_headers, group_id, **fields) -> dict:+ payload = {"name": "Member"}+ payload.update(fields)+ resp = await client.post(+ f"/api/groups/{group_id}/members", headers=auth_headers, json=payload+ )+ assert resp.status_code == 201, resp.text+ return resp.json()+++# ---------------------------------------------------------------------------+# update / delete group+# ---------------------------------------------------------------------------+async def test_update_group(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="Before")+ resp = await client.patch(+ f"/api/groups/{group['id']}",+ headers=auth_headers,+ json={"name": "After", "color": "#FF0000", "notes": "hi"},+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["name"] == "After"+ assert body["color"] == "#FF0000"+ assert body["notes"] == "hi"+++async def test_update_group_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.patch(+ f"/api/groups/{uuid.uuid4()}", headers=auth_headers, json={"name": "X"}+ )+ assert resp.status_code == 404+++async def test_update_group_duplicate_name_400(client: AsyncClient, auth_headers, test_user):+ await _create_group(client, auth_headers, name="Taken")+ other = await _create_group(client, auth_headers, name="Other")+ resp = await client.patch(+ f"/api/groups/{other['id']}", headers=auth_headers, json={"name": "Taken"}+ )+ assert resp.status_code == 400+++async def test_delete_group(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="ToDelete")+ resp = await client.delete(f"/api/groups/{group['id']}", headers=auth_headers)+ assert resp.status_code == 204+ # Now gone.+ resp = await client.get(f"/api/groups/{group['id']}", headers=auth_headers)+ assert resp.status_code == 404+++async def test_delete_group_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.delete(f"/api/groups/{uuid.uuid4()}", headers=auth_headers)+ assert resp.status_code == 404+++async def test_get_group_not_found_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(f"/api/groups/{uuid.uuid4()}", headers=auth_headers)+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# members+# ---------------------------------------------------------------------------+async def test_list_members_unknown_group_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(f"/api/groups/{uuid.uuid4()}/members", headers=auth_headers)+ assert resp.status_code == 404+++async def test_create_member_unknown_group_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.post(+ f"/api/groups/{uuid.uuid4()}/members",+ headers=auth_headers,+ json={"name": "Ghost"},+ )+ assert resp.status_code == 404+++async def test_list_members_returns_added(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="HasMembers")+ await _add_member(client, auth_headers, group["id"], name="Bob")+ resp = await client.get(f"/api/groups/{group['id']}/members", headers=auth_headers)+ assert resp.status_code == 200+ assert any(m["name"] == "Bob" for m in resp.json())+++async def test_update_member_not_found_404(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="MemUpd")+ resp = await client.patch(+ f"/api/groups/{group['id']}/members/{uuid.uuid4()}",+ headers=auth_headers,+ json={"name": "Nope"},+ )+ assert resp.status_code == 404+++async def test_delete_member_not_found_404(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="MemDel")+ resp = await client.delete(+ f"/api/groups/{group['id']}/members/{uuid.uuid4()}", headers=auth_headers+ )+ assert resp.status_code == 404+++async def test_create_member_validation_422(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="MemVal")+ resp = await client.post(+ f"/api/groups/{group['id']}/members", headers=auth_headers, json={"name": ""}+ )+ assert resp.status_code == 422+++# ---------------------------------------------------------------------------+# transactions+# ---------------------------------------------------------------------------+async def test_group_transactions_empty(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="Txns")+ resp = await client.get(+ f"/api/groups/{group['id']}/transactions?limit=5", headers=auth_headers+ )+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_group_transactions_unknown_group_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(+ f"/api/groups/{uuid.uuid4()}/transactions", headers=auth_headers+ )+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# balances+# ---------------------------------------------------------------------------+async def test_balances_unknown_group_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(f"/api/groups/{uuid.uuid4()}/balances", headers=auth_headers)+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# settlements+# ---------------------------------------------------------------------------+async def test_settlements_unknown_group_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.get(+ f"/api/groups/{uuid.uuid4()}/settlements", headers=auth_headers+ )+ assert resp.status_code == 404+++async def test_settlement_full_lifecycle(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="SettCov")+ a = await _add_member(client, auth_headers, group["id"], name="A")+ b = await _add_member(client, auth_headers, group["id"], name="B")++ create = await client.post(+ f"/api/groups/{group['id']}/settlements",+ headers=auth_headers,+ json={+ "from_member_id": a["id"],+ "to_member_id": b["id"],+ "amount": "20.00",+ "currency": "USD",+ "date": "2026-05-01",+ },+ )+ assert create.status_code == 201, create.text+ settlement_id = create.json()["id"]++ upd = await client.patch(+ f"/api/groups/{group['id']}/settlements/{settlement_id}",+ headers=auth_headers,+ json={"amount": "25.00"},+ )+ assert upd.status_code == 200, upd.text+ assert float(upd.json()["amount"]) == 25.00++ listing = await client.get(+ f"/api/groups/{group['id']}/settlements", headers=auth_headers+ )+ assert listing.status_code == 200+ assert any(s["id"] == settlement_id for s in listing.json())++ delete = await client.delete(+ f"/api/groups/{group['id']}/settlements/{settlement_id}", headers=auth_headers+ )+ assert delete.status_code == 204+++async def test_create_settlement_unknown_member_400(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="SettBad")+ a = await _add_member(client, auth_headers, group["id"], name="A")+ resp = await client.post(+ f"/api/groups/{group['id']}/settlements",+ headers=auth_headers,+ json={+ "from_member_id": a["id"],+ "to_member_id": str(uuid.uuid4()),+ "amount": "10.00",+ "currency": "USD",+ "date": "2026-05-01",+ },+ )+ assert resp.status_code in (400, 404)+++async def test_update_settlement_not_found_404(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="SettUpd404")+ resp = await client.patch(+ f"/api/groups/{group['id']}/settlements/{uuid.uuid4()}",+ headers=auth_headers,+ json={"amount": "5.00"},+ )+ assert resp.status_code == 404+++async def test_delete_settlement_not_found_404(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="SettDel404")+ resp = await client.delete(+ f"/api/groups/{group['id']}/settlements/{uuid.uuid4()}", headers=auth_headers+ )+ assert resp.status_code == 404+++async def test_list_groups_include_archived(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="Archivable")+ # Archive via update.+ upd = await client.patch(+ f"/api/groups/{group['id']}", headers=auth_headers, json={"is_archived": True}+ )+ assert upd.status_code == 200+ # Not in default listing.+ default = await client.get("/api/groups", headers=auth_headers)+ assert not any(g["id"] == group["id"] for g in default.json())+ # Present with include_archived.+ archived = await client.get("/api/groups?include_archived=true", headers=auth_headers)+ assert any(g["id"] == group["id"] for g in archived.json())diff --git a/backend/tests/test_report_service_coverage.py b/backend/tests/test_report_service_coverage.pynew file mode 100644index 00000000..3e585361--- /dev/null+++ b/backend/tests/test_report_service_coverage.py@@ -0,0 +1,730 @@+"""Coverage-focused tests for app.services.report_service.++These exercise the large uncovered blocks: get_income_expenses_report+(lines 328-865), the cash-flow accrual / baseline / non-daily-interval+branches, and the net-worth credit-card / asset composition branches.++`get_income_expenses_report` builds its period buckets with PostgreSQL's+``to_char`` (and ``extract`` for weekly). Tests run on SQLite, so we register+a ``to_char`` user-defined function on the shared test engine for the+daily / monthly / yearly intervals (weekly relies on ``extract('isoyear')``+which SQLite cannot compile and is therefore not exercised here — its label+helper is covered by the existing pure-function tests).+"""+import uuid+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal++import pytest+from sqlalchemy import event+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset import Asset+from app.models.asset_value import AssetValue+from app.models.bank_connection import BankConnection+from app.models.category import Category+from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction+from app.models.user import User+from app.services.report_service import (+ _get_baseline_projection,+ _net_worth_at,+ get_cash_flow_report,+ get_income_expenses_report,+ get_net_worth_report,+)++from tests.conftest import engine as _test_engine+++# ---------------------------------------------------------------------------+# Register a `to_char` UDF on the SQLite test engine so the income/expenses+# report (which uses Postgres `to_char`) can run. Idempotent across tests.+# ---------------------------------------------------------------------------+++def _py_to_char(value, fmt):+ """Minimal emulation of PostgreSQL to_char(date, fmt) for the formats+ the report uses: 'YYYY-MM-DD', 'YYYY-MM', 'YYYY'."""+ if value is None:+ return None+ s = str(value)[:10] # 'YYYY-MM-DD'+ y, m, d = s.split("-")+ if fmt == "YYYY-MM-DD":+ return f"{y}-{m}-{d}"+ if fmt == "YYYY-MM":+ return f"{y}-{m}"+ if fmt == "YYYY":+ return y+ return s++[email protected]_for(_test_engine.sync_engine, "connect")+def _register_to_char(dbapi_connection, _connection_record):+ dbapi_connection.create_function("to_char", 2, _py_to_char)++[email protected](autouse=True)+async def _ensure_to_char(session: AsyncSession):+ """Make sure the UDF is registered on the live connection.++ The `connect` listener covers fresh connections; for the StaticPool's+ already-open connection we register directly via the raw DBAPI handle.+ """+ raw = await session.connection()++ def _do(sync_conn):+ dbapi = sync_conn.connection.dbapi_connection+ dbapi.create_function("to_char", 2, _py_to_char)++ await raw.run_sync(_do)+ yield+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++async def _make_account(+ session: AsyncSession, user_id: uuid.UUID, name: str,+ acc_type: str = "checking", balance: str = "0.00", currency: str = "BRL",+ connection_id: uuid.UUID | None = None, is_closed: bool = False,+) -> Account:+ acct = Account(+ id=uuid.uuid4(), user_id=user_id, name=name, type=acc_type,+ balance=Decimal(balance), currency=currency,+ connection_id=connection_id, is_closed=is_closed,+ )+ session.add(acct)+ await session.commit()+ await session.refresh(acct)+ return acct+++async def _add_txn(+ session: AsyncSession, user_id: uuid.UUID, account_id: uuid.UUID,+ amount: float, txn_type: str, txn_date: date, *,+ source: str = "manual", category_id: uuid.UUID | None = None,+ currency: str = "BRL", effective_date: date | None = None,+ workspace_id: uuid.UUID | None = None,+) -> Transaction:+ txn = Transaction(+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,+ category_id=category_id, description=f"Test {txn_type} {amount}",+ amount=Decimal(str(amount)), date=txn_date, type=txn_type,+ source=source, currency=currency,+ effective_date=effective_date or txn_date,+ created_at=datetime.now(timezone.utc),+ )+ if workspace_id is not None:+ txn.workspace_id = workspace_id+ session.add(txn)+ await session.commit()+ await session.refresh(txn)+ return txn+++async def _make_category(+ session: AsyncSession, user_id: uuid.UUID, name: str, color: str = "#123456",+) -> Category:+ cat = Category(+ id=uuid.uuid4(), user_id=user_id, name=name, icon="tag",+ color=color, is_system=False,+ )+ session.add(cat)+ await session.commit()+ await session.refresh(cat)+ return cat+++async def _make_recurring(+ session: AsyncSession, user_id: uuid.UUID, account_id: uuid.UUID,+ amount: float, txn_type: str, *, frequency: str = "monthly",+ next_occurrence: date | None = None, category_id: uuid.UUID | None = None,+ currency: str = "BRL",+) -> RecurringTransaction:+ today = date.today()+ rec = RecurringTransaction(+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,+ category_id=category_id, description=f"Rec {txn_type} {amount}",+ amount=Decimal(str(amount)), currency=currency, type=txn_type,+ frequency=frequency, start_date=today,+ next_occurrence=next_occurrence or (today + timedelta(days=2)),+ is_active=True,+ )+ session.add(rec)+ await session.commit()+ await session.refresh(rec)+ return rec+++# ---------------------------------------------------------------------------+# Sanity: the to_char UDF is wired up+# ---------------------------------------------------------------------------+++async def test_to_char_udf_registered(session: AsyncSession):+ from sqlalchemy import func, select+ from app.models.transaction import Transaction # noqa: F401++ res = await session.execute(select(func.to_char(date(2025, 6, 15), "YYYY-MM")))+ assert res.scalar_one() == "2025-06"+++# ---------------------------------------------------------------------------+# get_income_expenses_report — the big uncovered function (328-865)+# ---------------------------------------------------------------------------+++async def test_income_expenses_basic_structure(session, test_user, test_workspace):+ """Income + expense actuals flow through into summary, trend, composition."""+ cat_food = await _make_category(session, test_user.id, "Food", color="#F00")+ cat_salary = await _make_category(session, test_user.id, "Salary", color="#0F0")+ acct = await _make_account(session, test_user.id, "IE Acct")+ today = date.today()++ await _add_txn(session, test_user.id, acct.id, 5000, "credit", today, category_id=cat_salary.id)+ await _add_txn(session, test_user.id, acct.id, 1200, "debit", today, category_id=cat_food.id)+ await _add_txn(session, test_user.id, acct.id, 300, "debit", today) # uncategorized+ # opening balance must be excluded+ await _add_txn(session, test_user.id, acct.id, 99999, "credit", today, source="opening_balance")++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=3, interval="monthly"+ )++ assert report.meta.type == "income_expenses"+ assert report.meta.series_keys == ["income", "expenses"]+ assert report.meta.currency == "BRL"+ assert report.meta.interval == "monthly"++ bd = {b.key: b.value for b in report.summary.breakdowns}+ assert bd["income"] == pytest.approx(5000.0)+ assert bd["expenses"] == pytest.approx(1500.0)+ assert bd["netIncome"] == pytest.approx(3500.0)++ # Composition contains the two named categories + uncategorized+ labels = {c.label for c in report.composition}+ assert "Salary" in labels+ assert "Food" in labels+ assert "Uncategorized" in labels++ # Each trend point has income/expenses breakdowns+ for dp in report.trend:+ assert "income" in dp.breakdowns+ assert "expenses" in dp.breakdowns++ # Category trend present with proper grouping+ groups = {ct.group for ct in report.category_trend}+ assert "expenses" in groups+ assert "income" in groups+ for ct in report.category_trend:+ assert len(ct.series) == len(report.trend)+++async def test_income_expenses_empty_data(session, test_user, test_workspace):+ """No transactions → zeroed summary, empty composition / category trend."""+ report = await get_income_expenses_report(+ session, 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["netIncome"] == 0.0+ assert report.summary.change_percent is None # previous net == 0+ assert report.composition == []+ assert report.category_trend == []+ assert len(report.trend) > 0+++async def test_income_expenses_daily_interval(session, test_user, test_workspace):+ """Daily interval exercises the YYYY-MM-DD to_char path."""+ acct = await _make_account(session, test_user.id, "IE Daily")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 400, "debit", today)++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=1, interval="daily"+ )+ assert report.meta.interval == "daily"+ bd = {b.key: b.value for b in report.summary.breakdowns}+ assert bd["expenses"] == pytest.approx(400.0)+++async def test_income_expenses_yearly_interval(session, test_user, test_workspace):+ """Yearly interval exercises the YYYY to_char path."""+ acct = await _make_account(session, test_user.id, "IE Yearly")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 2000, "credit", today)++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=6, interval="yearly"+ )+ assert report.meta.interval == "yearly"+ bd = {b.key: b.value for b in report.summary.breakdowns}+ assert 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."""+ 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)++ 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")++ report = await get_income_expenses_report(+ session, 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+++async def test_income_expenses_with_recurring_projection(session, test_user, test_workspace):+ """Recurring projections are layered into income / expenses + composition."""+ cat = await _make_category(session, test_user.id, "Rent", color="#00F")+ acct = await _make_account(session, test_user.id, "IE Rec")+ today = date.today()+ month_start = today.replace(day=1)+ # Recurring projections are layered per-month over the [start, today]+ # window. Anchor occurrences at the 1st of the current month so they+ # land inside that window regardless of what day "today" is.+ await _make_recurring(+ session, test_user.id, acct.id, 800, "debit",+ frequency="monthly", next_occurrence=month_start,+ category_id=cat.id,+ )+ await _make_recurring(+ session, test_user.id, acct.id, 1500, "credit",+ frequency="monthly", next_occurrence=month_start,+ )++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=2, interval="monthly"+ )+ bd = {b.key: b.value for b in report.summary.breakdowns}+ assert bd["expenses"] >= 800.0+ assert bd["income"] >= 1500.0++ labels = {c.label for c in report.composition}+ assert "Rent" in labels+++async def test_income_expenses_many_categories_triggers_other_bucket(session, test_user, test_workspace):+ """More than CATEGORY_TREND_TOP_N expense categories → an 'Other' bucket."""+ acct = await _make_account(session, test_user.id, "IE Many")+ today = date.today()+ # 14 distinct expense categories (> top-N of 11)+ for i in range(14):+ cat = await _make_category(session, test_user.id, f"Cat{i}", color="#aabbcc")+ await _add_txn(+ session, test_user.id, acct.id, 100 + i, "debit", today, category_id=cat.id+ )++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=1, interval="monthly"+ )+ expense_items = [ct for ct in report.category_trend if ct.group == "expenses"]+ keys = {ct.key for ct in expense_items}+ assert "other" in keys+ other = next(ct for ct in expense_items if ct.key == "other")+ assert other.label == "Other"+ assert other.total > 0+++async def test_income_expenses_change_percent_computed(session, test_user, test_workspace):+ """A non-zero net in the first period yields a numeric change_percent."""+ acct = await _make_account(session, test_user.id, "IE Change")+ today = date.today()+ # Transaction ~2 months ago and one today so trend has >1 point with nets+ two_months_ago = (today.replace(day=1) - timedelta(days=40)).replace(day=10)+ await _add_txn(session, test_user.id, acct.id, 1000, "credit", two_months_ago)+ await _add_txn(session, test_user.id, acct.id, 3000, "credit", today)++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=4, interval="monthly"+ )+ # change_percent may be None only if the first trend net is 0 — assert the+ # field is the right type either way and totals are correct.+ bd = {b.key: b.value for b in report.summary.breakdowns}+ assert bd["income"] == pytest.approx(4000.0)+++# ---------------------------------------------------------------------------+# get_net_worth_report — credit-card composition + asset-value branches+# ---------------------------------------------------------------------------+++async def test_net_worth_composition_includes_credit_card_liability(session, test_user, test_workspace):+ """A credit-card account surfaces as a liabilities-group composition item."""+ conn = BankConnection(+ id=uuid.uuid4(), user_id=test_user.id, provider="test",+ external_id="ext-nw-cc", institution_name="CC Bank",+ credentials={}, status="active",+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(conn)+ await session.flush()+ cc = Account(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ name="My Card", type="credit_card", balance=Decimal("1500"), currency="BRL",+ )+ session.add(cc)+ await session.commit()++ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id, months=1, interval="monthly"+ )+ liab = [c for c in report.composition if c.group == "liabilities"]+ assert any(c.label == "My Card" for c in liab)+++async def test_net_worth_composition_asset_uses_asset_value_entry(session, test_user, test_workspace):+ """Asset with an AssetValue row is valued via the latest entry."""+ asset = Asset(+ id=uuid.uuid4(), user_id=test_user.id, name="Loft",+ type="real_estate", currency="BRL",+ )+ session.add(asset)+ await session.flush()+ session.add(AssetValue(+ id=uuid.uuid4(), asset_id=asset.id,+ amount=Decimal("250000"), date=date.today(),+ ))+ await session.commit()++ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id, months=1, interval="monthly"+ )+ asset_items = [c for c in report.composition if c.group == "assets"]+ loft = next((c for c in asset_items if c.label == "Loft"), None)+ assert loft is not None+ assert loft.value == pytest.approx(250000.0)+++async def test_net_worth_at_credit_card_branch(session, test_user, test_workspace):+ """_net_worth_at puts credit-card balances into liabilities."""+ conn = BankConnection(+ id=uuid.uuid4(), user_id=test_user.id, provider="test",+ external_id="ext-nwat-cc", institution_name="CC",+ credentials={}, status="active",+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(conn)+ await session.flush()+ cc = Account(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ name="CC", type="credit_card", balance=Decimal("700"), currency="BRL",+ )+ session.add(cc)+ await session.commit()++ dp = await _net_worth_at(session, test_workspace.id, date.today(), "BRL")+ assert dp.breakdowns["liabilities"] == pytest.approx(700.0)+++# ---------------------------------------------------------------------------+# get_cash_flow_report — non-daily interval aggregation (1261-1294)+# ---------------------------------------------------------------------------+++async def test_cash_flow_monthly_interval_aggregation(session, test_user, test_workspace):+ """Monthly interval groups daily balances into period buckets."""+ acct = await _make_account(session, test_user.id, "CF Monthly")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 5000, "credit", today, source="opening_balance")+ await _make_recurring(+ session, test_user.id, acct.id, 400, "debit",+ frequency="monthly", next_occurrence=today + timedelta(days=2),+ )++ report = await get_cash_flow_report(+ session, test_workspace.id, test_user.id, months=3, interval="monthly"+ )+ assert report.meta.interval == "monthly"+ assert len(report.trend) > 0+ for dp in report.trend:+ assert "inflow" in dp.breakdowns+ assert "outflow" in dp.breakdowns+++async def test_cash_flow_weekly_interval_aggregation(session, test_user, test_workspace):+ """Weekly interval also goes through the grouped (non-daily) path."""+ acct = await _make_account(session, test_user.id, "CF Weekly")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 1000, "credit", today, source="opening_balance")+ await _make_recurring(+ session, test_user.id, acct.id, 50, "debit",+ frequency="weekly", next_occurrence=today + timedelta(days=1),+ )++ report = await get_cash_flow_report(+ session, test_workspace.id, test_user.id, months=2, interval="weekly"+ )+ assert report.meta.interval == "weekly"+ assert len(report.trend) > 0+++# ---------------------------------------------------------------------------+# get_cash_flow_report — baseline projection branch (_get_baseline_projection)+# ---------------------------------------------------------------------------+++async def test_cash_flow_baseline_mode_projects_from_history(session, test_user, test_workspace):+ """baseline=True replaces recurring rules with a historical-mean estimate."""+ acct = await _make_account(session, test_user.id, "CF Baseline")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 3000, "credit", today, source="opening_balance")+ # Past actual flows feed the baseline window+ await _add_txn(session, test_user.id, acct.id, 6000, "credit", today - timedelta(days=20))+ await _add_txn(session, test_user.id, acct.id, 2000, "debit", today - timedelta(days=15))++ report = await get_cash_flow_report(+ session, test_workspace.id, test_user.id, months=3, interval="daily", baseline=True+ )+ assert report.meta.baseline_active is True+ assert report.meta.baseline_lookback_days is not None+ assert report.meta.baseline_lookback_days > 0+ # Baseline composition uses a synthetic "baseline" category key+ keys = {c.key for c in report.composition}+ assert "baseline" in keys+++async def test_baseline_projection_no_history_returns_empty(session, test_user, test_workspace):+ """No qualifying transactions → empty projection, zero lookback days."""+ async def _to_primary(amount, ccy):+ return float(amount)++ today = date.today()+ end = today + timedelta(days=30)+ projections, lookback = await _get_baseline_projection(+ session, test_workspace.id, today, end, "BRL", _to_primary,+ )+ assert projections == []+ assert lookback == 0+++async def test_baseline_projection_with_history(session, test_user, test_workspace):+ """With history, projection emits forward synthetic flows."""+ acct = await _make_account(session, test_user.id, "Baseline Hist")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 3000, "credit", today - timedelta(days=10))+ await _add_txn(session, test_user.id, acct.id, 900, "debit", today - timedelta(days=5))++ async def _to_primary(amount, ccy):+ return float(amount)++ end = today + timedelta(days=5)+ projections, lookback = await _get_baseline_projection(+ session, test_workspace.id, today, end, "BRL", _to_primary,+ )+ assert lookback > 0+ assert len(projections) > 0+ types = {p["type"] for p in projections}+ assert "credit" in types+ assert "debit" in types+ for p in projections:+ assert today < p["date"] <= end+ assert p["currency"] == "BRL"+++# ---------------------------------------------------------------------------+# get_cash_flow_report — accrual mode (pending CC purchases branch 1122-1152)+# ---------------------------------------------------------------------------+++async def test_income_expenses_owner_split_offset(session, test_user, test_workspace):+ """A split debit owned by the user has the non-owner share subtracted from+ expenses (owner_offset + per-category offset branches)."""+ from app.models.group import Group, GroupMember+ from app.models.transaction_split import TransactionSplit++ cat = await _make_category(session, test_user.id, "Dinner", color="#abc")+ acct = await _make_account(session, test_user.id, "IE Split")+ today = date.today()++ group = Group(+ id=uuid.uuid4(), user_id=test_user.id, name="Trip",+ kind="shared", default_currency="BRL",+ )+ session.add(group)+ await session.flush()+ # The owner's own self-member, and a friend (non-owner) member.+ self_member = GroupMember(+ id=uuid.uuid4(), group_id=group.id, name="Me",+ linked_user_id=test_user.id, is_self=True,+ )+ friend = GroupMember(+ id=uuid.uuid4(), group_id=group.id, name="Friend", is_self=False,+ )+ session.add_all([self_member, friend])+ await session.flush()++ # User pays a 1000 dinner; friend owes 400 of it.+ txn = await _add_txn(session, test_user.id, acct.id, 1000, "debit", today, category_id=cat.id)+ session.add(TransactionSplit(+ id=uuid.uuid4(), transaction_id=txn.id, group_member_id=friend.id,+ share_amount=Decimal("400"), share_type="amount",+ ))+ await session.commit()++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=2, interval="monthly"+ )+ bd = {b.key: b.value for b in report.summary.breakdowns}+ # Owner's share of the dinner is 1000 - 400 = 600.+ assert bd["expenses"] == pytest.approx(600.0)++ dinner = next((c for c in report.composition if c.label == "Dinner"), None)+ assert dinner is not None+ assert dinner.value == pytest.approx(600.0)+++async def test_net_worth_composition_positive_checking_in_accounts_group(session, test_user, test_workspace):+ """A manual checking account with positive balance lands in the accounts group."""+ acct = await _make_account(session, test_user.id, "NW Pos Checking")+ await _add_txn(session, test_user.id, acct.id, 4200, "credit", date.today(), source="opening_balance")++ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id, months=1, interval="monthly"+ )+ accts = [c for c in report.composition if c.group == "accounts"]+ item = next((c for c in accts if c.label == "NW Pos Checking"), None)+ assert item is not None+ assert item.value == pytest.approx(4200.0)+++async def test_net_worth_composition_asset_purchase_price_fallback(session, test_user, test_workspace):+ """Asset with no AssetValue rows falls back to purchase_price in composition."""+ asset = Asset(+ id=uuid.uuid4(), user_id=test_user.id, name="Old Car",+ type="vehicle", currency="BRL", purchase_price=Decimal("18000"),+ purchase_date=date.today() - timedelta(days=100),+ )+ session.add(asset)+ await session.commit()++ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id, months=1, interval="monthly"+ )+ asset_items = [c for c in report.composition if c.group == "assets"]+ car = next((c for c in asset_items if c.label == "Old Car"), None)+ assert car is not None+ assert car.value == pytest.approx(18000.0)+++async def test_net_worth_composition_asset_zero_value_excluded(session, test_user, test_workspace):+ """Asset with no value entry and future purchase date contributes nothing."""+ asset = Asset(+ id=uuid.uuid4(), user_id=test_user.id, name="Future Buy",+ type="other", currency="BRL", purchase_price=Decimal("5000"),+ purchase_date=date.today() + timedelta(days=60),+ )+ session.add(asset)+ await session.commit()++ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id, months=1, interval="monthly"+ )+ assert all(c.label != "Future Buy" for c in report.composition)+++async def test_cash_flow_foreign_currency_conversion_path(session, test_user, test_workspace):+ """A non-primary-currency transaction exercises the _to_primary rate path."""+ acct = await _make_account(session, test_user.id, "CF USD", currency="USD")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 1000, "credit", today,+ source="opening_balance", currency="USD")+ # Past actual flow in USD → hits _to_primary with a non-BRL currency+ await _add_txn(session, test_user.id, acct.id, 200, "debit",+ today - timedelta(days=5), currency="USD")++ report = await get_cash_flow_report(+ session, test_workspace.id, test_user.id, months=2, interval="daily"+ )+ assert report.meta.type == "cash_flow"+ assert len(report.trend) > 0+++async def test_cash_flow_categorized_recurring_composition(session, test_user, test_workspace):+ """Categorized recurring projection populates the per-category cache + composition."""+ cat = await _make_category(session, test_user.id, "Utilities", color="#777")+ acct = await _make_account(session, test_user.id, "CF Cat")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 2000, "credit", today, source="opening_balance")+ await _make_recurring(+ session, test_user.id, acct.id, 150, "debit",+ frequency="monthly", next_occurrence=today + timedelta(days=2),+ category_id=cat.id,+ )++ report = await get_cash_flow_report(+ session, test_workspace.id, test_user.id, months=3, interval="daily"+ )+ util = next((c for c in report.composition if c.label == "Utilities"), None)+ assert util is not None+ assert util.group == "expenses"+ assert util.value > 0+++async def test_cash_flow_baseline_amount_primary_used(session, test_user, test_workspace):+ """Baseline projection uses amount_primary when present on the transaction."""+ acct = await _make_account(session, test_user.id, "CF Baseline AP", currency="USD")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 500, "credit", today,+ source="opening_balance", currency="USD")+ # Give the historical txn an explicit amount_primary+ txn = await _add_txn(session, test_user.id, acct.id, 100, "debit",+ today - timedelta(days=8), currency="USD")+ txn.amount_primary = Decimal("550")+ await session.commit()++ report = await get_cash_flow_report(+ session, test_workspace.id, test_user.id, months=2, interval="daily", baseline=True+ )+ assert report.meta.baseline_active is True+ assert report.meta.baseline_lookback_days > 0+++async def test_cash_flow_accrual_mode_pending_cc(session, test_user, test_workspace):+ """Accrual mode re-projects pending CC purchases on their effective_date."""+ from app.models.app_settings import AppSetting++ # Switch global accounting mode to accrual+ session.add(AppSetting(key="credit_card_accounting_mode", value="accrual"))+ await session.commit()++ conn = BankConnection(+ id=uuid.uuid4(), user_id=test_user.id, provider="test",+ external_id="ext-cf-accrual", institution_name="CC",+ credentials={}, status="active",+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(conn)+ await session.flush()+ cc = Account(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ name="CC Accrual", type="credit_card", balance=Decimal("0"), currency="BRL",+ )+ session.add(cc)+ await session.commit()++ today = date.today()+ # Purchase booked today, cash impact (effective_date) in the future window+ await _add_txn(+ session, test_user.id, cc.id, 500, "debit", today,+ effective_date=today + timedelta(days=15),+ )++ report = await get_cash_flow_report(+ session, test_workspace.id, test_user.id, months=2, interval="daily"+ )+ assert report.meta.type == "cash_flow"+ assert len(report.trend) > 0diff --git a/backend/tests/test_settlement_service_coverage.py b/backend/tests/test_settlement_service_coverage.pynew file mode 100644index 00000000..c00ff5ad--- /dev/null+++ b/backend/tests/test_settlement_service_coverage.py@@ -0,0 +1,430 @@+"""Coverage-focused tests for settlement_service.++Targets _validate_transaction (valid + missing), list_settlements,+account_id + transaction_id conflict, linking an existing transaction,+update_settlement (not found / permission / member+transaction revalidation),+and delete_settlement (success / not found / permission).+"""+import uuid+from datetime import date+from decimal import Decimal++import bcrypt as _bcrypt+import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.models.user import User+from app.schemas.group import GroupCreate, GroupMemberCreate+from app.schemas.group_settlement import (+ GroupSettlementCreate,+ GroupSettlementUpdate,+)+from app.services import group_service, settlement_service, workspace_service+++async def _setup_group(session, user_id, workspace_id):+ group = await group_service.create_group(+ session, workspace_id, user_id, GroupCreate(name=f"S-{uuid.uuid4().hex[:6]}")+ )+ a = await group_service.create_member(+ session, group.id, workspace_id, GroupMemberCreate(name="Alice", is_self=True)+ )+ b = await group_service.create_member(+ session, group.id, workspace_id, GroupMemberCreate(name="Bob")+ )+ c = await group_service.create_member(+ session, group.id, workspace_id, GroupMemberCreate(name="Carol")+ )+ return group, a, b, c+++async def _make_account(session, user_id, workspace_id):+ account = Account(+ id=uuid.uuid4(),+ user_id=user_id,+ workspace_id=workspace_id,+ name=f"Acc-{uuid.uuid4().hex[:4]}",+ type="checking",+ balance=Decimal("0"),+ currency="USD",+ )+ session.add(account)+ await session.flush()+ return account+++async def _make_transaction(session, user_id, workspace_id, account_id):+ tx = Transaction(+ id=uuid.uuid4(),+ user_id=user_id,+ workspace_id=workspace_id,+ account_id=account_id,+ description="Existing",+ amount=Decimal("5.00"),+ currency="USD",+ date=date.today(),+ type="debit",+ source="manual",+ )+ session.add(tx)+ await session.flush()+ return tx+++async def test_list_settlements(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("10.00"), currency="USD", date=date.today(),+ ),+ )+ listed = await settlement_service.list_settlements(+ session, group.id, test_workspace.id, test_user.id+ )+ assert listed is not None+ assert len(listed) == 1+++async def test_list_settlements_group_not_visible(session: AsyncSession, test_user, test_workspace):+ result = await settlement_service.list_settlements(+ session, uuid.uuid4(), test_workspace.id, test_user.id+ )+ assert result is None+++async def test_create_settlement_links_existing_transaction(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ account = await _make_account(session, test_user.id, test_workspace.id)+ tx = await _make_transaction(session, test_user.id, test_workspace.id, account.id)++ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("5.00"), currency="USD", date=date.today(),+ transaction_id=tx.id,+ ),+ )+ assert s is not None+ assert s.transaction_id == tx.id+++async def test_create_settlement_invalid_transaction(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ with pytest.raises(ValueError, match="Linked transaction not found"):+ await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("5.00"), currency="USD", date=date.today(),+ transaction_id=uuid.uuid4(),+ ),+ )+++async def test_create_settlement_account_and_transaction_conflict(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ account = await _make_account(session, test_user.id, test_workspace.id)+ tx = await _make_transaction(session, test_user.id, test_workspace.id, account.id)++ with pytest.raises(ValueError, match="either account_id"):+ await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("5.00"), currency="USD", date=date.today(),+ account_id=account.id, transaction_id=tx.id,+ ),+ )+++async def test_create_settlement_bad_account(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ with pytest.raises(ValueError, match="Account not found"):+ await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("5.00"), currency="USD", date=date.today(),+ account_id=uuid.uuid4(),+ ),+ )+++async def test_create_settlement_with_account_creates_payment_tx(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ account = await _make_account(session, test_user.id, test_workspace.id)++ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("25.00"), currency="USD", date=date.today(),+ account_id=account.id, description="Custom desc",+ ),+ )+ assert s is not None+ assert s.transaction_id is not None+ tx = await session.get(Transaction, s.transaction_id)+ assert tx is not None+ assert tx.type == "debit"+ assert tx.source == "settlement"+ assert tx.amount == Decimal("25.00")+ assert tx.description == "Custom desc"+++async def test_create_settlement_receiver_self_member_owner_fallback(session: AsyncSession, test_user, test_workspace):+ """to_member is the owner's self-member with no linked user -> receiver+ credit falls back to group.user_id and lands on the owner's account."""+ owner_account = await _make_account(session, test_user.id, test_workspace.id)+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="SelfRx")+ )+ owner_self = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Me", is_self=True)+ )+ friend = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Friend")+ )+ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=friend.id, to_member_id=owner_self.id,+ amount=Decimal("8.00"), currency="USD", date=date.today(),+ ),+ )+ assert s is not None+ assert s.receiver_transaction_id is not None+ rx = await session.get(Transaction, s.receiver_transaction_id)+ assert rx.account_id == owner_account.id+ assert rx.type == "credit"+++async def test_create_settlement_group_not_visible(session: AsyncSession, test_user, test_workspace):+ """A different workspace can't see the group -> create returns None."""+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ result = await settlement_service.create_settlement(+ session, group.id, uuid.uuid4(), test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("1.00"), currency="USD", date=date.today(),+ ),+ )+ assert result is None+++async def test_update_settlement_change_only_from_member(session: AsyncSession, test_user, test_workspace):+ """Changing only from_member_id triggers the single-member validation+ branch (covers the member_check append for from)."""+ group, a, b, c = await _setup_group(session, test_user.id, test_workspace.id)+ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("10.00"), currency="USD", date=date.today(),+ ),+ )+ updated = await settlement_service.update_settlement(+ session, group.id, s.id, test_workspace.id, test_user.id,+ GroupSettlementUpdate(from_member_id=c.id),+ )+ assert updated is not None+ assert updated.from_member_id == c.id+++async def test_update_settlement_not_found(session: AsyncSession, test_user, test_workspace):+ group, _a, _b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ result = await settlement_service.update_settlement(+ session, group.id, uuid.uuid4(), test_workspace.id, test_user.id,+ GroupSettlementUpdate(amount=Decimal("1.00")),+ )+ assert result is None+++async def test_update_settlement_group_not_visible(session: AsyncSession, test_user, test_workspace):+ result = await settlement_service.update_settlement(+ session, uuid.uuid4(), uuid.uuid4(), test_workspace.id, test_user.id,+ GroupSettlementUpdate(amount=Decimal("1.00")),+ )+ assert result is None+++async def test_update_settlement_revalidates_members_and_transaction(session: AsyncSession, test_user, test_workspace):+ group, a, b, c = await _setup_group(session, test_user.id, test_workspace.id)+ account = await _make_account(session, test_user.id, test_workspace.id)+ tx = await _make_transaction(session, test_user.id, test_workspace.id, account.id)++ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("10.00"), currency="USD", date=date.today(),+ ),+ )+ # Change to_member to Carol and link the transaction.+ updated = await settlement_service.update_settlement(+ session, group.id, s.id, test_workspace.id, test_user.id,+ GroupSettlementUpdate(to_member_id=c.id, transaction_id=tx.id),+ )+ assert updated is not None+ assert updated.to_member_id == c.id+ assert updated.transaction_id == tx.id+++async def test_update_settlement_invalid_member(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("10.00"), currency="USD", date=date.today(),+ ),+ )+ with pytest.raises(ValueError, match="must belong to the group"):+ await settlement_service.update_settlement(+ session, group.id, s.id, test_workspace.id, test_user.id,+ GroupSettlementUpdate(to_member_id=uuid.uuid4()),+ )+++async def test_delete_settlement(session: AsyncSession, test_user, test_workspace):+ group, a, b, _c = await _setup_group(session, test_user.id, test_workspace.id)+ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("10.00"), currency="USD", date=date.today(),+ ),+ )+ assert await settlement_service.delete_settlement(+ session, group.id, s.id, test_workspace.id, test_user.id+ ) is True+ # Now gone.+ assert await settlement_service.delete_settlement(+ session, group.id, s.id, test_workspace.id, test_user.id+ ) is False+++async def test_delete_settlement_group_not_visible(session: AsyncSession, test_user, test_workspace):+ assert await settlement_service.delete_settlement(+ session, uuid.uuid4(), uuid.uuid4(), test_workspace.id, test_user.id+ ) is False+++async def test_settlement_permission_for_linked_member(session: AsyncSession, test_user, test_workspace):+ """A linked non-owner member may only settle when they are the payer."""+ hashed = _bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode()+ payer_user = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=hashed,+ is_active=True,+ is_verified=True,+ preferences={"currency_display": "USD"},+ )+ session.add(payer_user)+ await session.flush()+ payer_ws = await workspace_service.create_personal_workspace_for_user(+ session, payer_user, commit=True+ )++ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Perm")+ )+ me = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Me", is_self=True)+ )+ payer = await group_service.create_member(+ session, group.id, test_workspace.id,+ GroupMemberCreate(name="Payer", linked_user_id=payer_user.id),+ )++ # The linked payer can record a payment where they are the from_member.+ s = await settlement_service.create_settlement(+ session, group.id, payer_ws.id, payer_user.id,+ GroupSettlementCreate(+ from_member_id=payer.id, to_member_id=me.id,+ amount=Decimal("3.00"), currency="USD", date=date.today(),+ ),+ )+ assert s is not None++ # But NOT one where someone else is the from_member.+ with pytest.raises(PermissionError, match="you are the payer"):+ await settlement_service.create_settlement(+ session, group.id, payer_ws.id, payer_user.id,+ GroupSettlementCreate(+ from_member_id=me.id, to_member_id=payer.id,+ amount=Decimal("3.00"), currency="USD", date=date.today(),+ ),+ )+++async def test_update_settlement_permission_denied(session: AsyncSession, test_user, test_workspace):+ """A linked member can't edit a settlement they don't own."""+ hashed = _bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode()+ intruder = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=hashed,+ is_active=True,+ is_verified=True,+ preferences={"currency_display": "USD"},+ )+ session.add(intruder)+ await session.flush()+ intruder_ws = await workspace_service.create_personal_workspace_for_user(+ session, intruder, commit=True+ )++ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Owned")+ )+ a = await group_service.create_member(+ session, group.id, test_workspace.id, GroupMemberCreate(name="Owner", is_self=True)+ )+ b = await group_service.create_member(+ session, group.id, test_workspace.id,+ GroupMemberCreate(name="Intruder", linked_user_id=intruder.id),+ )+ # Owner creates a settlement from a -> b.+ s = await settlement_service.create_settlement(+ session, group.id, test_workspace.id, test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id, to_member_id=b.id,+ amount=Decimal("10.00"), currency="USD", date=date.today(),+ ),+ )+ # Intruder (linked to b, not the from_member) can't edit it.+ with pytest.raises(PermissionError, match="settlements you created"):+ await settlement_service.update_settlement(+ session, group.id, s.id, intruder_ws.id, intruder.id,+ GroupSettlementUpdate(amount=Decimal("99.00")),+ )+ # Nor delete it.+ with pytest.raises(PermissionError, match="settlements you created"):+ await settlement_service.delete_settlement(+ session, group.id, s.id, intruder_ws.id, intruder.id+ )diff --git a/backend/tests/test_transaction_service_coverage.py b/backend/tests/test_transaction_service_coverage.pynew file mode 100644index 00000000..b357012e--- /dev/null+++ b/backend/tests/test_transaction_service_coverage.py@@ -0,0 +1,912 @@+"""Additional coverage for app.services.transaction_service.++Targets the previously-uncovered branches: group-scope visibility, filtered+summary, sorting, transfer candidates / linking / counterparts, FX cascade in+updates, splits in create/update, bulk add-to-group, bill-link re-sync, and+assorted edge branches. See test_transaction_service.py for the baseline.+"""++import uuid+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal++import pytest+import pytest_asyncio+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.category import Category+from app.models.credit_card_bill import CreditCardBill+from app.models.group import Group, GroupMember+from app.models.transaction import Transaction+from app.schemas.transaction import (+ TransactionCreate,+ TransactionUpdate,+ TransferCreate,+)+from app.schemas.transaction_split import (+ TransactionSplitInput,+ TransactionSplitsInput,+)+from app.services.transaction_service import (+ bulk_add_tags,+ bulk_add_to_group,+ bulk_remove_tags,+ create_transaction,+ create_transfer,+ create_transfer_counterpart,+ get_transaction,+ get_transactions,+ get_transfer_candidates,+ link_existing_as_transfer,+ update_transaction,+)+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++@pytest_asyncio.fixture+async def acct(session: AsyncSession, test_user) -> Account:+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="CovAcc",+ type="checking",+ balance=Decimal("10000"),+ currency="BRL",+ )+ session.add(account)+ await session.commit()+ await session.refresh(account)+ return account+++@pytest_asyncio.fixture+async def acct_usd(session: AsyncSession, test_user) -> Account:+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="CovUSD",+ type="checking",+ balance=Decimal("5000"),+ currency="USD",+ )+ session.add(account)+ await session.commit()+ await session.refresh(account)+ return account+++@pytest_asyncio.fixture+async def cc_account(session: AsyncSession, test_user) -> Account:+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="CovCard",+ type="credit_card",+ balance=Decimal("0"),+ currency="BRL",+ statement_close_day=10,+ payment_due_day=20,+ )+ session.add(account)+ await session.commit()+ await session.refresh(account)+ return account+++async def _mk_txn(session, test_user, account, **kw) -> Transaction:+ defaults = dict(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=account.id,+ description="T",+ amount=Decimal("10"),+ date=date(2025, 3, 1),+ type="debit",+ source="manual",+ created_at=datetime.now(timezone.utc),+ )+ defaults.update(kw)+ txn = Transaction(**defaults)+ session.add(txn)+ await session.commit()+ await session.refresh(txn)+ return txn+++async def _mk_group(session, test_user, test_workspace, with_self=True, n_members=2):+ group = Group(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name=f"G-{uuid.uuid4().hex[:6]}",+ default_currency="BRL",+ )+ session.add(group)+ await session.flush()+ members = []+ if with_self:+ self_m = GroupMember(+ id=uuid.uuid4(),+ group_id=group.id,+ workspace_id=test_workspace.id,+ name="Me",+ linked_user_id=test_user.id,+ is_self=True,+ )+ session.add(self_m)+ members.append(self_m)+ for i in range(n_members):+ m = GroupMember(+ id=uuid.uuid4(),+ group_id=group.id,+ workspace_id=test_workspace.id,+ name=f"Member{i}",+ )+ session.add(m)+ members.append(m)+ await session.commit()+ for m in members:+ await session.refresh(m)+ await session.refresh(group)+ return group, members+++# ---------------------------------------------------------------------------+# get_transactions — filters, summary, sorting, multi-id (lines 144, 209, 365+)+# ---------------------------------------------------------------------------+++async def test_get_transactions_filter_by_transaction_ids(session, test_user, test_workspace, acct):+ t1 = await _mk_txn(session, test_user, acct, description="Keep")+ await _mk_txn(session, test_user, acct, description="Drop")+ res, total, _ = await get_transactions(+ session, test_workspace.id, test_user.id, transaction_ids=[t1.id]+ )+ assert {t.description for t in res} == {"Keep"}+ assert total == 1+++async def test_get_transactions_filter_by_payee_id(session, test_user, test_workspace, acct):+ from app.models.payee import Payee++ payee = Payee(id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id, name="Acme")+ session.add(payee)+ await session.commit()+ await _mk_txn(session, test_user, acct, description="WithPayee", payee_id=payee.id)+ await _mk_txn(session, test_user, acct, description="NoPayee")+ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, payee_id=payee.id+ )+ assert {t.description for t in res} == {"WithPayee"}+++async def test_get_transactions_filter_by_currency_and_amount(session, test_user, test_workspace, acct):+ await _mk_txn(session, test_user, acct, description="Small", amount=Decimal("5"), currency="BRL")+ await _mk_txn(session, test_user, acct, description="Big", amount=Decimal("500"), currency="BRL")+ await _mk_txn(session, test_user, acct, description="UsdOne", amount=Decimal("50"), currency="USD")++ res, _, _ = await get_transactions(session, test_workspace.id, test_user.id, currency="usd")+ assert {t.description for t in res} == {"UsdOne"}++ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, min_amount=10, max_amount=100+ )+ assert {t.description for t in res} == {"UsdOne"}+++async def test_get_transactions_filter_by_account_types_and_ids(session, test_user, test_workspace, acct, acct_usd):+ await _mk_txn(session, test_user, acct, description="Checking")+ sav = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="Sav", type="savings",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(sav)+ await session.commit()+ await _mk_txn(session, test_user, sav, description="Saving")++ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, account_types=["savings"]+ )+ assert {t.description for t in res} == {"Saving"}++ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, account_ids=[acct.id, sav.id]+ )+ assert {t.description for t in res} == {"Checking", "Saving"}++ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, category_ids=[uuid.uuid4()]+ )+ assert res == []+++async def test_get_transactions_include_summary(session, test_user, test_workspace, acct):+ await _mk_txn(session, test_user, acct, description="Inc", amount=Decimal("1000"), type="credit")+ await _mk_txn(session, test_user, acct, description="Exp", amount=Decimal("300"), type="debit")+ res, _, summary = await get_transactions(+ session, test_workspace.id, test_user.id, include_summary=True+ )+ assert summary is not None+ assert summary["income"] == Decimal("1000")+ assert summary["expense"] == Decimal("300")+ assert summary["net"] == Decimal("700")+++async def test_get_transactions_summary_excludes_ignored(session, test_user, test_workspace, acct):+ await _mk_txn(session, test_user, acct, description="Counted", amount=Decimal("100"), type="debit")+ await _mk_txn(+ session, test_user, acct, description="Ignored", amount=Decimal("999"),+ type="debit", is_ignored=True,+ )+ _, _, summary = await get_transactions(+ session, test_workspace.id, test_user.id, include_summary=True+ )+ assert summary["expense"] == Decimal("100")+++async def test_get_transactions_sorting(session, test_user, test_workspace, acct):+ await _mk_txn(session, test_user, acct, description="Aaa", amount=Decimal("30"))+ await _mk_txn(session, test_user, acct, description="Zzz", amount=Decimal("10"))+ await _mk_txn(session, test_user, acct, description="Mmm", amount=Decimal("20"))++ asc, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, sort_by="amount", sort_dir="asc"+ )+ amts = [t.amount for t in asc]+ assert amts == sorted(amts)++ desc, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, sort_by="description", sort_dir="desc"+ )+ descs = [t.description for t in desc]+ assert descs[0] == "Zzz"++ # transaction_date sort path+ td, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, sort_by="transaction_date", sort_dir="asc"+ )+ assert len(td) == 3+++# ---------------------------------------------------------------------------+# Group-scope visibility (lines 110-112, 146-155)+# ---------------------------------------------------------------------------+++async def test_get_transactions_group_scope(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ txn = await _mk_txn(session, test_user, acct, description="Shared dinner", amount=Decimal("100"))+ # Split among the two non-self members+ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=members[1].id),+ TransactionSplitInput(group_member_id=members[2].id)],+ )+ from app.services import split_service+ await split_service.replace_splits(session, txn, payload, test_user.id)+ await session.commit()++ res, total, _ = await get_transactions(+ session, test_workspace.id, test_user.id, group_id=group.id+ )+ assert {t.description for t in res} == {"Shared dinner"}+ assert total == 1+++async def test_get_transactions_group_scope_not_visible(session, test_user, test_workspace, acct):+ # A random group id the user cannot see returns the early-out tuple.+ result = await get_transactions(+ session, test_workspace.id, test_user.id, group_id=uuid.uuid4()+ )+ # The not-visible branch short-circuits with ([], 0).+ assert result[0] == []+ assert result[1] == 0+++async def test_get_transactions_owner_share_tagging(session, test_user, test_workspace, acct):+ """Owner with a self-split should get group_id and viewer_share tagged."""+ group, members = await _mk_group(session, test_user, test_workspace)+ txn = await _mk_txn(session, test_user, acct, description="With self share", amount=Decimal("90"))+ self_member = next(m for m in members if m.is_self)+ other = next(m for m in members if not m.is_self)+ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=self_member.id),+ TransactionSplitInput(group_member_id=other.id)],+ )+ from app.services import split_service+ await split_service.replace_splits(session, txn, payload, test_user.id)+ await session.commit()++ res, _, _ = await get_transactions(session, test_workspace.id, test_user.id)+ tagged = next(t for t in res if t.description == "With self share")+ assert tagged.group_id == group.id+ assert tagged.is_shared is False+ assert tagged.viewer_share == Decimal("45.00")+++# ---------------------------------------------------------------------------+# include_opening_balance branch+# ---------------------------------------------------------------------------+++async def test_get_transactions_opening_balance_excluded_then_included(session, test_user, test_workspace, acct):+ await _mk_txn(+ session, test_user, acct, description="Opening", amount=Decimal("1000"),+ type="credit", source="opening_balance",+ )+ await _mk_txn(session, test_user, acct, description="Normal", amount=Decimal("10"))++ res, _, _ = await get_transactions(session, test_workspace.id, test_user.id)+ assert "Opening" not in {t.description for t in res}++ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id, include_opening_balance=True+ )+ assert "Opening" in {t.description for t in res}+++# ---------------------------------------------------------------------------+# get_transfer_candidates (lines 802-869)+# ---------------------------------------------------------------------------+++async def test_get_transfer_candidates_ranks_by_proximity(session, test_user, test_workspace, acct):+ acct2 = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="Cand2", type="savings",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(acct2)+ await session.commit()++ anchor = await _mk_txn(+ session, test_user, acct, description="Anchor", amount=Decimal("100"),+ type="debit", date=date(2025, 3, 15),+ )+ # Best candidate: closest date + same amount, opposing type, other account+ close = await _mk_txn(+ session, test_user, acct2, description="Close", amount=Decimal("100"),+ type="credit", date=date(2025, 3, 16),+ )+ far = await _mk_txn(+ session, test_user, acct2, description="Far", amount=Decimal("100"),+ type="credit", date=date(2025, 3, 25),+ )+ # Same account → excluded+ await _mk_txn(+ session, test_user, acct, description="SameAcct", amount=Decimal("100"),+ type="credit", date=date(2025, 3, 16),+ )++ cands = await get_transfer_candidates(session, test_workspace.id, anchor.id)+ descs = [c.description for c in cands]+ assert descs[0] == "Close"+ assert "Far" in descs+ assert "SameAcct" not in descs+++async def test_get_transfer_candidates_anchor_missing(session, test_user, test_workspace):+ cands = await get_transfer_candidates(session, test_workspace.id, uuid.uuid4())+ assert cands == []+++async def test_get_transfer_candidates_anchor_already_paired(session, test_user, test_workspace, acct):+ anchor = await _mk_txn(+ session, test_user, acct, description="Paired", amount=Decimal("50"),+ transfer_pair_id=uuid.uuid4(),+ )+ cands = await get_transfer_candidates(session, test_workspace.id, anchor.id)+ assert cands == []+++# ---------------------------------------------------------------------------+# link_existing_as_transfer (lines 884-921)+# ---------------------------------------------------------------------------+++async def test_link_existing_as_transfer_success(session, test_user, test_workspace, acct):+ acct2 = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="Link2", type="savings",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(acct2)+ await session.commit()+ debit = await _mk_txn(session, test_user, acct, description="D", amount=Decimal("100"), type="debit")+ credit = await _mk_txn(session, test_user, acct2, description="C", amount=Decimal("100"), type="credit")++ d, c = await link_existing_as_transfer(session, test_workspace.id, [debit.id, credit.id])+ assert d.transfer_pair_id == c.transfer_pair_id+ assert d.type == "debit" and c.type == "credit"+ assert d.category_id is None+++async def test_link_existing_wrong_count(session, test_workspace):+ with pytest.raises(ValueError, match="Exactly two"):+ await link_existing_as_transfer(session, test_workspace.id, [uuid.uuid4()])+++async def test_link_existing_same_id(session, test_workspace):+ same = uuid.uuid4()+ with pytest.raises(ValueError, match="itself"):+ await link_existing_as_transfer(session, test_workspace.id, [same, same])+++async def test_link_existing_not_found(session, test_workspace, test_user, acct):+ real = await _mk_txn(session, test_user, acct, description="R", type="debit")+ with pytest.raises(ValueError, match="not found"):+ await link_existing_as_transfer(session, test_workspace.id, [real.id, uuid.uuid4()])+++async def test_link_existing_already_transfer(session, test_user, test_workspace, acct):+ acct2 = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="L2", type="savings",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(acct2)+ await session.commit()+ debit = await _mk_txn(session, test_user, acct, description="D", type="debit", transfer_pair_id=uuid.uuid4())+ credit = await _mk_txn(session, test_user, acct2, description="C", type="credit")+ with pytest.raises(ValueError, match="already part of a transfer"):+ await link_existing_as_transfer(session, test_workspace.id, [debit.id, credit.id])+++async def test_link_existing_same_account(session, test_user, test_workspace, acct):+ debit = await _mk_txn(session, test_user, acct, description="D", type="debit")+ credit = await _mk_txn(session, test_user, acct, description="C", type="credit")+ with pytest.raises(ValueError, match="different accounts"):+ await link_existing_as_transfer(session, test_workspace.id, [debit.id, credit.id])+++async def test_link_existing_wrong_types(session, test_user, test_workspace, acct):+ acct2 = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="L3", type="savings",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(acct2)+ await session.commit()+ a = await _mk_txn(session, test_user, acct, description="A", type="debit")+ b = await _mk_txn(session, test_user, acct2, description="B", type="debit")+ with pytest.raises(ValueError, match="one debit and one credit"):+ await link_existing_as_transfer(session, test_workspace.id, [a.id, b.id])+++# ---------------------------------------------------------------------------+# create_transfer_counterpart (lines 942-1013)+# ---------------------------------------------------------------------------+++async def test_create_transfer_counterpart_same_currency(session, test_user, test_workspace, acct):+ acct2 = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="CP2", type="savings",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(acct2)+ await session.commit()+ anchor = await _mk_txn(session, test_user, acct, description="Anchor", amount=Decimal("75"), type="debit")++ debit, credit = await create_transfer_counterpart(+ session, test_workspace.id, test_user.id, anchor.id, acct2.id+ )+ assert debit.transfer_pair_id == credit.transfer_pair_id+ assert debit.type == "debit" and credit.type == "credit"+ assert credit.account_id == acct2.id+ assert credit.amount == Decimal("75")+++async def test_create_transfer_counterpart_cross_currency(session, test_user, test_workspace, acct, acct_usd):+ anchor = await _mk_txn(session, test_user, acct, description="X", amount=Decimal("500"), type="debit")+ debit, credit = await create_transfer_counterpart(+ session, test_workspace.id, test_user.id, anchor.id, acct_usd.id+ )+ assert credit.currency == "USD"+ assert debit.transfer_pair_id == credit.transfer_pair_id+++async def test_create_transfer_counterpart_anchor_missing(session, test_workspace, test_user, acct):+ with pytest.raises(ValueError, match="Transaction not found"):+ await create_transfer_counterpart(+ session, test_workspace.id, test_user.id, uuid.uuid4(), acct.id+ )+++async def test_create_transfer_counterpart_already_transfer(session, test_user, test_workspace, acct, acct_usd):+ anchor = await _mk_txn(+ session, test_user, acct, description="P", type="debit", transfer_pair_id=uuid.uuid4()+ )+ with pytest.raises(ValueError, match="already part of a transfer"):+ await create_transfer_counterpart(+ session, test_workspace.id, test_user.id, anchor.id, acct_usd.id+ )+++async def test_create_transfer_counterpart_same_account(session, test_user, test_workspace, acct):+ anchor = await _mk_txn(session, test_user, acct, description="S", type="debit")+ with pytest.raises(ValueError, match="different account"):+ await create_transfer_counterpart(+ session, test_workspace.id, test_user.id, anchor.id, acct.id+ )+++async def test_create_transfer_counterpart_dest_missing(session, test_user, test_workspace, acct):+ anchor = await _mk_txn(session, test_user, acct, description="N", type="credit")+ with pytest.raises(ValueError, match="Destination account not found"):+ await create_transfer_counterpart(+ session, test_workspace.id, test_user.id, anchor.id, uuid.uuid4()+ )+++# ---------------------------------------------------------------------------+# update_transaction — splits, FX cascade, effective_bill_date (1154+, 1166-1173)+# ---------------------------------------------------------------------------+++async def test_update_transaction_with_splits(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(+ account_id=acct.id, description="ToSplit", amount=Decimal("100"),+ date=date.today(), type="debit",+ ))+ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=members[1].id),+ TransactionSplitInput(group_member_id=members[2].id)],+ )+ updated = await update_transaction(+ session, txn.id, test_workspace.id, test_user.id,+ TransactionUpdate(splits=payload),+ )+ assert len(updated.splits) == 2+++async def test_create_transaction_with_splits(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=members[1].id),+ TransactionSplitInput(group_member_id=members[2].id)],+ )+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(+ account_id=acct.id, description="CreatedWithSplit", amount=Decimal("80"),+ date=date.today(), type="debit", splits=payload,+ ))+ assert len(txn.splits) == 2+++async def test_update_transfer_cascades_amount_cross_currency(session, test_user, test_workspace, acct, acct_usd):+ debit, credit = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(+ from_account_id=acct.id, to_account_id=acct_usd.id,+ description="XC", amount=Decimal("500"), date=date.today(), fx_rate=Decimal("0.2"),+ ))+ # Change amount on debit side; cascade should re-convert for the credit side.+ updated = await update_transaction(+ session, debit.id, test_workspace.id, test_user.id,+ TransactionUpdate(amount=Decimal("1000")),+ )+ assert updated.amount == Decimal("1000")+ paired = await get_transaction(session, credit.id, test_workspace.id)+ # The cross-currency cascade branch ran: paired amount was re-converted+ # (rate is 1:1 in tests since no FX rate is seeded, so it tracks 1000).+ assert paired.amount == Decimal("1000")+++async def test_update_transfer_cascade_category(session, test_user, test_workspace, acct, test_categories):+ acct2 = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="CC2", type="savings",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(acct2)+ await session.commit()+ debit, credit = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(+ from_account_id=acct.id, to_account_id=acct2.id,+ description="CatXfer", amount=Decimal("100"), date=date.today(),+ ))+ await update_transaction(+ session, debit.id, test_workspace.id, test_user.id,+ TransactionUpdate(category_id=test_categories[0].id, apply_to_transfer_pair=True),+ )+ paired = await get_transaction(session, credit.id, test_workspace.id)+ assert paired.category_id == test_categories[0].id+++async def test_update_transaction_effective_bill_date_links_bill(session, test_user, test_workspace, cc_account):+ bill = CreditCardBill(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=cc_account.id, external_id="bill-1",+ due_date=date(2025, 4, 20), total_amount=Decimal("500"), currency="BRL",+ )+ session.add(bill)+ await session.commit()+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(+ account_id=cc_account.id, description="CC charge", amount=Decimal("50"),+ date=date(2025, 4, 1), type="debit",+ ))+ updated = await update_transaction(+ session, txn.id, test_workspace.id, test_user.id,+ TransactionUpdate(effective_bill_date=date(2025, 4, 20)),+ )+ assert updated.bill_id == bill.id+ assert updated.effective_date == date(2025, 4, 20)+++async def test_update_transaction_effective_bill_date_no_match(session, test_user, test_workspace, cc_account):+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(+ account_id=cc_account.id, description="CC nomatch", amount=Decimal("30"),+ date=date(2025, 4, 1), type="debit",+ ))+ updated = await update_transaction(+ session, txn.id, test_workspace.id, test_user.id,+ TransactionUpdate(effective_bill_date=date(2099, 1, 1)),+ )+ assert updated.bill_id is None+ assert updated.effective_date == date(2099, 1, 1)+++async def test_update_transaction_clear_bill_override_recovers_pluggy(session, test_user, test_workspace, cc_account):+ bill = CreditCardBill(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=cc_account.id, external_id="ext-bill-99",+ due_date=date(2025, 5, 20), total_amount=Decimal("200"), currency="BRL",+ )+ session.add(bill)+ txn = await _mk_txn(+ session, test_user, cc_account, description="Synced charge",+ amount=Decimal("40"), date=date(2025, 5, 1), source="sync",+ effective_bill_date=date(2025, 5, 20), bill_id=bill.id,+ raw_data={"creditCardMetadata": {"billId": "ext-bill-99"}},+ )+ # Clear the override -> should recover the original Pluggy bill linkage.+ updated = await update_transaction(+ session, txn.id, test_workspace.id, test_user.id,+ TransactionUpdate(effective_bill_date=None),+ )+ assert updated.bill_id == bill.id+++async def test_update_transaction_clear_bill_override_no_raw(session, test_user, test_workspace, cc_account):+ txn = await _mk_txn(+ session, test_user, cc_account, description="No raw",+ amount=Decimal("40"), date=date(2025, 5, 1),+ effective_bill_date=date(2025, 5, 20),+ )+ updated = await update_transaction(+ session, txn.id, test_workspace.id, test_user.id,+ TransactionUpdate(effective_bill_date=None),+ )+ assert updated.bill_id is None+++# ---------------------------------------------------------------------------+# bulk tag edge branches (1221, 1225, 1254, 1258, 1269)+# ---------------------------------------------------------------------------+++async def test_bulk_add_tags_empty_inputs(session, test_workspace):+ assert await bulk_add_tags(session, test_workspace.id, [], ["#x"]) == 0+ assert await bulk_add_tags(session, test_workspace.id, [uuid.uuid4()], []) == 0+ # Tags that normalize to nothing+ assert await bulk_add_tags(session, test_workspace.id, [uuid.uuid4()], [" "]) == 0+++async def test_bulk_remove_tags_empty_inputs(session, test_workspace):+ assert await bulk_remove_tags(session, test_workspace.id, [], ["#x"]) == 0+ assert await bulk_remove_tags(session, test_workspace.id, [uuid.uuid4()], []) == 0+ assert await bulk_remove_tags(session, test_workspace.id, [uuid.uuid4()], [" "]) == 0+++async def test_bulk_remove_tags_skips_empty_notes(session, test_user, test_workspace, acct):+ t = await _mk_txn(session, test_user, acct, description="NoNotes", notes=None)+ touched = await bulk_remove_tags(session, test_workspace.id, [t.id], ["#anything"])+ assert touched == 0+++# ---------------------------------------------------------------------------+# bulk_add_to_group (1308, 1314, 1328-1380)+# ---------------------------------------------------------------------------+++async def test_bulk_add_to_group_equal(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ t1 = await _mk_txn(session, test_user, acct, description="G1", amount=Decimal("100"))+ t2 = await _mk_txn(session, test_user, acct, description="G2", amount=Decimal("60"))++ result = await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [t1.id, t2.id], group.id, share_type="equal"+ )+ assert result["updated"] == 2+ assert result["skipped"] == 0+++async def test_bulk_add_to_group_percent_with_member_splits(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ non_self = [m for m in members if not m.is_self]+ t1 = await _mk_txn(session, test_user, acct, description="P1", amount=Decimal("100"))++ splits = [+ TransactionSplitInput(group_member_id=non_self[0].id, share_pct=Decimal("60")),+ TransactionSplitInput(group_member_id=non_self[1].id, share_pct=Decimal("40")),+ ]+ result = await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [t1.id], group.id,+ share_type="percent", member_splits=splits,+ )+ assert result["updated"] == 1+++async def test_bulk_add_to_group_skips_transfers_and_existing_splits(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ transfer = await _mk_txn(+ session, test_user, acct, description="Xfer", amount=Decimal("50"),+ transfer_pair_id=uuid.uuid4(),+ )+ # A tx that already has splits+ pre_split = await _mk_txn(session, test_user, acct, description="Pre", amount=Decimal("80"))+ from app.services import split_service+ await split_service.replace_splits(+ session, pre_split,+ TransactionSplitsInput(share_type="equal", splits=[+ TransactionSplitInput(group_member_id=members[1].id),+ ]),+ test_user.id,+ )+ await session.commit()++ result = await bulk_add_to_group(+ session, test_workspace.id, test_user.id,+ [transfer.id, pre_split.id], group.id, share_type="equal",+ )+ assert result["updated"] == 0+ assert result["skipped"] == 2+++async def test_bulk_add_to_group_invalid_share_type(session, test_user, test_workspace):+ group, _ = await _mk_group(session, test_user, test_workspace)+ with pytest.raises(ValueError, match="equal' or 'percent"):+ await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [uuid.uuid4()], group.id, share_type="exact"+ )+++async def test_bulk_add_to_group_empty_ids(session, test_user, test_workspace):+ group, _ = await _mk_group(session, test_user, test_workspace)+ result = await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [], group.id, share_type="equal"+ )+ assert result == {"updated": 0, "skipped": 0}+++async def test_bulk_add_to_group_group_not_found(session, test_user, test_workspace):+ with pytest.raises(ValueError, match="Group not found"):+ await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [uuid.uuid4()], uuid.uuid4(), share_type="equal"+ )+++async def test_bulk_add_to_group_no_members(session, test_user, test_workspace):+ group, _ = await _mk_group(session, test_user, test_workspace, with_self=False, n_members=0)+ with pytest.raises(ValueError, match="no members"):+ await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [uuid.uuid4()], group.id, share_type="equal"+ )+++async def test_bulk_add_to_group_invalid_member(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ bad_splits = [TransactionSplitInput(group_member_id=uuid.uuid4())]+ with pytest.raises(ValueError, match="split members not found"):+ await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [uuid.uuid4()], group.id,+ share_type="equal", member_splits=bad_splits,+ )+++async def test_bulk_add_to_group_counts_missing_ids_as_skipped(session, test_user, test_workspace, acct):+ group, members = await _mk_group(session, test_user, test_workspace)+ t1 = await _mk_txn(session, test_user, acct, description="Real", amount=Decimal("40"))+ missing = uuid.uuid4()+ result = await bulk_add_to_group(+ session, test_workspace.id, test_user.id, [t1.id, missing], group.id, share_type="equal"+ )+ assert result["updated"] == 1+ assert result["skipped"] == 1+++# ---------------------------------------------------------------------------+# Bill-driven filters and unbilled_only cycle math (lines 247-325)+# ---------------------------------------------------------------------------+++async def test_get_transactions_bill_id_filter(session, test_user, test_workspace, cc_account):+ bill = CreditCardBill(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=cc_account.id, external_id="b-filter",+ due_date=date(2025, 4, 20), total_amount=Decimal("500"), currency="BRL",+ )+ session.add(bill)+ await session.commit()++ # Linked to the bill directly.+ linked = await _mk_txn(+ session, test_user, cc_account, description="Linked", amount=Decimal("100"),+ date=date(2025, 4, 5), bill_id=bill.id, effective_date=date(2025, 4, 20),+ )+ # Unlinked manual tx whose date falls inside the window.+ in_window = await _mk_txn(+ session, test_user, cc_account, description="InWindow", amount=Decimal("50"),+ date=date(2025, 4, 7), effective_date=date(2025, 4, 7),+ )+ # Outside the window and unlinked.+ await _mk_txn(+ session, test_user, cc_account, description="Outside", amount=Decimal("20"),+ date=date(2025, 1, 1), effective_date=date(2025, 1, 1),+ )++ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id,+ bill_id=bill.id, from_date=date(2025, 4, 1), to_date=date(2025, 4, 30),+ )+ descs = {t.description for t in res}+ assert "Linked" in descs+ assert "InWindow" in descs+ assert "Outside" not in descs+++async def test_get_transactions_bill_id_no_dates(session, test_user, test_workspace, cc_account):+ bill = CreditCardBill(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=cc_account.id, external_id="b-nodates",+ due_date=date(2025, 4, 20), total_amount=Decimal("500"), currency="BRL",+ )+ session.add(bill)+ await session.commit()+ linked = await _mk_txn(+ session, test_user, cc_account, description="OnlyLinked", amount=Decimal("100"),+ date=date(2025, 4, 5), bill_id=bill.id, effective_date=date(2025, 4, 20),+ )+ res, _, _ = await get_transactions(session, test_workspace.id, test_user.id, bill_id=bill.id)+ assert "OnlyLinked" in {t.description for t in res}+++async def test_get_transactions_unbilled_only(session, test_user, test_workspace, cc_account):+ bill = CreditCardBill(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=cc_account.id, external_id="b-unbilled",+ due_date=date(2025, 4, 20), total_amount=Decimal("500"), currency="BRL",+ )+ session.add(bill)+ await session.commit()++ billed = await _mk_txn(+ session, test_user, cc_account, description="AlreadyBilled", amount=Decimal("100"),+ date=date(2025, 5, 3), bill_id=bill.id, effective_date=date(2025, 5, 3),+ )+ unbilled = await _mk_txn(+ session, test_user, cc_account, description="StillUnbilled", amount=Decimal("40"),+ date=date(2025, 5, 4), effective_date=date(2025, 5, 4),+ )+ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id,+ unbilled_only=True, from_date=date(2025, 5, 1), to_date=date(2025, 5, 31),+ )+ descs = {t.description for t in res}+ assert "StillUnbilled" in descs+ assert "AlreadyBilled" not in descs+++async def test_get_transactions_unbilled_only_forward_override(session, test_user, test_workspace, cc_account):+ # A tx with a forward-pointing manual override beyond the window edge+ # should still surface in the in-progress cycle (issue #162).+ forward = await _mk_txn(+ session, test_user, cc_account, description="ForwardOverride", amount=Decimal("70"),+ date=date(2025, 5, 10), effective_date=date(2025, 7, 20),+ effective_bill_date=date(2025, 7, 20),+ )+ res, _, _ = await get_transactions(+ session, test_workspace.id, test_user.id,+ unbilled_only=True, from_date=date(2025, 5, 1), to_date=date(2025, 5, 31),+ )+ assert "ForwardOverride" in {t.description for t in res}diff --git a/backend/tests/test_transactions_api_coverage.py b/backend/tests/test_transactions_api_coverage.pynew file mode 100644index 00000000..fea4ea5f--- /dev/null+++ b/backend/tests/test_transactions_api_coverage.py@@ -0,0 +1,355 @@+"""Coverage-focused tests for app/api/transactions.py.++Covers list filters, export (filtered + selection), get/create/update/delete,+ignore toggle, bulk endpoints, transfer/link/counterpart/candidates, and+error branches (404/400/422).+"""+import uuid+from datetime import date+from decimal import Decimal++import pytest+from httpx import AsyncClient++from app.models.account import Account+from app.models.transaction import Transaction+++NONEXISTENT = "00000000-0000-0000-0000-000000000000"+++async def _manual_account(client: AsyncClient, auth_headers, name: str) -> str:+ resp = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": name, "type": "checking", "balance": "0.00"},+ )+ assert resp.status_code == 201, resp.text+ return resp.json()["id"]+++# ---------------------------------------------------------------------------+# list filters + summary+# ---------------------------------------------------------------------------+++async def test_list_with_summary(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get("/api/transactions", headers=auth_headers)+ assert resp.status_code == 200+ data = resp.json()+ assert data["summary"] is not None+ assert {"income", "expense", "net", "currency"} <= data["summary"].keys()+++async def test_list_filter_by_type(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get("/api/transactions?type=credit", headers=auth_headers)+ assert resp.status_code == 200+ assert all(t["type"] == "credit" for t in resp.json()["items"])+++async def test_list_search_query(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get("/api/transactions?q=UBER", headers=auth_headers)+ assert resp.status_code == 200+ items = resp.json()["items"]+ assert len(items) == 1+ assert "UBER" in items[0]["description"]+++async def test_list_uncategorized_only(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get("/api/transactions?uncategorized=true", headers=auth_headers)+ assert resp.status_code == 200+ assert all(t["category_id"] is None for t in resp.json()["items"])+++async def test_list_amount_bounds_and_sort(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get(+ "/api/transactions?min_amount=40&max_amount=200&sort_by=amount&sort_dir=asc",+ headers=auth_headers,+ )+ assert resp.status_code == 200+ items = resp.json()["items"]+ amounts = [abs(float(t["amount"])) for t in items]+ assert amounts == sorted(amounts)+ assert all(40 <= a <= 200 for a in amounts)+++async def test_list_exclude_transfers(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get("/api/transactions?exclude_transfers=true", headers=auth_headers)+ assert resp.status_code == 200+++async def test_list_invalid_sort_dir_422(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get("/api/transactions?sort_dir=sideways", headers=auth_headers)+ assert resp.status_code == 422+++# ---------------------------------------------------------------------------+# export+# ---------------------------------------------------------------------------+++async def test_export_filtered(client: AsyncClient, auth_headers, test_transactions):+ resp = await client.get("/api/transactions/export", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.headers["content-type"].startswith("text/csv")+ body = resp.text+ assert "date,description,amount" in body+ assert "UBER TRIP" in body+++async def test_export_selection_only(client: AsyncClient, auth_headers, test_transactions):+ tx_id = str(test_transactions[0].id)+ resp = await client.get(+ f"/api/transactions/export?transaction_ids={tx_id}", headers=auth_headers+ )+ assert resp.status_code == 200+ body = resp.text+ assert test_transactions[0].description in body+++# ---------------------------------------------------------------------------+# get / create / update / delete / ignore+# ---------------------------------------------------------------------------+++async def test_get_transaction(client: AsyncClient, auth_headers, test_transactions):+ tx = test_transactions[0]+ resp = await client.get(f"/api/transactions/{tx.id}", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.json()["description"] == tx.description+++async def test_get_transaction_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.get(f"/api/transactions/{NONEXISTENT}", headers=auth_headers)+ assert resp.status_code == 404+++async def test_create_transaction(client: AsyncClient, auth_headers, test_account: Account):+ resp = await client.post(+ "/api/transactions", headers=auth_headers,+ json={+ "account_id": str(test_account.id),+ "description": "Padaria",+ "amount": "12.50",+ "date": date.today().isoformat(),+ "type": "debit",+ },+ )+ assert resp.status_code == 201, resp.text+ assert resp.json()["description"] == "Padaria"+++async def test_create_transaction_bad_account_400(client: AsyncClient, auth_headers, test_account):+ resp = await client.post(+ "/api/transactions", headers=auth_headers,+ json={+ "account_id": NONEXISTENT,+ "description": "Ghost",+ "amount": "1.00",+ "date": date.today().isoformat(),+ "type": "debit",+ },+ )+ assert resp.status_code == 400+++async def test_update_transaction(client: AsyncClient, auth_headers, test_transactions):+ tx = test_transactions[0]+ resp = await client.patch(+ f"/api/transactions/{tx.id}", headers=auth_headers,+ json={"description": "UBER updated", "notes": "trip"},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["description"] == "UBER updated"+ assert data["notes"] == "trip"+++async def test_update_transaction_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.patch(+ f"/api/transactions/{NONEXISTENT}", headers=auth_headers,+ json={"description": "X"},+ )+ assert resp.status_code == 404+++async def test_toggle_ignore(client: AsyncClient, auth_headers, test_transactions):+ tx = test_transactions[0]+ resp = await client.patch(f"/api/transactions/{tx.id}/ignore", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.json()["is_ignored"] is True+++async def test_toggle_ignore_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.patch(f"/api/transactions/{NONEXISTENT}/ignore", headers=auth_headers)+ assert resp.status_code == 404+++async def test_delete_transaction(client: AsyncClient, auth_headers, test_transactions):+ tx = test_transactions[0]+ resp = await client.delete(f"/api/transactions/{tx.id}", headers=auth_headers)+ assert resp.status_code == 204+ assert (await client.get(f"/api/transactions/{tx.id}", headers=auth_headers)).status_code == 404+++async def test_delete_transaction_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.delete(f"/api/transactions/{NONEXISTENT}", headers=auth_headers)+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# bulk endpoints+# ---------------------------------------------------------------------------+++async def test_bulk_categorize(client: AsyncClient, auth_headers, test_transactions, test_categories):+ ids = [str(t.id) for t in test_transactions[:2]]+ resp = await client.patch(+ "/api/transactions/bulk-categorize", headers=auth_headers,+ json={"transaction_ids": ids, "category_id": str(test_categories[0].id)},+ )+ assert resp.status_code == 200+ assert resp.json()["updated"] == 2+++async def test_bulk_add_and_remove_tags(client: AsyncClient, auth_headers, test_transactions):+ ids = [str(t.id) for t in test_transactions[:2]]+ add = await client.patch(+ "/api/transactions/bulk-add-tags", headers=auth_headers,+ json={"transaction_ids": ids, "tags": ["viagem", "reembolso"]},+ )+ assert add.status_code == 200+ assert add.json()["updated"] == 2++ remove = await client.patch(+ "/api/transactions/bulk-remove-tags", headers=auth_headers,+ json={"transaction_ids": ids, "tags": ["viagem"]},+ )+ assert remove.status_code == 200+ assert remove.json()["updated"] == 2+++async def test_bulk_add_to_group_bad_group_400(client: AsyncClient, auth_headers, test_transactions):+ ids = [str(t.id) for t in test_transactions[:1]]+ resp = await client.patch(+ "/api/transactions/bulk-add-to-group", headers=auth_headers,+ json={"transaction_ids": ids, "group_id": NONEXISTENT, "share_type": "equal"},+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# transfer / link / counterpart / candidates+# ---------------------------------------------------------------------------+++async def test_create_transfer(client: AsyncClient, auth_headers, test_account: Account):+ other = await _manual_account(client, auth_headers, "Destino")+ resp = await client.post(+ "/api/transactions/transfer", headers=auth_headers,+ json={+ "from_account_id": str(test_account.id),+ "to_account_id": other,+ "amount": "100.00",+ "date": date.today().isoformat(),+ "description": "Transferência",+ },+ )+ assert resp.status_code == 201, resp.text+ data = resp.json()+ assert data["debit"]["type"] == "debit"+ assert data["credit"]["type"] == "credit"+ assert data["transfer_pair_id"]+++async def test_create_transfer_same_account_400(client: AsyncClient, auth_headers, test_account):+ resp = await client.post(+ "/api/transactions/transfer", headers=auth_headers,+ json={+ "from_account_id": str(test_account.id),+ "to_account_id": str(test_account.id),+ "amount": "10.00",+ "date": date.today().isoformat(),+ "description": "self",+ },+ )+ assert resp.status_code == 400+++async def test_transfer_candidates(client: AsyncClient, auth_headers, test_transactions):+ tx = test_transactions[0]+ resp = await client.get(+ f"/api/transactions/{tx.id}/transfer-candidates", headers=auth_headers+ )+ assert resp.status_code == 200+ assert isinstance(resp.json(), list)+++async def test_transfer_candidates_not_found(client: AsyncClient, auth_headers, test_account):+ resp = await client.get(+ f"/api/transactions/{NONEXISTENT}/transfer-candidates", headers=auth_headers+ )+ assert resp.status_code == 404+++async def test_create_counterpart(+ client: AsyncClient, auth_headers, test_account: Account, test_transactions+):+ """Mark an existing tx as a transfer by auto-creating its counterpart."""+ other = await _manual_account(client, auth_headers, "Contrapartida")+ tx = test_transactions[0]+ resp = await client.post(+ f"/api/transactions/{tx.id}/create-counterpart", headers=auth_headers,+ json={"to_account_id": other},+ )+ assert resp.status_code == 201, resp.text+ assert resp.json()["transfer_pair_id"]+++async def test_create_counterpart_bad_target_400(+ client: AsyncClient, auth_headers, test_transactions+):+ tx = test_transactions[0]+ resp = await client.post(+ f"/api/transactions/{tx.id}/create-counterpart", headers=auth_headers,+ json={"to_account_id": NONEXISTENT},+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# auth+# ---------------------------------------------------------------------------+++async def test_list_transactions_requires_auth(client: AsyncClient):+ resp = await client.get("/api/transactions")+ assert resp.status_code == 401diff --git a/backend/tests/test_workspace_service_coverage.py b/backend/tests/test_workspace_service_coverage.pynew file mode 100644index 00000000..9498385e--- /dev/null+++ b/backend/tests/test_workspace_service_coverage.py@@ -0,0 +1,356 @@+"""Coverage-focused tests for workspace_service.++Targets get_managed_workspaces, get_default_workspace manager fallback,+create_workspace with self_membership + seed_defaults, add_member error+paths, update_member_role validation, get_workspace_stats, archive_workspace,+and remove_member.+"""+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import bcrypt as _bcrypt+import pytest+from fastapi import HTTPException+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.models.user import User+from app.models.workspace import Workspace, WorkspaceMember+from app.services import workspace_service+++async def _make_user(session, email):+ hashed = _bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode()+ user = User(+ id=uuid.uuid4(),+ email=email,+ hashed_password=hashed,+ is_active=True,+ is_verified=True,+ preferences={"currency_display": "USD", "language": "en"},+ )+ session.add(user)+ await session.flush()+ return user+++async def test_get_managed_workspaces(session: AsyncSession, test_user: User):+ ws = await workspace_service.create_workspace(+ session, name="Managed Co", creator=test_user, seed_defaults=False+ )+ await session.commit()+ managed = await workspace_service.get_managed_workspaces(session, test_user.id)+ assert ws.id in {w.id for w in managed}+++async def test_get_default_workspace_member_first(session: AsyncSession, test_user: User):+ ws = await workspace_service.get_default_workspace(session, test_user.id)+ assert ws is not None+ assert ws.kind == "personal"+++async def test_get_default_workspace_falls_back_to_managed(session: AsyncSession):+ """A manager-only user (no memberships) falls back to a managed workspace."""+ manager = await _make_user(session, "[email protected]")+ ws = Workspace(+ id=uuid.uuid4(),+ name="OnlyManaged",+ kind="personal",+ created_by_user_id=manager.id,+ managed_by_user_id=manager.id,+ default_currency="USD",+ )+ session.add(ws)+ await session.commit()++ default = await workspace_service.get_default_workspace(session, manager.id)+ assert default is not None+ assert default.id == ws.id+++async def test_get_default_workspace_none(session: AsyncSession):+ stranger = await _make_user(session, "[email protected]")+ await session.commit()+ assert await workspace_service.get_default_workspace(session, stranger.id) is None+++async def test_create_workspace_with_self_membership_and_seed(session: AsyncSession, test_user: User):+ ws = await workspace_service.create_workspace(+ session,+ name="Day To Day",+ creator=test_user,+ self_membership=True,+ seed_defaults=True,+ icon="briefcase",+ color="#112233",+ )+ await session.commit()++ assert ws.icon == "briefcase"+ assert ws.color == "#112233"+ members = await workspace_service.list_members(session, ws.id)+ assert len(members) == 1+ assert members[0][0].role == "owner"++ # seed_defaults created categories for the workspace.+ from app.models.category import Category+ cats = await session.execute(+ select(Category).where(Category.workspace_id == ws.id)+ )+ assert len(cats.scalars().all()) > 0+++async def test_create_workspace_blank_name_fallback(session: AsyncSession, test_user: User):+ ws = await workspace_service.create_workspace(+ session, name=" ", creator=test_user, seed_defaults=False+ )+ await session.commit()+ assert ws.name == "Workspace"+++async def test_add_member_invalid_role(session: AsyncSession, test_user: User, test_workspace):+ other = await _make_user(session, "[email protected]")+ await session.commit()+ with pytest.raises(HTTPException) as exc:+ await workspace_service.add_member(+ session, test_workspace.id, other.id, role="superadmin"+ )+ assert exc.value.status_code == 400+++async def test_add_member_duplicate(session: AsyncSession, test_user: User, test_workspace):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.add_member(+ session, test_workspace.id, test_user.id, role="editor"+ )+ assert exc.value.status_code == 409+++async def test_update_member_role_invalid(session: AsyncSession, test_user: User, test_workspace):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.update_member_role(+ session, test_workspace.id, test_user.id, "boss"+ )+ assert exc.value.status_code == 400+++async def test_update_member_role_member_not_found(session: AsyncSession, test_workspace):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.update_member_role(+ session, test_workspace.id, uuid.uuid4(), "editor"+ )+ assert exc.value.status_code == 404+++async def test_update_member_role_demote_with_other_owner(session: AsyncSession, test_user: User, test_workspace):+ other = await _make_user(session, "[email protected]")+ await session.commit()+ await workspace_service.add_member(+ session, test_workspace.id, other.id, role="owner"+ )+ await session.commit()+ # Now demoting test_user is allowed since another owner exists.+ member = await workspace_service.update_member_role(+ session, test_workspace.id, test_user.id, "editor"+ )+ await session.commit()+ assert member.role == "editor"+++async def test_get_workspace_stats(session: AsyncSession, test_user: User, test_workspace, test_account, test_transactions):+ stats = await workspace_service.get_workspace_stats(session, test_workspace.id)+ assert stats["members"] == 1+ assert stats["accounts"] >= 1+ assert stats["transactions"] >= 1+++async def test_archive_workspace_blocks_last(session: AsyncSession, test_user: User, test_workspace):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.archive_workspace(session, test_workspace.id, test_user.id)+ assert exc.value.status_code == 400+ assert "last workspace" in exc.value.detail.lower()+++async def test_archive_workspace_succeeds_with_other(session: AsyncSession, test_user: User, test_workspace):+ second = await workspace_service.create_workspace(+ session, name="Second", creator=test_user, self_membership=True, seed_defaults=False+ )+ await session.commit()+ archived = await workspace_service.archive_workspace(+ session, test_workspace.id, test_user.id+ )+ await session.commit()+ assert archived.is_archived is True++ # Archiving an already-archived workspace is a no-op return.+ again = await workspace_service.archive_workspace(+ session, test_workspace.id, test_user.id+ )+ assert again.is_archived is True+++async def test_archive_workspace_not_found(session: AsyncSession, test_user: User):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.archive_workspace(session, uuid.uuid4(), test_user.id)+ assert exc.value.status_code == 404+++async def test_remove_member_not_found(session: AsyncSession, test_workspace):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.remove_member(session, test_workspace.id, uuid.uuid4())+ assert exc.value.status_code == 404+++async def test_remove_member_non_owner_succeeds(session: AsyncSession, test_user: User, test_workspace):+ other = await _make_user(session, "[email protected]")+ await session.commit()+ await workspace_service.add_member(+ session, test_workspace.id, other.id, role="editor"+ )+ await session.commit()+ await workspace_service.remove_member(session, test_workspace.id, other.id)+ await session.commit()+ assert await workspace_service.get_membership(session, test_workspace.id, other.id) is None+++async def test_remove_sole_owner_blocked(session: AsyncSession, test_user: User, test_workspace):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.remove_member(session, test_workspace.id, test_user.id)+ assert exc.value.status_code == 400+ assert "sole owner" in exc.value.detail.lower()+++async def test_remove_owner_succeeds_with_co_owner(session: AsyncSession, test_user: User, test_workspace):+ other = await _make_user(session, "[email protected]")+ await session.commit()+ await workspace_service.add_member(+ session, test_workspace.id, other.id, role="owner"+ )+ await session.commit()+ # With a second owner, removing one owner is allowed.+ await workspace_service.remove_member(session, test_workspace.id, other.id)+ await session.commit()+ assert await workspace_service.get_membership(session, test_workspace.id, other.id) is None+++async def test_demote_sole_owner_blocked(session: AsyncSession, test_user: User, test_workspace):+ with pytest.raises(HTTPException) as exc:+ await workspace_service.update_member_role(+ session, test_workspace.id, test_user.id, "viewer"+ )+ assert exc.value.status_code == 400+++async def test_list_members_empty(session: AsyncSession):+ ws = Workspace(+ id=uuid.uuid4(),+ name="EmptyWs",+ kind="personal",+ default_currency="USD",+ )+ session.add(ws)+ await session.commit()+ assert await workspace_service.list_members(session, ws.id) == []+++async def test_is_workspace_manager(session: AsyncSession, test_user: User):+ ws = await workspace_service.create_workspace(+ session, name="MgrCheck", creator=test_user, seed_defaults=False+ )+ await session.commit()+ assert await workspace_service.is_workspace_manager(session, ws.id, test_user.id) is True+ assert await workspace_service.is_workspace_manager(session, ws.id, uuid.uuid4()) is False+++async def test_get_membership_none(session: AsyncSession, test_workspace):+ assert await workspace_service.get_membership(+ session, test_workspace.id, uuid.uuid4()+ ) is None+++async def test_require_membership_manager_path_and_role_floor(session: AsyncSession):+ """A manager (no membership row) gets virtual owner access and passes+ the owner floor; a stranger is rejected with 404."""+ manager = await _make_user(session, "[email protected]")+ ws = Workspace(+ id=uuid.uuid4(),+ name="Mgr",+ kind="personal",+ created_by_user_id=manager.id,+ managed_by_user_id=manager.id,+ default_currency="USD",+ )+ session.add(ws)+ await session.commit()++ member = await workspace_service.require_membership(session, ws.id, manager.id)+ assert member.role == "manager"++ member = await workspace_service.require_membership(+ session, ws.id, manager.id, min_role="owner"+ )+ assert member.role == "manager"++ with pytest.raises(HTTPException) as exc:+ await workspace_service.require_membership(session, ws.id, uuid.uuid4())+ assert exc.value.status_code == 404+++async def test_require_membership_viewer_role_floor_403(session: AsyncSession, test_user: User, test_workspace):+ viewer = await _make_user(session, "[email protected]")+ await session.commit()+ await workspace_service.add_member(+ session, test_workspace.id, viewer.id, role="viewer"+ )+ await session.commit()+ # Viewer trying for editor floor -> 403.+ with pytest.raises(HTTPException) as exc:+ await workspace_service.require_membership(+ session, test_workspace.id, viewer.id, min_role="editor"+ )+ assert exc.value.status_code == 403+++async def test_create_personal_workspace_english_name(session: AsyncSession):+ """A non-pt user gets the English 'Personal' name; idempotent on repeat."""+ user = await _make_user(session, "[email protected]")+ user.preferences = {"language": "en", "currency_display": "USD"}+ await session.flush()+ ws1 = await workspace_service.create_personal_workspace_for_user(+ session, user, commit=True+ )+ assert ws1.name == "Personal"+ # Second call returns the existing one (idempotent found branch).+ ws2 = await workspace_service.create_personal_workspace_for_user(+ session, user, commit=True+ )+ assert ws2.id == ws1.iddiff --git a/backend/tests/test_workspaces_api_coverage.py b/backend/tests/test_workspaces_api_coverage.pynew file mode 100644index 00000000..ef631a21--- /dev/null+++ b/backend/tests/test_workspaces_api_coverage.py@@ -0,0 +1,264 @@+"""Coverage-focused API tests for app/api/workspaces.py.++Exercises list/create/get-current/update, member invite/list/role-change/+remove, stats, and archive — plus the error branches (404, 403, 400).+"""+import uuid++import pytest+from httpx import AsyncClient+++# ---------------------------------------------------------------------------+# list / create / current+# ---------------------------------------------------------------------------+async def test_list_my_workspaces(client: AsyncClient, auth_headers, test_user):+ resp = await client.get("/api/workspaces", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert isinstance(body, list)+ assert len(body) >= 1+ # The auto-created Personal workspace reports the owner role.+ assert any(w["role"] == "owner" for w in body)+++async def test_unauthenticated_returns_401(client: AsyncClient):+ resp = await client.get("/api/workspaces")+ assert resp.status_code == 401+++async def test_create_workspace_with_self_membership(client: AsyncClient, auth_headers, test_user):+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={+ "name": "Side Business",+ "kind": "small_business",+ "default_currency": "EUR",+ "self_membership": True,+ },+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert body["name"] == "Side Business"+ assert body["default_currency"] == "EUR"+ assert body["role"] == "owner"++ # It now shows up in the listing.+ resp = await client.get("/api/workspaces", headers=auth_headers)+ assert any(w["id"] == body["id"] for w in resp.json())+++async def test_create_workspace_manager_only(client: AsyncClient, auth_headers, test_user):+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Client Books", "self_membership": False},+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert body["role"] == "manager"+ # Manager-only workspaces still appear in the listing via managed union.+ resp = await client.get("/api/workspaces", headers=auth_headers)+ assert any(w["id"] == body["id"] and w["role"] == "manager" for w in resp.json())+++async def test_create_workspace_validation_422(client: AsyncClient, auth_headers, test_user):+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "", "default_currency": "TOOLONG"},+ )+ assert resp.status_code == 422+++async def test_get_current_workspace(client: AsyncClient, auth_headers, test_user):+ resp = await client.get("/api/workspaces/current", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["kind"] == "personal"+ assert body["role"] in {"owner", "manager", "editor", "viewer"}+++# ---------------------------------------------------------------------------+# update+# ---------------------------------------------------------------------------+async def test_update_workspace(client: AsyncClient, auth_headers, test_workspace):+ resp = await client.patch(+ f"/api/workspaces/{test_workspace.id}",+ headers=auth_headers,+ json={"name": "Renamed", "color": "#123456"},+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["name"] == "Renamed"+ assert body["color"] == "#123456"+ assert body["role"] == "owner"+++async def test_update_workspace_not_member_404(client: AsyncClient, auth_headers, test_user):+ # A random workspace id the user has no membership/management on.+ resp = await client.patch(+ f"/api/workspaces/{uuid.uuid4()}",+ headers=auth_headers,+ json={"name": "Nope"},+ )+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# members+# ---------------------------------------------------------------------------+async def test_list_members(client: AsyncClient, auth_headers, test_workspace, test_user):+ resp = await client.get(+ f"/api/workspaces/{test_workspace.id}/members", headers=auth_headers+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert any(m["email"] == "[email protected]" and m["role"] == "owner" for m in body)+++async def test_invite_new_user_member(client: AsyncClient, auth_headers, test_workspace):+ resp = await client.post(+ f"/api/workspaces/{test_workspace.id}/members",+ headers=auth_headers,+ json={"email": "[email protected]", "role": "editor", "password": "supersecret123"},+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert body["email"] == "[email protected]"+ assert body["role"] == "editor"+++async def test_invite_unknown_user_without_password_400(client: AsyncClient, auth_headers, test_workspace):+ resp = await client.post(+ f"/api/workspaces/{test_workspace.id}/members",+ headers=auth_headers,+ json={"email": "[email protected]", "role": "editor"},+ )+ assert resp.status_code == 400+++async def test_invite_member_into_unknown_workspace_404(client: AsyncClient, auth_headers, test_user):+ resp = await client.post(+ f"/api/workspaces/{uuid.uuid4()}/members",+ headers=auth_headers,+ json={"email": "[email protected]", "role": "editor", "password": "supersecret123"},+ )+ assert resp.status_code == 404+++async def test_change_member_role_and_remove(client: AsyncClient, auth_headers, test_workspace):+ # Invite a brand-new member.+ invite = await client.post(+ f"/api/workspaces/{test_workspace.id}/members",+ headers=auth_headers,+ json={"email": "[email protected]", "role": "editor", "password": "supersecret123"},+ )+ assert invite.status_code == 201, invite.text+ member_user_id = invite.json()["user_id"]++ # Promote them to viewer.+ resp = await client.patch(+ f"/api/workspaces/{test_workspace.id}/members/{member_user_id}",+ headers=auth_headers,+ json={"role": "viewer"},+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["role"] == "viewer"++ # Remove them.+ resp = await client.delete(+ f"/api/workspaces/{test_workspace.id}/members/{member_user_id}",+ headers=auth_headers,+ )+ assert resp.status_code == 204+++async def test_change_role_invalid_role_400(client: AsyncClient, auth_headers, test_workspace):+ invite = await client.post(+ f"/api/workspaces/{test_workspace.id}/members",+ headers=auth_headers,+ json={"email": "[email protected]", "role": "editor", "password": "supersecret123"},+ )+ member_user_id = invite.json()["user_id"]+ resp = await client.patch(+ f"/api/workspaces/{test_workspace.id}/members/{member_user_id}",+ headers=auth_headers,+ json={"role": "supreme_leader"},+ )+ assert resp.status_code == 400+++async def test_demote_sole_owner_400(client: AsyncClient, auth_headers, test_workspace, test_user):+ resp = await client.patch(+ f"/api/workspaces/{test_workspace.id}/members/{test_user.id}",+ headers=auth_headers,+ json={"role": "editor"},+ )+ assert resp.status_code == 400+++async def test_remove_sole_owner_400(client: AsyncClient, auth_headers, test_workspace, test_user):+ resp = await client.delete(+ f"/api/workspaces/{test_workspace.id}/members/{test_user.id}",+ headers=auth_headers,+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# stats / archive+# ---------------------------------------------------------------------------+async def test_workspace_stats(client: AsyncClient, auth_headers, test_workspace):+ resp = await client.get(+ f"/api/workspaces/{test_workspace.id}/stats", headers=auth_headers+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["members"] >= 1+ assert "accounts" in body+ assert "transactions" in body+++async def test_archive_last_workspace_400(client: AsyncClient, auth_headers, test_workspace):+ # The personal workspace is the user's only one -> can't archive it.+ resp = await client.post(+ f"/api/workspaces/{test_workspace.id}/archive", headers=auth_headers+ )+ assert resp.status_code == 400+++async def test_archive_workspace_success(client: AsyncClient, auth_headers, test_workspace):+ # Create a second member-owned workspace so archiving the first is allowed.+ second = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Second", "self_membership": True},+ )+ assert second.status_code == 201, second.text++ resp = await client.post(+ f"/api/workspaces/{test_workspace.id}/archive", headers=auth_headers+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["is_archived"] is True