The personal finance app for everyone (by everyone)
Ruby
Resolve duplicate same-type Enable Banking balances deterministically (#4344)
GFR244954105927
diff --git a/app/models/enable_banking_account/processor.rb b/app/models/enable_banking_account/processor.rbindex fe8b8fca8d..ab7add31a6 100644--- a/app/models/enable_banking_account/processor.rb+++ b/app/models/enable_banking_account/processor.rb@@ -22,6 +22,8 @@ class EnableBankingAccount::ProcessorRails.logger.error "EnableBankingAccount::Processor - Failed to process account #{enable_banking_account.id}: #{e.message}"Rails.logger.error "Backtrace: #{e.backtrace.join("\n")}"report_exception(e, "account")+ # Whatever happened to the anchor here, it is not known to be verified.+ enable_banking_account.update_column(:balance_verified, false) if enable_banking_account.persisted?raiseend@@ -87,6 +89,11 @@ class EnableBankingAccount::Processor# bank-reported balance — eliminating spurious cash adjustment spikes.result = account.set_current_balance(balance)raise ProcessingError, "Failed to set current balance: #{result.error}" unless result.success?++ # The anchor now holds this balance, so its verification is the+ # importer's evidence for it. Only set here, so a sync that stops+ # before this point never vouches for an older anchor.+ enable_banking_account.update!(balance_verified: enable_banking_account.balance_evidence_verified?)endenddiff --git a/app/models/enable_banking_entry/processor.rb b/app/models/enable_banking_entry/processor.rbindex 07025f267a..fa8c4bf3c6 100644--- a/app/models/enable_banking_entry/processor.rb+++ b/app/models/enable_banking_entry/processor.rb@@ -107,6 +107,31 @@ class EnableBankingEntry::Processorline.match?(/\A(POS|ATM)\s+\d+[.,]\d{2}\b.*\d{1,2}[.\/]\d{1,2}\.?\s+\d{2}:\d{2}\z/i)end+ # Prefer booking_date, fall back to value_date, then transaction_date.+ # Timestamps are read in the family's timezone.+ def self.transaction_date(raw_transaction_data, timezone)+ data = raw_transaction_data.with_indifferent_access+ date_value = data[:booking_date] || data[:value_date] || data[:transaction_date]++ case date_value+ when String+ if date_value.include?("T") || date_value.include?(":")+ Time.parse(date_value).in_time_zone(timezone).to_date+ else+ Date.parse(date_value)+ end+ when Integer, Float+ Time.at(date_value).in_time_zone(timezone).to_date+ when Time, DateTime+ date_value.in_time_zone(timezone).to_date+ when Date+ date_value+ else+ Rails.logger.error("Enable Banking transaction has invalid date value: #{date_value.inspect}")+ raise ArgumentError, "Invalid date format: #{date_value.inspect}"+ end+ end+# True when the transaction represents an unfinalized card authorization hold# (missing provider identifiers, no legitimate counterparty name, and a masked# card descriptor in remittance or transaction code).@@ -608,27 +633,9 @@ class EnableBankingEntry::Processorenddef date- # Prefer booking_date, fall back to value_date, then transaction_date- date_value = data[:booking_date] || data[:value_date] || data[:transaction_date]-- case date_value- when String- if date_value.include?("T") || date_value.include?(":")- Time.parse(date_value).in_time_zone(account&.family&.timezone).to_date- else- Date.parse(date_value)- end- when Integer, Float- Time.at(date_value).in_time_zone(account&.family&.timezone).to_date- when Time, DateTime- date_value.in_time_zone(account&.family&.timezone).to_date- when Date- date_value- else- Rails.logger.error("Enable Banking transaction has invalid date value: #{date_value.inspect}")- raise ArgumentError, "Invalid date format: #{date_value.inspect}"- end+ self.class.transaction_date(data, account&.family&.timezone)rescue ArgumentError, TypeError => e+ date_value = data[:booking_date] || data[:value_date] || data[:transaction_date]Rails.logger.error("Failed to parse Enable Banking transaction date '#{date_value}': #{e.message}")raise ArgumentError, "Unable to parse transaction date: #{date_value.inspect}"enddiff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rbindex f8afd55220..6c52a861ae 100644--- a/app/models/enable_banking_item/importer.rb+++ b/app/models/enable_banking_item/importer.rb@@ -48,6 +48,16 @@ class EnableBankingItem::Importer# mirroring BALANCE_TYPE_PRIORITY's own XPCD/CLAV/ITAV entries above.FRESHNESS_BALANCE_TYPES = %w[xpcd expected clav closingavailable itav interimavailable].freeze+ # Two same-type balances within this distance of each other (or of an expected+ # value) are treated as equal when breaking a tie (see resolve_same_type_balances).+ BALANCE_TIEBREAK_TOLERANCE = BigDecimal("0.01")++ # Tiebreak stages backed by evidence rather than a heuristic. A balance chosen+ # this way (or without any tiebreak) is stored as balance_evidence_verified;+ # the processor promotes that to balance_verified only once the balance has+ # been written as the anchor, which lets the next sync trust that anchor.+ VERIFIED_TIEBREAK_STAGES = %i[last_committed_transaction credit_limit anchor].freeze+NETWORK_ERRORS = [::SocketError,::Errno::ECONNREFUSED,@@ -138,8 +148,6 @@ class EnableBankingItem::Importerlinked_accounts_query.each do |enable_banking_account|begin- balances_failed += 1 unless fetch_and_update_balance(enable_banking_account)-result = fetch_and_store_transactions(enable_banking_account)if result[:success]transactions_imported += result[:transactions_count]@@ -152,6 +160,17 @@ class EnableBankingItem::Importer@sync_error = promote_session_invalid(@sync_error, handle_sync_error(e))Rails.logger.error "EnableBankingItem::Importer - Failed to process account #{enable_banking_account.uid}: #{e.message}"end++ # Runs after the transaction fetch so a same-type balance tie can be checked+ # against this sync's booked transactions (see resolve_same_type_balances),+ # and in its own rescue so a failed transaction fetch never skips it.+ begin+ balances_failed += 1 unless fetch_and_update_balance(enable_banking_account)+ rescue => e+ balances_failed += 1+ @sync_error = promote_session_invalid(@sync_error, handle_sync_error(e))+ Rails.logger.error "EnableBankingItem::Importer - Failed to update balance for account #{enable_banking_account.uid}: #{e.message}"+ endendresult = {@@ -245,8 +264,8 @@ class EnableBankingItem::Importerendcurrency, kept, skipped = split_balances_by_currency(balances, enable_banking_account)- balance = select_current_balance(- kept, prefer_available: prefer_available_balance?(enable_banking_account)+ balance, tiebreak_stage = select_current_balance(+ kept, enable_banking_account, prefer_available: prefer_available_balance?(enable_banking_account))unless balance.present?@@ -270,7 +289,8 @@ class EnableBankingItem::Importerenable_banking_account.update!(current_balance: parsed_amount,- currency: balance_currency(balance) || enable_banking_account.currency+ currency: balance_currency(balance) || enable_banking_account.currency,+ balance_evidence_verified: tiebreak_stage.nil? || VERIFIED_TIEBREAK_STAGES.include?(tiebreak_stage))# Only now is the chosen-currency balance known to be the one in use.capture_skipped_currency_balances(enable_banking_account, currency, skipped)@@ -294,7 +314,7 @@ class EnableBankingItem::Importer# under the same balance type (EUR, CAD, USD, ...). Keep the balances in# the currency the accounts endpoint reports for the account, else in the# first currency listed, which is the wallet's primary one. Otherwise- # select_current_balance takes the last entry of each type, so an empty+ # the same-type tiebreak would choose between currencies, so an empty# USD balance replaced the EUR one and switched the account to USD.# Returns the chosen currency, the balances in it and the ones left out.def split_balances_by_currency(balances, enable_banking_account)@@ -357,24 +377,271 @@ class EnableBankingItem::Importerenable_banking_account.current_account&.accountable_type == "CreditCard"end- def select_current_balance(balances, prefer_available: false)- by_type = balances.index_by { |balance| normalize_balance_type(balance[:balance_type]) }+ # Returns [balance, tiebreak_stage]. tiebreak_stage is nil unless the chosen+ # type was reported more than once (see resolve_same_type_balances).+ def select_current_balance(balances, enable_banking_account, prefer_available: false)+ by_type = balances.group_by { |balance| normalize_balance_type(balance[:balance_type]) }priority = prefer_available ? AVAILABLE_CREDIT_BALANCE_TYPE_PRIORITY : BALANCE_TYPE_PRIORITYpriority.each do |type|normalized_type = normalize_balance_type(type)- balance = by_type[normalized_type]- next unless balance.present?+ candidates = by_type[normalized_type]+ next if candidates.blank?if PERIOD_BOUNDARY_TYPES.include?(normalized_type)- fresher = fresher_balance(balance, balances)- return fresher if fresher+ # Checked before the tiebreak, so a tie among OPBD/PRCD entries that a+ # fresher balance replaces anyway is neither resolved nor logged.+ newest = candidates.max_by { |candidate| parse_reference_date(candidate[:reference_date]) || Date.new(0) }+ fresher = fresher_balance(newest, balances)+ if fresher+ # fresher_balance takes the first entry of the newest date, so+ # same-type entries of that date go through the same tiebreak.+ # Older entries of that type still make the pick unverified.+ same_type = by_type[normalize_balance_type(fresher[:balance_type])]+ fresher_date = parse_reference_date(fresher[:reference_date])+ same_day = same_type.select { |candidate| parse_reference_date(candidate[:reference_date]) == fresher_date }+ fresher, fresher_stage = resolve_same_type_balances(same_day, enable_banking_account)+ return [ fresher, same_day.size == same_type.size ? fresher_stage : :fresher ]+ endend- return balance+ return resolve_same_type_balances(candidates, enable_banking_account)+ end++ # No known type: response order decides, which is no evidence once there+ # is more than one entry.+ [ balances.first, balances.one? ? nil : :first ]+ end++ # Some ASPSPs report the same balance_type twice with different amounts, e.g.+ # two CLBD entries where one includes the arranged overdraft (#3188). Stages,+ # strongest evidence first:+ # :credit_limit (depository) gap equals the credit limit; lower wins+ # :last_committed_transaction candidates point to different bookings; newest wins+ # :anchor / :anchor_timestamp (depository) matches the previous anchor minus+ # booked flows since, if that anchor was verified+ # :lowest (depository) an included overdraft only ever raises it+ # :first (other accounts) first entry in response order+ def resolve_same_type_balances(candidates, enable_banking_account)+ return [ candidates.first, nil ] if candidates.one?++ usable = candidates.select { |balance| signed_balance_amount(balance) }+ return [ candidates.first, nil ] if usable.empty?+ return [ usable.first, nil ] if usable.one?+ # The same amount reported twice is no ambiguity.+ return [ usable.first, nil ] if usable.map { |balance| signed_balance_amount(balance) }.uniq.one?++ balance, stage = tiebreak_same_type_balances(usable, enable_banking_account)+ capture_balance_tiebreak_debug_log(enable_banking_account, candidates, balance, stage)+ [ balance, stage ]+ end++ def tiebreak_same_type_balances(candidates, enable_banking_account)+ account = enable_banking_account.current_account+ depository = account&.accountable_type == "Depository"++ # A gap equal to the arranged overdraft is direct evidence of #3188, so it+ # decides before the booking references, which say nothing about overdrafts.+ if depository+ winner = balance_by_credit_limit(candidates, enable_banking_account)+ return [ winner, :credit_limit ] if winner+ end++ booked = booked_raw_transactions(enable_banking_account)+ winner = balance_by_last_committed_transaction(candidates, booked)+ return [ winner, :last_committed_transaction ] if winner++ return [ candidates.first, :first ] unless depository++ winner, stage = balance_by_anchor(candidates, enable_banking_account, account, booked)+ return [ winner, stage ] if winner++ [ candidates.min_by { |balance| signed_balance_amount(balance) }, :lowest ]+ end++ # last_committed_transaction is the entry_reference of the last booking the+ # balance includes. Only decides when every candidate points to a different,+ # known booking; equal references say nothing about which amount is right.+ def balance_by_last_committed_transaction(candidates, booked)+ references = candidates.map { |balance| balance[:last_committed_transaction].presence }+ return nil if references.any?(&:nil?) || references.uniq.size != references.size++ # A reference reused with different dates cannot say which booking is+ # newer, and this stage counts as verified, so such a reference abstains.+ booking_dates = booked.each_with_object({}) do |tx, dates|+ reference = tx[:entry_reference].presence+ date = raw_transaction_date(tx)+ (dates[reference] ||= Set.new) << date if reference && date+ end++ dates = references.map { |reference| booking_dates[reference] }+ return nil unless dates.all? { |reference_dates| reference_dates&.one? }++ dated = candidates.zip(dates.map(&:first))++ latest = dated.map(&:last).max+ newest = dated.select { |_, date| date == latest }+ newest.one? ? newest.first.first : nil+ end++ # An arranged overdraft counted into one of the balances shifts it up by the+ # credit limit, so a gap matching the limit identifies the lower one as real.+ def balance_by_credit_limit(candidates, enable_banking_account)+ credit_limit = enable_banking_account.credit_limit+ return nil unless credit_limit.present? && credit_limit.positive?++ amounts = candidates.map { |balance| signed_balance_amount(balance) }+ return nil unless ((amounts.max - amounts.min) - credit_limit).abs <= BALANCE_TIEBREAK_TOLERANCE++ candidates.min_by { |balance| signed_balance_amount(balance) }+ end++ # Expected balance = previous anchor minus booked flows since (asset account,+ # positive amount = outflow, mirroring Balance::ForwardCalculator). Skipped+ # unless the current anchor was verified when it was written: an anchor that+ # already came from the wrong candidate would otherwise confirm itself.+ #+ # Bookings dated on the anchor day may or may not be in the anchor (it was+ # taken at some point that day), so the expectation is computed both ways and+ # only an answer both agree on counts.+ def balance_by_anchor(candidates, enable_banking_account, account, booked)+ return nil unless enable_banking_account.balance_verified? && account.has_current_anchor?+ return nil unless anchor_written_by_this_link?(account, enable_banking_account)++ anchor_date = account.current_anchor_date+ flows = booked.map { |tx| [ raw_transaction_date(tx), tx ] }+ # A booking without a usable date may fall after the anchor: abstain.+ return nil if flows.any? { |date, _| date.nil? }++ dated = flows.filter_map do |date, tx|+ [ date, signed_transaction_amount(tx) ] if date >= anchor_date && date <= Date.current+ end+ # An unparseable amount makes the expected balance unknowable: abstain.+ return nil if dated.any? { |_, amount| amount.nil? }+ later_flows = dated.sum { |date, amount| date > anchor_date ? amount : 0 }+ all_flows = dated.sum { |_, amount| amount }++ closest = matching_balances(candidates, account.current_anchor_balance - later_flows)+ return nil if closest.empty?+ return nil unless closest == matching_balances(candidates, account.current_anchor_balance - all_flows)+ return [ closest.first, :anchor ] if closest.one?++ latest = closest.filter_map { |balance| [ balance, parse_balance_timestamp(balance[:last_change_date_time]) ] }+ .select { |_, time| time }+ return nil unless latest.size == closest.size++ newest_time = latest.map(&:last).max+ newest = latest.select { |_, time| time == newest_time }+ newest.one? ? [ newest.first.first, :anchor_timestamp ] : nil+ end++ # balance_verified lives on the provider account, so after a relink it would+ # otherwise vouch for an anchor the new account got elsewhere.+ def anchor_written_by_this_link?(account, enable_banking_account)+ linked_at = enable_banking_account.account_provider&.created_at+ anchor_written_at = account.valuations.current_anchor.joins(:entry).pick(Arel.sql("entries.updated_at"))+ linked_at.present? && anchor_written_at.present? && anchor_written_at >= linked_at+ end++ # Only candidates that actually match the expectation count: the closest of+ # several far-off amounts is no evidence for any of them.+ def matching_balances(candidates, expected)+ candidates.select { |balance| (signed_balance_amount(balance) - expected).abs <= BALANCE_TIEBREAK_TOLERANCE }+ end++ # Same dates as the entries get (EnableBankingEntry::Processor#date); nil+ # when the row has no usable date.+ def raw_transaction_date(tx)+ return nil if tx.values_at(:booking_date, :value_date, :transaction_date).all?(&:blank?)++ EnableBankingEntry::Processor.transaction_date(tx, enable_banking_item.family.timezone)+ rescue ArgumentError, TypeError+ nil+ end++ def booked_raw_transactions(enable_banking_account)+ enable_banking_account.raw_transactions_payload.to_a.map(&:with_indifferent_access).select do |tx|+ tx[:status] != "PDNG" && !tx[:_pending] && !tx.dig(:extra, :enable_banking, :pending) &&+ !EnableBankingEntry::Processor.unidentified_hold?(tx)end+ end++ # Same sign convention as EnableBankingEntry::Processor#amount_value:+ # DBIT (outflow) positive, CRDT (inflow) negative.+ def signed_transaction_amount(tx)+ amount = tx.dig(:transaction_amount, :amount) || tx[:amount]+ absolute = BigDecimal(amount.to_s).abs+ tx[:credit_debit_indicator] == "CRDT" ? -absolute : absolute+ rescue ArgumentError, TypeError+ nil+ end++ def signed_balance_amount(balance)+ amount = balance.dig(:balance_amount, :amount) || balance[:amount]+ return nil if amount.blank?++ parsed = BigDecimal(amount.to_s)+ balance[:credit_debit_indicator].to_s.upcase == "DBIT" ? -parsed : parsed+ rescue ArgumentError, TypeError+ nil+ end++ def parse_balance_timestamp(value)+ return nil if value.blank?+ Time.zone.parse(value.to_s)+ rescue ArgumentError, TypeError+ nil+ end++ # Banks that always report the duplicate would otherwise add the same warning+ # on every sync; log again only when the candidates or the outcome change.+ # Amounts, not positions, so a bank reordering the same entries stays quiet.+ def capture_balance_tiebreak_debug_log(enable_banking_account, candidates, chosen, stage)+ amount_key = ->(balance) { signed_balance_amount(balance)&.to_s("F").to_s }+ fingerprint = Digest::SHA256.hexdigest(+ [ stage, amount_key.call(chosen), candidates.map(&amount_key).sort ].to_json+ )+ return if last_balance_tiebreak_fingerprint(enable_banking_account) == fingerprint++ DebugLogEntry.capture(+ category: "provider_sync_warning",+ level: "warn",+ message: "Enable Banking reported the same balance type more than once; resolved by #{stage}",+ source: self.class.name,+ provider_key: "enable_banking",+ family: enable_banking_item.family,+ account_provider: enable_banking_account.account_provider,+ metadata: {+ enable_banking_item_id: enable_banking_item.id,+ enable_banking_account_id: enable_banking_account.id,+ balance_type: chosen[:balance_type],+ stage: stage.to_s,+ fingerprint: fingerprint,+ chosen_index: candidates.index(chosen),+ previous_balance_verified: enable_banking_account.balance_verified?,+ credit_limit: enable_banking_account.credit_limit&.to_s("F"),+ candidates: candidates.map do |balance|+ {+ amount: balance.dig(:balance_amount, :amount) || balance[:amount],+ currency: balance_currency(balance),+ credit_debit_indicator: balance[:credit_debit_indicator],+ last_change_date_time: balance[:last_change_date_time],+ reference_date: balance[:reference_date],+ last_committed_transaction: balance[:last_committed_transaction].present?+ }+ end+ }+ )+ end++ def last_balance_tiebreak_fingerprint(enable_banking_account)+ account_provider = enable_banking_account.account_provider+ return nil unless account_provider- balances.first+ DebugLogEntry+ .where(account_provider: account_provider, category: "provider_sync_warning", source: self.class.name)+ .order(created_at: :desc, id: :desc)+ .first&.metadata&.dig("fingerprint")end# Guards the OPBD/PRCD priority (see BALANCE_TYPE_PRIORITY) against picking adiff --git a/db/migrate/20261020090000_add_balance_verification_to_enable_banking_accounts.rb b/db/migrate/20261020090000_add_balance_verification_to_enable_banking_accounts.rbnew file mode 100644index 0000000000..f302d99b66--- /dev/null+++ b/db/migrate/20261020090000_add_balance_verification_to_enable_banking_accounts.rb@@ -0,0 +1,6 @@+class AddBalanceVerificationToEnableBankingAccounts < ActiveRecord::Migration[8.1]+ def change+ add_column :enable_banking_accounts, :balance_evidence_verified, :boolean, default: false, null: false+ add_column :enable_banking_accounts, :balance_verified, :boolean, default: false, null: false+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 8506a2a8c4..79d72e07db 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_10_15_090000) do+ActiveRecord::Schema[8.1].define(version: 2026_10_20_090000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -640,6 +640,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_15_090000) dot.string "account_id"t.string "account_status"t.string "account_type"+ t.boolean "balance_evidence_verified", default: false, null: false+ t.boolean "balance_verified", default: false, null: falset.datetime "created_at", null: falset.decimal "credit_limit", precision: 19, scale: 4t.string "currency"diff --git a/test/models/enable_banking_account/processor_test.rb b/test/models/enable_banking_account/processor_test.rbindex 5f8af19ea0..d7f4467b6b 100644--- a/test/models/enable_banking_account/processor_test.rb+++ b/test/models/enable_banking_account/processor_test.rb@@ -27,6 +27,41 @@ class EnableBankingAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal 1500.0, @account.reload.cash_balanceend+ test "promotes the importer's evidence to balance_verified once the anchor is written" do+ @enable_banking_account.update!(balance_evidence_verified: true, balance_verified: false)++ EnableBankingAccount::Processor.new(@enable_banking_account).process++ assert @enable_banking_account.reload.balance_verified?+ end++ test "an unverified balance clears balance_verified when it becomes the anchor" do+ @enable_banking_account.update!(balance_evidence_verified: false, balance_verified: true)++ EnableBankingAccount::Processor.new(@enable_banking_account).process++ assert_not @enable_banking_account.reload.balance_verified?+ end++ test "keeps balance_verified when no balance was fetched and the anchor stays as it is" do+ @enable_banking_account.update_columns(current_balance: nil, balance_evidence_verified: false, balance_verified: true)++ EnableBankingAccount::Processor.new(@enable_banking_account).process++ assert @enable_banking_account.reload.balance_verified?+ end++ test "clears balance_verified when the balance never becomes the anchor" do+ @enable_banking_account.update!(balance_evidence_verified: true, balance_verified: true)+ Account.any_instance.stubs(:set_current_balance).raises(StandardError, "boom")++ assert_raises(StandardError) do+ EnableBankingAccount::Processor.new(@enable_banking_account).process+ end++ assert_not @enable_banking_account.reload.balance_verified?+ end+test "updates account currency" do@enable_banking_account.update!(currency: "USD")diff --git a/test/models/enable_banking_item/importer_balance_test.rb b/test/models/enable_banking_item/importer_balance_test.rbindex 89b51da631..4b5d93e8b1 100644--- a/test/models/enable_banking_item/importer_balance_test.rb+++ b/test/models/enable_banking_item/importer_balance_test.rb@@ -594,6 +594,540 @@ class EnableBankingItem::ImporterBalanceTest < ActiveSupport::TestCaseassert_nil unsaved_account.current_balanceend+ test "import refreshes the balance after fetching transactions" do+ link_account(Depository.create!)++ @enable_banking_item.stubs(:upsert_enable_banking_snapshot!)+ @importer.stubs(:fetch_session_data).returns(accounts: [])+ order = sequence("balance after transactions")+ @importer.expects(:fetch_and_store_transactions).with(@enable_banking_account).returns(success: true, transactions_count: 0).in_sequence(order)+ @importer.expects(:fetch_and_update_balance).with(@enable_banking_account).returns(true).in_sequence(order)++ @importer.import+ end++ test "import still refreshes the balance when the transaction fetch raises" do+ link_account(Depository.create!)++ @enable_banking_item.stubs(:upsert_enable_banking_snapshot!)+ @importer.stubs(:fetch_session_data).returns(accounts: [])+ @importer.stubs(:fetch_and_store_transactions).raises(StandardError, "boom")+ @importer.expects(:fetch_and_update_balance).with(@enable_banking_account).returns(true)++ result = @importer.import++ assert_equal 1, result[:transactions_failed]+ assert_equal 0, result[:balances_failed]+ end++ test "a failed import leaves the anchor's verification untouched" do+ link_account(Depository.create!)+ @enable_banking_account.update!(balance_verified: false)++ @enable_banking_item.stubs(:upsert_enable_banking_snapshot!)+ @importer.stubs(:fetch_session_data).returns(accounts: [])+ @importer.stubs(:fetch_and_store_transactions).raises(StandardError, "boom")+ stub_balances(clbd("950.00"))++ result = @importer.import++ # The syncer stops before the processor whenever the import fails, so this+ # balance never becomes the anchor and must not vouch for the old one.+ assert_not result[:success]+ @enable_banking_account.reload+ assert_equal BigDecimal("950.00"), @enable_banking_account.current_balance+ assert_not @enable_banking_account.balance_verified?+ assert @enable_banking_account.balance_evidence_verified?+ end++ test "duplicate CLBD balances without metadata pick the lower one on a depository account (#3188)" do+ link_account(Depository.create!)+ stub_balances(clbd("1234.56"), clbd("5834.56"))++ assert_difference "DebugLogEntry.count", 1 do+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end++ @enable_banking_account.reload+ assert_equal BigDecimal("1234.56"), @enable_banking_account.current_balance+ assert_not @enable_banking_account.balance_evidence_verified?, "a heuristic pick must not become a trusted anchor"++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "provider_sync_warning", entry.category+ assert_equal "lowest", entry.metadata["stage"]+ assert_equal 2, entry.metadata["candidates"].size+ end++ test "the same duplicate balances are logged only once across syncs" do+ link_account(Depository.create!)+ stub_balances(clbd("1234.56"), clbd("5834.56"))++ assert_difference "DebugLogEntry.count", 1 do+ 2.times { assert @importer.send(:fetch_and_update_balance, @enable_banking_account) }+ end+ end++ test "a single balance per type counts as evidence and logs nothing" do+ stub_balances(clbd("1234.56"))++ assert_no_difference "DebugLogEntry.count" do+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end++ assert @enable_banking_account.reload.balance_evidence_verified?+ end++ test "duplicate balances in different currencies are narrowed by currency before any tiebreak" do+ link_account(Depository.create!)+ @enable_banking_account.update!(raw_payload: { "currency" => "EUR" })+ stub_balances(clbd("900.00", currency: "USD"), clbd("1234.56"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ @enable_banking_account.reload+ assert_equal BigDecimal("1234.56"), @enable_banking_account.current_balance+ assert @enable_banking_account.balance_evidence_verified?+ assert_empty DebugLogEntry.where("metadata ->> 'stage' IS NOT NULL")+ end++ test "duplicate balances pointing to different bookings prefer the newer booking" do+ link_account(CreditCard.create!)+ @enable_banking_account.update!(raw_transactions_payload: [+ booked_tx("ref-old", 3.days.ago.to_date, "10.00"),+ booked_tx("ref-new", 1.day.ago.to_date, "20.00")+ ])+ stub_balances(+ clbd("100.00", last_committed_transaction: "ref-old"),+ clbd("80.00", last_committed_transaction: "ref-new")+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("80.00"), @enable_banking_account.reload.current_balance+ assert_equal "last_committed_transaction", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "a booking reference reused with different dates does not decide the tie" do+ link_account(CreditCard.create!)+ @enable_banking_account.update!(raw_transactions_payload: [+ booked_tx("ref-a", 3.days.ago.to_date, "10.00"),+ booked_tx("ref-b", 1.day.ago.to_date, "20.00"),+ booked_tx("ref-a", Date.current, "30.00")+ ])+ stub_balances(+ clbd("80.00", last_committed_transaction: "ref-b"),+ clbd("100.00", last_committed_transaction: "ref-a")+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("80.00"), @enable_banking_account.reload.current_balance+ assert_equal "first", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "duplicate balances pointing to the same booking fall through to later stages" do+ link_account(Depository.create!)+ @enable_banking_account.update!(raw_transactions_payload: [ booked_tx("ref-1", 1.day.ago.to_date, "10.00") ])+ stub_balances(+ clbd("5834.56", last_committed_transaction: "ref-1"),+ clbd("1234.56", last_committed_transaction: "ref-1")+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1234.56"), @enable_banking_account.reload.current_balance+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "a gap equal to the credit limit identifies the overdraft-inclusive balance" do+ link_account(Depository.create!)+ @enable_banking_account.update!(credit_limit: BigDecimal("4600.00"))+ stub_balances(clbd("5834.56"), clbd("1234.56"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1234.56"), @enable_banking_account.reload.current_balance+ entry = DebugLogEntry.order(:created_at).last+ assert_equal "credit_limit", entry.metadata["stage"]+ assert_equal "4600.0", entry.metadata["credit_limit"]+ end++ test "a verified previous anchor minus booked outflows picks the matching balance" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.update!(+ balance_verified: true,+ raw_transactions_payload: [ booked_tx("ref-1", 1.day.ago.to_date, "50.00", indicator: "DBIT") ]+ )+ # 1000 - 50 = 950. Adding the outflow instead (1050) would pick 1100.+ stub_balances(clbd("1100.00"), clbd("950.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("950.00"), @enable_banking_account.reload.current_balance+ assert @enable_banking_account.balance_evidence_verified?+ assert_equal "anchor", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check abstains when bookings on the anchor day change the answer" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.update!(+ balance_verified: true,+ raw_transactions_payload: [ booked_tx("ref-same-day", 2.days.ago.to_date, "700.00", indicator: "DBIT") ]+ )+ # Without the anchor-day booking 1000 matches, with it 300 does.+ stub_balances(clbd("1000.00"), clbd("300.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("300.00"), @enable_banking_account.reload.current_balance+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check abstains when a booked amount cannot be parsed" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.update!(+ balance_verified: true,+ raw_transactions_payload: [ booked_tx("ref-bad", 1.day.ago.to_date, "not-a-number", indicator: "DBIT") ]+ )+ # Treating the bad amount as 0 would confirm 1000 as the anchor-backed pick.+ stub_balances(clbd("1000.00"), clbd("950.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("950.00"), @enable_banking_account.reload.current_balance+ assert_not @enable_banking_account.balance_evidence_verified?+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check falls back to value_date when booking_date is missing" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ tx = booked_tx("ref-1", 1.day.ago.to_date, "50.00", indicator: "DBIT")+ tx["value_date"] = tx.delete("booking_date")+ @enable_banking_account.update!(balance_verified: true, raw_transactions_payload: [ tx ])+ stub_balances(clbd("1000.00"), clbd("950.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("950.00"), @enable_banking_account.reload.current_balance+ assert_equal "anchor", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check ignores pending rows and bookings before the anchor date" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.update!(+ balance_verified: true,+ raw_transactions_payload: [+ booked_tx("ref-before", 3.days.ago.to_date, "300.00", indicator: "DBIT"),+ booked_tx("ref-pending", 1.day.ago.to_date, "300.00", indicator: "DBIT").merge("status" => "PDNG", "_pending" => true),+ booked_tx("ref-in", 1.day.ago.to_date, "100.00", indicator: "CRDT")+ ]+ )+ stub_balances(clbd("1100.00"), clbd("700.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1100.00"), @enable_banking_account.reload.current_balance+ assert_equal "anchor", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check is skipped when the previous balance was not verified" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.update!(balance_verified: false, raw_transactions_payload: [])+ stub_balances(clbd("1000.00"), clbd("800.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("800.00"), @enable_banking_account.reload.current_balance+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "an anchor tie is broken by the newer last_change_date_time" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.update!(balance_verified: true, raw_transactions_payload: [])+ stub_balances(+ clbd("999.99", last_change_date_time: "2026-09-29T08:00:00Z"),+ clbd("1000.00", last_change_date_time: "2026-09-30T08:00:00Z")+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1000.00"), @enable_banking_account.reload.current_balance+ assert_not @enable_banking_account.balance_evidence_verified?+ assert @enable_banking_account.balance_verified?, "only the processor may change the anchor's verification"+ assert_equal "anchor_timestamp", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check abstains when no candidate matches the expected balance" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.update!(balance_verified: true, raw_transactions_payload: [])+ # 1500 is closer to 1000 than 1600 but still no match, so it is no evidence.+ stub_balances(clbd("1600.00"), clbd("1500.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1500.00"), @enable_banking_account.reload.current_balance+ assert_not @enable_banking_account.balance_evidence_verified?+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "duplicate fresher balances go through the same tiebreak regardless of response order" do+ link_account(Depository.create!)+ itav = lambda do |amount|+ { balance_type: "ITAV", balance_amount: { amount: amount, currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-29" }+ end+ opbd = { balance_type: "OPBD", balance_amount: { amount: "100.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-01" }++ [ [ "900.00", "200.00" ], [ "200.00", "900.00" ] ].each do |first, second|+ stub_balances(opbd, itav.call(first), itav.call(second))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("200.00"), @enable_banking_account.reload.current_balance, "order #{first}, #{second}"+ assert_not @enable_banking_account.balance_evidence_verified?+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end+ end++ test "an older entry of the fresher type keeps an evidence-backed fresher pick unverified" do+ stub_balances(+ { balance_type: "OPBD", balance_amount: { amount: "100.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-01" },+ { balance_type: "ITAV", balance_amount: { amount: "150.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-15" },+ { balance_type: "ITAV", balance_amount: { amount: "900.00", currency: "USD" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-29" },+ { balance_type: "ITAV", balance_amount: { amount: "200.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-29" }+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ @enable_banking_account.reload+ assert_equal BigDecimal("200.00"), @enable_banking_account.current_balance+ assert_not @enable_banking_account.balance_evidence_verified?+ end++ test "several balances of unknown types are not treated as evidence" do+ @enable_banking_account.update!(balance_evidence_verified: true)+ stub_balances(+ { balance_type: "XYZ1", balance_amount: { amount: "100.00", currency: "EUR" }, credit_debit_indicator: "CRDT" },+ { balance_type: "XYZ2", balance_amount: { amount: "900.00", currency: "EUR" }, credit_debit_indicator: "CRDT" }+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ @enable_banking_account.reload+ assert_equal BigDecimal("100.00"), @enable_banking_account.current_balance+ assert_not @enable_banking_account.balance_evidence_verified?+ end++ test "a fresher balance whose type is duplicated is not marked as verified" do+ @enable_banking_account.update!(balance_evidence_verified: true)+ stub_balances(+ { balance_type: "OPBD", balance_amount: { amount: "100.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-01" },+ { balance_type: "ITAV", balance_amount: { amount: "200.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-29" },+ { balance_type: "ITAV", balance_amount: { amount: "900.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-29" }+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_not @enable_banking_account.reload.balance_evidence_verified?+ end++ test "import counts a raising balance refresh as failed and keeps syncing" do+ link_account(Depository.create!)++ @enable_banking_item.stubs(:upsert_enable_banking_snapshot!)+ @importer.stubs(:fetch_session_data).returns(accounts: [])+ @importer.stubs(:fetch_and_store_transactions).returns(success: true, transactions_count: 1)+ @importer.stubs(:fetch_and_update_balance).raises(ActiveRecord::StatementInvalid, "lock timeout")++ result = nil+ assert_nothing_raised { result = @importer.import }++ assert_equal 1, result[:balances_failed]+ assert_equal 1, result[:transactions_imported]+ end++ test "duplicate balances on a credit card keep the first reported entry" do+ link_account(CreditCard.create!)+ stub_balances(clbd("500.00"), clbd("100.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("500.00"), @enable_banking_account.reload.current_balance+ assert_equal "first", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "a gap equal to the credit limit decides before the booking references" do+ link_account(Depository.create!)+ @enable_banking_account.update!(+ credit_limit: BigDecimal("4580.00"),+ raw_transactions_payload: [+ booked_tx("ref-a", 2.days.ago.to_date, "10.00"),+ booked_tx("ref-b", 1.day.ago.to_date, "20.00")+ ]+ )+ stub_balances(+ clbd("1234.56", last_committed_transaction: "ref-a"),+ clbd("5814.56", last_committed_transaction: "ref-b")+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1234.56"), @enable_banking_account.reload.current_balance+ assert_equal "credit_limit", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "an evidence-backed tie in the fresher type stays verified when it has no older entries" do+ link_account(Depository.create!)+ @enable_banking_account.update!(credit_limit: BigDecimal("4600.00"))+ itav = lambda do |amount|+ { balance_type: "ITAV", balance_amount: { amount: amount, currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-29" }+ end+ stub_balances(+ { balance_type: "OPBD", balance_amount: { amount: "100.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-01" },+ itav.call("5834.56"),+ itav.call("1234.56")+ )++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ @enable_banking_account.reload+ assert_equal BigDecimal("1234.56"), @enable_banking_account.current_balance+ assert @enable_banking_account.balance_evidence_verified?+ assert_equal "credit_limit", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the same amount reported twice is no tie" do+ link_account(Depository.create!)+ stub_balances(clbd("1000.00"), clbd("1000.00"))++ assert_no_difference -> { DebugLogEntry.count } do+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end++ @enable_banking_account.reload+ assert_equal BigDecimal("1000.00"), @enable_banking_account.current_balance+ assert @enable_banking_account.balance_evidence_verified?+ end++ test "a duplicated period boundary balance that a fresher balance replaces is not logged" do+ link_account(Depository.create!)+ opbd = lambda do |amount|+ { balance_type: "OPBD", balance_amount: { amount: amount, currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-01" }+ end+ stub_balances(+ opbd.call("100.00"),+ opbd.call("900.00"),+ { balance_type: "ITAV", balance_amount: { amount: "200.00", currency: "EUR" }, credit_debit_indicator: "CRDT", reference_date: "2026-09-29" }+ )++ assert_no_difference -> { DebugLogEntry.count } do+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end++ @enable_banking_account.reload+ assert_equal BigDecimal("200.00"), @enable_banking_account.current_balance+ assert @enable_banking_account.balance_evidence_verified?+ end++ test "the anchor check leaves unidentified card holds out of the booked flows" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ hold = {+ "entry_reference" => nil,+ "transaction_id" => nil,+ "status" => "BOOK",+ "booking_date" => 1.day.ago.to_date.iso8601,+ "credit_debit_indicator" => "DBIT",+ "transaction_amount" => { "amount" => "50.00", "currency" => "EUR" },+ "remittance_information" => [ "474836xxxxxx6879 003015315475" ]+ }+ @enable_banking_account.update!(balance_verified: true, raw_transactions_payload: [ hold ])+ stub_balances(clbd("1000.00"), clbd("950.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1000.00"), @enable_banking_account.reload.current_balance+ assert_equal "anchor", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check ignores an anchor written before the provider account was linked" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ @enable_banking_account.account_provider.update_column(:created_at, 1.hour.from_now)+ @enable_banking_account.update!(balance_verified: true, raw_transactions_payload: [])+ stub_balances(clbd("1000.00"), clbd("800.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("800.00"), @enable_banking_account.reload.current_balance+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "an unchanged tie is logged once, a changed one again" do+ link_account(Depository.create!)+ stub_balances(clbd("5834.56"), clbd("1234.56"))++ assert_difference -> { DebugLogEntry.count }, 1 do+ 2.times { assert @importer.send(:fetch_and_update_balance, @enable_banking_account) }+ end++ stub_balances(clbd("5800.00"), clbd("1200.00"))+ assert_difference -> { DebugLogEntry.count }, 1 do+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end+ end++ test "the same tie reported in a different order is not logged again" do+ link_account(Depository.create!)++ assert_difference -> { DebugLogEntry.count }, 1 do+ stub_balances(clbd("5834.56"), clbd("1234.56"))+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ stub_balances(clbd("1234.56"), clbd("5834.56"))+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end+ end++ test "the anchor check abstains when a booked flow has no usable date" do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: 2.days.ago.to_date)+ undated = booked_tx("ref-1", 1.day.ago.to_date, "100.00").merge("booking_date" => nil)+ @enable_banking_account.update!(balance_verified: true, raw_transactions_payload: [ undated ])+ stub_balances(clbd("1000.00"), clbd("900.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("900.00"), @enable_banking_account.reload.current_balance+ assert_not @enable_banking_account.balance_evidence_verified?+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "the anchor check dates timestamped bookings in the family timezone" do+ @family.update!(timezone: "America/New_York")+ travel_to Time.zone.parse("2026-10-10 12:00:00 UTC") do+ account = link_account(Depository.create!)+ create_anchor(account, amount: 1000, date: Date.new(2026, 10, 9))+ # 02:00 UTC on the 9th is still the 8th in New York, so the booking is+ # before the anchor and the expected balance stays 1000.+ early = booked_tx("ref-1", Date.new(2026, 10, 9), "50.00").merge("booking_date" => "2026-10-09T02:00:00Z")+ @enable_banking_account.update!(balance_verified: true, raw_transactions_payload: [ early ])+ stub_balances(clbd("950.00"), clbd("1000.00"))++ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_equal BigDecimal("1000.00"), @enable_banking_account.reload.current_balance+ assert_equal "anchor", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end+ end+privatedef link_account(accountable)@@ -606,6 +1140,44 @@ class EnableBankingItem::ImporterBalanceTest < ActiveSupport::TestCaseaccountable: accountable)AccountProvider.create!(account: account, provider: @enable_banking_account)+ @enable_banking_account.reload+ account+ end++ def create_anchor(account, amount:, date:)+ account.entries.create!(+ date: date,+ name: "Current balance",+ amount: amount,+ currency: "EUR",+ entryable: Valuation.new(kind: "current_anchor")+ )+ end++ def stub_balances(*balances)+ @mock_provider.stubs(:get_account_balances).returns(balances: balances)+ end++ def clbd(amount, currency: "EUR", **metadata)+ {+ name: "Accounting balance",+ balance_type: "CLBD",+ balance_amount: { amount: amount, currency: currency },+ credit_debit_indicator: "CRDT",+ last_change_date_time: nil,+ reference_date: nil,+ last_committed_transaction: nil+ }.merge(metadata)+ end++ def booked_tx(entry_reference, booking_date, amount, indicator: "DBIT")+ {+ "entry_reference" => entry_reference,+ "status" => "BOOK",+ "booking_date" => booking_date.iso8601,+ "credit_debit_indicator" => indicator,+ "transaction_amount" => { "amount" => amount, "currency" => "EUR" }+ }end# Shaped like PayPal's response: the primary EUR balance first, then empty