Skip to content

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

fix(import): preselect CSV categories in preview (#812)

João Vitor Lucena5be1cf15deb8
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index d5419ad4..438ca6d1 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -658,8 +658,8 @@ async def enrich_with_category_suggestions(
hidden_categories = await get_hidden_category_ids(session, workspace_id)
category_name_map = {str(c.id): c.name for c in categories}
category_name_to_id = {
- c.name.strip().lower(): c.id
- for c in categories
+ c.name.strip().lower(): c.id
+ for c in categories
if c.id not in hidden_categories
}
@@ -678,7 +678,7 @@ async def enrich_with_category_suggestions(
category_id=None,
)
category_set = False
-
+
for rule in rules:
conditions = rule.conditions or []
actions = rule.actions or []
@@ -689,7 +689,7 @@ async def enrich_with_category_suggestions(
category_set,
hidden_category_ids=hidden_categories,
)
-
+
# If rules did not set a category, apply the CSV category if found
if not category_set and txn.category_name:
csv_cat_id = category_name_to_id.get(txn.category_name.strip().lower())
@@ -817,7 +817,7 @@ async def import_transactions(
import_payee_id = import_payee_entity.id
user_category_id = txn_data.category_id
- suggested_cat_id = txn_data.suggested_category_id
+ suggested_category_id = txn_data.suggested_category_id
csv_category_id = (
category_map.get(txn_data.category_name.strip().lower())
if txn_data.category_name
@@ -826,7 +826,7 @@ async def import_transactions(
category_id = (
None
if txn_data.force_uncategorized
- else user_category_id or suggested_cat_id or csv_category_id
+ else user_category_id or suggested_category_id
)
incoming = Transaction(
@@ -854,6 +854,8 @@ async def import_transactions(
incoming,
skip_category_rules=txn_data.force_uncategorized,
)
+ if preview.category_id is None and not txn_data.force_uncategorized:
+ preview.category_id = csv_category_id
# Normalize a detached candidate before either recurring match. If a
# generated placeholder already represents this occurrence, upgrade it
@@ -920,6 +922,8 @@ async def import_transactions(
incoming,
skip_category_rules=txn_data.force_uncategorized,
)
+ if incoming.category_id is None and not txn_data.force_uncategorized:
+ incoming.category_id = csv_category_id
if not txn_data.fx_rate:
await stamp_primary_amount(session, user_id, incoming)
diff --git a/backend/tests/test_import_api.py b/backend/tests/test_import_api.py
index 6d7fbbdd..335f2436 100644
--- a/backend/tests/test_import_api.py
+++ b/backend/tests/test_import_api.py
@@ -1,9 +1,13 @@
import json
+import uuid
import pytest
from httpx import AsyncClient
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
+from app.models.transaction import Transaction
@pytest.mark.asyncio
@@ -312,6 +316,46 @@ async def test_preview_returns_suggested_categories(
assert unknown["suggested_category_name"] is None
+async def test_preview_uses_csv_category_as_default(
+ client: AsyncClient, auth_headers, test_categories
+):
+ csv_content = (
+ "data,descricao,valor,categoria\n"
+ "10/02/2026,COMPRA QUALQUER,-25.50,Alimenta\u00e7\u00e3o\n"
+ ).encode("utf-8")
+
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("extrato.csv", csv_content, "text/csv")},
+ )
+
+ assert response.status_code == 200
+ txn = response.json()["transactions"][0]
+ assert txn["suggested_category_id"] == str(test_categories[0].id)
+ assert txn["suggested_category_name"] == "Alimenta\u00e7\u00e3o"
+
+
+async def test_preview_rule_overrides_csv_category_default(
+ client: AsyncClient, auth_headers, test_categories, test_rules
+):
+ csv_content = (
+ "data,descricao,valor,categoria\n"
+ "10/02/2026,UBER TRIP,-25.50,Alimenta\u00e7\u00e3o\n"
+ ).encode("utf-8")
+
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("extrato.csv", csv_content, "text/csv")},
+ )
+
+ assert response.status_code == 200
+ txn = response.json()["transactions"][0]
+ assert txn["suggested_category_id"] == str(test_categories[1].id)
+ assert txn["suggested_category_name"] == "Transporte"
+
+
async def test_import_with_excluded_transactions(
client: AsyncClient, auth_headers, test_account: Account
):
@@ -353,7 +397,12 @@ async def test_import_with_excluded_transactions(
async def test_import_with_category_override(
- client: AsyncClient, auth_headers, test_account: Account, test_categories: list
+ client: AsyncClient,
+ auth_headers,
+ test_account: Account,
+ test_categories: list,
+ test_rules,
+ session: AsyncSession,
):
override_cat_id = str(test_categories[0].id)
response = await client.post(
@@ -363,7 +412,7 @@ async def test_import_with_category_override(
"account_id": str(test_account.id),
"transactions": [
{
- "description": "GROCERY",
+ "description": "UBER EXPLICIT OVERRIDE",
"amount": "25.50",
"date": "2026-02-10",
"type": "debit",
@@ -380,3 +429,79 @@ async def test_import_with_category_override(
logs_resp = await client.get("/api/import-logs", headers=auth_headers)
log = next(entry for entry in logs_resp.json() if entry["id"] == import_log_id)
assert log["transaction_count"] == 1
+
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.import_id == uuid.UUID(import_log_id),
+ )
+ )
+ imported = result.scalar_one()
+ assert imported.category_id == test_categories[0].id
+
+
+async def test_import_rule_overrides_csv_category_default(
+ client: AsyncClient,
+ auth_headers,
+ test_account: Account,
+ test_categories: list,
+ test_rules,
+ session: AsyncSession,
+):
+ response = await client.post(
+ "/api/transactions/import",
+ headers=auth_headers,
+ json={
+ "account_id": str(test_account.id),
+ "transactions": [
+ {
+ "description": "UBER CSV DEFAULT",
+ "amount": "25.50",
+ "date": "2026-02-11",
+ "type": "debit",
+ "category_name": test_categories[0].name,
+ },
+ ],
+ },
+ )
+
+ assert response.status_code == 201
+ import_log_id = uuid.UUID(response.json()["import_log_id"])
+ result = await session.execute(
+ select(Transaction).where(Transaction.import_id == import_log_id)
+ )
+ imported = result.scalar_one()
+ assert imported.category_id == test_categories[1].id
+
+
+async def test_import_uses_csv_category_when_no_rule_matches(
+ client: AsyncClient,
+ auth_headers,
+ test_account: Account,
+ test_categories: list,
+ test_rules,
+ session: AsyncSession,
+):
+ response = await client.post(
+ "/api/transactions/import",
+ headers=auth_headers,
+ json={
+ "account_id": str(test_account.id),
+ "transactions": [
+ {
+ "description": "NO MATCH CSV DEFAULT",
+ "amount": "25.50",
+ "date": "2026-02-12",
+ "type": "debit",
+ "category_name": test_categories[0].name,
+ },
+ ],
+ },
+ )
+
+ assert response.status_code == 201
+ import_log_id = uuid.UUID(response.json()["import_log_id"])
+ result = await session.execute(
+ select(Transaction).where(Transaction.import_id == import_log_id)
+ )
+ imported = result.scalar_one()
+ assert imported.category_id == test_categories[0].id
diff --git a/frontend/src/pages/import.tsx b/frontend/src/pages/import.tsx
index 3cc9a1d9..c675be99 100644
--- a/frontend/src/pages/import.tsx
+++ b/frontend/src/pages/import.tsx
@@ -132,7 +132,7 @@ function TransactionImportPanel() {
excluded: rt.excluded,
category_id: rt.selected_category_id !== undefined
? (rt.selected_category_id ?? undefined)
- : (rt.suggested_category_id ?? undefined),
+ : undefined,
force_uncategorized: rt.selected_category_id === null,
}))
return transactionsApi.import(