The personal finance app for everyone (by everyone)
Ruby
fix(enable-banking): handle unavailable and overdraft balances (#2578)
Carlos Lindo5b9fd1e1a0cd
diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rbindex a2c5f1452a..e34f4cf110 100644--- a/app/models/enable_banking_item/importer.rb+++ b/app/models/enable_banking_item/importer.rb@@ -3,6 +3,17 @@ class EnableBankingItem::Importer# Enable Banking typically returns ~100 transactions per page, so 100 pages = ~10,000 transactionsMAX_PAGINATION_PAGES = 100+ # Prefer booked ledger balances for net worth/current_balance. Available balances+ # can include an arranged overdraft facility for some ASPSPs (for example CGD PT),+ # so they are only a last-resort fallback.+ BALANCE_TYPE_PRIORITY = %w[+ CLBD closingBooked+ ITBD interimBooked+ XPCD expected+ CLAV closingAvailable+ ITAV interimAvailable+ ].freeze+NETWORK_ERRORS = [::SocketError,::Errno::ECONNREFUSED,@@ -82,19 +93,18 @@ class EnableBankingItem::Importerendend- # Fetch balances and transactions for linked accounts+ # Fetch balances and transactions for linked accounts. Balance refreshes are+ # best-effort: a balance endpoint failure should keep the previous balance and+ # must not prevent transaction sync for the same account.transactions_imported = 0transactions_failed = 0+ balances_failed = 0linked_accounts_query = enable_banking_item.enable_banking_accounts.joins(:account_provider).joins(:account).merge(Account.visible)linked_accounts_query.each do |enable_banking_account|begin- unless fetch_and_update_balance(enable_banking_account)- transactions_failed += 1- # @sync_error already set in fetch_and_update_balance- next- end+ balances_failed += 1 unless fetch_and_update_balance(enable_banking_account)result = fetch_and_store_transactions(enable_banking_account)if result[:success]@@ -115,7 +125,8 @@ class EnableBankingItem::Importeraccounts_updated: accounts_updated,accounts_failed: accounts_failed,transactions_imported: transactions_imported,- transactions_failed: transactions_failed+ transactions_failed: transactions_failed,+ balances_failed: balances_failed}result[:error] = @sync_error || I18n.t("enable_banking_items.errors.unexpected") if !result[:success]@@ -187,48 +198,147 @@ class EnableBankingItem::Importerbalance_data = enable_banking_provider.get_account_balances(account_id: enable_banking_account.api_account_id,psu_headers: enable_banking_item.build_psu_headers- )+ ).with_indifferent_access- # Enable Banking returns an array of balances. We prioritize types based on reliability.- # closingBooked (CLBD) > interimAvailable (ITAV) > expected (XPCD)- balances = balance_data[:balances] || []- return true if balances.empty?+ # Enable Banking returns an array of balances. Use booked ledger balances for+ # current_balance/net worth before considering available balances. Available+ # balances can include arranged overdraft facilities and overstate cash.+ balances = Array(balance_data[:balances]).map { |balance| balance.with_indifferent_access }- priority_types = [ "CLBD", "ITAV", "XPCD", "CLAV", "ITBD" ]- balance = nil+ if balances.empty?+ mark_balance_unavailable(enable_banking_account)+ return false+ end- priority_types.each do |type|- balance = balances.find { |b| b[:balance_type] == type }- break if balance+ balance = select_current_balance(balances)++ unless balance.present?+ mark_balance_unavailable(enable_banking_account)+ return falseend- balance ||= balances.first+ amount = balance.dig(:balance_amount, :amount) || balance[:amount]+ currency = balance.dig(:balance_amount, :currency) || balance[:currency]- if balance.present?- amount = balance.dig(:balance_amount, :amount) || balance[:amount]- currency = balance.dig(:balance_amount, :currency) || balance[:currency]+ unless amount.present?+ mark_balance_unavailable(enable_banking_account)+ return false+ end- if amount.present?- indicator = balance[:credit_debit_indicator]- parsed_amount = amount.to_d+ indicator = balance[:credit_debit_indicator].to_s.upcase+ parsed_amount = amount.to_d- # Enable Banking uses positive amounts for both credit and debit.- # DBIT indicates a negative balance (money owed/withdrawn).- parsed_amount = -parsed_amount if indicator == "DBIT"+ # Enable Banking uses positive amounts for both credit and debit.+ # DBIT indicates a negative balance (money owed/withdrawn).+ parsed_amount = -parsed_amount if indicator == "DBIT"++ enable_banking_account.update!(+ current_balance: parsed_amount,+ currency: currency.presence || enable_banking_account.currency+ )- enable_banking_account.update!(- current_balance: parsed_amount,- currency: currency.presence || enable_banking_account.currency- )- end- endtruerescue Provider::EnableBanking::EnableBankingError => e@sync_error = promote_session_invalid(@sync_error, handle_sync_error(e))Rails.logger.error "EnableBankingItem::Importer - Error fetching balance for account #{enable_banking_account.uid}: #{e.message}"+ capture_balance_sync_error(enable_banking_account, e)+ mark_balance_unavailable(enable_banking_account)+ false+ rescue => e+ @sync_error = promote_session_invalid(@sync_error, handle_sync_error(e))+ Rails.logger.error "EnableBankingItem::Importer - Unexpected error fetching balance for account #{enable_banking_account.uid}: #{e.class} - #{e.message}"+ capture_balance_sync_error(enable_banking_account, e)+ mark_balance_unavailable(enable_banking_account)falseend+ def select_current_balance(balances)+ by_type = balances.index_by { |balance| normalize_balance_type(balance[:balance_type]) }++ BALANCE_TYPE_PRIORITY.each do |type|+ balance = by_type[normalize_balance_type(type)]+ return balance if balance.present?+ end++ balances.first+ end++ def normalize_balance_type(type)+ type.to_s.delete("_-").downcase+ end++ def mark_balance_unavailable(enable_banking_account)+ unless enable_banking_account.persisted?+ enable_banking_account.current_balance = nil+ return+ end++ enable_banking_account.update_columns(+ current_balance: nil,+ updated_at: Time.current+ )+ end++ def capture_balance_sync_error(enable_banking_account, error)+ metadata = {+ enable_banking_item_id: enable_banking_item.id,+ enable_banking_account_id: enable_banking_account.id,+ uid: enable_banking_account.uid,+ api_account_id: enable_banking_account.api_account_id,+ previous_current_balance: enable_banking_account.current_balance,+ error_class: error.class.name,+ error_message: sanitized_error_message(error)+ }++ if error.is_a?(Provider::EnableBanking::EnableBankingError)+ metadata[:error_type] = error.error_type.to_s+ metadata[:provider_error] = sanitized_provider_error(error)+ end++ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "Failed to fetch Enable Banking balance; keeping previous balance and continuing transaction sync",+ source: self.class.name,+ provider_key: "enable_banking",+ family: enable_banking_item.family,+ account_provider: enable_banking_account.account_provider,+ metadata: metadata+ )+ end++ def sanitized_error_message(error)+ return error.message unless error.is_a?(Provider::EnableBanking::EnableBankingError)++ provider_error = sanitized_provider_error(error)+ provider_error[:message].presence ||+ provider_error[:error].presence ||+ provider_error[:error_type].presence ||+ error.error_type.to_s+ end++ def sanitized_provider_error(error)+ response_data = error.response_data+ response_data = response_data.with_indifferent_access if response_data.respond_to?(:with_indifferent_access)++ metadata = { error_type: error.error_type.to_s }+ return metadata unless response_data.is_a?(Hash)++ metadata[:code] = response_data[:code] if response_data[:code].present?+ metadata[:error] = response_data[:error] if response_data[:error].present?+ metadata[:message] = response_data[:message] if response_data[:message].present?++ detail = response_data[:detail]+ detail = detail.with_indifferent_access if detail.respond_to?(:with_indifferent_access)++ if detail.is_a?(Hash)+ metadata[:detail_message] = detail[:message] if detail[:message].present?+ metadata[:detail_error_name] = detail[:error_name] if detail[:error_name].present?+ end++ metadata+ end+def promote_session_invalid(existing, new)return new if existing.nil?return new if new == I18n.t("enable_banking_items.errors.session_invalid")diff --git a/app/models/provider/enable_banking.rb b/app/models/provider/enable_banking.rbindex da6a2ea065..540accfc47 100644--- a/app/models/provider/enable_banking.rb+++ b/app/models/provider/enable_banking.rb@@ -247,7 +247,8 @@ class Provider::EnableBankingwhen 204{}when 400- raise EnableBankingError.new("Bad request to Enable Banking API: #{response.body}", :bad_request)+ response_data = parse_error_response_body(response)+ raise EnableBankingError.new("Bad request to Enable Banking API: #{response.body}", :bad_request, response_data: response_data)when 401raise EnableBankingError.new("Invalid credentials or expired JWT", :unauthorized)when 403@@ -262,10 +263,19 @@ class Provider::EnableBankingwhen 429raise EnableBankingError.new("Rate limit exceeded. Please try again later.", :rate_limited)else- raise EnableBankingError.new("Failed to fetch data: #{response.code} #{response.message} - #{response.body}", :fetch_failed)+ response_data = parse_error_response_body(response)+ raise EnableBankingError.new("Failed to fetch data: #{response.code} #{response.message} - #{response.body}", :fetch_failed, response_data: response_data)endend+ def parse_error_response_body(response)+ return {} if response.body.blank?++ JSON.parse(response.body, symbolize_names: true)+ rescue JSON::ParserError+ { raw_body: response.body.to_s }+ end+def parse_response_body(response)return {} if response.body.blank?diff --git a/test/models/enable_banking_account/processor_test.rb b/test/models/enable_banking_account/processor_test.rbindex ab4c41b1b3..474bf2b9d7 100644--- a/test/models/enable_banking_account/processor_test.rb+++ b/test/models/enable_banking_account/processor_test.rb@@ -42,6 +42,17 @@ class EnableBankingAccount::ProcessorTest < ActiveSupport::TestCaseassert_nil resultend+ test "skips balance update when provider current_balance is nil" do+ @account.update!(cash_balance: 987.65)+ @enable_banking_account.update_columns(current_balance: nil)++ EnableBankingAccount::Transactions::Processor.any_instance.expects(:process).once++ assert_no_changes -> { @account.reload.cash_balance } do+ EnableBankingAccount::Processor.new(@enable_banking_account).process+ end+ end+test "sets CC balance as absolute debt and tracks available_credit when limit is present" docc_account = accounts(:credit_card)@enable_banking_account.update!(diff --git a/test/models/enable_banking_item/importer_balance_test.rb b/test/models/enable_banking_item/importer_balance_test.rbnew file mode 100644index 0000000000..d6223e03aa--- /dev/null+++ b/test/models/enable_banking_item/importer_balance_test.rb@@ -0,0 +1,176 @@+require "test_helper"+require "ostruct"++class EnableBankingItem::ImporterBalanceTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @enable_banking_item = EnableBankingItem.create!(+ family: @family,+ name: "CGD PT",+ country_code: "PT",+ application_id: "test_app_id",+ client_certificate: "test_cert",+ session_id: "test_session",+ session_expires_at: 1.day.from_now,+ status: :good+ )++ @enable_banking_account = @enable_banking_item.enable_banking_accounts.create!(+ name: "CGD Current",+ uid: "identification_hash_1",+ account_id: "11111111-1111-1111-1111-111111111111",+ currency: "EUR",+ current_balance: 123.45,+ account_status: "active",+ provider: "enable_banking"+ )++ @mock_provider = OpenStruct.new+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ end++ test "fetch_and_update_balance prefers booked balance before available balance" do+ @mock_provider.stubs(:get_account_balances).returns(+ balances: [+ {+ balance_type: "ITAV",+ balance_amount: { amount: "1250.00", currency: "EUR" },+ credit_debit_indicator: "CRDT"+ },+ {+ balance_type: "ITBD",+ balance_amount: { amount: "50.00", currency: "EUR" },+ credit_debit_indicator: "DBIT"+ }+ ]+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("-50.00"), @enable_banking_account.reload.current_balance+ end++ test "fetch_and_update_balance handles descriptive booked balance types" do+ @mock_provider.stubs(:get_account_balances).returns(+ balances: [+ {+ balance_type: "interimAvailable",+ balance_amount: { amount: "2000.00", currency: "EUR" },+ credit_debit_indicator: "CRDT"+ },+ {+ balance_type: "closingBooked",+ balance_amount: { amount: "321.09", currency: "EUR" },+ credit_debit_indicator: "CRDT"+ }+ ]+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("321.09"), @enable_banking_account.reload.current_balance+ end++ test "balance endpoint failure marks provider balance unavailable and creates sanitized debug log" do+ error = Provider::EnableBanking::EnableBankingError.new(+ "Bad request to Enable Banking API: {\"error\":\"BALANCES_UNAVAILABLE\"}",+ :bad_request,+ response_data: {+ error: "BALANCES_UNAVAILABLE",+ detail: { account_id: "sensitive_account_id_should_not_be_persisted" }+ }+ )++ @mock_provider.stubs(:get_account_balances).raises(error)++ assert_difference "DebugLogEntry.count", 1 do+ assert_not @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end++ assert_nil @enable_banking_account.reload.current_balance++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "provider_sync_error", entry.category+ assert_equal "warn", entry.level+ assert_equal "enable_banking", entry.provider_key+ assert_equal "bad_request", entry.metadata["error_type"]+ assert_equal "BALANCES_UNAVAILABLE", entry.metadata.dig("provider_error", "error")+ assert_nil entry.metadata["response_data"]+ assert_nil entry.metadata.dig("provider_error", "account_id")+ end++ test "empty balance response marks provider balance unavailable" do+ @mock_provider.stubs(:get_account_balances).returns(balances: [])++ assert_not @importer.send(:fetch_and_update_balance, @enable_banking_account)+ assert_nil @enable_banking_account.reload.current_balance+ end++ test "unusable balance response marks provider balance unavailable" do+ @mock_provider.stubs(:get_account_balances).returns(+ balances: [+ {+ balance_type: "CLBD",+ balance_amount: { currency: "EUR" },+ credit_debit_indicator: "CRDT"+ }+ ]+ )++ assert_not @importer.send(:fetch_and_update_balance, @enable_banking_account)+ assert_nil @enable_banking_account.reload.current_balance+ end++ test "import continues transaction sync when balance refresh fails" do+ depository = Depository.create!+ linked_account = Account.create!(+ family: @family,+ name: "CGD linked",+ balance: 123.45,+ cash_balance: 123.45,+ currency: "EUR",+ accountable: depository+ )+ AccountProvider.create!(account: linked_account, provider: @enable_banking_account)++ @enable_banking_item.stubs(:upsert_enable_banking_snapshot!)+ @importer.stubs(:fetch_session_data).returns(accounts: [])+ @importer.expects(:fetch_and_update_balance).with(@enable_banking_account).returns(false)+ @importer.expects(:fetch_and_store_transactions).with(@enable_banking_account).returns(+ success: true,+ transactions_count: 2+ )++ result = @importer.import++ assert result[:success]+ assert_equal 2, result[:transactions_imported]+ assert_equal 0, result[:transactions_failed]+ assert_equal 1, result[:balances_failed]+ end++ test "balance endpoint failure marks unsaved provider balance unavailable" do+ unsaved_account = EnableBankingAccount.new(+ enable_banking_item: @enable_banking_item,+ uid: "unsaved-account",+ current_balance: BigDecimal("123.45"),+ currency: "EUR"+ )++ unsaved_account.stubs(:api_account_id).returns("unsaved-account")++ error = Provider::EnableBanking::EnableBankingError.new(+ "Bad request to Enable Banking API",+ :bad_request,+ response_data: { error: "BALANCES_UNAVAILABLE" }+ )++ @mock_provider.stubs(:get_account_balances).raises(error)++ assert_nothing_raised do+ assert_not @importer.send(:fetch_and_update_balance, unsaved_account)+ end++ assert_nil unsaved_account.current_balance+ end+enddiff --git a/test/models/provider/enable_banking_test.rb b/test/models/provider/enable_banking_test.rbindex 16c3a8d8af..f74f91b76c 100644--- a/test/models/provider/enable_banking_test.rb+++ b/test/models/provider/enable_banking_test.rb@@ -104,4 +104,21 @@ class Provider::EnableBankingTest < ActiveSupport::TestCaseassert_not captured_body.key?("auth_method")end+ test "bad request errors expose parsed response data" do+ response = OpenStruct.new(+ code: 400,+ body: {+ error: "BALANCES_UNAVAILABLE",+ detail: { account_id: "redacted" }+ }.to_json+ )++ error = assert_raises Provider::EnableBanking::EnableBankingError do+ @provider.send(:handle_response, response)+ end++ assert_equal :bad_request, error.error_type+ assert_equal "BALANCES_UNAVAILABLE", error.response_data[:error]+ assert_equal "redacted", error.response_data.dig(:detail, :account_id)+ endend