Open-source personal finance manager. Self-hosted, privacy-first.
Fix/csv import improvements (#576)
jorishaenseler15f2689817921d
diff --git a/backend/app/api/import_transactions.py b/backend/app/api/import_transactions.pyindex c575a56c..1ab8e9a1 100644--- a/backend/app/api/import_transactions.py+++ b/backend/app/api/import_transactions.py@@ -63,6 +63,7 @@ async def preview_import()parse_error: Optional[str] = None+ failed_rows = []try:if filename.lower().endswith('.ofx') or filename.lower().endswith('.qfx'):transactions = import_service.parse_ofx(content)@@ -76,7 +77,7 @@ async def preview_import(elif filename.lower().endswith('.csv'):detected_format = "csv"try:- transactions = import_service.parse_csv(+ transactions, failed_rows = import_service.parse_csv(content,date_format=date_format,flip_amount=flip_amount,@@ -106,7 +107,7 @@ async def preview_import(transactions = import_service.parse_camt(content)detected_format = "camt"except Exception:- transactions = import_service.parse_csv(content)+ transactions, failed_rows = import_service.parse_csv(content)detected_format = "csv"except Exception as e:logger.error(@@ -143,6 +144,7 @@ async def preview_import(detected_format=detected_format,csv_columns=csv_columns,parse_error=parse_error,+ failed_rows=failed_rows,)diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex 21645e84..7b93b731 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -284,6 +284,13 @@ class TransactionImport(TransactionBase):notes: Optional[str] = None+class FailedRow(BaseModel):+ line_number: int+ description: str+ raw_value: str+ error_reason: str++class TransactionImportPreview(BaseModel):transactions: list[TransactionImport]detected_format: str@@ -293,6 +300,7 @@ class TransactionImportPreview(BaseModel):# Set when a CSV's columns could not be auto-detected. The preview still# succeeds (with no transactions) so the UI can show the mapping dropdowns.parse_error: Optional[str] = None+ failed_rows: list[FailedRow] = []class TransactionImportRequest(BaseModel):diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.pyindex e155bf6b..a9f84b85 100644--- a/backend/app/services/import_service.py+++ b/backend/app/services/import_service.py@@ -16,7 +16,7 @@ from app.models.account import Accountfrom app.models.category import Categoryfrom app.models.rule import Rulefrom app.models.transaction import Transaction-from app.schemas.transaction import TransactionImport+from app.schemas.transaction import TransactionImport, FailedRowfrom app.services import recurring_match_servicefrom app.services.credit_card_service import apply_effective_datefrom app.services.category_service import get_hidden_category_ids@@ -412,7 +412,7 @@ def parse_csv(inflow_column: str | None = None,outflow_column: str | None = None,column_mapping: dict[str, str] | None = None,-) -> list[TransactionImport]:+ ) -> tuple[list[TransactionImport], list[FailedRow]]:"""Parse CSV file content and return transactions.Attempts to detect common column formats:@@ -516,9 +516,18 @@ def parse_csv(date_formats = ['%Y-%m-%d', '%d/%m/%Y', '%d-%m-%Y', '%m/%d/%Y', '%d.%m.%Y']transactions = []+ failed_rows = []for row in reader:- # Normalize row keys- row = {k.lower().strip() if k is not None else "": v for k, v in row.items()}+ # Normalize row keys, and missing cells along with them. A row with+ # fewer cells than the header leaves the rest as None, which every+ # .strip() below raises on and which FailedRow.raw_value rejects. That+ # turned a single short row into a 400 for the whole file, which is+ # exactly the case this parser is meant to report row by row. An+ # absent cell reads as an empty one.+ row = {+ k.lower().strip() if k is not None else "": ("" if v is None else v)+ for k, v in row.items()+ }# Parse datedate_str = row[date_col].strip()@@ -531,6 +540,7 @@ def parse_csv(continueif not txn_date:+ failed_rows.append(FailedRow(line_number=reader.line_num, description=row.get(desc_col, "").strip(), raw_value=date_str, error_reason="invalid_date"))continue # Skip invalid dates# Parse amount@@ -554,6 +564,8 @@ def parse_csv(amount = outflowtxn_type = "debit"else:+ raw_val = f"inflow: {row.get(inflow_col, '')}, outflow: {row.get(outflow_col, '')}"+ failed_rows.append(FailedRow(line_number=reader.line_num, description=row.get(desc_col, "").strip(), raw_value=raw_val, error_reason="no_amount"))continue # Skip rows with no amountelse:amount_str = normalize_amount(row[amount_col])@@ -561,6 +573,7 @@ def parse_csv(try:amount = Decimal(amount_str)except Exception:+ failed_rows.append(FailedRow(line_number=reader.line_num, description=row.get(desc_col, "").strip(), raw_value=row[amount_col], error_reason="invalid_amount"))continue # Skip invalid amountsif flip_amount:@@ -603,7 +616,7 @@ def parse_csv(notes=txn_notes,))- return transactions+ return transactions, failed_rowsasync def enrich_with_category_suggestions(@@ -621,10 +634,16 @@ async def enrich_with_category_suggestions(category_result = await session.execute(select(Category).where(Category.workspace_id == workspace_id))- category_name_map = {str(c.id): c.name for c in category_result.scalars()}+ categories = category_result.scalars().all()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+ if c.id not in hidden_categories+ }- if not rules:+ if not rules and not category_name_to_id:return transactionsfor txn in transactions:@@ -639,6 +658,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 []@@ -649,6 +669,13 @@ 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())+ if csv_cat_id:+ proxy.category_id = csv_cat_id+ category_set = Trueif proxy.category_id:txn.suggested_category_id = proxy.category_idtxn.suggested_category_name = category_name_map.get(str(proxy.category_id))@@ -702,11 +729,20 @@ 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 scoped to the workspace.+ # Build category name → id map scoped to the workspace, on the same terms+ # the preview used: hidden categories excluded, names matched+ # case-insensitively. Diverging here meant a CSV category the preview+ # deliberately withheld was still persisted on the imported row, and that+ # "Food" matched in the preview but not on import.category_result = await session.execute(select(Category).where(Category.workspace_id == workspace_id))- category_map = {c.name: c.id for c in category_result.scalars()}+ hidden_categories = await get_hidden_category_ids(session, workspace_id)+ category_map = {+ c.name.strip().lower(): c.id+ for c in category_result.scalars()+ if c.id not in hidden_categories+ }imported = 0skipped = 0@@ -762,7 +798,7 @@ async def import_transactions(user_category_id = txn_data.category_idsuggested_cat_id = txn_data.suggested_category_idcsv_category_id = (- category_map.get(txn_data.category_name)+ category_map.get(txn_data.category_name.strip().lower())if txn_data.category_nameelse None)@@ -886,7 +922,8 @@ def normalize_amount(amount_str: str | None) -> str:if not amount_str:return ""- amount_str = str(amount_str).replace('R$', '').strip()+ # Strip currency prefix and Swiss thousands separators (single quote)+ amount_str = str(amount_str).replace('R$', '').replace("'", "").strip()if ',' in amount_str and '.' in amount_str:if amount_str.rfind(',') > amount_str.rfind('.'):diff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.pyindex 8d7525a0..c5349b1d 100644--- a/backend/tests/test_import_service.py+++ b/backend/tests/test_import_service.py@@ -31,7 +31,7 @@ class TestParseCsv:"12/02/2026,IFOOD RESTAURANTE,-45.00\n""05/02/2026,SALARIO FEV,8000.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 3@@ -60,7 +60,7 @@ class TestParseCsv:"2026-02-10,GROCERY STORE,-120.50\n""2026-02-15,SALARY PAYMENT,5000.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2@@ -97,7 +97,7 @@ class TestParseCsv:'10/02/2026,MERCADO LIVRE,"R$ -150,99"\n''11/02/2026,PIX RECEBIDO,"R$ 200,00"\n')- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2@@ -115,7 +115,7 @@ class TestParseCsv:"""CSV encoded with UTF-8 BOM should be parsed correctly."""# Encode with utf-8-sig which prepends BOM bytes; parse_csv decodes with utf-8-sigcsv_content = "date,description,amount\n2026-01-15,TEST TRANSACTION,-50.00\n"- transactions = parse_csv(csv_content.encode("utf-8-sig"))+ transactions, _ = parse_csv(csv_content.encode("utf-8-sig"))assert len(transactions) == 1assert transactions[0].description == "TEST TRANSACTION"@@ -128,7 +128,7 @@ class TestParseCsv:"not-a-date,BAD ROW,-10.00\n""2026-02-20,GOOD ROW,-30.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 1assert transactions[0].description == "GOOD ROW"@@ -140,7 +140,7 @@ class TestParseCsv:"2026-02-20,BAD AMOUNT,abc\n""2026-02-21,GOOD AMOUNT,-75.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 1assert transactions[0].description == "GOOD AMOUNT"@@ -148,7 +148,7 @@ class TestParseCsv:def test_parse_csv_dd_mm_yyyy_format(self):"""DD/MM/YYYY date format should be correctly parsed."""csv_content = "data,descricao,valor\n25/12/2025,NATAL,-500.00\n"- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 1assert transactions[0].date == date(2025, 12, 25)@@ -160,7 +160,7 @@ class TestParseCsv:"15/01/2026;Grocery Store;-120.50\n""20/01/2026;Salary Payment;5000.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2assert transactions[0].description == "Grocery Store"@@ -177,7 +177,7 @@ class TestParseCsv:"2026-01-15\tGrocery Store\t-120.50\n""2026-01-20\tSalary Payment\t5000.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2assert transactions[0].description == "Grocery Store"@@ -190,7 +190,7 @@ class TestParseCsv:def test_parse_csv_empty_file(self):"""A CSV with only headers and no data rows should return empty list."""csv_content = "date,description,amount\n"- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 0def test_parse_csv_explicit_date_format(self):@@ -200,12 +200,12 @@ class TestParseCsv:"03/04/2026,PAYMENT,-100.00\n")# With MM/DD/YYYY format, 03/04 = March 4- transactions = parse_csv(csv_content.encode("utf-8"), date_format="MM/DD/YYYY")+ transactions, _ = parse_csv(csv_content.encode("utf-8"), date_format="MM/DD/YYYY")assert len(transactions) == 1assert transactions[0].date == date(2026, 3, 4)# With DD/MM/YYYY format, 03/04 = April 3- transactions = parse_csv(csv_content.encode("utf-8"), date_format="DD/MM/YYYY")+ transactions, _ = parse_csv(csv_content.encode("utf-8"), date_format="DD/MM/YYYY")assert len(transactions) == 1assert transactions[0].date == date(2026, 4, 3)@@ -216,7 +216,7 @@ class TestParseCsv:"2026-01-10,EXPENSE,100.00\n""2026-01-11,INCOME,-500.00\n")- transactions = parse_csv(csv_content.encode("utf-8"), flip_amount=True)+ transactions, _ = parse_csv(csv_content.encode("utf-8"), flip_amount=True)assert len(transactions) == 2# 100.00 flipped to -100.00 => debitassert transactions[0].type == "debit"@@ -232,7 +232,7 @@ class TestParseCsv:"2026-01-10,SALARY,5000.00,\n""2026-01-11,RENT,,1200.00\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),inflow_column="inflow",outflow_column="outflow",@@ -251,7 +251,7 @@ class TestParseCsv:"2026-01-11,RENT,1200.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2assert transactions[0].amount == Decimal("5000.00")assert transactions[1].amount == Decimal("1200.00")@@ -262,7 +262,7 @@ class TestParseCsv:"date,description,amount,merchant,transaction_id,notes\n""2026-05-01,AMAZON,-25.00,Amazon.com,txn_123,Gift for John\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 1assert transactions[0].payee_raw == "Amazon.com"assert transactions[0].external_id is None@@ -278,7 +278,7 @@ class TestParseCsvColumnMapping:"2026-01-10,COFFEE SHOP,-12.50\n""2026-01-11,PAYCHECK,3000.00\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "Posted On",@@ -306,7 +306,7 @@ class TestParseCsvColumnMapping:"date,description,details,amount\n""2026-01-10,WRONG,RIGHT,-10.00\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"description": "details"},)@@ -319,7 +319,7 @@ class TestParseCsvColumnMapping:"txn_date,description,amount\n""2026-01-10,GROCERIES,-55.00\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "txn_date"},)@@ -340,7 +340,7 @@ class TestParseCsvColumnMapping:def test_column_mapping_case_insensitive(self):"""Mapping values are matched case-insensitively against CSV headers."""csv_content = "Date,Description,Amount\n2026-01-10,X,-1.00\n"- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "DATE", "description": "Description", "amount": "amount"},)@@ -354,7 +354,7 @@ class TestParseCsvColumnMapping:"2026-01-10,SALARY,5000.00,\n""2026-01-11,RENT,,1200.00\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "Posted On",@@ -375,7 +375,7 @@ class TestParseCsvColumnMapping:"date,description,amount,ccy,exch\n""2026-01-10,HOTEL,-100.00,EUR,1.08\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"currency": "ccy", "fx_rate": "exch"},)@@ -386,7 +386,7 @@ class TestParseCsvColumnMapping:def test_column_mapping_ignores_empty_values(self):"""Empty mapping values are ignored and fall back to auto-detection."""csv_content = "date,description,amount\n2026-01-10,X,-1.00\n"- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "", "description": " "},)@@ -401,7 +401,7 @@ class TestParseCsvColumnMapping:"2026-04-01,Whole Foods,55.00,debit\n""2026-04-02,Employer Inc,4200.00,credit\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "Booking Date",@@ -422,7 +422,7 @@ class TestParseCsvColumnMapping:"Posting Date,Details,Amount\n""22/03/2026,Gym Membership,-60.00\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),date_format="DD/MM/YYYY",column_mapping={@@ -442,7 +442,7 @@ class TestParseCsvColumnMapping:"2026-07-02;Nomina;3.500,00\n""2026-07-03;Hotel;-200,00\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "Fecha",@@ -462,7 +462,7 @@ class TestParseCsvColumnMapping:"Txn Date,Memo,Value,Counterparty,ExtRef,Comment\n""2026-08-01,Purchase,-15.00,Target,ref999,Groceries\n")- transactions = parse_csv(+ transactions, _ = parse_csv(csv_content.encode("utf-8"),column_mapping={"date": "Txn Date",@@ -1158,7 +1158,7 @@ class TestCsvCurrencyParsing:"2026-01-11,Local Store,-45.00,BRL\n""2026-01-12,Euro Payment,-80.00,EUR\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 3assert transactions[0].currency == "USD"@@ -1172,7 +1172,7 @@ class TestCsvCurrencyParsing:"10/01/2026,AMAZON,-120.50,USD\n""11/01/2026,PIX RECEBIDO,500.00,BRL\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2assert transactions[0].currency == "USD"@@ -1185,7 +1185,7 @@ class TestCsvCurrencyParsing:"2026-01-10,Amazon Purchase,-120.50,USD,5.25\n""2026-01-11,Local Store,-45.00,BRL,\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2assert transactions[0].currency == "USD"@@ -1199,7 +1199,7 @@ class TestCsvCurrencyParsing:"data,descricao,valor,moeda,taxa_cambio\n"'10/01/2026,COMPRA EXTERIOR,-200.00,USD,"5,30"\n')- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 1assert transactions[0].fx_rate == Decimal("5.30")@@ -1210,7 +1210,7 @@ class TestCsvCurrencyParsing:"date,description,amount\n""2026-01-10,GROCERY,-50.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 1assert transactions[0].currency is None@@ -1577,7 +1577,7 @@ class TestParseCsvTypeColumn:"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"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2assert transactions[0].type == "credit"@@ -1592,7 +1592,7 @@ class TestParseCsvTypeColumn:"2026-01-01,Rent,1200.00,debit\n""2026-01-02,Internet,119.00,debit\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert all(t.type == "debit" for t in transactions)@@ -1603,7 +1603,7 @@ class TestParseCsvTypeColumn:"2026-01-01,Expense,-100.00\n""2026-01-02,Income,500.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert transactions[0].type == "debit"assert transactions[1].type == "credit"@@ -1615,7 +1615,7 @@ class TestParseCsvTypeColumn:"2026-01-01,Expense,-100.00,unknown\n""2026-01-02,Income,500.00,invalid\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert transactions[0].type == "debit"assert transactions[1].type == "credit"@@ -1640,7 +1640,7 @@ class TestParseCsvCategoryColumn:"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"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 2assert transactions[0].category_name == "Salário & Renda"@@ -1652,7 +1652,7 @@ class TestParseCsvCategoryColumn:"date,description,amount\n""2026-01-01,Grocery Store,-50.00\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert transactions[0].category_name is None@@ -1662,7 +1662,7 @@ class TestParseCsvCategoryColumn:"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"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert transactions[0].category_name is None@@ -1672,7 +1672,7 @@ class TestParseCsvCategoryColumn:"data,descricao,valor,categoria\n""01/01/2026,Supermercado,-150.00,Alimentação\n")- transactions = parse_csv(csv_content.encode("utf-8"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert len(transactions) == 1assert transactions[0].category_name == "Alimentação"@@ -1753,6 +1753,84 @@ class TestImportTransactionsWithCategory:)).scalar_one()assert tx.category_id is None+ @pytest.mark.asyncio+ @patch("app.services.fx_rate_service._provider")+ async def test_hidden_category_name_leaves_uncategorized(+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,+ ):+ """A hidden category is withheld on import, as it is in the preview.++ The preview filters hidden categories out of its suggestion map. The+ final import used to build its own unfiltered map, so a CSV naming a+ hidden category still got it persisted, and the imported row disagreed+ with what the preview showed.+ """+ from app.models.category import Category+ from app.models.transaction import Transaction+ from app.schemas.transaction import TransactionImport+ from sqlalchemy import select++ hidden = Category(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Categoria Oculta", icon="eye-off", color="#64748B", is_hidden=True,+ )+ session.add(hidden)+ await session.commit()++ txns = [TransactionImport(+ description="Hidden Cat Transaction",+ amount=Decimal("42.00"),+ date=date(2026, 1, 11),+ type="debit",+ category_name="Categoria Oculta",+ )]++ imported, _, _, _ = await import_transactions(+ session, test_workspace.id, test_user.id, test_account.id, txns, "import",+ )++ assert imported == 1+ tx = (await session.execute(+ select(Transaction).where(Transaction.description == "Hidden Cat Transaction")+ )).scalar_one()+ assert tx.category_id is None++ @pytest.mark.asyncio+ @patch("app.services.fx_rate_service._provider")+ async def test_category_name_matches_case_insensitively(+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,+ ):+ """Import matches category names the way the preview does."""+ from app.models.category import Category+ from app.models.transaction import Transaction+ from app.schemas.transaction import TransactionImport+ from sqlalchemy import select++ category = Category(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Alimentação", icon="utensils", color="#F97316",+ )+ session.add(category)+ await session.commit()++ txns = [TransactionImport(+ description="Case Insensitive Cat",+ amount=Decimal("18.00"),+ date=date(2026, 1, 12),+ type="debit",+ category_name=" alimentação ",+ )]++ imported, _, _, _ = await import_transactions(+ session, test_workspace.id, test_user.id, test_account.id, txns, "import",+ )++ assert imported == 1+ tx = (await session.execute(+ select(Transaction).where(Transaction.description == "Case Insensitive Cat")+ )).scalar_one()+ assert tx.category_id == category.id+@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_no_category_name_leaves_uncategorized(@@ -1876,7 +1954,7 @@ class TestImportTransactionsWithCategory:"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"))+ transactions, _ = parse_csv(csv_content.encode("utf-8"))assert transactions[0].type == "credit"assert transactions[1].type == "debit"@@ -2433,3 +2511,61 @@ async def test_import_tolerates_duplicate_external_id_rows())).scalars().all()assert len(remaining) == 2+++def test_normalize_amount_swiss_single_quotes():+ from app.services.import_service import normalize_amount+ assert normalize_amount("1'050.45") == "1050.45"+ assert normalize_amount("-2'416.70") == "-2416.70"+ assert normalize_amount("5'400") == "5400"+++def test_parse_csv_returns_failed_rows():+ from app.services.import_service import parse_csv+ csv_content = (+ "date,description,amount,currency\n"+ "2026-08-01,Valid,-10.00,CHF\n"+ "invalid_date,Invalid Date,-10.00,CHF\n"+ "2026-08-03,Invalid Amount,invalid_val,CHF\n"+ )+ transactions, failed_rows = parse_csv(csv_content.encode("utf-8"))+ assert len(transactions) == 1+ assert len(failed_rows) == 2+ assert failed_rows[0].line_number == 3+ assert failed_rows[0].error_reason == "invalid_date"+ assert failed_rows[0].raw_value == "invalid_date"+ assert failed_rows[0].description == "Invalid Date"+ assert failed_rows[1].line_number == 4+ assert failed_rows[1].error_reason == "invalid_amount"+ assert failed_rows[1].raw_value == "invalid_val"+ assert failed_rows[1].description == "Invalid Amount"+++def test_parse_csv_reports_short_rows_instead_of_raising():+ """A row with fewer cells than the header is reported, not fatal.++ csv.DictReader leaves the missing cells as None, so every .strip() on them+ used to raise and the API turned that into a 400 for the whole file. One+ malformed row is exactly what failed_rows exists to describe.+ """+ from app.services.import_service import parse_csv+ csv_content = (+ "date,description,amount\n"+ "2026-08-01,Valid,-10.00\n"+ "2026-08-02,Missing amount\n"+ "2026-08-03\n"+ "invalid_date\n"+ )+ transactions, failed_rows = parse_csv(csv_content.encode("utf-8"))++ assert len(transactions) == 1+ assert len(failed_rows) == 3+ assert failed_rows[0].line_number == 3+ assert failed_rows[0].description == "Missing amount"+ assert failed_rows[0].error_reason == "invalid_amount"+ # A cell the row never had reads as empty, never as None.+ assert failed_rows[1].line_number == 4+ assert failed_rows[1].description == ""+ assert failed_rows[2].line_number == 5+ assert failed_rows[2].error_reason == "invalid_date"+ assert failed_rows[2].raw_value == "invalid_date"diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 51c3c141..7e4cc673 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -42,6 +42,7 @@ import type {RulePreviewResponse,ImportLog,ImportPreviewTransaction,+ FailedRow,PayeeTaxId,TaxIdKindOption,Workspace,@@ -638,7 +639,7 @@ export const transactions = {inflow_column?: stringoutflow_column?: stringcolumn_mapping?: Record<string, string>- }): Promise<{ transactions: ImportPreviewTransaction[]; detected_format: string; csv_columns?: string[]; parse_error?: string | null }> => {+ }): Promise<{ transactions: ImportPreviewTransaction[]; detected_format: string; csv_columns?: string[]; parse_error?: string | null; failed_rows?: FailedRow[] }> => {const formData = new FormData()formData.append('file', file)if (options?.date_format) formData.append('date_format', options.date_format)diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 75c421fa..fd2bf087 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -1277,6 +1277,13 @@"columnMappingHint": "Ordne deine CSV-Spalten den Securo-Feldern zu. Belasse die Einstellung auf automatischer Erkennung, um die erkannte Spalte zu behalten.","columnAutoDetect": "Automatische Erkennung","mappingNeeded": "Wir konnten deine CSV-Spalten nicht automatisch erkennen. Ordne sie unten den Securo-Feldern zu, um fortzufahren.",+ "failedRowsWarning": "{{count}} Zeile(n) in dieser Datei konnten nicht analysiert werden und wurden übersprungen.",+ "viewDetails": "Details anzeigen",+ "failedRowsTitle": "Nicht analysierte CSV-Zeilen",+ "failedRowsDesc": "Die folgenden Zeilen in der CSV-Datei wurden übersprungen, da ihr Datums- oder Betragsformat nicht erkannt werden konnte.",+ "lineNumber": "Zeile",+ "rawValue": "Wert",+ "errorReason": "Grund","mapDate": "Spalte für Datum","mapDescription": "Spalte für Beschreibung","mapAmount": "Spalte für Betrag",@@ -1334,7 +1341,13 @@"page": "Seite {{current}} von {{total}}","mapPayee": "Spalte Zahlungsempfänger","mapExternalId": "Spalte Transaktions-ID",- "mapNotes": "Spalte Notizen"+ "mapNotes": "Spalte Notizen",+ "description": "Beschreibung",+ "errors": {+ "invalid_date": "Ungültiges Datumsformat",+ "no_amount": "Kein Zu- oder Abflussbetrag",+ "invalid_amount": "Ungültiges Betragsformat"+ }},"assetImport": {"title": "Wertpapierorders importieren",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex f51835d1..a773a1b6 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -1276,6 +1276,13 @@"columnMappingHint": "Αντιστοιχίστε τις στήλες του CSV στα πεδία του Securo. Αφήστε τον αυτόματο εντοπισμό για διατήρηση της αναγνωρισμένης στήλης.","columnAutoDetect": "Αυτόματος εντοπισμός","mappingNeeded": "Δεν μπορέσαμε να αναγνωρίσουμε αυτόματα τις στήλες του CSV. Αντιστοιχίστε τες στα πεδία του Securo παρακάτω για να συνεχίσετε.",+ "failedRowsWarning": "{{count}} γραμμή(ές) σε αυτό το αρχείο δεν ήταν δυνατό να αναλυθούν και παραλείφθηκαν.",+ "viewDetails": "Προβολή λεπτομερειών",+ "failedRowsTitle": "Μη αναγνωρισμένες γραμμές CSV",+ "failedRowsDesc": "Οι παρακάτω γραμμές του αρχείου CSV παραλείφθηκαν επειδή δεν ήταν δυνατή η αναγνώριση της μορφής ημερομηνίας ή ποσού.",+ "lineNumber": "Γραμμή",+ "rawValue": "Τιμή",+ "errorReason": "Αιτία","mapDate": "Στήλη ημερομηνίας","mapDescription": "Στήλη περιγραφής","mapAmount": "Στήλη ποσού",@@ -1333,7 +1340,13 @@"page": "Σελίδα {{current}} από {{total}}","mapPayee": "Στήλη δικαιούχου","mapExternalId": "Στήλη αναγνωριστικού συναλλαγής",- "mapNotes": "Στήλη σημειώσεων"+ "mapNotes": "Στήλη σημειώσεων",+ "description": "Περιγραφή",+ "errors": {+ "invalid_date": "Μη έγκυρη μορφή ημερομηνίας",+ "no_amount": "Χωρίς ποσό εισροής ή εκροής",+ "invalid_amount": "Μη έγκυρη μορφή ποσού"+ }},"assetImport": {"title": "Εισαγωγή επενδυτικών εντολών",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 47a80cc8..e414800c 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1276,6 +1276,13 @@"columnMappingHint": "Map your CSV columns to Securo fields. Leave on auto-detect to keep the detected column.","columnAutoDetect": "Auto-detect","mappingNeeded": "We couldn't recognize your CSV columns automatically. Map them to Securo fields below to continue.",+ "failedRowsWarning": "{{count}} row(s) in this file could not be parsed and were skipped.",+ "viewDetails": "View details",+ "failedRowsTitle": "Unparsed CSV Rows",+ "failedRowsDesc": "The following rows in the CSV file were skipped because their date or amount format could not be recognized.",+ "lineNumber": "Line",+ "rawValue": "Value",+ "errorReason": "Reason","mapDate": "Date column","mapDescription": "Description column","mapAmount": "Amount column",@@ -1333,7 +1340,13 @@"page": "Page {{current}} of {{total}}","mapPayee": "Payee column","mapExternalId": "Transaction ID column",- "mapNotes": "Notes column"+ "mapNotes": "Notes column",+ "description": "Description",+ "errors": {+ "invalid_date": "Invalid Date Format",+ "no_amount": "No Inflow or Outflow Amount",+ "invalid_amount": "Invalid Amount Format"+ }},"assetImport": {"title": "Import investment orders",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 317cb49d..dcf76370 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1277,6 +1277,13 @@"columnMappingHint": "Asigna las columnas de tu CSV a los campos de Securo. Deja la detección automática para conservar la columna detectada.","columnAutoDetect": "Detección automática","mappingNeeded": "No pudimos reconocer automáticamente las columnas de tu CSV. Asigna las columnas a los campos de Securo abajo para continuar.",+ "failedRowsWarning": "{{count}} fila(s) en este archivo no se pudieron analizar y fueron omitidas.",+ "viewDetails": "Ver detalles",+ "failedRowsTitle": "Filas de CSV no analizadas",+ "failedRowsDesc": "Las siguientes filas en el archivo CSV se omitieron porque no se pudo reconocer su formato de fecha o monto.",+ "lineNumber": "Línea",+ "rawValue": "Valor",+ "errorReason": "Razón","mapDate": "Columna de fecha","mapDescription": "Columna de descripción","mapAmount": "Columna de importe",@@ -1334,7 +1341,13 @@"page": "Página {{current}} de {{total}}","mapPayee": "Columna de beneficiario","mapExternalId": "Columna de ID de transacción",- "mapNotes": "Columna de notas"+ "mapNotes": "Columna de notas",+ "description": "Descripción",+ "errors": {+ "invalid_date": "Formato de fecha no válido",+ "no_amount": "Sin importe de entrada o salida",+ "invalid_amount": "Formato de importe no válido"+ }},"assetImport": {"title": "Importar órdenes de inversión",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex d9097d95..5b4226d1 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -1277,6 +1277,13 @@"columnMappingHint": "Faites correspondre vos colonnes CSV aux champs de Securo. Laissez sur détection automatique pour conserver la colonne détectée.","columnAutoDetect": "Détection automatique","mappingNeeded": "Nous n'avons pas pu reconnaître automatiquement vos colonnes CSV. Faites-les correspondre aux champs de Securo ci-dessous pour continuer.",+ "failedRowsWarning": "{{count}} ligne(s) dans ce fichier n'ont pas pu être analysées et ont été ignorées.",+ "viewDetails": "Voir les détails",+ "failedRowsTitle": "Lignes CSV non analysées",+ "failedRowsDesc": "Les lignes suivantes du fichier CSV ont été ignorées car leur format de date ou de montant n'a pas pu être reconnu.",+ "lineNumber": "Ligne",+ "rawValue": "Valeur",+ "errorReason": "Raison","mapDate": "Colonne de date","mapDescription": "Colonne de description","mapAmount": "Colonne de montant",@@ -1334,7 +1341,13 @@"page": "Page {{current}} sur {{total}}","mapPayee": "Colonne du bénéficiaire","mapExternalId": "Colonne d'ID de transaction",- "mapNotes": "Colonne des notes"+ "mapNotes": "Colonne des notes",+ "description": "Description",+ "errors": {+ "invalid_date": "Format de date invalide",+ "no_amount": "Aucun montant d'entrée ou de sortie",+ "invalid_amount": "Format de montant invalide"+ }},"assetImport": {"title": "Importer des ordres d'investissement",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 2870aae4..298a0c93 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1277,6 +1277,13 @@"columnMappingHint": "Associa le colonne del tuo CSV ai campi di Securo. Lascia su rilevamento automatico per mantenere la colonna rilevata.","columnAutoDetect": "Rilevamento automatico","mappingNeeded": "Non siamo riusciti a riconoscere automaticamente le colonne del tuo CSV. Associale ai campi di Securo qui sotto per continuare.",+ "failedRowsWarning": "{{count}} riga/he in questo file non è stato possibile analizzare e sono state saltate.",+ "viewDetails": "Visualizza dettagli",+ "failedRowsTitle": "Righe CSV non analizzate",+ "failedRowsDesc": "Le seguenti righe nel file CSV sono state saltate perché non è stato possibile riconoscere il formato della data o dell'importo.",+ "lineNumber": "Riga",+ "rawValue": "Valore",+ "errorReason": "Motivo","mapDate": "Colonna data","mapDescription": "Colonna descrizione","mapAmount": "Colonna importo",@@ -1334,7 +1341,13 @@"page": "Pagina {{current}} di {{total}}","mapPayee": "Colonna del beneficiario","mapExternalId": "Colonna dell'ID transazione",- "mapNotes": "Colonna delle note"+ "mapNotes": "Colonna delle note",+ "description": "Descrizione",+ "errors": {+ "invalid_date": "Formato data non valido",+ "no_amount": "Nessun importo in entrata o in uscita",+ "invalid_amount": "Formato importo non valido"+ }},"assetImport": {"title": "Importa ordini di investimento",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex cba59901..22d05d29 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -951,7 +951,8 @@"description": "Amerikaanse en internationale banken via SimpleFIN Bridge"}},- "reconnected": "Bank heeft opnieuw verbinding gemaakt"+ "reconnected": "Bank heeft opnieuw verbinding gemaakt",+ "multiInstitutionLink": "{{provider}} · {{count}} institutions"},"connections": {"settings": "Verbindingsinstellingen",@@ -1334,7 +1335,20 @@"page": "Pagina {{current}} van {{total}}","mapPayee": "Kolom begunstigde","mapExternalId": "Kolom Transactie-ID",- "mapNotes": "Kolom Opmerkingen"+ "mapNotes": "Kolom Opmerkingen",+ "failedRowsWarning": "{{count}} row(s) in this file could not be parsed and were skipped.",+ "viewDetails": "View details",+ "failedRowsTitle": "Unparsed CSV Rows",+ "failedRowsDesc": "The following rows in the CSV file were skipped because their date or amount format could not be recognized.",+ "lineNumber": "Line",+ "rawValue": "Value",+ "errorReason": "Reason",+ "description": "Omschrijving",+ "errors": {+ "invalid_date": "Ongeldige datumformaat",+ "no_amount": "Geen in- of uitstroombedrag",+ "invalid_amount": "Ongeldig bedragformaat"+ }},"assetImport": {"title": "Investeringsorders importeren",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex a1fbbd6c..a157e7be 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1339,6 +1339,13 @@"columnMappingHint": "Przypisz kolumny CSV do pól Securo. Zostaw na automatycznym wykrywaniu, aby zachować wykrytą kolumnę.","columnAutoDetect": "Wykryj automatycznie","mappingNeeded": "Nie udało się automatycznie rozpoznać kolumn CSV. Przypisz je poniżej do pól Securo, aby kontynuować.",+ "failedRowsWarning": "Nie udało się przeanalizować {{count}} wierszy w tym pliku (zostały pominięte).",+ "viewDetails": "Pokaż szczegóły",+ "failedRowsTitle": "Nieprzeanalizowane wiersze CSV",+ "failedRowsDesc": "Następujące wiersze w pliku CSV zostały pominięte, ponieważ nie można było rozpoznać ich formatu daty lub kwoty.",+ "lineNumber": "Wiersz",+ "rawValue": "Wartość",+ "errorReason": "Powód","mapDate": "Kolumna daty","mapDescription": "Kolumna opisu","mapAmount": "Kolumna kwoty",@@ -1414,7 +1421,13 @@"page": "Strona {{current}} z {{total}}","mapPayee": "Kolumna odbiorcy","mapExternalId": "Kolumna ID transakcji",- "mapNotes": "Kolumna notatek"+ "mapNotes": "Kolumna notatek",+ "description": "Opis",+ "errors": {+ "invalid_date": "Nieprawidłowy format daty",+ "no_amount": "Brak kwoty wpływu lub wypływu",+ "invalid_amount": "Nieprawidłowy format kwoty"+ }},"assetImport": {"title": "Importuj zlecenia inwestycyjne",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 0456c450..53e5d88a 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1277,6 +1277,13 @@"columnMappingHint": "Associe as colunas do seu CSV aos campos do Securo. Deixe em automático para manter a coluna detectada.","columnAutoDetect": "Detectar automaticamente","mappingNeeded": "Não reconhecemos as colunas do seu CSV automaticamente. Associe-as aos campos do Securo abaixo para continuar.",+ "failedRowsWarning": "{{count}} linha(s) neste arquivo não puderam ser analisadas e foram ignoradas.",+ "viewDetails": "Ver detalhes",+ "failedRowsTitle": "Linhas CSV não analisadas",+ "failedRowsDesc": "As seguintes linhas no arquivo CSV foram ignoradas porque o formato de data ou valor não pôde ser reconhecido.",+ "lineNumber": "Linha",+ "rawValue": "Valor",+ "errorReason": "Motivo","mapDate": "Coluna de data","mapDescription": "Coluna de descrição","mapAmount": "Coluna de valor",@@ -1334,7 +1341,13 @@"page": "Página {{current}} de {{total}}","mapPayee": "Coluna da pessoa","mapExternalId": "Coluna de ID da transação",- "mapNotes": "Coluna de notas"+ "mapNotes": "Coluna de notas",+ "description": "Descrição",+ "errors": {+ "invalid_date": "Formato de data inválido",+ "no_amount": "Nenhum valor de entrada ou saída",+ "invalid_amount": "Formato de valor inválido"+ }},"assetImport": {"title": "Importar ordens de investimento",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex c6dc77fc..30a65718 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -1277,6 +1277,13 @@"columnMappingHint": "Associa as colunas do teu CSV aos campos do Securo. Deixa em automático para manter a coluna detectada.","columnAutoDetect": "Detectar automaticamente","mappingNeeded": "Não reconhecemos as colunas do teu CSV automaticamente. Associa-as aos campos do Securo abaixo para continuar.",+ "failedRowsWarning": "{{count}} linha(s) neste ficheiro não puderam ser analisadas e foram ignoradas.",+ "viewDetails": "Ver detalhes",+ "failedRowsTitle": "Linhas CSV não analisadas",+ "failedRowsDesc": "As seguintes linhas no ficheiro CSV foram ignoradas porque o formato de data ou valor não pôde ser reconhecido.",+ "lineNumber": "Linha",+ "rawValue": "Valor",+ "errorReason": "Motivo","mapDate": "Coluna de data","mapDescription": "Coluna de descrição","mapAmount": "Coluna de valor",@@ -1334,7 +1341,13 @@"balanceImpact": "Impacto no saldo","importedWithExcluded": "{{imported}} importadas, {{skipped}} ignoradas, {{excluded}} excluídas","suggested": "Sugerida",- "page": "Página {{current}} de {{total}}"+ "page": "Página {{current}} de {{total}}",+ "description": "Descrição",+ "errors": {+ "invalid_date": "Formato de data inválido",+ "no_amount": "Nenhum valor de entrada ou saída",+ "invalid_amount": "Formato de valor inválido"+ }},"assetImport": {"title": "Importar ordens de investimento",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex c8bb415d..d0fb6d36 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -1285,6 +1285,13 @@"columnMappingHint": "Сопоставьте колонки вашего CSV с полями Securo. Оставьте автоопределение, чтобы сохранить обнаруженную колонку.","columnAutoDetect": "Автоопределение","mappingNeeded": "Мы не смогли автоматически распознать колонки вашего CSV. Сопоставьте их с полями Securo ниже, чтобы продолжить.",+ "failedRowsWarning": "Не удалось распознать {{count}} строк(и) в этом файле (пропущены).",+ "viewDetails": "Показать детали",+ "failedRowsTitle": "Нераспознанные строки CSV",+ "failedRowsDesc": "Следующие строки в файле CSV были пропущены, так как не удалось распознать их формат даты или суммы.",+ "lineNumber": "Строка",+ "rawValue": "Значение",+ "errorReason": "Причина","mapDate": "Колонка даты","mapDescription": "Колонка описания","mapAmount": "Колонка суммы",@@ -1342,7 +1349,13 @@"page": "Страница {{current}} из {{total}}","mapPayee": "Колонка получателя","mapExternalId": "Колонка ID транзакции",- "mapNotes": "Колонка заметок"+ "mapNotes": "Колонка заметок",+ "description": "Описание",+ "errors": {+ "invalid_date": "Неверный формат даты",+ "no_amount": "Нет суммы прихода или расхода",+ "invalid_amount": "Неверный формат суммы"+ }},"assetImport": {"title": "Импорт инвестиционных заявок",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 9723673f..30269495 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -1360,6 +1360,13 @@"columnMappingHint": "Priraď stĺpce svojho CSV k poliam Securo. Nechaj automatické rozpoznanie, ak chceš zachovať rozpoznaný stĺpec.","columnAutoDetect": "Rozpoznať automaticky","mappingNeeded": "Stĺpce tvojho CSV sa nepodarilo rozpoznať automaticky. Pokračuj tak, že ich nižšie priradíš k poliam Securo.",+ "failedRowsWarning": "{{count}} riadok(ov) v tomto súbore sa nepodarilo spracovať a boli preskočené.",+ "viewDetails": "Zobraziť podrobnosti",+ "failedRowsTitle": "Nespracované riadky CSV",+ "failedRowsDesc": "Nasledujúce riadky v súbore CSV boli preskočené, pretože sa nepodarilo rozpoznať formát dátumu alebo sumy.",+ "lineNumber": "Riadok",+ "rawValue": "Hodnota",+ "errorReason": "Dôvod","mapDate": "Stĺpec dátumu","mapDescription": "Stĺpec popisu","mapAmount": "Stĺpec sumy",@@ -1441,7 +1448,13 @@"page": "Strana {{current}} z {{total}}","mapPayee": "Stĺpec príjemcu","mapExternalId": "Stĺpec ID transakcie",- "mapNotes": "Stĺpec poznámky"+ "mapNotes": "Stĺpec poznámky",+ "description": "Popis",+ "errors": {+ "invalid_date": "Neplatný formát dátumu",+ "no_amount": "Chýba suma príjmu alebo výdaja",+ "invalid_amount": "Neplatný formát sumy"+ }},"assetImport": {"title": "Import investičných pokynov",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex c3c7db27..ff9d1ed2 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -1285,6 +1285,13 @@"columnMappingHint": "Зіставте стовпці вашого CSV з полями Securo. Залиште автовизначення, щоб зберегти виявлений стовпець.","columnAutoDetect": "Автовизначення","mappingNeeded": "Ми не змогли автоматично розпізнати стовпці вашого CSV. Зіставте їх з полями Securo нижче, щоб продовжити.",+ "failedRowsWarning": "Не вдалося розпізнати {{count}} рядків у цьому файлі (пропущено).",+ "viewDetails": "Показати деталі",+ "failedRowsTitle": "Нерозпізнані рядки CSV",+ "failedRowsDesc": "Наступні рядки у файлі CSV було пропущено, оскільки не вдалося розпізнати їхній формат дати або суми.",+ "lineNumber": "Рядок",+ "rawValue": "Значення",+ "errorReason": "Причина","mapDate": "Стовпець дати","mapDescription": "Стовпець опису","mapAmount": "Стовпець суми",@@ -1342,7 +1349,13 @@"page": "Сторінка {{current}} із {{total}}","mapPayee": "Стовпець одержувача","mapExternalId": "Стовпець ID транзакції",- "mapNotes": "Стовпець приміток"+ "mapNotes": "Стовпець приміток",+ "description": "Опис",+ "errors": {+ "invalid_date": "Недійсний формат дати",+ "no_amount": "Немає суми надходження або витрати",+ "invalid_amount": "Недійсний формат суми"+ }},"assetImport": {"title": "Імпорт інвестиційних заявок",diff --git a/frontend/src/pages/import.tsx b/frontend/src/pages/import.tsxindex 18c10008..3cc9a1d9 100644--- a/frontend/src/pages/import.tsx+++ b/frontend/src/pages/import.tsx@@ -9,8 +9,9 @@ import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import { Label } from '@/components/ui/label'-import type { ImportPreviewTransaction, ImportReviewTransaction } from '@/types'+import type { ImportPreviewTransaction, ImportReviewTransaction, FailedRow } from '@/types'import { Upload, FileText, X, CheckCircle2, AlertCircle, Settings2, Download } from 'lucide-react'+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'import { PageHeader } from '@/components/page-header'import { AssetImportPanel } from '@/components/asset-import-panel'import { ImportSummaryBar } from '@/components/import-summary-bar'@@ -58,13 +59,14 @@ function TransactionImportPanel() {const dateLocale = useDateLocale()const queryClient = useQueryClient()const fileInputRef = useRef<HTMLInputElement>(null)- const [previewData, setPreviewData] = useState<{ transactions: ImportPreviewTransaction[]; detected_format: string; csv_columns?: string[]; parse_error?: string | null } | null>(null)+ const [previewData, setPreviewData] = useState<{ transactions: ImportPreviewTransaction[]; detected_format: string; csv_columns?: string[]; parse_error?: string | null; failed_rows?: FailedRow[] } | null>(null)const [reviewTransactions, setReviewTransactions] = useState<ImportReviewTransaction[]>([])const [selectedAccount, setSelectedAccount] = useState('')const [dragOver, setDragOver] = useState(false)const [fileName, setFileName] = useState<string | null>(null)const [currentFile, setCurrentFile] = useState<File | null>(null)const [csvHeaders, setCsvHeaders] = useState<string[]>([])+ const [isFailedRowsOpen, setIsFailedRowsOpen] = useState(false)const [searchQuery, setSearchQuery] = useState('')const [filterCategoryIds, setFilterCategoryIds] = useState<string[]>([])@@ -406,6 +408,24 @@ function TransactionImportPanel() {<span>{t('import.mappingNeeded')}</span></div>)}++ {previewData.failed_rows && previewData.failed_rows.length > 0 && (+ <div className="flex items-start gap-2 text-xs text-amber-700 bg-amber-50 border border-amber-200 px-3 py-2 rounded-lg mb-3">+ <AlertCircle size={14} className="shrink-0 mt-0.5" />+ <div className="flex-1">+ <span>+ {t('import.failedRowsWarning', { count: previewData.failed_rows.length })}+ </span>+ <button+ type="button"+ className="ml-2 font-semibold underline hover:text-amber-800 focus:outline-none"+ onClick={() => setIsFailedRowsOpen(true)}+ >+ {t('import.viewDetails')}+ </button>+ </div>+ </div>+ )}<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"><div><Label className="text-xs text-muted-foreground mb-1 block">{t('import.dateFormat')}</Label>@@ -565,6 +585,44 @@ function TransactionImportPanel() {<ImportHistory entity="transactions" />+ {/* Unparsed CSV rows dialog */}+ <Dialog open={isFailedRowsOpen} onOpenChange={setIsFailedRowsOpen}>+ <DialogContent className="max-w-2xl max-h-[85vh] flex flex-col p-6">+ <DialogHeader>+ <DialogTitle className="text-base font-semibold">{t('import.failedRowsTitle')}</DialogTitle>+ <DialogDescription className="text-xs text-muted-foreground mt-1">+ {t('import.failedRowsDesc')}+ </DialogDescription>+ </DialogHeader>+ <div className="flex-1 border border-border rounded-lg overflow-hidden bg-card text-foreground mt-4 max-h-[50vh] overflow-y-auto">+ <table className="w-full text-left text-xs border-collapse">+ <thead>+ <tr className="bg-muted text-muted-foreground border-b border-border sticky top-0">+ <th className="px-3 py-2 font-semibold w-16">{t('import.lineNumber')}</th>+ <th className="px-3 py-2 font-semibold">{t('import.description')}</th>+ <th className="px-3 py-2 font-semibold">{t('import.rawValue')}</th>+ <th className="px-3 py-2 font-semibold">{t('import.errorReason')}</th>+ </tr>+ </thead>+ <tbody>+ {previewData?.failed_rows?.map((row, idx) => (+ <tr key={idx} className="border-b border-border last:border-0 hover:bg-muted/50">+ <td className="px-3 py-2 text-muted-foreground">{row.line_number}</td>+ <td className="px-3 py-2 truncate max-w-[200px]" title={row.description}>{row.description || '-'}</td>+ <td className="px-3 py-2 font-mono break-all max-w-[150px]">{row.raw_value}</td>+ <td className="px-3 py-2 text-amber-600 font-medium">{t(`import.errors.${row.error_reason}`)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ <DialogFooter className="mt-4 pt-4 border-t border-border flex justify-end">+ <Button onClick={() => setIsFailedRowsOpen(false)} size="sm">+ {t('common.close')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></div>)}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex f9d87556..405443d2 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -581,6 +581,13 @@ export interface ImportReviewTransaction extends ImportPreviewTransaction {selected_category_id?: string | null}+export interface FailedRow {+ line_number: number+ description: string+ raw_value: string+ error_reason: string+}+export interface RecurringTransaction {id: stringuser_id: string