Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Read CR and DR balance markers on statement uploads (#5451)

jaysbeekaye1eeb7f6d04f
diff --git a/app/models/account_statement.rb b/app/models/account_statement.rb
index 4c17fa1389..decb6d8617 100644
--- a/app/models/account_statement.rb
+++ b/app/models/account_statement.rb
@@ -19,6 +19,7 @@ class AccountStatement < ApplicationRecord
PreparedUpload = Data.define(:content, :filename, :content_type, :byte_size, :checksum, :content_sha256)
+ BALANCE_FIELDS = %w[opening_balance closing_balance].freeze
MAX_FILE_SIZE = 25.megabytes
READ_CHUNK_SIZE = 1.megabyte
ALLOWED_EXTENSION_CONTENT_TYPES = {
@@ -45,6 +46,8 @@ class AccountStatement < ApplicationRecord
before_validation :sync_file_metadata, if: -> { original_file.attached? }
before_validation :normalize_currency
before_validation :sync_review_status
+ before_validation :note_edited_balances
+ before_validation :derive_detected_balances, if: -> { new_record? || will_save_change_to_account_id? || will_save_change_to_currency? }
validates :filename, :content_type, :checksum, presence: true
validates :byte_size, presence: true, numericality: { greater_than: 0, less_than_or_equal_to: MAX_FILE_SIZE }
@@ -367,6 +370,16 @@ class AccountStatement < ApplicationRecord
pdf_imports.where.not(status: :failed).order(created_at: :desc).first
end
+ # Whether `amount` is the figure the statement text already gave for this
+ # balance, whatever its sign: the detected value, signed for the account,
+ # then stands.
+ def detected_balance?(field, amount)
+ field = field.to_s
+ return false if pdf_output["balance_readings"].blank? || edited_balances.include?(field)
+
+ self[field].present? && amount.present? && self[field].to_d.abs == amount.to_d.abs
+ end
+
private
def reconciliation_check(key:, statement_amount:, ledger_amount:)
@@ -398,6 +411,51 @@ class AccountStatement < ApplicationRecord
self.currency = currency.to_s.upcase.presence if currency.present?
end
+ def pdf_output
+ sanitized_parser_output.to_h["pdf"].to_h
+ end
+
+ def edited_balances
+ Array(pdf_output["edited_balances"])
+ end
+
+ def merge_pdf_output(values)
+ self.sanitized_parser_output = sanitized_parser_output.to_h.merge("pdf" => pdf_output.merge(values))
+ end
+
+ # A balance written by anyone but derive_detected_balances (the form, the
+ # AI extraction) is theirs from then on and is never worked out again.
+ # What the derivation wrote is remembered, so a save that fails
+ # validation and is retried does not count it as an edit.
+ def note_edited_balances
+ return if pdf_output["balance_readings"].blank?
+
+ edited = BALANCE_FIELDS.select do |field|
+ will_save_change_to_attribute?(field) && !(@derived_balances&.key?(field) && @derived_balances[field] == self[field])
+ end
+ merge_pdf_output("edited_balances" => (edited_balances | edited)) if edited.any?
+ end
+
+ # The detected balances follow the account and the currency: their CR/DR
+ # sign and whether the summary table adds up come from the account's
+ # classification, and "$" is read in the statement's currency. So they are
+ # worked out from the stored readings on upload and on every link, unlink,
+ # relink and currency change. An edited balance is left as it is.
+ def derive_detected_balances
+ readings = pdf_output["balance_readings"]
+ return if readings.blank?
+
+ balances = TextMetadataParser.balances_for(readings, classification: account&.classification, currency: statement_currency)
+ @derived_balances = (BALANCE_FIELDS - edited_balances).to_h do |field|
+ self[field] = balances&.public_send(field)
+ [ field, self[field] ]
+ end
+ merge_pdf_output(
+ "balances_source" => balances&.source,
+ "balances_detected" => opening_balance.present? && closing_balance.present?
+ )
+ end
+
def sync_review_status
return if rejected?
diff --git a/app/models/account_statement/metadata_detector.rb b/app/models/account_statement/metadata_detector.rb
index 6b1234818f..4735c560b2 100644
--- a/app/models/account_statement/metadata_detector.rb
+++ b/app/models/account_statement/metadata_detector.rb
@@ -132,27 +132,20 @@ class AccountStatement::MetadataDetector
end
def detect_from_pdf(output)
- summary = AccountStatement::TextMetadataParser.parse(pdf_text, currency: statement.currency)
+ summary = AccountStatement::TextMetadataParser.parse(pdf_text)
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
-
+ # The balances themselves are worked out from these readings by
+ # AccountStatement when it is saved, and again whenever its account or
+ # currency changes, because their sign, source and currency depend on
+ # both.
output["pdf_detection"] = "text"
- output["pdf"] = {
- "balances_source" => (summary.balances_source if balances_kept),
- "balances_detected" => statement.opening_balance.present? && statement.closing_balance.present?
- }
+ output["pdf"] = { "balances_source" => nil, "balances_detected" => false }
+ output["pdf"]["balance_readings"] = summary.balance_readings if summary.balance_readings.present?
true
end
diff --git a/app/models/account_statement/text_metadata_parser.rb b/app/models/account_statement/text_metadata_parser.rb
index adc6b22885..abe57381da 100644
--- a/app/models/account_statement/text_metadata_parser.rb
+++ b/app/models/account_statement/text_metadata_parser.rb
@@ -11,15 +11,22 @@
# 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.
+# - An opening or closing balance may carry a CR or DR marker ("$435.88 CR").
+#
+# Both candidates are returned as printed, in `balance_readings`: amount,
+# marker and currency token of each balance, and the kinds of account the
+# summary table adds up as. .balances_for turns them into the balances for an
+# account and a statement 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
+ :period_start_on, :period_end_on, :iban_last4, :balance_readings
)
+ Balances = Data.define(:opening_balance, :closing_balance, :currency, :source)
+ CLASSIFICATIONS = %w[asset liability].freeze
# Month tokens are matched in full, then on their first four and three
# letters, which covers abbreviations ("Sept.", "févr.") and full names.
@@ -84,42 +91,91 @@ class AccountStatement::TextMetadataParser
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}))?/
- )
+ # Either form may be followed, directly or after one space, by a CR or DR
+ # marker: "$435.88 CR", "435.88Cr".
+ 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}))?/
+ )})
+ (?:\p{Blank}?(?<side>(?i:cr|dr))\b)?
+ /x
+ SIDES = { "cr" => :credit, "dr" => :debit }.freeze
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)
+ # value carries only a "-" sign; currency is the token as printed ("$",
+ # "EUR"); side is the CR/DR marker, if any.
+ Amount = Data.define(:value, :currency, :side)
+ BALANCE_FIELDS = %w[opening_balance closing_balance].freeze
- # 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
+ def self.parse(text)
+ new(text).parse
end
- def initialize(text, currency: nil)
+ # The balances `readings` give for an account of `classification` ("asset",
+ # "liability", or nil when there is none) and a statement in `currency`:
+ # the summary table when it adds up for that account (for either, with
+ # none), otherwise the labelled balances, whichever first has both balances
+ # in `currency`. A marked balance is its absolute value, negative for CR on
+ # a liability or DR on an asset, unsigned with no account.
+ def self.balances_for(readings, classification:, currency:)
+ readings = readings.to_h
+ table = readings["summary_table"]
+ candidates = []
+ candidates << [ "summary_table", table ] if table && (classification.nil? || Array(table["adds_up_as"]).include?(classification))
+ candidates << [ "labels", readings["labels"] ] if readings["labels"]
+
+ candidates.each do |source, pair|
+ currencies = BALANCE_FIELDS.map { |field| resolve_currency(pair.dig(field, "currency"), currency) }
+ next unless currencies.uniq.size == 1 && currencies.first.present?
+ next if currency.present? && currencies.first != currency.to_s.upcase
+
+ opening, closing = BALANCE_FIELDS.map do |field|
+ signed_amount(BigDecimal(pair.dig(field, "amount")), pair.dig(field, "side")&.to_sym, classification)
+ end
+ return Balances.new(opening_balance: opening, closing_balance: closing, currency: currencies.first, source: source)
+ end
+ nil
+ end
+
+ # "$" is read as the statement's currency when that is a dollar currency.
+ def self.resolve_currency(token, statement_currency)
+ return nil if token.blank?
+ return CURRENCY_SYMBOLS[token] if CURRENCY_SYMBOLS.key?(token)
+ if token == "$"
+ return Money::Currency.new(statement_currency).symbol == "$" ? statement_currency.to_s.upcase : nil
+ end
+
+ Money::Currency.new(token).iso_code
+ rescue Money::Currency::UnknownCurrencyError, ArgumentError
+ nil
+ end
+
+ def self.signed_amount(value, side, classification)
+ return value unless SIDES.value?(side)
+
+ negative = (side == :credit && classification == "liability") || (side == :debit && classification == "asset")
+ negative ? -value.abs : value.abs
+ end
+
+ def initialize(text)
@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?
+ readings = balance_readings
+ return nil if period.nil? && readings.empty?
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
+ balance_readings: readings
)
end
@@ -191,14 +247,20 @@ class AccountStatement::TextMetadataParser
MONTHS[token] || MONTHS[token[0, 4]] || MONTHS[token[0, 3]]
end
- def parse_balances
- summary = parse_summary_table
- return [ summary, "summary_table" ] if summary
-
+ def balance_readings
+ table, adds_up_as = parse_summary_table
labelled = parse_labelled_balances
- return [ labelled, "labels" ] if labelled
- nil
+ readings = {}
+ readings["summary_table"] = reading(table).merge("adds_up_as" => adds_up_as) if table
+ readings["labels"] = reading(labelled) if labelled
+ readings
+ end
+
+ def reading(pair)
+ BALANCE_FIELDS.zip(pair).to_h do |field, amount|
+ [ field, { "amount" => amount.value.to_s("F"), "side" => amount.side&.to_s, "currency" => amount.currency } ]
+ end
end
def parse_summary_table
@@ -208,10 +270,17 @@ class AccountStatement::TextMetadataParser
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
+ adds_up_as = CLASSIFICATIONS.select { |classification| adds_up?(amounts, classification) }
+ [ [ amounts.first, amounts.last ], adds_up_as ] if adds_up_as.any?
+ end
- same_currency(opening, closing)
+ # Only the balances take their sign from a marker; the money in and out
+ # columns are totals and are read as printed.
+ def adds_up?(amounts, classification)
+ opening, money_in, money_out, closing = amounts
+ opening = self.class.signed_amount(opening.value, opening.side, classification)
+ closing = self.class.signed_amount(closing.value, closing.side, classification)
+ (opening + money_in.value - money_out.value - closing).abs <= TOLERANCE
end
def parse_labelled_balances
@@ -219,7 +288,7 @@ class AccountStatement::TextMetadataParser
closing = amount_after_label(CLOSING_PATTERN)
return nil unless opening && closing
- same_currency(opening, closing)
+ [ opening, closing ]
end
# The first amount after the label on its line, or on the next non-blank
@@ -243,12 +312,6 @@ class AccountStatement::TextMetadataParser
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
@@ -256,7 +319,11 @@ class AccountStatement::TextMetadataParser
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]))
+ Amount.new(
+ value: negative ? -value : value,
+ currency: match[:prefix_currency] || match[:suffix_currency],
+ side: SIDES[match[:side]&.downcase]
+ )
end
end
@@ -272,22 +339,6 @@ class AccountStatement::TextMetadataParser
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
diff --git a/app/models/pdf_import.rb b/app/models/pdf_import.rb
index 804e946e73..d3b1c87fff 100644
--- a/app/models/pdf_import.rb
+++ b/app/models/pdf_import.rb
@@ -612,13 +612,14 @@ class PdfImport < Import
end
# Only sync balances when currency is compatible with the statement's currency,
- # matching AccountStatement::MetadataDetector#detect_from_pdf behavior.
+ # as AccountStatement does for the balances it reads from the statement text.
target_currency = updates[:currency] || account_statement.statement_currency
currency_compatible = currency.blank? || target_currency.blank? || currency.to_s.casecmp?(target_currency)
if currency_compatible
- updates[:opening_balance] = opening_balance if opening_balance.present?
- updates[:closing_balance] = closing_balance if closing_balance.present?
+ # The statement text's own figure keeps its account-derived sign.
+ updates[:opening_balance] = opening_balance if opening_balance.present? && !account_statement.detected_balance?(:opening_balance, opening_balance)
+ updates[:closing_balance] = closing_balance if closing_balance.present? && !account_statement.detected_balance?(:closing_balance, closing_balance)
else
DebugLogEntry.capture(
category: "import",
diff --git a/test/models/account_statement/text_metadata_parser_test.rb b/test/models/account_statement/text_metadata_parser_test.rb
index a41ecc3e3b..b9fb30007b 100644
--- a/test/models/account_statement/text_metadata_parser_test.rb
+++ b/test/models/account_statement/text_metadata_parser_test.rb
@@ -1,6 +1,10 @@
require "test_helper"
class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
+ def balances(result, currency: "EUR", classification: nil)
+ AccountStatement::TextMetadataParser.balances_for(result.balance_readings, classification: classification, currency: currency)
+ end
+
# A Trade Republic statement, in the text order of a layout-preserving extractor.
LAYOUT_TEXT = <<~TEXT
TRADE REPUBLIC BANK GMBH, BRANCH ITALY
@@ -48,11 +52,11 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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 BigDecimal("821.00"), balances(result).opening_balance
+ assert_equal BigDecimal("1944.58"), balances(result).closing_balance
+ assert_equal "EUR", balances(result).currency
assert_equal "1234", result.iban_last4
- assert_equal "summary_table", result.balances_source
+ assert_equal "summary_table", balances(result).source
end
test "reads a summary table whose cells are on separate lines" do
@@ -60,8 +64,8 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_equal BigDecimal("1101.14"), balances(result).opening_balance
+ assert_equal BigDecimal("11948.59"), balances(result).closing_balance
end
test "reads labelled balances, numeric dates and a grouped IBAN" do
@@ -69,11 +73,11 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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 BigDecimal("1234.56"), balances(result).opening_balance
+ assert_equal BigDecimal("2000.00"), balances(result).closing_balance
+ assert_equal "EUR", balances(result).currency
assert_equal "3000", result.iban_last4
- assert_equal "labels", result.balances_source
+ assert_equal "labels", balances(result).source
end
test "takes the period from the balance labels over a promotion's date range" do
@@ -99,10 +103,10 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_equal BigDecimal("1250.00"), balances(result).opening_balance
+ assert_equal BigDecimal("1674.60"), balances(result).closing_balance
+ assert_equal "EUR", balances(result).currency
+ assert_equal "labels", balances(result).source
end
test "starts the period after an opening balance dated at a month end" do
@@ -121,8 +125,8 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_equal BigDecimal("1734.56"), balances(result, currency: "GBP").closing_balance
+ assert_equal "GBP", balances(result, currency: "GBP").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
@@ -135,11 +139,11 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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")
+ usd = balances(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
+ assert_nil balances(AccountStatement::TextMetadataParser.parse(text), currency: "EUR")
end
test "reads a period without balances from an ordinal-date statement" do
@@ -156,9 +160,9 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_nil balances(result)&.opening_balance
+ assert_nil balances(result)&.closing_balance
+ assert_nil balances(result)&.source
end
test "understands German and English month names and amount formats" do
@@ -169,12 +173,12 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_equal BigDecimal("1101.14"), balances(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
+ assert_equal BigDecimal("4324.20"), balances(english_result).opening_balance
+ assert_equal BigDecimal("1846.90"), balances(english_result).closing_balance
end
test "reads French statements and full month names" do
@@ -186,13 +190,13 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_equal BigDecimal("7099.61"), balances(french_result).opening_balance
+ assert_equal BigDecimal("4324.20"), balances(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
+ assert_equal BigDecimal("125.00"), balances(german_result).closing_balance
end
test "reads Spanish and Dutch long month names" do
@@ -206,7 +210,7 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_equal BigDecimal("14.00"), balances(dutch_result).closing_balance
end
test "keeps the sign of negative balances in either currency position" do
@@ -217,11 +221,11 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
[ 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
+ assert_equal BigDecimal("-12.34"), balances(result).opening_balance
+ assert_equal BigDecimal("37.66"), balances(result).closing_balance
end
- assert_equal BigDecimal("-12.34"), AccountStatement::TextMetadataParser.parse(suffix).closing_balance
+ assert_equal BigDecimal("-12.34"), balances(AccountStatement::TextMetadataParser.parse(suffix)).closing_balance
end
test "drops balances that do not add up" do
@@ -230,9 +234,9 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_nil balances(result)&.opening_balance
+ assert_nil balances(result)&.closing_balance
+ assert_nil balances(result)&.currency
end
test "drops labelled balances in different currencies" do
@@ -241,8 +245,156 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
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
+ assert_nil balances(result)&.opening_balance
+ assert_nil balances(result)&.closing_balance
+ end
+
+ # A credit card statement whose closing balance is in credit ("CR").
+ CARD_LABELS_TEXT = <<~TEXT
+ Statement period 12 Apr 2024 - 15 May 2024
+ Opening balance $1,066.47
+ Closing balance $435.88 CR
+ TEXT
+
+ CARD_SUMMARY_TEXT = <<~TEXT
+ Statement period 12 Apr 2024 - 15 May 2024
+ Opening balance Debits Credits Closing balance
+ $1,066.47 $0.00 $1,502.35 $435.88 CR
+ TEXT
+
+ def card_balances(text, classification:, currency: "AUD")
+ balances(AccountStatement::TextMetadataParser.parse(text), currency: currency, classification: classification)
+ end
+
+ test "reads a CR balance on a liability as in credit" do
+ result = card_balances(CARD_LABELS_TEXT, classification: "liability")
+
+ assert_equal BigDecimal("1066.47"), result.opening_balance
+ assert_equal BigDecimal("-435.88"), result.closing_balance
+ assert_equal "labels", result.source
+ end
+
+ test "keeps a summary table whose CR closing balance only adds up as a credit" do
+ result = card_balances(CARD_SUMMARY_TEXT, classification: "liability")
+
+ assert_equal "summary_table", result.source
+ assert_equal BigDecimal("1066.47"), result.opening_balance
+ assert_equal BigDecimal("-435.88"), result.closing_balance
+ end
+
+ test "returns the readings as printed and the kinds of account the table adds up as" do
+ readings = AccountStatement::TextMetadataParser.parse(CARD_SUMMARY_TEXT).balance_readings
+
+ assert_equal(
+ {
+ "opening_balance" => { "amount" => "1066.47", "side" => nil, "currency" => "$" },
+ "closing_balance" => { "amount" => "435.88", "side" => "credit", "currency" => "$" },
+ "adds_up_as" => [ "liability" ]
+ },
+ readings["summary_table"]
+ )
+ end
+
+ test "keeps a CR summary table without an account, unsigned" do
+ result = card_balances(CARD_SUMMARY_TEXT, classification: nil)
+
+ assert_equal "summary_table", result.source
+ assert_equal BigDecimal("435.88"), result.closing_balance
+ end
+
+ test "drops a summary table for an account it does not add up for" do
+ assert_nil card_balances(CARD_SUMMARY_TEXT, classification: "asset")
+ end
+
+ test "reads a dollar sign in the statement's currency" do
+ assert_equal "AUD", card_balances(CARD_LABELS_TEXT, classification: "liability", currency: "AUD").currency
+ assert_equal "USD", card_balances(CARD_LABELS_TEXT, classification: "liability", currency: "USD").currency
+ assert_nil card_balances(CARD_LABELS_TEXT, classification: "liability", currency: "EUR")
+ end
+
+ test "falls back to the labelled balances when the table is in another currency" do
+ text = <<~TEXT
+ Opening balance Debits Credits Closing balance
+ €1,066.47 €0.00 €1,502.35 €435.88 CR
+ Opening balance AUD 1,000.00
+ Closing balance AUD 900.00
+ TEXT
+
+ result = card_balances(text, classification: "liability")
+
+ assert_equal "labels", result.source
+ assert_equal BigDecimal("900.00"), result.closing_balance
+ end
+
+ test "reads a CR opening balance on a liability as in credit" do
+ text = "Opening balance $435.88 CR\nClosing balance $120.00\n"
+
+ result = card_balances(text, classification: "liability")
+
+ assert_equal BigDecimal("-435.88"), result.opening_balance
+ assert_equal BigDecimal("120.00"), result.closing_balance
+ end
+
+ test "leaves unmarked and DR balances on a liability as owed" do
+ assert_equal BigDecimal("435.88"), card_balances(CARD_LABELS_TEXT.sub(" CR", ""), classification: "liability").closing_balance
+ assert_equal BigDecimal("435.88"), card_balances(CARD_LABELS_TEXT.sub(" CR", " DR"), classification: "liability").closing_balance
+ end
+
+ test "reads a DR balance on an asset as overdrawn and a CR one as positive" do
+ assert_equal BigDecimal("-435.88"), card_balances(CARD_LABELS_TEXT.sub(" CR", " DR"), classification: "asset").closing_balance
+ assert_equal BigDecimal("435.88"), card_balances(CARD_LABELS_TEXT, classification: "asset").closing_balance
+ end
+
+ test "lets the marker set the sign of a minus-signed marked balance" do
+ text = CARD_LABELS_TEXT.sub("$435.88 CR", "-$435.88 CR")
+
+ assert_equal BigDecimal("-435.88"), card_balances(text, classification: "liability").closing_balance
+ assert_equal BigDecimal("435.88"), card_balances(text, classification: "asset").closing_balance
+ end
+
+ # Only the balances take a marker's sign: the money in and out columns are
+ # totals, read as printed.
+ test "keeps a depository summary table with CR and DR on its totals" do
+ text = <<~TEXT
+ Opening balance Credits Debits Closing balance
+ $100.00 CR $50.00 CR $20.00 DR $130.00 CR
+ TEXT
+
+ result = card_balances(text, classification: "asset")
+
+ assert_equal "summary_table", result.source
+ assert_equal BigDecimal("100.00"), result.opening_balance
+ assert_equal BigDecimal("130.00"), result.closing_balance
+ end
+
+ test "reads a marker in any case, straight after the amount or after one space" do
+ [ "$435.88CR", "$435.88 Cr", "$435.88 cr" ].each do |printed|
+ result = card_balances(CARD_LABELS_TEXT.sub("$435.88 CR", printed), classification: "liability")
+
+ assert_equal BigDecimal("-435.88"), result.closing_balance, printed
+ end
+ end
+
+ test "does not read CR or DR further along the line as a marker" do
+ text = CARD_LABELS_TEXT.sub("$435.88 CR", "$435.88 Dr Smith")
+
+ assert_equal BigDecimal("-435.88"), card_balances(CARD_LABELS_TEXT.sub(" CR", " DR"), classification: "asset").closing_balance
+ assert_equal BigDecimal("435.88"), card_balances(text, classification: "asset").closing_balance
+ end
+
+ test "drops a table that adds up only when its CR and DR markers are ignored" do
+ text = <<~TEXT
+ Opening balance Debits Credits Closing balance
+ $100.00 CR $50.00 $0.00 $150.00 DR
+ TEXT
+
+ assert_nil AccountStatement::TextMetadataParser.parse(text)
+ end
+
+ test "does not read CR at the start of a word as a marker" do
+ text = CARD_LABELS_TEXT.sub("$435.88 CR", "$435.88 CREDIT LIMIT $5,000.00")
+
+ assert_equal BigDecimal("435.88"), card_balances(text, classification: "liability").closing_balance
end
test "ignores text without a period or balances" do
diff --git a/test/models/account_statement_test.rb b/test/models/account_statement_test.rb
index 25ce1753bc..9f29ac7435 100644
--- a/test/models/account_statement_test.rb
+++ b/test/models/account_statement_test.rb
@@ -581,6 +581,207 @@ class AccountStatementTest < ActiveSupport::TestCase
assert_nil statement.sanitized_parser_output.dig("pdf", "balances_source")
end
+ CARD_STATEMENT_TEXT = <<~TEXT
+ Statement period 12 Apr 2024 - 15 May 2024
+ Opening balance $1,066.47
+ Closing balance $435.88 CR
+ TEXT
+
+ # Adds up only as a liability: 1,066.47 + 0.00 - 1,502.35 = -435.88.
+ CARD_SUMMARY_TEXT = <<~TEXT
+ Statement period 12 Apr 2024 - 15 May 2024
+ Opening balance Debits Credits Closing balance
+ $1,066.47 $0.00 $1,502.35 $435.88 CR
+ TEXT
+
+ test "stores a CR closing balance on a credit card as in credit" do
+ statement = upload_card_statement(account: accounts(:credit_card))
+
+ assert_equal BigDecimal("1066.47"), statement.opening_balance
+ assert_equal BigDecimal("-435.88"), statement.closing_balance
+ assert_equal "labels", statement.sanitized_parser_output.dig("pdf", "balances_source")
+ assert_equal({ "amount" => "435.88", "side" => "credit", "currency" => "$" },
+ statement.sanitized_parser_output.dig("pdf", "balance_readings", "labels", "closing_balance"))
+ end
+
+ test "stores a DR closing balance on a depository account as overdrawn" do
+ statement = upload_card_statement(account: @account, text: CARD_STATEMENT_TEXT.sub(" CR", " DR"))
+
+ assert_equal BigDecimal("-435.88"), statement.closing_balance
+ end
+
+ test "signs an inbox upload's CR balance when it is linked to a credit card" do
+ statement = upload_card_statement(account: nil)
+ assert_equal BigDecimal("435.88"), statement.closing_balance
+
+ statement.link_to_account!(accounts(:credit_card))
+
+ assert_equal BigDecimal("-435.88"), statement.reload.closing_balance
+ assert_equal BigDecimal("1066.47"), statement.opening_balance
+ end
+
+ test "signs a CR balance when the account is set through an edit" do
+ statement = upload_card_statement(account: nil)
+
+ statement.update!(account: accounts(:credit_card))
+
+ assert_equal BigDecimal("-435.88"), statement.reload.closing_balance
+ end
+
+ test "re-signs a CR balance when the statement moves to a depository account" do
+ statement = upload_card_statement(account: accounts(:credit_card))
+
+ statement.unlink!
+ statement.link_to_account!(@account)
+
+ assert_equal BigDecimal("435.88"), statement.reload.closing_balance
+ end
+
+ test "unlinking returns a CR balance to its unsigned inbox value" do
+ statement = upload_card_statement(account: accounts(:credit_card))
+
+ statement.unlink!
+
+ assert_equal BigDecimal("435.88"), statement.reload.closing_balance
+ end
+
+ test "keeps a balance edited by hand before linking" do
+ statement = upload_card_statement(account: nil)
+ statement.update!(closing_balance: 400)
+
+ statement.link_to_account!(accounts(:credit_card))
+
+ assert_equal BigDecimal("400"), statement.reload.closing_balance
+ assert_equal BigDecimal("1066.47"), statement.opening_balance
+ end
+
+ test "keeps a balance typed in the same save that sets the account" do
+ statement = upload_card_statement(account: nil)
+
+ statement.update!(account: @account, closing_balance: -435.88)
+
+ assert_equal BigDecimal("-435.88"), statement.reload.closing_balance
+ end
+
+ test "keeps a deliberately signed balance across relinking" do
+ statement = upload_card_statement(account: accounts(:credit_card))
+ statement.update!(closing_balance: 435.88)
+
+ statement.unlink!
+ statement.link_to_account!(@account)
+ statement.link_to_account!(accounts(:credit_card))
+
+ assert_equal BigDecimal("435.88"), statement.reload.closing_balance
+ end
+
+ test "keeps a CR summary table on a credit card upload" do
+ statement = upload_card_statement(account: accounts(:credit_card), text: CARD_SUMMARY_TEXT)
+
+ assert_equal BigDecimal("-435.88"), statement.closing_balance
+ assert_equal "summary_table", statement.sanitized_parser_output.dig("pdf", "balances_source")
+ end
+
+ test "drops a CR summary table uploaded to a depository account" do
+ statement = upload_card_statement(account: @account, text: CARD_SUMMARY_TEXT)
+
+ assert_nil statement.opening_balance
+ assert_nil statement.closing_balance
+ assert_nil statement.sanitized_parser_output.dig("pdf", "balances_source")
+ assert_equal false, statement.sanitized_parser_output.dig("pdf", "balances_detected")
+ end
+
+ test "drops an inbox summary table when it is linked to an account it does not add up for" do
+ statement = upload_card_statement(account: nil, text: CARD_SUMMARY_TEXT)
+ assert_equal BigDecimal("435.88"), statement.closing_balance
+
+ statement.link_to_account!(@account)
+
+ assert_nil statement.reload.opening_balance
+ assert_nil statement.closing_balance
+ assert_nil statement.sanitized_parser_output.dig("pdf", "balances_source")
+ assert_equal false, statement.sanitized_parser_output.dig("pdf", "balances_detected")
+ end
+
+ test "drops a card upload's summary table when it moves to a depository account" do
+ statement = upload_card_statement(account: accounts(:credit_card), text: CARD_SUMMARY_TEXT)
+
+ statement.unlink!
+ statement.link_to_account!(@account)
+
+ assert_nil statement.reload.opening_balance
+ assert_nil statement.closing_balance
+ end
+
+ test "restores a dropped summary table when relinked to an account it adds up for" do
+ statement = upload_card_statement(account: @account, text: CARD_SUMMARY_TEXT)
+ assert_nil statement.closing_balance
+
+ statement.unlink!
+ statement.link_to_account!(accounts(:credit_card))
+
+ assert_equal BigDecimal("1066.47"), statement.reload.opening_balance
+ assert_equal BigDecimal("-435.88"), statement.closing_balance
+ assert_equal "summary_table", statement.sanitized_parser_output.dig("pdf", "balances_source")
+ assert_equal true, statement.sanitized_parser_output.dig("pdf", "balances_detected")
+ end
+
+ test "keeps an edited balance when the summary table is dropped" do
+ statement = upload_card_statement(account: nil, text: CARD_SUMMARY_TEXT)
+ statement.update!(closing_balance: 400)
+
+ statement.link_to_account!(@account)
+
+ assert_nil statement.reload.opening_balance
+ assert_equal BigDecimal("400"), statement.closing_balance
+ end
+
+ test "unlinking keeps an inbox summary table that adds up only as a card's" do
+ statement = upload_card_statement(account: nil, text: CARD_SUMMARY_TEXT)
+ statement.link_to_account!(accounts(:credit_card))
+
+ statement.unlink!
+
+ assert_equal BigDecimal("1066.47"), statement.reload.opening_balance
+ assert_equal BigDecimal("435.88"), statement.closing_balance
+ end
+
+ test "reads the balances again in the statement's currency when it changes" do
+ @family.update!(currency: "EUR")
+ card = @family.accounts.create!(name: "AUD card", balance: 0, currency: "AUD", accountable: CreditCard.new)
+ statement = upload_card_statement(account: nil)
+ assert_equal "EUR", statement.currency
+ assert_nil statement.closing_balance, "a dollar amount was read as euros"
+
+ statement.link_to_account!(card)
+ statement.update!(currency: "AUD")
+
+ assert_equal BigDecimal("-435.88"), statement.reload.closing_balance
+ assert_equal BigDecimal("1066.47"), statement.opening_balance
+ end
+
+ test "a save that fails validation and is retried does not mark derived balances as edited" do
+ statement = upload_card_statement(account: nil)
+ statement.account = accounts(:credit_card)
+ statement.period_end_on = statement.period_start_on - 1
+ assert_not statement.save
+
+ statement.period_end_on = statement.period_start_on + 30
+ statement.save!
+ statement.unlink!
+
+ assert_empty Array(statement.reload.sanitized_parser_output.dig("pdf", "edited_balances"))
+ assert_equal BigDecimal("435.88"), statement.closing_balance
+ end
+
+ test "leaves statements without balance readings alone when linked" do
+ statement = upload_card_statement(account: nil, text: "nothing to read")
+ statement.update!(closing_balance: 250)
+
+ statement.link_to_account!(accounts(:credit_card))
+
+ assert_equal BigDecimal("250"), statement.reload.closing_balance
+ end
+
test "does not read a bare MM-YYYY token in the filename as the period" do
statement = AccountStatement.create_from_upload!(
family: @family,
@@ -934,6 +1135,15 @@ class AccountStatementTest < ActiveSupport::TestCase
private
+ def upload_card_statement(account:, text: CARD_STATEMENT_TEXT)
+ Pdf::TextExtractor.stubs(:pages).returns([ text ])
+ AccountStatement.create_from_upload!(
+ family: @family,
+ account: account,
+ file: uploaded_file(filename: "card.pdf", content_type: "application/pdf", content: "%PDF-1.4 card statement")
+ )
+ end
+
def create_statement(account:, month:, content:, suggested_account: nil, closing_balance: nil)
statement = AccountStatement.create_from_upload!(
family: @family,
diff --git a/test/models/pdf_import_reconciliation_test.rb b/test/models/pdf_import_reconciliation_test.rb
index 8b3b1f8184..49babb67d2 100644
--- a/test/models/pdf_import_reconciliation_test.rb
+++ b/test/models/pdf_import_reconciliation_test.rb
@@ -176,6 +176,49 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
assert_equal "2007", @statement.account_last4_hint
end
+ test "extract_transactions keeps the detected sign of a CR balance the AI repeats unsigned" do
+ detect_card_statement!(account: accounts(:credit_card))
+ stub_extracted_balances(opening: 1066.47, closing: 435.88)
+
+ @import.extract_transactions
+
+ assert_equal BigDecimal("-435.88"), @statement.reload.closing_balance
+ assert_equal BigDecimal("1066.47"), @statement.opening_balance
+ end
+
+ test "extract_transactions leaves an unlinked CR balance to be signed on linking" do
+ detect_card_statement!(account: nil)
+ stub_extracted_balances(opening: 1066.47, closing: -435.88)
+
+ @import.extract_transactions
+ @statement.reload.link_to_account!(@account)
+
+ assert_equal BigDecimal("435.88"), @statement.reload.closing_balance,
+ "the AI's sign was kept over the CR marker on a depository account"
+ end
+
+ test "extract_transactions writes an AI balance over a hand edit of the same size" do
+ detect_card_statement!(account: accounts(:credit_card))
+ @statement.update!(closing_balance: 400)
+ stub_extracted_balances(opening: 1066.47, closing: -400.0)
+
+ @import.extract_transactions
+
+ assert_equal BigDecimal("-400"), @statement.reload.closing_balance
+ end
+
+ test "extract_transactions keeps a different AI balance through relinking" do
+ detect_card_statement!(account: accounts(:credit_card), text: :summary_table)
+ stub_extracted_balances(opening: 1066.47, closing: 400.0)
+
+ @import.extract_transactions
+ @statement.reload.unlink!
+ @statement.link_to_account!(@account)
+
+ assert_equal BigDecimal("400"), @statement.reload.closing_balance
+ assert_nil @statement.opening_balance, "the detected half of the table was kept"
+ end
+
test "extract_transactions ignores inverted dates while syncing valid balances and hints" do
use_ai_routes
provider = mock("llm_provider")
@@ -625,6 +668,34 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
private
+ # Readings as MetadataDetector stores them for "Closing balance $435.88 CR",
+ # then a link so the statement works its balances out for `account`.
+ def detect_card_statement!(account:, text: :labels)
+ pair = {
+ "opening_balance" => { "amount" => "1066.47", "side" => nil, "currency" => "$" },
+ "closing_balance" => { "amount" => "435.88", "side" => "credit", "currency" => "$" }
+ }
+ readings = text == :summary_table ? { "summary_table" => pair.merge("adds_up_as" => [ "liability" ]) } : { "labels" => pair }
+ @statement.update_columns(
+ account_id: nil, opening_balance: 1066.47, closing_balance: 435.88,
+ sanitized_parser_output: { "pdf" => { "balance_readings" => readings } }
+ )
+ @statement.link_to_account!(account) if account
+ end
+
+ def stub_extracted_balances(opening:, closing:)
+ use_ai_routes
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: { opening_balance: opening, closing_balance: closing, transactions: [] }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+ end
+
def create_statement
AccountStatement.create_from_upload!(
family: @family,