Skip to content

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

test: add service-level tests for 6 more services (101 tests, 93% coverage)

Tássio Noronha94a68f824566
diff --git a/backend/tests/test_budget_service.py b/backend/tests/test_budget_service.py
new file mode 100644
index 00000000..7bdd1d18
--- /dev/null
+++ b/backend/tests/test_budget_service.py
@@ -0,0 +1,426 @@
+import uuid
+from datetime import date, datetime, timezone
+from decimal import Decimal
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.category_group import CategoryGroup
+from app.models.transaction import Transaction
+from app.schemas.budget import BudgetCreate, BudgetUpdate
+from app.services.budget_service import (
+ create_budget,
+ delete_budget,
+ get_budget,
+ get_budget_vs_actual,
+ get_budgets,
+ update_budget,
+)
+
+
+# ---------------------------------------------------------------------------
+# create_budget
+# ---------------------------------------------------------------------------
+
+
+async def test_create_budget(session: AsyncSession, test_user, test_categories):
+ data = BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("500.00"),
+ month=date(2025, 3, 15), # mid-month — should normalize to day=1
+ )
+ budget = await create_budget(session, test_user.id, data)
+
+ assert budget.id is not None
+ assert budget.amount == Decimal("500.00")
+ assert budget.month == date(2025, 3, 1)
+ assert budget.is_recurring is False
+
+
+async def test_create_recurring_budget(session: AsyncSession, test_user, test_categories):
+ data = BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("300.00"),
+ month=date(2025, 1, 1),
+ is_recurring=True,
+ )
+ budget = await create_budget(session, test_user.id, data)
+
+ assert budget.is_recurring is True
+ assert budget.month == date(2025, 1, 1)
+
+
+# ---------------------------------------------------------------------------
+# get_budgets
+# ---------------------------------------------------------------------------
+
+
+async def test_get_budgets_all(session: AsyncSession, test_user, test_categories):
+ await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("100"),
+ month=date(2025, 1, 1),
+ ),
+ )
+ await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[1].id,
+ amount=Decimal("200"),
+ month=date(2025, 2, 1),
+ ),
+ )
+
+ budgets = await get_budgets(session, test_user.id)
+ assert len(budgets) >= 2
+
+
+async def test_get_budgets_with_month_filter(session: AsyncSession, test_user, test_categories):
+ # Recurring default for Jan
+ await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("100"),
+ month=date(2025, 1, 1),
+ is_recurring=True,
+ ),
+ )
+ # Month-specific override for March
+ await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("999"),
+ month=date(2025, 3, 1),
+ is_recurring=False,
+ ),
+ )
+
+ # Querying March should get the override, not the recurring
+ budgets = await get_budgets(session, test_user.id, month=date(2025, 3, 1))
+ cat0_budgets = [b for b in budgets if b.category_id == test_categories[0].id]
+ assert len(cat0_budgets) == 1
+ assert cat0_budgets[0].amount == Decimal("999")
+ assert cat0_budgets[0].is_recurring is False
+
+
+async def test_get_budgets_recurring_default_for_future(
+ session: AsyncSession, test_user, test_categories
+):
+ # Recurring from Jan carries forward to June
+ await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[1].id,
+ amount=Decimal("250"),
+ month=date(2025, 1, 1),
+ is_recurring=True,
+ ),
+ )
+
+ budgets = await get_budgets(session, test_user.id, month=date(2025, 6, 1))
+ cat1_budgets = [b for b in budgets if b.category_id == test_categories[1].id]
+ assert len(cat1_budgets) == 1
+ assert cat1_budgets[0].amount == Decimal("250")
+
+
+# ---------------------------------------------------------------------------
+# get_budget
+# ---------------------------------------------------------------------------
+
+
+async def test_get_budget_by_id(session: AsyncSession, test_user, test_categories):
+ created = await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("400"),
+ month=date(2025, 4, 1),
+ ),
+ )
+ fetched = await get_budget(session, created.id, test_user.id)
+ assert fetched is not None
+ assert fetched.id == created.id
+
+
+async def test_get_budget_not_found(session: AsyncSession, test_user):
+ result = await get_budget(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# update_budget
+# ---------------------------------------------------------------------------
+
+
+async def test_update_budget_in_place(session: AsyncSession, test_user, test_categories):
+ budget = await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("100"),
+ month=date(2025, 5, 1),
+ ),
+ )
+ updated = await update_budget(
+ session, budget.id, test_user.id, BudgetUpdate(amount=Decimal("777"))
+ )
+
+ assert updated is not None
+ assert updated.id == budget.id
+ assert updated.amount == Decimal("777")
+
+
+async def test_update_recurring_different_effective_month_creates_new(
+ session: AsyncSession, test_user, test_categories
+):
+ budget = await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("100"),
+ month=date(2025, 1, 1),
+ is_recurring=True,
+ ),
+ )
+ updated = await update_budget(
+ session,
+ budget.id,
+ test_user.id,
+ BudgetUpdate(amount=Decimal("200"), effective_month=date(2025, 6, 1)),
+ )
+
+ assert updated is not None
+ assert updated.id != budget.id # new record
+ assert updated.month == date(2025, 6, 1)
+ assert updated.amount == Decimal("200")
+ assert updated.is_recurring is True
+
+
+async def test_update_budget_not_found(session: AsyncSession, test_user):
+ result = await update_budget(
+ session, uuid.uuid4(), test_user.id, BudgetUpdate(amount=Decimal("1"))
+ )
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# delete_budget
+# ---------------------------------------------------------------------------
+
+
+async def test_delete_budget(session: AsyncSession, test_user, test_categories):
+ budget = await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("50"),
+ month=date(2025, 7, 1),
+ ),
+ )
+ assert await delete_budget(session, budget.id, test_user.id) is True
+ assert await get_budget(session, budget.id, test_user.id) is None
+
+
+async def test_delete_budget_not_found(session: AsyncSession, test_user):
+ assert await delete_budget(session, uuid.uuid4(), test_user.id) is False
+
+
+# ---------------------------------------------------------------------------
+# get_budget_vs_actual
+# ---------------------------------------------------------------------------
+
+
+async def test_get_budget_vs_actual(session: AsyncSession, test_user, test_categories):
+ # Need a category group for budget_vs_actual join
+ group = CategoryGroup(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="TestGroup",
+ icon="folder",
+ color="#000000",
+ position=0,
+ is_system=False,
+ )
+ session.add(group)
+ await session.commit()
+
+ # Assign group to category
+ test_categories[0].group_id = group.id
+ await session.commit()
+
+ # Create account
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="BudgetAcc",
+ type="checking",
+ balance=Decimal("5000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+
+ # Create budget for March 2025
+ await create_budget(
+ session,
+ test_user.id,
+ BudgetCreate(
+ category_id=test_categories[0].id,
+ amount=Decimal("500"),
+ month=date(2025, 3, 1),
+ ),
+ )
+
+ # Create spending transaction in March
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="IFOOD",
+ amount=Decimal("100"),
+ date=date(2025, 3, 10),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ comparisons = await get_budget_vs_actual(session, test_user.id, month=date(2025, 3, 1))
+ assert len(comparisons) > 0
+
+ cat0_comp = [c for c in comparisons if c.category_id == test_categories[0].id]
+ assert len(cat0_comp) == 1
+ assert cat0_comp[0].budget_amount == Decimal("500")
+ assert cat0_comp[0].actual_amount == Decimal("100")
+ assert cat0_comp[0].percentage_used == pytest.approx(20.0)
+
+
+async def test_budget_vs_actual_excludes_transfers(
+ session: AsyncSession, test_user, test_categories
+):
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="BvAXfer",
+ type="checking",
+ balance=Decimal("5000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+
+ pair_id = uuid.uuid4()
+ txns = [
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Transfer",
+ amount=Decimal("200"),
+ date=date(2025, 4, 5),
+ type="debit",
+ source="manual",
+ transfer_pair_id=pair_id,
+ created_at=datetime.now(timezone.utc),
+ ),
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Real spend",
+ amount=Decimal("50"),
+ date=date(2025, 4, 6),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ ),
+ ]
+ session.add_all(txns)
+ await session.commit()
+
+ comparisons = await get_budget_vs_actual(session, test_user.id, month=date(2025, 4, 1))
+ cat0 = [c for c in comparisons if c.category_id == test_categories[0].id]
+ if cat0:
+ assert cat0[0].actual_amount == Decimal("50")
+
+
+async def test_budget_vs_actual_includes_prev_month(
+ session: AsyncSession, test_user, test_categories
+):
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="PrevMonth",
+ type="checking",
+ balance=Decimal("5000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+
+ # Spending in Feb (prev month)
+ txn_prev = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Feb spend",
+ amount=Decimal("75"),
+ date=date(2025, 2, 15),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ # Spending in March (current)
+ txn_curr = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=test_categories[0].id,
+ description="Mar spend",
+ amount=Decimal("120"),
+ date=date(2025, 3, 15),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add_all([txn_prev, txn_curr])
+ await session.commit()
+
+ comparisons = await get_budget_vs_actual(session, test_user.id, month=date(2025, 3, 1))
+ cat0 = [c for c in comparisons if c.category_id == test_categories[0].id]
+ if cat0:
+ assert cat0[0].prev_month_amount == Decimal("75")
diff --git a/backend/tests/test_category_group_service.py b/backend/tests/test_category_group_service.py
new file mode 100644
index 00000000..0ba241a4
--- /dev/null
+++ b/backend/tests/test_category_group_service.py
@@ -0,0 +1,215 @@
+import uuid
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.category import Category
+from app.schemas.category_group import CategoryGroupCreate, CategoryGroupUpdate
+from app.services.category_group_service import (
+ DEFAULT_GROUPS_I18N,
+ create_default_groups,
+ create_group,
+ delete_group,
+ get_group,
+ get_groups,
+ update_group,
+)
+
+
+# ---------------------------------------------------------------------------
+# create_default_groups
+# ---------------------------------------------------------------------------
+
+
+async def test_create_default_groups(session: AsyncSession, test_user):
+ groups = await create_default_groups(session, test_user.id, lang="pt-BR")
+ await session.commit()
+
+ assert len(groups) == len(DEFAULT_GROUPS_I18N)
+ assert "housing" in groups
+ assert "food" in groups
+ assert "income" in groups
+
+ # Check localized names
+ assert groups["housing"].name == "Moradia"
+ assert groups["food"].name == "Alimentação"
+ assert groups["income"].name == "Renda"
+
+ # All should be system groups
+ for g in groups.values():
+ assert g.is_system is True
+
+
+async def test_create_default_groups_english(session: AsyncSession, test_user):
+ groups = await create_default_groups(session, test_user.id, lang="en")
+ await session.commit()
+
+ assert groups["housing"].name == "Housing"
+ assert groups["food"].name == "Food & Dining"
+
+
+# ---------------------------------------------------------------------------
+# get_groups
+# ---------------------------------------------------------------------------
+
+
+async def test_get_groups_ordered_by_position(session: AsyncSession, test_user):
+ await create_default_groups(session, test_user.id)
+ await session.commit()
+
+ groups = await get_groups(session, test_user.id)
+ assert len(groups) == len(DEFAULT_GROUPS_I18N)
+
+ positions = [g.position for g in groups]
+ assert positions == sorted(positions)
+
+
+async def test_get_groups_loads_categories(session: AsyncSession, test_user):
+ groups_map = await create_default_groups(session, test_user.id)
+ await session.commit()
+
+ # Add a category to one group
+ cat = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="TestCat",
+ icon="star",
+ color="#FF0000",
+ is_system=False,
+ group_id=groups_map["food"].id,
+ )
+ session.add(cat)
+ await session.commit()
+
+ groups = await get_groups(session, test_user.id)
+ food_group = [g for g in groups if g.name == "Alimentação"][0]
+ assert len(food_group.categories) >= 1
+
+
+# ---------------------------------------------------------------------------
+# get_group / create_group / update_group
+# ---------------------------------------------------------------------------
+
+
+async def test_create_custom_group(session: AsyncSession, test_user):
+ data = CategoryGroupCreate(name="Pets", icon="paw-print", color="#FF5733", position=10)
+ group = await create_group(session, test_user.id, data)
+
+ assert group.name == "Pets"
+ assert group.icon == "paw-print"
+ assert group.is_system is False
+
+
+async def test_get_group_by_id(session: AsyncSession, test_user):
+ created = await create_group(
+ session,
+ test_user.id,
+ CategoryGroupCreate(name="Lookup", icon="search", color="#000000"),
+ )
+ fetched = await get_group(session, created.id, test_user.id)
+ assert fetched is not None
+ assert fetched.id == created.id
+
+
+async def test_get_group_not_found(session: AsyncSession, test_user):
+ result = await get_group(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_update_group(session: AsyncSession, test_user):
+ group = await create_group(
+ session,
+ test_user.id,
+ CategoryGroupCreate(name="Old", icon="x", color="#111111"),
+ )
+ updated = await update_group(
+ session,
+ group.id,
+ test_user.id,
+ CategoryGroupUpdate(name="New", color="#222222"),
+ )
+ assert updated is not None
+ assert updated.name == "New"
+ assert updated.color == "#222222"
+ assert updated.icon == "x" # unchanged
+
+
+async def test_update_group_not_found(session: AsyncSession, test_user):
+ result = await update_group(
+ session,
+ uuid.uuid4(),
+ test_user.id,
+ CategoryGroupUpdate(name="Nope"),
+ )
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# delete_group
+# ---------------------------------------------------------------------------
+
+
+async def test_delete_custom_group(session: AsyncSession, test_user):
+ group = await create_group(
+ session,
+ test_user.id,
+ CategoryGroupCreate(name="ToDelete", icon="trash", color="#FF0000"),
+ )
+ assert await delete_group(session, group.id, test_user.id) is True
+ assert await get_group(session, group.id, test_user.id) is None
+
+
+async def test_delete_system_group_rejected(session: AsyncSession, test_user):
+ groups = await create_default_groups(session, test_user.id)
+ await session.commit()
+
+ # Try deleting a system group
+ system_group = groups["housing"]
+ assert await delete_group(session, system_group.id, test_user.id) is False
+ # Should still exist
+ assert await get_group(session, system_group.id, test_user.id) is not None
+
+
+async def test_delete_group_unlinks_categories(session: AsyncSession, test_user):
+ group = await create_group(
+ session,
+ test_user.id,
+ CategoryGroupCreate(name="UnlinkMe", icon="link", color="#00FF00"),
+ )
+ cat = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="ChildCat",
+ icon="star",
+ color="#0000FF",
+ is_system=False,
+ group_id=group.id,
+ )
+ session.add(cat)
+ await session.commit()
+
+ assert await delete_group(session, group.id, test_user.id) is True
+
+ # Category should still exist but group_id should be None
+ result = await session.execute(select(Category).where(Category.id == cat.id))
+ orphan = result.scalar_one_or_none()
+ assert orphan is not None
+ assert orphan.group_id is None
+
+
+async def test_delete_group_not_found(session: AsyncSession, test_user):
+ assert await delete_group(session, uuid.uuid4(), test_user.id) is False
diff --git a/backend/tests/test_category_service.py b/backend/tests/test_category_service.py
index 6d7469cd..4caf1e76 100644
--- a/backend/tests/test_category_service.py
+++ b/backend/tests/test_category_service.py
@@ -1,9 +1,11 @@
import uuid
+import pytest
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.category import Category
-from app.models.user import User
+from app.models.category_group import CategoryGroup
from app.schemas.category import CategoryCreate, CategoryUpdate
from app.services.category_service import (
DEFAULT_CATEGORIES_I18N,
@@ -11,124 +13,235 @@ from app.services.category_service import (
create_default_categories,
delete_category,
get_categories,
+ get_category,
update_category,
)
-async def test_create_default_categories(session: AsyncSession, test_user: User):
- """create_default_categories should create all default system categories."""
- categories = await create_default_categories(session, test_user.id)
+# ---------------------------------------------------------------------------
+# create_default_categories
+# ---------------------------------------------------------------------------
+
+
+async def test_create_default_categories(session: AsyncSession, test_user):
+ categories = await create_default_categories(session, test_user.id, lang="pt-BR")
+
assert len(categories) == len(DEFAULT_CATEGORIES_I18N)
- # All should be system categories
+
+ names = {c.name for c in categories}
+ assert "Moradia" in names
+ assert "Alimentação" in names
+ assert "Transporte" in names
+ assert "Outros" in names
+
for cat in categories:
assert cat.is_system is True
- assert cat.user_id == test_user.id
- # Verify names match the DEFAULT_CATEGORIES_I18N (pt-BR by default)
- expected_names = {data["pt-BR"] for data in DEFAULT_CATEGORIES_I18N.values()}
- actual_names = {c.name for c in categories}
- assert actual_names == expected_names
-async def test_get_categories(
- session: AsyncSession, test_user: User, test_categories: list[Category]
-):
- """get_categories should return all categories for the given user."""
+async def test_create_default_categories_creates_groups(session: AsyncSession, test_user):
+ await create_default_categories(session, test_user.id, lang="pt-BR")
+
+ result = await session.execute(
+ select(CategoryGroup).where(CategoryGroup.user_id == test_user.id)
+ )
+ groups = result.scalars().all()
+ assert len(groups) == 6 # housing, food, transport, lifestyle, income, other
+
+
+async def test_create_default_categories_links_to_groups(session: AsyncSession, test_user):
+ categories = await create_default_categories(session, test_user.id, lang="pt-BR")
+
+ with_group = [c for c in categories if c.group_id is not None]
+ assert len(with_group) == len(DEFAULT_CATEGORIES_I18N)
+
+
+async def test_create_default_categories_english(session: AsyncSession, test_user):
+ categories = await create_default_categories(session, test_user.id, lang="en")
+
+ names = {c.name for c in categories}
+ assert "Housing" in names
+ assert "Food & Dining" in names
+ assert "Transport" in names
+
+
+async def test_create_default_categories_race_guard(session: AsyncSession, test_user):
+ """Second call should return existing instead of duplicating."""
+ first = await create_default_categories(session, test_user.id, lang="pt-BR")
+ second = await create_default_categories(session, test_user.id, lang="pt-BR")
+
+ assert len(second) == len(first)
+ first_ids = {c.id for c in first}
+ second_ids = {c.id for c in second}
+ assert first_ids == second_ids
+
+
+# ---------------------------------------------------------------------------
+# get_categories
+# ---------------------------------------------------------------------------
+
+
+async def test_get_categories_ordered(session: AsyncSession, test_user):
+ await create_default_categories(session, test_user.id)
+
+ custom = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="AAA Custom",
+ icon="star",
+ color="#FF0000",
+ is_system=False,
+ )
+ session.add(custom)
+ await session.commit()
+
categories = await get_categories(session, test_user.id)
- assert len(categories) == len(test_categories)
- returned_ids = {c.id for c in categories}
- expected_ids = {c.id for c in test_categories}
- assert returned_ids == expected_ids
+ system_cats = [c for c in categories if c.is_system]
+ custom_cats = [c for c in categories if not c.is_system]
+
+ if system_cats and custom_cats:
+ system_idx = categories.index(system_cats[0])
+ custom_idx = categories.index(custom_cats[0])
+ assert system_idx < custom_idx
async def test_get_categories_excludes_other_users(
- session: AsyncSession, test_user: User, test_categories: list[Category]
+ session: AsyncSession, test_user, test_categories
):
- """get_categories should not return categories belonging to other users."""
- other_user_id = uuid.uuid4()
- categories = await get_categories(session, other_user_id)
+ categories = await get_categories(session, uuid.uuid4())
assert len(categories) == 0
-async def test_create_category(session: AsyncSession, test_user: User):
- """create_category should create a custom (non-system) category."""
- data = CategoryCreate(name="Educacao", icon="📚", color="#9333EA")
- category = await create_category(session, test_user.id, data)
+# ---------------------------------------------------------------------------
+# get_category / create_category / update_category
+# ---------------------------------------------------------------------------
- assert category.id is not None
- assert category.name == "Educacao"
- assert category.icon == "📚"
- assert category.color == "#9333EA"
- assert category.user_id == test_user.id
- assert category.is_system is False
+async def test_create_custom_category(session: AsyncSession, test_user):
+ data = CategoryCreate(name="Pets", icon="paw-print", color="#8B4513")
+ cat = await create_category(session, test_user.id, data)
-async def test_update_category(
- session: AsyncSession, test_user: User, test_categories: list[Category]
-):
- """update_category should update name, icon, and color."""
- cat = test_categories[0] # Alimentacao
- data = CategoryUpdate(name="Comida", icon="🍕", color="#FF6347")
- updated = await update_category(session, cat.id, test_user.id, data)
+ assert cat.name == "Pets"
+ assert cat.icon == "paw-print"
+ assert cat.is_system is False
+
+async def test_create_category_with_group(session: AsyncSession, test_user):
+ from app.services.category_group_service import create_group
+ from app.schemas.category_group import CategoryGroupCreate
+
+ group = await create_group(
+ session,
+ test_user.id,
+ CategoryGroupCreate(name="CustomGroup", icon="folder", color="#000"),
+ )
+ cat = await create_category(
+ session,
+ test_user.id,
+ CategoryCreate(name="WithGroup", icon="star", color="#FFF", group_id=group.id),
+ )
+ assert cat.group_id == group.id
+
+
+async def test_get_category_by_id(session: AsyncSession, test_user):
+ created = await create_category(
+ session,
+ test_user.id,
+ CategoryCreate(name="Lookup", icon="search", color="#000000"),
+ )
+ fetched = await get_category(session, created.id, test_user.id)
+ assert fetched is not None
+ assert fetched.id == created.id
+
+
+async def test_get_category_not_found(session: AsyncSession, test_user):
+ result = await get_category(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_update_category(session: AsyncSession, test_user):
+ cat = await create_category(
+ session,
+ test_user.id,
+ CategoryCreate(name="OldName", icon="x", color="#111111"),
+ )
+ updated = await update_category(
+ session,
+ cat.id,
+ test_user.id,
+ CategoryUpdate(name="NewName", color="#222222"),
+ )
assert updated is not None
- assert updated.name == "Comida"
- assert updated.icon == "🍕"
- assert updated.color == "#FF6347"
+ assert updated.name == "NewName"
+ assert updated.color == "#222222"
+ assert updated.icon == "x"
-async def test_update_category_partial(
- session: AsyncSession, test_user: User, test_categories: list[Category]
-):
- """update_category with partial data should only update provided fields."""
- cat = test_categories[1] # Transporte
+async def test_update_category_partial(session: AsyncSession, test_user, test_categories):
+ cat = test_categories[1]
original_icon = cat.icon
original_color = cat.color
- data = CategoryUpdate(name="Mobilidade")
- updated = await update_category(session, cat.id, test_user.id, data)
-
+ updated = await update_category(
+ session,
+ cat.id,
+ test_user.id,
+ CategoryUpdate(name="Mobilidade"),
+ )
assert updated is not None
assert updated.name == "Mobilidade"
assert updated.icon == original_icon
assert updated.color == original_color
-async def test_update_category_not_found(session: AsyncSession, test_user: User):
- """update_category should return None for non-existent category."""
- data = CategoryUpdate(name="Ghost")
- result = await update_category(session, uuid.uuid4(), test_user.id, data)
+async def test_update_category_not_found(session: AsyncSession, test_user):
+ result = await update_category(
+ session,
+ uuid.uuid4(),
+ test_user.id,
+ CategoryUpdate(name="Nope"),
+ )
assert result is None
-async def test_delete_category(session: AsyncSession, test_user: User):
- """delete_category should successfully delete a non-system category."""
- # Create a non-system category first
- data = CategoryCreate(name="Temporaria", icon="🗑️", color="#000000")
- cat = await create_category(session, test_user.id, data)
- assert cat.is_system is False
+# ---------------------------------------------------------------------------
+# delete_category
+# ---------------------------------------------------------------------------
- result = await delete_category(session, cat.id, test_user.id)
- assert result is True
- # Verify it's gone
- from app.services.category_service import get_category
+async def test_delete_custom_category(session: AsyncSession, test_user):
+ cat = await create_category(
+ session,
+ test_user.id,
+ CategoryCreate(name="ToDelete", icon="trash", color="#FF0000"),
+ )
+ assert await delete_category(session, cat.id, test_user.id) is True
+ assert await get_category(session, cat.id, test_user.id) is None
- deleted = await get_category(session, cat.id, test_user.id)
- assert deleted is None
+async def test_delete_system_category_rejected(session: AsyncSession, test_user):
+ categories = await create_default_categories(session, test_user.id)
+ system_cat = categories[0]
-async def test_delete_system_category_fails(
- session: AsyncSession, test_user: User, test_categories: list[Category]
-):
- """delete_category should refuse to delete system categories (returns False)."""
- system_cat = test_categories[0] # is_system=True from fixture
assert system_cat.is_system is True
+ assert await delete_category(session, system_cat.id, test_user.id) is False
+ assert await get_category(session, system_cat.id, test_user.id) is not None
- result = await delete_category(session, system_cat.id, test_user.id)
- assert result is False
-
- # Verify it still exists
- from app.services.category_service import get_category
- still_exists = await get_category(session, system_cat.id, test_user.id)
- assert still_exists is not None
- assert still_exists.id == system_cat.id
+async def test_delete_category_not_found(session: AsyncSession, test_user):
+ assert await delete_category(session, uuid.uuid4(), test_user.id) is False
diff --git a/backend/tests/test_recurring_transaction_service.py b/backend/tests/test_recurring_transaction_service.py
new file mode 100644
index 00000000..50dd103c
--- /dev/null
+++ b/backend/tests/test_recurring_transaction_service.py
@@ -0,0 +1,365 @@
+import uuid
+from datetime import date
+from decimal import Decimal
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.transaction import Transaction
+from app.schemas.recurring_transaction import RecurringTransactionCreate, RecurringTransactionUpdate
+from app.services.recurring_transaction_service import (
+ _advance_date,
+ create_recurring_transaction,
+ delete_recurring_transaction,
+ generate_pending,
+ get_occurrences_in_range,
+ get_recurring_transaction,
+ get_recurring_transactions,
+ update_recurring_transaction,
+)
+
+
+async def test_account_for_recurring(session: AsyncSession, test_user) -> Account:
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="RecurAcc",
+ type="checking",
+ balance=Decimal("10000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+# ---------------------------------------------------------------------------
+# CRUD
+# ---------------------------------------------------------------------------
+
+
+async def test_create_recurring_transaction(
+ session: AsyncSession, test_user, test_account_for_recurring
+):
+ data = RecurringTransactionCreate(
+ description="Netflix",
+ amount=Decimal("39.90"),
+ type="debit",
+ frequency="monthly",
+ start_date=date(2025, 1, 15),
+ account_id=test_account_for_recurring.id,
+ )
+ rec = await create_recurring_transaction(session, test_user.id, data)
+
+ assert rec.id is not None
+ assert rec.description == "Netflix"
+ assert rec.amount == Decimal("39.90")
+ assert rec.frequency == "monthly"
+ assert rec.next_occurrence == date(2025, 1, 15)
+ assert rec.is_active is True
+
+
+async def test_create_with_skip_first(session: AsyncSession, test_user, test_account_for_recurring):
+ data = RecurringTransactionCreate(
+ description="Rent",
+ amount=Decimal("2000"),
+ type="debit",
+ frequency="monthly",
+ start_date=date(2025, 3, 1),
+ account_id=test_account_for_recurring.id,
+ skip_first=True,
+ )
+ rec = await create_recurring_transaction(session, test_user.id, data)
+
+ # skip_first should advance to next month
+ assert rec.start_date == date(2025, 3, 1)
+ assert rec.next_occurrence == date(2025, 4, 1)
+
+
+async def test_get_recurring_transactions(
+ session: AsyncSession, test_user, test_account_for_recurring
+):
+ for desc, dt in [("Sub1", date(2025, 1, 1)), ("Sub2", date(2025, 2, 1))]:
+ await create_recurring_transaction(
+ session,
+ test_user.id,
+ RecurringTransactionCreate(
+ description=desc,
+ amount=Decimal("10"),
+ type="debit",
+ frequency="monthly",
+ start_date=dt,
+ account_id=test_account_for_recurring.id,
+ ),
+ )
+
+ result = await get_recurring_transactions(session, test_user.id)
+ assert len(result) >= 2
+
+ # Ordered by next_occurrence
+ dates = [r.next_occurrence for r in result]
+ assert dates == sorted(dates)
+
+
+async def test_get_recurring_transaction_by_id(
+ session: AsyncSession, test_user, test_account_for_recurring
+):
+ created = await create_recurring_transaction(
+ session,
+ test_user.id,
+ RecurringTransactionCreate(
+ description="Lookup",
+ amount=Decimal("50"),
+ type="debit",
+ frequency="weekly",
+ start_date=date(2025, 6, 1),
+ account_id=test_account_for_recurring.id,
+ ),
+ )
+ fetched = await get_recurring_transaction(session, created.id, test_user.id)
+ assert fetched is not None
+ assert fetched.id == created.id
+
+
+async def test_get_recurring_transaction_not_found(session: AsyncSession, test_user):
+ result = await get_recurring_transaction(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_update_recurring_transaction(
+ session: AsyncSession, test_user, test_account_for_recurring
+):
+ rec = await create_recurring_transaction(
+ session,
+ test_user.id,
+ RecurringTransactionCreate(
+ description="Old",
+ amount=Decimal("100"),
+ type="debit",
+ frequency="monthly",
+ start_date=date(2025, 1, 1),
+ account_id=test_account_for_recurring.id,
+ ),
+ )
+ updated = await update_recurring_transaction(
+ session,
+ rec.id,
+ test_user.id,
+ RecurringTransactionUpdate(description="Updated", amount=Decimal("150")),
+ )
+ assert updated is not None
+ assert updated.description == "Updated"
+ assert updated.amount == Decimal("150")
+
+
+async def test_update_recurring_not_found(session: AsyncSession, test_user):
+ result = await update_recurring_transaction(
+ session,
+ uuid.uuid4(),
+ test_user.id,
+ RecurringTransactionUpdate(description="Nope"),
+ )
+ assert result is None
+
+
+async def test_delete_recurring_transaction(
+ session: AsyncSession, test_user, test_account_for_recurring
+):
+ rec = await create_recurring_transaction(
+ session,
+ test_user.id,
+ RecurringTransactionCreate(
+ description="ToDelete",
+ amount=Decimal("10"),
+ type="debit",
+ frequency="monthly",
+ start_date=date(2025, 1, 1),
+ account_id=test_account_for_recurring.id,
+ ),
+ )
+ assert await delete_recurring_transaction(session, rec.id, test_user.id) is True
+ assert await get_recurring_transaction(session, rec.id, test_user.id) is None
+
+
+async def test_delete_recurring_not_found(session: AsyncSession, test_user):
+ assert await delete_recurring_transaction(session, uuid.uuid4(), test_user.id) is False
+
+
+# ---------------------------------------------------------------------------
+# _advance_date
+# ---------------------------------------------------------------------------
+
+
+def test_advance_date_monthly():
+ assert _advance_date(date(2025, 1, 15), "monthly") == date(2025, 2, 15)
+ assert _advance_date(date(2025, 12, 10), "monthly") == date(2026, 1, 10)
+
+
+def test_advance_date_monthly_overflow():
+ # Jan 31 -> Feb should clamp to 28
+ assert _advance_date(date(2025, 1, 31), "monthly") == date(2025, 2, 28)
+ # Leap year: Jan 31 -> Feb 29
+ assert _advance_date(date(2024, 1, 31), "monthly") == date(2024, 2, 29)
+
+
+def test_advance_date_weekly():
+ assert _advance_date(date(2025, 1, 1), "weekly") == date(2025, 1, 8)
+ assert _advance_date(date(2025, 12, 29), "weekly") == date(2026, 1, 5)
+
+
+def test_advance_date_yearly():
+ assert _advance_date(date(2025, 3, 15), "yearly") == date(2026, 3, 15)
+ # Leap year: Feb 29 -> Feb 28 next year
+ assert _advance_date(date(2024, 2, 29), "yearly") == date(2025, 2, 28)
+
+
+# ---------------------------------------------------------------------------
+# get_occurrences_in_range
+# ---------------------------------------------------------------------------
+
+
+def test_get_occurrences_in_range_monthly():
+ occurrences = get_occurrences_in_range(
+ start=date(2025, 1, 1),
+ frequency="monthly",
+ end_date=None,
+ range_start=date(2025, 3, 1),
+ range_end=date(2025, 6, 1),
+ )
+ assert occurrences == [date(2025, 3, 1), date(2025, 4, 1), date(2025, 5, 1)]
+
+
+def test_get_occurrences_in_range_respects_end_date():
+ occurrences = get_occurrences_in_range(
+ start=date(2025, 1, 1),
+ frequency="monthly",
+ end_date=date(2025, 4, 15),
+ range_start=date(2025, 3, 1),
+ range_end=date(2025, 12, 1),
+ )
+ assert occurrences == [date(2025, 3, 1), date(2025, 4, 1)]
+
+
+def test_get_occurrences_in_range_weekly():
+ occurrences = get_occurrences_in_range(
+ start=date(2025, 1, 6),
+ frequency="weekly",
+ end_date=None,
+ range_start=date(2025, 1, 6),
+ range_end=date(2025, 1, 27),
+ )
+ assert len(occurrences) == 3 # Jan 6, 13, 20 (range_end is exclusive)
+
+
+def test_get_occurrences_in_range_empty():
+ occurrences = get_occurrences_in_range(
+ start=date(2025, 6, 1),
+ frequency="monthly",
+ end_date=None,
+ range_start=date(2025, 1, 1),
+ range_end=date(2025, 3, 1),
+ )
+ assert occurrences == []
+
+
+# ---------------------------------------------------------------------------
+# generate_pending
+# ---------------------------------------------------------------------------
+
+
+async def test_generate_pending(session: AsyncSession, test_user, test_account_for_recurring):
+ rec = await create_recurring_transaction(
+ session,
+ test_user.id,
+ RecurringTransactionCreate(
+ description="Monthly Sub",
+ amount=Decimal("29.90"),
+ type="debit",
+ frequency="monthly",
+ start_date=date(2025, 1, 1),
+ account_id=test_account_for_recurring.id,
+ ),
+ )
+
+ count = await generate_pending(session, test_user.id, up_to=date(2025, 3, 15))
+ assert count == 3 # Jan, Feb, Mar
+
+ # Verify transactions were created
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.user_id == test_user.id,
+ Transaction.source == "recurring",
+ Transaction.description == "Monthly Sub",
+ )
+ )
+ txns = result.scalars().all()
+ assert len(txns) == 3
+
+ # next_occurrence should be advanced past cutoff
+ await session.refresh(rec)
+ assert rec.next_occurrence == date(2025, 4, 1)
+
+
+async def test_generate_pending_deactivates_past_end_date(
+ session: AsyncSession, test_user, test_account_for_recurring
+):
+ rec = await create_recurring_transaction(
+ session,
+ test_user.id,
+ RecurringTransactionCreate(
+ description="Short Sub",
+ amount=Decimal("10"),
+ type="debit",
+ frequency="monthly",
+ start_date=date(2025, 1, 1),
+ end_date=date(2025, 2, 15),
+ account_id=test_account_for_recurring.id,
+ ),
+ )
+
+ count = await generate_pending(session, test_user.id, up_to=date(2025, 12, 31))
+ # Should create Jan and Feb (Feb 1 <= Feb 15), then deactivate
+ assert count == 2
+
+ await session.refresh(rec)
+ assert rec.is_active is False
+
+
+async def test_generate_pending_no_duplicates(
+ session: AsyncSession, test_user, test_account_for_recurring
+):
+ await create_recurring_transaction(
+ session,
+ test_user.id,
+ RecurringTransactionCreate(
+ description="NoDup",
+ amount=Decimal("5"),
+ type="debit",
+ frequency="monthly",
+ start_date=date(2025, 1, 1),
+ account_id=test_account_for_recurring.id,
+ ),
+ )
+
+ # Generate once
+ count1 = await generate_pending(session, test_user.id, up_to=date(2025, 3, 1))
+ # Generate again with same cutoff — should produce 0
+ count2 = await generate_pending(session, test_user.id, up_to=date(2025, 3, 1))
+ assert count1 == 3
+ assert count2 == 0
diff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.py
new file mode 100644
index 00000000..c284aa46
--- /dev/null
+++ b/backend/tests/test_rule_service.py
@@ -0,0 +1,420 @@
+import uuid
+from datetime import date, datetime, timezone
+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.rule import RuleAction, RuleCondition, RuleCreate, RuleUpdate
+from app.services.rule_service import (
+ DuplicateRuleError,
+ apply_all_rules,
+ apply_rules_to_transaction,
+ create_default_rules,
+ create_rule,
+ delete_rule,
+ get_installed_packs,
+ get_rule,
+ get_rules,
+ install_rule_pack,
+ update_rule,
+)
+from app.services.category_service import create_default_categories
+
+
+# ---------------------------------------------------------------------------
+# CRUD
+# ---------------------------------------------------------------------------
+
+
+async def test_create_rule(session: AsyncSession, test_user, test_categories):
+ data = RuleCreate(
+ name="My Rule",
+ conditions_op="or",
+ conditions=[RuleCondition(field="description", op="contains", value="UBER")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[1].id))],
+ priority=10,
+ )
+ rule = await create_rule(session, test_user.id, data)
+
+ assert rule.id is not None
+ assert rule.name == "My Rule"
+ assert rule.conditions_op == "or"
+ assert len(rule.conditions) == 1
+ assert len(rule.actions) == 1
+ assert rule.is_active is True
+
+
+async def test_get_rules(session: AsyncSession, test_user, test_categories):
+ for name in ["Rule A", "Rule B"]:
+ await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name=name,
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ ),
+ )
+
+ rules = await get_rules(session, test_user.id)
+ assert len(rules) >= 2
+ names = {r.name for r in rules}
+ assert "Rule A" in names
+ assert "Rule B" in names
+
+
+async def test_get_rule_by_id(session: AsyncSession, test_user, test_categories):
+ created = await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="Lookup Rule",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ ),
+ )
+ fetched = await get_rule(session, created.id, test_user.id)
+ assert fetched is not None
+ assert fetched.id == created.id
+
+
+async def test_get_rule_not_found(session: AsyncSession, test_user):
+ result = await get_rule(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_update_rule(session: AsyncSession, test_user, test_categories):
+ rule = await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="Original",
+ conditions=[RuleCondition(field="description", op="contains", value="OLD")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ priority=5,
+ ),
+ )
+ updated = await update_rule(
+ session,
+ rule.id,
+ test_user.id,
+ RuleUpdate(name="Updated", priority=20),
+ )
+ assert updated is not None
+ assert updated.name == "Updated"
+ assert updated.priority == 20
+
+
+async def test_update_rule_not_found(session: AsyncSession, test_user):
+ result = await update_rule(
+ session,
+ uuid.uuid4(),
+ test_user.id,
+ RuleUpdate(name="Nope"),
+ )
+ assert result is None
+
+
+async def test_delete_rule(session: AsyncSession, test_user, test_categories):
+ rule = await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="ToDelete",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ ),
+ )
+ assert await delete_rule(session, rule.id, test_user.id) is True
+ assert await get_rule(session, rule.id, test_user.id) is None
+
+
+async def test_delete_rule_not_found(session: AsyncSession, test_user):
+ assert await delete_rule(session, uuid.uuid4(), test_user.id) is False
+
+
+# ---------------------------------------------------------------------------
+# DuplicateRuleError
+# ---------------------------------------------------------------------------
+
+
+async def test_create_duplicate_rule_raises(session: AsyncSession, test_user, test_categories):
+ data = RuleCreate(
+ name="Unique Name",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ )
+ await create_rule(session, test_user.id, data)
+
+ with pytest.raises(DuplicateRuleError):
+ await create_rule(session, test_user.id, data)
+
+
+async def test_update_rule_duplicate_name_raises(session: AsyncSession, test_user, test_categories):
+ rule_a = await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="Name A",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ ),
+ )
+ await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="Name B",
+ conditions=[RuleCondition(field="description", op="contains", value="Y")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ ),
+ )
+
+ with pytest.raises(DuplicateRuleError):
+ await update_rule(
+ session,
+ rule_a.id,
+ test_user.id,
+ RuleUpdate(name="Name B"),
+ )
+
+
+# ---------------------------------------------------------------------------
+# apply_rules_to_transaction
+# ---------------------------------------------------------------------------
+
+
+async def test_apply_rules_to_transaction(session: AsyncSession, test_user, test_categories):
+ # Create a rule matching UBER
+ await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="UBER Rule",
+ conditions_op="or",
+ conditions=[RuleCondition(field="description", op="starts_with", value="UBER")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[1].id))],
+ priority=10,
+ ),
+ )
+
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="RuleAcc",
+ type="checking",
+ balance=Decimal("1000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ description="UBER TRIP",
+ amount=Decimal("25.50"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ await apply_rules_to_transaction(session, test_user.id, txn)
+
+ assert txn.category_id == test_categories[1].id
+
+
+async def test_apply_rules_no_match(session: AsyncSession, test_user, test_categories):
+ await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="IFOOD Only",
+ conditions_op="or",
+ conditions=[RuleCondition(field="description", op="starts_with", value="IFOOD")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ ),
+ )
+
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="NoMatch",
+ type="checking",
+ balance=Decimal("1000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ description="RANDOM MERCHANT",
+ amount=Decimal("10"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ await apply_rules_to_transaction(session, test_user.id, txn)
+ assert txn.category_id is None
+
+
+# ---------------------------------------------------------------------------
+# apply_all_rules
+# ---------------------------------------------------------------------------
+
+
+async def test_apply_all_rules(session: AsyncSession, test_user, test_categories):
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="AllRules",
+ type="checking",
+ balance=Decimal("5000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+
+ # Create transactions
+ txn1 = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ description="UBER RIDE",
+ amount=Decimal("30"),
+ date=date(2025, 3, 5),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ txn2 = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ description="IFOOD RESTAURANTE",
+ amount=Decimal("45"),
+ date=date(2025, 3, 6),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add_all([txn1, txn2])
+ await session.commit()
+
+ # Create rules
+ await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="UBER apply-all",
+ conditions_op="or",
+ conditions=[RuleCondition(field="description", op="starts_with", value="UBER")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[1].id))],
+ priority=10,
+ ),
+ )
+ await create_rule(
+ session,
+ test_user.id,
+ RuleCreate(
+ name="IFOOD apply-all",
+ conditions_op="or",
+ conditions=[RuleCondition(field="description", op="starts_with", value="IFOOD")],
+ actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],
+ priority=10,
+ ),
+ )
+
+ count = await apply_all_rules(session, test_user.id)
+ assert count >= 2
+
+ await session.refresh(txn1)
+ await session.refresh(txn2)
+ assert txn1.category_id == test_categories[1].id # transport
+ assert txn2.category_id == test_categories[0].id # food
+
+
+# ---------------------------------------------------------------------------
+# create_default_rules / install_rule_pack / get_installed_packs
+# ---------------------------------------------------------------------------
+
+
+async def test_create_default_rules(session: AsyncSession, test_user):
+ # Need default categories first so rule templates can resolve
+ await create_default_categories(session, test_user.id, lang="pt-BR")
+
+ rules = await create_default_rules(session, test_user.id, lang="pt-BR")
+ assert len(rules) >= 3 # at least Streaming, Uber, Amazon, etc.
+
+ names = {r.name for r in rules}
+ assert "Uber" in names
+ assert "Amazon" in names
+
+
+async def test_install_rule_pack_br(session: AsyncSession, test_user):
+ await create_default_categories(session, test_user.id, lang="pt-BR")
+
+ rules = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+ assert len(rules) > 0
+
+ names = {r.name for r in rules}
+ assert "iFood / Rappi" in names
+
+
+async def test_install_rule_pack_skips_duplicates(session: AsyncSession, test_user):
+ await create_default_categories(session, test_user.id, lang="pt-BR")
+
+ first = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+ second = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+
+ assert len(first) > 0
+ assert len(second) == 0 # all already installed
+
+
+async def test_install_rule_pack_unknown_returns_empty(session: AsyncSession, test_user):
+ result = await install_rule_pack(session, test_user.id, "ZZ")
+ assert result == []
+
+
+async def test_get_installed_packs(session: AsyncSession, test_user):
+ await create_default_categories(session, test_user.id, lang="pt-BR")
+
+ packs_before = await get_installed_packs(session, test_user.id)
+ assert packs_before["BR"] is False
+
+ await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+
+ packs_after = await get_installed_packs(session, test_user.id)
+ assert packs_after["BR"] is True
diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.py
new file mode 100644
index 00000000..b4ed747b
--- /dev/null
+++ b/backend/tests/test_transaction_service.py
@@ -0,0 +1,497 @@
+import uuid
+from datetime import date, datetime, timezone
+from decimal import Decimal
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.rule import Rule
+from app.models.transaction import Transaction
+from app.schemas.transaction import TransactionCreate, TransactionUpdate
+from app.services.transaction_service import (
+ bulk_update_category,
+ create_transaction,
+ delete_transaction,
+ get_transaction,
+ get_transactions,
+ update_transaction,
+)
+
+
+async def txn_account(session: AsyncSession, test_user) -> Account:
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="TxnAcc",
+ type="checking",
+ balance=Decimal("10000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+# ---------------------------------------------------------------------------
+# create_transaction
+# ---------------------------------------------------------------------------
+
+
+async def test_create_transaction_manual(
+ session: AsyncSession, test_user, test_categories, txn_account
+):
+ data = TransactionCreate(
+ description="Lunch",
+ amount=Decimal("35.00"),
+ date=date(2025, 3, 10),
+ type="debit",
+ account_id=txn_account.id,
+ category_id=test_categories[0].id,
+ )
+ txn = await create_transaction(session, test_user.id, data)
+
+ assert txn.id is not None
+ assert txn.description == "Lunch"
+ assert txn.source == "manual"
+ assert txn.category_id == test_categories[0].id
+
+
+async def test_create_transaction_applies_rules(
+ session: AsyncSession, test_user, test_categories, txn_account
+):
+ # Create a rule
+ rule = Rule(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="UBER auto",
+ conditions_op="or",
+ conditions=[{"field": "description", "op": "starts_with", "value": "UBER"}],
+ actions=[{"op": "set_category", "value": str(test_categories[1].id)}],
+ priority=10,
+ is_active=True,
+ )
+ session.add(rule)
+ await session.commit()
+
+ # Create transaction without category — rule should apply
+ data = TransactionCreate(
+ description="UBER TRIP",
+ amount=Decimal("25"),
+ date=date(2025, 3, 10),
+ type="debit",
+ account_id=txn_account.id,
+ )
+ txn = await create_transaction(session, test_user.id, data)
+
+ assert txn.category_id == test_categories[1].id
+
+
+async def test_create_transaction_with_category_skips_rules(
+ session: AsyncSession, test_user, test_categories, txn_account
+):
+ rule = Rule(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="UBER skip",
+ conditions_op="or",
+ conditions=[{"field": "description", "op": "starts_with", "value": "UBER"}],
+ actions=[{"op": "set_category", "value": str(test_categories[1].id)}],
+ priority=10,
+ is_active=True,
+ )
+ session.add(rule)
+ await session.commit()
+
+ # Explicitly provide a different category — rule should NOT override
+ data = TransactionCreate(
+ description="UBER TRIP",
+ amount=Decimal("25"),
+ date=date(2025, 3, 10),
+ type="debit",
+ account_id=txn_account.id,
+ category_id=test_categories[0].id,
+ )
+ txn = await create_transaction(session, test_user.id, data)
+ assert txn.category_id == test_categories[0].id
+
+
+async def test_create_transaction_invalid_account(session: AsyncSession, test_user):
+ data = TransactionCreate(
+ description="Orphan",
+ amount=Decimal("10"),
+ date=date(2025, 3, 10),
+ type="debit",
+ account_id=uuid.uuid4(),
+ )
+ with pytest.raises(ValueError, match="Account not found"):
+ await create_transaction(session, test_user.id, data)
+
+
+# ---------------------------------------------------------------------------
+# get_transactions — pagination & filters
+# ---------------------------------------------------------------------------
+
+
+async def test_get_transactions_pagination(session: AsyncSession, test_user, txn_account):
+ # Create 5 transactions
+ for i in range(5):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description=f"Txn {i}",
+ amount=Decimal("10"),
+ date=date(2025, 3, i + 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ page1, total = await get_transactions(session, test_user.id, limit=2, page=1)
+ assert total >= 5
+ assert len(page1) == 2
+
+ page2, _ = await get_transactions(session, test_user.id, limit=2, page=2)
+ assert len(page2) == 2
+
+ # No overlap
+ p1_ids = {t.id for t in page1}
+ p2_ids = {t.id for t in page2}
+ assert p1_ids.isdisjoint(p2_ids)
+
+
+async def test_get_transactions_filter_by_account(session: AsyncSession, test_user, txn_account):
+ other_account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Other",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
+ )
+ session.add(other_account)
+ await session.commit()
+
+ txn1 = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="In main",
+ amount=Decimal("10"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ txn2 = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=other_account.id,
+ description="In other",
+ amount=Decimal("20"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add_all([txn1, txn2])
+ await session.commit()
+
+ results, _ = await get_transactions(session, test_user.id, account_id=txn_account.id)
+ descs = {t.description for t in results}
+ assert "In main" in descs
+ assert "In other" not in descs
+
+
+async def test_get_transactions_filter_by_category(
+ session: AsyncSession, test_user, test_categories, txn_account
+):
+ txn1 = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ category_id=test_categories[0].id,
+ description="Cat A",
+ amount=Decimal("10"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ txn2 = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ category_id=test_categories[1].id,
+ description="Cat B",
+ amount=Decimal("20"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add_all([txn1, txn2])
+ await session.commit()
+
+ results, _ = await get_transactions(session, test_user.id, category_id=test_categories[0].id)
+ descs = {t.description for t in results}
+ assert "Cat A" in descs
+ assert "Cat B" not in descs
+
+
+async def test_get_transactions_filter_by_date_range(session: AsyncSession, test_user, txn_account):
+ txn_jan = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="Jan",
+ amount=Decimal("10"),
+ date=date(2025, 1, 15),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ txn_mar = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="Mar",
+ amount=Decimal("10"),
+ date=date(2025, 3, 15),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add_all([txn_jan, txn_mar])
+ await session.commit()
+
+ results, _ = await get_transactions(
+ session,
+ test_user.id,
+ from_date=date(2025, 3, 1),
+ to_date=date(2025, 3, 31),
+ )
+ descs = {t.description for t in results}
+ assert "Mar" in descs
+ assert "Jan" not in descs
+
+
+async def test_get_transactions_filter_by_search(session: AsyncSession, test_user, txn_account):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="NETFLIX SUBSCRIPTION",
+ amount=Decimal("39.90"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ results, _ = await get_transactions(session, test_user.id, search="netflix")
+ descs = {t.description for t in results}
+ assert "NETFLIX SUBSCRIPTION" in descs
+
+
+async def test_get_transactions_filter_by_type(session: AsyncSession, test_user, txn_account):
+ txn_debit = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="Expense",
+ amount=Decimal("50"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ txn_credit = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="Income",
+ amount=Decimal("1000"),
+ date=date(2025, 3, 1),
+ type="credit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add_all([txn_debit, txn_credit])
+ await session.commit()
+
+ results, _ = await get_transactions(session, test_user.id, txn_type="credit")
+ types = {t.type for t in results}
+ assert "credit" in types
+ assert all(t.type == "credit" for t in results)
+
+
+# ---------------------------------------------------------------------------
+# get_transaction / update_transaction / delete_transaction
+# ---------------------------------------------------------------------------
+
+
+async def test_get_transaction_by_id(session: AsyncSession, test_user, txn_account):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="Lookup",
+ amount=Decimal("10"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ fetched = await get_transaction(session, txn.id, test_user.id)
+ assert fetched is not None
+ assert fetched.id == txn.id
+
+
+async def test_get_transaction_not_found(session: AsyncSession, test_user):
+ result = await get_transaction(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_update_transaction(session: AsyncSession, test_user, txn_account):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="Old",
+ amount=Decimal("10"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ updated = await update_transaction(
+ session,
+ txn.id,
+ test_user.id,
+ TransactionUpdate(description="New", amount=Decimal("99")),
+ )
+ assert updated is not None
+ assert updated.description == "New"
+ assert updated.amount == Decimal("99")
+
+
+async def test_update_transaction_not_found(session: AsyncSession, test_user):
+ result = await update_transaction(
+ session,
+ uuid.uuid4(),
+ test_user.id,
+ TransactionUpdate(description="Ghost"),
+ )
+ assert result is None
+
+
+async def test_delete_transaction(session: AsyncSession, test_user, txn_account):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="ToDelete",
+ amount=Decimal("5"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ assert await delete_transaction(session, txn.id, test_user.id) is True
+ assert await get_transaction(session, txn.id, test_user.id) is None
+
+
+async def test_delete_transaction_not_found(session: AsyncSession, test_user):
+ assert await delete_transaction(session, uuid.uuid4(), test_user.id) is False
+
+
+# ---------------------------------------------------------------------------
+# bulk_update_category
+# ---------------------------------------------------------------------------
+
+
+async def test_bulk_update_category(session: AsyncSession, test_user, test_categories, txn_account):
+ txns = []
+ for i in range(3):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description=f"Bulk {i}",
+ amount=Decimal("10"),
+ date=date(2025, 3, i + 1),
+ type="debit",
+ source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ txns.append(txn)
+ await session.commit()
+
+ ids = [t.id for t in txns]
+ count = await bulk_update_category(session, test_user.id, ids, test_categories[0].id)
+ assert count == 3
+
+ for txn in txns:
+ await session.refresh(txn)
+ assert txn.category_id == test_categories[0].id
+
+
+async def test_bulk_update_category_clear(
+ session: AsyncSession, test_user, test_categories, txn_account
+):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="ClearCat",
+ amount=Decimal("10"),
+ date=date(2025, 3, 1),
+ type="debit",
+ source="manual",
+ category_id=test_categories[0].id,
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ count = await bulk_update_category(session, test_user.id, [txn.id], category_id=None)
+ assert count == 1
+
+ await session.refresh(txn)
+ assert txn.category_id is None