The personal finance app for everyone (by everyone)
Ruby
Keep AI and posted-back statement balances straight (#5549)
jaysbeekayc0432ec06bf5
diff --git a/app/models/account_statement.rb b/app/models/account_statement.rbindex a0ac4acc19..da7cf3f30e 100644--- a/app/models/account_statement.rb+++ b/app/models/account_statement.rb@@ -47,7 +47,7 @@ class AccountStatement < ApplicationRecordbefore_validation :normalize_currencybefore_validation :sync_review_statusbefore_validation :note_edited_balances- before_validation :derive_detected_balances, if: -> { new_record? || will_save_change_to_account_id? || will_save_change_to_currency? }+ before_validation :derive_detected_balancesvalidates :filename, :content_type, :checksum, presence: truevalidates :byte_size, presence: true, numericality: { greater_than: 0, less_than_or_equal_to: MAX_FILE_SIZE }@@ -383,13 +383,31 @@ class AccountStatement < ApplicationRecordend# 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)+ # balance in `currency`, whatever its sign, and the text marked it CR or DR:+ # the detected value, signed for the account, then stands.+ def detected_balance?(field, amount, currency: statement_currency)field = field.to_s- return false if pdf_output["balance_readings"].blank? || edited_balances.include?(field)+ readings = pdf_output["balance_readings"]+ return false if readings.blank? || edited_balances.include?(field)- self[field].present? && amount.present? && self[field].to_d.abs == amount.to_d.abs+ balances = TextMetadataParser.balances_for(readings, classification: account&.classification, currency: currency)+ return false if balances.nil? || readings.dig(balances.source, field, "side").blank?++ detected = balances.public_send(field)+ detected.present? && amount.present? && detected.to_d.abs == amount.to_d.abs+ end++ # Records the assigned balances in `fields` as edited, so they are never+ # worked out again, unless the statement text gives the same figure in the+ # statement's currency. Unlike note_edited_balances, a value equal to an+ # earlier derivation still counts: the currency may have changed since.+ def mark_balances_edited(fields)+ readings = pdf_output["balance_readings"]+ return if readings.blank?++ derived = TextMetadataParser.balances_for(readings, classification: account&.classification, currency: statement_currency)+ edited = fields.map(&:to_s).select { |field| derived&.public_send(field) != self[field] }+ merge_pdf_output("edited_balances" => (edited_balances | edited)) if edited.any?endprivate@@ -437,13 +455,18 @@ class AccountStatement < ApplicationRecord# 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.+ # A value equal to what the derivation wrote, or would write now, is not+ # an edit, so a save that fails validation and is retried, in the same+ # object or through the form, keeps its balances derived.def note_edited_balances- return if pdf_output["balance_readings"].blank?+ readings = pdf_output["balance_readings"]+ return if readings.blank?+ derived = TextMetadataParser.balances_for(readings, classification: account&.classification, currency: statement_currency)edited = BALANCE_FIELDS.select do |field|- will_save_change_to_attribute?(field) && !(@derived_balances&.key?(field) && @derived_balances[field] == self[field])+ will_save_change_to_attribute?(field) &&+ !(@derived_balances&.key?(field) && @derived_balances[field] == self[field]) &&+ derived&.public_send(field) != self[field]endmerge_pdf_output("edited_balances" => (edited_balances | edited)) if edited.any?end@@ -451,8 +474,9 @@ class AccountStatement < ApplicationRecord# 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.+ # worked out from the stored readings on every validation, which leaves an+ # unedited balance as it was unless the account or currency changed. An+ # edited balance is left as it is.def derive_detected_balancesreadings = pdf_output["balance_readings"]return if readings.blank?diff --git a/app/models/account_statement/text_metadata_parser.rb b/app/models/account_statement/text_metadata_parser.rbindex dd0aad803f..960708d289 100644--- a/app/models/account_statement/text_metadata_parser.rb+++ b/app/models/account_statement/text_metadata_parser.rb@@ -135,7 +135,6 @@ class AccountStatement::TextMetadataParser# 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].freezedef self.parse(text)new(text).parse@@ -155,11 +154,11 @@ class AccountStatement::TextMetadataParsercandidates << [ "labels", readings["labels"] ] if readings["labels"]candidates.each do |source, pair|- currencies = BALANCE_FIELDS.map { |field| resolve_currency(pair.dig(field, "currency"), currency) }+ currencies = AccountStatement::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|+ opening, closing = AccountStatement::BALANCE_FIELDS.map do |field|signed_amount(BigDecimal(pair.dig(field, "amount")), pair.dig(field, "side")&.to_sym, classification)endreturn Balances.new(opening_balance: opening, closing_balance: closing, currency: currencies.first, source: source)@@ -300,7 +299,7 @@ class AccountStatement::TextMetadataParserenddef reading(pair)- BALANCE_FIELDS.zip(pair).to_h do |field, amount|+ AccountStatement::BALANCE_FIELDS.zip(pair).to_h do |field, amount|[ field, { "amount" => amount.value.to_s("F"), "side" => amount.side&.to_s, "currency" => amount.currency } ]endenddiff --git a/app/models/pdf_import.rb b/app/models/pdf_import.rbindex d3b1c87fff..dc2d3d43ae 100644--- a/app/models/pdf_import.rb+++ b/app/models/pdf_import.rb@@ -618,8 +618,8 @@ class PdfImport < Importif currency_compatible# 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)+ updates[:opening_balance] = opening_balance if opening_balance.present? && !account_statement.detected_balance?(:opening_balance, opening_balance, currency: target_currency)+ updates[:closing_balance] = closing_balance if closing_balance.present? && !account_statement.detected_balance?(:closing_balance, closing_balance, currency: target_currency)elseDebugLogEntry.capture(category: "import",@@ -671,7 +671,13 @@ class PdfImport < Importreturn if updates.empty?- unless account_statement.update(updates)+ # An AI balance the statement text doesn't give in the target currency+ # is the AI's from then on, even when it equals the stored balance, so+ # the statement keeps it rather than reading it again in a new currency.+ account_statement.assign_attributes(updates)+ account_statement.mark_balances_edited(updates.slice(:opening_balance, :closing_balance).keys)++ unless account_statement.saveDebugLogEntry.capture(category: "import",level: "warn",diff --git a/test/models/account_statement_test.rb b/test/models/account_statement_test.rbindex 5fba500838..5ec0695c1a 100644--- a/test/models/account_statement_test.rb+++ b/test/models/account_statement_test.rb@@ -801,6 +801,43 @@ class AccountStatementTest < ActiveSupport::TestCaseassert_equal BigDecimal("435.88"), statement.closing_balanceend+ test "balances posted back from a failed save stay derived" do+ @family.update!(currency: "EUR")+ statement = upload_card_statement(account: nil)+ assert_nil statement.closing_balance, "a dollar amount was read as euros"+ statement.currency = "USD"+ statement.period_end_on = statement.period_start_on - 1+ assert_not statement.save+ assert_equal BigDecimal("435.88"), statement.closing_balance++ # The form re-renders the derived values, and the next request posts them+ # back on a fresh record.+ retried = AccountStatement.find(statement.id)+ retried.update!(+ currency: "USD",+ period_end_on: retried.period_start_on + 30,+ opening_balance: statement.opening_balance.to_s,+ closing_balance: statement.closing_balance.to_s+ )+ retried.link_to_account!(accounts(:credit_card))++ assert_equal BigDecimal("-435.88"), retried.reload.closing_balance+ assert_empty Array(retried.sanitized_parser_output.dig("pdf", "edited_balances"))+ end++ test "a retry after an invalid currency re-derives the balances" do+ statement = upload_card_statement(account: nil)+ assert_equal "USD", statement.currency+ statement.currency = "NOPE"+ assert_not statement.save++ statement.currency = "USD"+ statement.save!++ assert_equal BigDecimal("435.88"), statement.reload.closing_balance+ assert_equal BigDecimal("1066.47"), statement.opening_balance+ end+test "leaves statements without balance readings alone when linked" dostatement = upload_card_statement(account: nil, text: "nothing to read")statement.update!(closing_balance: 250)diff --git a/test/models/pdf_import_reconciliation_test.rb b/test/models/pdf_import_reconciliation_test.rbindex 49babb67d2..8c32f952b3 100644--- a/test/models/pdf_import_reconciliation_test.rb+++ b/test/models/pdf_import_reconciliation_test.rb@@ -197,6 +197,59 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase"the AI's sign was kept over the CR marker on a depository account"end+ test "an AI sign correction still applies to a balance printed without a CR/DR marker" do+ # "Closing balance ($435.88)": the text reads 435.88, with no marker.+ detect_card_statement!(account: @account, closing_side: nil)+ stub_extracted_balances(opening: 1066.47, closing: -435.88)++ @import.extract_transactions++ assert_equal BigDecimal("-435.88"), @statement.reload.closing_balance+ end++ test "an AI balance in a currency the text can't resolve is kept" do+ detect_card_statement!(account: nil)+ @statement.update_columns(currency: nil)+ assert_equal "USD", @statement.reload.statement_currency+ stub_extracted_balances(opening: 1066.47, closing: 435.88, currency: "EUR")++ @import.extract_transactions++ @statement.reload+ assert_equal "EUR", @statement.currency+ assert_equal BigDecimal("1066.47"), @statement.opening_balance+ assert_equal BigDecimal("435.88"), @statement.closing_balance+ end++ test "an AI balance in another currency is kept when the same statement was saved earlier in the job" do+ detect_card_statement!(account: nil)+ @statement.update_columns(currency: nil)+ stub_extracted_balances(opening: 1066.47, closing: 435.88, currency: "EUR")+ period = { "statement_period_start" => @statement.period_start_on.to_s, "statement_period_end" => @statement.period_end_on.to_s }+ PdfImport::AiProcessor.any_instance.stubs(:process).returns(OpenStruct.new(extracted_data: period))++ # As ProcessPdfJob does: both calls save the import's one statement object,+ # the first in the family's dollars, the second switching it to euros.+ @import.process_with_ai+ assert_equal BigDecimal("435.88"), @import.account_statement.closing_balance+ @import.extract_transactions++ @statement.reload+ assert_equal "EUR", @statement.currency+ assert_equal BigDecimal("1066.47"), @statement.opening_balance+ assert_equal BigDecimal("435.88"), @statement.closing_balance+ end++ test "an AI balance keeps the hand edits already recorded on the statement" do+ detect_card_statement!(account: accounts(:credit_card))+ @statement.update!(opening_balance: 999)+ stub_extracted_balances(opening: nil, closing: 400.0)++ @import.extract_transactions++ assert_equal %w[closing_balance opening_balance], @statement.reload.sanitized_parser_output.dig("pdf", "edited_balances").sort+ end+test "extract_transactions writes an AI balance over a hand edit of the same size" dodetect_card_statement!(account: accounts(:credit_card))@statement.update!(closing_balance: 400)@@ -408,7 +461,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCaseendtest "apply_statement_metadata_updates captures debug log entry when update fails validation" do- @statement.stubs(:update).returns(false)+ @statement.stubs(:save).returns(false)@statement.errors.add(:base, "Simulated validation failure")assert_difference -> { DebugLogEntry.where(category: "import", level: "warn").count }, 1 do@@ -670,10 +723,10 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase# 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)+ def detect_card_statement!(account:, text: :labels, closing_side: "credit")pair = {"opening_balance" => { "amount" => "1066.47", "side" => nil, "currency" => "$" },- "closing_balance" => { "amount" => "435.88", "side" => "credit", "currency" => "$" }+ "closing_balance" => { "amount" => "435.88", "side" => closing_side, "currency" => "$" }}readings = text == :summary_table ? { "summary_table" => pair.merge("adds_up_as" => [ "liability" ]) } : { "labels" => pair }@statement.update_columns(@@ -683,14 +736,14 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase@statement.link_to_account!(account) if accountend- def stub_extracted_balances(opening:, closing:)+ def stub_extracted_balances(opening:, closing:, currency: nil)use_ai_routesprovider = 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: [] }+ data: { opening_balance: opening, closing_balance: closing, currency: currency, transactions: [] }))@import.stubs(:pdf_file_content).returns("fake-pdf")