Skip to content

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

feat: read type and category columns from CSV import (#117)

Leandro Nascimento95560864e85a
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index 27782f8a..4a56fa0d 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -99,13 +99,18 @@ class TransferRead(BaseModel):
transfer_pair_id: uuid.UUID
+class TransactionImport(TransactionBase):
+ """TransactionBase extended with import-only fields not exposed in read responses."""
+ category_name: Optional[str] = None
+
+
class TransactionImportPreview(BaseModel):
- transactions: list[TransactionBase]
+ transactions: list[TransactionImport]
detected_format: str
class TransactionImportRequest(BaseModel):
account_id: uuid.UUID
- transactions: list[TransactionBase]
+ transactions: list[TransactionImport]
filename: str = ""
detected_format: str = ""
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index b52fe19b..1c2eed8e 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -13,8 +13,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import get_settings
from app.models.account import Account
+from app.models.category import Category
from app.models.transaction import Transaction
-from app.schemas.transaction import TransactionBase
+from app.schemas.transaction import TransactionBase, TransactionImport
from app.services.credit_card_service import apply_effective_date
from app.services.rule_service import apply_rules_to_transaction
from app.services.fx_rate_service import stamp_primary_amount
@@ -84,7 +85,7 @@ def _is_balance_summary_row(description: str | None) -> bool:
return any(normalized.startswith(prefix) for prefix in _OFX_BALANCE_ROW_DESCRIPTIONS)
-def parse_ofx(content: bytes) -> list[TransactionBase]:
+def parse_ofx(content: bytes) -> list[TransactionImport]:
"""Parse OFX file content and return transactions."""
content = _preprocess_ofx_for_empty_fitid(content)
ofx = OfxParser.parse(io.BytesIO(content))
@@ -102,7 +103,7 @@ def parse_ofx(content: bytes) -> list[TransactionBase]:
# identifiers.
if external_id and external_id.startswith("SYNTH-"):
external_id = None
- transactions.append(TransactionBase(
+ transactions.append(TransactionImport(
description=description,
amount=abs(Decimal(str(txn.amount))),
date=txn.date.date() if hasattr(txn.date, 'date') else txn.date,
@@ -114,7 +115,7 @@ def parse_ofx(content: bytes) -> list[TransactionBase]:
return transactions
-def parse_qif(content: bytes) -> list[TransactionBase]:
+def parse_qif(content: bytes) -> list[TransactionImport]:
"""Parse QIF file content and return transactions."""
# Try UTF-8 first, fall back to Latin-1 for legacy software (e.g. Microsoft Money)
try:
@@ -166,7 +167,7 @@ def parse_qif(content: bytes) -> list[TransactionBase]:
continue
description = payee or memo or "Unknown"
- transactions.append(TransactionBase(
+ transactions.append(TransactionImport(
description=description,
amount=abs(amount),
date=txn_date,
@@ -177,7 +178,7 @@ def parse_qif(content: bytes) -> list[TransactionBase]:
return transactions
-def parse_camt(content: bytes) -> list[TransactionBase]:
+def parse_camt(content: bytes) -> list[TransactionImport]:
"""Parse CAMT.053 (ISO 20022) XML file content and return transactions."""
root = ET.fromstring(content)
@@ -244,7 +245,7 @@ def parse_camt(content: bytes) -> list[TransactionBase]:
# Extract currency from Ccy attribute on Amt element
txn_currency = amt_el.get('Ccy') or None
- transactions.append(TransactionBase(
+ transactions.append(TransactionImport(
description=description,
amount=abs(amount),
date=txn_date,
@@ -268,7 +269,7 @@ def parse_csv(
flip_amount: bool = False,
inflow_column: str | None = None,
outflow_column: str | None = None,
-) -> list[TransactionBase]:
+) -> list[TransactionImport]:
"""Parse CSV file content and return transactions.
Attempts to detect common column formats:
@@ -295,6 +296,8 @@ def parse_csv(
date_cols = ['date', 'data', 'dt', 'transaction_date', 'data_transacao']
desc_cols = ['description', 'descricao', 'desc', 'memo', 'historico', 'lancamento']
amount_cols = ['amount', 'valor', 'value', 'quantia']
+ type_cols = ['type', 'tipo']
+ category_cols = ['category', 'categoria']
currency_cols = ['currency', 'moeda', 'currency_code']
fx_rate_cols = ['fx_rate', 'fx_rate_used', 'taxa_cambio', 'exchange_rate', 'taxa']
@@ -319,6 +322,8 @@ def parse_csv(
else:
amount_col = find_col(amount_cols)
+ type_col = find_col(type_cols)
+ category_col = find_col(category_cols)
currency_col = find_col(currency_cols)
fx_rate_col = find_col(fx_rate_cols)
@@ -390,10 +395,14 @@ def parse_csv(
if flip_amount:
amount = -amount
- txn_type = "credit" if amount > 0 else "debit"
+ if type_col and row.get(type_col, '').strip() in ('credit', 'debit'):
+ txn_type = row[type_col].strip()
+ else:
+ txn_type = "credit" if amount > 0 else "debit"
amount = abs(amount)
- # Extract optional currency and fx_rate from CSV columns
+ # Extract optional category, currency and fx_rate from CSV columns
+ category_name = row[category_col].strip() if category_col and row.get(category_col) else None
txn_currency = None
txn_fx_rate = None
if currency_col and row.get(currency_col):
@@ -406,13 +415,14 @@ def parse_csv(
except Exception:
pass
- transactions.append(TransactionBase(
+ transactions.append(TransactionImport(
description=row[desc_col].strip(),
amount=abs(amount),
date=txn_date,
type=txn_type,
currency=txn_currency,
fx_rate=txn_fx_rate,
+ category_name=category_name,
))
return transactions
@@ -454,6 +464,12 @@ async def import_transactions(
account = account_result.scalar_one_or_none()
account_currency = account.currency if account else get_settings().default_currency
+ # Build category name → id map for this user (used when CSV provides category names)
+ category_result = await session.execute(
+ select(Category).where(Category.user_id == user_id)
+ )
+ category_map = {c.name: c.id for c in category_result.scalars()}
+
imported = 0
skipped = 0
for txn_data in transactions:
@@ -495,6 +511,8 @@ async def import_transactions(
import_payee_entity = await get_or_create_payee(session, user_id, import_payee_raw)
import_payee_id = import_payee_entity.id
+ category_id = category_map.get(getattr(txn_data, "category_name", None)) if getattr(txn_data, "category_name", None) else None
+
transaction = Transaction(
user_id=user_id,
account_id=account_id,
@@ -508,6 +526,7 @@ async def import_transactions(
currency=txn_currency,
payee=import_payee_raw,
payee_id=import_payee_id,
+ category_id=category_id,
)
apply_effective_date(transaction, account)
diff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.py
index ecedf7bd..9194a0f6 100644
--- a/backend/tests/test_import_service.py
+++ b/backend/tests/test_import_service.py
@@ -1009,6 +1009,352 @@ class TestImportTransactionsFx:
assert tx.amount_primary is not None
+# ═══════════════════════════════════════════════════════════════════════════
+# CSV TYPE COLUMN TESTS
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestParseCsvTypeColumn:
+ """Tests for explicit 'type' column support in parse_csv.
+
+ Before this fix, parse_csv always derived type from the amount sign.
+ Now, when a 'type' column is present with 'credit' or 'debit', it is
+ used directly — enabling all-positive-amount CSVs (like Securo exports).
+ """
+
+ def test_explicit_type_column_overrides_amount_sign(self):
+ """Positive amounts with type=debit should produce debit transactions."""
+ csv_content = (
+ "date,description,amount,type\n"
+ "2026-01-05,Salario Dia 5,13311.00,credit\n"
+ "2026-01-01,Financiamento Casa,577.00,debit\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert len(transactions) == 2
+ assert transactions[0].type == "credit"
+ assert transactions[0].amount == Decimal("13311.00")
+ assert transactions[1].type == "debit"
+ assert transactions[1].amount == Decimal("577.00")
+
+ def test_explicit_type_column_all_debit(self):
+ """All-positive CSV with type=debit should not become credit."""
+ csv_content = (
+ "date,description,amount,type\n"
+ "2026-01-01,Rent,1200.00,debit\n"
+ "2026-01-02,Internet,119.00,debit\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert all(t.type == "debit" for t in transactions)
+
+ def test_without_type_column_derives_from_sign(self):
+ """Without a type column, backward-compatible sign-based derivation applies."""
+ csv_content = (
+ "date,description,amount\n"
+ "2026-01-01,Expense,-100.00\n"
+ "2026-01-02,Income,500.00\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert transactions[0].type == "debit"
+ assert transactions[1].type == "credit"
+
+ def test_unknown_type_value_falls_back_to_sign(self):
+ """Unrecognized type values (not credit/debit) fall back to amount sign."""
+ csv_content = (
+ "date,description,amount,type\n"
+ "2026-01-01,Expense,-100.00,unknown\n"
+ "2026-01-02,Income,500.00,invalid\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert transactions[0].type == "debit"
+ assert transactions[1].type == "credit"
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# CSV CATEGORY COLUMN TESTS
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestParseCsvCategoryColumn:
+ """Tests for 'category' column support in parse_csv.
+
+ The category column value is stored as category_name on TransactionBase
+ and later resolved to a UUID by import_transactions.
+ """
+
+ def test_category_column_populates_category_name(self):
+ """CSV with a category column should set category_name on each transaction."""
+ csv_content = (
+ "date,description,amount,type,currency,category\n"
+ "2026-01-05,Salario Dia 5,13311.00,credit,BRL,Salário & Renda\n"
+ "2026-01-01,Financiamento Casa,577.00,debit,BRL,Moradia\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert len(transactions) == 2
+ assert transactions[0].category_name == "Salário & Renda"
+ assert transactions[1].category_name == "Moradia"
+
+ def test_without_category_column_leaves_none(self):
+ """CSV without category column should leave category_name as None."""
+ csv_content = (
+ "date,description,amount\n"
+ "2026-01-01,Grocery Store,-50.00\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert transactions[0].category_name is None
+
+ def test_empty_category_field_leaves_none(self):
+ """An empty category field should result in category_name = None."""
+ csv_content = (
+ "date,description,amount,type,currency,category\n"
+ "2026-01-01,Some Transaction,100.00,credit,BRL,\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert transactions[0].category_name is None
+
+ def test_portuguese_categoria_column_detected(self):
+ """Portuguese 'categoria' column should also be detected."""
+ csv_content = (
+ "data,descricao,valor,categoria\n"
+ "01/01/2026,Supermercado,-150.00,Alimentação\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert len(transactions) == 1
+ assert transactions[0].category_name == "Alimentação"
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# IMPORT TRANSACTIONS WITH CATEGORY RESOLUTION
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestImportTransactionsWithCategory:
+ """Tests for category_name → category_id resolution in import_transactions."""
+
+ @pytest.mark.asyncio
+ @patch("app.services.fx_rate_service._provider")
+ async def test_known_category_name_resolved_to_id(
+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,
+ ):
+ """When category_name matches a user category, category_id should be set."""
+ from app.models.category import Category
+ from app.models.transaction import Transaction
+ from sqlalchemy import select
+
+ category = Category(
+ id=uuid.uuid4(), user_id=test_user.id,
+ name="Salário & Renda", icon="banknote", color="#16A34A",
+ )
+ session.add(category)
+ await session.commit()
+
+ from app.schemas.transaction import TransactionImport
+ txns = [TransactionImport(
+ description="Salario Dia 5",
+ amount=Decimal("13311.00"),
+ date=date(2026, 1, 5),
+ type="credit",
+ category_name="Salário & Renda",
+ )]
+
+ imported, skipped, _ = await import_transactions(
+ session, test_user.id, test_account.id, txns, "import",
+ )
+
+ assert imported == 1
+ assert skipped == 0
+
+ tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "Salario Dia 5")
+ )).scalar_one()
+ assert tx.category_id == category.id
+
+ @pytest.mark.asyncio
+ @patch("app.services.fx_rate_service._provider")
+ async def test_unknown_category_name_leaves_uncategorized(
+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,
+ ):
+ """When category_name has no match, category_id should be None."""
+ from app.schemas.transaction import TransactionImport
+ from app.models.transaction import Transaction
+ from sqlalchemy import select
+
+ txns = [TransactionImport(
+ description="Unknown Cat Transaction",
+ amount=Decimal("100.00"),
+ date=date(2026, 1, 10),
+ type="debit",
+ category_name="Categoria Inexistente",
+ )]
+
+ imported, _, _ = await import_transactions(
+ session, test_user.id, test_account.id, txns, "import",
+ )
+
+ assert imported == 1
+
+ tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "Unknown Cat Transaction")
+ )).scalar_one()
+ assert tx.category_id is None
+
+ @pytest.mark.asyncio
+ @patch("app.services.fx_rate_service._provider")
+ async def test_no_category_name_leaves_uncategorized(
+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,
+ ):
+ """When category_name is None, category_id should be None."""
+ from app.schemas.transaction import TransactionImport
+ from app.models.transaction import Transaction
+ from sqlalchemy import select
+
+ txns = [TransactionImport(
+ description="No Cat Transaction",
+ amount=Decimal("50.00"),
+ date=date(2026, 1, 15),
+ type="debit",
+ )]
+
+ imported, _, _ = await import_transactions(
+ session, test_user.id, test_account.id, txns, "import",
+ )
+
+ assert imported == 1
+
+ tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "No Cat Transaction")
+ )).scalar_one()
+ assert tx.category_id is None
+
+ @pytest.mark.asyncio
+ @patch("app.services.fx_rate_service._provider")
+ async def test_multiple_categories_resolved_correctly(
+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,
+ ):
+ """Multiple transactions with different categories should each resolve correctly."""
+ from app.models.category import Category
+ from app.models.transaction import Transaction
+ from app.schemas.transaction import TransactionImport
+ from sqlalchemy import select
+
+ salary_cat = Category(
+ id=uuid.uuid4(), user_id=test_user.id,
+ name="Salário & Renda", icon="banknote", color="#16A34A",
+ )
+ housing_cat = Category(
+ id=uuid.uuid4(), user_id=test_user.id,
+ name="Moradia", icon="house", color="#8B5CF6",
+ )
+ session.add(salary_cat)
+ session.add(housing_cat)
+ await session.commit()
+
+ txns = [
+ TransactionImport(
+ description="Salario",
+ amount=Decimal("13311.00"),
+ date=date(2026, 1, 5),
+ type="credit",
+ category_name="Salário & Renda",
+ ),
+ TransactionImport(
+ description="Financiamento",
+ amount=Decimal("577.00"),
+ date=date(2026, 1, 1),
+ type="debit",
+ category_name="Moradia",
+ ),
+ TransactionImport(
+ description="Unknown",
+ amount=Decimal("100.00"),
+ date=date(2026, 1, 2),
+ type="debit",
+ category_name="Categoria Inexistente",
+ ),
+ ]
+
+ imported, skipped, _ = await import_transactions(
+ session, test_user.id, test_account.id, txns, "import",
+ )
+
+ assert imported == 3
+ assert skipped == 0
+
+ salary_tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "Salario")
+ )).scalar_one()
+ housing_tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "Financiamento")
+ )).scalar_one()
+ unknown_tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "Unknown")
+ )).scalar_one()
+
+ assert salary_tx.category_id == salary_cat.id
+ assert housing_tx.category_id == housing_cat.id
+ assert unknown_tx.category_id is None
+
+ @pytest.mark.asyncio
+ @patch("app.services.fx_rate_service._provider")
+ async def test_end_to_end_parse_and_import_with_type_and_category(
+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,
+ ):
+ """Full flow: parse_csv reads type+category columns, import_transactions resolves them."""
+ from app.models.category import Category
+ from app.models.transaction import Transaction
+ from sqlalchemy import select
+
+ salary_cat = Category(
+ id=uuid.uuid4(), user_id=test_user.id,
+ name="Salário & Renda", icon="banknote", color="#16A34A",
+ )
+ housing_cat = Category(
+ id=uuid.uuid4(), user_id=test_user.id,
+ name="Moradia", icon="house", color="#8B5CF6",
+ )
+ session.add(salary_cat)
+ session.add(housing_cat)
+ await session.commit()
+
+ csv_content = (
+ "date,description,amount,type,currency,category\n"
+ "2026-01-05,Salario Dia 5,13311.00,credit,BRL,Salário & Renda\n"
+ "2026-01-01,Financiamento Casa,577.00,debit,BRL,Moradia\n"
+ )
+ transactions = parse_csv(csv_content.encode("utf-8"))
+
+ assert transactions[0].type == "credit"
+ assert transactions[1].type == "debit"
+ assert transactions[0].category_name == "Salário & Renda"
+ assert transactions[1].category_name == "Moradia"
+
+ imported, skipped, _ = await import_transactions(
+ session, test_user.id, test_account.id, transactions, "import",
+ )
+
+ assert imported == 2
+ assert skipped == 0
+
+ salary_tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "Salario Dia 5")
+ )).scalar_one()
+ housing_tx = (await session.execute(
+ select(Transaction).where(Transaction.description == "Financiamento Casa")
+ )).scalar_one()
+
+ assert salary_tx.type == "credit"
+ assert salary_tx.category_id == salary_cat.id
+ assert housing_tx.type == "debit"
+ assert housing_tx.category_id == housing_cat.id
+
+
class TestOfxInstallmentDedup:
"""Brazilian credit-card installments share one FITID across all monthly
statements (issue #98). Deduplication must consider the date so that