Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(statements): sync extracted metadata from PdfImport to AccountStatement (#5001)

Élian Gadbois-Royb0f9c042a340
diff --git a/app/models/pdf_import.rb b/app/models/pdf_import.rb
index fbecbea913..5ffbd8c40a 100644
--- a/app/models/pdf_import.rb
+++ b/app/models/pdf_import.rb
@@ -235,6 +235,7 @@ class PdfImport < Import
ai_summary: result.summary,
document_type: result.document_type
)
+ sync_statement_metadata_from_process_result(result)
result
end
@@ -263,6 +264,7 @@ class PdfImport < Import
# in-memory read comes back empty and the import produces no rows at all.
data = response.data.deep_stringify_keys
update!(extracted_data: data)
+ sync_statement_metadata_from_extracted_data(data)
data
end
@@ -593,4 +595,178 @@ class PdfImport < Import
errors.add(:account_statement, :invalid)
end
+
+ def sync_statement_metadata_from_extracted_data(data)
+ return unless statement_backed?
+
+ start_date = data.dig("period", "start_date").presence
+ end_date = data.dig("period", "end_date").presence
+ opening_bal = data["opening_balance"]
+ closing_bal = data["closing_balance"]
+ bank_name = data["bank_name"].presence
+ last4 = data["account_number"].presence&.to_s&.last(4)
+ currency = data["currency"].presence || account_statement.sanitized_parser_output&.dig("extracted_currency").presence
+
+ apply_statement_metadata_updates(
+ start_date: start_date,
+ end_date: end_date,
+ opening_balance: opening_bal,
+ closing_balance: closing_bal,
+ institution_name: bank_name,
+ account_last4: last4,
+ currency: currency
+ )
+ end
+
+ def sync_statement_metadata_from_process_result(result)
+ return unless statement_backed?
+ return unless result.respond_to?(:extracted_data) && result.extracted_data.is_a?(Hash)
+
+ data = result.extracted_data.deep_stringify_keys
+ start_date = data["statement_period_start"].presence
+ end_date = data["statement_period_end"].presence
+ opening_bal = data["opening_balance"]
+ closing_bal = data["closing_balance"]
+ institution = data["institution_name"].presence
+ currency = data["currency"].presence || account_statement.sanitized_parser_output&.dig("extracted_currency").presence
+
+ apply_statement_metadata_updates(
+ start_date: start_date,
+ end_date: end_date,
+ opening_balance: opening_bal,
+ closing_balance: closing_bal,
+ institution_name: institution,
+ account_last4: nil,
+ currency: currency
+ )
+ end
+
+ def apply_statement_metadata_updates(start_date:, end_date:, opening_balance:, closing_balance:, institution_name:, account_last4:, currency: nil)
+ updates = {}
+
+ if currency.present?
+ if account_statement.currency.blank? && account_statement.account_id.blank?
+ updates[:currency] = currency.to_s.upcase
+ end
+ parser_output = (account_statement.sanitized_parser_output || {}).dup
+ if parser_output["extracted_currency"] != currency.to_s.upcase
+ parser_output["extracted_currency"] = currency.to_s.upcase
+ updates[:sanitized_parser_output] = parser_output
+ end
+ end
+
+ # Only sync balances when currency is compatible with the statement's currency,
+ # matching AccountStatement::MetadataDetector#detect_from_pdf behavior.
+ 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?
+ else
+ DebugLogEntry.capture(
+ category: "import",
+ level: "warn",
+ message: "PdfImport: extracted balance currency '#{currency}' does not match statement currency '#{target_currency}'",
+ source: "pdf_import",
+ family: family,
+ account: account,
+ metadata: {
+ import_id: id,
+ account_statement_id: account_statement.id,
+ extracted_currency: currency,
+ statement_currency: target_currency
+ }
+ )
+ end
+
+ bounded_institution = institution_name.presence&.to_s&.strip&.first(200)&.presence
+ updates[:institution_name_hint] = bounded_institution if bounded_institution && account_statement.institution_name_hint.blank?
+ updates[:account_last4_hint] = account_last4 if account_last4.present? && account_statement.account_last4_hint.blank?
+
+ parsed_start = parse_statement_date(start_date)
+ parsed_end = parse_statement_date(end_date)
+
+ proposed_start = parsed_start || account_statement.period_start_on
+ proposed_end = parsed_end || account_statement.period_end_on
+
+ if proposed_start && proposed_end && proposed_start > proposed_end
+ DebugLogEntry.capture(
+ category: "import",
+ level: "warn",
+ message: "PdfImport: extracted statement period is inverted or conflicts with existing period",
+ source: "pdf_import",
+ family: family,
+ account: account,
+ metadata: {
+ import_id: id,
+ account_statement_id: account_statement.id,
+ parsed_start: parsed_start&.iso8601,
+ parsed_end: parsed_end&.iso8601,
+ existing_start: account_statement.period_start_on&.iso8601,
+ existing_end: account_statement.period_end_on&.iso8601
+ }
+ )
+ else
+ updates[:period_start_on] = parsed_start if parsed_start
+ updates[:period_end_on] = parsed_end if parsed_end
+ end
+
+ return if updates.empty?
+
+ unless account_statement.update(updates)
+ DebugLogEntry.capture(
+ category: "import",
+ level: "warn",
+ message: "PdfImport: failed to sync statement metadata (#{account_statement.errors.full_messages.to_sentence})",
+ source: "pdf_import",
+ family: family,
+ account: account,
+ metadata: {
+ import_id: id,
+ account_statement_id: account_statement.id,
+ updates: updates,
+ errors: account_statement.errors.messages
+ }
+ )
+ end
+ end
+
+ def parse_statement_date(date_str)
+ return nil if date_str.blank?
+
+ date = date_str.is_a?(Date) ? date_str : Date.parse(date_str.to_s)
+ return date if Import.reasonable_date_range.cover?(date)
+
+ DebugLogEntry.capture(
+ category: "import",
+ level: "warn",
+ message: "PdfImport: statement date '#{date_str}' falls outside reasonable date range",
+ source: "pdf_import",
+ family: family,
+ account: account,
+ metadata: {
+ import_id: id,
+ account_statement_id: account_statement&.id,
+ raw_date: date_str,
+ parsed_date: date.iso8601
+ }
+ )
+ nil
+ rescue Date::Error, ArgumentError => e
+ DebugLogEntry.capture(
+ category: "import",
+ level: "warn",
+ message: "PdfImport: failed to parse statement date '#{date_str}' (#{e.message})",
+ source: "pdf_import",
+ family: family,
+ account: account,
+ metadata: {
+ import_id: id,
+ account_statement_id: account_statement&.id,
+ raw_date: date_str
+ }
+ )
+ nil
+ end
end
diff --git a/test/models/pdf_import_reconciliation_test.rb b/test/models/pdf_import_reconciliation_test.rb
index 5c44f87aa9..b59f4e7ba0 100644
--- a/test/models/pdf_import_reconciliation_test.rb
+++ b/test/models/pdf_import_reconciliation_test.rb
@@ -145,6 +145,234 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
assert_equal "Coffee", @import.extracted_transactions.first["name"]
end
+ test "extract_transactions syncs period and balances to statement_backed import" do
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: {
+ period: { start_date: "2026-10-09", end_date: "2026-11-06" },
+ opening_balance: 325.0,
+ closing_balance: 3176.22,
+ bank_name: "American Express",
+ account_number: "2007",
+ transactions: [ { date: "2026-10-15", amount: "-10.0", name: "Lunch" } ]
+ }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+
+ @import.extract_transactions
+
+ @statement.reload
+ assert_equal Date.parse("2026-10-09"), @statement.period_start_on
+ assert_equal Date.parse("2026-11-06"), @statement.period_end_on
+ assert_equal 325.0, @statement.opening_balance
+ assert_equal 3176.22, @statement.closing_balance
+ assert_equal "American Express", @statement.institution_name_hint
+ assert_equal "2007", @statement.account_last4_hint
+ end
+
+ test "extract_transactions ignores inverted dates while syncing valid balances and hints" do
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: {
+ period: { start_date: "2026-11-06", end_date: "2026-10-09" },
+ opening_balance: 100.0,
+ closing_balance: 200.0,
+ bank_name: "Chase",
+ account_number: "1234",
+ transactions: []
+ }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+ initial_start = @statement.period_start_on
+ initial_end = @statement.period_end_on
+
+ assert_difference -> { DebugLogEntry.where(category: "import", level: "warn").count }, 1 do
+ @import.extract_transactions
+ end
+
+ @statement.reload
+ assert_equal initial_start, @statement.period_start_on
+ assert_equal initial_end, @statement.period_end_on
+ assert_equal 100.0, @statement.opening_balance
+ assert_equal 200.0, @statement.closing_balance
+ assert_equal "Chase", @statement.institution_name_hint
+ assert_equal "1234", @statement.account_last4_hint
+ end
+
+ test "extract_transactions handles unparseable date independently without dropping balances" do
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: {
+ period: { start_date: "2026-02-30", end_date: "2026-11-06" },
+ opening_balance: 50.0,
+ closing_balance: 150.0,
+ bank_name: "Wells Fargo",
+ account_number: "5678",
+ transactions: []
+ }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+
+ assert_difference -> { DebugLogEntry.where(category: "import", level: "warn").count }, 1 do
+ @import.extract_transactions
+ end
+
+ @statement.reload
+ assert_equal 50.0, @statement.opening_balance
+ assert_equal 150.0, @statement.closing_balance
+ assert_equal "Wells Fargo", @statement.institution_name_hint
+ assert_equal "5678", @statement.account_last4_hint
+ end
+
+ test "extract_transactions rejects dates outside Import.reasonable_date_range" do
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: {
+ period: { start_date: "1950-01-01", end_date: "2026-11-06" },
+ opening_balance: 50.0,
+ closing_balance: 150.0,
+ transactions: []
+ }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+
+ assert_difference -> { DebugLogEntry.where(category: "import", level: "warn").count }, 1 do
+ @import.extract_transactions
+ end
+ end
+
+ test "extract_transactions drops balances when extracted currency conflicts with statement currency" do
+ @statement.update!(currency: "USD", opening_balance: 10.0)
+
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: {
+ period: { start_date: "2026-10-01", end_date: "2026-10-31" },
+ opening_balance: 50.0,
+ closing_balance: 150.0,
+ currency: "EUR",
+ transactions: []
+ }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+
+ assert_difference -> { DebugLogEntry.where(category: "import", level: "warn").count }, 1 do
+ @import.extract_transactions
+ end
+
+ @statement.reload
+ assert_equal 10.0, @statement.opening_balance
+ assert_nil @statement.closing_balance
+ end
+
+ test "extract_transactions honors currency mismatch detected during earlier processing" do
+ @statement.update!(currency: "USD", opening_balance: 10.0, sanitized_parser_output: { "extracted_currency" => "EUR" })
+
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: {
+ period: { start_date: "2026-10-01", end_date: "2026-10-31" },
+ opening_balance: 50.0,
+ closing_balance: 150.0,
+ transactions: []
+ }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+
+ assert_difference -> { DebugLogEntry.where(category: "import", level: "warn").count }, 1 do
+ @import.extract_transactions
+ end
+
+ @statement.reload
+ assert_equal 10.0, @statement.opening_balance
+ assert_nil @statement.closing_balance
+ end
+
+ test "apply_statement_metadata_updates bounds institution_name_hint to 200 characters" do
+ long_name = "A" * 300
+ @import.send(
+ :apply_statement_metadata_updates,
+ start_date: "2026-10-01",
+ end_date: "2026-10-31",
+ opening_balance: 100,
+ closing_balance: 200,
+ institution_name: long_name,
+ account_last4: "1234"
+ )
+
+ @statement.reload
+ assert_equal ("A" * 200), @statement.institution_name_hint
+ assert_equal 200, @statement.institution_name_hint.length
+ end
+
+ test "apply_statement_metadata_updates preserves existing hints when already populated" do
+ @statement.update!(institution_name_hint: "Existing Bank", account_last4_hint: "9999")
+
+ provider = mock("llm_provider")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+ provider.stubs(:extract_bank_statement).returns(
+ OpenStruct.new(
+ success?: true,
+ data: {
+ period: { start_date: "2026-10-01", end_date: "2026-10-31" },
+ opening_balance: 10.0,
+ closing_balance: 20.0,
+ bank_name: "New Bank",
+ account_number: "1111",
+ transactions: []
+ }
+ )
+ )
+ @import.stubs(:pdf_file_content).returns("fake-pdf")
+
+ @import.extract_transactions
+
+ @statement.reload
+ assert_equal "Existing Bank", @statement.institution_name_hint
+ assert_equal "9999", @statement.account_last4_hint
+ end
+
+ test "apply_statement_metadata_updates captures debug log entry when update fails validation" do
+ @statement.stubs(:update).returns(false)
+ @statement.errors.add(:base, "Simulated validation failure")
+
+ assert_difference -> { DebugLogEntry.where(category: "import", level: "warn").count }, 1 do
+ @import.send(
+ :apply_statement_metadata_updates,
+ start_date: "2026-10-01",
+ end_date: "2026-10-31",
+ opening_balance: 100,
+ closing_balance: 200,
+ institution_name: "Bank",
+ account_last4: "1234"
+ )
+ end
+ end
+
test "publishing does not re-match a row against an entry row generation already consumed" do
create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")