The personal finance app for everyone (by everyone)
Ruby
fix(statements): read period and balances from statement PDF text (#4054)
Simonecc615b3ee7ef
diff --git a/app/models/account_statement/metadata_detector.rb b/app/models/account_statement/metadata_detector.rbindex e8079d5b8d..6b1234818f 100644--- a/app/models/account_statement/metadata_detector.rb+++ b/app/models/account_statement/metadata_detector.rb@@ -35,6 +35,7 @@ class AccountStatement::MetadataDetectorMAX_CSV_COLUMNS = 100MAX_CSV_DATE_SAMPLES = 250MAX_CSV_SAMPLE_BYTES = 256+ MAX_PDF_METADATA_PAGES = 2attr_reader :statement, :content@@ -47,6 +48,12 @@ class AccountStatement::MetadataDetectoroutput = statement.sanitized_parser_output || {}metadata_sources = []+ # The document's own text is more reliable than the filename, so it runs+ # first and the filename only fills what it left blank.+ if statement.pdf? && detect_from_pdf(output)+ metadata_sources << "pdf_text"+ end+if detect_from_filenamemetadata_sources << "filename"end@@ -56,12 +63,14 @@ class AccountStatement::MetadataDetectorelsif statement.xlsx?output["spreadsheet_detection"] = "filename_only"elsif statement.pdf?- output["pdf_detection"] = "filename_only"+ output["pdf_detection"] ||= "filename_only"endoutput["metadata_sources"] = metadata_sourcesstatement.sanitized_parser_output = output- statement.parser_confidence ||= if metadata_sources.include?("csv_dates")+ statement.parser_confidence ||= if metadata_sources.include?("pdf_text")+ 0.85+ elsif metadata_sources.include?("csv_dates")0.65elsif metadata_sources.any?0.45@@ -122,6 +131,41 @@ class AccountStatement::MetadataDetectordetectedend+ def detect_from_pdf(output)+ summary = AccountStatement::TextMetadataParser.parse(pdf_text, currency: statement.currency)+ return false unless summary++ statement.period_start_on ||= summary.period_start_on+ statement.period_end_on ||= summary.period_end_on+ statement.account_last4_hint ||= summary.iban_last4++ # Only keep balances when they are in the statement's currency; a+ # mismatch would make reconciliation compare different currencies.+ balances_kept = summary.currency.present? && (statement.currency.blank? || statement.currency == summary.currency)+ if balances_kept+ statement.currency ||= summary.currency+ statement.opening_balance ||= summary.opening_balance+ statement.closing_balance ||= summary.closing_balance+ end++ output["pdf_detection"] = "text"+ output["pdf"] = {+ "balances_source" => (summary.balances_source if balances_kept),+ "balances_detected" => statement.opening_balance.present? && statement.closing_balance.present?+ }+ true+ end++ # Text of the first pages only: periods and balance summaries sit at the+ # top of a statement. Any reader failure leaves filename detection as the+ # fallback instead of failing the upload.+ def pdf_text+ Pdf::TextExtractor.pages(content, max_pages: MAX_PDF_METADATA_PAGES).join("\n")+ rescue StandardError => e+ Rails.logger.info("AccountStatement::MetadataDetector - PDF text unavailable: #{e.class}")+ ""+ end+def detect_from_csv(output)csv = CSV.new(StringIO.new(content.to_s), headers: true, liberal_parsing: true)first_row = csv.shiftdiff --git a/app/models/account_statement/text_metadata_parser.rb b/app/models/account_statement/text_metadata_parser.rbnew file mode 100644index 0000000000..adc6b22885--- /dev/null+++ b/app/models/account_statement/text_metadata_parser.rb@@ -0,0 +1,302 @@+# frozen_string_literal: true++# Reads the period, IBAN and opening/closing balances from the text of a bank+# statement, without knowing which bank wrote it.+#+# - Period: the first date range in the text, e.g. "01 apr 2026 - 30 apr 2026",+# "01.04.2026 – 30.04.2026", "2026-04-01 to 2026-04-30",+# "April 1, 2026 to April 30, 2026" or "01st 1 2025 - 01st 7 2025".+# - Balances, in order of preference:+# 1. A summary table: the first four amounts after an opening-balance label,+# kept only when opening + in - out == closing.+# 2. An opening and a closing balance, each on the same line as its label+# ("Alter Kontostand 1.234,56 EUR" ... "Neuer Kontostand 2.000,00 EUR").+# Both balances must carry the same currency.+#+# Month names and labels cover Italian, English, German, French, Spanish,+# Dutch and Portuguese. Anything it can't read is left blank, so a statement+# it doesn't understand falls back to filename detection.+class AccountStatement::TextMetadataParser+ Result = Data.define(+ :period_start_on, :period_end_on, :opening_balance, :closing_balance, :currency, :iban_last4, :balances_source+ )++ # Month tokens are matched in full, then on their first four and three+ # letters, which covers abbreviations ("Sept.", "févr.") and full names.+ MONTHS = {+ "jan" => 1, "gen" => 1, "ene" => 1, "janv" => 1,+ "feb" => 2, "fév" => 2, "fev" => 2, "févr" => 2, "fevr" => 2,+ "mar" => 3, "maa" => 3, "mär" => 3, "mrz" => 3, "mrt" => 3,+ "apr" => 4, "avr" => 4, "abr" => 4,+ "may" => 5, "mag" => 5, "mai" => 5, "mei" => 5,+ "jun" => 6, "giu" => 6, "juin" => 6,+ "jul" => 7, "lug" => 7, "juil" => 7,+ "aug" => 8, "ago" => 8, "aoû" => 8, "aou" => 8,+ "sep" => 9, "set" => 9,+ "oct" => 10, "ott" => 10, "okt" => 10, "out" => 10,+ "nov" => 11,+ "dec" => 12, "dic" => 12, "dez" => 12, "déc" => 12+ }.freeze++ ORDINAL = /(?:st|nd|rd|th)?/i+ MONTH_NAME = /[[:alpha:]]{3,10}/+ DATE_FORMATS = {+ iso: /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/,+ numeric: %r{(?<day>\d{1,2})[./-](?<month>\d{1,2})[./-](?<year>\d{4})},+ ordinal_numeric: /(?<day>\d{1,2})(?:st|nd|rd|th)\s+(?<month>\d{1,2})\s+(?<year>\d{4})/i,+ day_month_name: /(?<day>\d{1,2})\.?#{ORDINAL}\s+(?<month_name>#{MONTH_NAME})\.?\s+(?<year>\d{4})/,+ month_name_day: /(?<month_name>#{MONTH_NAME})\.?\s+(?<day>\d{1,2})#{ORDINAL},?\s+(?<year>\d{4})/+ }.freeze+ DATE = Regexp.union(DATE_FORMATS.values.map { |format| Regexp.new(format.source.gsub(/\(\?<\w+>/, "(?:"), format.options) })+ RANGE_SEPARATOR = /\s*(?:[-–—]|\b(?:to|through|until|bis|al|au|tot|a|até|hasta)\b)\s*/i+ PERIOD_PATTERN = /(?<start>#{DATE})#{RANGE_SEPARATOR}(?<end>#{DATE})/+ # Annual statements span a year; anything longer isn't one period.+ MAX_PERIOD_DAYS = 400++ OPENING_LABELS = [+ "opening balance", "beginning balance", "starting balance", "initial balance", "previous balance",+ "balance brought forward", "saldo iniziale", "saldo precedente", "anfangssaldo", "alter kontostand",+ "alter saldo", "solde initial", "solde d'ouverture", "ancien solde", "solde précédent",+ "saldo inicial", "saldo anterior", "beginsaldo", "vorig saldo"+ ].freeze+ # "Carried forward" is left out: it is often a per-page subtotal.+ CLOSING_LABELS = [+ "closing balance", "ending balance", "final balance", "new balance", "saldo finale", "endsaldo",+ "neuer kontostand", "neuer saldo", "solde final", "solde de fermeture", "nouveau solde",+ "saldo final", "saldo atual", "eindsaldo", "nieuw saldo"+ ].freeze++ # Words may be split by spaces or dots: some PDFs extract "Saldo.iniziale".+ def self.label_pattern(labels)+ Regexp.union(labels.map { |label| /#{label.split.map { |word| Regexp.escape(word) }.join('[\s.]+')}/i })+ end++ OPENING_PATTERN = label_pattern(OPENING_LABELS)+ CLOSING_PATTERN = label_pattern(CLOSING_LABELS)+ BALANCE_LABEL_PATTERN = Regexp.union(OPENING_PATTERN, CLOSING_PATTERN)+ # The date a balance label is stated for: "Saldo iniziale al 01.07.2025",+ # "Alter Kontostand vom 31.03.2026", "Opening balance on 1 April 2026".+ LABEL_DATE = /\A[\s.:]*(?:(?:al|vom|am|as of|as at|at|on|du|au|del|op|em|per)\b)?[\s.:]*(?<date>#{DATE})/i++ # A number with two decimals ("1.944,58", "1,944.58", "1 944,58", "1'944.58")+ # that isn't part of a date such as 31.03.2026.+ AMOUNT_NUMBER = /(?<![\d.,])\d{1,3}(?:[.,'\u00A0\u202F ]\d{3})*[.,]\d{2}(?![\d]|[.,\/-]\d)/+ CURRENCY_MARK = /€|£|\$|\b[A-Z]{3}\b/+ # "1.234,56 €", "+1.234,56 €", "1.234,56 EUR", "-1.234,56 €", "€1,234.56",+ # "-€1,234.56", "€-1,234.56", "EUR 1.234,56" or a bare "1.234,56".+ AMOUNT_PATTERN = Regexp.union(+ /(?<prefix_sign>[-+])?(?<prefix_currency>#{CURRENCY_MARK})\p{Blank}*(?<inner_sign>[-+])?(?<prefix_number>#{AMOUNT_NUMBER})/,+ /(?<suffix_sign>[-+])?(?<suffix_number>#{AMOUNT_NUMBER})(?:\p{Blank}*(?<suffix_currency>#{CURRENCY_MARK}))?/+ )+ CURRENCY_SYMBOLS = { "€" => "EUR", "£" => "GBP" }.freeze+ # The rest of the line after "IBAN": one unspaced token, or the printed+ # groups of four ("DE89 3704 0044 0532 0130 00").+ IBAN_PATTERN = /IBAN[:\s]*([A-Z]{2}\d{2}[A-Z0-9 ]*)/+ TOLERANCE = BigDecimal("0.01")++ Amount = Data.define(:value, :currency)++ # currency: the statement's currency, used to read an ambiguous symbol+ # such as "$" when the statement is in a dollar currency.+ def self.parse(text, currency: nil)+ new(text, currency: currency).parse+ end++ def initialize(text, currency: nil)+ @text = text.to_s.dup.force_encoding(Encoding::UTF_8).scrub+ @currency_hint = currency.to_s.upcase.presence+ end++ def parse+ period = parse_period+ balances, source = parse_balances+ return nil if period.nil? && balances.nil?++ Result.new(+ period_start_on: period&.first,+ period_end_on: period&.last,+ opening_balance: balances&.first&.value,+ closing_balance: balances&.last&.value,+ currency: balances&.first&.currency,+ iban_last4: parse_iban_last4,+ balances_source: source+ )+ end++ private++ # The dates next to the opening and closing balance belong to the+ # statement itself, so they win over the first date range in the text,+ # which can be a promotion ("dal 3 luglio 2024 al 30 giugno 2025").+ def parse_period+ label_period || range_period+ end++ def label_period+ opening_on = date_after_label(OPENING_PATTERN)+ closing_on = date_after_label(CLOSING_PATTERN)+ return nil unless opening_on && closing_on++ # A balance dated at a month end is the previous period's closing+ # ("Alter Kontostand vom 31.03.2026"), so the period starts the next day.+ start_on = opening_on == opening_on.end_of_month ? opening_on + 1 : opening_on+ valid_period(start_on, closing_on)+ end++ def range_period+ @text.to_enum(:scan, PERIOD_PATTERN).each do+ match = Regexp.last_match+ period = valid_period(parse_date(match[:start]), parse_date(match[:end]))+ return period if period+ end+ nil+ end++ def valid_period(start_on, end_on)+ return nil if start_on.nil? || end_on.nil? || end_on < start_on || (end_on - start_on) > MAX_PERIOD_DAYS++ [ start_on, end_on ]+ end++ def date_after_label(pattern)+ @text.each_line do |line|+ match = line.match(pattern)+ next unless match++ raw = line[match.end(0)..][LABEL_DATE, "date"]+ date = raw && parse_date(raw)+ return date if date+ end+ nil+ end++ def parse_date(raw)+ DATE_FORMATS.each_value do |format|+ match = raw.match(/\A#{format}\z/)+ next unless match++ month = match.names.include?("month") ? match[:month].to_i : month_number(match[:month_name])+ next unless month&.between?(1, 12)++ date = Date.new(match[:year].to_i, month, match[:day].to_i)+ return date if AccountStatement::MetadataDetector.reasonable_date?(date)+ rescue Date::Error+ next+ end+ nil+ end++ def month_number(name)+ token = name.to_s.downcase+ MONTHS[token] || MONTHS[token[0, 4]] || MONTHS[token[0, 3]]+ end++ def parse_balances+ summary = parse_summary_table+ return [ summary, "summary_table" ] if summary++ labelled = parse_labelled_balances+ return [ labelled, "labels" ] if labelled++ nil+ end++ def parse_summary_table+ header_index = @text =~ OPENING_PATTERN+ return nil unless header_index++ amounts = amounts_in(@text[header_index..]).first(4)+ return nil if amounts.size < 4++ opening, money_in, money_out, closing = amounts+ return nil unless (opening.value + money_in.value - money_out.value - closing.value).abs <= TOLERANCE++ same_currency(opening, closing)+ end++ def parse_labelled_balances+ opening = amount_after_label(OPENING_PATTERN)+ closing = amount_after_label(CLOSING_PATTERN)+ return nil unless opening && closing++ same_currency(opening, closing)+ end++ # The first amount after the label on its line, or on the next non-blank+ # line when the label stands alone ("Saldo finale al 30.09.2025", then+ # "+6.506,55 €"). A line with several labels is a table header whose next+ # line holds every column, so it never falls through.+ def amount_after_label(pattern)+ lines = @text.lines+ lines.each_with_index do |line, index|+ match = line.match(pattern)+ next unless match++ amount = amounts_in(line[match.end(0)..]).first+ return amount if amount+ next if line.scan(BALANCE_LABEL_PATTERN).size > 1++ following = lines[(index + 1)..].find { |candidate| candidate.strip.present? }+ amount = following && amounts_in(following).first+ return amount if amount+ end+ nil+ end++ def same_currency(opening, closing)+ return nil unless opening.currency == closing.currency++ [ opening, closing ]+ end++ def amounts_in(text)+ text.to_enum(:scan, AMOUNT_PATTERN).filter_map do+ match = Regexp.last_match+ value = parse_amount(match[:prefix_number] || match[:suffix_number])+ next unless value++ negative = [ match[:prefix_sign], match[:inner_sign], match[:suffix_sign] ].include?("-")+ Amount.new(value: negative ? -value : value, currency: resolve_currency(match[:prefix_currency] || match[:suffix_currency]))+ end+ end++ # Accepts "1.944,58" and "1,944.58": the last separator is the decimal one.+ def parse_amount(value)+ digits = value.to_s.delete(" '\u00A0\u202F")+ decimal_separator = digits[-3]+ integer_part, fraction = digits[0...-3], digits[-2..]+ return nil unless [ ",", "." ].include?(decimal_separator)++ BigDecimal("#{integer_part.delete(".,")}.#{fraction}")+ rescue ArgumentError+ nil+ end++ def resolve_currency(token)+ return nil if token.blank?+ return CURRENCY_SYMBOLS[token] if CURRENCY_SYMBOLS.key?(token)+ return dollar_hint if token == "$"++ Money::Currency.new(token).iso_code+ rescue Money::Currency::UnknownCurrencyError+ nil+ end++ def dollar_hint+ @currency_hint if @currency_hint && Money::Currency.new(@currency_hint).symbol == "$"+ rescue Money::Currency::UnknownCurrencyError+ nil+ end++ def parse_iban_last4+ tokens = @text[IBAN_PATTERN, 1].to_s.split(" ")+ iban = tokens.shift.to_s+ if iban.length == 4+ # Printed groups: keep the four-character ones, then a shorter final+ # group of digits, and stop before anything else on the line (a BIC).+ iban << tokens.shift while tokens.first&.match?(/\A[A-Z0-9]{4}\z/)+ iban << tokens.shift if tokens.first&.match?(/\A\d{1,3}\z/)+ end+ iban.match?(/\d{4}\z/) ? iban[-4..] : nil+ end+enddiff --git a/app/models/pdf/text_extractor.rb b/app/models/pdf/text_extractor.rbnew file mode 100644index 0000000000..83f7ef1e9f--- /dev/null+++ b/app/models/pdf/text_extractor.rb@@ -0,0 +1,9 @@+# The text of each page of a PDF, in order. Callers decide how to join the+# pages and how to handle a PDF the reader cannot open; errors propagate.+module Pdf::TextExtractor+ def self.pages(content, max_pages: nil)+ pages = PDF::Reader.new(StringIO.new(content.to_s)).pages+ pages = pages.first(max_pages) if max_pages+ pages.map(&:text)+ end+enddiff --git a/app/models/provider/openai/pdf_processor.rb b/app/models/provider/openai/pdf_processor.rbindex 6098ab303c..00a6f0072f 100644--- a/app/models/provider/openai/pdf_processor.rb+++ b/app/models/provider/openai/pdf_processor.rb@@ -146,15 +146,9 @@ class Provider::Openai::PdfProcessordef extract_text_from_pdfreturn nil if pdf_content.blank?- reader = PDF::Reader.new(StringIO.new(pdf_content))- text_parts = []-- reader.pages.each_with_index do |page, index|- text_parts << "--- Page #{index + 1} ---"- text_parts << page.text- end-- text_parts.join("\n\n")+ Pdf::TextExtractor.pages(pdf_content).each_with_index.flat_map do |text, index|+ [ "--- Page #{index + 1} ---", text ]+ end.join("\n\n")rescue => eRails.logger.error("Failed to extract text from PDF: #{e.message}")nildiff --git a/app/models/vector_store/embeddable.rb b/app/models/vector_store/embeddable.rbindex 298e9e30a9..11d6baf569 100644--- a/app/models/vector_store/embeddable.rb+++ b/app/models/vector_store/embeddable.rb@@ -28,9 +28,7 @@ module VectorStore::Embeddableenddef extract_pdf_text(file_content)- io = StringIO.new(file_content)- reader = PDF::Reader.new(io)- reader.pages.map(&:text).join("\n\n")+ Pdf::TextExtractor.pages(file_content).join("\n\n")rescue => eRails.logger.error("VectorStore::Embeddable PDF extraction error: #{e.message}")nildiff --git a/app/views/account_statements/index.html.erb b/app/views/account_statements/index.html.erbindex 1d45dede56..3b9069a944 100644--- a/app/views/account_statements/index.html.erb+++ b/app/views/account_statements/index.html.erb@@ -22,7 +22,7 @@<%# Its own row on wide screens, so the three fields line up with eachother rather than with the bottom of this hint. Stacked, it stillfollows the file field it describes. %>- <p class="text-xs text-secondary -mt-1 lg:col-start-1 lg:row-start-2"><%= t("account_statements.form.files_hint", max_size: AccountStatement::MAX_FILE_SIZE / 1.megabyte) %></p>+ <p class="text-xs text-secondary -mt-1 lg:col-start-1 lg:row-start-2"><%= t("account_statements.form.files_hint", max_size: AccountStatement::MAX_FILE_SIZE / 1.megabyte) %> <%= t("account_statements.form.period_hint") %></p><%= form.collection_select :account_id,@accounts,:id,diff --git a/app/views/accounts/show/_statements.html.erb b/app/views/accounts/show/_statements.html.erbindex 877f203986..c8a7273fa5 100644--- a/app/views/accounts/show/_statements.html.erb+++ b/app/views/accounts/show/_statements.html.erb@@ -46,7 +46,7 @@label: t("account_statements.form.files_label"),multiple: true,accept: AccountStatement::ACCEPTED_FILE_EXTENSIONS.join(",") %>- <p class="text-xs text-secondary mt-2"><%= t("account_statements.form.files_hint", max_size: AccountStatement::MAX_FILE_SIZE / 1.megabyte) %></p>+ <p class="text-xs text-secondary mt-2"><%= t("account_statements.form.files_hint", max_size: AccountStatement::MAX_FILE_SIZE / 1.megabyte) %> <%= t("account_statements.form.period_hint") %></p></div><%= form.submit t("account_statements.form.account_upload") %><% end %>diff --git a/config/locales/views/account_statements/ca.yml b/config/locales/views/account_statements/ca.ymlindex c171114496..681291e8bd 100644--- a/config/locales/views/account_statements/ca.yml+++ b/config/locales/views/account_statements/ca.yml@@ -37,6 +37,7 @@ ca:files_hint: PDF, CSV o XLSX. Màxim %{max_size}MB per fitxer.files_label: Fitxers d'extracteinbox_upload: Puja+ period_hint: "Sure llegeix el període del PDF si l’indica, o d’una data al nom del fitxer (p. ex. 2026-04). També el pots indicar a l’extracte."index:account_label: Compteconfidence: Coincidència %{confidence}diff --git a/config/locales/views/account_statements/de.yml b/config/locales/views/account_statements/de.ymlindex 9b5295ca4a..b7f37f21cc 100644--- a/config/locales/views/account_statements/de.yml+++ b/config/locales/views/account_statements/de.yml@@ -36,6 +36,7 @@ de:files_hint: PDF, CSV oder XLSX. Max. %{max_size} MB pro Datei.files_label: Kontoauszugsdateieninbox_upload: Hochladen+ period_hint: "Sure liest den Zeitraum aus dem PDF, wenn er dort angegeben ist, oder aus einem Datum im Dateinamen (z. B. 2026-04). Du kannst ihn auch am Auszug festlegen."index:account_label: Kontoconfidence: "%{confidence} Übereinstimmung"diff --git a/config/locales/views/account_statements/en.yml b/config/locales/views/account_statements/en.ymlindex 6a4062d47d..2c6fcf3034 100644--- a/config/locales/views/account_statements/en.yml+++ b/config/locales/views/account_statements/en.yml@@ -36,6 +36,7 @@ en:files_hint: PDF, CSV, or XLSX. %{max_size}MB max per file.files_label: Statement filesinbox_upload: Upload+ period_hint: "Sure reads the period from the PDF when it states one, or from a date in the filename (e.g. 2026-04). You can also set it on the statement."index:account_label: Accountconfidence: "%{confidence} match"diff --git a/config/locales/views/account_statements/es.yml b/config/locales/views/account_statements/es.ymlindex 8572eb7180..ba03e111f2 100644--- a/config/locales/views/account_statements/es.yml+++ b/config/locales/views/account_statements/es.yml@@ -36,6 +36,7 @@ es:files_hint: PDF, CSV o XLSX. Máximo %{max_size} MB por archivo.files_label: Archivos de extractoinbox_upload: Subir+ period_hint: "Sure lee el periodo del PDF si lo indica, o de una fecha en el nombre del archivo (p. ej. 2026-04). También puedes indicarlo en el extracto."index:account_label: Cuentaconfidence: "Coincidencia del %{confidence}"diff --git a/config/locales/views/account_statements/fr.yml b/config/locales/views/account_statements/fr.ymlindex b2b0265374..07df5bea21 100644--- a/config/locales/views/account_statements/fr.yml+++ b/config/locales/views/account_statements/fr.yml@@ -38,6 +38,7 @@ fr:files_hint: PDF, CSV ou XLSX. %{max_size}Mo maximum par fichier.files_label: Fichiers de relevésinbox_upload: Télécharger+ period_hint: "Sure lit la période dans le PDF lorsqu’il l’indique, ou à partir d’une date dans le nom du fichier (p. ex. 2026-04). Vous pouvez aussi la saisir sur le relevé."index:account_label: Compteconfidence: "%{confidence} correspond"diff --git a/config/locales/views/account_statements/hu.yml b/config/locales/views/account_statements/hu.ymlindex 8a9201114f..3c864896ba 100644--- a/config/locales/views/account_statements/hu.yml+++ b/config/locales/views/account_statements/hu.yml@@ -36,6 +36,7 @@ hu:files_hint: PDF, CSV vagy XLSX. Maximum %{max_size} MB fájlonként.files_label: Kimutatásfájlokinbox_upload: Feltöltés+ period_hint: "A Sure az időszakot a PDF-ből olvassa ki, ha szerepel benne, vagy a fájlnévben lévő dátumból (pl. 2026-04). A kivonaton kézzel is megadhatod."index:account_label: Számlaconfidence: "%{confidence} egyezés"diff --git a/config/locales/views/account_statements/it.yml b/config/locales/views/account_statements/it.ymlindex 8e6bc9e883..67386851bd 100644--- a/config/locales/views/account_statements/it.yml+++ b/config/locales/views/account_statements/it.yml@@ -36,6 +36,7 @@ it:files_hint: PDF, CSV o XLSX. Max %{max_size}MB per file.files_label: File estratti contoinbox_upload: Carica+ period_hint: "Sure legge il periodo dal PDF, se lo riporta, o da una data nel nome del file (es. 2026-04). Puoi anche impostarlo nell’estratto conto."index:account_label: Contoconfidence: "Corrispondenza %{confidence}"diff --git a/config/locales/views/account_statements/nl.yml b/config/locales/views/account_statements/nl.ymlindex 35e302f6ed..9f02ae7717 100644--- a/config/locales/views/account_statements/nl.yml+++ b/config/locales/views/account_statements/nl.yml@@ -36,6 +36,7 @@ nl:files_hint: PDF, CSV of XLSX. Max. %{max_size} MB per bestand.files_label: Afschriftbestandeninbox_upload: Uploaden+ period_hint: "Sure leest de periode uit de pdf als die erin staat, of uit een datum in de bestandsnaam (bijv. 2026-04). Je kunt hem ook bij het afschrift instellen."index:account_label: Accountconfidence: "%{confidence} overeenkomst"diff --git a/config/locales/views/account_statements/pl.yml b/config/locales/views/account_statements/pl.ymlindex c7326c417d..22ec43a590 100644--- a/config/locales/views/account_statements/pl.yml+++ b/config/locales/views/account_statements/pl.yml@@ -42,6 +42,7 @@ pl:files_hint: PDF, CSV lub XLSX. Maks. %{max_size} MB na plik.files_label: Pliki wyciągówinbox_upload: Prześlij+ period_hint: "Sure odczytuje okres z pliku PDF, jeśli jest w nim podany, lub z daty w nazwie pliku (np. 2026-04). Możesz go też ustawić na wyciągu."index:account_label: Kontoconfidence: Zgodność %{confidence}diff --git a/config/locales/views/account_statements/pt-BR.yml b/config/locales/views/account_statements/pt-BR.ymlindex 5a44e1cb76..526e03c3a7 100644--- a/config/locales/views/account_statements/pt-BR.yml+++ b/config/locales/views/account_statements/pt-BR.yml@@ -36,6 +36,7 @@ pt-BR:files_hint: PDF, CSV ou XLSX. Máximo de %{max_size} MB por arquivo.files_label: Arquivos de extratoinbox_upload: Enviar+ period_hint: "O Sure lê o período do PDF, quando ele o informa, ou de uma data no nome do arquivo (ex.: 2026-04). Você também pode defini-lo no extrato."index:account_label: Contaconfidence: "%{confidence} de correspondência"diff --git a/config/locales/views/account_statements/pt-PT.yml b/config/locales/views/account_statements/pt-PT.ymlindex cba28ac753..40aad380bc 100644--- a/config/locales/views/account_statements/pt-PT.yml+++ b/config/locales/views/account_statements/pt-PT.yml@@ -36,6 +36,7 @@ pt-PT:files_hint: PDF, CSV ou XLSX. Máx. %{max_size} MB por ficheiro.files_label: Ficheiros de extratoinbox_upload: Carregar+ period_hint: "O Sure lê o período do PDF, quando este o indica, ou de uma data no nome do ficheiro (ex.: 2026-04). Também o pode definir no extrato."index:account_label: Contaconfidence: "Correspondência de %{confidence}"diff --git a/config/locales/views/account_statements/ru.yml b/config/locales/views/account_statements/ru.ymlindex e1ad28bcc3..c117f42611 100644--- a/config/locales/views/account_statements/ru.yml+++ b/config/locales/views/account_statements/ru.yml@@ -42,6 +42,7 @@ ru:files_hint: PDF, CSV или XLSX. Максимум %{max_size}МБ на файл.files_label: Файлы выписокinbox_upload: Загрузить+ period_hint: "Sure берёт период из PDF-выписки, если он там указан, или из даты в имени файла (например, 2026-04). Его также можно указать в выписке вручную."index:account_label: Счётconfidence: "%{confidence} совпадение"diff --git a/config/locales/views/account_statements/tr.yml b/config/locales/views/account_statements/tr.ymlindex fed89c65fe..796e2775d9 100644--- a/config/locales/views/account_statements/tr.yml+++ b/config/locales/views/account_statements/tr.yml@@ -37,6 +37,7 @@ tr:files_hint: PDF, CSV veya XLSX. Dosya başına en fazla %{max_size}MB.files_label: Ekstre dosyalarıinbox_upload: Yükle+ period_hint: "Sure dönemi, belirtilmişse PDF’ten veya dosya adındaki bir tarihten (ör. 2026-04) okur. Dönemi ekstre üzerinde de ayarlayabilirsiniz."index:account_label: Hesapconfidence: "%{confidence} eşleşme"diff --git a/config/locales/views/account_statements/uk.yml b/config/locales/views/account_statements/uk.ymlindex fda1898364..3011741d1d 100644--- a/config/locales/views/account_statements/uk.yml+++ b/config/locales/views/account_statements/uk.yml@@ -40,6 +40,7 @@ uk:files_hint: "PDF, CSV або XLSX. Максимум %{max_size}MB на файл."files_label: "Файли виписок"inbox_upload: "Завантажити"+ period_hint: "Sure бере період із PDF-виписки, якщо його там зазначено, або з дати в назві файлу (наприклад, 2026-04). Його також можна вказати у виписці вручну."index:account_label: "Рахунок"confidence: "%{confidence} збіг"diff --git a/config/locales/views/account_statements/vi.yml b/config/locales/views/account_statements/vi.ymlindex b68ed162be..976d99e4e5 100644--- a/config/locales/views/account_statements/vi.yml+++ b/config/locales/views/account_statements/vi.yml@@ -36,6 +36,7 @@ vi:files_hint: PDF, CSV hoặc XLSX. Tối đa %{max_size}MB mỗi tệp.files_label: Tệp sao kêinbox_upload: Tải lên+ period_hint: "Sure đọc kỳ sao kê từ tệp PDF nếu tệp có ghi kỳ, hoặc từ ngày trong tên tệp (ví dụ 2026-04). Bạn cũng có thể đặt kỳ trên sao kê."index:account_label: Tài khoảnconfidence: "Khớp %{confidence}"diff --git a/config/locales/views/account_statements/zh-CN.yml b/config/locales/views/account_statements/zh-CN.ymlindex 96001b4939..7e974040d1 100644--- a/config/locales/views/account_statements/zh-CN.yml+++ b/config/locales/views/account_statements/zh-CN.yml@@ -36,6 +36,7 @@ zh-CN:files_hint: PDF、CSV 或 XLSX。每个文件最大 %{max_size}MB。files_label: 对账单文件inbox_upload: 上传+ period_hint: "如果 PDF 中写明了账单周期,Sure 会直接读取,否则从文件名中的日期(例如 2026-04)读取。你也可以在账单上手动设置。"index:account_label: 账户confidence: "%{confidence} 匹配"diff --git a/config/locales/views/account_statements/zh-TW.yml b/config/locales/views/account_statements/zh-TW.ymlindex 951b3cfed8..487ff99d48 100644--- a/config/locales/views/account_statements/zh-TW.yml+++ b/config/locales/views/account_statements/zh-TW.yml@@ -36,6 +36,7 @@ zh-TW:files_hint: PDF、CSV 或 XLSX,每個檔案最大 %{max_size}MB。files_label: 對帳單檔案inbox_upload: 上傳+ period_hint: "如果 PDF 中載明對帳單期間,Sure 會直接讀取,否則從檔名中的日期(例如 2026-04)讀取。你也可以在對帳單上手動設定。"index:account_label: 帳戶confidence: '%{confidence} 相符度'diff --git a/docs/onboarding/guide.md b/docs/onboarding/guide.mdindex 107c137b96..7a6d2a3700 100644--- a/docs/onboarding/guide.md+++ b/docs/onboarding/guide.md@@ -156,6 +156,18 @@ You will now see the transaction you added in your **transaction history**, as w<img width="566" height="587" alt="Filled-out expense form" src="assets/guide-expense-form.png" />+### Uploading statements++You can keep your bank's statements next to an account and let Sure check its balances against them. Open an account and upload the PDF, CSV or XLSX files in **Statements**, or use **Settings → Statement Vault** to upload first and link later.++Sure needs each statement's **period** to show which months are covered and to compare balances. It finds the period in this order:++1. **Inside the PDF**, when the statement states its period: as a date range, e.g. `01 Apr 2026 - 30 Apr 2026` or `01.04.2026 – 30.04.2026`, or as the dates of its opening and closing balance, e.g. "Saldo iniziale al 01.07.2025" and "Saldo finale al 30.09.2025". Sure also reads the opening and closing balance when the statement shows them in a balance summary or next to labels such as "Opening balance" and "Closing balance". Month names and labels are recognised in English, Italian, German, French, Spanish, Dutch and Portuguese. A file name without a date, like Trade Republic's `Account statement.pdf`, then doesn't matter.+2. **Dates in the filename**, for everything else, e.g. `2026-04`, `2026-04-30` or `Apr 2026`.+3. **Manually**: open the statement and enter the period and balances yourself.++If your bank names every file the same way, add the month to the filename before uploading, e.g. `Statement 2026-04.pdf`.+## 8. Managing Investment AccountsIf you're tracking investments in Sure, there are additional features to help you manage your portfolio accurately.diff --git a/test/fixtures/files/account_statements/trade_republic_it_2026_04.pdf b/test/fixtures/files/account_statements/trade_republic_it_2026_04.pdfnew file mode 100644index 0000000000..eb3ea7ba55--- /dev/null+++ b/test/fixtures/files/account_statements/trade_republic_it_2026_04.pdf@@ -0,0 +1,52 @@+%PDF-1.4+%����+1 0 obj+<< /Type /Catalog /Pages 2 0 R >>+endobj+2 0 obj+<< /Type /Pages /Kids [3 0 R] /Count 1 >>+endobj+3 0 obj+<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>+endobj+4 0 obj+<< /Length 817 >>+stream+BT /F1 9 Tf+1 0 0 1 50 800 Tm (TRADE REPUBLIC BANK GMBH, BRANCH ITALY) Tj+1 0 0 1 50 760 Tm (MARIO ROSSI) Tj+1 0 0 1 350 760 Tm (DATA 01 apr 2026 - 30 apr 2026) Tj+1 0 0 1 350 745 Tm (IBAN IT00X0000000000000000001234) Tj+1 0 0 1 350 730 Tm (BIC TRBKITMMXXX) Tj+1 0 0 1 50 690 Tm (ESTRATTO CONTO RIASSUNTIVO) Tj+1 0 0 1 50 670 Tm (PRODOTTO) Tj+1 0 0 1 150 670 Tm (SALDO INIZIALE) Tj+1 0 0 1 260 670 Tm (IN ENTRATA) Tj+1 0 0 1 360 670 Tm (IN USCITA) Tj+1 0 0 1 460 670 Tm (SALDO FINALE) Tj+1 0 0 1 50 650 Tm (Conto corrente) Tj+1 0 0 1 150 650 Tm (1.101,14 �) Tj+1 0 0 1 260 650 Tm (14.514,42 �) Tj+1 0 0 1 360 650 Tm (3.666,97 �) Tj+1 0 0 1 460 650 Tm (11.948,59 �) Tj+1 0 0 1 50 610 Tm (TRANSAZIONI SUL CONTO) Tj+1 0 0 1 50 590 Tm (01 apr 2026 Interessi Your interest payment 10,00 � 1.111,14 �) Tj+ET+endstream+endobj+5 0 obj+<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>+endobj+xref+0 6+0000000000 65535 f+0000000015 00000 n+0000000064 00000 n+0000000121 00000 n+0000000247 00000 n+0000001114 00000 n+trailer+<< /Size 6 /Root 1 0 R >>+startxref+1211+%%EOFdiff --git a/test/models/account_statement/text_metadata_parser_test.rb b/test/models/account_statement/text_metadata_parser_test.rbnew file mode 100644index 0000000000..a41ecc3e3b--- /dev/null+++ b/test/models/account_statement/text_metadata_parser_test.rb@@ -0,0 +1,252 @@+require "test_helper"++class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase+ # A Trade Republic statement, in the text order of a layout-preserving extractor.+ LAYOUT_TEXT = <<~TEXT+ TRADE REPUBLIC BANK GMBH, BRANCH ITALY+ MARIO ROSSI DATA 01 gen 2025 - 31 dic 2025+ IBAN IT00X0000000000000000001234+ ESTRATTO CONTO RIASSUNTIVO+ PRODOTTO SALDO INIZIALE IN ENTRATA IN USCITA SALDO FINALE+ Conto corrente 821,00 € 62.190,10 € 61.066,52 € 1.944,58 €+ TRANSAZIONI SUL CONTO+ 01 gen 2025 Interessi Your interest payment 0,26 € 821,26 €+ TEXT++ # Same statement with every cell on its own line, as a plain extractor emits it.+ STACKED_TEXT = <<~TEXT+ TRADE REPUBLIC BANK GMBH, BRANCH ITALY+ 01 apr 2026 - 30 apr 2026+ DATA+ IBAN IT00X0000000000000000001234+ ESTRATTO CONTO RIASSUNTIVO+ PRODOTTO+ SALDO INIZIALE+ IN ENTRATA+ IN USCITA+ SALDO FINALE+ Conto corrente+ 1.101,14 €+ 14.514,42 €+ 3.666,97 €+ 11.948,59 €+ TEXT++ # A statement with the balances next to their labels and numeric dates.+ GERMAN_TEXT = <<~TEXT+ Kontoauszug Nr. 4+ Zeitraum: 01.04.2026 - 30.04.2026+ IBAN DE89 3704 0044 0532 0130 00 BIC COBADEFFXXX+ Alter Kontostand vom 31.03.2026 1.234,56 EUR+ 02.04.2026 Miete -800,00 EUR+ 15.04.2026 Gehalt 1.565,44 EUR+ Neuer Kontostand vom 30.04.2026 2.000,00 EUR+ TEXT++ test "reads period, balances and IBAN from a summary table" do+ result = AccountStatement::TextMetadataParser.parse(LAYOUT_TEXT)++ assert_equal Date.new(2025, 1, 1), result.period_start_on+ assert_equal Date.new(2025, 12, 31), result.period_end_on+ assert_equal BigDecimal("821.00"), result.opening_balance+ assert_equal BigDecimal("1944.58"), result.closing_balance+ assert_equal "EUR", result.currency+ assert_equal "1234", result.iban_last4+ assert_equal "summary_table", result.balances_source+ end++ test "reads a summary table whose cells are on separate lines" do+ result = AccountStatement::TextMetadataParser.parse(STACKED_TEXT)++ assert_equal Date.new(2026, 4, 1), result.period_start_on+ assert_equal Date.new(2026, 4, 30), result.period_end_on+ assert_equal BigDecimal("1101.14"), result.opening_balance+ assert_equal BigDecimal("11948.59"), result.closing_balance+ end++ test "reads labelled balances, numeric dates and a grouped IBAN" do+ result = AccountStatement::TextMetadataParser.parse(GERMAN_TEXT)++ assert_equal Date.new(2026, 4, 1), result.period_start_on+ assert_equal Date.new(2026, 4, 30), result.period_end_on+ assert_equal BigDecimal("1234.56"), result.opening_balance+ assert_equal BigDecimal("2000.00"), result.closing_balance+ assert_equal "EUR", result.currency+ assert_equal "3000", result.iban_last4+ assert_equal "labels", result.balances_source+ end++ test "takes the period from the balance labels over a promotion's date range" do+ # Shaped like an isybank statement: no period range, the closing amount on+ # the line after its label, a column of stray digits, "Saldo.iniziale" as+ # some extractors emit it, and a promotion with its own date range.+ text = <<~TEXT+ ESTRATTO CONTO N. 002/2026+ AL 30.06.2026+ Riepilogo conto+ Saldo.iniziale al 01.04.2026 +1.250,00 €+ Totale accrediti +2.400,00 €+ Totale addebiti -1.975,40 €+ Saldo del periodo +424,60 €+ 4+ - Saldo finale al 30.06.2026+ 0 +1.674,60 €+ 2 Avvisi importanti+ Prelievi gratuiti dal 3 luglio 2026 al 30 giugno 2027+ TEXT++ result = AccountStatement::TextMetadataParser.parse(text)++ assert_equal Date.new(2026, 4, 1), result.period_start_on+ assert_equal Date.new(2026, 6, 30), result.period_end_on+ assert_equal BigDecimal("1250.00"), result.opening_balance+ assert_equal BigDecimal("1674.60"), result.closing_balance+ assert_equal "EUR", result.currency+ assert_equal "labels", result.balances_source+ end++ test "starts the period after an opening balance dated at a month end" do+ text = "Alter Kontostand vom 31.03.2026 1.234,56 EUR\nNeuer Kontostand vom 30.04.2026 2.000,00 EUR"++ result = AccountStatement::TextMetadataParser.parse(text)++ assert_equal Date.new(2026, 4, 1), result.period_start_on+ assert_equal Date.new(2026, 4, 30), result.period_end_on+ end++ test "reads month-first dates and pounds" do+ text = "Statement period 1 April 2026 to 30 April 2026\nBalance brought forward £1,234.56\n" \+ "Payments in £500.00\nClosing balance £1,734.56"++ result = AccountStatement::TextMetadataParser.parse(text)++ assert_equal Date.new(2026, 4, 1), result.period_start_on+ assert_equal BigDecimal("1734.56"), result.closing_balance+ assert_equal "GBP", result.currency++ us = AccountStatement::TextMetadataParser.parse("Statement Period: April 1, 2026 through April 30, 2026")+ assert_equal Date.new(2026, 4, 1), us.period_start_on+ assert_equal Date.new(2026, 4, 30), us.period_end_on++ iso = AccountStatement::TextMetadataParser.parse("Period 2026-04-01 to 2026-04-30")+ assert_equal Date.new(2026, 4, 30), iso.period_end_on+ end++ test "reads a dollar amount only in the statement's dollar currency" do+ text = "Statement Period: April 1, 2026 through April 30, 2026\nBeginning Balance $2,500.00\nEnding Balance $3,100.25"++ usd = AccountStatement::TextMetadataParser.parse(text, currency: "USD")+ assert_equal BigDecimal("2500.00"), usd.opening_balance+ assert_equal "USD", usd.currency++ assert_nil AccountStatement::TextMetadataParser.parse(text, currency: "EUR").currency+ end++ test "reads a period without balances from an ordinal-date statement" do+ text = <<~TEXT+ MPESA FULL STATEMENT+ Date of Statement: 13th 10 2025+ Statement Period: 01st 1 2025 - 01st 7 2025+ SUMMARY+ TRANSACTION TYPE PAID IN PAID OUT+ TOTAL: 127,000.00 122,757.00+ TEXT++ result = AccountStatement::TextMetadataParser.parse(text)++ assert_equal Date.new(2025, 1, 1), result.period_start_on+ assert_equal Date.new(2025, 7, 1), result.period_end_on+ assert_nil result.opening_balance+ assert_nil result.closing_balance+ assert_nil result.balances_source+ end++ test "understands German and English month names and amount formats" do+ german = "DATUM 01 März 2026 - 31 März 2026\nANFANGSSALDO ZAHLUNGSEINGANG ZAHLUNGSAUSGANG ENDSALDO\n" \+ "Cashkonto 5.440,93 € 0,00 € 4.339,79 € 1.101,14 €"+ english = "DATE 01 Sept 2026 - 30 Sept 2026\nOPENING BALANCE MONEY IN MONEY OUT CLOSING BALANCE\n" \+ "Cash account €4,324.20 €100.00 €2,577.30 €1,846.90"++ german_result = AccountStatement::TextMetadataParser.parse(german)+ assert_equal Date.new(2026, 3, 1), german_result.period_start_on+ assert_equal BigDecimal("1101.14"), german_result.closing_balance++ english_result = AccountStatement::TextMetadataParser.parse(english)+ assert_equal Date.new(2026, 9, 30), english_result.period_end_on+ assert_equal BigDecimal("4324.20"), english_result.opening_balance+ assert_equal BigDecimal("1846.90"), english_result.closing_balance+ end++ test "reads French statements and full month names" do+ french = "DATE 01 juil. 2026 - 31 juil. 2026\nSYNTHÈSE DU RELEVÉ DE COMPTE\n" \+ "PRODUIT SOLDE D'OUVERTURE ENTRÉE D'ARGENT SORTIE D'ARGENT SOLDE DE FERMETURE\n" \+ "Compte courant 7 099,61 € 1 250,00 € 4 025,41 € 4 324,20 €"+ german = "DATUM 01. Oktober 2025 - 31. Dezember 2025\nANFANGSSALDO\n100,00 € 50,00 € 25,00 € 125,00 €"++ french_result = AccountStatement::TextMetadataParser.parse(french)+ assert_equal Date.new(2026, 7, 1), french_result.period_start_on+ assert_equal Date.new(2026, 7, 31), french_result.period_end_on+ assert_equal BigDecimal("7099.61"), french_result.opening_balance+ assert_equal BigDecimal("4324.20"), french_result.closing_balance++ german_result = AccountStatement::TextMetadataParser.parse(german)+ assert_equal Date.new(2025, 10, 1), german_result.period_start_on+ assert_equal Date.new(2025, 12, 31), german_result.period_end_on+ assert_equal BigDecimal("125.00"), german_result.closing_balance+ end++ test "reads Spanish and Dutch long month names" do+ spanish = "FECHA 01 septiembre 2026 - 30 septiembre 2026\nSALDO INICIAL\n10,00 € 5,00 € 1,00 € 14,00 €"+ dutch = "DATUM 01 maart 2026 - 31 maart 2026\nBEGINSALDO\n10,00 € 5,00 € 1,00 € 14,00 €"++ spanish_result = AccountStatement::TextMetadataParser.parse(spanish)+ assert_equal Date.new(2026, 9, 1), spanish_result.period_start_on+ assert_equal Date.new(2026, 9, 30), spanish_result.period_end_on++ dutch_result = AccountStatement::TextMetadataParser.parse(dutch)+ assert_equal Date.new(2026, 3, 1), dutch_result.period_start_on+ assert_equal Date.new(2026, 3, 31), dutch_result.period_end_on+ assert_equal BigDecimal("14.00"), dutch_result.closing_balance+ end++ test "keeps the sign of negative balances in either currency position" do+ prefix = "DATE 01 Aug 2026 - 31 Aug 2026\nOPENING BALANCE MONEY IN MONEY OUT CLOSING BALANCE\n" \+ "Cash account -€12.34 €100.00 €50.00 €37.66"+ inner = prefix.sub("-€12.34", "€-12.34")+ suffix = "DATA 01 ago 2026 - 31 ago 2026\nSALDO INIZIALE\n10,00 € 0,00 € 22,34 € -12,34 €"++ [ prefix, inner ].each do |text|+ result = AccountStatement::TextMetadataParser.parse(text)+ assert_equal BigDecimal("-12.34"), result.opening_balance+ assert_equal BigDecimal("37.66"), result.closing_balance+ end++ assert_equal BigDecimal("-12.34"), AccountStatement::TextMetadataParser.parse(suffix).closing_balance+ end++ test "drops balances that do not add up" do+ text = LAYOUT_TEXT.sub("1.944,58 €", "1.999,99 €")++ result = AccountStatement::TextMetadataParser.parse(text)++ assert_equal Date.new(2025, 1, 1), result.period_start_on+ assert_nil result.opening_balance+ assert_nil result.closing_balance+ assert_nil result.currency+ end++ test "drops labelled balances in different currencies" do+ text = GERMAN_TEXT.sub("2.000,00 EUR", "2.000,00 USD")++ result = AccountStatement::TextMetadataParser.parse(text)++ assert_equal Date.new(2026, 4, 1), result.period_start_on+ assert_nil result.opening_balance+ assert_nil result.closing_balance+ end++ test "ignores text without a period or balances" do+ assert_nil AccountStatement::TextMetadataParser.parse("Invoice 2026-04 total 1.234,56 EUR due 15.05.2026")+ assert_nil AccountStatement::TextMetadataParser.parse("")+ end+enddiff --git a/test/models/account_statement_test.rb b/test/models/account_statement_test.rbindex 08438332e9..0307dc090b 100644--- a/test/models/account_statement_test.rb+++ b/test/models/account_statement_test.rb@@ -430,7 +430,7 @@ class AccountStatementTest < ActiveSupport::TestCaseassert_equal 0.1.to_d, statement.parser_confidenceend- test "stores an actual pdf document fixture as a statement" do+ test "stores another bank's pdf statement and reads its period from the text" dofixture_path = file_fixture("imports/sample_bank_statement.pdf")statement = AccountStatement.create_from_upload!(family: @family,@@ -448,13 +448,113 @@ class AccountStatementTest < ActiveSupport::TestCaseassert_equal "application/pdf", statement.content_typeassert_equal fixture_path.size, statement.byte_sizeassert_equal Digest::SHA256.file(fixture_path).hexdigest, statement.content_sha256- assert_equal "filename_only", statement.sanitized_parser_output["pdf_detection"]- assert_equal [ "filename" ], statement.sanitized_parser_output["metadata_sources"]- assert_equal Date.new(2024, 1, 1), statement.period_start_on- assert_equal Date.new(2024, 1, 31), statement.period_end_on+ # An M-PESA statement: "Statement Period: 01st 1 2025 - 01st 7 2025" wins+ # over the filename date, and it has no opening or closing balance.+ assert_equal "text", statement.sanitized_parser_output["pdf_detection"]+ assert_equal Date.new(2025, 1, 1), statement.period_start_on+ assert_equal Date.new(2025, 7, 1), statement.period_end_on+ assert_nil statement.opening_balance+ assert_nil statement.closing_balance+ assert_equal false, statement.sanitized_parser_output.dig("pdf", "balances_detected")assert statement.original_file.blob.download.start_with?("%PDF-")end+ test "reads period and balances from a Trade Republic statement pdf over a filename date" do+ eur_account = @family.accounts.create!(+ name: "Trade Republic Cash",+ balance: 0,+ currency: "EUR",+ accountable: Depository.new+ )+ fixture_path = file_fixture("account_statements/trade_republic_it_2026_04.pdf")++ statement = AccountStatement.create_from_upload!(+ family: @family,+ account: eur_account,+ file: Rack::Test::UploadedFile.new(+ fixture_path,+ "application/pdf",+ true,+ original_filename: "Trade Republic 2026-03.pdf"+ )+ )++ assert_equal Date.new(2026, 4, 1), statement.period_start_on+ assert_equal Date.new(2026, 4, 30), statement.period_end_on+ assert_equal BigDecimal("1101.14"), statement.opening_balance+ assert_equal BigDecimal("11948.59"), statement.closing_balance+ assert_equal "1234", statement.account_last4_hint+ assert_equal "Trade Republic", statement.institution_name_hint+ assert_equal "text", statement.sanitized_parser_output["pdf_detection"]+ assert_equal "summary_table", statement.sanitized_parser_output.dig("pdf", "balances_source")+ assert_equal [ "pdf_text", "filename" ], statement.sanitized_parser_output["metadata_sources"]+ assert_equal 0.85.to_d, statement.parser_confidence+ assert_not_includes statement.sanitized_parser_output.to_json, "MARIO ROSSI"+ end++ test "reads a Trade Republic statement saved under its default filename" do+ eur_account = @family.accounts.create!(+ name: "Trade Republic Cash",+ balance: 0,+ currency: "EUR",+ accountable: Depository.new+ )++ statement = AccountStatement.create_from_upload!(+ family: @family,+ account: eur_account,+ file: Rack::Test::UploadedFile.new(+ file_fixture("account_statements/trade_republic_it_2026_04.pdf"),+ "application/pdf",+ true,+ original_filename: "Account statement.pdf"+ )+ )++ assert_equal Date.new(2026, 4, 1), statement.period_start_on+ assert_equal Date.new(2026, 4, 30), statement.period_end_on+ assert_equal BigDecimal("11948.59"), statement.closing_balance+ assert_nil statement.institution_name_hint+ assert_nil statement.account_name_hint+ assert_equal [ "pdf_text" ], statement.sanitized_parser_output["metadata_sources"]+ end++ test "skips Trade Republic balances when the statement currency differs" do+ statement = AccountStatement.create_from_upload!(+ family: @family,+ account: nil,+ file: Rack::Test::UploadedFile.new(+ file_fixture("account_statements/trade_republic_it_2026_04.pdf"),+ "application/pdf",+ true,+ original_filename: "statement.pdf"+ )+ )++ assert_equal "USD", statement.currency+ assert_equal Date.new(2026, 4, 1), statement.period_start_on+ assert_equal Date.new(2026, 4, 30), statement.period_end_on+ assert_nil statement.opening_balance+ assert_nil statement.closing_balance+ assert_equal false, statement.sanitized_parser_output.dig("pdf", "balances_detected")+ assert_nil statement.sanitized_parser_output.dig("pdf", "balances_source")+ end++ test "does not read a bare MM-YYYY token in the filename as the period" do+ statement = AccountStatement.create_from_upload!(+ family: @family,+ account: nil,+ file: uploaded_file(+ filename: "Invoice_04-2029.pdf",+ content_type: "application/pdf",+ content: "%PDF-1.4 statement"+ )+ )++ assert_nil statement.period_start_on+ assert_nil statement.period_end_on+ end+test "handles malformed csv metadata detection without raw parser output" dostatement = AccountStatement.create_from_upload!(family: @family,diff --git a/test/models/pdf/text_extractor_test.rb b/test/models/pdf/text_extractor_test.rbnew file mode 100644index 0000000000..6532f7677f--- /dev/null+++ b/test/models/pdf/text_extractor_test.rb@@ -0,0 +1,24 @@+require "test_helper"++class Pdf::TextExtractorTest < ActiveSupport::TestCase+ setup do+ @content = file_fixture("account_statements/trade_republic_it_2026_04.pdf").binread+ end++ test "returns the text of each page" do+ pages = Pdf::TextExtractor.pages(@content)++ assert pages.any?+ assert_match(/Trade Republic/i, pages.join("\n"))+ end++ test "stops after max_pages" do+ PDF::Reader.any_instance.stubs(:pages).returns(%w[one two three].map { |text| stub(text: text) })++ assert_equal %w[one two], Pdf::TextExtractor.pages(@content, max_pages: 2)+ end++ test "raises for content that is not a PDF" do+ assert_raises(PDF::Reader::MalformedPDFError) { Pdf::TextExtractor.pages("not a pdf") }+ end+end