Open-source personal finance manager. Self-hosted, privacy-first.
fix: skip empty-FITID balance rows in BB OFX import (#99) (#106)
Tássio Noronhabaf8326e5298
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.pyindex 7722765d..b52fe19b 100644--- a/backend/app/services/import_service.py+++ b/backend/app/services/import_service.py@@ -1,4 +1,5 @@import csv+import hashlibimport ioimport reimport uuid@@ -20,20 +21,93 @@ from app.services.fx_rate_service import stamp_primary_amountfrom app.services.payee_service import get_or_create_payee+# Descriptions used by some Brazilian banks (e.g. Banco do Brasil) for+# balance-summary rows that arrive as <STMTTRN> blocks but are not real+# transactions. Matched case-insensitively against MEMO/NAME.+_OFX_BALANCE_ROW_DESCRIPTIONS = (+ "saldo anterior",+ "saldo do dia",+ "saldo final",+ "s a l d o",+)+++def _preprocess_ofx_for_empty_fitid(content: bytes) -> bytes:+ """Synthesize a FITID for STMTTRN blocks that have an empty/missing one.++ Banco do Brasil (and a few other Brazilian banks) emit balance-summary+ rows as <STMTTRN> blocks with empty <FITID> tags, which makes ofxparse+ abort the entire import with "Empty FIT id (a required field)". We patch+ each affected block with a deterministic synthetic FITID so parsing+ succeeds; balance rows are filtered out later by description.+ """+ try:+ text = content.decode("utf-8")+ original_encoding = "utf-8"+ except UnicodeDecodeError:+ text = content.decode("latin-1")+ original_encoding = "latin-1"++ def _replace(match: re.Match) -> str:+ block = match.group(0)+ fitid_match = re.search(r"<FITID>([^<\r\n]*)", block, re.IGNORECASE)+ has_value = fitid_match and fitid_match.group(1).strip()+ if has_value:+ return block++ seed = hashlib.sha1(block.encode("utf-8", errors="replace")).hexdigest()[:16].upper()+ synthetic = f"SYNTH-{seed}"+ if fitid_match:+ return block[: fitid_match.start(1)] + synthetic + block[fitid_match.end(1):]+ # No FITID tag at all — inject one right after the opening <STMTTRN>+ return re.sub(+ r"(<STMTTRN>)",+ rf"\1\n<FITID>{synthetic}",+ block,+ count=1,+ flags=re.IGNORECASE,+ )++ patched = re.sub(+ r"<STMTTRN>.*?</STMTTRN>",+ _replace,+ text,+ flags=re.IGNORECASE | re.DOTALL,+ )+ return patched.encode(original_encoding, errors="replace")+++def _is_balance_summary_row(description: str | None) -> bool:+ if not description:+ return False+ normalized = description.strip().lower()+ return any(normalized.startswith(prefix) for prefix in _OFX_BALANCE_ROW_DESCRIPTIONS)++def parse_ofx(content: bytes) -> list[TransactionBase]:"""Parse OFX file content and return transactions."""+ content = _preprocess_ofx_for_empty_fitid(content)ofx = OfxParser.parse(io.BytesIO(content))transactions = []for account in ofx.accounts:for txn in account.statement.transactions:raw_payee = getattr(txn, 'payee', None) or None+ description = txn.memo or txn.payee or "Unknown"+ if _is_balance_summary_row(description):+ continue+ external_id = getattr(txn, 'id', None)+ # Synthetic IDs are added only to make ofxparse happy; do not+ # persist them as external_id since they are not stable bank+ # identifiers.+ if external_id and external_id.startswith("SYNTH-"):+ external_id = Nonetransactions.append(TransactionBase(- description=txn.memo or txn.payee or "Unknown",+ description=description,amount=abs(Decimal(str(txn.amount))),date=txn.date.date() if hasattr(txn.date, 'date') else txn.date,type="credit" if txn.amount > 0 else "debit",- external_id=getattr(txn, 'id', None),+ external_id=external_id,payee_raw=raw_payee,))diff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.pyindex c9ec5812..ecedf7bd 100644--- a/backend/tests/test_import_service.py+++ b/backend/tests/test_import_service.py@@ -599,6 +599,57 @@ class TestParseOfx:assert transactions[0].amount == transactions[1].amountassert transactions[0].description == transactions[1].description+ def test_parse_ofx_skips_balance_summary_rows_with_empty_fitid(self):+ """Banco do Brasil emits Saldo Anterior/Saldo do dia as STMTTRN with empty+ FITID. These should be silently skipped instead of aborting the import."""+ ofx = self._make_ofx(+ "<STMTTRN>\n"+ "<TRNTYPE>OTHER\n"+ "<DTPOSTED>20260101\n"+ "<TRNAMT>0.00\n"+ "<FITID>\n"+ "<MEMO>Saldo Anterior\n"+ "</STMTTRN>\n"+ "<STMTTRN>\n"+ "<TRNTYPE>DEBIT\n"+ "<DTPOSTED>20260115\n"+ "<TRNAMT>-985.50\n"+ "<FITID>TXN001ABC\n"+ "<MEMO>PIX ENVIADO - FULANO\n"+ "</STMTTRN>\n"+ "<STMTTRN>\n"+ "<TRNTYPE>OTHER\n"+ "<DTPOSTED>20260131\n"+ "<TRNAMT>0.00\n"+ "<FITID>\n"+ "<MEMO>Saldo do dia\n"+ "</STMTTRN>\n"+ )+ transactions = parse_ofx(ofx)++ assert len(transactions) == 1+ assert transactions[0].external_id == "TXN001ABC"+ assert transactions[0].description == "PIX ENVIADO - FULANO"++ def test_parse_ofx_keeps_real_transactions_with_empty_fitid(self):+ """A real transaction missing a FITID should still be imported (without+ an external_id), not abort the whole file."""+ ofx = self._make_ofx(+ "<STMTTRN>\n"+ "<TRNTYPE>DEBIT\n"+ "<DTPOSTED>20260115\n"+ "<TRNAMT>-100.00\n"+ "<FITID>\n"+ "<MEMO>UBER TRIP\n"+ "</STMTTRN>\n"+ )+ transactions = parse_ofx(ofx)++ assert len(transactions) == 1+ assert transactions[0].external_id is None+ assert transactions[0].description == "UBER TRIP"+ assert transactions[0].amount == Decimal("100.00")+# ═══════════════════════════════════════════════════════════════════════════# MULTI-CURRENCY PARSING TESTS