fix(statements): read period and balances from statement PDF text

Merged
SI
2mo ago
+773-21

Problem

PDF statements only get metadata from their filename (pdf_detection: "filename_only"). Many banks give every statement the same undated name (Trade Republic calls them all Account statement.pdf), so those statements end up with no period and no balances. The coverage view then shows missing months, and balance reconciliation can't run.

Closes #4053

Changes

  • New AccountStatement::TextMetadataParser: reads the period, the IBAN's last four digits and the opening and closing balances from a statement's text, for any bank. It has no bank-specific code: anything it can't read stays blank, and filename detection fills in.
    • Period: the dates of the opening and closing balance ("Saldo iniziale al 01.07.2025" … "Saldo finale al 30.09.2025", "Alter Kontostand vom 31.03.2026"), otherwise the first date range in the text. Balance dates win because the first range can belong to a promotion. An opening balance dated at a month end starts the period the next day.
    • Dates: textual (01 apr 2026, April 1, 2026), numeric (01.04.2026), ISO (2026-04-01) and ordinal (01st 1 2025). Month names are matched by prefix in Italian, English, German, French, Spanish, Dutch and Portuguese, e.g. Sept., févr., maart, septiembre.
    • Balances: a summary table, i.e. the first four amounts after an opening-balance label, kept only when opening + in − out = closing (±0.01). Otherwise an opening and a closing balance next to their labels ("Opening/Closing balance", "Saldo iniziale/finale", "Alter/Neuer Kontostand", "Solde initial/final", "Beginning/Ending balance", …), on the same line or on the next one when the label stands alone. "Carried forward" isn't used, because it is often a per-page subtotal.
    • Amounts: 1.944,58 €, +6.045,31 €, 1 944,58 €, €1,944.58, 1.234,56 EUR, £1,234.56 or $2,500.00, with a sign on either side. Dates such as 31.03.2026 are never read as amounts. Both balances must carry the same currency, and $ is only accepted when the statement is in a dollar currency.
    • IBAN: unspaced or in printed groups (DE89 3704 0044 0532 0130 00), stopping before a BIC on the same line.
    • Keyword sources: the opening-balance labels and month names beyond Italian follow two open-source Trade Republic PDF converters, jcmpagel/Trade-Republic-CSV-Excel (including its French support PR) and kalix127/tradesight. The other labels are common statement wording in those languages.
  • AccountStatement::MetadataDetector: for PDFs, reads the text of the first two pages before falling back to the filename.
    • Values from the document win; the filename only fills what the document left blank.
    • Balances are stored only when their currency matches the statement's, so reconciliation never compares different currencies.
    • If the PDF can't be read, it falls back to filename detection instead of failing the upload.
    • sanitized_parser_output records pdf_detection: "text", pdf.balances_source (summary_table or labels) and pdf.balances_detected, never the extracted text.
    • parser_confidence is 0.85 when the PDF text was used.
  • New Pdf::TextExtractor: one shared way to get the text of a PDF's pages, with an optional page limit. The statement detector, VectorStore::Embeddable and Provider::Openai::PdfProcessor all use it; each keeps its own page joining and error handling.
  • Upload hint: a new account_statements.form.period_hint explains where the period comes from (the PDF when it states one, a date in the filename like 2026-04, or manual entry). It's translated in all 17 locale files.
  • Onboarding guide: a new "Uploading statements" section explains how the period and balances are detected.

Filename detection is unchanged: the existing YYYY-MM, full-date and month-name patterns still apply.

Validation

  • Real statements from two banks:
    • Trade Republic (Italian edition), monthly and annual statements and the anonymised fixture: period, IBAN and balances are read from the summary table.
    • isybank (Intesa Sanpaolo), two quarterly statements: the period comes from the balance dates (one statement also contains a promotion with its own date range), and the balances from their labels, with the closing amount on the line after its label.
    • The repo's M-PESA sample (imports/sample_bank_statement.pdf) now gets its period (01st 1 2025 - 01st 7 2025) from the text. It has no opening or closing balance, so none is stored.
  • Minitest:
    • text_metadata_parser_test.rb: the summary table in both text orders; labelled balances with numeric dates and a grouped IBAN; the isybank layout (anonymised text); an opening balance dated at a month end; month-first and ISO dates and pounds; a dollar statement only in a dollar currency; ordinal dates without balances; German, English, French, Spanish and Dutch month names and amount formats; negative amounts; balances that don't add up or don't share a currency are dropped; unrelated text is ignored.
    • account_statement_test.rb: end-to-end upload of the anonymised Trade Republic PDF, under its default name and under a filename with a conflicting date (the PDF's period wins); the currency guard; the M-PESA PDF; a bare token like Invoice_04-2029.pdf is not read as a period.
    • pdf/text_extractor_test.rb: page text, the page limit, and errors for non-PDF content.
  • Checks: bin/rubocop, erb_lint, npm run lint and bin/brakeman pass. bin/rails test has no new failures; the failures left locally come from my local environment and pass in CI.

Summary by CodeRabbit

Summary

  • New Features
    • Trade Republic PDF statements can provide the statement period, opening and closing balances, currency, institution, and last four digits of the IBAN.
    • Statement details are recognized across six languages and multiple date formats.
  • Improvements
    • Sure checks PDF content before filename dates when detecting a statement period; you can also enter the period manually.
    • Balances are included only when the detected currency matches the statement currency or it is blank.
    • Upload guidance now includes the maximum file size and explains period detection.