Skip to content

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

feat: improve csv import error and fields

Tássio Noronha5915fc7c7312
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index dca9bf67..6ebdfc04 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -222,7 +222,7 @@ def parse_csv(
if use_split:
if inflow_col not in fieldnames or outflow_col not in fieldnames:
- raise ValueError(f"Inflow/outflow columns not found in CSV. Available: {fieldnames}")
+ raise ValueError(f"Inflow/outflow columns not found in CSV. Available columns: {', '.join(fieldnames)}")
amount_col = None
else:
amount_col = find_col(amount_cols)
@@ -231,9 +231,15 @@ def parse_csv(
fx_rate_col = find_col(fx_rate_cols)
if not date_col or not desc_col:
- raise ValueError("Could not detect CSV columns. Expected: date, description, amount")
+ raise ValueError(
+ f"Could not detect CSV columns. Found: {', '.join(fieldnames)}. "
+ f"Expected columns like: date, description, amount (or Portuguese equivalents: data, descricao, valor)"
+ )
if not use_split and not amount_col:
- raise ValueError("Could not detect CSV columns. Expected: date, description, amount")
+ raise ValueError(
+ f"Could not detect amount column. Found: {', '.join(fieldnames)}. "
+ f"Expected a column named: {', '.join(amount_cols)}"
+ )
# Determine date formats to try
if date_format and date_format in DATE_FORMAT_MAP:
diff --git a/backend/tests/test_import_api.py b/backend/tests/test_import_api.py
index 8686bc0e..75fe4b59 100644
--- a/backend/tests/test_import_api.py
+++ b/backend/tests/test_import_api.py
@@ -29,6 +29,27 @@ async def test_preview_invalid_file(client: AsyncClient, auth_headers, test_acco
files={"file": ("bad.csv", b"col1,col2,col3\na,b,c\n", "text/csv")},
)
assert response.status_code == 400
+ data = response.json()
+ assert "detail" in data
+ assert data["detail"] # must not be empty
+
+
+async def test_preview_invalid_file_returns_specific_error(
+ client: AsyncClient, auth_headers, test_account
+):
+ """Error response should tell the user what columns were found and what is expected."""
+ response = await client.post(
+ "/api/transactions/import/preview",
+ headers=auth_headers,
+ files={"file": ("bad.csv", b"foo,bar,baz\n1,2,3\n", "text/csv")},
+ )
+ assert response.status_code == 400
+ detail = response.json()["detail"]
+ # Should mention what columns were found in the file
+ assert "foo" in detail
+ # Should mention what columns are expected
+ assert "date" in detail and "description" in detail and "amount" in detail
@pytest.mark.asyncio
diff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.py
index e63b3a11..56a70a1d 100644
--- a/backend/tests/test_import_service.py
+++ b/backend/tests/test_import_service.py
@@ -67,13 +67,16 @@ class TestParseCsv:
assert transactions[1].type == "credit"
def test_parse_csv_invalid_columns(self):
- """CSV with unrecognized column names should raise ValueError."""
+ """CSV with unrecognized column names should raise ValueError with found and expected columns."""
csv_content = (
"col_a,col_b,col_c\n"
"foo,bar,baz\n"
)
- with pytest.raises(ValueError, match="Could not detect CSV columns"):
+ with pytest.raises(ValueError, match="Found: col_a, col_b, col_c") as exc_info:
parse_csv(csv_content.encode("utf-8"))
+ # Should also tell the user what columns are expected
+ assert "date" in str(exc_info.value)
+ assert "description" in str(exc_info.value)
def test_parse_csv_brl_amounts(self):
"""CSV with R$ prefix and comma-as-decimal amounts should be parsed correctly.
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 71193b14..906339c6 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -367,6 +367,7 @@
},
"import": {
"acceptedFormats": "Accepted formats: OFX, CSV, QIF, CAMT",
+ "downloadTemplate": "Download CSV template",
"transactionsImported": "transactions imported",
"importedWithSkipped": "{{imported}} imported, {{skipped}} duplicates skipped",
"csvOptions": "CSV Options",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index af189913..4dca50ee 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -367,6 +367,7 @@
},
"import": {
"acceptedFormats": "Formatos aceitos: OFX, CSV, QIF, CAMT",
+ "downloadTemplate": "Baixar modelo CSV",
"transactionsImported": "transações importadas",
"importedWithSkipped": "{{imported}} importadas, {{skipped}} duplicatas ignoradas",
"csvOptions": "Opções do CSV",
diff --git a/frontend/src/pages/import.tsx b/frontend/src/pages/import.tsx
index 9fcf265e..14d8f900 100644
--- a/frontend/src/pages/import.tsx
+++ b/frontend/src/pages/import.tsx
@@ -14,7 +14,7 @@ import {
TableRow,
} from '@/components/ui/table'
import type { Transaction, ImportLog } from '@/types'
-import { Upload, FileText, X, CheckCircle2, AlertCircle, History, Trash2, Settings2 } from 'lucide-react'
+import { Upload, FileText, X, CheckCircle2, AlertCircle, History, Trash2, Settings2, Download } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
import { PageHeader } from '@/components/page-header'
import { useAuth } from '@/contexts/auth-context'
@@ -66,7 +66,10 @@ export default function ImportPage() {
mutationFn: ({ file, options }: { file: File; options?: { date_format?: string; flip_amount?: boolean; inflow_column?: string; outflow_column?: string } }) =>
transactionsApi.previewImport(file, options),
onSuccess: (data) => setPreviewData(data),
- onError: () => toast.error(t('import.processError')),
+ onError: (error: unknown) => {
+ const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
+ toast.error(detail || t('import.processError'))
+ },
})
const importMutation = useMutation({
@@ -86,7 +89,10 @@ export default function ImportPage() {
resetCsvOptions()
if (fileInputRef.current) fileInputRef.current.value = ''
},
- onError: () => toast.error(t('import.importError')),
+ onError: (error: unknown) => {
+ const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
+ toast.error(detail || t('import.importError'))
+ },
})
const deleteMutation = useMutation({
@@ -223,6 +229,23 @@ export default function ImportPage() {
{t('import.dragOrClick')}
</p>
<p className="text-xs text-muted-foreground">{t('import.acceptedFormats')}</p>
+ <button
+ className="mt-2 text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1"
+ onClick={(e) => {
+ e.stopPropagation()
+ const csv = 'date,description,amount,currency,fx_rate\n2026-01-15,Grocery Store,-120.50,USD,\n2026-01-20,Salary Payment,5000.00,EUR,1.08\n'
+ const blob = new Blob([csv], { type: 'text/csv' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = 'template.csv'
+ a.click()
+ URL.revokeObjectURL(url)
+ }}
+ >
+ <Download size={12} />
+ {t('import.downloadTemplate')}
+ </button>
</>
)}
</div>