Skip to content

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

ci: add coverage badge via gist + shields.io

Tássio Noronha151d1321efe4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fcc13bed..2ffe44a7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -41,6 +41,26 @@ jobs:
name: coverage-report
path: backend/coverage.xml
+ - name: Extract coverage percentage
+ if: github.ref == 'refs/heads/main'
+ id: coverage
+ run: |
+ COVERAGE=$(python -c "import xml.etree.ElementTree as ET; print(round(float(ET.parse('coverage.xml').getroot().attrib['line-rate']) * 100))")
+ echo "percentage=$COVERAGE" >> $GITHUB_OUTPUT
+
+ - name: Update coverage badge
+ if: github.ref == 'refs/heads/main'
+ uses: schneegans/[email protected]
+ with:
+ auth: ${{ secrets.GIST_TOKEN }}
+ gistID: ae627b744aaa2ba89d850ea541c311be
+ filename: coverage.json
+ label: coverage
+ message: ${{ steps.coverage.outputs.percentage }}%
+ valColorRange: ${{ steps.coverage.outputs.percentage }}
+ minColorRange: 50
+ maxColorRange: 90
+
frontend-checks:
name: Frontend Checks
runs-on: ubuntu-latest
diff --git a/README.md b/README.md
index cf2b0350..328b17f7 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,7 @@
<h1 align="center">Securo</h1>
<p align="center">
<a href="https://github.com/securo-finance/securo/actions/workflows/ci.yml"><img src="https://github.com/securo-finance/securo/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
+ <img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/tassionoronha/ae627b744aaa2ba89d850ea541c311be/raw/coverage.json" alt="Coverage" />
<a href="https://www.gnu.org/licenses/agpl-3.0"><img src="https://img.shields.io/badge/License-AGPL--3.0-blue.svg" alt="License: AGPL-3.0" /></a>
<br />
<a href="https://usesecuro.com/">Website</a> · <a href="https://github.com/orgs/securo-finance/projects/2">Roadmap</a>
diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.py
new file mode 100644
index 00000000..e4172235
--- /dev/null
+++ b/backend/tests/test_account_service.py
@@ -0,0 +1,603 @@
+"""Service-level tests for account_service.
+
+Directly exercises the service functions to ensure full coverage of:
+- create_account (with balance, zero balance, credit_card type)
+- update_account (rename, balance change, sync opening_balance, bank-connected rejection)
+- delete_account (manual, bank-connected rejection, not found)
+- close_account / reopen_account
+- get_account_summary (manual, bank-connected, credit_card, date range)
+- get_account_balance_history
+- _account_balance_at / _account_daily_balance_series
+"""
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.transaction import Transaction
+from app.schemas.account import AccountCreate, AccountUpdate
+from app.services.account_service import (
+ create_account,
+ close_account,
+ delete_account,
+ get_account,
+ get_account_balance_history,
+ get_account_summary,
+ get_accounts,
+ reopen_account,
+ update_account,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+async def _make_account(
+ session: AsyncSession, user_id: uuid.UUID,
+ name: str = "Test Account", acc_type: str = "checking",
+ balance: str = "0.00", currency: str = "BRL",
+ connection_id: uuid.UUID | None = None,
+ external_id: str | None = None,
+) -> Account:
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ name=name,
+ type=acc_type,
+ balance=Decimal(balance),
+ currency=currency,
+ connection_id=connection_id,
+ external_id=external_id,
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+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", transfer_pair_id: uuid.UUID | None = None,
+) -> Transaction:
+ from datetime import datetime, timezone
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ account_id=account_id,
+ description=f"Test {txn_type} {amount}",
+ amount=Decimal(str(amount)),
+ date=txn_date,
+ type=txn_type,
+ source=source,
+ currency="BRL",
+ transfer_pair_id=transfer_pair_id,
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+ await session.refresh(txn)
+ return txn
+
+
+# ---------------------------------------------------------------------------
+# create_account
+# ---------------------------------------------------------------------------
+
+
+async def test_create_account_with_balance(session: AsyncSession, test_user):
+ """Creating an account with balance > 0 creates an opening_balance transaction."""
+ data = AccountCreate(name="Checking", type="checking", balance=Decimal("1000.00"), currency="BRL")
+ account = await create_account(session, test_user.id, data)
+
+ assert account.name == "Checking"
+ assert account.balance == Decimal("1000.00")
+
+ # Verify opening_balance transaction was created
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one_or_none()
+ assert opening is not None
+ assert opening.amount == Decimal("1000.00")
+ assert opening.type == "credit"
+
+
+async def test_create_credit_card_account_opening_is_debit(session: AsyncSession, test_user):
+ """Credit card opening balance is recorded as debit (represents debt)."""
+ data = AccountCreate(name="Nubank", type="credit_card", balance=Decimal("500.00"), currency="BRL")
+ account = await create_account(session, test_user.id, data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.type == "debit"
+ assert opening.amount == Decimal("500.00")
+
+
+async def test_create_account_zero_balance_no_opening(session: AsyncSession, test_user):
+ """Creating an account with zero balance creates no opening transaction."""
+ data = AccountCreate(name="Empty", type="checking", balance=Decimal("0.00"), currency="BRL")
+ account = await create_account(session, test_user.id, data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ assert result.scalar_one_or_none() is None
+
+
+async def test_create_account_with_balance_date(session: AsyncSession, test_user):
+ """Opening transaction uses the provided balance_date."""
+ custom_date = date(2025, 1, 15)
+ data = AccountCreate(
+ name="Dated", type="checking", balance=Decimal("2000.00"),
+ currency="BRL", balance_date=custom_date,
+ )
+ account = await create_account(session, test_user.id, data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.date == custom_date
+
+
+# ---------------------------------------------------------------------------
+# update_account
+# ---------------------------------------------------------------------------
+
+
+async def test_update_account_name(session: AsyncSession, test_user):
+ """Updating account name works for manual accounts."""
+ account = await _make_account(session, test_user.id, "Old Name")
+ data = AccountUpdate(name="New Name")
+ updated = await update_account(session, account.id, test_user.id, data)
+
+ assert updated is not None
+ assert updated.name == "New Name"
+
+
+async def test_update_account_balance_creates_opening(session: AsyncSession, test_user):
+ """Updating balance on an account with no opening_balance creates one."""
+ account = await _make_account(session, test_user.id, "No Balance", balance="0.00")
+ data = AccountUpdate(balance=Decimal("500.00"))
+ updated = await update_account(session, account.id, test_user.id, data)
+
+ assert updated is not None
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.amount == Decimal("500.00")
+ assert opening.type == "credit"
+
+
+async def test_update_account_balance_updates_existing_opening(session: AsyncSession, test_user):
+ """Updating balance when opening_balance exists updates it."""
+ data = AccountCreate(name="Update Test", type="checking", balance=Decimal("1000.00"), currency="BRL")
+ account = await create_account(session, test_user.id, data)
+
+ update_data = AccountUpdate(balance=Decimal("2000.00"))
+ await update_account(session, account.id, test_user.id, update_data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.amount == Decimal("2000.00")
+
+
+async def test_update_account_balance_to_zero_removes_opening(session: AsyncSession, test_user):
+ """Setting balance to 0 removes the opening_balance transaction."""
+ data = AccountCreate(name="Zero Test", type="checking", balance=Decimal("500.00"), currency="BRL")
+ account = await create_account(session, test_user.id, data)
+
+ update_data = AccountUpdate(balance=Decimal("0.00"))
+ await update_account(session, account.id, test_user.id, update_data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ assert result.scalar_one_or_none() is None
+
+
+async def test_update_account_balance_with_date(session: AsyncSession, test_user):
+ """Updating balance with balance_date updates the opening tx date."""
+ data = AccountCreate(name="Date Test", type="checking", balance=Decimal("1000.00"), currency="BRL")
+ account = await create_account(session, test_user.id, data)
+
+ new_date = date(2025, 6, 15)
+ update_data = AccountUpdate(balance=Decimal("1500.00"), balance_date=new_date)
+ await update_account(session, account.id, test_user.id, update_data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.date == new_date
+ assert opening.amount == Decimal("1500.00")
+
+
+async def test_update_bank_connected_raises(session: AsyncSession, test_user, test_connection):
+ """Updating a bank-connected account raises ValueError."""
+ account = await _make_account(
+ session, test_user.id, "Connected",
+ connection_id=test_connection.id, external_id="ext-1",
+ )
+ data = AccountUpdate(name="Hacked")
+ with pytest.raises(ValueError, match="bank-connected"):
+ await update_account(session, account.id, test_user.id, data)
+
+
+async def test_update_account_not_found(session: AsyncSession, test_user):
+ """Updating nonexistent account returns None."""
+ data = AccountUpdate(name="Ghost")
+ result = await update_account(session, uuid.uuid4(), test_user.id, data)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# delete_account
+# ---------------------------------------------------------------------------
+
+
+async def test_delete_manual_account(session: AsyncSession, test_user):
+ """Deleting a manual account returns True."""
+ account = await _make_account(session, test_user.id, "To Delete")
+ result = await delete_account(session, account.id, test_user.id)
+ assert result is True
+
+ # Verify it's gone
+ assert await get_account(session, account.id, test_user.id) is None
+
+
+async def test_delete_bank_connected_raises(session: AsyncSession, test_user, test_connection):
+ """Deleting a bank-connected account raises ValueError."""
+ account = await _make_account(
+ session, test_user.id, "Connected",
+ connection_id=test_connection.id, external_id="ext-del",
+ )
+ with pytest.raises(ValueError, match="bank-connected"):
+ await delete_account(session, account.id, test_user.id)
+
+
+async def test_delete_account_not_found(session: AsyncSession, test_user):
+ """Deleting nonexistent account returns False."""
+ result = await delete_account(session, uuid.uuid4(), test_user.id)
+ assert result is False
+
+
+# ---------------------------------------------------------------------------
+# close_account / reopen_account
+# ---------------------------------------------------------------------------
+
+
+async def test_close_account(session: AsyncSession, test_user):
+ """Closing a manual account sets is_closed and closed_at."""
+ account = await _make_account(session, test_user.id, "To Close")
+ closed = await close_account(session, account.id, test_user.id)
+
+ assert closed is not None
+ assert closed.is_closed is True
+ assert closed.closed_at is not None
+
+
+async def test_close_bank_connected_unlinks(session: AsyncSession, test_user, test_connection):
+ """Closing bank-connected account sets connection_id to None."""
+ account = await _make_account(
+ session, test_user.id, "Connected Close",
+ connection_id=test_connection.id, external_id="ext-close",
+ )
+ closed = await close_account(session, account.id, test_user.id)
+ assert closed.connection_id is None
+ assert closed.is_closed is True
+
+
+async def test_close_already_closed_raises(session: AsyncSession, test_user):
+ """Closing an already-closed account raises ValueError."""
+ account = await _make_account(session, test_user.id, "Already Closed")
+ await close_account(session, account.id, test_user.id)
+
+ with pytest.raises(ValueError, match="already closed"):
+ await close_account(session, account.id, test_user.id)
+
+
+async def test_close_not_found(session: AsyncSession, test_user):
+ """Closing nonexistent account returns None."""
+ result = await close_account(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_reopen_account(session: AsyncSession, test_user):
+ """Reopening a closed account clears is_closed and closed_at."""
+ account = await _make_account(session, test_user.id, "Reopen Test")
+ await close_account(session, account.id, test_user.id)
+
+ reopened = await reopen_account(session, account.id, test_user.id)
+ assert reopened is not None
+ assert reopened.is_closed is False
+ assert reopened.closed_at is None
+
+
+async def test_reopen_not_closed_raises(session: AsyncSession, test_user):
+ """Reopening a non-closed account raises ValueError."""
+ account = await _make_account(session, test_user.id, "Open")
+ with pytest.raises(ValueError, match="not closed"):
+ await reopen_account(session, account.id, test_user.id)
+
+
+async def test_reopen_not_found(session: AsyncSession, test_user):
+ """Reopening nonexistent account returns None."""
+ result = await reopen_account(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# get_accounts
+# ---------------------------------------------------------------------------
+
+
+async def test_get_accounts_returns_list(session: AsyncSession, test_user):
+ """get_accounts returns list with current_balance and previous_balance."""
+ account = await _make_account(session, test_user.id, "List Test", balance="1000.00")
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", date.today(), source="opening_balance")
+
+ accounts = await get_accounts(session, test_user.id)
+ assert len(accounts) >= 1
+ acc = next(a for a in accounts if a["id"] == account.id)
+ assert acc["name"] == "List Test"
+ assert "current_balance" in acc
+ assert "previous_balance" in acc
+
+
+async def test_get_accounts_excludes_closed(session: AsyncSession, test_user):
+ """get_accounts excludes closed accounts by default."""
+ account = await _make_account(session, test_user.id, "Closed Account")
+ await close_account(session, account.id, test_user.id)
+
+ accounts = await get_accounts(session, test_user.id)
+ ids = [a["id"] for a in accounts]
+ assert account.id not in ids
+
+
+async def test_get_accounts_includes_closed_when_requested(session: AsyncSession, test_user):
+ """get_accounts includes closed accounts when include_closed=True."""
+ account = await _make_account(session, test_user.id, "Closed Visible")
+ await close_account(session, account.id, test_user.id)
+
+ accounts = await get_accounts(session, test_user.id, include_closed=True)
+ ids = [a["id"] for a in accounts]
+ assert account.id in ids
+
+
+async def test_get_accounts_credit_card_negated_balance(session: AsyncSession, test_user, test_connection):
+ """Bank-connected credit_card current_balance is negated."""
+ account = await _make_account(
+ session, test_user.id, "CC Connected",
+ acc_type="credit_card", balance="3000.00",
+ connection_id=test_connection.id, external_id="ext-cc",
+ )
+ accounts = await get_accounts(session, test_user.id)
+ cc = next(a for a in accounts if a["id"] == account.id)
+ # For bank-connected CC: current_balance = -balance
+ assert cc["current_balance"] == pytest.approx(-3000.0)
+
+
+# ---------------------------------------------------------------------------
+# get_account_summary
+# ---------------------------------------------------------------------------
+
+
+async def test_get_account_summary_manual(session: AsyncSession, test_user):
+ """Summary for manual account computes balance from transactions."""
+ account = await _make_account(session, test_user.id, "Summary Test")
+ today = date.today()
+
+ # Add opening balance and some transactions
+ await _add_txn(session, test_user.id, account.id, 5000, "credit", today, source="opening_balance")
+ await _add_txn(session, test_user.id, account.id, 200, "debit", today)
+ await _add_txn(session, test_user.id, account.id, 100, "credit", today)
+
+ summary = await get_account_summary(session, account.id, test_user.id)
+ assert summary is not None
+ assert summary["current_balance"] == pytest.approx(4900.0) # 5000 - 200 + 100
+ assert summary["monthly_income"] == pytest.approx(100.0) # excludes opening_balance
+ assert summary["monthly_expenses"] == pytest.approx(200.0)
+
+
+async def test_get_account_summary_bank_connected(session: AsyncSession, test_user, test_connection):
+ """Summary for bank-connected account uses stored balance."""
+ account = await _make_account(
+ session, test_user.id, "Connected Summary",
+ balance="7500.00",
+ connection_id=test_connection.id, external_id="ext-sum",
+ )
+ summary = await get_account_summary(session, account.id, test_user.id)
+ assert summary is not None
+ assert summary["current_balance"] == pytest.approx(7500.0)
+
+
+async def test_get_account_summary_credit_card_bank(session: AsyncSession, test_user, test_connection):
+ """Bank-connected credit_card summary negates balance."""
+ account = await _make_account(
+ session, test_user.id, "CC Bank",
+ acc_type="credit_card", balance="2000.00",
+ connection_id=test_connection.id, external_id="ext-cc-sum",
+ )
+ summary = await get_account_summary(session, account.id, test_user.id)
+ assert summary is not None
+ assert summary["current_balance"] == pytest.approx(-2000.0)
+
+
+async def test_get_account_summary_with_date_range(session: AsyncSession, test_user):
+ """Summary filters income/expenses by date range."""
+ account = await _make_account(session, test_user.id, "Date Range Test")
+ today = date.today()
+ last_month = (today.replace(day=1) - timedelta(days=1)).replace(day=15)
+
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", last_month)
+ await _add_txn(session, test_user.id, account.id, 500, "credit", today)
+
+ # Query only this month
+ summary = await get_account_summary(
+ session, account.id, test_user.id,
+ date_from=today.replace(day=1), date_to=today,
+ )
+ assert summary is not None
+ assert summary["monthly_income"] == pytest.approx(500.0)
+
+
+async def test_get_account_summary_excludes_transfers(session: AsyncSession, test_user):
+ """Summary excludes transfer pair transactions from income/expenses."""
+ account = await _make_account(session, test_user.id, "Transfer Exclude")
+ today = date.today()
+ pair_id = uuid.uuid4()
+
+ await _add_txn(session, test_user.id, account.id, 300, "debit", today, transfer_pair_id=pair_id)
+ await _add_txn(session, test_user.id, account.id, 100, "debit", today)
+
+ summary = await get_account_summary(session, account.id, test_user.id)
+ assert summary is not None
+ # Only the non-transfer debit counts
+ assert summary["monthly_expenses"] == pytest.approx(100.0)
+
+
+async def test_get_account_summary_not_found(session: AsyncSession, test_user):
+ """Summary for nonexistent account returns None."""
+ result = await get_account_summary(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# get_account_balance_history
+# ---------------------------------------------------------------------------
+
+
+async def test_get_account_balance_history(session: AsyncSession, test_user):
+ """Balance history returns daily balance series."""
+ account = await _make_account(session, test_user.id, "History Test")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", today.replace(day=1), source="opening_balance")
+ await _add_txn(session, test_user.id, account.id, 200, "debit", today.replace(day=min(5, today.day)))
+
+ history = await get_account_balance_history(
+ session, account.id, test_user.id,
+ date_from=today.replace(day=1), date_to=today,
+ )
+ assert history is not None
+ assert len(history) > 0
+ # Each entry has date and balance
+ assert "date" in history[0]
+ assert "balance" in history[0]
+
+
+async def test_get_account_balance_history_not_found(session: AsyncSession, test_user):
+ """Balance history for nonexistent account returns None."""
+ result = await get_account_balance_history(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_get_account_balance_history_default_dates(session: AsyncSession, test_user):
+ """Balance history uses current month if no dates provided."""
+ account = await _make_account(session, test_user.id, "Default Dates")
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", date.today(), source="opening_balance")
+
+ history = await get_account_balance_history(session, account.id, test_user.id)
+ assert history is not None
+ assert len(history) > 0
+
+
+async def test_get_account_balance_history_credit_card_negated(
+ session: AsyncSession, test_user, test_connection,
+):
+ """Balance history for bank-connected credit_card applies sign negation."""
+ account = await _make_account(
+ session, test_user.id, "CC History",
+ acc_type="credit_card", balance="1000.00",
+ connection_id=test_connection.id, external_id="ext-cc-hist",
+ )
+ today = date.today()
+ await _add_txn(session, test_user.id, account.id, 500, "debit", today)
+
+ history = await get_account_balance_history(
+ session, account.id, test_user.id,
+ date_from=today, date_to=today,
+ )
+ assert history is not None
+ assert len(history) == 1
+ # CC with connection_id has sign=-1.0: a debit (spending) on CC
+ # produces negative balance, negated to positive (showing debt increase)
+ assert history[0]["balance"] == pytest.approx(500.0)
diff --git a/backend/tests/test_api_extended.py b/backend/tests/test_api_extended.py
new file mode 100644
index 00000000..9fbc23f3
--- /dev/null
+++ b/backend/tests/test_api_extended.py
@@ -0,0 +1,647 @@
+"""Extended API tests covering missing lines in transactions, rules, assets,
+accounts, and import endpoints."""
+import uuid
+from datetime import date
+
+import pytest
+from httpx import AsyncClient
+
+from app.models.account import Account
+from app.models.transaction import Transaction
+
+
+# ---------------------------------------------------------------------------
+# Transactions API — export and bulk categorize
+# ---------------------------------------------------------------------------
+
+
+async def test_export_transactions_csv(
+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],
+):
+ """GET /api/transactions/export returns CSV with proper headers."""
+ response = await client.get("/api/transactions/export", headers=auth_headers)
+ assert response.status_code == 200
+ assert "text/csv" in response.headers["content-type"]
+ content = response.text
+ # Should have header row + transaction rows
+ lines = content.strip().split("\n")
+ assert len(lines) > 1
+ header = lines[0].replace("\ufeff", "") # Remove BOM
+ assert "date" in header
+ assert "description" in header
+ assert "amount" in header
+
+
+async def test_export_transactions_with_filters(
+ client: AsyncClient, auth_headers, test_transactions, test_account,
+):
+ """Export with filters returns filtered results."""
+ response = await client.get(
+ "/api/transactions/export",
+ params={"account_id": str(test_account.id)},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert "text/csv" in response.headers["content-type"]
+
+
+async def test_export_transactions_with_search(
+ client: AsyncClient, auth_headers, test_transactions,
+):
+ """Export with search query returns filtered results."""
+ response = await client.get(
+ "/api/transactions/export",
+ params={"q": "UBER"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ content = response.text
+ assert "UBER" in content
+
+
+async def test_export_transactions_by_type(
+ client: AsyncClient, auth_headers, test_transactions,
+):
+ """Export filtered by type."""
+ response = await client.get(
+ "/api/transactions/export",
+ params={"type": "debit"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert "text/csv" in response.headers["content-type"]
+
+
+async def test_export_uncategorized(
+ client: AsyncClient, auth_headers, test_transactions,
+):
+ """Export uncategorized transactions."""
+ response = await client.get(
+ "/api/transactions/export",
+ params={"uncategorized": "true"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+
+
+async def test_bulk_categorize(
+ client: AsyncClient, auth_headers, test_transactions, test_categories,
+):
+ """PATCH /api/transactions/bulk-categorize updates multiple transactions."""
+ # Get uncategorized transactions (NETFLIX and PIX RECEBIDO)
+ uncategorized_ids = [
+ str(t.id) for t in test_transactions if t.category_id is None
+ ]
+ assert len(uncategorized_ids) >= 1
+
+ response = await client.patch(
+ "/api/transactions/bulk-categorize",
+ headers=auth_headers,
+ json={
+ "transaction_ids": uncategorized_ids,
+ "category_id": str(test_categories[0].id),
+ },
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["updated"] == len(uncategorized_ids)
+
+
+async def test_update_transaction_not_found(
+ client: AsyncClient, auth_headers, test_transactions,
+):
+ """PATCH nonexistent transaction returns 404."""
+ response = await client.patch(
+ "/api/transactions/00000000-0000-0000-0000-000000000000",
+ headers=auth_headers,
+ json={"description": "Ghost"},
+ )
+ assert response.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Rules API — missing coverage
+# ---------------------------------------------------------------------------
+
+
+async def test_create_duplicate_rule(
+ client: AsyncClient, auth_headers, test_rules, test_categories,
+):
+ """Creating a rule with duplicate name returns 409."""
+ existing_name = test_rules[0].name
+ response = await client.post(
+ "/api/rules",
+ headers=auth_headers,
+ json={
+ "name": existing_name,
+ "conditions_op": "and",
+ "conditions": [{"field": "description", "op": "contains", "value": "TEST"}],
+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],
+ "priority": 5,
+ },
+ )
+ assert response.status_code == 409
+
+
+async def test_update_rule_not_found(client: AsyncClient, auth_headers, test_rules):
+ """PATCH nonexistent rule returns 404."""
+ response = await client.patch(
+ "/api/rules/00000000-0000-0000-0000-000000000000",
+ headers=auth_headers,
+ json={"name": "Ghost"},
+ )
+ assert response.status_code == 404
+
+
+async def test_delete_rule_not_found(client: AsyncClient, auth_headers, test_rules):
+ """DELETE nonexistent rule returns 404."""
+ response = await client.delete(
+ "/api/rules/00000000-0000-0000-0000-000000000000",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_list_rule_packs(client: AsyncClient, auth_headers, test_rules):
+ """GET /api/rules/packs returns available rule packs."""
+ response = await client.get("/api/rules/packs", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert isinstance(data, list)
+ # Each pack has expected fields
+ for pack in data:
+ assert "code" in pack
+ assert "name" in pack
+ assert "flag" in pack
+ assert "rule_count" in pack
+ assert "installed" in pack
+
+
+async def test_install_rule_pack(client: AsyncClient, auth_headers, test_categories):
+ """POST /api/rules/packs/{code}/install installs a rule pack."""
+ # First list packs to get a valid code
+ packs_resp = await client.get("/api/rules/packs", headers=auth_headers)
+ packs = packs_resp.json()
+ if not packs:
+ pytest.skip("No rule packs available")
+
+ pack_code = packs[0]["code"]
+ response = await client.post(
+ f"/api/rules/packs/{pack_code}/install",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert "installed" in response.json()
+
+
+async def test_install_rule_pack_not_found(client: AsyncClient, auth_headers, test_categories):
+ """POST /api/rules/packs/nonexistent/install returns 404."""
+ response = await client.post(
+ "/api/rules/packs/nonexistent/install",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Accounts API — balance-history and additional endpoints
+# ---------------------------------------------------------------------------
+
+
+async def test_account_balance_history_api(client: AsyncClient, auth_headers):
+ """GET /api/accounts/{id}/balance-history returns daily series."""
+ # Create account with transactions
+ acc_resp = await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "Hist API", "type": "checking", "balance": 1000, "currency": "BRL"},
+ )
+ assert acc_resp.status_code == 201
+ account_id = acc_resp.json()["id"]
+
+ response = await client.get(
+ f"/api/accounts/{account_id}/balance-history",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert isinstance(data, list)
+ assert len(data) > 0
+ assert "date" in data[0]
+ assert "balance" in data[0]
+
+
+async def test_account_balance_history_with_dates(client: AsyncClient, auth_headers):
+ """Balance history with custom date range."""
+ acc_resp = await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "Date Hist", "type": "checking", "balance": 500, "currency": "BRL"},
+ )
+ account_id = acc_resp.json()["id"]
+ today = date.today()
+
+ response = await client.get(
+ f"/api/accounts/{account_id}/balance-history",
+ params={
+ "from": today.replace(day=1).isoformat(),
+ "to": today.isoformat(),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+
+
+async def test_account_balance_history_not_found(client: AsyncClient, auth_headers):
+ """Balance history for nonexistent account returns 404."""
+ response = await client.get(
+ "/api/accounts/00000000-0000-0000-0000-000000000000/balance-history",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_account_summary_with_date_params(client: AsyncClient, auth_headers):
+ """Account summary accepts from/to date parameters."""
+ acc_resp = await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "Sum Dates", "type": "checking", "balance": 0, "currency": "BRL"},
+ )
+ account_id = acc_resp.json()["id"]
+ today = date.today()
+
+ response = await client.get(
+ f"/api/accounts/{account_id}/summary",
+ params={
+ "from": today.replace(day=1).isoformat(),
+ "to": today.isoformat(),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+
+
+async def test_close_account_api_not_found(client: AsyncClient, auth_headers):
+ """Close nonexistent account returns 404."""
+ response = await client.post(
+ "/api/accounts/00000000-0000-0000-0000-000000000000/close",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_reopen_account_api_not_found(client: AsyncClient, auth_headers):
+ """Reopen nonexistent account returns 404."""
+ response = await client.post(
+ "/api/accounts/00000000-0000-0000-0000-000000000000/reopen",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_delete_account_api_not_found(client: AsyncClient, auth_headers):
+ """Delete nonexistent account returns 404."""
+ response = await client.delete(
+ "/api/accounts/00000000-0000-0000-0000-000000000000",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_update_account_api_not_found(client: AsyncClient, auth_headers):
+ """Update nonexistent account returns 404."""
+ response = await client.patch(
+ "/api/accounts/00000000-0000-0000-0000-000000000000",
+ headers=auth_headers,
+ json={"name": "Ghost"},
+ )
+ assert response.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Assets API — portfolio trend and missing endpoints
+# ---------------------------------------------------------------------------
+
+
+async def test_portfolio_trend(client: AsyncClient, auth_headers, test_user):
+ """GET /api/assets/portfolio-trend returns data."""
+ response = await client.get("/api/assets/portfolio-trend", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert "assets" in data
+ assert "trend" in data
+ assert "total" in data
+
+
+async def test_update_asset_not_found(client: AsyncClient, auth_headers):
+ """PATCH nonexistent asset returns 404."""
+ response = await client.patch(
+ f"/api/assets/{uuid.uuid4()}",
+ headers=auth_headers,
+ json={"name": "Ghost"},
+ )
+ assert response.status_code == 404
+
+
+async def test_delete_asset_not_found(client: AsyncClient, auth_headers):
+ """DELETE nonexistent asset returns 404."""
+ response = await client.delete(
+ f"/api/assets/{uuid.uuid4()}", headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_list_asset_values_not_found(client: AsyncClient, auth_headers):
+ """GET values for nonexistent asset returns 404."""
+ response = await client.get(
+ f"/api/assets/{uuid.uuid4()}/values", headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_add_asset_value_not_found(client: AsyncClient, auth_headers):
+ """POST value to nonexistent asset returns 404."""
+ response = await client.post(
+ f"/api/assets/{uuid.uuid4()}/values",
+ headers=auth_headers,
+ json={"amount": 1000, "date": "2026-01-01"},
+ )
+ assert response.status_code == 404
+
+
+async def test_delete_asset_value_not_found(client: AsyncClient, auth_headers):
+ """DELETE nonexistent asset value returns 404."""
+ response = await client.delete(
+ f"/api/assets/values/{uuid.uuid4()}", headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_get_asset_value_trend_not_found(client: AsyncClient, auth_headers):
+ """GET value-trend for nonexistent asset returns 404."""
+ response = await client.get(
+ f"/api/assets/{uuid.uuid4()}/value-trend", headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Connections API — transfer detection and additional
+# ---------------------------------------------------------------------------
+
+
+async def test_detect_transfers_api(client: AsyncClient, auth_headers):
+ """POST /api/connections/transfers/detect returns pairs_created count."""
+ response = await client.post(
+ "/api/connections/transfers/detect", headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert "pairs_created" in response.json()
+
+
+async def test_unlink_transfer_not_found(client: AsyncClient, auth_headers):
+ """DELETE nonexistent transfer pair returns 404."""
+ response = await client.delete(
+ f"/api/connections/transfers/{uuid.uuid4()}", headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_reconnect_token_not_found(client: AsyncClient, auth_headers):
+ """POST reconnect-token for nonexistent connection returns 404."""
+ response = await client.post(
+ f"/api/connections/{uuid.uuid4()}/reconnect-token",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_reconnect_token_no_item_id(
+ client: AsyncClient, auth_headers, test_connection,
+):
+ """POST reconnect-token when connection has no item_id returns 400."""
+ response = await client.post(
+ f"/api/connections/{test_connection.id}/reconnect-token",
+ headers=auth_headers,
+ )
+ assert response.status_code == 400
+ assert "item_id" in response.json()["detail"].lower()
+
+
+# ---------------------------------------------------------------------------
+# Dashboard API — balance-history and projected-transactions
+# ---------------------------------------------------------------------------
+
+
+async def test_dashboard_projected_transactions(
+ client: AsyncClient, auth_headers, test_categories,
+):
+ """GET /api/dashboard/projected-transactions returns projections."""
+ # Create a recurring transaction
+ next_month = date.today().replace(day=1)
+ if next_month.month == 12:
+ next_month = next_month.replace(year=next_month.year + 1, month=1)
+ else:
+ next_month = next_month.replace(month=next_month.month + 1)
+
+ await client.post(
+ "/api/recurring-transactions",
+ headers=auth_headers,
+ json={
+ "description": "Proj Test",
+ "amount": 100,
+ "type": "debit",
+ "frequency": "monthly",
+ "start_date": next_month.isoformat(),
+ "category_id": str(test_categories[0].id),
+ },
+ )
+
+ response = await client.get(
+ "/api/dashboard/projected-transactions",
+ params={"month": next_month.isoformat()},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert isinstance(data, list)
+ assert len(data) >= 1
+
+
+async def test_dashboard_balance_history(client: AsyncClient, auth_headers):
+ """GET /api/dashboard/balance-history returns current/previous month data."""
+ # Create an account first
+ await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "BH Test", "type": "checking", "balance": 1000, "currency": "BRL"},
+ )
+
+ response = await client.get(
+ "/api/dashboard/balance-history", headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert "current" in data
+ assert "previous" in data
+ assert isinstance(data["current"], list)
+ assert isinstance(data["previous"], list)
+
+
+# ---------------------------------------------------------------------------
+# Import API — additional edge cases
+# ---------------------------------------------------------------------------
+
+
+async def test_import_duplicate_skips(
+ client: AsyncClient, auth_headers, test_account: Account,
+):
+ """Re-importing the same transactions skips duplicates."""
+ transactions = [
+ {
+ "description": "Dup Test",
+ "amount": "99.99",
+ "date": "2026-01-15",
+ "type": "debit",
+ },
+ ]
+
+ # First import
+ resp1 = await client.post(
+ "/api/transactions/import",
+ headers=auth_headers,
+ json={
+ "account_id": str(test_account.id),
+ "transactions": transactions,
+ },
+ )
+ assert resp1.status_code == 201
+ assert resp1.json()["imported"] == 1
+
+ # Second import — same data should be skipped
+ resp2 = await client.post(
+ "/api/transactions/import",
+ headers=auth_headers,
+ json={
+ "account_id": str(test_account.id),
+ "transactions": transactions,
+ },
+ )
+ assert resp2.status_code == 201
+ assert resp2.json()["imported"] == 0
+ assert resp2.json()["skipped"] == 1
+
+
+async def test_preview_ofx_file_unknown_extension(client: AsyncClient, auth_headers):
+ """Preview with unknown extension tries auto-detection chain."""
+ csv_content = b"date,description,amount\n2026-01-15,Test,-50.00\n"
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("data.txt", csv_content, "text/plain")},
+ )
+ # Auto-detection tries ofx → qif → camt → csv. QIF parser may "succeed"
+ # with 0 transactions before reaching CSV, so we only assert the code path runs.
+ assert response.status_code == 200
+ data = response.json()
+ assert data["detected_format"] in ("csv", "qif", "camt")
+
+
+async def test_preview_qif_format(client: AsyncClient, auth_headers):
+ """Preview QIF file."""
+ qif_content = b"!Type:Bank\nD01/15/2026\nT-50.00\nPTest Payment\n^\n"
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("data.qif", qif_content, "application/qif")},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["detected_format"] == "qif"
+ assert len(data["transactions"]) >= 1
+
+
+async def test_preview_csv_with_date_format(client: AsyncClient, auth_headers):
+ """Preview CSV with explicit date format."""
+ csv_content = b"date,description,amount\n03/15/2026,US Format,-30.00\n"
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("us.csv", csv_content, "text/csv")},
+ data={"date_format": "MM/DD/YYYY"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data["transactions"]) >= 1
+
+
+async def test_preview_csv_with_flip_amount(client: AsyncClient, auth_headers):
+ """Preview CSV with flip_amount option."""
+ csv_content = b"date,description,amount\n2026-01-15,Inverted,50.00\n"
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("flip.csv", csv_content, "text/csv")},
+ data={"flip_amount": "true"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ # Amount was positive, flip makes it negative -> debit
+ assert data["transactions"][0]["type"] == "debit"
+
+
+async def test_preview_csv_split_columns(client: AsyncClient, auth_headers):
+ """Preview CSV with inflow/outflow split columns."""
+ csv_content = b"date,description,inflow,outflow\n2026-01-15,Salary,5000,\n2026-01-16,Rent,,1500\n"
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("split.csv", csv_content, "text/csv")},
+ data={"inflow_column": "inflow", "outflow_column": "outflow"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data["transactions"]) == 2
+ assert data["transactions"][0]["type"] == "credit"
+ assert data["transactions"][1]["type"] == "debit"
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
new file mode 100644
index 00000000..d62ad22d
--- /dev/null
+++ b/backend/tests/test_connection_service.py
@@ -0,0 +1,262 @@
+"""Service-level tests for connection_service.
+
+Tests: _match_pluggy_category, _description_similarity, get_connections,
+get_connection, delete_connection, update_connection_settings.
+"""
+import uuid
+from datetime import datetime, timezone
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.bank_connection import BankConnection
+from app.models.category import Category
+from app.services.connection_service import (
+ _description_similarity,
+ _match_pluggy_category,
+ delete_connection,
+ get_connection,
+ get_connections,
+ update_connection_settings,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+async def _make_connection(
+ session: AsyncSession, user_id: uuid.UUID, name: str = "Test Bank",
+ settings: dict | None = 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
+
+
+async def _make_category(
+ session: AsyncSession, user_id: uuid.UUID, name: str,
+) -> Category:
+ cat = Category(
+ id=uuid.uuid4(), user_id=user_id, name=name,
+ icon="tag", color="#000", is_system=False,
+ )
+ session.add(cat)
+ await session.commit()
+ await session.refresh(cat)
+ return cat
+
+
+# ---------------------------------------------------------------------------
+# _description_similarity (pure function)
+# ---------------------------------------------------------------------------
+
+
+def test_description_similarity_identical():
+ assert _description_similarity("hello world", "hello world") == 1.0
+
+
+def test_description_similarity_partial():
+ score = _description_similarity("hello world foo", "hello world bar")
+ assert 0.0 < score < 1.0
+
+
+def test_description_similarity_no_overlap():
+ assert _description_similarity("abc", "xyz") == 0.0
+
+
+def test_description_similarity_none():
+ assert _description_similarity(None, "hello") == 0.0
+ assert _description_similarity("hello", None) == 0.0
+ assert _description_similarity(None, None) == 0.0
+
+
+def test_description_similarity_empty():
+ assert _description_similarity("", "hello") == 0.0
+ assert _description_similarity("hello", "") == 0.0
+
+
+def test_description_similarity_case_insensitive():
+ score = _description_similarity("Hello World", "hello world")
+ assert score == 1.0
+
+
+# ---------------------------------------------------------------------------
+# _match_pluggy_category
+# ---------------------------------------------------------------------------
+
+
+async def test_match_pluggy_exact(session: AsyncSession, test_user):
+ """Exact Pluggy category match maps to user's category."""
+ await _make_category(session, test_user.id, "Alimentação")
+ cat_id = await _match_pluggy_category(session, test_user.id, "Eating out")
+ assert cat_id is not None
+
+
+async def test_match_pluggy_prefix(session: AsyncSession, test_user):
+ """Pluggy category with ' - ' prefix matches via split."""
+ await _make_category(session, test_user.id, "Transferências")
+ cat_id = await _match_pluggy_category(session, test_user.id, "Transfer - PIX")
+ assert cat_id is not None
+
+
+async def test_match_pluggy_no_match(session: AsyncSession, test_user):
+ """Unknown Pluggy category returns None."""
+ cat_id = await _match_pluggy_category(session, test_user.id, "Unknown Category XYZ")
+ assert cat_id is None
+
+
+async def test_match_pluggy_none(session: AsyncSession, test_user):
+ """None category returns None."""
+ cat_id = await _match_pluggy_category(session, test_user.id, None)
+ assert cat_id is None
+
+
+async def test_match_pluggy_user_has_no_category(session: AsyncSession, test_user):
+ """Pluggy category maps but user doesn't have the target category."""
+ # "Eating out" maps to "Alimentação" but we don't create it
+ cat_id = await _match_pluggy_category(session, test_user.id, "Eating out")
+ assert cat_id is None
+
+
+# ---------------------------------------------------------------------------
+# get_connections / get_connection
+# ---------------------------------------------------------------------------
+
+
+async def test_get_connections_returns_list(session: AsyncSession, test_user):
+ """Returns list of connections for user."""
+ await _make_connection(session, test_user.id, "Bank A")
+ await _make_connection(session, test_user.id, "Bank B")
+
+ connections = await get_connections(session, test_user.id)
+ assert len(connections) >= 2
+ names = {c.institution_name for c in connections}
+ assert "Bank A" in names
+ assert "Bank B" in names
+
+
+async def test_get_connections_empty(session: AsyncSession, test_user):
+ """Returns empty list when no connections."""
+ connections = await get_connections(session, test_user.id)
+ # May have connections from other fixtures; just verify it's a list
+ assert isinstance(connections, list)
+
+
+async def test_get_connection_found(session: AsyncSession, test_user):
+ """Returns a specific connection."""
+ conn = await _make_connection(session, test_user.id, "Specific Bank")
+ result = await get_connection(session, conn.id, test_user.id)
+ assert result is not None
+ assert result.institution_name == "Specific Bank"
+
+
+async def test_get_connection_not_found(session: AsyncSession, test_user):
+ """Returns None for nonexistent connection."""
+ result = await get_connection(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_get_connection_wrong_user(session: AsyncSession, test_user):
+ """Returns None when connection belongs to another user."""
+ conn = await _make_connection(session, test_user.id, "Other User Bank")
+ result = await get_connection(session, conn.id, uuid.uuid4())
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# update_connection_settings
+# ---------------------------------------------------------------------------
+
+
+async def test_update_settings_new(session: AsyncSession, test_user):
+ """Updates settings on a connection with no prior settings."""
+ conn = await _make_connection(session, test_user.id, "Settings Test")
+
+ updated = await update_connection_settings(
+ session, conn.id, test_user.id, {"payee_source": "merchant"},
+ )
+ assert updated is not None
+ assert updated.settings["payee_source"] == "merchant"
+
+
+async def test_update_settings_preserves_existing(session: AsyncSession, test_user):
+ """Updates one setting without clobbering others."""
+ conn = await _make_connection(
+ session, test_user.id, "Preserve Test",
+ settings={"payee_source": "auto", "import_pending": True},
+ )
+
+ updated = await update_connection_settings(
+ session, conn.id, test_user.id, {"import_pending": False},
+ )
+ assert updated is not None
+ assert updated.settings["payee_source"] == "auto"
+ assert updated.settings["import_pending"] is False
+
+
+async def test_update_settings_ignores_none(session: AsyncSession, test_user):
+ """None values in settings_update are not written."""
+ conn = await _make_connection(
+ session, test_user.id, "None Test",
+ settings={"payee_source": "auto"},
+ )
+ updated = await update_connection_settings(
+ session, conn.id, test_user.id, {"payee_source": None},
+ )
+ assert updated is not None
+ assert updated.settings["payee_source"] == "auto"
+
+
+async def test_update_settings_not_found(session: AsyncSession, test_user):
+ """Returns None when connection not found."""
+ result = await update_connection_settings(
+ session, uuid.uuid4(), test_user.id, {"payee_source": "auto"},
+ )
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# delete_connection
+# ---------------------------------------------------------------------------
+
+
+async def test_delete_connection_found(session: AsyncSession, test_user):
+ """Deletes an existing connection."""
+ conn = await _make_connection(session, test_user.id, "To Delete")
+ result = await delete_connection(session, conn.id, test_user.id)
+ assert result is True
+
+ assert await get_connection(session, conn.id, test_user.id) is None
+
+
+async def test_delete_connection_not_found(session: AsyncSession, test_user):
+ """Returns False for nonexistent connection."""
+ result = await delete_connection(session, uuid.uuid4(), test_user.id)
+ assert result is False
diff --git a/backend/tests/test_dashboard_service.py b/backend/tests/test_dashboard_service.py
new file mode 100644
index 00000000..867a3af7
--- /dev/null
+++ b/backend/tests/test_dashboard_service.py
@@ -0,0 +1,446 @@
+"""Service-level tests for dashboard_service.
+
+Tests: _month_range, get_summary, get_spending_by_category,
+get_projected_transactions, _account_balance_at, _total_balance_by_currency,
+_get_open_accounts.
+"""
+import uuid
+from datetime import date, timedelta
+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.recurring_transaction import RecurringTransaction
+from app.models.transaction import Transaction
+from app.services.dashboard_service import (
+ _month_range,
+ _get_open_accounts,
+ _account_balance_at,
+ _total_balance_by_currency,
+ get_summary,
+ get_spending_by_category,
+ get_projected_transactions,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+async def _make_account(
+ session: AsyncSession, user_id: uuid.UUID,
+ name: str = "Dash Test", acc_type: str = "checking",
+ balance: str = "0.00", currency: str = "BRL",
+ connection_id: uuid.UUID | None = None,
+ is_closed: bool = False,
+) -> Account:
+ account = 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(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+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", transfer_pair_id: uuid.UUID | None = None,
+ category_id: uuid.UUID | None = None,
+) -> Transaction:
+ from datetime import datetime, timezone
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,
+ description=f"Test {txn_type} {amount}", amount=Decimal(str(amount)),
+ date=txn_date, type=txn_type, source=source, currency="BRL",
+ transfer_pair_id=transfer_pair_id, category_id=category_id,
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+ await session.refresh(txn)
+ return txn
+
+
+async def _make_category(
+ session: AsyncSession, user_id: uuid.UUID, name: str,
+ icon: str = "tag", color: str = "#000",
+) -> Category:
+ cat = Category(
+ id=uuid.uuid4(), user_id=user_id, name=name,
+ icon=icon, color=color, is_system=False,
+ )
+ session.add(cat)
+ await session.commit()
+ await session.refresh(cat)
+ return cat
+
+
+# ---------------------------------------------------------------------------
+# _month_range (pure function)
+# ---------------------------------------------------------------------------
+
+
+def test_month_range_normal():
+ start, end = _month_range(date(2025, 6, 15))
+ assert start == date(2025, 6, 1)
+ assert end == date(2025, 7, 1)
+
+
+def test_month_range_december():
+ start, end = _month_range(date(2025, 12, 20))
+ assert start == date(2025, 12, 1)
+ assert end == date(2026, 1, 1)
+
+
+def test_month_range_january():
+ start, end = _month_range(date(2026, 1, 1))
+ assert start == date(2026, 1, 1)
+ assert end == date(2026, 2, 1)
+
+
+# ---------------------------------------------------------------------------
+# _get_open_accounts
+# ---------------------------------------------------------------------------
+
+
+async def test_get_open_accounts(session: AsyncSession, test_user):
+ """Returns only non-closed accounts."""
+ open_acc = await _make_account(session, test_user.id, "Open")
+ closed_acc = await _make_account(session, test_user.id, "Closed", is_closed=True)
+
+ accounts = await _get_open_accounts(session, test_user.id)
+ ids = [a.id for a in accounts]
+ assert open_acc.id in ids
+ assert closed_acc.id not in ids
+
+
+# ---------------------------------------------------------------------------
+# _account_balance_at (dashboard version — supports bank-connected)
+# ---------------------------------------------------------------------------
+
+
+async def test_account_balance_at_manual(session: AsyncSession, test_user):
+ """Manual account balance is sum of transactions up to cutoff."""
+ account = await _make_account(session, test_user.id, "Manual Bal")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", today - timedelta(days=10), source="opening_balance")
+ await _add_txn(session, test_user.id, account.id, 200, "debit", today - timedelta(days=5))
+ await _add_txn(session, test_user.id, account.id, 300, "debit", today)
+
+ # Balance at 3 days ago should be 1000 - 200 = 800 (excludes today's 300 debit)
+ bal = await _account_balance_at(session, account, today - timedelta(days=3))
+ assert bal == pytest.approx(800.0)
+
+
+async def test_account_balance_at_manual_opening_fallback(session: AsyncSession, test_user):
+ """Manual account falls back to opening_balance when no transactions before cutoff."""
+ account = await _make_account(session, test_user.id, "Fallback Bal")
+ today = date.today()
+
+ # Opening balance dated today, cutoff is yesterday
+ await _add_txn(session, test_user.id, account.id, 5000, "credit", today, source="opening_balance")
+
+ bal = await _account_balance_at(session, account, today - timedelta(days=1))
+ assert bal == pytest.approx(5000.0)
+
+
+async def test_account_balance_at_bank_connected(session: AsyncSession, test_user, test_connection):
+ """Bank-connected account backtracks from stored balance."""
+ account = await _make_account(
+ session, test_user.id, "Connected Bal", balance="5000.00",
+ connection_id=test_connection.id,
+ )
+ today = date.today()
+
+ # Add transactions after cutoff
+ await _add_txn(session, test_user.id, account.id, 300, "credit", today)
+
+ # Balance at yesterday = 5000 - 300 = 4700
+ bal = await _account_balance_at(session, account, today - timedelta(days=1))
+ assert bal == pytest.approx(4700.0)
+
+
+async def test_account_balance_at_credit_card_connected(session: AsyncSession, test_user, test_connection):
+ """Bank-connected credit_card negates balance."""
+ account = await _make_account(
+ session, test_user.id, "CC Bal", acc_type="credit_card", balance="2000.00",
+ connection_id=test_connection.id,
+ )
+ bal = await _account_balance_at(session, account, date.today())
+ # Credit card: current_bal = -2000
+ assert bal == pytest.approx(-2000.0)
+
+
+# ---------------------------------------------------------------------------
+# _total_balance_by_currency
+# ---------------------------------------------------------------------------
+
+
+async def test_total_balance_by_currency(session: AsyncSession, test_user):
+ """Total balance groups by currency."""
+ brl_acc = await _make_account(session, test_user.id, "BRL", currency="BRL")
+ usd_acc = await _make_account(session, test_user.id, "USD", currency="USD")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, brl_acc.id, 1000, "credit", today, source="opening_balance")
+ await _add_txn(session, test_user.id, usd_acc.id, 500, "credit", today, source="opening_balance")
+
+ totals = await _total_balance_by_currency(session, test_user.id, today)
+ assert totals.get("BRL", 0) == pytest.approx(1000.0)
+ assert totals.get("USD", 0) == pytest.approx(500.0)
+
+
+# ---------------------------------------------------------------------------
+# get_summary
+# ---------------------------------------------------------------------------
+
+
+async def test_get_summary_basic(session: AsyncSession, test_user):
+ """Summary returns correct structure with balances and counts."""
+ account = await _make_account(session, test_user.id, "Summary Acc")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 5000, "credit", today, source="opening_balance")
+ await _add_txn(session, test_user.id, account.id, 200, "debit", today)
+ await _add_txn(session, test_user.id, account.id, 100, "credit", today)
+
+ summary = await get_summary(session, test_user.id)
+ assert summary.monthly_income == pytest.approx(100.0)
+ assert summary.monthly_expenses == pytest.approx(200.0)
+ assert summary.accounts_count >= 1
+
+
+async def test_get_summary_excludes_opening_balance_from_income(session: AsyncSession, test_user):
+ """Opening balance does not count as monthly income."""
+ account = await _make_account(session, test_user.id, "No OB Income")
+ await _add_txn(session, test_user.id, account.id, 10000, "credit", date.today(), source="opening_balance")
+
+ summary = await get_summary(session, test_user.id)
+ assert summary.monthly_income == pytest.approx(0.0)
+
+
+async def test_get_summary_excludes_transfers(session: AsyncSession, test_user):
+ """Transfer pair transactions excluded from income/expenses."""
+ account = await _make_account(session, test_user.id, "Transfer Excl")
+ today = date.today()
+ pair_id = uuid.uuid4()
+
+ await _add_txn(session, test_user.id, account.id, 500, "debit", today, transfer_pair_id=pair_id)
+ await _add_txn(session, test_user.id, account.id, 100, "debit", today)
+
+ summary = await get_summary(session, test_user.id)
+ assert summary.monthly_expenses == pytest.approx(100.0)
+
+
+async def test_get_summary_pending_categorization(session: AsyncSession, test_user):
+ """Summary counts uncategorized transactions."""
+ account = await _make_account(session, test_user.id, "Pending Cat")
+ today = date.today()
+
+ # 2 uncategorized, 1 opening_balance (excluded)
+ await _add_txn(session, test_user.id, account.id, 100, "debit", today)
+ await _add_txn(session, test_user.id, account.id, 200, "debit", today)
+ await _add_txn(session, test_user.id, account.id, 5000, "credit", today, source="opening_balance")
+
+ summary = await get_summary(session, test_user.id)
+ assert summary.pending_categorization >= 2
+
+
+async def test_get_summary_with_specific_month(session: AsyncSession, test_user):
+ """Summary uses the specified month."""
+ account = await _make_account(session, test_user.id, "Month Test")
+ today = date.today()
+ past = (today.replace(day=1) - timedelta(days=1)).replace(day=15)
+
+ await _add_txn(session, test_user.id, account.id, 300, "debit", past)
+
+ # Current month - no transactions
+ await get_summary(session, test_user.id, month=today.replace(day=1))
+ # Past month - has 300 debit
+ summary_past = await get_summary(session, test_user.id, month=past.replace(day=1))
+ assert summary_past.monthly_expenses >= 300.0
+
+
+async def test_get_summary_with_balance_date(session: AsyncSession, test_user):
+ """balance_date overrides the default cutoff for balance calculation."""
+ account = await _make_account(session, test_user.id, "Balance Date")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", today - timedelta(days=10))
+ await _add_txn(session, test_user.id, account.id, 500, "debit", today - timedelta(days=3))
+
+ # With cutoff 5 days ago, the 500 debit shouldn't be included
+ summary = await get_summary(
+ session, test_user.id, month=today.replace(day=1),
+ balance_date=today - timedelta(days=5),
+ )
+ total = sum(summary.total_balance.values())
+ assert total == pytest.approx(1000.0)
+
+
+# ---------------------------------------------------------------------------
+# get_spending_by_category
+# ---------------------------------------------------------------------------
+
+
+async def test_spending_by_category_basic(session: AsyncSession, test_user):
+ """Returns spending grouped by category."""
+ cat = await _make_category(session, test_user.id, "Food", color="#F00")
+ account = await _make_account(session, test_user.id, "Spend Test")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 100, "debit", today, category_id=cat.id)
+ await _add_txn(session, test_user.id, account.id, 50, "debit", today, category_id=cat.id)
+
+ spending = await get_spending_by_category(session, test_user.id)
+ assert len(spending) > 0
+ food = next((s for s in spending if s.category_id == str(cat.id)), None)
+ assert food is not None
+ assert food.total == pytest.approx(150.0)
+
+
+async def test_spending_by_category_uncategorized(session: AsyncSession, test_user):
+ """Uncategorized transactions show as 'Sem categoria'."""
+ account = await _make_account(session, test_user.id, "Uncat Spend")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 75, "debit", today)
+
+ spending = await get_spending_by_category(session, test_user.id)
+ uncat = next((s for s in spending if s.category_id is None), None)
+ assert uncat is not None
+ assert uncat.category_name == "Sem categoria"
+
+
+async def test_spending_excludes_credits(session: AsyncSession, test_user):
+ """Spending by category only includes debit transactions."""
+ cat = await _make_category(session, test_user.id, "Income Cat")
+ account = await _make_account(session, test_user.id, "Credit Excl")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", today, category_id=cat.id)
+
+ spending = await get_spending_by_category(session, test_user.id)
+ income = next((s for s in spending if s.category_id == str(cat.id)), None)
+ assert income is None
+
+
+async def test_spending_excludes_transfers(session: AsyncSession, test_user):
+ """Transfer pairs are excluded from spending."""
+ account = await _make_account(session, test_user.id, "Transfer Spend")
+ today = date.today()
+ pair_id = uuid.uuid4()
+
+ await _add_txn(session, test_user.id, account.id, 500, "debit", today, transfer_pair_id=pair_id)
+
+ spending = await get_spending_by_category(session, test_user.id)
+ # No spending should include the transfer
+ total = sum(s.total for s in spending)
+ assert 500 not in [s.total for s in spending] or total == 0
+
+
+async def test_spending_percentage(session: AsyncSession, test_user):
+ """Percentages sum to approximately 100%."""
+ cat1 = await _make_category(session, test_user.id, "Cat A")
+ cat2 = await _make_category(session, test_user.id, "Cat B")
+ account = await _make_account(session, test_user.id, "Pct Test")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, account.id, 300, "debit", today, category_id=cat1.id)
+ await _add_txn(session, test_user.id, account.id, 700, "debit", today, category_id=cat2.id)
+
+ spending = await get_spending_by_category(session, test_user.id)
+ total_pct = sum(s.percentage for s in spending)
+ assert total_pct == pytest.approx(100.0, abs=0.1)
+
+
+# ---------------------------------------------------------------------------
+# get_projected_transactions
+# ---------------------------------------------------------------------------
+
+
+async def test_get_projected_transactions(session: AsyncSession, test_user):
+ """Projected transactions include recurring template details."""
+ cat = await _make_category(session, test_user.id, "Recurring Cat")
+
+ # Create a recurring transaction for next month
+ next_month = date.today().replace(day=1)
+ if next_month.month == 12:
+ next_month = next_month.replace(year=next_month.year + 1, month=1)
+ else:
+ next_month = next_month.replace(month=next_month.month + 1)
+
+ from datetime import datetime, timezone
+ rec = RecurringTransaction(
+ id=uuid.uuid4(), user_id=test_user.id,
+ description="Weekly Coffee", amount=Decimal("25.00"),
+ currency="BRL", type="debit", frequency="weekly",
+ start_date=next_month, next_occurrence=next_month,
+ is_active=True, category_id=cat.id,
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(rec)
+ await session.commit()
+
+ projections = await get_projected_transactions(session, test_user.id, month=next_month)
+ assert len(projections) >= 4 # Weekly = at least 4 occurrences
+
+ for proj in projections:
+ assert proj.description == "Weekly Coffee"
+ assert proj.amount == 25.0
+ assert proj.category_name == "Recurring Cat"
+
+
+async def test_get_projected_transactions_no_category(session: AsyncSession, test_user):
+ """Projected transactions work without category."""
+ next_month = date.today().replace(day=1)
+ if next_month.month == 12:
+ next_month = next_month.replace(year=next_month.year + 1, month=1)
+ else:
+ next_month = next_month.replace(month=next_month.month + 1)
+
+ from datetime import datetime, timezone
+ rec = RecurringTransaction(
+ id=uuid.uuid4(), user_id=test_user.id,
+ description="Monthly Fee", amount=Decimal("50.00"),
+ currency="BRL", type="debit", frequency="monthly",
+ start_date=next_month, next_occurrence=next_month,
+ is_active=True, category_id=None,
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(rec)
+ await session.commit()
+
+ projections = await get_projected_transactions(session, test_user.id, month=next_month)
+ assert len(projections) >= 1
+ proj = projections[0]
+ assert proj.category_name is None
+ assert proj.category_id is None
diff --git a/backend/tests/test_setup_api.py b/backend/tests/test_setup_api.py
new file mode 100644
index 00000000..ce0a5b92
--- /dev/null
+++ b/backend/tests/test_setup_api.py
@@ -0,0 +1,100 @@
+"""Tests for setup API endpoints.
+
+Tests: GET /api/setup/status, POST /api/setup/create-admin.
+"""
+import pytest
+from httpx import AsyncClient
+
+
+async def test_setup_status_has_users(client: AsyncClient, test_user):
+ """Setup status returns has_users=True when users exist."""
+ response = await client.get("/api/setup/status")
+ assert response.status_code == 200
+ assert response.json()["has_users"] is True
+
+
+async def test_setup_status_no_users(client: AsyncClient, clean_db):
+ """Setup status returns has_users=False when no users exist."""
+ response = await client.get("/api/setup/status")
+ assert response.status_code == 200
+ assert response.json()["has_users"] is False
+
+
+async def test_create_admin_success(client: AsyncClient, clean_db):
+ """Create admin succeeds when no users exist."""
+ response = await client.post(
+ "/api/setup/create-admin",
+ json={
+ "email": "[email protected]",
+ "password": "StrongPass123!",
+ "currency": "BRL",
+ "name": "Admin",
+ "language": "pt-BR",
+ },
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert "access_token" in data
+ assert data["token_type"] == "bearer"
+
+
+async def test_create_admin_already_exists(client: AsyncClient, test_user):
+ """Create admin fails when users already exist."""
+ response = await client.post(
+ "/api/setup/create-admin",
+ json={
+ "email": "[email protected]",
+ "password": "Pass123!",
+ },
+ )
+ assert response.status_code == 403
+ assert "already completed" in response.json()["detail"].lower()
+
+
+async def test_create_admin_english_wallet(client: AsyncClient, clean_db):
+ """Create admin with English language creates 'Wallet' account."""
+ response = await client.post(
+ "/api/setup/create-admin",
+ json={
+ "email": "[email protected]",
+ "password": "StrongPass123!",
+ "currency": "USD",
+ "language": "en",
+ },
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ # Use the token to check accounts
+ headers = {"Authorization": f"Bearer {data['access_token']}"}
+ accounts = await client.get("/api/accounts", headers=headers)
+ assert accounts.status_code == 200
+ names = [a["name"] for a in accounts.json()]
+ assert "Wallet" in names
+
+
+async def test_create_admin_portuguese_wallet(client: AsyncClient, clean_db):
+ """Create admin with Portuguese language creates 'Carteira' account."""
+ response = await client.post(
+ "/api/setup/create-admin",
+ json={
+ "email": "[email protected]",
+ "password": "StrongPass123!",
+ "currency": "BRL",
+ "language": "pt-BR",
+ },
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ headers = {"Authorization": f"Bearer {data['access_token']}"}
+ accounts = await client.get("/api/accounts", headers=headers)
+ assert accounts.status_code == 200
+ names = [a["name"] for a in accounts.json()]
+ assert "Carteira" in names
diff --git a/backend/tests/test_transfer_detection.py b/backend/tests/test_transfer_detection.py
new file mode 100644
index 00000000..d4e1bd5e
--- /dev/null
+++ b/backend/tests/test_transfer_detection.py
@@ -0,0 +1,256 @@
+"""Service-level tests for transfer_detection_service.
+
+Tests: detect_transfer_pairs, unlink_transfer_pair.
+"""
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.transaction import Transaction
+from app.services.transfer_detection_service import (
+ detect_transfer_pairs,
+ unlink_transfer_pair,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+async def _make_account(
+ session: AsyncSession, user_id: uuid.UUID, name: str,
+) -> Account:
+ account = Account(
+ id=uuid.uuid4(), user_id=user_id, name=name,
+ type="checking", balance=Decimal("0.00"), currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+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",
+) -> Transaction:
+ from datetime import datetime, timezone
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,
+ description=f"Transfer {txn_type} {amount}",
+ amount=Decimal(str(amount)), date=txn_date, type=txn_type,
+ source=source, currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+ await session.refresh(txn)
+ return txn
+
+
+# ---------------------------------------------------------------------------
+# detect_transfer_pairs
+# ---------------------------------------------------------------------------
+
+
+async def test_detect_basic_pair(session: AsyncSession, test_user):
+ """Detects a simple debit-credit pair across two accounts."""
+ acc1 = await _make_account(session, test_user.id, "Account A")
+ acc2 = await _make_account(session, test_user.id, "Account B")
+ today = date.today()
+
+ debit = await _add_txn(session, test_user.id, acc1.id, 500, "debit", today)
+ credit = await _add_txn(session, test_user.id, acc2.id, 500, "credit", today)
+
+ pairs_created = await detect_transfer_pairs(session, test_user.id)
+ await session.commit()
+ assert pairs_created == 1
+
+ # Reload and verify
+ await session.refresh(debit)
+ await session.refresh(credit)
+ assert debit.transfer_pair_id is not None
+ assert debit.transfer_pair_id == credit.transfer_pair_id
+
+
+async def test_detect_with_candidate_ids(session: AsyncSession, test_user):
+ """Only considers candidate debits when candidate_ids is provided."""
+ acc1 = await _make_account(session, test_user.id, "Cand A")
+ acc2 = await _make_account(session, test_user.id, "Cand B")
+ today = date.today()
+
+ debit1 = await _add_txn(session, test_user.id, acc1.id, 100, "debit", today)
+ debit2 = await _add_txn(session, test_user.id, acc1.id, 200, "debit", today)
+ await _add_txn(session, test_user.id, acc2.id, 100, "credit", today)
+ await _add_txn(session, test_user.id, acc2.id, 200, "credit", today)
+
+ # Only consider debit1 as candidate
+ pairs = await detect_transfer_pairs(session, test_user.id, candidate_ids=[debit1.id])
+ await session.commit()
+ assert pairs == 1
+
+ await session.refresh(debit1)
+ await session.refresh(debit2)
+ assert debit1.transfer_pair_id is not None
+ assert debit2.transfer_pair_id is None
+
+
+async def test_detect_no_debits(session: AsyncSession, test_user):
+ """Returns 0 when there are no debits."""
+ acc = await _make_account(session, test_user.id, "No Debits")
+ await _add_txn(session, test_user.id, acc.id, 100, "credit", date.today())
+
+ pairs = await detect_transfer_pairs(session, test_user.id)
+ assert pairs == 0
+
+
+async def test_detect_no_credits(session: AsyncSession, test_user):
+ """Returns 0 when there are no credits."""
+ acc = await _make_account(session, test_user.id, "No Credits")
+ await _add_txn(session, test_user.id, acc.id, 100, "debit", date.today())
+
+ pairs = await detect_transfer_pairs(session, test_user.id)
+ assert pairs == 0
+
+
+async def test_detect_respects_date_tolerance(session: AsyncSession, test_user):
+ """Only pairs transactions within date_tolerance_days."""
+ acc1 = await _make_account(session, test_user.id, "Tol A")
+ acc2 = await _make_account(session, test_user.id, "Tol B")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, acc1.id, 300, "debit", today)
+ # Credit too far away (5 days)
+ await _add_txn(session, test_user.id, acc2.id, 300, "credit", today + timedelta(days=5))
+
+ pairs = await detect_transfer_pairs(session, test_user.id, date_tolerance_days=2)
+ assert pairs == 0
+
+
+async def test_detect_within_tolerance(session: AsyncSession, test_user):
+ """Pairs transactions within tolerance."""
+ acc1 = await _make_account(session, test_user.id, "In Tol A")
+ acc2 = await _make_account(session, test_user.id, "In Tol B")
+ today = date.today()
+
+ debit = await _add_txn(session, test_user.id, acc1.id, 400, "debit", today)
+ credit = await _add_txn(session, test_user.id, acc2.id, 400, "credit", today + timedelta(days=1))
+
+ pairs = await detect_transfer_pairs(session, test_user.id, date_tolerance_days=2)
+ await session.commit()
+ assert pairs == 1
+
+ await session.refresh(debit)
+ await session.refresh(credit)
+ assert debit.transfer_pair_id == credit.transfer_pair_id
+
+
+async def test_detect_ignores_same_account(session: AsyncSession, test_user):
+ """Does not pair debit and credit in the same account."""
+ acc = await _make_account(session, test_user.id, "Same Acc")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, acc.id, 100, "debit", today)
+ await _add_txn(session, test_user.id, acc.id, 100, "credit", today)
+
+ pairs = await detect_transfer_pairs(session, test_user.id)
+ assert pairs == 0
+
+
+async def test_detect_different_amounts_no_pair(session: AsyncSession, test_user):
+ """Does not pair transactions with different amounts."""
+ acc1 = await _make_account(session, test_user.id, "Diff A")
+ acc2 = await _make_account(session, test_user.id, "Diff B")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, acc1.id, 100, "debit", today)
+ await _add_txn(session, test_user.id, acc2.id, 200, "credit", today)
+
+ pairs = await detect_transfer_pairs(session, test_user.id)
+ assert pairs == 0
+
+
+async def test_detect_excludes_opening_balance(session: AsyncSession, test_user):
+ """Opening balance transactions are excluded from pairing."""
+ acc1 = await _make_account(session, test_user.id, "OB A")
+ acc2 = await _make_account(session, test_user.id, "OB B")
+ today = date.today()
+
+ await _add_txn(session, test_user.id, acc1.id, 1000, "debit", today, source="opening_balance")
+ await _add_txn(session, test_user.id, acc2.id, 1000, "credit", today)
+
+ pairs = await detect_transfer_pairs(session, test_user.id)
+ assert pairs == 0
+
+
+async def test_detect_greedy_closest_date(session: AsyncSession, test_user):
+ """Greedy matching picks the closest date first."""
+ acc1 = await _make_account(session, test_user.id, "Greedy A")
+ acc2 = await _make_account(session, test_user.id, "Greedy B")
+ today = date.today()
+
+ debit = await _add_txn(session, test_user.id, acc1.id, 500, "debit", today)
+ await _add_txn(session, test_user.id, acc2.id, 500, "credit", today + timedelta(days=2))
+ close_credit = await _add_txn(session, test_user.id, acc2.id, 500, "credit", today)
+
+ pairs = await detect_transfer_pairs(session, test_user.id)
+ await session.commit()
+ assert pairs == 1
+
+ await session.refresh(debit)
+ await session.refresh(close_credit)
+ assert debit.transfer_pair_id == close_credit.transfer_pair_id
+
+
+# ---------------------------------------------------------------------------
+# unlink_transfer_pair
+# ---------------------------------------------------------------------------
+
+
+async def test_unlink_transfer_pair(session: AsyncSession, test_user):
+ """Unlinks a transfer pair, clearing transfer_pair_id on both."""
+ acc1 = await _make_account(session, test_user.id, "Unlink A")
+ acc2 = await _make_account(session, test_user.id, "Unlink B")
+ today = date.today()
+
+ debit = await _add_txn(session, test_user.id, acc1.id, 250, "debit", today)
+ credit = await _add_txn(session, test_user.id, acc2.id, 250, "credit", today)
+
+ await detect_transfer_pairs(session, test_user.id)
+ await session.commit()
+ await session.refresh(debit)
+ pair_id = debit.transfer_pair_id
+ assert pair_id is not None
+
+ unlinked = await unlink_transfer_pair(session, test_user.id, pair_id)
+ await session.commit()
+ assert unlinked == 2
+
+ await session.refresh(debit)
+ await session.refresh(credit)
+ assert debit.transfer_pair_id is None
+ assert credit.transfer_pair_id is None
+
+
+async def test_unlink_nonexistent_pair(session: AsyncSession, test_user):
+ """Unlinking a nonexistent pair returns 0."""
+ unlinked = await unlink_transfer_pair(session, test_user.id, uuid.uuid4())
+ assert unlinked == 0